diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000..be4aeab0e0 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# To configure git to use this file when using `git blame`: +# $ git config blame.ignoreRevsFile .git-blame-ignore-revs + +# DT-921: Add spotless to consent service +# https://github.com/DataBiosphere/consent/pull/2508 diff --git a/.github/workflows/maven.yaml b/.github/workflows/maven.yaml index 6625662ec2..40be877cbd 100644 --- a/.github/workflows/maven.yaml +++ b/.github/workflows/maven.yaml @@ -14,6 +14,8 @@ jobs: distribution: 'temurin' java-version: 25 cache: 'maven' + - name: Spotless Check + run: mvn -q spotless:check --batch-mode - name: Package env: MAVEN_OPTS: -Dorg.slf4j.simpleLogger.defaultLogLevel=warn -Dmaven.test.skip=true -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.httpconnectionManager.ttlSeconds=120 diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml index cb81e0b950..fdab357755 100644 --- a/.github/workflows/semgrep.yml +++ b/.github/workflows/semgrep.yml @@ -2,6 +2,7 @@ name: Semgrep on: [ pull_request ] jobs: semgrep: + if: false # disabled until spotless changes are merged runs-on: ubuntu-latest container: image: returntocorp/semgrep diff --git a/.gitignore b/.gitignore index 16a29dbc45..9140fd929a 100644 --- a/.gitignore +++ b/.gitignore @@ -10,9 +10,6 @@ .vscode/ .metals/ -## Do not ignore project based code styles -!.idea/codeStyles - ## File-based project format *.ipr *.iws diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml deleted file mode 100644 index b6c57434e5..0000000000 --- a/.idea/codeStyles/Project.xml +++ /dev/null @@ -1,581 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml deleted file mode 100644 index 79ee123c2b..0000000000 --- a/.idea/codeStyles/codeStyleConfig.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index 71b542d4d6..d6f14e16fc 100644 --- a/pom.xml +++ b/pom.xml @@ -26,6 +26,7 @@ 5.20.0 5.2.0.4988 4.2.7.Final + 3.0.0 UTF-8 UTF-8 @@ -98,6 +99,48 @@ + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + + + + + + + spotless-check + + check + + verify + + + ${env.CI != true} + + + + spotless-apply + + apply + + process-sources + + + ${env.CI} + + + + + org.owasp dependency-check-maven diff --git a/src/main/java/org/broadinstitute/consent/http/ConsentApplication.java b/src/main/java/org/broadinstitute/consent/http/ConsentApplication.java index 8c5fc7c8e7..d228286922 100644 --- a/src/main/java/org/broadinstitute/consent/http/ConsentApplication.java +++ b/src/main/java/org/broadinstitute/consent/http/ConsentApplication.java @@ -88,9 +88,9 @@ /** * Top-level entry point to the entire application. - *

- * See the Dropwizard docs here: - * https://dropwizard.github.io + * + *

See the Dropwizard docs here: https://dropwizard.github.io */ public class ConsentApplication extends Application { @@ -106,19 +106,21 @@ public static void main(String[] args) throws Exception { try { String dsn = System.getProperties().getProperty("sentry.dsn"); if (StringUtils.isNotBlank(dsn)) { - Sentry.init(config -> { - config.setDsn(dsn); - config.setDiagnosticLevel(SentryLevel.ERROR); - config.setServerName("Consent"); - config.addContextTag("Consent"); - config.addInAppInclude("org.broadinstitute"); - }); + Sentry.init( + config -> { + config.setDsn(dsn); + config.setDiagnosticLevel(SentryLevel.ERROR); + config.setServerName("Consent"); + config.addContextTag("Consent"); + config.addInAppInclude("org.broadinstitute"); + }); Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit()); } else { LOGGER.error("Unable to bootstrap sentry logging."); } } catch (Exception e) { - LOGGER.error(MessageFormat.format("Exception loading sentry properties: {0}", e.getMessage())); + LOGGER.error( + MessageFormat.format("Exception loading sentry properties: {0}", e.getMessage())); } new ConsentApplication().run(args); LOGGER.info("Consent Application Started"); @@ -187,18 +189,24 @@ public void run(ConsentConfiguration config, Environment env) { // Authentication filters final OAuthAuthenticator authenticator = injector.getProvider(OAuthAuthenticator.class).get(); - final DuosUserAuthenticator duosUserAuthenticator = injector.getProvider(DuosUserAuthenticator.class).get(); - final AuthorizationHelper authorizationHelper = injector.getProvider(AuthorizationHelper.class).get(); + final DuosUserAuthenticator duosUserAuthenticator = + injector.getProvider(DuosUserAuthenticator.class).get(); + final AuthorizationHelper authorizationHelper = + injector.getProvider(AuthorizationHelper.class).get(); // Requests annotated with @Auth AuthUser will be authenticated through this filter - final AuthFilter primaryAuthFilter = new OAuthCustomAuthFilter<>(authenticator, authorizationHelper); - // Requests annotated with @Auth DuosUser will be authenticated through this filter and are guaranteed to have a populated User object - final AuthFilter duosAuthUserFilter = new OAuthCustomAuthFilter<>(duosUserAuthenticator, authorizationHelper); - final PolymorphicAuthDynamicFeature feature = new PolymorphicAuthDynamicFeature<>( - Map.of( - AuthUser.class, primaryAuthFilter, - DuosUser.class, duosAuthUserFilter)); - final AbstractBinder binder = new PolymorphicAuthValueFactoryProvider.Binder<>( - Set.of(AuthUser.class, DuosUser.class)); + final AuthFilter primaryAuthFilter = + new OAuthCustomAuthFilter<>(authenticator, authorizationHelper); + // Requests annotated with @Auth DuosUser will be authenticated through this filter and are + // guaranteed to have a populated User object + final AuthFilter duosAuthUserFilter = + new OAuthCustomAuthFilter<>(duosUserAuthenticator, authorizationHelper); + final PolymorphicAuthDynamicFeature feature = + new PolymorphicAuthDynamicFeature<>( + Map.of( + AuthUser.class, primaryAuthFilter, + DuosUser.class, duosAuthUserFilter)); + final AbstractBinder binder = + new PolymorphicAuthValueFactoryProvider.Binder<>(Set.of(AuthUser.class, DuosUser.class)); env.jersey().register(feature); env.jersey().register(binder); @@ -224,15 +232,16 @@ private void initializeLiquibase(ConsentConfiguration config) values.set("ui", new LoggerUIService()); } catch (IllegalAccessException | NoSuchFieldException ignored) { } - Connection connection = DriverManager.getConnection( - config.getDataSourceFactory().getUrl(), - config.getDataSourceFactory().getUser(), - config.getDataSourceFactory().getPassword() - ); - Database database = DatabaseFactory.getInstance() - .findCorrectDatabaseImplementation(new JdbcConnection(connection)); - Liquibase liquibase = new Liquibase(liquibaseFile(), new ClassLoaderResourceAccessor(), - database); + Connection connection = + DriverManager.getConnection( + config.getDataSourceFactory().getUrl(), + config.getDataSourceFactory().getUser(), + config.getDataSourceFactory().getPassword()); + Database database = + DatabaseFactory.getInstance() + .findCorrectDatabaseImplementation(new JdbcConnection(connection)); + Liquibase liquibase = + new Liquibase(liquibaseFile(), new ClassLoaderResourceAccessor(), database); liquibase.update(new Contexts(), new LabelExpression()); } @@ -246,5 +255,4 @@ private String liquibaseFile() { } return changeLogFile; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/ConsentModule.java b/src/main/java/org/broadinstitute/consent/http/ConsentModule.java index 9542c332be..94dcf58842 100644 --- a/src/main/java/org/broadinstitute/consent/http/ConsentModule.java +++ b/src/main/java/org/broadinstitute/consent/http/ConsentModule.java @@ -67,7 +67,6 @@ import org.broadinstitute.consent.http.service.OntologyService; import org.broadinstitute.consent.http.service.SupportRequestService; import org.broadinstitute.consent.http.service.UseRestrictionConverter; -import org.broadinstitute.consent.http.service.feature.InstitutionAndLibraryCardEnforcement; import org.broadinstitute.consent.http.service.UserService; import org.broadinstitute.consent.http.service.VoteService; import org.broadinstitute.consent.http.service.dao.DaaServiceDAO; @@ -80,6 +79,7 @@ import org.broadinstitute.consent.http.service.dao.NihServiceDAO; import org.broadinstitute.consent.http.service.dao.UserServiceDAO; import org.broadinstitute.consent.http.service.dao.VoteServiceDAO; +import org.broadinstitute.consent.http.service.feature.InstitutionAndLibraryCardEnforcement; import org.broadinstitute.consent.http.service.ontology.ElasticSearchSupport; import org.broadinstitute.consent.http.service.sam.SamService; import org.broadinstitute.consent.http.util.HttpClientUtil; @@ -93,10 +93,8 @@ public class ConsentModule extends AbstractModule { public static final String DB_ENV = "postgresql"; - @Inject - private final ConsentConfiguration config; - @Inject - private final Environment environment; + @Inject private final ConsentConfiguration config; + @Inject private final Environment environment; private final Client client; private final Jdbi jdbi; private final CounterDAO counterDAO; @@ -125,9 +123,10 @@ public class ConsentModule extends AbstractModule { ConsentModule(ConsentConfiguration consentConfiguration, Environment environment) { this.config = consentConfiguration; this.environment = environment; - this.client = new JerseyClientBuilder(environment) - .using(config.getJerseyClientConfiguration()) - .build(this.getClass().getName()); + this.client = + new JerseyClientBuilder(environment) + .using(config.getJerseyClientConfiguration()) + .build(this.getClass().getName()); this.jdbi = new JdbiFactory().build(environment, config.getDataSourceFactory(), DB_ENV); jdbi.installPlugin(new SqlObjectPlugin()); @@ -256,16 +255,13 @@ DuosUserAuthenticator providesDuosUserOAuthAuthenticator() { @Provides DarCollectionService providesDarCollectionService() { - return new DarCollectionService(providesJdbi(), providesDarCollectionServiceDAO(), - providesEmailService()); + return new DarCollectionService( + providesJdbi(), providesDarCollectionServiceDAO(), providesEmailService()); } @Provides FileStorageObjectService providesFileStorageObjectService() { - return new FileStorageObjectService( - providesFileStorageObjectDAO(), - providesGCSService() - ); + return new FileStorageObjectService(providesFileStorageObjectDAO(), providesGCSService()); } @Provides @@ -293,8 +289,7 @@ DACAutomationRuleService providesRuleService() { providesUserDAO(), providesVoteDAO(), providesVoteServiceDAO(), - providesVoteService() - ); + providesVoteService()); } @Provides @@ -308,17 +303,13 @@ DataAccessRequestService providesDataAccessRequestService() { providesInstitutionService(), providesEmailService(), providesRuleService(), - config - ); + config); } @Provides DatasetServiceDAO providesDatasetServiceDAO() { return new DatasetServiceDAO( - jdbi, - providesDatasetDAO(), - providesStudyDAO(), - providesDatasetAuthorizationReaderDAO()); + jdbi, providesDatasetDAO(), providesStudyDAO(), providesDatasetAuthorizationReaderDAO()); } @Provides @@ -338,9 +329,7 @@ DatasetService providesDatasetService() { @Provides ElectionService providesElectionService() { - return new ElectionService( - providesElectionDAO() - ); + return new ElectionService(providesElectionDAO()); } @Provides @@ -360,9 +349,7 @@ EmailService providesEmailService() { @Provides SendGridAPI providesSendGridAPI() { - return new SendGridAPI( - config.getMailConfiguration(), - providesUserDAO()); + return new SendGridAPI(config.getMailConfiguration(), providesUserDAO()); } @Provides @@ -383,19 +370,13 @@ DarCollectionSummaryDAO providesDarCollectionSummaryDAO() { @Provides DarCollectionServiceDAO providesDarCollectionServiceDAO() { return new DarCollectionServiceDAO( - providesDatasetDAO(), - providesElectionDAO(), - providesJdbi(), - providesUserDAO()); + providesDatasetDAO(), providesElectionDAO(), providesJdbi(), providesUserDAO()); } @Provides DataAccessRequestServiceDAO providesDataAccessRequestServiceDAO() { return new DataAccessRequestServiceDAO( - providesDataAccessRequestDAO(), - providesJdbi(), - providesDARCollectionDAO() - ); + providesDataAccessRequestDAO(), providesJdbi(), providesDARCollectionDAO()); } @Provides @@ -415,9 +396,7 @@ StudyDAO providesStudyDAO() { @Provides VoteServiceDAO providesVoteServiceDAO() { - return new VoteServiceDAO( - providesJdbi(), - providesVoteDAO()); + return new VoteServiceDAO(providesJdbi(), providesVoteDAO()); } @Provides @@ -447,16 +426,12 @@ DatasetDAO providesDatasetDAO() { @Provides DaaServiceDAO providesDaaServiceDAO() { - return new DaaServiceDAO( - providesJdbi(), - providesDaaDAO(), - providesFileStorageObjectDAO()); + return new DaaServiceDAO(providesJdbi(), providesDaaDAO(), providesFileStorageObjectDAO()); } @Provides DacServiceDAO providesDacServiceDAO() { - return new DacServiceDAO( - providesJdbi()); + return new DacServiceDAO(providesJdbi()); } @Provides @@ -491,7 +466,8 @@ DacService providesDacService() { providesDataAccessRequestDAO(), providesVoteService(), providesDaaService(), - providesDacServiceDAO(), providesDACAutomationRuleDAO()); + providesDacServiceDAO(), + providesDACAutomationRuleDAO()); } @Provides @@ -505,8 +481,7 @@ ElasticSearchService providesElasticSearchService() { providesInstitutionDAO(), providesDatasetDAO(), providesDatasetServiceDAO(), - providesStudyDAO() - ); + providesStudyDAO()); } @Provides @@ -546,8 +521,7 @@ MetricsService providesMetricsService() { providesDatasetDAO(), providesDataAccessRequestDAO(), providesDARCollectionDAO(), - providesElectionDAO() - ); + providesElectionDAO()); } @Provides @@ -577,7 +551,10 @@ AcknowledgementDAO providesAcknowledgementDAO() { @Provides InstitutionService providesInstitutionService() { - return new InstitutionService(providesInstitutionDAO(), providesUserDAO(), providesInstitutionAndLibraryCardEnforcement()); + return new InstitutionService( + providesInstitutionDAO(), + providesUserDAO(), + providesInstitutionAndLibraryCardEnforcement()); } @Provides @@ -593,10 +570,7 @@ LibraryCardService providesLibraryCardService() { @Provides AcknowledgementService providesAcknowledgementService() { return new AcknowledgementService( - providesAcknowledgementDAO(), - providesDataAccessRequestDAO(), - providesEmailService() - ); + providesAcknowledgementDAO(), providesDataAccessRequestDAO(), providesEmailService()); } @Provides @@ -608,18 +582,13 @@ DatasetRegistrationService providesDatasetRegistrationService() { providesGCSService(), providesElasticSearchService(), providesStudyDAO(), - providesEmailService() - ); + providesEmailService()); } @Provides UserServiceDAO providesUserServiceDAO() { return new UserServiceDAO( - providesJdbi(), - providesLibraryCardDAO(), - providesUserDAO(), - providesUserRoleDAO() - ); + providesJdbi(), providesLibraryCardDAO(), providesUserDAO(), providesUserRoleDAO()); } @Provides @@ -644,9 +613,7 @@ UserService providesUserService() { @Provides InstitutionAndLibraryCardEnforcement providesInstitutionAndLibraryCardEnforcement() { - return new InstitutionAndLibraryCardEnforcement( - providesJdbi(), - providesUserServiceDAO()); + return new InstitutionAndLibraryCardEnforcement(providesJdbi(), providesUserServiceDAO()); } @Provides @@ -695,14 +662,14 @@ DraftDAO providesDraftDAO() { @Provides DraftFileStorageServiceDAO providesDraftFileStorageService() { - return new DraftFileStorageServiceDAO(providesJdbi(), providesGCSService(), - providesFileStorageObjectDAO()); + return new DraftFileStorageServiceDAO( + providesJdbi(), providesGCSService(), providesFileStorageObjectDAO()); } @Provides DraftServiceDAO providesDraftService() { - return new DraftServiceDAO(providesJdbi(), providesDraftDAO(), - providesDraftFileStorageService()); + return new DraftServiceDAO( + providesJdbi(), providesDraftDAO(), providesDraftFileStorageService()); } @Provides diff --git a/src/main/java/org/broadinstitute/consent/http/authentication/AuthorizationHelper.java b/src/main/java/org/broadinstitute/consent/http/authentication/AuthorizationHelper.java index 14de0afbfc..3eaebfab2e 100644 --- a/src/main/java/org/broadinstitute/consent/http/authentication/AuthorizationHelper.java +++ b/src/main/java/org/broadinstitute/consent/http/authentication/AuthorizationHelper.java @@ -27,8 +27,7 @@ public class AuthorizationHelper implements ConsentLogger { protected final UserService userService; @Inject - public AuthorizationHelper(SamService samService, - UserService userService) { + public AuthorizationHelper(SamService samService, UserService userService) { this.claimsCache = ClaimsCache.getInstance(); this.samService = samService; this.userService = userService; @@ -48,10 +47,12 @@ protected AuthUser buildAuthUserFromHeaders(Map headers) { name = email; } if (email == null) { - logWarn(String.format( - "Reading oauth2 claim headers: email is null, auth user is incomplete. Aud: %s Name: %s", - aud, name)); - throw new NotAuthorizedException("You are not authorized to use this service without a valid email address."); + logWarn( + String.format( + "Reading oauth2 claim headers: email is null, auth user is incomplete. Aud: %s Name: %s", + aud, name)); + throw new NotAuthorizedException( + "You are not authorized to use this service without a valid email address."); } else { try { userService.enforceInstitutionAndLibraryCardRules(email); @@ -96,7 +97,7 @@ protected UserStatusInfo getUserStatusInfo(DuosUser duosUser) { * look for all roles they may have, returning true if any of them match the requested role. * * @param authUser AuthUser - * @param role String role to check + * @param role String role to check * @return True if the user has the role, false otherwise */ protected boolean authorize(AuthUser authUser, String role) { @@ -109,5 +110,4 @@ protected boolean authorize(AuthUser authUser, String role) { } return authorize; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticator.java b/src/main/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticator.java index 6e48233b11..305290a75b 100644 --- a/src/main/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticator.java +++ b/src/main/java/org/broadinstitute/consent/http/authentication/DuosUserAuthenticator.java @@ -23,7 +23,8 @@ public Optional authenticate(String bearer) { if (headers != null) { AuthUser authUser = authorizationHelper.buildAuthUserFromHeaders(headers); if (authUser.getEmail() != null) { - authUser.setUserStatusInfo(authorizationHelper.getUserStatusInfo(new DuosUser(authUser, null))); + authUser.setUserStatusInfo( + authorizationHelper.getUserStatusInfo(new DuosUser(authUser, null))); try { User duosUser = authorizationHelper.userService.findUserByEmail(authUser.getEmail()); return Optional.of(new DuosUser(authUser, duosUser)); diff --git a/src/main/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilter.java b/src/main/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilter.java index 8508b9b215..45995de7df 100644 --- a/src/main/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilter.java +++ b/src/main/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilter.java @@ -19,30 +19,34 @@ public class OAuthCustomAuthFilter

extends AuthFilter() - .setAuthenticator(authenticator) - .setAuthorizer(new UserAuthorizer(authorizationHelper)) - .setPrefix("Bearer") - .setRealm("OAUTH-AUTH") - .buildAuthFilter(); + public OAuthCustomAuthFilter( + OAuthAuthenticator authenticator, AuthorizationHelper authorizationHelper) { + filter = + new OAuthCredentialAuthFilter.Builder() + .setAuthenticator(authenticator) + .setAuthorizer(new UserAuthorizer(authorizationHelper)) + .setPrefix("Bearer") + .setRealm("OAUTH-AUTH") + .buildAuthFilter(); } /** * Constructor for OAuthCustomAuthFilter intended to be used with DuosUsers. * * @param authenticator DuosUserAuthenticator - * @param authorizationHelper AuthorizationHelper + * @param authorizationHelper AuthorizationHelper */ - public OAuthCustomAuthFilter(DuosUserAuthenticator authenticator, AuthorizationHelper authorizationHelper) { - filter = new OAuthCredentialAuthFilter.Builder() - .setAuthenticator(authenticator) - .setAuthorizer(new DuosUserAuthorizer(authorizationHelper)) - .setPrefix("Bearer") - .setRealm("OAUTH-AUTH") - .buildAuthFilter(); + public OAuthCustomAuthFilter( + DuosUserAuthenticator authenticator, AuthorizationHelper authorizationHelper) { + filter = + new OAuthCredentialAuthFilter.Builder() + .setAuthenticator(authenticator) + .setAuthorizer(new DuosUserAuthorizer(authorizationHelper)) + .setPrefix("Bearer") + .setRealm("OAUTH-AUTH") + .buildAuthFilter(); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/cloudstore/GCSService.java b/src/main/java/org/broadinstitute/consent/http/cloudstore/GCSService.java index 3c651bfe54..d6ad667a97 100644 --- a/src/main/java/org/broadinstitute/consent/http/cloudstore/GCSService.java +++ b/src/main/java/org/broadinstitute/consent/http/cloudstore/GCSService.java @@ -28,20 +28,20 @@ public class GCSService implements ConsentLogger { private StoreConfiguration config; private Storage storage; - public GCSService() { - } + public GCSService() {} @Inject public GCSService(StoreConfiguration config) { this.config = config; try { - ServiceAccountCredentials credentials = ServiceAccountCredentials. - fromStream(new FileInputStream(config.getPassword())); - Storage storage = StorageOptions.newBuilder(). - setProjectId(credentials.getProjectId()). - setCredentials(credentials). - build(). - getService(); + ServiceAccountCredentials credentials = + ServiceAccountCredentials.fromStream(new FileInputStream(config.getPassword())); + Storage storage = + StorageOptions.newBuilder() + .setProjectId(credentials.getProjectId()) + .setCredentials(credentials) + .build() + .getService(); this.setStorage(storage); } catch (Exception e) { logException("Exception initializing GCSService: " + e.getMessage(), e); @@ -65,21 +65,20 @@ protected void setConfig(StoreConfiguration config) { * @return Bucket */ public Bucket getRootBucketWithMetadata() { - return storage.get(config.getBucket(), - Storage.BucketGetOption.fields(Storage.BucketField.values())); + return storage.get( + config.getBucket(), Storage.BucketGetOption.fields(Storage.BucketField.values())); } /** * Store an input stream as a Blob * - * @param content InputStream content + * @param content InputStream content * @param mediaType String media type - * @param id String UUID of the file + * @param id String UUID of the file * @return BlobId of the stored document * @throws IOException Exception when storing document */ - public BlobId storeDocument(InputStream content, String mediaType, UUID id) - throws IOException { + public BlobId storeDocument(InputStream content, String mediaType, UUID id) throws IOException { byte[] bytes = IOUtils.toByteArray(content); BlobId blobId = BlobId.of(config.getBucket(), id.toString()); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType(mediaType).build(); @@ -87,7 +86,6 @@ public BlobId storeDocument(InputStream content, String mediaType, UUID id) return blob.getBlobId(); } - /** * Delete a document by Blob Id Name * @@ -96,9 +94,7 @@ public BlobId storeDocument(InputStream content, String mediaType, UUID id) */ public boolean deleteDocument(String blobIdName) { Optional blobOptional = getBlobFromUrl(blobIdName); - return blobOptional - .map(blob -> storage.delete(blob.getBlobId())) - .orElse(false); + return blobOptional.map(blob -> storage.delete(blob.getBlobId())).orElse(false); } /** diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/ConsentConfiguration.java b/src/main/java/org/broadinstitute/consent/http/configurations/ConsentConfiguration.java index d1dfc14ea6..53b0e6dba5 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/ConsentConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/ConsentConfiguration.java @@ -11,54 +11,34 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class ConsentConfiguration extends Configuration { - public ConsentConfiguration() { - } + public ConsentConfiguration() {} - @Valid - @NotNull - @JsonProperty - private final DataSourceFactory database = new DataSourceFactory(); + @Valid @NotNull @JsonProperty private final DataSourceFactory database = new DataSourceFactory(); - @Valid - @NotNull - @JsonProperty + @Valid @NotNull @JsonProperty private final StoreConfiguration googleStore = new StoreConfiguration(); - @Valid - @NotNull - @JsonProperty + @Valid @NotNull @JsonProperty private final ServicesConfiguration services = new ServicesConfiguration(); - @Valid - @NotNull - private JerseyClientConfiguration httpClient = new JerseyClientConfiguration(); + @Valid @NotNull private JerseyClientConfiguration httpClient = new JerseyClientConfiguration(); - @Valid - @NotNull - private MailConfiguration mailConfiguration = new MailConfiguration(); + @Valid @NotNull private MailConfiguration mailConfiguration = new MailConfiguration(); - @Valid - @NotNull + @Valid @NotNull private FreeMarkerConfiguration freeMarkerConfiguration = new FreeMarkerConfiguration(); - @Valid - @NotNull - private GoogleOAuth2Config googleAuthentication = new GoogleOAuth2Config(); + @Valid @NotNull private GoogleOAuth2Config googleAuthentication = new GoogleOAuth2Config(); @JsonProperty("httpClient") public JerseyClientConfiguration getJerseyClientConfiguration() { return httpClient; } - - @Valid - @NotNull - @JsonProperty + @Valid @NotNull @JsonProperty private final ElasticSearchConfiguration elasticSearch = new ElasticSearchConfiguration(); - @Valid - @NotNull - @JsonProperty + @Valid @NotNull @JsonProperty private final OidcConfiguration oidcConfiguration = new OidcConfiguration(); public DataSourceFactory getDataSourceFactory() { diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/ElasticSearchConfiguration.java b/src/main/java/org/broadinstitute/consent/http/configurations/ElasticSearchConfiguration.java index f2202be602..4beb8c82b9 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/ElasticSearchConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/ElasticSearchConfiguration.java @@ -7,18 +7,13 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class ElasticSearchConfiguration { - @NotNull - private String indexName; + @NotNull private String indexName; - @NotNull - private List servers; + @NotNull private List servers; - @NotNull - private String datasetIndexName; + @NotNull private String datasetIndexName; - /** - * This is configurable for testing purposes - */ + /** This is configurable for testing purposes */ private int port = 9200; public List getServers() { diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/FreeMarkerConfiguration.java b/src/main/java/org/broadinstitute/consent/http/configurations/FreeMarkerConfiguration.java index c529d7dd06..d63b957a50 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/FreeMarkerConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/FreeMarkerConfiguration.java @@ -6,11 +6,9 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class FreeMarkerConfiguration { - @NotNull - public String templateDirectory; + @NotNull public String templateDirectory; - @NotNull - public String defaultEncoding; + @NotNull public String defaultEncoding; public String getTemplateDirectory() { return templateDirectory; @@ -27,5 +25,4 @@ public String getDefaultEncoding() { public void setDefaultEncoding(String defaultEncoding) { this.defaultEncoding = defaultEncoding; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/GoogleOAuth2Config.java b/src/main/java/org/broadinstitute/consent/http/configurations/GoogleOAuth2Config.java index ce1d4d1068..7ea044f074 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/GoogleOAuth2Config.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/GoogleOAuth2Config.java @@ -6,8 +6,7 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class GoogleOAuth2Config { - @NotNull - public String clientId; + @NotNull public String clientId; public String getClientId() { return clientId; @@ -16,5 +15,4 @@ public String getClientId() { public void setClientId(String clientId) { this.clientId = clientId; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/MailConfiguration.java b/src/main/java/org/broadinstitute/consent/http/configurations/MailConfiguration.java index f4125e8315..311ce970b7 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/MailConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/MailConfiguration.java @@ -6,17 +6,13 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class MailConfiguration { - @NotNull - private boolean activateEmailNotifications; + @NotNull private boolean activateEmailNotifications; - @NotNull - private String googleAccount; + @NotNull private String googleAccount; - @NotNull - private String sendGridApiKey; + @NotNull private String sendGridApiKey; - @NotNull - private String sendGridStatusUrl; + @NotNull private String sendGridStatusUrl; public boolean isActivateEmailNotifications() { return activateEmailNotifications; diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/OidcConfiguration.java b/src/main/java/org/broadinstitute/consent/http/configurations/OidcConfiguration.java index 6163c8a532..68ba443a0d 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/OidcConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/OidcConfiguration.java @@ -3,8 +3,7 @@ import jakarta.validation.constraints.NotNull; public class OidcConfiguration { - @NotNull - private String authorityEndpoint; + @NotNull private String authorityEndpoint; private String extraAuthParams; private boolean addClientIdToScope = false; private String clientId; diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/ServicesConfiguration.java b/src/main/java/org/broadinstitute/consent/http/configurations/ServicesConfiguration.java index a786edc2bf..b1c746b68f 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/ServicesConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/ServicesConfiguration.java @@ -21,17 +21,13 @@ public class ServicesConfiguration { // nosemgrep public static final String BROAD_ZENDESK_URL = "https://broadinstitute.zendesk.com"; - @NotNull - private String ontologyURL; + @NotNull private String ontologyURL; - @NotNull - private String localURL; + @NotNull private String localURL; - @NotNull - private String samUrl; + @NotNull private String samUrl; - @NotNull - private String ecmUrl; + @NotNull private String ecmUrl; /** * This represents the max time we'll wait for an external status check to return. If it does not @@ -57,7 +53,6 @@ public class ServicesConfiguration { private boolean activateSupportNotifications = false; - public String getOntologyURL() { return ontologyURL; } diff --git a/src/main/java/org/broadinstitute/consent/http/configurations/StoreConfiguration.java b/src/main/java/org/broadinstitute/consent/http/configurations/StoreConfiguration.java index 87eb693fff..102ca51926 100644 --- a/src/main/java/org/broadinstitute/consent/http/configurations/StoreConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/configurations/StoreConfiguration.java @@ -8,11 +8,9 @@ public class StoreConfiguration { public String password; - @NotNull - public String endpoint; + @NotNull public String endpoint; - @NotNull - public String bucket; + @NotNull public String bucket; public String getPassword() { return password; @@ -37,5 +35,4 @@ public String getBucket() { public void setBucket(String bucket) { this.bucket = bucket; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/AcknowledgementDAO.java b/src/main/java/org/broadinstitute/consent/http/db/AcknowledgementDAO.java index 167f6fa704..d9401d6028 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/AcknowledgementDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/AcknowledgementDAO.java @@ -20,18 +20,22 @@ public interface AcknowledgementDAO extends Transactional { + " ON CONFLICT (ack_key, user_id) DO UPDATE SET last_acknowledged = current_timestamp ") void upsertAcknowledgement(@Bind("key") String key, @Bind("userId") Integer userId); - @SqlQuery("SELECT ack_key, user_id, first_acknowledged, last_acknowledged " - + " FROM acknowledgement WHERE ack_key = :key and user_id = :userId") - Acknowledgement findAcknowledgementsByKeyForUser(@Bind("key") String key, - @Bind("userId") Integer userId); - - @SqlQuery("SELECT ack_key, user_id, first_acknowledged, last_acknowledged " - + " FROM acknowledgement WHERE user_id = :userId") + @SqlQuery( + "SELECT ack_key, user_id, first_acknowledged, last_acknowledged " + + " FROM acknowledgement WHERE ack_key = :key and user_id = :userId") + Acknowledgement findAcknowledgementsByKeyForUser( + @Bind("key") String key, @Bind("userId") Integer userId); + + @SqlQuery( + "SELECT ack_key, user_id, first_acknowledged, last_acknowledged " + + " FROM acknowledgement WHERE user_id = :userId") List findAcknowledgementsForUser(@Bind("userId") Integer userId); - @SqlQuery("SELECT ack_key, user_id, first_acknowledged, last_acknowledged " - + " FROM acknowledgement WHERE user_id = :userId and ack_key IN ()") - List findAcknowledgementsForUser(@BindList(value = "key_list", onEmpty = EmptyHandling.NULL_STRING) List keys, + @SqlQuery( + "SELECT ack_key, user_id, first_acknowledged, last_acknowledged " + + " FROM acknowledgement WHERE user_id = :userId and ack_key IN ()") + List findAcknowledgementsForUser( + @BindList(value = "key_list", onEmpty = EmptyHandling.NULL_STRING) List keys, @Bind("userId") Integer userId); @SqlUpdate("DELETE FROM acknowledgement where user_id = :userId AND ack_key = :key") diff --git a/src/main/java/org/broadinstitute/consent/http/db/CounterDAO.java b/src/main/java/org/broadinstitute/consent/http/db/CounterDAO.java index afe70dbc28..84e8e85344 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/CounterDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/CounterDAO.java @@ -22,5 +22,4 @@ public interface CounterDAO extends Transactional { + " ) " + " SELECT MAX(count) FROM m WHERE name = :name ") Integer incrementCountByName(@Bind("name") String name); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAO.java index 78d36e9909..2e4ef320d0 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAO.java @@ -16,130 +16,147 @@ @RegisterRowMapper(DACAutomationRuleMapper.class) public interface DACAutomationRuleDAO extends Transactional { - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM dac_automation_rules """) List findAll(); - default Integer auditedInsertDACRuleSetting(int dacId, int ruleId, int userId, Instant activationDate) { - return inTransaction(d -> { - Handle handle = getHandle(); - String auditSql = """ + default Integer auditedInsertDACRuleSetting( + int dacId, int ruleId, int userId, Instant activationDate) { + return inTransaction( + d -> { + Handle handle = getHandle(); + String auditSql = + """ INSERT INTO dac_rule_audit (action, dac_id, rule_id, user_id, action_date) VALUES (:auditType::rule_audit_action, :dacId, :ruleId, :auditUserId, :actionDate) """; - String insertRuleSql = """ + String insertRuleSql = + """ INSERT INTO dac_rule_settings (dac_id, rule_id, user_id, activation_date) VALUES (:dacId, :ruleId, :userId, current_timestamp) """; - handle.createUpdate(auditSql) - .bind("dacId", dacId) - .bind("ruleId", ruleId) - .bind("auditUserId", userId) - .bind("auditType", RuleAuditAction.ADD) - .bind("actionDate", activationDate) - .execute(); + handle + .createUpdate(auditSql) + .bind("dacId", dacId) + .bind("ruleId", ruleId) + .bind("auditUserId", userId) + .bind("auditType", RuleAuditAction.ADD) + .bind("actionDate", activationDate) + .execute(); - return handle.createUpdate(insertRuleSql) - .bind("dacId", dacId) - .bind("ruleId", ruleId) - .bind("userId", userId) - .executeAndReturnGeneratedKeys("id") - .mapTo(Integer.class) - .one(); - }); + return handle + .createUpdate(insertRuleSql) + .bind("dacId", dacId) + .bind("ruleId", ruleId) + .bind("userId", userId) + .executeAndReturnGeneratedKeys("id") + .mapTo(Integer.class) + .one(); + }); } default void auditedDeleteDACRuleSetting(int dacId, int ruleId, int auditUserId) { - useTransaction(d -> { - Handle handle = getHandle(); - String auditSql = """ + useTransaction( + d -> { + Handle handle = getHandle(); + String auditSql = + """ INSERT INTO dac_rule_audit (action, dac_id, rule_id, user_id, action_date) SELECT :auditType::rule_audit_action, s.dac_id, s.rule_id, :auditUserId, current_timestamp FROM dac_rule_settings s WHERE s.dac_id = :dacId AND s.rule_id = :ruleId """; - String deleteRuleSql = """ + String deleteRuleSql = + """ DELETE FROM dac_rule_settings WHERE dac_id = :dacId AND rule_id = :ruleId """; - handle.createUpdate(auditSql) - .bind("dacId", dacId) - .bind("ruleId", ruleId) - .bind("auditUserId", auditUserId) - .bind("auditType", RuleAuditAction.REMOVE) - .execute(); - handle.createUpdate(deleteRuleSql) - .bind("dacId", dacId) - .bind("ruleId", ruleId) - .execute(); - handle.commit(); - }); + handle + .createUpdate(auditSql) + .bind("dacId", dacId) + .bind("ruleId", ruleId) + .bind("auditUserId", auditUserId) + .bind("auditType", RuleAuditAction.REMOVE) + .execute(); + handle.createUpdate(deleteRuleSql).bind("dacId", dacId).bind("ruleId", ruleId).execute(); + handle.commit(); + }); } default Integer auditedDeleteDACRuleSettingByUser(int dacId, int userId, int auditUserId) { - return inTransaction(d -> { - Handle handle = getHandle(); - // Note that we're logging the audit user as the user for the audit record - String auditSql = """ + return inTransaction( + d -> { + Handle handle = getHandle(); + // Note that we're logging the audit user as the user for the audit record + String auditSql = + """ INSERT INTO dac_rule_audit (action, dac_id, rule_id, user_id, action_date) SELECT :auditType::rule_audit_action, s.dac_id, s.rule_id, :auditUserId, current_timestamp FROM dac_rule_settings s WHERE s.dac_id = :dacId AND s.user_id = :userId; """; - String deleteRuleSql = """ + String deleteRuleSql = + """ DELETE FROM dac_rule_settings WHERE dac_id = :dacId AND user_id = :userId """; - handle.createUpdate(auditSql) - .bind("dacId", dacId) - .bind("userId", userId) - .bind("auditUserId", auditUserId) - .bind("auditType", RuleAuditAction.REMOVE) - .execute(); - return handle.createUpdate(deleteRuleSql) - .bind("dacId", dacId) - .bind("userId", userId) - .execute(); - }); + handle + .createUpdate(auditSql) + .bind("dacId", dacId) + .bind("userId", userId) + .bind("auditUserId", auditUserId) + .bind("auditType", RuleAuditAction.REMOVE) + .execute(); + return handle + .createUpdate(deleteRuleSql) + .bind("dacId", dacId) + .bind("userId", userId) + .execute(); + }); } default Integer auditedDeleteAllDACRuleSettingForUser(int userId, int auditUserId) { - return inTransaction(d -> { - Handle handle = getHandle(); - String auditSql = """ + return inTransaction( + d -> { + Handle handle = getHandle(); + String auditSql = + """ INSERT INTO dac_rule_audit (action, dac_id, rule_id, user_id, action_date) SELECT :auditType::rule_audit_action, s.dac_id, s.rule_id, :auditUserId, current_timestamp FROM dac_rule_settings s WHERE s.user_id = :userId; """; - String deleteRulesSql = """ + String deleteRulesSql = + """ DELETE FROM dac_rule_settings WHERE user_id = :userId """; - Integer count; - handle.createUpdate(auditSql) - .bind("auditUserId", auditUserId) - .bind("userId", userId) - .bind("auditType", RuleAuditAction.REMOVE) - .execute(); - return handle.createUpdate(deleteRulesSql) - .bind("userId", userId) - .execute(); - }); + Integer count; + handle + .createUpdate(auditSql) + .bind("auditUserId", auditUserId) + .bind("userId", userId) + .bind("auditType", RuleAuditAction.REMOVE) + .execute(); + return handle.createUpdate(deleteRulesSql).bind("userId", userId).execute(); + }); } - @SqlQuery(""" + @SqlQuery( + """ SELECT rules.*, settings.user_id, settings.activation_date, u.* FROM dac_automation_rules rules LEFT JOIN dac_rule_settings settings ON rules.id = settings.rule_id AND settings.dac_id = :dacId - LEFT JOIN users u on settings.user_id = u.user_id + LEFT JOIN users u on settings.user_id = u.user_id WHERE state = 'AVAILABLE' """) List findAllDACAutomationRulesByDACId(@Bind("dacId") int dacId); @RegisterRowMapper(DACAutomationRuleAuditMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT a.action, a.action_date, r.rule, u.email, u.display_name from dac_rule_audit as a LEFT JOIN dac_automation_rules as r on r.id = a.rule_id LEFT JOIN users u on a.user_id = u.user_id @@ -148,11 +165,11 @@ INSERT INTO dac_rule_audit (action, dac_id, rule_id, user_id, action_date) LIMIT :limit OFFSET :offset """) - List findAutomationAuditsForDac(@Bind("dacId") int dacId, - @Bind("limit") int limit, - @Bind("offset") int offset); + List findAutomationAuditsForDac( + @Bind("dacId") int dacId, @Bind("limit") int limit, @Bind("offset") int offset); - @SqlQuery(""" + @SqlQuery( + """ SELECT count(*) from dac_rule_audit WHERE dac_id = :dacId """) Integer findCountOfAutomationAuditsForDac(@Bind("dacId") int dacId); diff --git a/src/main/java/org/broadinstitute/consent/http/db/DAOContainer.java b/src/main/java/org/broadinstitute/consent/http/db/DAOContainer.java index a45febc154..71664d451e 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DAOContainer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DAOContainer.java @@ -2,9 +2,8 @@ /** * Generic container class for DAOs that can be used in service constructors to simplify instance - * creation. - * Per feedback in https://github.com/DataBiosphere/consent/pull/2408 - * 'We should only expand this usage if necessary.' + * creation. Per feedback in https://github.com/DataBiosphere/consent/pull/2408 'We should only + * expand this usage if necessary.' */ @SuppressWarnings("unused") public class DAOContainer { @@ -48,8 +47,7 @@ public DataAccessRequestDAO getDataAccessRequestDAO() { return dataAccessRequestDAO; } - public void setDataAccessRequestDAO( - DataAccessRequestDAO dataAccessRequestDAO) { + public void setDataAccessRequestDAO(DataAccessRequestDAO dataAccessRequestDAO) { this.dataAccessRequestDAO = dataAccessRequestDAO; } @@ -61,14 +59,11 @@ public DarCollectionSummaryDAO getDarCollectionSummaryDAO() { return darCollectionSummaryDAO; } - public void setDarCollectionDAO( - DarCollectionDAO darCollectionDAO) { + public void setDarCollectionDAO(DarCollectionDAO darCollectionDAO) { this.darCollectionDAO = darCollectionDAO; } - public void setDarCollectionSummaryDAO( - DarCollectionSummaryDAO darCollectionSummaryDAO - ) { + public void setDarCollectionSummaryDAO(DarCollectionSummaryDAO darCollectionSummaryDAO) { this.darCollectionSummaryDAO = darCollectionSummaryDAO; } @@ -80,7 +75,8 @@ public void setDatasetDAO(DatasetDAO datasetDAO) { this.datasetDAO = datasetDAO; } - public void setDatasetAuthorizationReaderDAO(DatasetAuthorizationReaderDAO datasetAuthorizationReaderDAO) { + public void setDatasetAuthorizationReaderDAO( + DatasetAuthorizationReaderDAO datasetAuthorizationReaderDAO) { this.datasetAuthorizationReaderDAO = datasetAuthorizationReaderDAO; } @@ -116,8 +112,7 @@ public UserPropertyDAO getUserPropertyDAO() { return userPropertyDAO; } - public void setUserPropertyDAO( - UserPropertyDAO userPropertyDAO) { + public void setUserPropertyDAO(UserPropertyDAO userPropertyDAO) { this.userPropertyDAO = userPropertyDAO; } diff --git a/src/main/java/org/broadinstitute/consent/http/db/DaaDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DaaDAO.java index 42e4af9b75..5765da792e 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DaaDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DaaDAO.java @@ -1,7 +1,6 @@ package org.broadinstitute.consent.http.db; import java.time.Instant; -import java.util.Date; import java.util.List; import org.broadinstitute.consent.http.db.mapper.DaaMapper; import org.broadinstitute.consent.http.db.mapper.DataAccessAgreementReducer; @@ -30,7 +29,8 @@ public interface DaaDAO extends Transactional { @RegisterBeanMapper(value = Dac.class) @RegisterBeanMapper(value = FileStorageObjectDAO.class) @UseRowReducer(DataAccessAgreementReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT daa.daa_id as daa_daa_id, daa.create_user_id as daa_create_user_id, daa.create_date as daa_create_date, @@ -60,7 +60,6 @@ public interface DaaDAO extends Transactional { """) List findAll(); - /** * Find a DAA by id * @@ -71,7 +70,8 @@ public interface DaaDAO extends Transactional { @RegisterBeanMapper(value = Dac.class) @RegisterBeanMapper(value = FileStorageObjectDAO.class) @UseRowReducer(DataAccessAgreementReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT daa.daa_id as daa_daa_id, daa.create_user_id as daa_create_user_id, daa.create_date as daa_create_date, @@ -112,11 +112,12 @@ public interface DaaDAO extends Transactional { @RegisterBeanMapper(value = Dac.class) @RegisterBeanMapper(value = FileStorageObjectDAO.class) @UseRowReducer(DataAccessAgreementReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT daa.daa_id as daa_daa_id, daa.create_user_id as daa_create_user_id, daa.create_date as daa_create_date, - daa.update_user_id as daa_update_user_id, + daa.update_user_id as daa_update_user_id, daa.update_date as daa_update_date, daa.initial_dac_id as daa_initial_dac_id, fso.file_storage_object_id AS file_storage_object_id, @@ -147,29 +148,35 @@ public interface DaaDAO extends Transactional { * Create a Daa given name, description, and create date * * @param createUserId The id of the user who created this DAA - * @param createDate The date this new DAA was created + * @param createDate The date this new DAA was created * @param updateUserId The id of the user who updated this DAA - * @param updateDate The date that this DAA was updated + * @param updateDate The date that this DAA was updated * @param initialDacId The id for the initial DAC this DAA was created for * @return Integer */ - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO data_access_agreement (create_user_id, create_date, update_user_id, update_date, initial_dac_id) VALUES (:createUserId, :createDate, :updateUserId, :updateDate, :initialDacId) """) @GetGeneratedKeys - Integer createDaa(@Bind("createUserId") Integer createUserId, - @Bind("createDate") Instant createDate, @Bind("updateUserId") Integer updateUserId, - @Bind("updateDate") Instant updateDate, @Bind("initialDacId") Integer initialDacId); + Integer createDaa( + @Bind("createUserId") Integer createUserId, + @Bind("createDate") Instant createDate, + @Bind("updateUserId") Integer updateUserId, + @Bind("updateDate") Instant updateDate, + @Bind("initialDacId") Integer initialDacId); - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO dac_daa (dac_id, daa_id) VALUES (:dacId, :daaId) ON CONFLICT (dac_id) DO UPDATE SET daa_id = :daaId """) void createDacDaaRelation(@Bind("dacId") Integer dacId, @Bind("daaId") Integer daaId); - @SqlUpdate(""" + @SqlUpdate( + """ DELETE FROM dac_daa WHERE dac_id = :dacId AND daa_id = :daaId @@ -177,8 +184,8 @@ ON CONFLICT (dac_id) DO UPDATE SET daa_id = :daaId void deleteDacDaaRelation(@Bind("dacId") Integer dacId, @Bind("daaId") Integer daaId); /** - * Relationship chain: - * User -> Library Card -> Data Access Agreement -> DAC -> Dataset + * Relationship chain: User -> Library Card -> Data Access Agreement -> DAC -> Dataset + * * @param userId The requesting User ID * @return List of Dataset Ids for which a user has DAA acceptances */ @@ -193,7 +200,8 @@ ON CONFLICT (dac_id) DO UPDATE SET daa_id = :daaId """) List findDaaDatasetIdsByUserId(@Bind("userId") Integer userId); - @SqlUpdate(""" + @SqlUpdate( + """ WITH lc_deletes AS (DELETE FROM lc_daa WHERE lc_daa.daa_id = :daaId), dac_delete AS (DELETE FROM dac_daa WHERE dac_daa.daa_id = :daaId) DELETE FROM data_access_agreement WHERE daa_id = :daaId @@ -201,8 +209,8 @@ dac_delete AS (DELETE FROM dac_daa WHERE dac_daa.daa_id = :daaId) void deleteDaa(@Bind("daaId") Integer daaId); /** - * Find all DAAs for a Data Access Request by Reference ID - * DAR -> dar dataset join table -> Dataset -> DAC -> dac daa join table -> DAA + * Find all DAAs for a Data Access Request by Reference ID DAR -> dar dataset join table -> + * Dataset -> DAC -> dac daa join table -> DAA * * @param referenceId DAR Reference ID * @return List of Data Access Agreements @@ -211,11 +219,12 @@ dac_delete AS (DELETE FROM dac_daa WHERE dac_daa.daa_id = :daaId) @RegisterBeanMapper(value = Dac.class) @RegisterBeanMapper(value = FileStorageObjectDAO.class) @UseRowReducer(DataAccessAgreementReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT daa.daa_id as daa_daa_id, daa.create_user_id as daa_create_user_id, daa.create_date as daa_create_date, - daa.update_user_id as daa_update_user_id, + daa.update_user_id as daa_update_user_id, daa.update_date as daa_update_date, daa.initial_dac_id as daa_initial_dac_id, fso.file_storage_object_id AS file_storage_object_id, @@ -239,9 +248,8 @@ dac_delete AS (DELETE FROM dac_daa WHERE dac_daa.daa_id = :daaId) INNER JOIN dac_daa ON daa.daa_id = dac_daa.daa_id INNER JOIN dac ON dac.dac_id = dac_daa.dac_id INNER JOIN dataset ON dataset.dac_id = dac.dac_id - INNER JOIN dar_dataset dd on dd.dataset_id = dataset.dataset_id + INNER JOIN dar_dataset dd on dd.dataset_id = dataset.dataset_id WHERE dd.reference_id = :referenceId """) List findByDarReferenceId(@Bind("referenceId") String referenceId); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/DacDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DacDAO.java index bfd807facf..24b6deb295 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DacDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DacDAO.java @@ -45,7 +45,8 @@ public interface DacDAO extends Transactional { @RegisterBeanMapper(value = Dac.class) @RegisterBeanMapper(value = Dataset.class) @UseRowReducer(DacReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT dac.dac_id, dac.email, @@ -98,7 +99,9 @@ public interface DacDAO extends Transactional { @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) @SqlQuery( - "SELECT " + User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR + "SELECT " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + " r.name, " + " ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id " + " FROM users u " @@ -130,7 +133,8 @@ public interface DacDAO extends Transactional { @RegisterBeanMapper(value = DataAccessAgreement.class, prefix = "daa") @RegisterBeanMapper(value = FileStorageObjectDAO.class) @UseRowReducer(DacReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT dac.*, daa.daa_id as daa_daa_id, daa.create_user_id as daa_create_user_id, @@ -161,38 +165,47 @@ public interface DacDAO extends Transactional { /** * Create a Dac given name, description, and create date * - * @param name The name for the new DAC + * @param name The name for the new DAC * @param description The description for the new DAC - * @param createDate The date this new DAC was created + * @param createDate The date this new DAC was created * @return Integer */ - @SqlUpdate("INSERT INTO dac (name, description, create_date) VALUES (:name, :description, :createDate)") + @SqlUpdate( + "INSERT INTO dac (name, description, create_date) VALUES (:name, :description, :createDate)") @GetGeneratedKeys - Integer createDac(@Bind("name") String name, @Bind("description") String description, + Integer createDac( + @Bind("name") String name, + @Bind("description") String description, @Bind("createDate") Date createDate); /** * Create a Dac given name, description, and create date * - * @param name The name for the new DAC + * @param name The name for the new DAC * @param description The description for the new DAC - * @param email The email for the new DAC - * @param createDate The date this new DAC was created + * @param email The email for the new DAC + * @param createDate The date this new DAC was created * @return Integer */ - @SqlUpdate("INSERT INTO dac (name, description, email, create_date) VALUES (:name, :description, :email, :createDate)") + @SqlUpdate( + "INSERT INTO dac (name, description, email, create_date) VALUES (:name, :description, :email, :createDate)") @GetGeneratedKeys - Integer createDac(@Bind("name") String name, @Bind("description") String description, - @Bind("email") String email, @Bind("createDate") Date createDate); + Integer createDac( + @Bind("name") String name, + @Bind("description") String description, + @Bind("email") String email, + @Bind("createDate") Date createDate); - @SqlUpdate("UPDATE dac SET name = :name, description = :description, update_date = :updateDate WHERE dac_id = :dacId") + @SqlUpdate( + "UPDATE dac SET name = :name, description = :description, update_date = :updateDate WHERE dac_id = :dacId") void updateDac( @Bind("name") String name, @Bind("description") String description, @Bind("updateDate") Date updateDate, @Bind("dacId") Integer dacId); - @SqlUpdate("UPDATE dac SET name = :name, description = :description, email = :email, update_date = :updateDate WHERE dac_id = :dacId") + @SqlUpdate( + "UPDATE dac SET name = :name, description = :description, email = :email, update_date = :updateDate WHERE dac_id = :dacId") void updateDac( @Bind("name") String name, @Bind("description") String description, @@ -215,7 +228,9 @@ void updateDac( @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) @SqlQuery( - "SELECT " + User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR + "SELECT " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + " ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id, r.name " + " FROM users u " + " INNER JOIN user_role ur ON ur.user_id = u.user_id " @@ -227,19 +242,21 @@ void updateDac( @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) @SqlQuery( - "SELECT " + User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR + "SELECT " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + " ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id, r.name " + " FROM users u " + " INNER JOIN user_role ur ON ur.user_id = u.user_id " + " INNER JOIN roles r ON r.role_id = ur.role_id " + " WHERE ur.dac_id = :dacId " + " AND ur.role_id = :roleId ") - List findMembersByDacIdAndRoleId(@Bind("dacId") Integer dacId, - @Bind("roleId") Integer roleId); + List findMembersByDacIdAndRoleId( + @Bind("dacId") Integer dacId, @Bind("roleId") Integer roleId); @SqlUpdate("INSERT INTO user_role (role_id, user_id, dac_id) VALUES (:roleId, :userId, :dacId)") - void addDacMember(@Bind("roleId") Integer roleId, @Bind("userId") Integer userId, - @Bind("dacId") Integer dacId); + void addDacMember( + @Bind("roleId") Integer roleId, @Bind("userId") Integer userId, @Bind("dacId") Integer dacId); @SqlUpdate("DELETE FROM user_role WHERE user_role_id = :userRoleId") void removeDacMember(@Bind("userRoleId") Integer userRoleId); @@ -252,7 +269,8 @@ void addDacMember(@Bind("roleId") Integer roleId, @Bind("userId") Integer userId @SqlQuery( "SELECT ur.*, r.name FROM user_role ur " + " INNER JOIN roles r ON ur.role_id = r.role_id WHERE ur.user_id IN ()") - List findUserRolesForUsers(@BindList(value = "userIds", onEmpty = EmptyHandling.NULL_STRING) List userIds); + List findUserRolesForUsers( + @BindList(value = "userIds", onEmpty = EmptyHandling.NULL_STRING) List userIds); /** * Find the Dacs for these datasets. @@ -261,16 +279,20 @@ void addDacMember(@Bind("roleId") Integer roleId, @Bind("userId") Integer userId * @return All DACs that corresponds to the provided dataset ids */ @RegisterRowMapper(DacMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.*, ds.dataset_id FROM dac d INNER JOIN dataset ds ON d.dac_id = ds.dac_id WHERE ds.dataset_id IN () """) - Set findDacsForDatasetIds(@BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) List datasetIds); + Set findDacsForDatasetIds( + @BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) + List datasetIds); @RegisterRowMapper(DacMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT dac.* FROM dac INNER JOIN dataset d ON d.dac_id = dac.dac_id @@ -279,5 +301,4 @@ WHERE ds.dataset_id IN () WHERE dar.collection_id = :collectionId """) Collection findDacsForCollectionId(@Bind("collectionId") Integer collectionId); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/DarCollectionDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DarCollectionDAO.java index 9ff70c12c8..72ca3e6a1b 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DarCollectionDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DarCollectionDAO.java @@ -26,32 +26,34 @@ public interface DarCollectionDAO extends Transactional { String QUERY_FIELD_SEPARATOR = ", "; String getCollectionAndDars = - " SELECT c.*, i.institution_name, u.display_name AS researcher, dd.dataset_id, " + - User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR + - Institution.QUERY_FIELDS_WITH_I_PREFIX + QUERY_FIELD_SEPARATOR + - Election.QUERY_FIELDS_WITH_E_PREFIX + QUERY_FIELD_SEPARATOR + - Vote.QUERY_FIELDS_WITH_V_PREFIX + QUERY_FIELD_SEPARATOR + - UserProperty.QUERY_FIELDS_WITH_UP_PREFIX + QUERY_FIELD_SEPARATOR + - DarCollection.DAR_FILTER_QUERY_COLUMNS + - " FROM dar_collection c " + - " INNER JOIN users u ON u.user_id = c.create_user_id " + - " LEFT JOIN user_property up ON u.user_id = up.user_id AND up.property_key in ('isThePI', 'piName', 'havePI', 'piERACommonsID') " - + - " LEFT JOIN institution i ON i.institution_id = u.institution_id " + - " INNER JOIN data_access_request dar ON c.collection_id = dar.collection_id " + - " LEFT JOIN dar_dataset dd ON dd.reference_id = dar.reference_id " + - " LEFT JOIN (" + - " SELECT election.*, MAX(election.election_id) OVER (PARTITION BY election.reference_id, election.election_type, election.dataset_id) AS latest " - + - " FROM election " + - " WHERE LOWER(election.election_type) = 'dataaccess' OR LOWER(election.election_type) = 'rp'" - + - " ) AS e " + - " ON (dar.reference_id = e.reference_id AND dd.dataset_id = e.dataset_id) AND (e.latest = e.election_id OR e.latest IS NULL) " - + - " LEFT JOIN vote v ON v.election_id = e.election_id "; + " SELECT c.*, i.institution_name, u.display_name AS researcher, dd.dataset_id, " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + + Institution.QUERY_FIELDS_WITH_I_PREFIX + + QUERY_FIELD_SEPARATOR + + Election.QUERY_FIELDS_WITH_E_PREFIX + + QUERY_FIELD_SEPARATOR + + Vote.QUERY_FIELDS_WITH_V_PREFIX + + QUERY_FIELD_SEPARATOR + + UserProperty.QUERY_FIELDS_WITH_UP_PREFIX + + QUERY_FIELD_SEPARATOR + + DarCollection.DAR_FILTER_QUERY_COLUMNS + + " FROM dar_collection c " + + " INNER JOIN users u ON u.user_id = c.create_user_id " + + " LEFT JOIN user_property up ON u.user_id = up.user_id AND up.property_key in ('isThePI', 'piName', 'havePI', 'piERACommonsID') " + + " LEFT JOIN institution i ON i.institution_id = u.institution_id " + + " INNER JOIN data_access_request dar ON c.collection_id = dar.collection_id " + + " LEFT JOIN dar_dataset dd ON dd.reference_id = dar.reference_id " + + " LEFT JOIN (" + + " SELECT election.*, MAX(election.election_id) OVER (PARTITION BY election.reference_id, election.election_type, election.dataset_id) AS latest " + + " FROM election " + + " WHERE LOWER(election.election_type) = 'dataaccess' OR LOWER(election.election_type) = 'rp'" + + " ) AS e " + + " ON (dar.reference_id = e.reference_id AND dd.dataset_id = e.dataset_id) AND (e.latest = e.election_id OR e.latest IS NULL) " + + " LEFT JOIN vote v ON v.election_id = e.election_id "; - String archiveFilterQuery = " AND (LOWER(data->>'status') != 'archived' OR data->>'status' IS NULL) "; + String archiveFilterQuery = + " AND (LOWER(data->>'status') != 'archived' OR data->>'status' IS NULL) "; @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = Institution.class, prefix = "i") @@ -64,7 +66,8 @@ public interface DarCollectionDAO extends Transactional { @SqlQuery( getCollectionAndDars + " WHERE c.collection_id in ()" + archiveFilterQuery) List findDARCollectionByCollectionIds( - @BindList(value = "collectionIds", onEmpty = EmptyHandling.NULL_STRING) List collectionIds); + @BindList(value = "collectionIds", onEmpty = EmptyHandling.NULL_STRING) + List collectionIds); /** * Find all DARCollections with their DataAccessRequests @@ -79,35 +82,34 @@ List findDARCollectionByCollectionIds( @RegisterBeanMapper(value = Election.class, prefix = "e") @UseRowReducer(DarCollectionReducer.class) @SqlQuery( - " SELECT c.*, " + - User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR + - Institution.QUERY_FIELDS_WITH_I_PREFIX + QUERY_FIELD_SEPARATOR + - UserProperty.QUERY_FIELDS_WITH_UP_PREFIX + QUERY_FIELD_SEPARATOR + - Election.QUERY_FIELDS_WITH_E_PREFIX + QUERY_FIELD_SEPARATOR + - "dd.dataset_id, " + - "dar.id AS dar_id, dar.reference_id AS dar_reference_id, dar.collection_id AS dar_collection_id, " - + - "dar.parent_id AS dar_parent_id, dar.user_id AS dar_userId, " + - "dar.create_date AS dar_create_date, dar.submission_date AS dar_submission_date, " + - "dar.closeout_so_approval_timestamp AS dar_closeout_signing_official_approved_date, "+ - "dar.closeout_approving_so_id AS dar_closeout_signing_official_approved_user_id, " + - "dar.update_date AS dar_update_date, (dar.data #>> '{}')::jsonb AS data " + - "FROM dar_collection c " + - "INNER JOIN users u ON c.create_user_id = u.user_id " + - "LEFT JOIN user_property up ON u.user_id = up.user_id " + - "INNER JOIN data_access_request dar on c.collection_id = dar.collection_id " + - "LEFT JOIN dar_dataset dd on dd.reference_id = dar.reference_id " + - "LEFT JOIN institution i ON i.institution_id = u.institution_id " + - "LEFT JOIN (" + - " SELECT election.*, MAX(election.election_id) OVER (PARTITION BY election.reference_id, election.election_type, election.dataset_id) AS latest FROM election " - + - " WHERE LOWER(election.election_type) = 'dataaccess' OR LOWER(election.election_type) = 'rp' " - + - ") AS e " + - " ON (dar.reference_id = e.reference_id AND dd.dataset_id = e.dataset_id) AND (e.latest = e.election_id OR e.latest IS NULL) " - + - "WHERE (LOWER(data->>'status')!='archived' OR data->>'status' IS NULL) " - ) + " SELECT c.*, " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + + Institution.QUERY_FIELDS_WITH_I_PREFIX + + QUERY_FIELD_SEPARATOR + + UserProperty.QUERY_FIELDS_WITH_UP_PREFIX + + QUERY_FIELD_SEPARATOR + + Election.QUERY_FIELDS_WITH_E_PREFIX + + QUERY_FIELD_SEPARATOR + + "dd.dataset_id, " + + "dar.id AS dar_id, dar.reference_id AS dar_reference_id, dar.collection_id AS dar_collection_id, " + + "dar.parent_id AS dar_parent_id, dar.user_id AS dar_userId, " + + "dar.create_date AS dar_create_date, dar.submission_date AS dar_submission_date, " + + "dar.closeout_so_approval_timestamp AS dar_closeout_signing_official_approved_date, " + + "dar.closeout_approving_so_id AS dar_closeout_signing_official_approved_user_id, " + + "dar.update_date AS dar_update_date, (dar.data #>> '{}')::jsonb AS data " + + "FROM dar_collection c " + + "INNER JOIN users u ON c.create_user_id = u.user_id " + + "LEFT JOIN user_property up ON u.user_id = up.user_id " + + "INNER JOIN data_access_request dar on c.collection_id = dar.collection_id " + + "LEFT JOIN dar_dataset dd on dd.reference_id = dar.reference_id " + + "LEFT JOIN institution i ON i.institution_id = u.institution_id " + + "LEFT JOIN (" + + " SELECT election.*, MAX(election.election_id) OVER (PARTITION BY election.reference_id, election.election_type, election.dataset_id) AS latest FROM election " + + " WHERE LOWER(election.election_type) = 'dataaccess' OR LOWER(election.election_type) = 'rp' " + + ") AS e " + + " ON (dar.reference_id = e.reference_id AND dd.dataset_id = e.dataset_id) AND (e.latest = e.election_id OR e.latest IS NULL) " + + "WHERE (LOWER(data->>'status')!='archived' OR data->>'status' IS NULL) ") List findAllDARCollections(); /** @@ -166,10 +168,14 @@ List findDARCollectionByCollectionIds( @SqlQuery( // nosemgrep "SELECT c.*, " - + User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR - + Institution.QUERY_FIELDS_WITH_I_PREFIX + QUERY_FIELD_SEPARATOR - + UserProperty.QUERY_FIELDS_WITH_UP_PREFIX + QUERY_FIELD_SEPARATOR - + LibraryCard.QUERY_FIELDS_WITH_LC_PREFIX + QUERY_FIELD_SEPARATOR + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + + Institution.QUERY_FIELDS_WITH_I_PREFIX + + QUERY_FIELD_SEPARATOR + + UserProperty.QUERY_FIELDS_WITH_UP_PREFIX + + QUERY_FIELD_SEPARATOR + + LibraryCard.QUERY_FIELDS_WITH_LC_PREFIX + + QUERY_FIELD_SEPARATOR + "dd.dataset_id, " + "dar.id AS dar_id, dar.reference_id AS dar_reference_id, dar.collection_id AS dar_collection_id, " + "dar.parent_id AS dar_parent_id, dar.user_id AS dar_userId, dar.era_commons_id AS dar_era_commons_id, " @@ -199,8 +205,7 @@ List findDARCollectionByCollectionIds( + "LEFT JOIN users du " + "ON du.user_id = v.user_id " + "WHERE c.collection_id = :collectionId " - + "AND (LOWER(data->>'status') != 'archived' OR data->>'status' IS NULL )" - ) + + "AND (LOWER(data->>'status') != 'archived' OR data->>'status' IS NULL )") DarCollection findDARCollectionByCollectionId(@Bind("collectionId") Integer collectionId); /** @@ -220,7 +225,7 @@ List findDARCollectionByCollectionIds( @RegisterBeanMapper(value = LibraryCard.class, prefix = "lc") @UseRowReducer(DarCollectionReducer.class) @SqlQuery( - """ +""" SELECT c.*, u.user_id as u_user_id, u.email as u_email, u.display_name as u_display_name, u.create_date as u_create_date, u.email_preference as u_email_preference, u.institution_id as u_institution_id, u.era_commons_id as u_era_commons_id, i.institution_id as i_id, i.institution_name as i_name, i.it_director_name as i_it_director_name, i.it_director_email as i_it_director_email, i.create_date as i_create_date, i.update_date as i_update_date, @@ -252,15 +257,15 @@ List findDARCollectionByCollectionIds( ON du.user_id = v.user_id WHERE c.collection_id = :collectionId AND (LOWER(data->>'status') != 'archived' OR data->>'status' IS NULL ) -""" - ) - DarCollection findCollectionWithAllElectionsByCollectionId(@Bind("collectionId") Integer collectionId); - +""") + DarCollection findCollectionWithAllElectionsByCollectionId( + @Bind("collectionId") Integer collectionId); /** * Find the DARCollection and all of its Data Access Requests that has the given collectionId - * Instead of including all elections for each DAR like findCollectionWithAllElectionsByCollectionId - * this query returns only elections for the datasets in the given datasetIds list + * Instead of including all elections for each DAR like + * findCollectionWithAllElectionsByCollectionId this query returns only elections for the datasets + * in the given datasetIds list * * @return DarCollection */ @@ -307,9 +312,10 @@ List findDARCollectionByCollectionIds( ON du.user_id = v.user_id WHERE c.collection_id = :collectionId AND (LOWER(data->>'status') != 'archived' OR data->>'status' IS NULL ) - """ - ) - DarCollection findCollectionWithElectionsByCollectionIdAndDatasetIds(@BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) List datasetIds, @Bind("collectionId") Integer collectionId); + """) + DarCollection findCollectionWithElectionsByCollectionIdAndDatasetIds( + @BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) List datasetIds, + @Bind("collectionId") Integer collectionId); /** * Create a new DAR Collection with the given dar code, create user ID, and create date @@ -323,22 +329,16 @@ List findDARCollectionByCollectionIds( VALUES (:darCode, :createUserId, :createDate) """) @GetGeneratedKeys - Integer insertDarCollection(@Bind("darCode") String darCode, + Integer insertDarCollection( + @Bind("darCode") String darCode, @Bind("createUserId") Integer createUserId, @Bind("createDate") Date createDate); - /** - * Update the update user and update date of the DAR Collection with the given collection ID - */ - @SqlUpdate("UPDATE dar_collection SET update_user_id = :updateUserId, update_date = :updateDate WHERE collection_id = :collectionId") - void updateDarCollection(@Bind("collectionId") Integer collectionId, + /** Update the update user and update date of the DAR Collection with the given collection ID */ + @SqlUpdate( + "UPDATE dar_collection SET update_user_id = :updateUserId, update_date = :updateDate WHERE collection_id = :collectionId") + void updateDarCollection( + @Bind("collectionId") Integer collectionId, @Bind("updateUserId") Integer updateUserId, @Bind("updateDate") Date updateDate); - } - - - - - - diff --git a/src/main/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAO.java index 219d4150c8..984f2edfb9 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAO.java @@ -21,7 +21,8 @@ public interface DarCollectionSummaryDAO extends Transactional getDarCollectionSummariesForDACRole( @RegisterBeanMapper(value = DarCollection.class) @RegisterBeanMapper(value = Election.class) @UseRowReducer(DarCollectionSummaryReducer.class) - @SqlQuery - ( - """ + @SqlQuery( + """ SELECT c.collection_id as dar_collection_id, c.dar_code, latest_dar.submission_date, @@ -153,8 +153,7 @@ WHERE LOWER(election.election_type) = 'dataaccess' latest_dar.closeout_approving_so_id, latest_dar.closeout_so_approval_timestamp, u.display_name, i.institution_name, e.election_id, e.status, e.reference_id, e.dataset_id, dd.dataset_id, latest_dar.data, dac.name - """ - ) + """) List getDarCollectionSummariesForSO( @Bind("institutionId") Integer institutionId); @@ -162,7 +161,8 @@ List getDarCollectionSummariesForSO( @RegisterBeanMapper(value = DarCollection.class) @RegisterBeanMapper(value = Election.class) @UseRowReducer(DarCollectionSummaryReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT c.collection_id AS dar_collection_id, c.dar_code, @@ -217,7 +217,8 @@ WHERE LOWER(election.election_type) = 'dataaccess' @RegisterBeanMapper(value = DarCollection.class) @RegisterBeanMapper(value = Election.class) @UseRowReducer(DarCollectionSummaryReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT c.collection_id AS dar_collection_id, c.dar_code, @@ -280,7 +281,8 @@ WHERE LOWER(election.election_type) = 'dataaccess' @RegisterBeanMapper(value = Vote.class, prefix = "v") @RegisterBeanMapper(value = Election.class) @UseRowReducer(DarCollectionSummaryReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT c.collection_id as dar_collection_id, c.dar_code, latest_dar.submission_date, latest_dar.reference_id AS latest_dar_reference_id, latest_dar.parent_id AS latest_dar_parent_id, latest_dar.closeout_approving_so_id as latest_dar_closeout_approving_so_id, @@ -338,14 +340,12 @@ DarCollectionSummary getDarCollectionSummaryForDACByCollectionId( @BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) List datasetIds, @Bind("collectionId") Integer collectionId); - @RegisterBeanMapper(value = DarCollectionSummary.class) @RegisterBeanMapper(value = DarCollection.class) @RegisterBeanMapper(value = Election.class) @UseRowReducer(DarCollectionSummaryReducer.class) - @SqlQuery - ( - """ + @SqlQuery( + """ SELECT c.collection_id as dar_collection_id, c.dar_code, latest_dar.submission_date, latest_dar.reference_id as latest_dar_reference_id, latest_dar.parent_id as latest_dar_parent_id, latest_dar.closeout_approving_so_id as latest_dar_closeout_approving_so_id, @@ -390,8 +390,7 @@ WHERE LOWER(election.election_type) = 'dataaccess' latest_dar.closeout_approving_so_id, latest_dar.closeout_so_approval_timestamp, u.display_name, u.user_id, i.institution_name, i.institution_id, e.election_id, e.status, e.dataset_id, e.reference_id, dd.dataset_id, latest_dar.data, dac.name - """ - ) + """) DarCollectionSummary getDarCollectionSummaryByCollectionId( @Bind("collectionId") Integer collectionId); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/DataAccessRequestDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DataAccessRequestDAO.java index a01d659027..9ed9255ff6 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DataAccessRequestDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DataAccessRequestDAO.java @@ -24,8 +24,8 @@ import org.jdbi.v3.sqlobject.transaction.Transactional; /** - * For all json queries, note the double `??` for jdbi3 escaped jsonb operators: - * ... + * For all json queries, note the double `??` for jdbi3 escaped jsonb operators: ... */ @RegisterRowMapper(DataAccessRequestMapper.class) public interface DataAccessRequestDAO extends Transactional { @@ -64,7 +64,8 @@ public interface DataAccessRequestDAO extends Transactional findDatasetApprovalsByDar(@Bind("darReferenceId") String darReferenceId); /** - * This query finds submitted DARs based on a date range. This would be useful if we wanted to + * This query finds submitted DARs based on a date range. This would be useful if we wanted to * send notifications for "expiring" DARs 30 days before expiration and again at 7 days. * * @param emailType - Type of email message associated with a DAR - * @param interval - The POSTGRESQL time interval. This value will be subtracted from now() + * @param interval - The POSTGRESQL time interval. This value will be subtracted from now() * @return List of submitted DARs within the date range provided. */ @UseRowReducer(DataAccessRequestReducer.class) @@ -167,10 +168,12 @@ AND dar.collection_id NOT IN ( WHERE dar.submission_date >= :notBefore AND (dar.submission_date < now() - :interval ::interval) AND (email.email_type IS NULL) - + """) - List findAgedDARsByEmailTypeOlderThanInterval(@Bind("emailType") Integer emailType, - @Bind("interval") String interval, @Bind("notBefore") Timestamp notBefore); + List findAgedDARsByEmailTypeOlderThanInterval( + @Bind("emailType") Integer emailType, + @Bind("interval") String interval, + @Bind("notBefore") Timestamp notBefore); /** * Find all draft/partial DataAccessRequests, sorted descending order @@ -256,17 +259,19 @@ List findAgedDARsByEmailTypeOlderThanInterval(@Bind("emailTyp WHERE dar.reference_id IN () AND (LOWER(dar.data->>'status') != 'archived' OR dar.data->>'status' IS NULL) """) - List findByReferenceIds(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + List findByReferenceIds( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); /** * Update DataAccessRequest properties by reference id. * - * @param referenceId String - * @param userId Integer User + * @param referenceId String + * @param userId Integer User * @param submissionDate Date Submission Date - * @param updateDate Date Update Date - * @param data DataAccessRequestData DAR Properties - * @param eraCommonsId The user's era commons id at the time of update + * @param updateDate Date Update Date + * @param data DataAccessRequestData DAR Properties + * @param eraCommonsId The user's era commons id at the time of update */ @RegisterArgumentFactory(JsonArgumentFactory.class) @SqlUpdate( @@ -290,14 +295,15 @@ void updateDataByReferenceId( * @param referenceId String */ @SqlUpdate( - """ + """ DELETE FROM data_access_request WHERE reference_id = :referenceId """) void deleteByReferenceId(@Bind("referenceId") String referenceId); - @SqlUpdate("DELETE FROM data_access_request WHERE reference_id IN ()") - void deleteByReferenceIds(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + void deleteByReferenceIds( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); @SqlUpdate( """ @@ -305,7 +311,9 @@ void updateDataByReferenceId( SET data = jsonb_set(data, '{status}', '"Canceled"'::jsonb) WHERE reference_id IN () """) - void cancelByReferenceIds(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + void cancelByReferenceIds( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); /** * Delete all DataAccessRequests with the given collection id @@ -313,7 +321,7 @@ WHERE reference_id IN () * @param collectionId Integer */ @SqlUpdate( - """ + """ DELETE FROM data_access_request WHERE collection_id = :collectionId """) void deleteByCollectionId(@Bind("collectionId") Integer collectionId); @@ -322,10 +330,10 @@ WHERE reference_id IN () * Create new DataAccessRequest in draft status * * @param referenceId String - * @param userId Integer User - * @param createDate Date Creation Date - * @param updateDate Date Update Date - * @param data DataAccessRequestData DAR Properties + * @param userId Integer User + * @param createDate Date Creation Date + * @param updateDate Date Update Date + * @param data DataAccessRequestData DAR Properties */ @RegisterArgumentFactory(JsonArgumentFactory.class) @SqlUpdate( @@ -345,13 +353,13 @@ void insertDraftDataAccessRequest( /** * Create new DataAccessRequest. This version supersedes `insertV2` * - * @param collectionId Integer DarCollection - * @param referenceId String - * @param userId Integer User - * @param createDate Date Creation Date + * @param collectionId Integer DarCollection + * @param referenceId String + * @param userId Integer User + * @param createDate Date Creation Date * @param submissionDate Date Submission Date - * @param updateDate Date Update Date - * @param data DataAccessRequestData DAR Properties + * @param updateDate Date Update Date + * @param data DataAccessRequestData DAR Properties */ @RegisterArgumentFactory(JsonArgumentFactory.class) @SqlUpdate( @@ -374,11 +382,11 @@ void insertDataAccessRequest( /** * Create new Progress Report. * - * @param parentId String Parent ID - * @param collectionId Integer DarCollection - * @param referenceId String - * @param userId Integer User - * @param data DataAccessRequestData DAR Properties + * @param parentId String Parent ID + * @param collectionId Integer DarCollection + * @param referenceId String + * @param userId Integer User + * @param data DataAccessRequestData DAR Properties */ @RegisterArgumentFactory(JsonArgumentFactory.class) @SqlUpdate( @@ -395,7 +403,6 @@ void insertProgressReport( @Bind("data") @Json DataAccessRequestData data, @Bind("eraCommonsId") String eraCommonsId); - /** * Converts a Draft DataAccessRequest into a non-draft DataAccessRequest * @@ -407,8 +414,8 @@ void insertProgressReport( SET submission_date = now(), collection_id = :collectionId WHERE reference_id = :referenceId """) - void updateDraftToSubmittedForCollection(@Bind("collectionId") Integer collectionId, - @Bind("referenceId") String referenceId); + void updateDraftToSubmittedForCollection( + @Bind("collectionId") Integer collectionId, @Bind("referenceId") String referenceId); @SqlUpdate( """ @@ -416,15 +423,18 @@ void updateDraftToSubmittedForCollection(@Bind("collectionId") Integer collectio SET data = jsonb_set ((data #>> '{}')::jsonb, '{status}', '"Archived"', true) WHERE reference_id IN () """) - void archiveByReferenceIds(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + void archiveByReferenceIds( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); @SqlUpdate( - """ + """ UPDATE data_access_request SET closeout_approving_so_id = :id, closeout_so_approval_timestamp = now() WHERE reference_id = :referenceId """) - void updateDarCloseoutSO(@Bind("id") Integer signingOfficialUserId, @Bind("referenceId") String referenceId); + void updateDarCloseoutSO( + @Bind("id") Integer signingOfficialUserId, @Bind("referenceId") String referenceId); /** * Inserts into dar_dataset collection @@ -466,7 +476,9 @@ INSERT INTO dar_dataset (reference_id, dataset_id) * @param referenceIds List */ @SqlUpdate("DELETE FROM dar_dataset WHERE reference_id in ()") - void deleteDARDatasetRelationByReferenceIds(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + void deleteDARDatasetRelationByReferenceIds( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); /** * Returns all dataset_ids that match any of the referenceIds inside the "referenceIds" list @@ -474,6 +486,7 @@ INSERT INTO dar_dataset (reference_id, dataset_id) * @param referenceIds List */ @SqlQuery("SELECT distinct dataset_id FROM dar_dataset WHERE reference_id IN ()") - List findAllDARDatasetRelations(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); - + List findAllDARDatasetRelations( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/DatasetDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DatasetDAO.java index c83c1784df..42aa637dce 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DatasetDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DatasetDAO.java @@ -48,11 +48,13 @@ public interface DatasetDAO extends Transactional { /** * Find a Dataset by id. + * * @param datasetId The dataset id * @return Dataset */ @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.dataset_id, d.name, d.create_date, d.create_user_id, d.update_date, d.update_user_id, d.object_id, d.dac_id, d.alias, d.data_use, d.translated_data_use, d.dac_approval, d.study_id, d.indexed_date, @@ -90,11 +92,13 @@ public interface DatasetDAO extends Transactional { /** * Find a minimal version of a Dataset by alias. This query excludes file and study information * which is often not necessary for many operations. + * * @param alias The dataset alias * @return Dataset */ @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.dataset_id, d.name, d.create_date, d.create_user_id, d.update_date, d.update_user_id, d.object_id, d.dac_id, d.alias, d.data_use, d.translated_data_use, d.dac_approval, d.study_id, d.indexed_date, @@ -140,7 +144,8 @@ Integer insertDataset( @Bind("dataUse") String dataUse, @Bind("dacId") Integer dacId); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE dataset SET name = :datasetName, update_date = :updateDate, @@ -156,7 +161,8 @@ void updateDatasetByDatasetId( @Bind("dacId") Integer updatedDacId); @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.dataset_id, d.name, d.create_date, d.create_user_id, d.update_date, d.update_user_id, d.object_id, d.dac_id, d.alias, d.data_use, d.translated_data_use, d.dac_approval, dar_ds_ids.id AS in_use, d.study_id, d.indexed_date, @@ -213,7 +219,8 @@ LEFT JOIN file_storage_object fso ON (fso.entity_id = d.dataset_id::text OR fso. * @return List of datasets */ @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.dataset_id, d.name, d.create_date, d.create_user_id, d.update_date, d.update_user_id, d.object_id, d.dac_id, d.alias, d.data_use, d.translated_data_use, d.dac_approval, dar_ds_ids.id AS in_use, d.study_id, d.indexed_date, @@ -242,9 +249,12 @@ LEFT JOIN (SELECT DISTINCT dataset_id AS id FROM dar_dataset) dar_ds_ids ON dar_ WHERE d.dataset_id in () ORDER BY d.dataset_id """) - List findDatasetsByIdList(@BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) Collection datasetIds); + List findDatasetsByIdList( + @BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) + Collection datasetIds); - @SqlQuery(""" + @SqlQuery( + """ SELECT dataset_id FROM dataset ORDER BY dataset_id """) List findAllDatasetIds(); @@ -255,7 +265,8 @@ WHERE d.dataset_id in () * @param userId User ID * @return List of Dataset IDs that are visible to the user via DACs. */ - @SqlQuery(""" + @SqlQuery( + """ SELECT distinct d.dataset_id FROM dataset d INNER JOIN user_role dac_role ON dac_role.dac_id = d.dac_id @@ -272,7 +283,8 @@ WHERE d.dataset_id in () * @return all datasets associated with DAC */ @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.dataset_id, d.name, d.create_date, d.create_user_id, d.update_date, d.update_user_id, d.object_id, d.dac_id, d.alias, d.data_use, d.translated_data_use, d.dac_approval, dar_ds_ids.id AS in_use, d.study_id, d.indexed_date, @@ -290,7 +302,8 @@ LEFT JOIN (SELECT DISTINCT dataset_id AS id FROM dar_dataset) dar_ds_ids ON dar_ """) List findDatasetsAssociatedWithDac(@Bind("dacId") Integer dacId); - @SqlQuery(""" + @SqlQuery( + """ SELECT DISTINCT dp.property_value as name FROM dataset_property dp INNER JOIN dataset d ON dp.dataset_id = d.dataset_id @@ -301,7 +314,8 @@ LEFT JOIN (SELECT DISTINCT dataset_id AS id FROM dar_dataset) dar_ds_ids ON dar_ """) Set findAllStudyNames(); - @SqlQuery(""" + @SqlQuery( + """ SELECT DISTINCT d.name FROM dataset d WHERE d.name IS NOT NULL @@ -309,7 +323,8 @@ LEFT JOIN (SELECT DISTINCT dataset_id AS id FROM dar_dataset) dar_ds_ids ON dar_ List findAllDatasetNames(); @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.dataset_id, d.name, d.create_date, d.create_user_id, d.update_date, d.update_user_id, d.object_id, d.dac_id, d.alias, d.data_use, d.translated_data_use, d.dac_approval, dar_ds_ids.id AS in_use, d.study_id, d.indexed_date, @@ -366,7 +381,8 @@ LEFT JOIN file_storage_object fso ON (fso.entity_id = d.dataset_id::text OR fso. * @return List of datasets */ @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.dataset_id, d.name, d.create_date, d.create_user_id, d.update_date, d.update_user_id, d.object_id, d.dac_id, d.alias, d.data_use, d.translated_data_use, d.dac_approval, dar_ds_ids.id AS in_use, d.study_id, d.indexed_date, @@ -394,21 +410,22 @@ LEFT JOIN (SELECT DISTINCT dataset_id AS id FROM dar_dataset) dar_ds_ids ON dar_ LEFT JOIN file_storage_object fso ON fso.entity_id = d.dataset_id::text AND fso.deleted = false WHERE d.alias IN () """) - List findDatasetsByAlias(@BindList(value = "aliases", onEmpty = EmptyHandling.NULL_STRING) List aliases); + List findDatasetsByAlias( + @BindList(value = "aliases", onEmpty = EmptyHandling.NULL_STRING) List aliases); @SqlUpdate("UPDATE dataset SET dac_id = :dacId WHERE dataset_id = :datasetId") void updateDatasetDacId(@Bind("datasetId") Integer datasetId, @Bind("dacId") Integer dacId); - - @SqlUpdate("UPDATE dataset SET translated_data_use = :translatedDataUse WHERE dataset_id = :datasetId") - void updateDatasetTranslatedDataUse(@Bind("datasetId") Integer datasetId, - @Bind("translatedDataUse") String translatedDataUse); + @SqlUpdate( + "UPDATE dataset SET translated_data_use = :translatedDataUse WHERE dataset_id = :datasetId") + void updateDatasetTranslatedDataUse( + @Bind("datasetId") Integer datasetId, @Bind("translatedDataUse") String translatedDataUse); @SqlUpdate("UPDATE dataset SET name = :name WHERE dataset_id = :datasetId") void updateDatasetName(@Bind("datasetId") Integer datasetId, @Bind("name") String name); - - @SqlBatch(""" + @SqlBatch( + """ INSERT INTO dataset_property (dataset_id, property_key, schema_property, property_value, property_type, create_date ) VALUES @@ -419,7 +436,8 @@ void updateDatasetTranslatedDataUse(@Bind("datasetId") Integer datasetId, @SqlUpdate("DELETE FROM dataset_property WHERE dataset_id = :datasetId") void deleteDatasetPropertiesByDatasetId(@Bind("datasetId") Integer datasetId); - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO dataset_audit (dataset_id, change_action, modified_by_user, modification_date, object_id, name) VALUES @@ -429,7 +447,8 @@ void updateDatasetTranslatedDataUse(@Bind("datasetId") Integer datasetId, Integer insertDatasetAudit(@BindBean DatasetAudit dataSets); @UseRowMapper(DatasetAuditMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM dataset_audit WHERE dataset_id = :datasetId @@ -441,29 +460,31 @@ void updateDatasetTranslatedDataUse(@Bind("datasetId") Integer datasetId, + "SET property_value = :propertyValue " + "WHERE dataset_id = :datasetId " + "AND property_key = :propertyKey") - void updateDatasetProperty(@Bind("datasetId") Integer datasetId, - @Bind("propertyKey") Integer propertyKey, @Bind("propertyValue") String propertyValue); + void updateDatasetProperty( + @Bind("datasetId") Integer datasetId, + @Bind("propertyKey") Integer propertyKey, + @Bind("propertyValue") String propertyValue); @SqlUpdate( """ UPDATE dataset SET study_id = :studyId WHERE dataset_id = :datasetId - """ - ) + """) void updateStudyId(@Bind("datasetId") Integer datasetId, @Bind("studyId") Integer studyId); @SqlUpdate( "DELETE from dataset_property " + "WHERE dataset_id = :datasetId " + "AND property_key = :propertyKey") - void deleteDatasetPropertyByKey(@Bind("datasetId") Integer datasetId, - @Bind("propertyKey") Integer propertyKey); + void deleteDatasetPropertyByKey( + @Bind("datasetId") Integer datasetId, @Bind("propertyKey") Integer propertyKey); @SqlUpdate("DELETE FROM dataset WHERE dataset_id = :datasetId") void deleteDatasetById(@Bind("datasetId") Integer datasetId); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE dataset SET name = :datasetName, update_date = :updateDate, @@ -471,53 +492,61 @@ void deleteDatasetPropertyByKey(@Bind("datasetId") Integer datasetId, dac_id = :dacId WHERE dataset_id = :datasetId """) - void updateDataset(@Bind("datasetId") Integer datasetId, - @Bind("datasetName") String datasetName, @Bind("updateDate") Timestamp updateDate, + void updateDataset( + @Bind("datasetId") Integer datasetId, + @Bind("datasetName") String datasetName, + @Bind("updateDate") Timestamp updateDate, @Bind("updateUserId") Integer updateUserId, @Bind("dacId") Integer updatedDacId); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE dataset SET data_use = :dataUse WHERE dataset_id = :datasetId """) void updateDatasetDataUse(@Bind("datasetId") Integer datasetId, @Bind("dataUse") String dataUse); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE dataset SET create_user_id = :createUserId WHERE dataset_id = :datasetId """) - void updateDatasetCreateUserId(@Bind("datasetId") Integer datasetId, - @Bind("createUserId") Integer createUserId); + void updateDatasetCreateUserId( + @Bind("datasetId") Integer datasetId, @Bind("createUserId") Integer createUserId); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE dataset SET name = :datasetName, update_date = :updateDate, update_user_id = :updateUserId WHERE dataset_id = :datasetId """) - void updateDatasetNameWithUpdateUser(@Bind("datasetId") Integer datasetId, + void updateDatasetNameWithUpdateUser( + @Bind("datasetId") Integer datasetId, @Bind("datasetName") String datasetName, @Bind("updateDate") Timestamp updateDate, @Bind("updateUserId") Integer updateUserId); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE dataset SET update_date = :updateDate, update_user_id = :updateUserId WHERE dataset_id = :datasetId """) - void updateDatasetUpdateUser(@Bind("datasetId") Integer datasetId, + void updateDatasetUpdateUser( + @Bind("datasetId") Integer datasetId, @Bind("updateDate") Timestamp updateDate, @Bind("updateUserId") Integer updateUserId); @UseRowMapper(DatasetPropertyMapper.class) @SqlQuery( - " SELECT p.*, d.key FROM dataset_property p " + - " INNER JOIN dictionary d ON p.property_key = d.key_id " + - " WHERE p.dataset_id = :datasetId ") + " SELECT p.*, d.key FROM dataset_property p " + + " INNER JOIN dictionary d ON p.property_key = d.key_id " + + " WHERE p.dataset_id = :datasetId ") Set findDatasetPropertiesByDatasetId(@Bind("datasetId") Integer datasetId); @RegisterRowMapper(DictionaryMapper.class) @@ -528,40 +557,44 @@ void updateDatasetUpdateUser(@Bind("datasetId") Integer datasetId, Dataset getDatasetByName(@Bind("name") String name); @UseRowReducer(DatasetReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT distinct d.*, k.key, p.property_value, d.dac_id FROM dataset d LEFT JOIN dataset_property p ON p.dataset_id = d.dataset_id LEFT JOIN dictionary k ON k.key_id = p.property_key WHERE d.dac_id IN () """) - List findDatasetListByDacIds(@BindList(value = "dacIds", onEmpty = EmptyHandling.NULL_STRING) List dacIds); + List findDatasetListByDacIds( + @BindList(value = "dacIds", onEmpty = EmptyHandling.NULL_STRING) List dacIds); - @SqlQuery(""" + @SqlQuery( + """ SELECT distinct d.dataset_id FROM dataset d WHERE d.dac_id IN () """) - List findDatasetIdsByDacIds(@BindList(value = "dacIds", onEmpty = EmptyHandling.NULL_STRING) List dacIds); + List findDatasetIdsByDacIds( + @BindList(value = "dacIds", onEmpty = EmptyHandling.NULL_STRING) List dacIds); @SqlUpdate( - "UPDATE dataset " + - "SET dac_approval = :dacApproval, " + - "update_date = :updateDate, " + - "update_user_id = :updateUserId " + - "WHERE dataset_id = :datasetId" - ) + "UPDATE dataset " + + "SET dac_approval = :dacApproval, " + + "update_date = :updateDate, " + + "update_user_id = :updateUserId " + + "WHERE dataset_id = :datasetId") void updateDatasetApproval( @Bind("dacApproval") Boolean dacApproved, @Bind("updateDate") Instant updateDate, @Bind("updateUserId") Integer updateUserId, - @Bind("datasetId") Integer datasetId - ); + @Bind("datasetId") Integer datasetId); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE dataset SET indexed_date = :indexedDate WHERE dataset_id = :datasetId """) - void updateDatasetIndexedDate(@Bind("datasetId") Integer datasetId, @Bind("indexedDate") Instant indexedDate); + void updateDatasetIndexedDate( + @Bind("datasetId") Integer datasetId, @Bind("indexedDate") Instant indexedDate); @RegisterRowMapper(ApprovedDatasetMapper.class) @UseRowReducer(ApprovedDatasetReducer.class) @@ -596,5 +629,4 @@ AND dar.collection_id NOT IN ( WHERE data ->> 'closeoutSupplement' IS NOT NULL) """) List getApprovedDatasets(@Bind("userId") Integer userId); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/DraftDAO.java b/src/main/java/org/broadinstitute/consent/http/db/DraftDAO.java index 7242f69230..452afb46dc 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/DraftDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/DraftDAO.java @@ -27,14 +27,16 @@ @RegisterRowMapper(FileStorageObjectMapperWithFSOPrefix.class) public interface DraftDAO extends Transactional { - String DRAFT_SUMMARY = """ + String DRAFT_SUMMARY = + """ SELECT ds.name, ds.create_date, ds.uuid, ds.update_date, ds.draft_type FROM draft ds WHERE ds.create_user_id = :createdUserId ORDER BY ds.update_date DESC """; - String DRAFT_DETAILS = """ + String DRAFT_DETAILS = + """ SELECT ds.name, ds.create_date, ds.create_user_id, ds.json, ds.uuid, ds.update_date, ds.update_user_id, ds.draft_type, uu.user_id AS uu_user_id, uu.email AS uu_email, uu.display_name AS uu_display_name, @@ -42,8 +44,9 @@ public interface DraftDAO extends Transactional { cu.user_id AS cu_user_id, cu.email AS cu_email, cu.display_name AS cu_display_name, cu.create_date AS cu_create_date, cu.email_preference AS cu_email_preference, """ - + FileStorageObject.QUERY_FIELDS_WITH_FSO_PREFIX + " " + - """ + + FileStorageObject.QUERY_FIELDS_WITH_FSO_PREFIX + + " " + + """ FROM draft ds LEFT JOIN users uu on ds.update_user_id = uu.user_id LEFT JOIN users cu on ds.create_user_id = cu.user_id @@ -56,8 +59,7 @@ public interface DraftDAO extends Transactional { (name, create_date, create_user_id, update_date, update_user_id, json, uuid, draft_type) (SELECT :name, :createdDate, :createdUserId, :createdDate, :createdUserId, :json::jsonb, :uuid, :draftType) - """ - ) + """) @GetGeneratedKeys Integer insert( @Bind("name") String name, @@ -67,7 +69,8 @@ Integer insert( @Bind("uuid") UUID uuid, @Bind("draftType") String draftType); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE draft SET name = :name, update_date = :updateDate, @@ -84,7 +87,8 @@ void updateDraftByDraftUUID( @Bind("uuid") UUID uuid, @Bind("draftType") String draftType); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE draft SET update_date = :updateDate, @@ -98,23 +102,20 @@ void updateDraftByDraftUUID( @UseRowReducer(DraftReducer.class) @SqlQuery( - DRAFT_DETAILS + - """ + DRAFT_DETAILS + + """ WHERE ds.create_user_id = :createdUserId """) - Collection findDraftsByUserId( - @Bind("createdUserId") Integer createdUserId); + Collection findDraftsByUserId(@Bind("createdUserId") Integer createdUserId); @UseRowMapper(DraftSummaryMapper.class) - @SqlQuery( - DRAFT_SUMMARY) - Collection findDraftSummariesByUserId( - @Bind("createdUserId") Integer createdUserId); + @SqlQuery(DRAFT_SUMMARY) + Collection findDraftSummariesByUserId(@Bind("createdUserId") Integer createdUserId); @UseRowReducer(DraftReducer.class) @SqlQuery( - DRAFT_DETAILS + - """ + DRAFT_DETAILS + + """ WHERE uuid = :uuid """) DraftInterface findDraftById(@Bind("uuid") UUID uuid); @@ -123,7 +124,7 @@ Collection findDraftSummariesByUserId( """ DELETE from draft WHERE uuid IN () - """ - ) - void deleteDraftByUUIDList(@BindList(value = "uuid_list", onEmpty = EmptyHandling.NULL_STRING) List uuid); + """) + void deleteDraftByUUIDList( + @BindList(value = "uuid_list", onEmpty = EmptyHandling.NULL_STRING) List uuid); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/ElectionDAO.java b/src/main/java/org/broadinstitute/consent/http/db/ElectionDAO.java index b9f47ffc72..1659ebe0bf 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/ElectionDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/ElectionDAO.java @@ -20,30 +20,38 @@ @RegisterRowMapper(ElectionMapper.class) public interface ElectionDAO extends Transactional { - @SqlQuery(""" + @SqlQuery( + """ SELECT DISTINCT election_id FROM election WHERE reference_id IN () """) - List getElectionIdsByReferenceIds(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + List getElectionIdsByReferenceIds( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); - @SqlUpdate(""" - INSERT INTO election (election_type, status, create_date, reference_id, dataset_id) + @SqlUpdate( + """ + INSERT INTO election (election_type, status, create_date, reference_id, dataset_id) VALUES (:electionType, :status, :createDate,:referenceId, :datasetId) """) @GetGeneratedKeys - Integer insertElection(@Bind("electionType") String electionType, + Integer insertElection( + @Bind("electionType") String electionType, @Bind("status") String status, @Bind("createDate") Date createDate, @Bind("referenceId") String referenceId, @Bind("datasetId") Integer datasetId); - @SqlUpdate("UPDATE election SET status = :status, last_update = :lastUpdate WHERE election_id = :electionId ") - void updateElectionById(@Bind("electionId") Integer electionId, + @SqlUpdate( + "UPDATE election SET status = :status, last_update = :lastUpdate WHERE election_id = :electionId ") + void updateElectionById( + @Bind("electionId") Integer electionId, @Bind("status") String status, @Bind("lastUpdate") Date lastUpdate); - @SqlQuery(""" + @SqlQuery( + """ SELECT DISTINCT e.election_id, e.dataset_id, v.vote final_vote, e.status, e.create_date, e.reference_id, v.rationale final_rationale, v.create_date final_vote_date, @@ -61,7 +69,8 @@ WHEN LOWER(e.election_type) = 'dataset' THEN 'data_owner' Election findElectionWithFinalVoteById(@Bind("electionId") Integer electionId); @UseRowMapper(SimpleElectionMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT e.* FROM election e INNER JOIN data_access_request dar ON dar.reference_id = e.reference_id INNER JOIN users u ON u.user_id = dar.user_id @@ -69,7 +78,8 @@ WHEN LOWER(e.election_type) = 'dataset' THEN 'data_owner' WHERE e.election_id IN () """) List findElectionsWithCardHoldingUsersByElectionIds( - @BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) List electionIds); + @BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) + List electionIds); @UseRowMapper(SimpleElectionMapper.class) @SqlQuery("SELECT * FROM election WHERE reference_id = :referenceId") @@ -77,10 +87,13 @@ List findElectionsWithCardHoldingUsersByElectionIds( @UseRowMapper(SimpleElectionMapper.class) @SqlQuery("SELECT * FROM election WHERE reference_id in ()") - List findElectionsByReferenceIds(@BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + List findElectionsByReferenceIds( + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); @UseRowMapper(SimpleElectionMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM election e INNER JOIN vote v ON v.election_id = e.election_id WHERE LOWER(e.election_type) = :electionType @@ -88,11 +101,10 @@ AND v.vote_id IN () """) List findElectionsByVoteIdsAndType( @BindList(value = "voteIds", onEmpty = EmptyHandling.NULL_STRING) List voteIds, - @Bind("electionType") String electionType - ); + @Bind("electionType") String electionType); - - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM ( SELECT e.*, v.vote final_vote, CASE @@ -119,9 +131,11 @@ WHERE e.reference_id IN () """) @UseRowMapper(ElectionMapper.class) List findLastElectionsByReferenceIds( - @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); - @SqlQuery(""" + @SqlQuery( + """ SELECT DISTINCT e.* FROM election e WHERE LOWER(e.status) = 'open' @@ -129,9 +143,11 @@ AND e.reference_id IN () """) @UseRowMapper(ElectionMapper.class) List findOpenElectionsByReferenceIds( - @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); - @SqlQuery(""" + @SqlQuery( + """ SELECT distinct * FROM election e INNER JOIN @@ -145,9 +161,12 @@ AND LOWER(e.election_type) = LOWER(:type) """) @UseRowMapper(SimpleElectionMapper.class) List findLastElectionsByReferenceIdsAndType( - @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds, @Bind("type") String type); + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds, + @Bind("type") String type); - @SqlQuery(""" + @SqlQuery( + """ SELECT e.* FROM election e INNER JOIN (SELECT reference_id, dataset_id, MAX(create_date) max_date @@ -162,39 +181,49 @@ WHERE LOWER(e.election_type) = lower(:type) AND e.dataset_id = :datasetId """) @UseRowMapper(SimpleElectionMapper.class) - Election findLastElectionByReferenceIdDatasetIdAndType(@Bind("referenceId") String referenceId, - @Bind("datasetId") Integer datasetId, @Bind("type") String type); + Election findLastElectionByReferenceIdDatasetIdAndType( + @Bind("referenceId") String referenceId, + @Bind("datasetId") Integer datasetId, + @Bind("type") String type); - @SqlQuery(""" + @SqlQuery( + """ SELECT e.* FROM election e WHERE e.reference_id = :referenceId AND e.dataset_id = :datasetId """) @UseRowMapper(SimpleElectionMapper.class) - List findElectionsByReferenceIdAndDatasetId(@Bind("referenceId") String referenceId, - @Bind("datasetId") Integer datasetId); + List findElectionsByReferenceIdAndDatasetId( + @Bind("referenceId") String referenceId, @Bind("datasetId") Integer datasetId); @UseRowMapper(SimpleElectionMapper.class) @SqlQuery("SELECT DISTINCT * FROM election e WHERE e.election_id IN ()") - List findElectionsByIds(@BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) List electionIds); + List findElectionsByIds( + @BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) + List electionIds); @UseRowMapper(SimpleElectionMapper.class) @SqlQuery("SELECT * FROM election e WHERE e.election_id = :electionId") Election findElectionById(@Bind("electionId") Integer electionId); - @SqlUpdate("UPDATE election SET status = :status, last_update = :lastUpdate, final_access_vote = :finalAccessVote WHERE election_id = :electionId ") - void updateElectionById(@Bind("electionId") Integer electionId, + @SqlUpdate( + "UPDATE election SET status = :status, last_update = :lastUpdate, final_access_vote = :finalAccessVote WHERE election_id = :electionId ") + void updateElectionById( + @Bind("electionId") Integer electionId, @Bind("status") String status, @Bind("lastUpdate") Date lastUpdate, @Bind("finalAccessVote") Boolean finalAccessVote); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE election SET archived = true, last_update = :lastUpdate WHERE election_id IN () """) - void archiveElectionByIds(@BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) List electionIds, + void archiveElectionByIds( + @BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) + List electionIds, @Bind("lastUpdate") Date lastUpdate); /** @@ -205,7 +234,8 @@ void archiveElectionByIds(@BindList(value = "electionIds", onEmpty = EmptyHandli * @return Dac for this election */ @UseRowMapper(DacMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT d.* FROM dac d INNER JOIN dataset ds on d.dac_id = ds.dac_id INNER JOIN election e on ds.dataset_id = e.dataset_id @@ -220,11 +250,11 @@ void archiveElectionByIds(@BindList(value = "electionIds", onEmpty = EmptyHandli * @return List of elections associated to the Dac */ @UseRowMapper(SimpleElectionMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT e1.* FROM election e1 INNER JOIN dataset ds1 on ds1.dac_id = :dacId AND ds1.dataset_id = e1.dataset_id WHERE LOWER(e1.status) = 'open' """) List findOpenElectionsByDacId(@Bind("dacId") Integer dacId); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/FileStorageObjectDAO.java b/src/main/java/org/broadinstitute/consent/http/db/FileStorageObjectDAO.java index 9dc68b0d3e..1db868a611 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/FileStorageObjectDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/FileStorageObjectDAO.java @@ -24,8 +24,7 @@ public interface FileStorageObjectDAO extends Transactional { (:fileName, :category, :gcsFileUri, :mediaType, :entityId, :createUserId, :createDate, false) - """ - ) + """) @GetGeneratedKeys Integer insertNewFile( @Bind("fileName") String fileName, @@ -34,8 +33,7 @@ Integer insertNewFile( @Bind("mediaType") String mediaType, @Bind("entityId") String entityId, @Bind("createUserId") Integer createUserId, - @Bind("createDate") Instant createDate - ); + @Bind("createDate") Instant createDate); @SqlUpdate( """ @@ -44,13 +42,12 @@ Integer insertNewFile( delete_user_id=:deleteUserId, delete_date=:deleteDate WHERE file_storage_object_id = :fileStorageObjectId - """ - ) - void deleteFileById(@Bind("fileStorageObjectId") Integer fileStorageObjectId, + """) + void deleteFileById( + @Bind("fileStorageObjectId") Integer fileStorageObjectId, @Bind("deleteUserId") Integer deleteUserId, @Bind("deleteDate") Instant deleteDate); - @SqlUpdate( """ UPDATE file_storage_object @@ -59,8 +56,7 @@ void deleteFileById(@Bind("fileStorageObjectId") Integer fileStorageObjectId, update_user_id=:updateUserId, update_date=:updateDate WHERE file_storage_object_id = :fileStorageObjectId - """ - ) + """) void updateFileById( @Bind("fileStorageObjectId") Integer fileStorageObjectId, @Bind("gcsFileUri") String gcsFileUri, @@ -75,20 +71,18 @@ void updateFileById( delete_user_id=:deleteUserId, delete_date=:deleteDate WHERE entity_id = :entityId - """ - ) - void deleteFilesByEntityId(@Bind("entityId") String entityId, + """) + void deleteFilesByEntityId( + @Bind("entityId") String entityId, @Bind("deleteUserId") Integer deleteUserId, @Bind("deleteDate") Instant deleteDate); - @SqlQuery( """ SELECT * FROM file_storage_object WHERE file_storage_object_id = :fileStorageObjectId - """ - ) + """) FileStorageObject findFileById(@Bind("fileStorageObjectId") Integer fileStorageObjectId); @SqlQuery( @@ -97,8 +91,7 @@ void deleteFilesByEntityId(@Bind("entityId") String entityId, FROM file_storage_object WHERE entity_id = :entityId AND deleted != true - """ - ) + """) List findFilesByEntityId(@Bind("entityId") String entityId); @SqlQuery( @@ -108,11 +101,11 @@ void deleteFilesByEntityId(@Bind("entityId") String entityId, WHERE entity_id = :entityId AND category = :category AND deleted != true - """ - ) - List findFilesByEntityIdAndCategory(@Bind("entityId") String entityId, - @Bind("category") String category); + """) + List findFilesByEntityIdAndCategory( + @Bind("entityId") String entityId, @Bind("category") String category); - @SqlUpdate("DELETE FROM file_storage_object WHERE create_user_id = :userId OR update_user_id = :userId OR delete_user_id = :userId") + @SqlUpdate( + "DELETE FROM file_storage_object WHERE create_user_id = :userId OR update_user_id = :userId OR delete_user_id = :userId") void deleteAllUserFiles(@Bind("userId") Integer userId); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/InstitutionDAO.java b/src/main/java/org/broadinstitute/consent/http/db/InstitutionDAO.java index 12f6e7b0b6..cd85c21bee 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/InstitutionDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/InstitutionDAO.java @@ -23,7 +23,8 @@ @RegisterRowMapper(InstitutionMapper.class) public interface InstitutionDAO extends Transactional { - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO institution (institution_name, it_director_name, it_director_email, institution_url, duns_number, org_chart_url, verification_url, verification_filename, @@ -33,7 +34,8 @@ public interface InstitutionDAO extends Transactional { :organizationType, :createUser, :createDate) """) @GetGeneratedKeys - Integer insertInstitution(@Bind("institutionName") String institutionName, + Integer insertInstitution( + @Bind("institutionName") String institutionName, @Bind("itDirectorName") String itDirectorName, @Bind("itDirectorEmail") String itDirectorEmail, @Bind("institutionUrl") String institutionUrl, @@ -54,43 +56,55 @@ Integer insertInstitution(@Bind("institutionName") String institutionName, * @return The inserted Institution object * @throws SQLException The exception thrown if the insert fails. */ - default Institution insertFullInstitution(Institution institution, Integer userId) throws SQLException { + default Institution insertFullInstitution(Institution institution, Integer userId) + throws SQLException { Date now = new Date(); AtomicReference institutionId = new AtomicReference<>(); - getHandle().useTransaction(handle -> { - handle.getConnection().setAutoCommit(false); - Integer id = insertInstitution( - institution.getName(), - institution.getItDirectorName(), - institution.getItDirectorEmail(), - institution.getInstitutionUrl(), - institution.getDunsNumber(), - institution.getOrgChartUrl(), - institution.getVerificationUrl(), - institution.getVerificationFilename(), - (Objects.nonNull(institution.getOrganizationType()) ? institution.getOrganizationType() - .getValue() : null), - userId, - now); - if (institution.getDomains() != null) { - String insertDomainQuery = """ + getHandle() + .useTransaction( + handle -> { + handle.getConnection().setAutoCommit(false); + Integer id = + insertInstitution( + institution.getName(), + institution.getItDirectorName(), + institution.getItDirectorEmail(), + institution.getInstitutionUrl(), + institution.getDunsNumber(), + institution.getOrgChartUrl(), + institution.getVerificationUrl(), + institution.getVerificationFilename(), + (Objects.nonNull(institution.getOrganizationType()) + ? institution.getOrganizationType().getValue() + : null), + userId, + now); + if (institution.getDomains() != null) { + String insertDomainQuery = + """ INSERT INTO institution_domains (institution_id, domain) VALUES (:institutionId, :domain) """; - institution.getDomains().forEach(domain -> handle.createUpdate(insertDomainQuery) - .bind("institutionId", id) - .bind("domain", domain) - .execute()); - } - handle.commit(); - institutionId.set(id); - }); + institution + .getDomains() + .forEach( + domain -> + handle + .createUpdate(insertDomainQuery) + .bind("institutionId", id) + .bind("domain", domain) + .execute()); + } + handle.commit(); + institutionId.set(id); + }); if (institutionId.get() != null) { return findInstitutionById(institutionId.get()); } throw new SQLException("Failed to insert institution"); } - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE institution SET institution_name = :institutionName, @@ -106,7 +120,8 @@ INSERT INTO institution_domains (institution_id, domain) VALUES (:institutionId, update_date = :updateDate WHERE institution_id = :institutionId """) - void updateInstitutionById(@Bind("institutionId") Integer institutionId, + void updateInstitutionById( + @Bind("institutionId") Integer institutionId, @Bind("institutionName") String institutionName, @Bind("itDirectorName") String itDirectorName, @Bind("itDirectorEmail") String itDirectorEmail, @@ -131,48 +146,60 @@ default Institution updateFullInstitution(Institution institution, Integer userI throws SQLException { Date now = new Date(); Integer institutionId = institution.getId(); - getHandle().useTransaction(handle -> { - handle.getConnection().setAutoCommit(false); - updateInstitutionById( - institution.getId(), - institution.getName(), - institution.getItDirectorName(), - institution.getItDirectorEmail(), - institution.getInstitutionUrl(), - institution.getDunsNumber(), - institution.getOrgChartUrl(), - institution.getVerificationUrl(), - institution.getVerificationFilename(), - (Objects.nonNull(institution.getOrganizationType()) ? institution.getOrganizationType() - .getValue() : null), - userId, - now); - handle.createUpdate("DELETE FROM institution_domains WHERE institution_id = :institutionId") - .bind("institutionId", institutionId) - .execute(); - if (institution.getDomains() != null) { - String insertDomainQuery = """ + getHandle() + .useTransaction( + handle -> { + handle.getConnection().setAutoCommit(false); + updateInstitutionById( + institution.getId(), + institution.getName(), + institution.getItDirectorName(), + institution.getItDirectorEmail(), + institution.getInstitutionUrl(), + institution.getDunsNumber(), + institution.getOrgChartUrl(), + institution.getVerificationUrl(), + institution.getVerificationFilename(), + (Objects.nonNull(institution.getOrganizationType()) + ? institution.getOrganizationType().getValue() + : null), + userId, + now); + handle + .createUpdate( + "DELETE FROM institution_domains WHERE institution_id = :institutionId") + .bind("institutionId", institutionId) + .execute(); + if (institution.getDomains() != null) { + String insertDomainQuery = + """ INSERT INTO institution_domains (institution_id, domain) VALUES (:institutionId, :domain) """; - institution.getDomains().forEach(domain -> handle.createUpdate(insertDomainQuery) - .bind("institutionId", institutionId) - .bind("domain", domain) - .execute()); - } - handle.commit(); - }); + institution + .getDomains() + .forEach( + domain -> + handle + .createUpdate(insertDomainQuery) + .bind("institutionId", institutionId) + .bind("domain", domain) + .execute()); + } + handle.commit(); + }); return findInstitutionById(institutionId); } @SqlUpdate( - """ + """ WITH domain_deletes AS (DELETE FROM institution_domains d WHERE d.institution_id = :institutionId) DELETE FROM institution WHERE institution_id = :institutionId """) void deleteInstitutionById(@Bind("institutionId") Integer institutionId); @UseRowReducer(InstitutionReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT i.*, d.domain FROM institution i LEFT JOIN institution_domains d on d.institution_id = i.institution_id @@ -181,7 +208,8 @@ WITH domain_deletes AS (DELETE FROM institution_domains d WHERE d.institution_id Institution findInstitutionById(@Bind("institutionId") Integer institutionId); @UseRowReducer(InstitutionReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT i.*, d.domain FROM institution i LEFT JOIN institution_domains d on d.institution_id = i.institution_id @@ -192,7 +220,8 @@ WHERE LOWER(TRIM(i.institution_name)) = LOWER(TRIM(:name)) @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = SimplifiedUser.class, prefix = "so") @UseRowReducer(InstitutionWithUsersReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT i.*, d.domain, u.user_id AS u_user_id, u.email AS u_email, @@ -222,7 +251,8 @@ ORDER BY LOWER(i.institution_name) @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = SimplifiedUser.class, prefix = "so") @UseRowReducer(InstitutionWithUsersReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT i.*, d.domain, u.user_id AS u_user_id, @@ -252,25 +282,30 @@ ORDER BY LOWER(i.institution_name) Institution findInstitutionWithSOById(@Bind("institutionId") Integer institutionId); default void deleteAllInstitutionsByUser(@Bind("userId") Integer userId) throws SQLException { - final String domainDeleteQuery = """ + final String domainDeleteQuery = + """ DELETE FROM institution_domains WHERE institution_id IN (SELECT institution_id FROM institution WHERE create_user = :userId OR update_user = :userId) """; - final String institutionDeleteQuery = """ + final String institutionDeleteQuery = + """ DELETE FROM institution WHERE create_user = :userId OR update_user = :userId """; - getHandle().useTransaction(handle -> { - handle.getConnection().setAutoCommit(false); - handle.createUpdate(domainDeleteQuery).bind("userId", userId).execute(); - handle.createUpdate(institutionDeleteQuery).bind("userId", userId).execute(); - handle.commit(); - }); + getHandle() + .useTransaction( + handle -> { + handle.getConnection().setAutoCommit(false); + handle.createUpdate(domainDeleteQuery).bind("userId", userId).execute(); + handle.createUpdate(institutionDeleteQuery).bind("userId", userId).execute(); + handle.commit(); + }); } @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = SimplifiedUser.class, prefix = "so") @UseRowReducer(InstitutionWithUsersReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT i.*, d.domain, u.user_id AS u_user_id, @@ -299,7 +334,8 @@ WHERE LOWER(d.domain) = LOWER(:domain) """) Institution findInstitutionByDomain(@Bind("domain") String domain); - @SqlQuery(""" + @SqlQuery( + """ SELECT distinct i.institution_id FROM institution i INNER JOIN institution_domains d ON d.institution_id = i.institution_id diff --git a/src/main/java/org/broadinstitute/consent/http/db/LibraryCardDAO.java b/src/main/java/org/broadinstitute/consent/http/db/LibraryCardDAO.java index 057a215d3d..2de8b489c9 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/LibraryCardDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/LibraryCardDAO.java @@ -18,35 +18,40 @@ public interface LibraryCardDAO extends Transactional { - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO library_card (user_id, user_name, user_email, create_user_id, create_date) VALUES (:userId, :userName, :userEmail, :createUserId, :createDate) """) @GetGeneratedKeys - Integer insertLibraryCard(@Bind("userId") Integer userId, + Integer insertLibraryCard( + @Bind("userId") Integer userId, @Bind("userName") String userName, @Bind("userEmail") String userEmail, @Bind("createUserId") Integer createUserId, @Bind("createDate") Date createDate); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE library_card SET - id = :libraryCardId, - user_id = :userId, - user_name = :userName, - user_email = :userEmail, - update_user_id = :updateUserId, - update_date = :updateDate + id = :libraryCardId, + user_id = :userId, + user_name = :userName, + user_email = :userEmail, + update_user_id = :updateUserId, + update_date = :updateDate WHERE id = :libraryCardId """) - void updateLibraryCardById(@Bind("libraryCardId") Integer libraryCardId, + void updateLibraryCardById( + @Bind("libraryCardId") Integer libraryCardId, @Bind("userId") Integer userId, @Bind("userName") String userName, @Bind("userEmail") String userEmail, @Bind("updateUserId") Integer updateUserId, @Bind("updateDate") Date updateDate); - @SqlUpdate(""" + @SqlUpdate( + """ WITH daa_deletes AS (DELETE FROM lc_daa lc_daa WHERE lc_daa.lc_id = :libraryCardId) DELETE FROM library_card lc WHERE lc.id = :libraryCardId """) @@ -54,7 +59,8 @@ WITH daa_deletes AS (DELETE FROM lc_daa lc_daa WHERE lc_daa.lc_id = :libraryCard @RegisterBeanMapper(value = LibraryCard.class) @UseRowReducer(LibraryCardReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT lc.*, ld.daa_id FROM library_card AS lc @@ -66,7 +72,8 @@ WITH daa_deletes AS (DELETE FROM lc_daa lc_daa WHERE lc_daa.lc_id = :libraryCard @RegisterBeanMapper(value = LibraryCard.class) @RegisterBeanMapper(value = DataAccessAgreement.class, prefix = "daa") @UseRowReducer(LibraryCardWithDaaReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT lc.*, ld.daa_id, daa.daa_id as daa_daa_id, @@ -84,7 +91,8 @@ WITH daa_deletes AS (DELETE FROM lc_daa lc_daa WHERE lc_daa.lc_id = :libraryCard @RegisterBeanMapper(value = LibraryCard.class) @UseRowReducer(LibraryCardReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT lc.*, ld.daa_id FROM library_card AS lc @@ -95,7 +103,8 @@ WITH daa_deletes AS (DELETE FROM lc_daa lc_daa WHERE lc_daa.lc_id = :libraryCard @RegisterBeanMapper(value = LibraryCard.class) @UseRowReducer(LibraryCardReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT library_card.*, ld.daa_id FROM library_card LEFT JOIN lc_daa ld ON library_card.id = ld.lc_id @@ -105,7 +114,8 @@ WITH daa_deletes AS (DELETE FROM lc_daa lc_daa WHERE lc_daa.lc_id = :libraryCard @RegisterBeanMapper(value = LibraryCard.class) @UseRowReducer(LibraryCardReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT lc.*, ld.daa_id FROM library_card AS lc @@ -115,21 +125,23 @@ WITH daa_deletes AS (DELETE FROM lc_daa lc_daa WHERE lc_daa.lc_id = :libraryCard @RegisterBeanMapper(value = LibraryCard.class) @UseRowReducer(LibraryCardReducer.class) - @SqlQuery("SELECT * FROM library_card " + - "WHERE user_email = :email") + @SqlQuery("SELECT * FROM library_card " + "WHERE user_email = :email") LibraryCard findLibraryCardByUserEmail(@Bind("email") String email); - @SqlUpdate("DELETE FROM library_card WHERE user_id = :userId OR create_user_id = :userId OR update_user_id = :userId") + @SqlUpdate( + "DELETE FROM library_card WHERE user_id = :userId OR create_user_id = :userId OR update_user_id = :userId") void deleteAllLibraryCardsByUser(@Bind("userId") Integer userId); - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO lc_daa (lc_id, daa_id) VALUES (:lcId, :daaId) ON CONFLICT DO NOTHING """) void createLibraryCardDaaRelation(@Bind("lcId") Integer lcId, @Bind("daaId") Integer daaId); - @SqlUpdate(""" + @SqlUpdate( + """ DELETE FROM lc_daa WHERE lc_id = :lcId AND daa_id = :daaId @@ -144,7 +156,8 @@ INSERT INTO lc_daa (lc_id, daa_id) */ @RegisterBeanMapper(value = LibraryCard.class) @UseRowReducer(LibraryCardReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM library_card WHERE LOWER(user_email) = ANY(ARRAY(SELECT LOWER(UNNEST(ARRAY[])))) @@ -160,12 +173,12 @@ List findByUserEmails( */ @RegisterBeanMapper(value = LibraryCard.class) @UseRowReducer(LibraryCardReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM library_card WHERE user_id in () """) List findLibraryCardsByUserIds( @BindList(value = "userIds", onEmpty = EmptyHandling.NULL_STRING) List userIds); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/MailMessageDAO.java b/src/main/java/org/broadinstitute/consent/http/db/MailMessageDAO.java index 43da5eac1b..36af2eef8a 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/MailMessageDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/MailMessageDAO.java @@ -16,12 +16,13 @@ @RegisterRowMapper(MailMessageMapper.class) public interface MailMessageDAO extends Transactional { - @SqlUpdate("INSERT INTO email_entity " + - "(entity_reference_id, vote_id, user_id, email_type, date_sent, email_text, sendgrid_response, sendgrid_status, create_date) VALUES " - + - "(:entityReferenceId, :voteId, :userId, :emailType, :dateSent, :emailText, :sendGridResponse, :sendGridStatus, :createDate)") + @SqlUpdate( + "INSERT INTO email_entity " + + "(entity_reference_id, vote_id, user_id, email_type, date_sent, email_text, sendgrid_response, sendgrid_status, create_date) VALUES " + + "(:entityReferenceId, :voteId, :userId, :emailType, :dateSent, :emailText, :sendGridResponse, :sendGridStatus, :createDate)") @GetGeneratedKeys - Integer insert(@Nullable @Bind("entityReferenceId") String entityReferenceId, + Integer insert( + @Nullable @Bind("entityReferenceId") String entityReferenceId, @Nullable @Bind("voteId") Integer voteId, @Bind("userId") Integer userId, @Bind("emailType") Integer emailType, @@ -31,37 +32,46 @@ Integer insert(@Nullable @Bind("entityReferenceId") String entityReferenceId, @Nullable @Bind("sendGridStatus") Integer sendGridStatus, @Bind("createDate") Instant createDate); - @SqlQuery(""" + @SqlQuery( + """ SELECT entity_reference_id, email_entity_id, vote_id, user_id, email_type, date_sent, email_text, sendgrid_response, sendgrid_status, create_date FROM email_entity e WHERE email_type = :emailType ORDER BY create_date DESC OFFSET :offset LIMIT :limit """) - List fetchMessagesByType(@Bind("emailType") Integer emailType, - @Bind("limit") Integer limit, @Bind("offset") Integer offset); + List fetchMessagesByType( + @Bind("emailType") Integer emailType, + @Bind("limit") Integer limit, + @Bind("offset") Integer offset); - @SqlQuery(""" + @SqlQuery( + """ SELECT entity_reference_id, email_entity_id, vote_id, user_id, email_type, date_sent, email_text, sendgrid_response, sendgrid_status, create_date FROM email_entity e WHERE user_id = :userId ORDER BY create_date DESC OFFSET :offset LIMIT :limit """) - List fetchMessagesByUserId(@Bind("userId") Integer userId, - @Bind("limit") Integer limit, @Bind("offset") Integer offset); + List fetchMessagesByUserId( + @Bind("userId") Integer userId, @Bind("limit") Integer limit, @Bind("offset") Integer offset); - @SqlQuery(""" + @SqlQuery( + """ SELECT entity_reference_id, email_entity_id, vote_id, user_id, email_type, date_sent, email_text, sendgrid_response, sendgrid_status, create_date FROM email_entity e WHERE create_date BETWEEN SYMMETRIC :start AND :end ORDER BY create_date DESC OFFSET :offset LIMIT :limit """) - List fetchMessagesByCreateDate(@Bind("start") Date start, @Bind("end") Date end, - @Bind("limit") Integer limit, @Bind("offset") Integer offset); + List fetchMessagesByCreateDate( + @Bind("start") Date start, + @Bind("end") Date end, + @Bind("limit") Integer limit, + @Bind("offset") Integer offset); - @SqlQuery(""" + @SqlQuery( + """ SELECT entity_reference_id, email_entity_id, vote_id, user_id, email_type, date_sent, email_text, sendgrid_response, sendgrid_status, create_date FROM email_entity e WHERE email_entity_id = :emailId """) diff --git a/src/main/java/org/broadinstitute/consent/http/db/MatchDAO.java b/src/main/java/org/broadinstitute/consent/http/db/MatchDAO.java index f2ef02403a..d8d3171d48 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/MatchDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/MatchDAO.java @@ -19,7 +19,8 @@ public interface MatchDAO extends Transactional { @UseRowReducer(MatchReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT m.*, r.* FROM match_entity m LEFT JOIN match_rationale r on r.match_entity_id = m.match_id @@ -28,7 +29,8 @@ public interface MatchDAO extends Transactional { List findMatchesByPurposeId(@Bind("purposeId") String purposeId); @UseRowReducer(MatchReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT m.*, r.* FROM match_entity m LEFT JOIN match_rationale r on r.match_entity_id = m.match_id @@ -37,7 +39,8 @@ public interface MatchDAO extends Transactional { Match findMatchById(@Bind("id") Integer id); @UseRowReducer(MatchReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT match_entity.*, r.* FROM match_entity LEFT JOIN match_rationale r on r.match_entity_id = match_entity.match_id INNER JOIN ( @@ -50,14 +53,16 @@ WHERE match_entity.purpose IN () AND e.election_id = latest List findMatchesForLatestDataAccessElectionsByPurposeIds( @BindList(value = "purposeIds", onEmpty = EmptyHandling.NULL_STRING) List purposeIds); - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO match_entity (consent, purpose, match_entity, failed, create_date, algorithm_version, abstain) VALUES (:consentId, :purposeId, :match, :failed, :createDate, :algorithmVersion, :abstain) """) @GetGeneratedKeys - Integer insertMatch(@Bind("consentId") String consentId, + Integer insertMatch( + @Bind("consentId") String consentId, @Bind("purposeId") String purposeId, @Bind("match") Boolean match, @Bind("failed") Boolean failed, @@ -65,15 +70,19 @@ Integer insertMatch(@Bind("consentId") String consentId, @Bind("algorithmVersion") String algorithmVersion, @Bind("abstain") Boolean abstain); - @SqlUpdate("INSERT INTO match_rationale (match_entity_id, rationale) VALUES (:matchId, :rationale) ") + @SqlUpdate( + "INSERT INTO match_rationale (match_entity_id, rationale) VALUES (:matchId, :rationale) ") void insertRationale(@Bind("matchId") Integer matchId, @Bind("rationale") String rationale); @SqlUpdate("DELETE FROM match_entity WHERE purpose = :purposeId") void deleteMatchesByPurposeId(@Bind("purposeId") String purposeId); - @SqlUpdate("DELETE FROM match_rationale WHERE match_entity_id in (SELECT match_id FROM match_entity WHERE purpose IN ()) ") - void deleteRationalesByPurposeIds(@BindList(value = "purposeIds", onEmpty = EmptyHandling.NULL_STRING) List purposeIds); + @SqlUpdate( + "DELETE FROM match_rationale WHERE match_entity_id in (SELECT match_id FROM match_entity WHERE purpose IN ()) ") + void deleteRationalesByPurposeIds( + @BindList(value = "purposeIds", onEmpty = EmptyHandling.NULL_STRING) List purposeIds); - @SqlQuery("SELECT COUNT(*) FROM match_entity WHERE match_entity = :matchEntity AND failed = 'FALSE' ") + @SqlQuery( + "SELECT COUNT(*) FROM match_entity WHERE match_entity = :matchEntity AND failed = 'FALSE' ") Integer countMatchesByResult(@Bind("matchEntity") Boolean matchEntity); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/OidcAuthorityDAO.java b/src/main/java/org/broadinstitute/consent/http/db/OidcAuthorityDAO.java index bccd193162..3224259ff6 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/OidcAuthorityDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/OidcAuthorityDAO.java @@ -36,21 +36,27 @@ public OidcAuthorityConfiguration getOidcAuthorityConfiguration() { } @VisibleForTesting - protected void setOidcAuthorityConfiguration(OidcAuthorityConfiguration oidcAuthorityConfiguration) { + protected void setOidcAuthorityConfiguration( + OidcAuthorityConfiguration oidcAuthorityConfiguration) { this.oidcAuthorityConfiguration = oidcAuthorityConfiguration; } - public String oauthTokenPost(MultivaluedMap formParameters, MultivaluedMap queryParameters) { + public String oauthTokenPost( + MultivaluedMap formParameters, + MultivaluedMap queryParameters) { try { var uriBuilder = UriBuilder.fromUri(getOidcAuthorityConfiguration().token_endpoint()); - queryParameters.forEach((key, values) -> values.forEach(value -> uriBuilder.queryParam(key, value))); + queryParameters.forEach( + (key, values) -> values.forEach(value -> uriBuilder.queryParam(key, value))); GenericUrl genericUrl = new GenericUrl(uriBuilder.build()); - HttpRequest request = clientUtil.buildUnAuthedPostRequest(genericUrl, new UrlEncodedContent(formParameters)); + HttpRequest request = + clientUtil.buildUnAuthedPostRequest(genericUrl, new UrlEncodedContent(formParameters)); HttpResponse response = clientUtil.handleHttpRequest(request); if (!response.isSuccessStatusCode()) { - String message = String.format( - "Error getting OIDC token from authority %s, response code %d, response body %s", - genericUrl, response.getStatusCode(), response.parseAsString()); + String message = + String.format( + "Error getting OIDC token from authority %s, response code %d, response body %s", + genericUrl, response.getStatusCode(), response.parseAsString()); var exception = new ServerErrorException(message, Response.Status.INTERNAL_SERVER_ERROR); logException(exception); throw exception; @@ -64,15 +70,19 @@ public String oauthTokenPost(MultivaluedMap formParameters, Mult private OidcAuthorityConfiguration loadOidcAuthorityConfiguration() { try { - URI oidcMetadataUri = UriBuilder.fromUri(configuration.getAuthorityEndpoint()).path(OIDC_METADATA_URL_SUFFIX).build(); + URI oidcMetadataUri = + UriBuilder.fromUri(configuration.getAuthorityEndpoint()) + .path(OIDC_METADATA_URL_SUFFIX) + .build(); GenericUrl genericUrl = new GenericUrl(oidcMetadataUri); HttpRequest request = clientUtil.buildUnAuthedGetRequest(genericUrl); HttpResponse response = clientUtil.handleHttpRequest(request); String body = response.parseAsString(); if (!response.isSuccessStatusCode()) { - String message = String.format( - "Error getting OIDC configuration from authority %s, response code %d, response body %s", - genericUrl, response.getStatusCode(), body); + String message = + String.format( + "Error getting OIDC configuration from authority %s, response code %d, response body %s", + genericUrl, response.getStatusCode(), body); var exception = new ServerErrorException(message, Response.Status.INTERNAL_SERVER_ERROR); logException(exception); throw exception; diff --git a/src/main/java/org/broadinstitute/consent/http/db/SamDAO.java b/src/main/java/org/broadinstitute/consent/http/db/SamDAO.java index b0a16b9910..db66705fda 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/SamDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/SamDAO.java @@ -38,8 +38,8 @@ public class SamDAO implements ConsentLogger { - private final ExecutorService executorService = new ThreadUtils().getExecutorService( - SamDAO.class); + private final ExecutorService executorService = + new ThreadUtils().getExecutorService(SamDAO.class); private final HttpClientUtil clientUtil; private final ServicesConfiguration configuration; private final Integer connectTimeoutMilliseconds; @@ -59,12 +59,12 @@ public List getResourceTypes(DuosUser authUser) throws Exception { HttpRequest request = clientUtil.buildGetRequest(genericUrl, authUser); HttpResponse response = executeRequest(request); if (!response.isSuccessStatusCode()) { - logException("Error getting resource types from Sam: " + response.getStatusMessage(), + logException( + "Error getting resource types from Sam: " + response.getStatusMessage(), new ServerErrorException(response.getStatusMessage(), response.getStatusCode())); } String body = response.parseAsString(); - Type resourceTypesListType = new TypeToken>() { - }.getType(); + Type resourceTypesListType = new TypeToken>() {}.getType(); return new Gson().fromJson(body, resourceTypesListType); } @@ -109,8 +109,9 @@ public UserStatus postRegistrationInfo(DuosUser duosUser) throws Exception { } public static String getErrorMessage(DuosUser duosUser, String body) { - var errorMsg = String.format("Error posting user registration information. Email: %s.", - duosUser.getEmail()); + var errorMsg = + String.format( + "Error posting user registration information. Email: %s.", duosUser.getEmail()); if (body == null || body.isEmpty()) { return errorMsg; } @@ -123,14 +124,14 @@ public static String getErrorMessage(DuosUser duosUser, String body) { duosUser.getEmail()); } return String.format(errorMsg + " %s.", message); - } catch (JsonSyntaxException e) { // If the body is not a valid JSON + } catch (JsonSyntaxException e) { // If the body is not a valid JSON return String.format(errorMsg + " %s.", body); } } public void asyncPostRegistrationInfo(DuosUser duosUser) { - ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator( - executorService); + ListeningExecutorService listeningExecutorService = + MoreExecutors.listeningDecorator(executorService); ListenableFuture userStatusFuture = listeningExecutorService.submit(() -> postRegistrationInfo(duosUser)); Futures.addCallback( @@ -143,8 +144,11 @@ public void onSuccess(@Nullable UserStatus userStatus) { @Override public void onFailure(@NonNull Throwable throwable) { - logWarn("Async Post Registration Failure for user: " + duosUser.getEmail() + "; " - + throwable.getMessage()); + logWarn( + "Async Post Registration Failure for user: " + + duosUser.getEmail() + + "; " + + throwable.getMessage()); } }, listeningExecutorService); @@ -156,7 +160,8 @@ public String getToSText() throws Exception { request.getHeaders().setAccept(MediaType.TEXT_PLAIN); HttpResponse response = executeRequest(request); if (!response.isSuccessStatusCode()) { - logException("Error getting Terms of Service text from Sam: " + response.getStatusMessage(), + logException( + "Error getting Terms of Service text from Sam: " + response.getStatusMessage(), new ServerErrorException(response.getStatusMessage(), response.getStatusCode())); } return response.parseAsString(); @@ -167,7 +172,9 @@ public TosResponse getTosResponse(DuosUser duosUser) throws Exception { HttpRequest request = clientUtil.buildGetRequest(genericUrl, duosUser); HttpResponse response = executeRequest(request); if (!response.isSuccessStatusCode()) { - logException(String.format("Error getting Terms of Service: %s for user %s", + logException( + String.format( + "Error getting Terms of Service: %s for user %s", response.getStatusMessage(), duosUser.getEmail()), new ServerErrorException(response.getStatusMessage(), response.getStatusCode())); } @@ -180,7 +187,9 @@ public int acceptTosStatus(DuosUser duosUser) throws Exception { HttpRequest request = clientUtil.buildPutRequest(genericUrl, new EmptyContent(), duosUser); HttpResponse response = executeRequest(request); if (!response.isSuccessStatusCode()) { - logException(String.format("Error accepting Terms of Service: %s for user %s", + logException( + String.format( + "Error accepting Terms of Service: %s for user %s", response.getStatusMessage(), duosUser.getEmail()), new ServerErrorException(response.getStatusMessage(), response.getStatusCode())); } @@ -193,7 +202,8 @@ public int rejectTosStatus(DuosUser duosUser) throws Exception { HttpResponse response = executeRequest(request); if (!response.isSuccessStatusCode()) { logException( - String.format("Error removing Terms of Service: %s for user %s", + String.format( + "Error removing Terms of Service: %s for user %s", response.getStatusMessage(), duosUser.getEmail()), new ServerErrorException(response.getStatusMessage(), response.getStatusCode())); } @@ -226,5 +236,4 @@ private HttpResponse executeRequest(HttpRequest request) { request.setReadTimeout(readTimeoutMilliseconds); return clientUtil.handleHttpRequest(request); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/StudyDAO.java b/src/main/java/org/broadinstitute/consent/http/db/StudyDAO.java index 4212c4844d..2944f7ba3b 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/StudyDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/StudyDAO.java @@ -20,9 +20,9 @@ @RegisterRowMapper(FileStorageObjectMapperWithFSOPrefix.class) public interface StudyDAO extends Transactional { - @UseRowReducer(StudyReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT s.*, sp.study_property_id AS sp_study_property_id, @@ -32,8 +32,9 @@ public interface StudyDAO extends Transactional { sp.type AS sp_type, d.dataset_id AS s_dataset_id, """ - + FileStorageObject.QUERY_FIELDS_WITH_FSO_PREFIX + " " + - """ + + FileStorageObject.QUERY_FIELDS_WITH_FSO_PREFIX + + " " + + """ FROM study s LEFT JOIN study_property sp ON sp.study_id = s.study_id @@ -43,7 +44,8 @@ public interface StudyDAO extends Transactional { """) Study findStudyById(@Bind("studyId") Integer studyId); - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO study ( name, description, pi_name, data_types, @@ -59,7 +61,8 @@ INSERT INTO study ( ) """) @GetGeneratedKeys - Integer insertStudy(@Bind("name") String name, + Integer insertStudy( + @Bind("name") String name, @Bind("description") String description, @Bind("piName") String piName, @Bind("dataTypes") List dataTypes, @@ -68,7 +71,8 @@ Integer insertStudy(@Bind("name") String name, @Bind("createDate") Instant createDate, @Bind("uuid") UUID uuid); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE study SET name = :name, description = :description, @@ -79,7 +83,8 @@ Integer insertStudy(@Bind("name") String name, update_date = :updateDate WHERE study_id = :studyId """) - void updateStudy(@Bind("studyId") Integer studyId, + void updateStudy( + @Bind("studyId") Integer studyId, @Bind("name") String name, @Bind("description") String description, @Bind("piName") String piName, @@ -88,7 +93,8 @@ void updateStudy(@Bind("studyId") Integer studyId, @Bind("updateUserId") Integer updateUserId, @Bind("updateDate") Instant updateDate); - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO study_property ( study_id, key, type, value @@ -102,10 +108,10 @@ Integer insertStudyProperty( @Bind("studyId") Integer studyId, @Bind("key") String key, @Bind("type") String type, - @Bind("value") String value - ); + @Bind("value") String value); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE study_property SET value = :value WHERE study_id = :studyId @@ -116,10 +122,10 @@ void updateStudyProperty( @Bind("studyId") Integer studyId, @Bind("key") String key, @Bind("type") String type, - @Bind("value") String value - ); + @Bind("value") String value); - @SqlUpdate(""" + @SqlUpdate( + """ WITH property_deletes AS ( DELETE from study_property where study_id = :studyId returning study_id ) @@ -128,9 +134,9 @@ DELETE FROM study WHERE study_id in (select study_id from property_deletes) void deleteStudyByStudyId(@Bind("studyId") Integer studyId); @UseRowReducer(StudyReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM study WHERE name = :name """) Study findStudyByName(@Bind("name") String name); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/UserDAO.java b/src/main/java/org/broadinstitute/consent/http/db/UserDAO.java index 8ecaf17f47..4202c62629 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/UserDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/UserDAO.java @@ -31,7 +31,8 @@ public interface UserDAO extends Transactional { @RegisterBeanMapper(value = Institution.class, prefix = "i") @RegisterBeanMapper(value = LibraryCard.class, prefix = "lc") @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT u.user_id as u_user_id, u.email as u_email, @@ -69,7 +70,8 @@ public interface UserDAO extends Transactional { @RegisterBeanMapper(value = LibraryCard.class, prefix = "lc") @RegisterBeanMapper(value = UserProperty.class, prefix = "up") @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT u.user_id as u_user_id, u.email as u_email, @@ -102,64 +104,78 @@ public interface UserDAO extends Transactional { LEFT JOIN user_property up ON up.user_id = u.user_id AND up.property_key IN () WHERE u.user_id = :userId """) - User findUserWithPropertiesById(@Bind("userId") Integer userId, @BindList(value = "keys", onEmpty = EmptyHandling.NULL_STRING) List keys); + User findUserWithPropertiesById( + @Bind("userId") Integer userId, + @BindList(value = "keys", onEmpty = EmptyHandling.NULL_STRING) List keys); @RegisterBeanMapper(value = User.class, prefix = "u") @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery("SELECT " - + User.QUERY_FIELDS_WITH_U_PREFIX - + " FROM users u WHERE u.user_id IN ()") - Collection findUsers(@BindList(value = "userIds", onEmpty = EmptyHandling.NULL_STRING) Collection userIds); + @SqlQuery( + "SELECT " + User.QUERY_FIELDS_WITH_U_PREFIX + " FROM users u WHERE u.user_id IN ()") + Collection findUsers( + @BindList(value = "userIds", onEmpty = EmptyHandling.NULL_STRING) + Collection userIds); @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery("SELECT " - + User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR - + " ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id, r.name " - + " FROM users u " - + " LEFT JOIN user_role ur ON ur.user_id = u.user_id " - + " LEFT JOIN roles r ON r.role_id = ur.role_id " - + " WHERE r.name = :name") + @SqlQuery( + "SELECT " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + + " ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id, r.name " + + " FROM users u " + + " LEFT JOIN user_role ur ON ur.user_id = u.user_id " + + " LEFT JOIN roles r ON r.role_id = ur.role_id " + + " WHERE r.name = :name") List describeUsersByRole(@Bind("name") String name); - @SqlQuery("select du.user_id from users du inner join user_role ur on ur.user_id = du.user_id inner join roles r on r.role_id = ur.role_id where du.user_id = :userId and r.name = 'Chairperson'") + @SqlQuery( + "select du.user_id from users du inner join user_role ur on ur.user_id = du.user_id inner join roles r on r.role_id = ur.role_id where du.user_id = :userId and r.name = 'Chairperson'") Integer checkChairpersonUser(@Bind("userId") Integer userId); @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery("SELECT " - + User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR - + " r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id " - + " FROM users u " - + " INNER JOIN user_role ur ON ur.user_id = u.user_id AND ur.dac_id = :dacId " - + " INNER JOIN roles r ON r.role_id = ur.role_id " - + " WHERE r.name = 'Chairperson' OR r.name = 'Member'") + @SqlQuery( + "SELECT " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + + " r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id " + + " FROM users u " + + " INNER JOIN user_role ur ON ur.user_id = u.user_id AND ur.dac_id = :dacId " + + " INNER JOIN roles r ON r.role_id = ur.role_id " + + " WHERE r.name = 'Chairperson' OR r.name = 'Member'") Set findUsersEnabledToVoteByDAC(@Bind("dacId") Integer dacId); @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery("select " - + User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR - + " r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id " - + " FROM users u " - + " INNER JOIN user_role ur ON ur.user_id = u.user_id AND ur.dac_id is null " - + " INNER JOIN roles r on r.role_id = ur.role_id " - + " WHERE r.name = 'Chairperson' OR r.name = 'Member'") + @SqlQuery( + "select " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + + " r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id " + + " FROM users u " + + " INNER JOIN user_role ur ON ur.user_id = u.user_id AND ur.dac_id is null " + + " INNER JOIN roles r on r.role_id = ur.role_id " + + " WHERE r.name = 'Chairperson' OR r.name = 'Member'") Set findNonDacUsersEnabledToVote(); @UseRowMapper(UserWithRolesMapper.class) - @SqlQuery("select du.*, r.role_id, r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id from users du inner join user_role ur on ur.user_id = du.user_id inner join roles r on r.role_id = ur.role_id where du.user_id IN ()") - Set findUsersWithRoles(@BindList(value = "userIds", onEmpty = EmptyHandling.NULL_STRING) Collection userIds); + @SqlQuery( + "select du.*, r.role_id, r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id from users du inner join user_role ur on ur.user_id = du.user_id inner join roles r on r.role_id = ur.role_id where du.user_id IN ()") + Set findUsersWithRoles( + @BindList(value = "userIds", onEmpty = EmptyHandling.NULL_STRING) + Collection userIds); @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = UserRole.class, prefix = "ur") @RegisterBeanMapper(value = Institution.class, prefix = "i") @RegisterBeanMapper(value = LibraryCard.class, prefix = "lc") @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT u.user_id as u_user_id, u.email as u_email, @@ -194,7 +210,8 @@ WHERE LOWER(u.email) = LOWER(:email) @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = UserRole.class, prefix = "ur") @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT u.user_id as u_user_id, u.email as u_email, u.display_name as u_display_name, u.create_date as u_create_date, u.email_preference as u_email_preference, @@ -206,11 +223,14 @@ WHERE LOWER(u.email) = LOWER(:email) LEFT JOIN roles r ON r.role_id = ur.role_id WHERE LOWER(u.email) ILIKE ANY (array[]) """) - List findUsersByEmailList(@BindList(value = "emails", onEmpty = EmptyHandling.NULL_STRING) List emails); + List findUsersByEmailList( + @BindList(value = "emails", onEmpty = EmptyHandling.NULL_STRING) List emails); - @SqlUpdate("INSERT INTO users (email, display_name, institution_id, create_date) values (:email, :displayName, :institutionId, :createDate)") + @SqlUpdate( + "INSERT INTO users (email, display_name, institution_id, create_date) values (:email, :displayName, :institutionId, :createDate)") @GetGeneratedKeys - Integer insertUser(@Bind("email") String email, + Integer insertUser( + @Bind("email") String email, @Bind("displayName") String displayName, @Bind("institutionId") Integer institutionId, @Bind("createDate") Date createDate); @@ -224,8 +244,8 @@ Integer insertUser(@Bind("email") String email, @RegisterBeanMapper(value = Institution.class, prefix = "i") @UseRowReducer(UserWithRolesReducer.class) @SqlQuery( - //This will pull in users tied to the institution - //Users will come with LCs issued by SOs institution (if any) + // This will pull in users tied to the institution + // Users will come with LCs issued by SOs institution (if any) """ SELECT DISTINCT u.user_id as u_user_id, @@ -257,7 +277,8 @@ Integer insertUser(@Bind("email") String email, List findUsersWithLCsAndInstitution(); @UseRowMapper(UserWithRolesMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT u.*, r.role_id, r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id FROM users u INNER JOIN user_role ur ON ur.user_id = u.user_id AND ur.role_id = :roleId @@ -266,7 +287,8 @@ Integer insertUser(@Bind("email") String email, List findUsersByRoleId(@Bind("roleId") Integer roleId); @UseRowMapper(UserWithRolesMapper.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT u.*, r.role_id, r.name, ur.user_role_id, ur.user_id, ur.role_id, ur.dac_id FROM users u INNER JOIN user_role ur ON ur.user_id = u.user_id AND ur.role_id in () @@ -274,8 +296,7 @@ Integer insertUser(@Bind("email") String email, INNER JOIN dac d ON d.dac_id = ur.dac_id INNER JOIN dataset ds ON ds.dac_id = d.dac_id WHERE ds.dataset_id in () - """ - ) + """) Set findUsersForDatasetsByRole( @BindList(value = "datasetIds", onEmpty = EmptyHandling.NULL_STRING) List datasetIds, @BindList(value = "roleIds", onEmpty = EmptyHandling.NULL_STRING) List roleIds); @@ -283,11 +304,12 @@ Set findUsersForDatasetsByRole( @RegisterBeanMapper(value = User.class) @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery("SELECT du.*, r.name, ur.role_id, ur.user_role_id, ur.dac_id " - + " FROM users du " - + " LEFT JOIN user_role ur ON ur.user_id = du.user_id " - + " LEFT JOIN roles r ON r.role_id = ur.role_id " - + " WHERE du.institution_id = :institutionId") + @SqlQuery( + "SELECT du.*, r.name, ur.role_id, ur.user_role_id, ur.dac_id " + + " FROM users du " + + " LEFT JOIN user_role ur ON ur.user_id = du.user_id " + + " LEFT JOIN roles r ON r.role_id = ur.role_id " + + " WHERE du.institution_id = :institutionId") List findUsersByInstitution(@Bind("institutionId") Integer institutionId); @RegisterBeanMapper(value = User.class, prefix = "u") @@ -296,8 +318,8 @@ Set findUsersForDatasetsByRole( @RegisterBeanMapper(value = Institution.class, prefix = "i") @UseRowReducer(UserWithRolesReducer.class) @SqlQuery( - //This will pull in users tied to the institution - //Users will come with LCs issued by SOs institution (if any) + // This will pull in users tied to the institution + // Users will come with LCs issued by SOs institution (if any) """ SELECT u.user_id as u_user_id, @@ -366,42 +388,44 @@ SELECT DISTINCT ON (u.user_id) """) List getUsersWithCardsByDaaId(@Bind("daaId") Integer daaId); - //SO only endpoint (so far) - //Meant to pull in users that have not yet been assigned an institution - //(SOs can assign LCs to these users as well) + // SO only endpoint (so far) + // Meant to pull in users that have not yet been assigned an institution + // (SOs can assign LCs to these users as well) @RegisterBeanMapper(value = User.class, prefix = "u") @RegisterBeanMapper(value = UserRole.class) @UseRowReducer(UserWithRolesReducer.class) - @SqlQuery(" SELECT " + - User.QUERY_FIELDS_WITH_U_PREFIX + QUERY_FIELD_SEPARATOR + - " r.name, ur.role_id, ur.user_role_id, ur.dac_id, ur.user_id " + - " FROM users u " + - " LEFT JOIN user_role ur ON ur.user_id = u.user_id " + - " LEFT JOIN roles r ON r.role_id = ur.role_id " + - " WHERE u.institution_id IS NULL") + @SqlQuery( + " SELECT " + + User.QUERY_FIELDS_WITH_U_PREFIX + + QUERY_FIELD_SEPARATOR + + " r.name, ur.role_id, ur.user_role_id, ur.dac_id, ur.user_id " + + " FROM users u " + + " LEFT JOIN user_role ur ON ur.user_id = u.user_id " + + " LEFT JOIN roles r ON r.role_id = ur.role_id " + + " WHERE u.institution_id IS NULL") List getUsersWithNoInstitution(); @RegisterBeanMapper(value = User.class) - @SqlQuery("SELECT u.user_id, u.display_name, u.email FROM users u " - + " LEFT JOIN user_role ur ON ur.user_id = u.user_id " - + " LEFT JOIN roles r ON r.role_id = ur.role_id " - + " WHERE LOWER(r.name) = 'signingofficial' " - + " AND u.institution_id = :institutionId") + @SqlQuery( + "SELECT u.user_id, u.display_name, u.email FROM users u " + + " LEFT JOIN user_role ur ON ur.user_id = u.user_id " + + " LEFT JOIN roles r ON r.role_id = ur.role_id " + + " WHERE LOWER(r.name) = 'signingofficial' " + + " AND u.institution_id = :institutionId") List getSOsByInstitution(@Bind("institutionId") Integer institutionId); @SqlUpdate("update users set email_preference = :emailPreference WHERE user_id = :userId") - void updateEmailPreference(@Bind("userId") Integer userId, - @Bind("emailPreference") Boolean emailPreference); + void updateEmailPreference( + @Bind("userId") Integer userId, @Bind("emailPreference") Boolean emailPreference); @SqlUpdate("UPDATE users SET era_commons_id = :eraCommonsId WHERE user_id = :userId") - void updateEraCommonsId(@Bind("userId") Integer userId, - @Bind("eraCommonsId") String eraCommonsId); + void updateEraCommonsId( + @Bind("userId") Integer userId, @Bind("eraCommonsId") String eraCommonsId); @SqlUpdate("UPDATE users SET institution_id = :institutionId WHERE user_id = :userId") - void updateInstitutionId(@Bind("userId") Integer userId, - @Bind("institutionId") Integer institutionId); + void updateInstitutionId( + @Bind("userId") Integer userId, @Bind("institutionId") Integer institutionId); @SqlUpdate("UPDATE users SET display_name = :displayName WHERE user_id = :userId") void updateDisplayName(@Bind("userId") Integer userId, @Bind("displayName") String displayName); - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/UserPropertyDAO.java b/src/main/java/org/broadinstitute/consent/http/db/UserPropertyDAO.java index 81608632f5..427618aa00 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/UserPropertyDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/UserPropertyDAO.java @@ -17,13 +17,16 @@ @RegisterRowMapper(UserPropertyMapper.class) public interface UserPropertyDAO extends Transactional { - @SqlQuery(""" + @SqlQuery( + """ SELECT * FROM user_property WHERE user_id = :userId AND property_key IN () """) - List findUserPropertiesByUserIdAndPropertyKeys(@Bind("userId") Integer userId, + List findUserPropertiesByUserIdAndPropertyKeys( + @Bind("userId") Integer userId, @BindList(value = "keys", onEmpty = EmptyHandling.NULL_STRING) List keys); - @SqlBatch(""" + @SqlBatch( + """ INSERT INTO user_property (user_id, property_key, property_value) VALUES (:userId, :propertyKey, :propertyValue) ON CONFLICT (user_id, property_key) @@ -31,12 +34,14 @@ ON CONFLICT (user_id, property_key) """) void insertAll(@BindBean Collection userProperties); - @SqlUpdate(""" + @SqlUpdate( + """ DELETE FROM user_property WHERE user_id = :userId """) void deleteAllPropertiesByUser(@Bind("userId") Integer userId); - @SqlBatch(""" + @SqlBatch( + """ DELETE FROM user_property WHERE user_id = :userId AND property_key = :propertyKey """) void deletePropertiesByUserAndKey(@BindBean Collection userProperties); diff --git a/src/main/java/org/broadinstitute/consent/http/db/UserRoleDAO.java b/src/main/java/org/broadinstitute/consent/http/db/UserRoleDAO.java index 21cb291e4f..5aad28b2a9 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/UserRoleDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/UserRoleDAO.java @@ -19,15 +19,17 @@ @RegisterRowMapper(UserRoleMapper.class) public interface UserRoleDAO extends Transactional { - @SqlQuery(""" - SELECT * + @SqlQuery( + """ + SELECT * FROM roles r - INNER JOIN user_role ur ON ur.role_id = r.role_id + INNER JOIN user_role ur ON ur.role_id = r.role_id WHERE ur.user_id = :userId """) List findRolesByUserId(@Bind("userId") Integer userId); - @SqlQuery(""" + @SqlQuery( + """ SELECT DISTINCT name FROM roles r INNER JOIN user_role ur ON ur.role_id = r.role_id @@ -37,63 +39,74 @@ WHERE LOWER(u.email) = LOWER(:email) List findRoleNamesByUserEmail(@Bind("email") String email); @UseRowMapper(DatabaseRoleMapper.class) - @SqlQuery(""" - SELECT * + @SqlQuery( + """ + SELECT * FROM roles """) List findRoles(); - @SqlQuery(""" + @SqlQuery( + """ SELECT role_id FROM roles WHERE name = :roleName """) Integer findRoleIdByName(@Bind("roleName") String roleName); - @SqlBatch(""" + @SqlBatch( + """ INSERT INTO user_role (role_id, user_id) VALUES (:roleId, :userId) """) void insertUserRoles(@BindBean List roles, @Bind("userId") Integer userId); - @SqlUpdate(""" + @SqlUpdate( + """ UPDATE user_role SET role_id = :newRoleId WHERE user_id = :userId AND role_id = :existentRoleId """) - void updateUserRoles(@Bind("newRoleId") Integer newRoleId, + void updateUserRoles( + @Bind("newRoleId") Integer newRoleId, @Bind("userId") Integer userId, @Bind("existentRoleId") Integer existentRoleId); - @SqlUpdate(""" + @SqlUpdate( + """ DELETE FROM user_role WHERE user_id = :userId AND role_id IN () """) - void removeUserRoles(@Bind("userId") Integer userId, - @BindList(value = "existentRoles", onEmpty = EmptyHandling.NULL_STRING) List existentRoles); + void removeUserRoles( + @Bind("userId") Integer userId, + @BindList(value = "existentRoles", onEmpty = EmptyHandling.NULL_STRING) + List existentRoles); - @SqlUpdate(""" + @SqlUpdate( + """ INSERT INTO user_role (role_id, user_id) VALUES (:roleId, :userId) """) void insertSingleUserRole(@Bind("roleId") Integer roleId, @Bind("userId") Integer userId); - @SqlUpdate(""" + @SqlUpdate( + """ DELETE FROM user_role WHERE user_id = :userId AND role_id = :roleId """) void removeSingleUserRole(@Bind("userId") Integer userId, @Bind("roleId") Integer roleId); - @SqlQuery(""" - SELECT r.role_id - FROM roles r - INNER JOIN user_role ur on ur.role_id = r.role_id + @SqlQuery( + """ + SELECT r.role_id + FROM roles r + INNER JOIN user_role ur on ur.role_id = r.role_id WHERE ur.user_id = :userId AND r.name = :name """) Integer findRoleByNameAndUser(@Bind("name") String name, @Bind("userId") Integer id); - @SqlQuery(""" + @SqlQuery( + """ SELECT * - FROM user_role ur + FROM user_role ur INNER JOIN roles r ON r.role_id = ur.role_id WHERE ur.user_id = :userId AND ur.role_id = :roleId """) - UserRole findRoleByUserIdAndRoleId(@Bind("userId") Integer userId, - @Bind("roleId") Integer roleId); - + UserRole findRoleByUserIdAndRoleId( + @Bind("userId") Integer userId, @Bind("roleId") Integer roleId); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/VoteDAO.java b/src/main/java/org/broadinstitute/consent/http/db/VoteDAO.java index 7bb9431b4b..34e16da477 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/VoteDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/db/VoteDAO.java @@ -22,39 +22,47 @@ public interface VoteDAO extends Transactional { Vote findVoteById(@Bind("voteId") Integer voteId); @SqlQuery("SELECT * FROM vote v WHERE v.vote_id IN ()") - List findVotesByIds(@BindList(value = "voteIds", onEmpty = EmptyHandling.NULL_STRING) List voteIds); + List findVotesByIds( + @BindList(value = "voteIds", onEmpty = EmptyHandling.NULL_STRING) List voteIds); @SqlQuery("select * from vote v where v.election_id IN ()") - List findVotesByElectionIds(@BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) List electionIds); - - @SqlQuery("select * from vote v where v.election_id = :electionId and lower(v.type) = lower(:type)") - List findVotesByElectionIdAndType(@Bind("electionId") Integer electionId, - @Bind("type") String type); - - @SqlQuery("select * from vote v where v.election_id = :electionId and v.user_id = :userId and lower(v.type) = 'dac'") - Vote findVoteByElectionIdAndUserId(@Bind("electionId") Integer electionId, - @Bind("userId") Integer userId); - - @SqlQuery(""" + List findVotesByElectionIds( + @BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) + List electionIds); + + @SqlQuery( + "select * from vote v where v.election_id = :electionId and lower(v.type) = lower(:type)") + List findVotesByElectionIdAndType( + @Bind("electionId") Integer electionId, @Bind("type") String type); + + @SqlQuery( + "select * from vote v where v.election_id = :electionId and v.user_id = :userId and lower(v.type) = 'dac'") + Vote findVoteByElectionIdAndUserId( + @Bind("electionId") Integer electionId, @Bind("userId") Integer userId); + + @SqlQuery( + """ SELECT vote.vote_id FROM vote INNER JOIN election ON election.election_id = vote.election_id WHERE election.reference_id = :referenceId AND vote.vote_id = :voteId """) - Integer checkVoteById(@Bind("referenceId") String referenceId, - @Bind("voteId") Integer voteId); + Integer checkVoteById(@Bind("referenceId") String referenceId, @Bind("voteId") Integer voteId); - @SqlUpdate("INSERT INTO vote (user_id, election_id, type, reminder_sent, create_date) VALUES (:userId, :electionId, :type, false, current_timestamp)") + @SqlUpdate( + "INSERT INTO vote (user_id, election_id, type, reminder_sent, create_date) VALUES (:userId, :electionId, :type, false, current_timestamp)") @GetGeneratedKeys - Integer insertVote(@Bind("userId") Integer userId, + Integer insertVote( + @Bind("userId") Integer userId, @Bind("electionId") Integer electionId, @Bind("type") String type); @SqlUpdate("update vote set reminder_sent = :reminderSent where vote_id = :voteId") - void updateVoteReminderFlag(@Bind("voteId") Integer voteId, - @Bind("reminderSent") boolean reminderSent); + void updateVoteReminderFlag( + @Bind("voteId") Integer voteId, @Bind("reminderSent") boolean reminderSent); - @SqlQuery(""" + @SqlQuery( + """ SELECT count(*) FROM vote v INNER JOIN election e ON v.election_id = e.election_id WHERE LOWER(e.election_type) = LOWER(:type) @@ -62,28 +70,36 @@ AND LOWER(e.status) = 'closed' AND LOWER(v.type) = 'final' AND v.vote = :finalVote """) - Integer findTotalFinalVoteByElectionTypeAndVote(@Bind("type") String type, - @Bind("finalVote") Boolean finalVote); + Integer findTotalFinalVoteByElectionTypeAndVote( + @Bind("type") String type, @Bind("finalVote") Boolean finalVote); - @SqlQuery("SELECT MAX(c) FROM (SELECT COUNT(vote) as c FROM vote WHERE lower(type) = 'dac' and election_id IN () GROUP BY election_id) as members") - Integer findMaxNumberOfDACMembers(@BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) List electionIds); + @SqlQuery( + "SELECT MAX(c) FROM (SELECT COUNT(vote) as c FROM vote WHERE lower(type) = 'dac' and election_id IN () GROUP BY election_id) as members") + Integer findMaxNumberOfDACMembers( + @BindList(value = "electionIds", onEmpty = EmptyHandling.NULL_STRING) + List electionIds); @SqlBatch("insert into vote (user_id, election_id, type) values (:userId, :electionId, :type)") - void insertVotes(@Bind("userId") List userIds, @Bind("electionId") Integer electionId, + void insertVotes( + @Bind("userId") List userIds, + @Bind("electionId") Integer electionId, @Bind("type") String type); @SqlUpdate("delete from vote where vote_id IN ()") - void removeVotesByIds(@BindList(value = "voteIds", onEmpty = EmptyHandling.NULL_STRING) List voteIds); + void removeVotesByIds( + @BindList(value = "voteIds", onEmpty = EmptyHandling.NULL_STRING) List voteIds); @SqlQuery("SELECT * FROM vote v WHERE v.user_id = :userId ") List findVotesByUserId(@Bind("userId") Integer userId); @SqlUpdate("UPDATE vote v SET rationale = :rationale WHERE v.vote_id IN ()") - void updateRationaleByVoteIds(@BindList(value = "voteIds", onEmpty = EmptyHandling.NULL_STRING) List voteIds, + void updateRationaleByVoteIds( + @BindList(value = "voteIds", onEmpty = EmptyHandling.NULL_STRING) List voteIds, @Bind("rationale") String rationale); @RegisterBeanMapper(value = User.class) - @SqlQuery(""" + @SqlQuery( + """ SELECT DISTINCT u.* FROM users u INNER JOIN vote v ON v.user_id = u.user_id @@ -91,6 +107,6 @@ void updateRationaleByVoteIds(@BindList(value = "voteIds", onEmpty = EmptyHandli WHERE e.reference_id IN () """) List findVoteUsersByElectionReferenceIdList( - @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) List referenceIds); - + @BindList(value = "referenceIds", onEmpty = EmptyHandling.NULL_STRING) + List referenceIds); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/CounterMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/CounterMapper.java index 8586bd6dfa..c66d815588 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/CounterMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/CounterMapper.java @@ -10,10 +10,6 @@ public class CounterMapper implements RowMapper { @Override public Counter map(ResultSet rs, StatementContext ctx) throws SQLException { - return new Counter( - rs.getInt("id"), - rs.getString("name"), - rs.getInt("count") - ); + return new Counter(rs.getInt("id"), rs.getString("name"), rs.getInt("count")); } } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleAuditMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleAuditMapper.java index ea6108bd65..500ab94fd8 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleAuditMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleAuditMapper.java @@ -3,14 +3,14 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; -import org.broadinstitute.consent.http.rules.RuleAuditAction; import org.broadinstitute.consent.http.rules.DACAutomationRuleAudit; import org.broadinstitute.consent.http.rules.DACAutomationRuleType; +import org.broadinstitute.consent.http.rules.RuleAuditAction; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; -public class DACAutomationRuleAuditMapper implements RowMapper, - RowMapperHelper { +public class DACAutomationRuleAuditMapper + implements RowMapper, RowMapperHelper { @Override public DACAutomationRuleAudit map(ResultSet rs, StatementContext ctx) throws SQLException { diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleMapper.java index 99ce8b2a8e..89680e7dd0 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DACAutomationRuleMapper.java @@ -33,8 +33,7 @@ public DACAutomationRule map(ResultSet rs, StatementContext ctx) throws SQLExcep if (hasColumn(rs, "display_name")) { userName = rs.getString("display_name"); } - return new DACAutomationRule(id, ruleType, description, ruleState, activationDate, enabledByUserId, userName, - userEmail); + return new DACAutomationRule( + id, ruleType, description, ruleState, activationDate, enabledByUserId, userName, userEmail); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DaaMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DaaMapper.java index 92ec3dbff8..b5cade9610 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DaaMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DaaMapper.java @@ -13,7 +13,8 @@ public class DaaMapper implements RowMapper, RowMapperHelpe private final Map daaMap = new HashMap<>(); @Override - public DataAccessAgreement map(ResultSet resultSet, StatementContext statementContext) throws SQLException { + public DataAccessAgreement map(ResultSet resultSet, StatementContext statementContext) + throws SQLException { DataAccessAgreement daa; Integer daaId = hasNonZeroColumn(resultSet, "daa_id") ? resultSet.getInt("daa_id") : null; if (daaId == null) { diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DacReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DacReducer.java index 73c513e57f..2dfb0057e3 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DacReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DacReducer.java @@ -11,8 +11,8 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -public class DacReducer implements LinkedHashMapRowReducer, - ConsentLogger, RowMapperHelper { +public class DacReducer + implements LinkedHashMapRowReducer, ConsentLogger, RowMapperHelper { private final DataUseParser dataUseParser = new DataUseParser(); @@ -41,14 +41,13 @@ public void accumulate(Map container, RowView rowView) { if (daa.getDaaId() != null) { dac.setAssociatedDaa(daa); } - } if (hasColumn(rowView, "dataset_id", Integer.class) && rowView.getColumn("dataset_id", Integer.class) > 0) { Dataset dataset = rowView.getRow(Dataset.class); - //aliased columns must be set directly + // aliased columns must be set directly String dsAlias = rowView.getColumn("dataset_alias", String.class); if (dsAlias != null) { try { @@ -76,10 +75,8 @@ public void accumulate(Map container, RowView rowView) { if (dataset != null) { dac.addDataset(dataset); } - } - } catch (MappingException e) { logWarn(e.getMessage()); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DarCollectionSummaryReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DarCollectionSummaryReducer.java index 30b6834136..2b473f66d9 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DarCollectionSummaryReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DarCollectionSummaryReducer.java @@ -13,16 +13,16 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -public class DarCollectionSummaryReducer implements - LinkedHashMapRowReducer, RowMapperHelper { +public class DarCollectionSummaryReducer + implements LinkedHashMapRowReducer, RowMapperHelper { @Override public void accumulate(Map map, RowView rowView) { - DarCollectionSummary summary = map.computeIfAbsent( - rowView.getColumn("dar_collection_id", Integer.class), - id -> rowView.getRow(DarCollectionSummary.class) - ); + DarCollectionSummary summary = + map.computeIfAbsent( + rowView.getColumn("dar_collection_id", Integer.class), + id -> rowView.getRow(DarCollectionSummary.class)); Election election; Vote vote; Integer datasetId; @@ -32,7 +32,8 @@ public void accumulate(Map map, RowView rowView) try { if (hasColumn(rowView, "closeout", String.class)) { String string = rowView.getColumn("closeout", String.class); - CloseoutSupplement closeout = GsonUtil.getInstance().fromJson(string, CloseoutSupplement.class); + CloseoutSupplement closeout = + GsonUtil.getInstance().fromJson(string, CloseoutSupplement.class); summary.setCloseoutSupplement(closeout); } @@ -53,7 +54,8 @@ public void accumulate(Map map, RowView rowView) summary.setLatestReferenceId(darReferenceId); } hasOptionalColumn(rowView, "latest_dar_parent_id", Integer.class) - .ifPresent(darParentId -> summary.addParentChildRelationship(darParentId, darReferenceId)); + .ifPresent( + darParentId -> summary.addParentChildRelationship(darParentId, darReferenceId)); hasOptionalColumn(rowView, "latest_dar_closeout_approving_so_id", Integer.class) .ifPresent(summary::setCloseoutSigningOfficialId); hasOptionalColumn(rowView, "latest_dar_closeout_so_approval_timestamp", Timestamp.class) @@ -63,7 +65,7 @@ public void accumulate(Map map, RowView rowView) summary.addStatus(darStatus, darReferenceId); } } catch (MappingException e) { - //ignore exception, it means dar_status and dar_reference_id wasn't included for this query + // ignore exception, it means dar_status and dar_reference_id wasn't included for this query } try { @@ -86,7 +88,8 @@ public void accumulate(Map map, RowView rowView) } } catch (NoSuchMapperException e) { - //ignore these exceptions, just means there's no elections and votes on the collection for this query + // ignore these exceptions, just means there's no elections and votes on the collection for + // this query } } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessAgreementReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessAgreementReducer.java index e4a3e9a15c..ac6432205c 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessAgreementReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessAgreementReducer.java @@ -9,18 +9,17 @@ import org.jdbi.v3.core.result.RowView; public class DataAccessAgreementReducer - implements LinkedHashMapRowReducer, RowMapperHelper, - ConsentLogger { + implements LinkedHashMapRowReducer, + RowMapperHelper, + ConsentLogger { @Override public void accumulate(Map map, RowView rowView) { - var daaId = hasNonZeroColumn(rowView, "daa_id") ? - rowView.getColumn("daa_id", Integer.class) : - rowView.getColumn("daa_daa_id", Integer.class); - map.computeIfAbsent( - daaId, - id -> rowView.getRow(DataAccessAgreement.class) - ); + var daaId = + hasNonZeroColumn(rowView, "daa_id") + ? rowView.getColumn("daa_id", Integer.class) + : rowView.getColumn("daa_daa_id", Integer.class); + map.computeIfAbsent(daaId, id -> rowView.getRow(DataAccessAgreement.class)); if (hasColumn(rowView, "file_storage_object_id", String.class)) { FileStorageObject fso = rowView.getRow(FileStorageObject.class); map.get(daaId).setFile(fso); diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestDataMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestDataMapper.java index c50d9cca89..9523662ea1 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestDataMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestDataMapper.java @@ -7,9 +7,8 @@ import org.jdbi.v3.core.statement.StatementContext; import org.postgresql.util.PGobject; -public class DataAccessRequestDataMapper implements RowMapper, - RowMapperHelper { - +public class DataAccessRequestDataMapper + implements RowMapper, RowMapperHelper { @Override public DataAccessRequestData map(ResultSet resultSet, StatementContext statementContext) @@ -18,5 +17,4 @@ public DataAccessRequestData map(ResultSet resultSet, StatementContext statement DataAccessRequestData data = translate(darDataString); return data; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestMapper.java index 83ff597901..5beb03fbf6 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataAccessRequestMapper.java @@ -26,7 +26,7 @@ public DataAccessRequest map(ResultSet resultSet, StatementContext statementCont dar.setDarCode(resultSet.getString("dar_code")); } - if (hasNonZeroColumn(resultSet,"parent_id")) { + if (hasNonZeroColumn(resultSet, "parent_id")) { dar.setParentId(resultSet.getInt("parent_id")); } @@ -44,9 +44,9 @@ public DataAccessRequest map(ResultSet resultSet, StatementContext statementCont } dar.setData(data); dar.setEraCommonsId(resultSet.getString("era_commons_id")); - dar.setCloseoutSigningOfficialApprovedDate(resultSet.getTimestamp("closeout_so_approval_timestamp")); + dar.setCloseoutSigningOfficialApprovedDate( + resultSet.getTimestamp("closeout_so_approval_timestamp")); dar.setCloseoutSigningOfficialApprovedUserId(resultSet.getInt("closeout_approving_so_id")); return dar; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataUseParser.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataUseParser.java index 4df8d8f923..a29ae570c4 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DataUseParser.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DataUseParser.java @@ -16,14 +16,15 @@ public DataUse parseDataUse(String dataUseString) { if (null == dataUseString || dataUseString.isEmpty()) { return null; } - return dataUseCache.computeIfAbsent(dataUseString, s -> { - try { - return gson.fromJson(dataUseString, DataUse.class); - } catch (Exception e) { - logWarn(String.format("Unable to parse data use string: '%s'", dataUseString)); - } - return null; - }); + return dataUseCache.computeIfAbsent( + dataUseString, + s -> { + try { + return gson.fromJson(dataUseString, DataUse.class); + } catch (Exception e) { + logWarn(String.format("Unable to parse data use string: '%s'", dataUseString)); + } + return null; + }); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetAuditMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetAuditMapper.java index 6ef481b5e6..0d7088b667 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetAuditMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetAuditMapper.java @@ -34,5 +34,4 @@ public DatasetAudit map(ResultSet rs, StatementContext ctx) throws SQLException } return datasetAudit; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetPropertyMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetPropertyMapper.java index 5343ff25b8..f34b58217d 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetPropertyMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetPropertyMapper.java @@ -10,15 +10,15 @@ public class DatasetPropertyMapper implements RowMapper, RowMapperHelper { public DatasetProperty map(ResultSet r, StatementContext ctx) throws SQLException { - DatasetProperty prop = new DatasetProperty( - r.getInt("property_id"), - r.getInt("dataset_id"), - r.getInt("property_key"), - r.getString("schema_property"), - r.getString("property_value"), - PropertyType.parse(r.getString("property_type")), - r.getTimestamp("create_date") - ); + DatasetProperty prop = + new DatasetProperty( + r.getInt("property_id"), + r.getInt("dataset_id"), + r.getInt("property_key"), + r.getString("schema_property"), + r.getString("property_value"), + PropertyType.parse(r.getString("property_type")), + r.getTimestamp("create_date")); if (hasColumn(r, "key")) { prop.setPropertyName(r.getString("key")); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetReducer.java index a1dc3ea78e..3ff93322d2 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DatasetReducer.java @@ -86,8 +86,7 @@ && hasColumn(rowView, "property_value", String.class)) { dataset.setNihInstitutionalCertificationFile(fileStorageObject); } } - default -> { - } + default -> {} } } @@ -101,7 +100,7 @@ && hasColumn(rowView, "property_value", String.class)) { } private boolean isFileNewer(FileStorageObject incomingFile, FileStorageObject existingFile) { - return Objects.isNull(existingFile) || incomingFile.getLatestUpdateDate() - .isAfter(existingFile.getLatestUpdateDate()); + return Objects.isNull(existingFile) + || incomingFile.getLatestUpdateDate().isAfter(existingFile.getLatestUpdateDate()); } } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftInterfaceMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftInterfaceMapper.java index ceb90f879c..caab363a23 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftInterfaceMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftInterfaceMapper.java @@ -12,11 +12,11 @@ import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; - public class DraftInterfaceMapper implements RowMapper, RowMapperHelper { @Override - public DraftInterface map(ResultSet rs, StatementContext ctx) throws SQLException, UnknownDraftTypeException { + public DraftInterface map(ResultSet rs, StatementContext ctx) + throws SQLException, UnknownDraftTypeException { DraftInterface dsi = getDraftImplByType(rs); if (hasColumn(rs, "name")) { @@ -40,28 +40,32 @@ public DraftInterface map(ResultSet rs, StatementContext ctx) throws SQLExceptio } if (hasColumn(rs, "uu_user_id")) { - User updateUser = buildUserFromResult(rs.getInt("uu_user_id"), - rs.getString("uu_email"), - rs.getString("uu_display_name"), - rs.getTimestamp("uu_create_date"), - rs.getBoolean("uu_email_preference")); + User updateUser = + buildUserFromResult( + rs.getInt("uu_user_id"), + rs.getString("uu_email"), + rs.getString("uu_display_name"), + rs.getTimestamp("uu_create_date"), + rs.getBoolean("uu_email_preference")); dsi.setUpdateUser(updateUser); } if (hasColumn(rs, "cu_user_id")) { - User createUser = buildUserFromResult(rs.getInt("cu_user_id"), - rs.getString("cu_email"), - rs.getString("cu_display_name"), - new Date(rs.getTimestamp("cu_create_date").getTime()), - rs.getBoolean("cu_email_preference")); + User createUser = + buildUserFromResult( + rs.getInt("cu_user_id"), + rs.getString("cu_email"), + rs.getString("cu_display_name"), + new Date(rs.getTimestamp("cu_create_date").getTime()), + rs.getBoolean("cu_email_preference")); dsi.setCreateUser(createUser); } return dsi; } - private User buildUserFromResult(Integer userId, String email, String displayName, - Date createDate, boolean emailPreference) { + private User buildUserFromResult( + Integer userId, String email, String displayName, Date createDate, boolean emailPreference) { User user = new User(); user.setUserId(userId); user.setEmail(email); @@ -71,11 +75,11 @@ private User buildUserFromResult(Integer userId, String email, String displayNam return user; } - private DraftInterface getDraftImplByType(ResultSet rs) throws SQLException, UnknownDraftTypeException { + private DraftInterface getDraftImplByType(ResultSet rs) + throws SQLException, UnknownDraftTypeException { try { String type = rs.getString("draft_type"); - DraftType draftType = DraftType.fromValue( - type); + DraftType draftType = DraftType.fromValue(type); return DraftBuilder.from(draftType); } catch (NullPointerException ex) { throw new UnknownDraftTypeException("Draft type was not found."); diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftReducer.java index c4647a8ffa..1090f143f0 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftReducer.java @@ -7,19 +7,18 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -public class DraftReducer implements - LinkedHashMapRowReducer, RowMapperHelper { +public class DraftReducer + implements LinkedHashMapRowReducer, RowMapperHelper { @Override public void accumulate(Map map, RowView rowView) { - DraftInterface draft = map.computeIfAbsent( - rowView.getColumn("uuid", UUID.class), - id -> rowView.getRow(DraftInterface.class)); + DraftInterface draft = + map.computeIfAbsent( + rowView.getColumn("uuid", UUID.class), id -> rowView.getRow(DraftInterface.class)); if (hasNonZeroColumn(rowView, "fso_file_storage_object_id")) { FileStorageObject fileStorageObject = rowView.getRow(FileStorageObject.class); draft.addStoredFile(fileStorageObject); } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftSummaryMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftSummaryMapper.java index 4fa22ae45c..10130ff70c 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftSummaryMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/DraftSummaryMapper.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.db.mapper; - import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; @@ -10,8 +9,7 @@ import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; -public class DraftSummaryMapper implements RowMapper, - RowMapperHelper { +public class DraftSummaryMapper implements RowMapper, RowMapperHelper { @Override public DraftSummary map(ResultSet rs, StatementContext ctx) throws SQLException { diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapper.java index 57be44d659..079dd89d2c 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapper.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.db.mapper; - import com.google.cloud.storage.BlobId; import java.sql.ResultSet; import java.sql.SQLException; @@ -12,8 +11,8 @@ import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; -public class FileStorageObjectMapper implements RowMapper, RowMapperHelper, - ConsentLogger { +public class FileStorageObjectMapper + implements RowMapper, RowMapperHelper, ConsentLogger { @Override public FileStorageObject map(ResultSet r, StatementContext statementContext) throws SQLException { @@ -36,7 +35,10 @@ public FileStorageObject map(ResultSet r, StatementContext statementContext) thr try { file.setBlobId(BlobId.fromGsUtilUri(value)); } catch (Exception e) { - logException("Error parsing blob id: %s for fso id: %s".formatted(value, file.getFileStorageObjectId()), e); + logException( + "Error parsing blob id: %s for fso id: %s" + .formatted(value, file.getFileStorageObjectId()), + e); file.setBlobId(null); } } @@ -46,7 +48,10 @@ public FileStorageObject map(ResultSet r, StatementContext statementContext) thr try { file.setCategory(FileCategory.findValue(value)); } catch (Exception e) { - logException("Error parsing file category: %s for fso id: %s".formatted(value, file.getFileStorageObjectId()), e); + logException( + "Error parsing file category: %s for fso id: %s" + .formatted(value, file.getFileStorageObjectId()), + e); file.setCategory(null); } } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapperWithFSOPrefix.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapperWithFSOPrefix.java index e7273e06f8..5a6b3f4c82 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapperWithFSOPrefix.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/FileStorageObjectMapperWithFSOPrefix.java @@ -3,8 +3,8 @@ import org.broadinstitute.consent.http.models.FileStorageObject; import org.jdbi.v3.core.mapper.RowMapper; -public class FileStorageObjectMapperWithFSOPrefix extends FileStorageObjectMapper implements - RowMapper, RowMapperHelper { +public class FileStorageObjectMapperWithFSOPrefix extends FileStorageObjectMapper + implements RowMapper, RowMapperHelper { @Override public String getPrefix() { diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionMapper.java index e7c4ca9e65..5cd16f496c 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionMapper.java @@ -29,8 +29,8 @@ public Institution map(ResultSet resultSet, StatementContext statementContext) setDateFieldValue(resultSet, "create_date", institution::setCreateDate); setDateFieldValue(resultSet, "update_date", institution::setUpdateDate); if (hasColumn(resultSet, "organization_type")) { - OrganizationType type = OrganizationType.getOrganizationTypeFromString( - resultSet.getString("organization_type")); + OrganizationType type = + OrganizationType.getOrganizationTypeFromString(resultSet.getString("organization_type")); institution.setOrganizationType(type); } return institution; diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionReducer.java index 98bb9f0341..50a0f1bf3d 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionReducer.java @@ -6,14 +6,15 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -public class InstitutionReducer implements LinkedHashMapRowReducer, - RowMapperHelper { +public class InstitutionReducer + implements LinkedHashMapRowReducer, RowMapperHelper { @Override public void accumulate(Map map, RowView rowView) { - Institution institution = map.computeIfAbsent( - rowView.getColumn("institution_id", Integer.class), - id -> rowView.getRow(Institution.class)); + Institution institution = + map.computeIfAbsent( + rowView.getColumn("institution_id", Integer.class), + id -> rowView.getRow(Institution.class)); if (hasColumn(rowView, "domain", String.class)) { String domain = rowView.getColumn("domain", String.class); if (!StringUtils.isBlank(domain)) { diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionWithUsersReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionWithUsersReducer.java index 231269db68..4ffb104868 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionWithUsersReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/InstitutionWithUsersReducer.java @@ -10,18 +10,17 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -/** - * Set the create user and update user on an institution - */ -public class InstitutionWithUsersReducer implements LinkedHashMapRowReducer, - RowMapperHelper { +/** Set the create user and update user on an institution */ +public class InstitutionWithUsersReducer + implements LinkedHashMapRowReducer, RowMapperHelper { @Override public void accumulate(Map map, RowView rowView) { - Institution institution = map.computeIfAbsent( - rowView.getColumn("institution_id", Integer.class), - id -> rowView.getRow(Institution.class)); + Institution institution = + map.computeIfAbsent( + rowView.getColumn("institution_id", Integer.class), + id -> rowView.getRow(Institution.class)); User createUser = new User(); if (Objects.nonNull(rowView.getColumn("u_user_id", Integer.class))) { @@ -51,5 +50,4 @@ public void accumulate(Map map, RowView rowView) { } } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardReducer.java index d7ee9faa1e..43e3a21172 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardReducer.java @@ -6,20 +6,20 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -public class LibraryCardReducer implements LinkedHashMapRowReducer, - RowMapperHelper { +public class LibraryCardReducer + implements LinkedHashMapRowReducer, RowMapperHelper { @Override public void accumulate(Map map, RowView rowView) { - LibraryCard card = map.computeIfAbsent( - rowView.getColumn("id", Integer.class), - id -> rowView.getRow(LibraryCard.class)); + LibraryCard card = + map.computeIfAbsent( + rowView.getColumn("id", Integer.class), id -> rowView.getRow(LibraryCard.class)); try { - if (hasNonZeroColumn(rowView,"daa_id")) { + if (hasNonZeroColumn(rowView, "daa_id")) { card.addDaa(rowView.getColumn("daa_id", Integer.class)); } } catch (MappingException e) { logWarn("Error adding DAA to Library Card", e); } } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardWithDaaReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardWithDaaReducer.java index c77b035116..de5ae9d667 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardWithDaaReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/LibraryCardWithDaaReducer.java @@ -7,14 +7,14 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -public class LibraryCardWithDaaReducer implements LinkedHashMapRowReducer, - RowMapperHelper { +public class LibraryCardWithDaaReducer + implements LinkedHashMapRowReducer, RowMapperHelper { @Override public void accumulate(Map map, RowView rowView) { - LibraryCard card = map.computeIfAbsent( - rowView.getColumn("id", Integer.class), - id -> rowView.getRow(LibraryCard.class)); + LibraryCard card = + map.computeIfAbsent( + rowView.getColumn("id", Integer.class), id -> rowView.getRow(LibraryCard.class)); DataAccessAgreement daa = new DataAccessAgreement(); try { @@ -30,4 +30,4 @@ public void accumulate(Map map, RowView rowView) { card.addDaaObject(daa); } } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/MatchReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/MatchReducer.java index f3c05325f1..9d12a1a894 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/MatchReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/MatchReducer.java @@ -10,11 +10,13 @@ public class MatchReducer implements LinkedHashMapRowReducer, Ro @Override public void accumulate(Map map, RowView rowView) { - Match match = map.computeIfAbsent(rowView.getColumn("match_id", Integer.class), - id -> rowView.getRow(Match.class)); + Match match = + map.computeIfAbsent( + rowView.getColumn("match_id", Integer.class), id -> rowView.getRow(Match.class)); hasOptionalColumn(rowView, "consent", String.class).ifPresent(match::setConsent); hasOptionalColumn(rowView, "purpose", String.class).ifPresent(match::setPurpose); - hasOptionalColumn(rowView, "algorithm_version", String.class).ifPresent(match::setAlgorithmVersion); + hasOptionalColumn(rowView, "algorithm_version", String.class) + .ifPresent(match::setAlgorithmVersion); hasOptionalColumn(rowView, "match_entity", Boolean.class).ifPresent(match::setMatch); hasOptionalColumn(rowView, "abstain", Boolean.class).ifPresent(match::setAbstain); hasOptionalColumn(rowView, "failed", Boolean.class).ifPresent(match::setFailed); diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/RowMapperHelper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/RowMapperHelper.java index 34e17c8cab..5078e67f4a 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/RowMapperHelper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/RowMapperHelper.java @@ -41,7 +41,8 @@ default boolean hasColumn(RowView rowView, String columnName, Class clazz) { */ default boolean hasNonZeroColumn(RowView rowView, String columnName) { try { - return rowView.getColumn(columnName, Integer.class) != null && rowView.getColumn(columnName, Integer.class) > 0; + return rowView.getColumn(columnName, Integer.class) != null + && rowView.getColumn(columnName, Integer.class) > 0; } catch (Exception e) { logDebug("RowView does not contain column %s".formatted(columnName)); return false; @@ -68,7 +69,7 @@ default Optional hasOptionalColumn(RowView rowView, String columnName, Cl /** * Utility method to check if a column exists in the result set or not. * - * @param rs The ResultSet + * @param rs The ResultSet * @param columnName The column name * @return True if column name exists, false otherwise * @throws SQLException The exception @@ -104,7 +105,6 @@ default boolean hasNonZeroColumn(ResultSet rs, String columnName) throws SQLExce return false; } - static String unescapeJava(String value) { return StringEscapeUtils.unescapeJava(StringEscapeUtils.unescapeJava(value)); } @@ -126,22 +126,25 @@ default DataAccessRequestData translate(String darDataString) { return data; } - default void setStringFieldValue(ResultSet resultSet, String columnName, - java.util.function.Consumer setter) throws SQLException { + default void setStringFieldValue( + ResultSet resultSet, String columnName, java.util.function.Consumer setter) + throws SQLException { if (hasColumn(resultSet, columnName)) { setter.accept(resultSet.getString(columnName)); } } - default void setNonZeroFieldValue(ResultSet resultSet, String columnName, - java.util.function.IntConsumer setter) throws SQLException { + default void setNonZeroFieldValue( + ResultSet resultSet, String columnName, java.util.function.IntConsumer setter) + throws SQLException { if (hasNonZeroColumn(resultSet, columnName)) { setter.accept(resultSet.getInt(columnName)); } } - default void setDateFieldValue(ResultSet resultSet, String columnName, - java.util.function.Consumer setter) throws SQLException { + default void setDateFieldValue( + ResultSet resultSet, String columnName, java.util.function.Consumer setter) + throws SQLException { if (hasColumn(resultSet, columnName)) { setter.accept(resultSet.getDate(columnName)); } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/SimpleElectionMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/SimpleElectionMapper.java index f4cff89fa1..6106c060b7 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/SimpleElectionMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/SimpleElectionMapper.java @@ -11,20 +11,21 @@ public class SimpleElectionMapper implements RowMapper, RowMapperHelpe @Override public Election map(ResultSet r, StatementContext ctx) throws SQLException { - Election e = new Election( - r.getInt(ElectionFields.ID.getValue()), - r.getString(ElectionFields.TYPE.getValue()), - r.getString(ElectionFields.STATUS.getValue()), - r.getDate(ElectionFields.CREATE_DATE.getValue()), - r.getString(ElectionFields.REFERENCE_ID.getValue()), - r.getDate(ElectionFields.LAST_UPDATE.getValue()), - (r.getString(ElectionFields.FINAL_ACCESS_VOTE.getValue()) == null) - ? null - : r.getBoolean(ElectionFields.FINAL_ACCESS_VOTE.getValue()), - r.getInt(ElectionFields.DATASET_ID.getValue()), - r.getBoolean(ElectionFields.ARCHIVED.getValue()), - r.getString(ElectionFields.DUL_NAME.getValue()), - r.getString(ElectionFields.DATA_USE_LETTER.getValue())); + Election e = + new Election( + r.getInt(ElectionFields.ID.getValue()), + r.getString(ElectionFields.TYPE.getValue()), + r.getString(ElectionFields.STATUS.getValue()), + r.getDate(ElectionFields.CREATE_DATE.getValue()), + r.getString(ElectionFields.REFERENCE_ID.getValue()), + r.getDate(ElectionFields.LAST_UPDATE.getValue()), + (r.getString(ElectionFields.FINAL_ACCESS_VOTE.getValue()) == null) + ? null + : r.getBoolean(ElectionFields.FINAL_ACCESS_VOTE.getValue()), + r.getInt(ElectionFields.DATASET_ID.getValue()), + r.getBoolean(ElectionFields.ARCHIVED.getValue()), + r.getString(ElectionFields.DUL_NAME.getValue()), + r.getString(ElectionFields.DATA_USE_LETTER.getValue())); if (hasColumn(r, ElectionFields.FINAL_VOTE.getValue())) { if (r.getString(ElectionFields.FINAL_VOTE.getValue()) != null) { e.setFinalVote(r.getBoolean(ElectionFields.FINAL_VOTE.getValue())); diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/StudyReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/StudyReducer.java index 69fb5d7014..7196e10f79 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/StudyReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/StudyReducer.java @@ -53,8 +53,7 @@ public void reduceStudy(Study study, RowView rowView) { } if (hasNonZeroColumn(rowView, "fso_file_storage_object_id") - && Objects.nonNull(rowView.getColumn("fso_file_storage_object_id", Integer.class)) - ) { + && Objects.nonNull(rowView.getColumn("fso_file_storage_object_id", Integer.class))) { FileStorageObject fileStorageObject = rowView.getRow(FileStorageObject.class); switch (fileStorageObject.getCategory()) { @@ -63,14 +62,13 @@ public void reduceStudy(Study study, RowView rowView) { study.setAlternativeDataSharingPlan(fileStorageObject); } } - default -> { - } + default -> {} } } } private boolean isFileNewer(FileStorageObject incomingFile, FileStorageObject existingFile) { - return Objects.isNull(existingFile) || incomingFile.getLatestUpdateDate() - .isAfter(existingFile.getLatestUpdateDate()); + return Objects.isNull(existingFile) + || incomingFile.getLatestUpdateDate().isAfter(existingFile.getLatestUpdateDate()); } } diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/UserPropertyMapper.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/UserPropertyMapper.java index cf3e758895..7958f4c37f 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/UserPropertyMapper.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/UserPropertyMapper.java @@ -9,8 +9,7 @@ public class UserPropertyMapper implements RowMapper { @Override - public UserProperty map(ResultSet r, StatementContext statementContext) - throws SQLException { + public UserProperty map(ResultSet r, StatementContext statementContext) throws SQLException { return new UserProperty( r.getInt("property_id"), r.getInt("user_id"), diff --git a/src/main/java/org/broadinstitute/consent/http/db/mapper/UserWithRolesReducer.java b/src/main/java/org/broadinstitute/consent/http/db/mapper/UserWithRolesReducer.java index a8684862a9..cff6aec4a6 100644 --- a/src/main/java/org/broadinstitute/consent/http/db/mapper/UserWithRolesReducer.java +++ b/src/main/java/org/broadinstitute/consent/http/db/mapper/UserWithRolesReducer.java @@ -11,11 +11,9 @@ import org.jdbi.v3.core.result.LinkedHashMapRowReducer; import org.jdbi.v3.core.result.RowView; -/** - * This class works well for individual Users as well as collections. - */ -public class UserWithRolesReducer implements LinkedHashMapRowReducer, - RowMapperHelper { +/** This class works well for individual Users as well as collections. */ +public class UserWithRolesReducer + implements LinkedHashMapRowReducer, RowMapperHelper { @Override public void accumulate(Map map, RowView rowView) { @@ -26,10 +24,7 @@ public void accumulate(Map map, RowView rowView) { } else if (hasNonZeroColumn(rowView, "u_user_id")) { userId = rowView.getColumn("u_user_id", Integer.class); } - User user = - map.computeIfAbsent( - userId, - id -> rowView.getRow(User.class)); + User user = map.computeIfAbsent(userId, id -> rowView.getRow(User.class)); try { UserRole userRole = mapUserRoleFromRowView(rowView, userId); @@ -50,9 +45,9 @@ public void accumulate(Map map, RowView rowView) { } catch (MappingException e) { logDebug("Error adding Institution to User: %s".formatted(e.getMessage())); } - //user role join can cause duplication of data if done in tandem with joins on other tables - //ex) The same LC can end up being repeated multiple times - //Below only adds LC if not currently saved on the array + // user role join can cause duplication of data if done in tandem with joins on other tables + // ex) The same LC can end up being repeated multiple times + // Below only adds LC if not currently saved on the array try { if (rowView.getColumn("lc_id", Integer.class) != null) { LibraryCard lc = rowView.getRow(LibraryCard.class); diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/DarDocumentType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/DarDocumentType.java index 4095f40ea8..fc684d9267 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/DarDocumentType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/DarDocumentType.java @@ -1,5 +1,6 @@ package org.broadinstitute.consent.http.enumeration; public enum DarDocumentType { - IRB, COLLABORATION; + IRB, + COLLABORATION; } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/DraftType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/DraftType.java index a6b2a312d5..773236c16c 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/DraftType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/DraftType.java @@ -14,8 +14,7 @@ public enum DraftType { private final String value; public static List getValues() { - return Stream.of(DraftType.values()).map(DraftType::getValue) - .collect(Collectors.toList()); + return Stream.of(DraftType.values()).map(DraftType::getValue).collect(Collectors.toList()); } DraftType(String value) { @@ -27,10 +26,10 @@ public String getValue() { } public static DraftType fromValue(String value) { - Optional type = EnumSet.allOf(DraftType.class). - stream(). - filter(t -> t.getValue().equalsIgnoreCase(value)). - findFirst(); + Optional type = + EnumSet.allOf(DraftType.class).stream() + .filter(t -> t.getValue().equalsIgnoreCase(value)) + .findFirst(); return type.orElse(null); } } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionFields.java b/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionFields.java index 26189ba54e..52ef0d5f57 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionFields.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionFields.java @@ -1,7 +1,6 @@ package org.broadinstitute.consent.http.enumeration; public enum ElectionFields { - ID("election_id"), TYPE("election_type"), STATUS("status"), @@ -27,5 +26,4 @@ public enum ElectionFields { public String getValue() { return value; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionStatus.java b/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionStatus.java index bf64e855ad..472d56eab8 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionStatus.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionStatus.java @@ -1,9 +1,11 @@ package org.broadinstitute.consent.http.enumeration; public enum ElectionStatus { - - OPEN("Open"), CLOSED("Closed"), CANCELED("Canceled"), FINAL("Final"), PENDING_APPROVAL( - "PendingApproval"); + OPEN("Open"), + CLOSED("Closed"), + CANCELED("Canceled"), + FINAL("Final"), + PENDING_APPROVAL("PendingApproval"); private final String value; @@ -40,8 +42,7 @@ public static String getValues() { values.append(","); } String valuesResult = values.toString(); - //removing the las "," + // removing the las "," return valuesResult.substring(0, valuesResult.length() - 1); } - -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionType.java index 79f2918d66..195d9361e2 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/ElectionType.java @@ -4,7 +4,6 @@ import java.util.Optional; public enum ElectionType { - DATA_ACCESS("DataAccess"), TRANSLATE_DUL("TranslateDUL"), RP("RP"), @@ -30,11 +29,10 @@ public static String getValue(String value) { } public static ElectionType getFromValue(String value) { - Optional type = EnumSet.allOf(ElectionType.class). - stream(). - filter(t -> t.getValue().equalsIgnoreCase(value)). - findFirst(); + Optional type = + EnumSet.allOf(ElectionType.class).stream() + .filter(t -> t.getValue().equalsIgnoreCase(value)) + .findFirst(); return type.orElse(null); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/EmailType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/EmailType.java index ade1e8b373..ed50e7fbdf 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/EmailType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/EmailType.java @@ -1,7 +1,6 @@ package org.broadinstitute.consent.http.enumeration; public enum EmailType { - COLLECT(1), NEW_CASE(2, "new-case.html"), REMINDER(3, "reminder.html"), @@ -33,7 +32,8 @@ public enum EmailType { SO_DAR_APPROVED(29, "so-dar-approved.html"), SO_PROGRESS_REPORT_SUBMITTED(30, "so-progress-report-submitted.html"), SO_PROGRESS_REPORT_APPROVED(31, "so-progress-report-approved.html"), - DAC_RADAR_APPROVED(32, "dac-radar-approved.html"),; + DAC_RADAR_APPROVED(32, "dac-radar-approved.html"), + ; private final Integer typeInt; public final String templateName; diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/FileCategory.java b/src/main/java/org/broadinstitute/consent/http/enumeration/FileCategory.java index 59f9c220be..abbf2dfe62 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/FileCategory.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/FileCategory.java @@ -6,7 +6,6 @@ import java.util.stream.Stream; public enum FileCategory { - @SerializedName("irbCollaborationLetter") IRB_COLLABORATION_LETTER("irbCollaborationLetter"), @SerializedName("dataUseLetter") @@ -31,7 +30,8 @@ public String getValue() { } public static List getValues() { - return Stream.of(FileCategory.values()).map(FileCategory::getValue) + return Stream.of(FileCategory.values()) + .map(FileCategory::getValue) .collect(Collectors.toList()); } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderDAR.java b/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderDAR.java index b7d5206ed2..edcf42ceb0 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderDAR.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderDAR.java @@ -1,7 +1,6 @@ package org.broadinstitute.consent.http.enumeration; public enum HeaderDAR { - DAR_ID("DAR ID"), DATASET_NAME("Dataset name"), DATASET_ID("Dataset ID"), @@ -20,7 +19,6 @@ public enum HeaderDAR { USERNAME("Username"), NAME("Name"); - private final String value; HeaderDAR(String value) { @@ -30,5 +28,4 @@ public enum HeaderDAR { public String getValue() { return value; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderSummary.java b/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderSummary.java index f033c601dc..1a69ef5ba8 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderSummary.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/HeaderSummary.java @@ -1,8 +1,6 @@ package org.broadinstitute.consent.http.enumeration; public enum HeaderSummary { - - CONSENT("Consent"), VERSION("Version"), STATUS("Status"), @@ -49,5 +47,4 @@ public enum HeaderSummary { public String getValue() { return value; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/OrganizationType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/OrganizationType.java index 88d3d23242..85b7d3aabd 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/OrganizationType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/OrganizationType.java @@ -19,7 +19,6 @@ public static OrganizationType getOrganizationTypeFromString(String value) { return null; } - public String getValue() { return value; } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/PropertyType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/PropertyType.java index 883c616a9d..c94579439a 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/PropertyType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/PropertyType.java @@ -91,4 +91,4 @@ public static JsonElement coerceToJson(String value) throws IllegalArgumentExcep throw new IllegalArgumentException("Could not parse as Json: " + e.getMessage()); } } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/SupportRequestType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/SupportRequestType.java index e44cf9e0ec..2f224ebf75 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/SupportRequestType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/SupportRequestType.java @@ -1,7 +1,8 @@ package org.broadinstitute.consent.http.enumeration; public enum SupportRequestType { - - QUESTION, BUG, FEATURE_REQUEST, TASK - + QUESTION, + BUG, + FEATURE_REQUEST, + TASK } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/UserRoles.java b/src/main/java/org/broadinstitute/consent/http/enumeration/UserRoles.java index c9ee7aa643..c816bd299e 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/UserRoles.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/UserRoles.java @@ -7,7 +7,6 @@ import org.broadinstitute.consent.http.resources.Resource; public enum UserRoles { - MEMBER(Resource.MEMBER, 1), CHAIRPERSON(Resource.CHAIRPERSON, 2), ALUMNI(Resource.ALUMNI, 3), @@ -19,8 +18,8 @@ public enum UserRoles { SERVICE_ACCOUNT(Resource.SERVICE_ACCOUNT, 10); private static final Set NON_DAC_ROLES = - Set.of(ALUMNI, ADMIN, RESEARCHER, SIGNINGOFFICIAL, DATASUBMITTER, ITDIRECTOR, - SERVICE_ACCOUNT); + Set.of( + ALUMNI, ADMIN, RESEARCHER, SIGNINGOFFICIAL, DATASUBMITTER, ITDIRECTOR, SERVICE_ACCOUNT); private static final Set SO_AUTHORIZED_ROLES_TO_ADJUST = Set.of(ITDIRECTOR, SIGNINGOFFICIAL, DATASUBMITTER); private final String roleName; @@ -89,8 +88,7 @@ public static boolean isValidRole(String roleName) { if (Objects.isNull(roleName)) { return false; } - return EnumSet.allOf(UserRoles.class) - .stream() + return EnumSet.allOf(UserRoles.class).stream() .map(UserRoles::getRoleName) .anyMatch(roleName::equalsIgnoreCase); } @@ -110,5 +108,4 @@ public String getRoleName() { public Integer getRoleId() { return roleId; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/enumeration/VoteType.java b/src/main/java/org/broadinstitute/consent/http/enumeration/VoteType.java index 44d28587f0..fa1c0bedc6 100644 --- a/src/main/java/org/broadinstitute/consent/http/enumeration/VoteType.java +++ b/src/main/java/org/broadinstitute/consent/http/enumeration/VoteType.java @@ -3,8 +3,11 @@ import org.broadinstitute.consent.http.resources.Resource; public enum VoteType { - - DAC("DAC"), FINAL("FINAL"), RADAR_APPROVE("RADAR_APPROVE"), AGREEMENT("AGREEMENT"), CHAIRPERSON(Resource.CHAIRPERSON); + DAC("DAC"), + FINAL("FINAL"), + RADAR_APPROVE("RADAR_APPROVE"), + AGREEMENT("AGREEMENT"), + CHAIRPERSON(Resource.CHAIRPERSON); private final String value; @@ -24,6 +27,4 @@ public static String getValue(String value) { } return null; } - - } diff --git a/src/main/java/org/broadinstitute/consent/http/exceptions/LibraryCardRequiredException.java b/src/main/java/org/broadinstitute/consent/http/exceptions/LibraryCardRequiredException.java index d6efde7284..e6168f3606 100644 --- a/src/main/java/org/broadinstitute/consent/http/exceptions/LibraryCardRequiredException.java +++ b/src/main/java/org/broadinstitute/consent/http/exceptions/LibraryCardRequiredException.java @@ -1,7 +1,9 @@ package org.broadinstitute.consent.http.exceptions; -public class LibraryCardRequiredException extends UnprocessableEntityException{ - public static final String MESSAGE = "Please register in DUOS with your institution's email and obtain a library card from your Signing Official in order to submit a data access request."; +public class LibraryCardRequiredException extends UnprocessableEntityException { + public static final String MESSAGE = + "Please register in DUOS with your institution's email and obtain a library card from your Signing Official in order to submit a data access request."; + public LibraryCardRequiredException() { super(MESSAGE); } diff --git a/src/main/java/org/broadinstitute/consent/http/exceptions/NIHComplianceRuleException.java b/src/main/java/org/broadinstitute/consent/http/exceptions/NIHComplianceRuleException.java index 1049ff47fe..4894a60c03 100644 --- a/src/main/java/org/broadinstitute/consent/http/exceptions/NIHComplianceRuleException.java +++ b/src/main/java/org/broadinstitute/consent/http/exceptions/NIHComplianceRuleException.java @@ -5,7 +5,8 @@ public class NIHComplianceRuleException extends ClientErrorException { - public static final String MESSAGE = "NIH has received, reviewed, and processed your data access request. This request is denied. Please see Guide Notice [NOT-OD-25-083](https://grants.nih.gov/grants/guide/notice-files/NOT-OD-25-083.html) for more information."; + public static final String MESSAGE = + "NIH has received, reviewed, and processed your data access request. This request is denied. Please see Guide Notice [NOT-OD-25-083](https://grants.nih.gov/grants/guide/notice-files/NOT-OD-25-083.html) for more information."; public NIHComplianceRuleException() { super(MESSAGE, HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY); diff --git a/src/main/java/org/broadinstitute/consent/http/exceptions/SubmittedDARCannotBeEditedException.java b/src/main/java/org/broadinstitute/consent/http/exceptions/SubmittedDARCannotBeEditedException.java index 3f533b3e6f..0751e2eb87 100644 --- a/src/main/java/org/broadinstitute/consent/http/exceptions/SubmittedDARCannotBeEditedException.java +++ b/src/main/java/org/broadinstitute/consent/http/exceptions/SubmittedDARCannotBeEditedException.java @@ -2,7 +2,8 @@ public class SubmittedDARCannotBeEditedException extends UnprocessableEntityException { - public static final String MESSAGE = "This data access request is already submitted for DAC consideration and cannot be edited."; + public static final String MESSAGE = + "This data access request is already submitted for DAC consideration and cannot be edited."; public SubmittedDARCannotBeEditedException() { super(MESSAGE); diff --git a/src/main/java/org/broadinstitute/consent/http/exceptions/UnknownIdentifierException.java b/src/main/java/org/broadinstitute/consent/http/exceptions/UnknownIdentifierException.java index 7e8f4598fb..b5feaa0c04 100644 --- a/src/main/java/org/broadinstitute/consent/http/exceptions/UnknownIdentifierException.java +++ b/src/main/java/org/broadinstitute/consent/http/exceptions/UnknownIdentifierException.java @@ -12,5 +12,4 @@ public UnknownIdentifierException(String id) { public String getId() { return id; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/exceptions/UnprocessableEntityException.java b/src/main/java/org/broadinstitute/consent/http/exceptions/UnprocessableEntityException.java index 5f8330bf85..1923f877a8 100644 --- a/src/main/java/org/broadinstitute/consent/http/exceptions/UnprocessableEntityException.java +++ b/src/main/java/org/broadinstitute/consent/http/exceptions/UnprocessableEntityException.java @@ -8,5 +8,4 @@ public class UnprocessableEntityException extends ClientErrorException { public UnprocessableEntityException(String message) { super(message, HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/filters/ClaimsCache.java b/src/main/java/org/broadinstitute/consent/http/filters/ClaimsCache.java index 610a2cb820..933c399be1 100644 --- a/src/main/java/org/broadinstitute/consent/http/filters/ClaimsCache.java +++ b/src/main/java/org/broadinstitute/consent/http/filters/ClaimsCache.java @@ -11,8 +11,8 @@ import java.util.stream.Collectors; /** - * Manage a cache of bearer token to map of `OAUTH2_CLAIM` headers for every request. This is - * useful in cases where components need, but do not have access to, the full request context. + * Manage a cache of bearer token to map of `OAUTH2_CLAIM` headers for every request. This is useful + * in cases where components need, but do not have access to, the full request context. */ public class ClaimsCache { @@ -24,10 +24,7 @@ public class ClaimsCache { public static final String OAUTH2_CLAIM_aud = "OAUTH2_CLAIM_aud"; private ClaimsCache() { - cache = CacheBuilder - .newBuilder() - .expireAfterWrite(5, TimeUnit.MINUTES) - .build(); + cache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build(); } public static ClaimsCache getInstance() { @@ -46,14 +43,13 @@ private String getFirst(List headerValues) { public void loadCache(String token, MultivaluedMap headers) { if (this.cache.getIfPresent(token) == null) { - Map claimsMap = headers.entrySet() - .stream() - .filter(e -> e.getKey().startsWith("OAUTH2_CLAIM")) - .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), getFirst(e.getValue()))) - .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + Map claimsMap = + headers.entrySet().stream() + .filter(e -> e.getKey().startsWith("OAUTH2_CLAIM")) + .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), getFirst(e.getValue()))) + .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); this.cache.put(token, claimsMap); this.cache.cleanUp(); } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/filters/ResponseServerFilter.java b/src/main/java/org/broadinstitute/consent/http/filters/ResponseServerFilter.java index d39235ab48..1a5e9fdcc6 100644 --- a/src/main/java/org/broadinstitute/consent/http/filters/ResponseServerFilter.java +++ b/src/main/java/org/broadinstitute/consent/http/filters/ResponseServerFilter.java @@ -11,8 +11,8 @@ public class ResponseServerFilter implements ContainerResponseFilter { @Override public void filter( - ContainerRequestContext requestContext, - ContainerResponseContext responseContext) throws IOException { + ContainerRequestContext requestContext, ContainerResponseContext responseContext) + throws IOException { // When the no-sniff header is on the swagger-ui files, it breaks the overall UI if (!requestContext.getUriInfo().getPath().contains("swagger-ui")) { responseContext.getHeaders().add("X-Content-Type-Options", "nosniff"); diff --git a/src/main/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheck.java b/src/main/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheck.java index c41f425ab5..5e02d56aab 100644 --- a/src/main/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheck.java +++ b/src/main/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheck.java @@ -22,8 +22,7 @@ public class ElasticSearchHealthCheck extends HealthCheck implements Managed { private final RestClient client; @Override - public void start() throws Exception { - } + public void start() throws Exception {} @Override public void stop() throws Exception { @@ -49,8 +48,8 @@ protected Result check() throws Exception { return Result.unhealthy( "Invalid health check request: " + esResponse.getStatusLine().getReasonPhrase()); } - String stringResponse = IOUtils.toString(esResponse.getEntity().getContent(), - Charset.defaultCharset()); + String stringResponse = + IOUtils.toString(esResponse.getEntity().getContent(), Charset.defaultCharset()); JsonObject jsonResponse = JsonParser.parseString(stringResponse).getAsJsonObject(); String status = jsonResponse.get("status").getAsString(); if (status.equalsIgnoreCase("red")) { diff --git a/src/main/java/org/broadinstitute/consent/http/health/GCSHealthCheck.java b/src/main/java/org/broadinstitute/consent/http/health/GCSHealthCheck.java index 3ccc514546..1139e5b92f 100644 --- a/src/main/java/org/broadinstitute/consent/http/health/GCSHealthCheck.java +++ b/src/main/java/org/broadinstitute/consent/http/health/GCSHealthCheck.java @@ -25,8 +25,8 @@ protected Result check() { return Result.unhealthy("GCS bucket unreachable or does not exist: " + e.getMessage()); } - return (bucket != null) ? Result.healthy() + return (bucket != null) + ? Result.healthy() : Result.unhealthy("GCS bucket unreachable or does not exist."); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/health/OntologyHealthCheck.java b/src/main/java/org/broadinstitute/consent/http/health/OntologyHealthCheck.java index 4061774d2c..34317968e7 100644 --- a/src/main/java/org/broadinstitute/consent/http/health/OntologyHealthCheck.java +++ b/src/main/java/org/broadinstitute/consent/http/health/OntologyHealthCheck.java @@ -50,10 +50,8 @@ public Result check() { } @Override - public void start() { - } + public void start() {} @Override - public void stop() { - } + public void stop() {} } diff --git a/src/main/java/org/broadinstitute/consent/http/health/SamHealthCheck.java b/src/main/java/org/broadinstitute/consent/http/health/SamHealthCheck.java index 7f06ce07eb..7e5408e17f 100644 --- a/src/main/java/org/broadinstitute/consent/http/health/SamHealthCheck.java +++ b/src/main/java/org/broadinstitute/consent/http/health/SamHealthCheck.java @@ -49,12 +49,10 @@ protected Result check() throws Exception { } @Override - public void start() throws Exception { - } + public void start() throws Exception {} @Override - public void stop() throws Exception { - } + public void stop() throws Exception {} private static class SamStatus { diff --git a/src/main/java/org/broadinstitute/consent/http/health/SendGridHealthCheck.java b/src/main/java/org/broadinstitute/consent/http/health/SendGridHealthCheck.java index 46573c31a2..4385e72f89 100644 --- a/src/main/java/org/broadinstitute/consent/http/health/SendGridHealthCheck.java +++ b/src/main/java/org/broadinstitute/consent/http/health/SendGridHealthCheck.java @@ -44,10 +44,8 @@ protected Result check() throws Exception { } @Override - public void start() throws Exception { - } + public void start() throws Exception {} @Override - public void stop() throws Exception { - } + public void stop() throws Exception {} } diff --git a/src/main/java/org/broadinstitute/consent/http/health/SendGridStatus.java b/src/main/java/org/broadinstitute/consent/http/health/SendGridStatus.java index 84175e0968..eeac354725 100644 --- a/src/main/java/org/broadinstitute/consent/http/health/SendGridStatus.java +++ b/src/main/java/org/broadinstitute/consent/http/health/SendGridStatus.java @@ -27,11 +27,8 @@ public Result getResult() { Result result; if (status.getIndicator() == Indicator.none) { - result = Result.builder() - .withDetail("page", page) - .withDetail("status", status) - .healthy() - .build(); + result = + Result.builder().withDetail("page", page).withDetail("status", status).healthy().build(); } else { result = Result.unhealthy("SendGrid status is unhealthy: " + status.getDescription()); } @@ -40,7 +37,10 @@ public Result getResult() { } enum Indicator { - none, minor, major, critical + none, + minor, + major, + critical } static class StatusObject { @@ -69,4 +69,4 @@ public void setDescription(String description) { this.description = description; } } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessage.java index f643b7b913..53e23112b2 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessage.java @@ -8,13 +8,19 @@ public class DACMembersDARRADARApprovedMessage extends MailMessage { - private static final String SUBJECT = "Broad Data Use Oversight System - Data Access Committee - Data Access Request %s is Rule Automated DAR (RADAR) Approved"; + private static final String SUBJECT = + "Broad Data Use Oversight System - Data Access Committee - Data Access Request %s is Rule Automated DAR (RADAR) Approved"; private final String darCode; private final User researcher; private final String referenceId; private final List datasets; - public DACMembersDARRADARApprovedMessage(User toUser, String darCode, User researcher, String referenceId, List datasets) { + public DACMembersDARRADARApprovedMessage( + User toUser, + String darCode, + User researcher, + String referenceId, + List datasets) { super(toUser, EmailType.DAC_RADAR_APPROVED); this.darCode = darCode; this.researcher = researcher; diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessage.java index 141d3fd6df..8298453847 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessage.java @@ -5,7 +5,8 @@ import org.broadinstitute.consent.http.models.User; public class DaaRequestMessage extends MailMessage { - private static final String NEW_DAA_LIBRARY_CARD_REQUEST = "New DAA-Library Card Relationship Request in DUOS"; + private static final String NEW_DAA_LIBRARY_CARD_REQUEST = + "New DAA-Library Card Relationship Request in DUOS"; private final User requestUser; private final String daaName; private final Integer daaId; @@ -24,10 +25,15 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("serverUrl", serverUrl, - "daaName", daaName, - "userName", requestUser.getDisplayName(), - "signingOfficialUserName", toUser.getDisplayName()); + return Map.of( + "serverUrl", + serverUrl, + "daaName", + daaName, + "userName", + requestUser.getDisplayName(), + "signingOfficialUserName", + toUser.getDisplayName()); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessage.java index f583bd6c4f..46040f1207 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessage.java @@ -22,9 +22,7 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("userName", toUser.getDisplayName(), - "darCode", darCode, - "serverUrl", serverUrl); + return Map.of("userName", toUser.getDisplayName(), "darCode", darCode, "serverUrl", serverUrl); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpiredMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpiredMessage.java index 838bea7ad2..35d836f9cb 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpiredMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/DarExpiredMessage.java @@ -22,8 +22,7 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("researcherName", toUser.getDisplayName(), - "darCode", darCode); + return Map.of("researcherName", toUser.getDisplayName(), "darCode", darCode); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetApprovedMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetApprovedMessage.java index f8c94c65c2..8c30e5cc80 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetApprovedMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetApprovedMessage.java @@ -23,9 +23,13 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("dataSubmitterName", toUser.getDisplayName(), - "datasetName", datasetName, - "dacName", dacName); + return Map.of( + "dataSubmitterName", + toUser.getDisplayName(), + "datasetName", + datasetName, + "dacName", + dacName); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetDeniedMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetDeniedMessage.java index 4f26450f35..9705fc5270 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetDeniedMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetDeniedMessage.java @@ -26,10 +26,15 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("dataSubmitterName", toUser.getDisplayName(), - "datasetName", datasetName, - "dacName", dacName, - "dacEmail", dacEmail); + return Map.of( + "dataSubmitterName", + toUser.getDisplayName(), + "datasetName", + datasetName, + "dacName", + dacName, + "dacEmail", + dacEmail); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessage.java index 396f55505c..36b06a31fb 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessage.java @@ -6,14 +6,15 @@ public class DatasetSubmittedMessage extends MailMessage { - private static final String DATASET_SUBMITTED = "Decision Needed: Accept or Reject Dataset Management Request"; + private static final String DATASET_SUBMITTED = + "Decision Needed: Accept or Reject Dataset Management Request"; private final String dataSubmitterName; private final String datasetName; private final String dacName; - public DatasetSubmittedMessage(User dacChair, String dataSubmitterName, String datasetName, - String dacName) { + public DatasetSubmittedMessage( + User dacChair, String dataSubmitterName, String datasetName, String dacName) { super(dacChair, EmailType.NEW_DATASET); this.dataSubmitterName = dataSubmitterName; this.datasetName = datasetName; @@ -27,10 +28,15 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("dacChairName", toUser.getDisplayName(), - "dataSubmitterName", dataSubmitterName, - "datasetName", datasetName, - "dacName", dacName); + return Map.of( + "dacChairName", + toUser.getDisplayName(), + "dataSubmitterName", + dataSubmitterName, + "datasetName", + datasetName, + "dacName", + dacName); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/NewCaseMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/NewCaseMessage.java index 38d4109d26..4f334414fa 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/NewCaseMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/NewCaseMessage.java @@ -28,10 +28,15 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("userName", toUser.getDisplayName(), - "electionType", type, - "entityName", referenceId, - "serverUrl", serverUrl); + return Map.of( + "userName", + toUser.getDisplayName(), + "electionType", + type, + "entityName", + referenceId, + "serverUrl", + serverUrl); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessage.java index b7c8e0506a..fe22d06a99 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessage.java @@ -27,11 +27,17 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("serverUrl", serverUrl, - "dacName", dacName, - "researcherUserName", toUser.getDisplayName(), - "previousDaaName", previousDaaName, - "newDaaName", newDaaName); + return Map.of( + "serverUrl", + serverUrl, + "dacName", + dacName, + "researcherUserName", + toUser.getDisplayName(), + "previousDaaName", + previousDaaName, + "newDaaName", + newDaaName); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessage.java index 57cc7e93ea..36ff23ceb6 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessage.java @@ -26,11 +26,17 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("serverUrl", serverUrl, - "dacName", dacName, - "signingOfficialUserName", toUser.getDisplayName(), - "previousDaaName", previousDaaName, - "newDaaName", newDaaName); + return Map.of( + "serverUrl", + serverUrl, + "dacName", + dacName, + "signingOfficialUserName", + toUser.getDisplayName(), + "previousDaaName", + previousDaaName, + "newDaaName", + newDaaName); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessage.java index 966f23a3be..134a4f73cc 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessage.java @@ -7,14 +7,15 @@ public class NewDARRequestMessage extends MailMessage { - private static final String NEW_DAR_REQUEST = "Create an election for Data Access Request id: %s."; + private static final String NEW_DAR_REQUEST = + "Create an election for Data Access Request id: %s."; private final String darCode; private final Map> dacDatasetMap; private final String researcherName; - public NewDARRequestMessage(User toUser, String darCode, Map> dacDatasetMap, - String researcherName) { + public NewDARRequestMessage( + User toUser, String darCode, Map> dacDatasetMap, String researcherName) { super(toUser, EmailType.NEW_DAR); this.darCode = darCode; this.dacDatasetMap = dacDatasetMap; diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessage.java index 339bd5ff64..5a5d44dbe2 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessage.java @@ -18,10 +18,7 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of( - "linkUrl", serverUrl + "datalibrary", - "displayName", toUser.getDisplayName() - ); + return Map.of("linkUrl", serverUrl + "datalibrary", "displayName", toUser.getDisplayName()); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessage.java index d0803fd65a..0eb61f6d22 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessage.java @@ -21,9 +21,8 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("userName", toUser.getDisplayName(), - "entityName", referenceId, - "serverUrl", serverUrl); + return Map.of( + "userName", toUser.getDisplayName(), "entityName", referenceId, "serverUrl", serverUrl); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessage.java index f4dc43f41b..770a0ea32f 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessage.java @@ -7,15 +7,19 @@ public class NewProgressReportRequestMessage extends MailMessage { - private static final String NEW_PROGRESS_REPORT_REQUEST = "Create an election for Progress Report id: %s."; + private static final String NEW_PROGRESS_REPORT_REQUEST = + "Create an election for Progress Report id: %s."; private final String darCode; private final Map> dacDatasetMap; private final String researcherName; private final String referenceId; - - public NewProgressReportRequestMessage(User toUser, String darCode, String referenceId, Map> dacDatasetMap, + public NewProgressReportRequestMessage( + User toUser, + String darCode, + String referenceId, + Map> dacDatasetMap, String researcherName) { super(toUser, EmailType.NEW_PROGRESS_REPORT_REQUEST); this.darCode = darCode; diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/ReminderMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/ReminderMessage.java index ed1eaef256..d9bbeeb8c8 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/ReminderMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/ReminderMessage.java @@ -7,16 +7,20 @@ public class ReminderMessage extends MailMessage { - private static final String REMINDER_DUL = "Urgent: Log vote on Data Use Limitations case id: %s."; - private static final String REMINDER_DAR = "Urgent: Log votes on Data Access Request case id: %s."; - private static final String REMINDER_RP = "Urgent: Log votes on Research Purpose Review case id: %s."; + private static final String REMINDER_DUL = + "Urgent: Log vote on Data Use Limitations case id: %s."; + private static final String REMINDER_DAR = + "Urgent: Log votes on Data Access Request case id: %s."; + private static final String REMINDER_RP = + "Urgent: Log votes on Research Purpose Review case id: %s."; private final Vote vote; private final String electionType; private final String darCode; private final String voteUrl; - public ReminderMessage(User toUser, Vote vote, String darCode, String electionType, String voteUrl) { + public ReminderMessage( + User toUser, Vote vote, String darCode, String electionType, String voteUrl) { super(toUser, EmailType.REMINDER); this.vote = vote; this.darCode = darCode; @@ -49,4 +53,4 @@ public String getEntityReferenceId() { public Integer getVoteId() { return vote.getVoteId(); } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherApprovedProgressReportMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherApprovedProgressReportMessage.java index 7401f99d30..d90bcd30f5 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherApprovedProgressReportMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherApprovedProgressReportMessage.java @@ -15,8 +15,12 @@ public class ResearcherApprovedProgressReportMessage extends MailMessage { private final String dataUseRestriction; private final String radarText; - public ResearcherApprovedProgressReportMessage(User toUser, String darCode, List datasets, - String dataUseRestriction, boolean radarApproved) { + public ResearcherApprovedProgressReportMessage( + User toUser, + String darCode, + List datasets, + String dataUseRestriction, + boolean radarApproved) { super(toUser, EmailType.RESEARCHER_PROGRESS_REPORT_APPROVED); this.darCode = darCode; this.datasets = datasets; @@ -31,12 +35,19 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("researcherName", toUser.getDisplayName(), - "darCode", darCode, - "datasets", datasets, - "dataUseRestriction", dataUseRestriction, - "radarText", radarText, - "researcherEmail", toUser.getEmail()); + return Map.of( + "researcherName", + toUser.getDisplayName(), + "darCode", + darCode, + "datasets", + datasets, + "dataUseRestriction", + dataUseRestriction, + "radarText", + radarText, + "researcherEmail", + toUser.getEmail()); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessage.java index 8d04939dd6..053f1d02c5 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessage.java @@ -22,9 +22,7 @@ public String createSubject() { @Override public Object createModel(String serverUrl) { - return Map.of("userName", toUser.getDisplayName(), - "darCode", darCode, - "serverUrl", serverUrl); + return Map.of("userName", toUser.getDisplayName(), "darCode", darCode, "serverUrl", serverUrl); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/SoDARSubmitted.java b/src/main/java/org/broadinstitute/consent/http/mail/message/SoDARSubmitted.java index dfd1b3a7ef..ce149b1a91 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/SoDARSubmitted.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/SoDARSubmitted.java @@ -8,13 +8,15 @@ public class SoDARSubmitted extends MailMessage { - private static final String SUBJECT = "Broad Data Use Oversight System - Signing Official - New Data Access Request Submitted From Your Institution"; + private static final String SUBJECT = + "Broad Data Use Oversight System - Signing Official - New Data Access Request Submitted From Your Institution"; private final String darCode; private final User researcher; private final String referenceId; private final List datasets; - public SoDARSubmitted(User toUser, String darCode, User researcher, String referenceId, List datasets) { + public SoDARSubmitted( + User toUser, String darCode, User researcher, String referenceId, List datasets) { super(toUser, EmailType.SO_DAR_SUBMITTED); this.darCode = darCode; this.researcher = researcher; diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRApproved.java b/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRApproved.java index f2ff83d76b..2f841e3927 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRApproved.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRApproved.java @@ -8,7 +8,8 @@ public class SoPRApproved extends MailMessage { - private static final String SUBJECT = "Broad Data Use Oversight System - Signing Official - Your Institutional Researcher's Progress Report %s is %sApproved"; + private static final String SUBJECT = + "Broad Data Use Oversight System - Signing Official - Your Institutional Researcher's Progress Report %s is %sApproved"; private final String darCode; private final User researcher; private final String referenceId; @@ -16,7 +17,14 @@ public class SoPRApproved extends MailMessage { private final String dataUseRestriction; private final String radarText; - public SoPRApproved(User toUser, String darCode, User researcher, String referenceId, List datasets, String dataUseRestriction, boolean radarApproved) { + public SoPRApproved( + User toUser, + String darCode, + User researcher, + String referenceId, + List datasets, + String dataUseRestriction, + boolean radarApproved) { super(toUser, EmailType.SO_PROGRESS_REPORT_APPROVED); this.darCode = darCode; this.researcher = researcher; @@ -48,5 +56,4 @@ public Object createModel(String serverUrl) { public String getEntityReferenceId() { return referenceId; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRSubmitted.java b/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRSubmitted.java index 6bbe812dee..9745971b9a 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRSubmitted.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/SoPRSubmitted.java @@ -6,15 +6,17 @@ import org.broadinstitute.consent.http.models.Dataset; import org.broadinstitute.consent.http.models.User; -public class SoPRSubmitted extends MailMessage { +public class SoPRSubmitted extends MailMessage { - private static final String SUBJECT = "Broad Data Use Oversight System - Signing Official - New Progress Report Submitted From Your Institution"; + private static final String SUBJECT = + "Broad Data Use Oversight System - Signing Official - New Progress Report Submitted From Your Institution"; private final String darCode; private final User researcher; private final String referenceId; private final List datasets; - public SoPRSubmitted(User toUser, String darCode, User researcher, String referenceId, List datasets) { + public SoPRSubmitted( + User toUser, String darCode, User researcher, String referenceId, List datasets) { super(toUser, EmailType.SO_PROGRESS_REPORT_SUBMITTED); this.darCode = darCode; this.researcher = researcher; diff --git a/src/main/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessage.java b/src/main/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessage.java index 6aa7f4fbbc..d1a0c62177 100644 --- a/src/main/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessage.java @@ -14,7 +14,8 @@ public class SubmittedCloseoutMessage extends MailMessage { private final String closeoutUrl; - public SubmittedCloseoutMessage(User toUser, String darId, String referenceId, String closeoutUrl) { + public SubmittedCloseoutMessage( + User toUser, String darId, String referenceId, String closeoutUrl) { super(toUser, EmailType.SUBMITTED_CLOSEOUT); this.darId = darId; this.referenceId = referenceId; @@ -28,14 +29,11 @@ public String createSubject() { @Override public Object createModel(String linkUrl) { - return Map.of("displayName", toUser.getDisplayName(), - "darId", darId, - "linkUrl", closeoutUrl); + return Map.of("displayName", toUser.getDisplayName(), "darId", darId, "linkUrl", closeoutUrl); } @Override public String getEntityReferenceId() { return referenceId; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Acknowledgement.java b/src/main/java/org/broadinstitute/consent/http/models/Acknowledgement.java index 34d07162d5..c6d5927e58 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Acknowledgement.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Acknowledgement.java @@ -52,9 +52,9 @@ public boolean equals(Object o) { return false; } Acknowledgement ack = (Acknowledgement) o; - return (Objects.equals(this.getAckKey(), ack.getAckKey()) && - Objects.equals(this.getUserId(), ack.getUserId()) && - this.getLastAcknowledged().getTime() == (ack.getLastAcknowledged().getTime()) && - this.getFirstAcknowledged().getTime() == (ack.getFirstAcknowledged()).getTime()); + return (Objects.equals(this.getAckKey(), ack.getAckKey()) + && Objects.equals(this.getUserId(), ack.getUserId()) + && this.getLastAcknowledged().getTime() == (ack.getLastAcknowledged().getTime()) + && this.getFirstAcknowledged().getTime() == (ack.getFirstAcknowledged()).getTime()); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/ApprovedDataset.java b/src/main/java/org/broadinstitute/consent/http/models/ApprovedDataset.java index 3a89e4631e..388bd1cf77 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/ApprovedDataset.java +++ b/src/main/java/org/broadinstitute/consent/http/models/ApprovedDataset.java @@ -11,7 +11,8 @@ public class ApprovedDataset { private String datasetIdentifier; private final Timestamp expirationDate; - public ApprovedDataset(int alias, String darId, String datasetName, String dacName, Timestamp expirationDate) { + public ApprovedDataset( + int alias, String darId, String datasetName, String dacName, Timestamp expirationDate) { this.alias = alias; this.darCode = darId; this.datasetName = datasetName; @@ -64,7 +65,6 @@ public Timestamp getExpirationDate() { return expirationDate; } - public Boolean isApprovedDatasetEqual(ApprovedDataset that) { return this.getAlias() == that.getAlias() && this.getDatasetName().equals(that.getDatasetName()) @@ -72,5 +72,4 @@ public Boolean isApprovedDatasetEqual(ApprovedDataset that) { && this.getDarCode().equals(that.getDarCode()) && this.getDacName().equals(that.getDacName()); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/AuthUser.java b/src/main/java/org/broadinstitute/consent/http/models/AuthUser.java index c37da4387b..10027b71f3 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/AuthUser.java +++ b/src/main/java/org/broadinstitute/consent/http/models/AuthUser.java @@ -15,8 +15,7 @@ public class AuthUser implements Principal { private String aud; private UserStatusInfo userStatusInfo; - public AuthUser() { - } + public AuthUser() {} public AuthUser(AuthUser authUser) { this.authToken = authUser.getAuthToken(); @@ -33,8 +32,8 @@ public AuthUser(String authToken, String email, String name, String aud) { this.aud = aud; } - public AuthUser(String authToken, String email, String name, String aud, - UserStatusInfo userStatusInfo) { + public AuthUser( + String authToken, String email, String name, String aud, UserStatusInfo userStatusInfo) { this.authToken = authToken; this.email = email; this.name = name; diff --git a/src/main/java/org/broadinstitute/consent/http/models/Author.java b/src/main/java/org/broadinstitute/consent/http/models/Author.java index 9fd6aa7ce3..f988395fd6 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Author.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Author.java @@ -1,5 +1,3 @@ package org.broadinstitute.consent.http.models; -public record Author (String name, String orcId) { - -} +public record Author(String name, String orcId) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/AutomationRuleToggleResponse.java b/src/main/java/org/broadinstitute/consent/http/models/AutomationRuleToggleResponse.java index 1b6951aeb4..25af87827b 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/AutomationRuleToggleResponse.java +++ b/src/main/java/org/broadinstitute/consent/http/models/AutomationRuleToggleResponse.java @@ -4,23 +4,18 @@ public final class AutomationRuleToggleResponse { - @JsonProperty - private final int ruleId; + @JsonProperty private final int ruleId; - @JsonProperty - private final boolean isRuleEnabled; + @JsonProperty private final boolean isRuleEnabled; - @JsonProperty - private final long enabledTime; + @JsonProperty private final long enabledTime; - @JsonProperty - private final String displayName; + @JsonProperty private final String displayName; - @JsonProperty - private final String email; + @JsonProperty private final String email; - public AutomationRuleToggleResponse(int id, boolean enabled, long enabledTime, String displayName, - String email) { + public AutomationRuleToggleResponse( + int id, boolean enabled, long enabledTime, String displayName, String email) { this.ruleId = id; this.isRuleEnabled = enabled; this.enabledTime = enabledTime; diff --git a/src/main/java/org/broadinstitute/consent/http/models/CloseoutSupplement.java b/src/main/java/org/broadinstitute/consent/http/models/CloseoutSupplement.java index 49f6810acb..db1099fa07 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/CloseoutSupplement.java +++ b/src/main/java/org/broadinstitute/consent/http/models/CloseoutSupplement.java @@ -2,6 +2,5 @@ import java.util.List; -public record CloseoutSupplement(List reasons, String otherText, Integer signingOfficialId) { - -} +public record CloseoutSupplement( + List reasons, String otherText, Integer signingOfficialId) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/Dac.java b/src/main/java/org/broadinstitute/consent/http/models/Dac.java index a96b860854..4ba1dcce91 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Dac.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Dac.java @@ -5,9 +5,7 @@ import java.util.List; import java.util.Objects; -/** - * Entity representing a Data Access Committee - */ +/** Entity representing a Data Access Committee */ public class Dac { private Integer dacId; @@ -34,8 +32,7 @@ public class Dac { private DataAccessAgreement associatedDaa; - public Dac() { - } + public Dac() {} public Integer getDacId() { return dacId; @@ -109,7 +106,6 @@ public void addDatasetId(Integer datasetId) { this.datasetIds.add(datasetId); } - public String getEmail() { return email; } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DacBuilder.java b/src/main/java/org/broadinstitute/consent/http/models/DacBuilder.java index ea2523c570..d04811bce0 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DacBuilder.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DacBuilder.java @@ -3,9 +3,7 @@ import java.util.Date; import java.util.List; -/** - * Convenience class for building Dacs. - */ +/** Convenience class for building Dacs. */ public class DacBuilder { private Dac dac; @@ -62,5 +60,4 @@ public DacBuilder setMembers(List members) { this.dac.setMembers(members); return this; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DarCollection.java b/src/main/java/org/broadinstitute/consent/http/models/DarCollection.java index 85069ce6d9..ad66cbf8d9 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DarCollection.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DarCollection.java @@ -12,50 +12,36 @@ import org.apache.commons.lang3.builder.EqualsBuilder; import org.broadinstitute.consent.http.util.gson.GsonUtil; -//represents a multi-dataset access request +// represents a multi-dataset access request public class DarCollection { - //This query is specific to DAR Collections, which is why it's defined here + // This query is specific to DAR Collections, which is why it's defined here public static final String DAR_FILTER_QUERY_COLUMNS = "dar.id AS dar_id, dar.reference_id AS dar_reference_id, dar.collection_id AS dar_collection_id, " - + - "dar.parent_id AS dar_parent_id, dar.user_id AS dar_userId, " + - "dar.create_date AS dar_create_date, dar.submission_date AS dar_submission_date, " - + - "dar.update_date AS dar_update_date, dar.data AS data, " - + - "dar.closeout_so_approval_timestamp AS dar_closeout_signing_official_approved_date, " - + - "dar.closeout_approving_so_id AS dar_closeout_signing_official_approved_user_id, " - + - "dar.data ->> 'projectTitle' as projectTitle "; + + "dar.parent_id AS dar_parent_id, dar.user_id AS dar_userId, " + + "dar.create_date AS dar_create_date, dar.submission_date AS dar_submission_date, " + + "dar.update_date AS dar_update_date, dar.data AS data, " + + "dar.closeout_so_approval_timestamp AS dar_closeout_signing_official_approved_date, " + + "dar.closeout_approving_so_id AS dar_closeout_signing_official_approved_user_id, " + + "dar.data ->> 'projectTitle' as projectTitle "; - @JsonProperty - private Integer darCollectionId; + @JsonProperty private Integer darCollectionId; - @JsonProperty - private String darCode; + @JsonProperty private String darCode; - @JsonProperty - private Timestamp createDate; + @JsonProperty private Timestamp createDate; - @JsonProperty - private User createUser; + @JsonProperty private User createUser; - @JsonProperty - private Integer createUserId; + @JsonProperty private Integer createUserId; - @JsonProperty - private Timestamp updateDate; + @JsonProperty private Timestamp updateDate; - @JsonProperty - private Integer updateUserId; + @JsonProperty private Integer updateUserId; - @JsonProperty - private final Map dars = new HashMap<>(); + @JsonProperty private final Map dars = new HashMap<>(); - @JsonProperty - private Set datasets; + @JsonProperty private Set datasets; public DarCollection() { this.createDate = new Timestamp(System.currentTimeMillis()); diff --git a/src/main/java/org/broadinstitute/consent/http/models/DarCollectionSummary.java b/src/main/java/org/broadinstitute/consent/http/models/DarCollectionSummary.java index 99069b9bb4..d68b9e922c 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DarCollectionSummary.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DarCollectionSummary.java @@ -16,48 +16,27 @@ public class DarCollectionSummary { - @Expose - private Integer darCollectionId; - @Expose - private Set referenceIds; - @Expose - private String darCode; - @Expose - private String name; - @Expose - private Timestamp submissionDate; - @Expose - private boolean expired; - @Expose - private Timestamp expiresAt; - @Expose - private String researcherName; - @Expose - private String institutionName; - @Expose - private String status; - @Expose - private Set actions; - @Expose - private int datasetCount; - @Expose - private final Map> parentToReferenceIds; - @Expose - private boolean progressReport; - @Expose - private String latestReferenceId; - @Expose - private Integer closeoutSigningOfficialId; - @Expose - private Timestamp closeoutSigningOfficialApprovalDate; - @Expose - private List dacNames; - @Expose - private Integer researcherId; - @Expose - private Integer institutionId; - @Expose - private Set datasetIds; + @Expose private Integer darCollectionId; + @Expose private Set referenceIds; + @Expose private String darCode; + @Expose private String name; + @Expose private Timestamp submissionDate; + @Expose private boolean expired; + @Expose private Timestamp expiresAt; + @Expose private String researcherName; + @Expose private String institutionName; + @Expose private String status; + @Expose private Set actions; + @Expose private int datasetCount; + @Expose private final Map> parentToReferenceIds; + @Expose private boolean progressReport; + @Expose private String latestReferenceId; + @Expose private Integer closeoutSigningOfficialId; + @Expose private Timestamp closeoutSigningOfficialApprovalDate; + @Expose private List dacNames; + @Expose private Integer researcherId; + @Expose private Integer institutionId; + @Expose private Set datasetIds; // Normally unused by the UI, but used in data population. Can be included in the JSON response // if needed by using a GsonBuilder without `excludeFieldsWithoutExposeAnnotation`. @@ -157,7 +136,10 @@ public Timestamp getSubmissionDate() { public void setSubmissionDate(Timestamp submissionDate) { this.submissionDate = submissionDate; if (submissionDate != null) { - this.expiresAt = Timestamp.from(Instant.ofEpochMilli(submissionDate.getTime() + DataAccessRequest.EXPIRATION_DURATION_MILLIS)); + this.expiresAt = + Timestamp.from( + Instant.ofEpochMilli( + submissionDate.getTime() + DataAccessRequest.EXPIRATION_DURATION_MILLIS)); this.expired = this.expiresAt.before(Timestamp.from(Instant.now())); } updateProgressReportStatus(); @@ -299,8 +281,7 @@ public CloseoutSupplement getCloseoutSupplement() { return closeoutSupplement; } - public void setCloseoutSupplement( - CloseoutSupplement closeoutSupplement) { + public void setCloseoutSupplement(CloseoutSupplement closeoutSupplement) { this.closeoutSupplement = closeoutSupplement; } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DarDataset.java b/src/main/java/org/broadinstitute/consent/http/models/DarDataset.java index 36ea18667b..eb2ce59317 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DarDataset.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DarDataset.java @@ -5,8 +5,7 @@ public class DarDataset { private String referenceId; private Integer datasetId; - public DarDataset() { - } + public DarDataset() {} public DarDataset(String referenceId, Integer datasetId) { this.referenceId = referenceId; diff --git a/src/main/java/org/broadinstitute/consent/http/models/DataAccessAgreement.java b/src/main/java/org/broadinstitute/consent/http/models/DataAccessAgreement.java index d2a5ea9f78..9102c6d099 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DataAccessAgreement.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DataAccessAgreement.java @@ -92,10 +92,7 @@ public void addDac(Dac dac) { if (this.dacs == null) { this.dacs = new ArrayList<>(); } - if (this.dacs - .stream() - .map(Dac::getDacId) - .noneMatch(d -> d.equals(dac.getDacId()))) { + if (this.dacs.stream().map(Dac::getDacId).noneMatch(d -> d.equals(dac.getDacId()))) { this.dacs.add(dac); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequest.java b/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequest.java index cf9ab6dd0e..f53ea38439 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequest.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequest.java @@ -30,70 +30,50 @@ public class DataAccessRequest { public static final long EXPIRATION_DURATION_MILLIS = TimeUnit.DAYS.toMillis(365); - @JsonProperty - public Integer id; + @JsonProperty public Integer id; - @JsonProperty - public String referenceId; + @JsonProperty public String referenceId; - @JsonProperty - public Integer collectionId; + @JsonProperty public Integer collectionId; - @JsonProperty - public Integer parentId; + @JsonProperty public Integer parentId; - @JsonProperty - public DataAccessRequestData data; + @JsonProperty public DataAccessRequestData data; - @JsonProperty - public String darCode; + @JsonProperty public String darCode; - @JsonProperty - public Boolean draft = true; + @JsonProperty public Boolean draft = true; - @JsonProperty - public Boolean progressReport = false; + @JsonProperty public Boolean progressReport = false; - @JsonProperty - public Boolean expired = false; + @JsonProperty public Boolean expired = false; - @JsonProperty - public Timestamp expiresAt; + @JsonProperty public Timestamp expiresAt; - @JsonProperty - public Integer userId; + @JsonProperty public Integer userId; - @JsonProperty - public Timestamp createDate; + @JsonProperty public Timestamp createDate; - @JsonProperty - public Timestamp submissionDate; + @JsonProperty public Timestamp submissionDate; - @JsonProperty - public Timestamp updateDate; - @JsonProperty - public List datasetIds; - @JsonProperty - private Map elections; - @JsonProperty - private String eraCommonsId; + @JsonProperty public Timestamp updateDate; + @JsonProperty public List datasetIds; + @JsonProperty private Map elections; + @JsonProperty private String eraCommonsId; - @JsonProperty - public Timestamp closeoutSigningOfficialApprovedDate; + @JsonProperty public Timestamp closeoutSigningOfficialApprovedDate; - @JsonProperty - public Integer closeoutSigningOfficialApprovedUserId; + @JsonProperty public Integer closeoutSigningOfficialApprovedUserId; public DataAccessRequest() { this.elections = new HashMap<>(); } public static boolean isCanceled(DataAccessRequest dar) { - return - Objects.nonNull(dar) && - Objects.nonNull(dar.getData()) && - Objects.nonNull(dar.getData().getStatus()) && - dar.getData().getStatus().equalsIgnoreCase("canceled"); + return Objects.nonNull(dar) + && Objects.nonNull(dar.getData()) + && Objects.nonNull(dar.getData().getStatus()) + && dar.getData().getStatus().equalsIgnoreCase("canceled"); } public Integer getId() { @@ -172,15 +152,20 @@ public Timestamp getSubmissionDate() { public void setSubmissionDate(Timestamp submissionDate) { this.submissionDate = submissionDate; draft = submissionDate == null; - expired = submissionDate != null - && submissionDate.before( - new Timestamp(System.currentTimeMillis() - EXPIRATION_DURATION_MILLIS)); - expiresAt = (submissionDate != null) ? new Timestamp( - submissionDate.getTime() + EXPIRATION_DURATION_MILLIS) : null; + expired = + submissionDate != null + && submissionDate.before( + new Timestamp(System.currentTimeMillis() - EXPIRATION_DURATION_MILLIS)); + expiresAt = + (submissionDate != null) + ? new Timestamp(submissionDate.getTime() + EXPIRATION_DURATION_MILLIS) + : null; updateProgressReportState(); } - public boolean getProgressReport() { return progressReport; } + public boolean getProgressReport() { + return progressReport; + } public Timestamp getUpdateDate() { return updateDate; @@ -236,10 +221,8 @@ public void addDatasetIds(List ids) { datasetIds = new ArrayList<>(); } if (Objects.nonNull(ids) && !ids.isEmpty()) { - datasetIds = Stream.of(datasetIds, ids) - .flatMap(List::stream) - .distinct() - .collect(Collectors.toList()); + datasetIds = + Stream.of(datasetIds, ids).flatMap(List::stream).distinct().collect(Collectors.toList()); } } @@ -263,7 +246,8 @@ public Integer getCloseoutSigningOfficialApprovedUserId() { return closeoutSigningOfficialApprovedUserId; } - public void setCloseoutSigningOfficialApprovedUserId(Integer closeoutSigningOfficialApprovedUserId) { + public void setCloseoutSigningOfficialApprovedUserId( + Integer closeoutSigningOfficialApprovedUserId) { this.closeoutSigningOfficialApprovedUserId = closeoutSigningOfficialApprovedUserId; } @@ -271,7 +255,8 @@ public Timestamp getCloseoutSigningOfficialApprovedDate() { return closeoutSigningOfficialApprovedDate; } - public void setCloseoutSigningOfficialApprovedDate(Timestamp closeoutSigningOfficialApprovedDate) { + public void setCloseoutSigningOfficialApprovedDate( + Timestamp closeoutSigningOfficialApprovedDate) { this.closeoutSigningOfficialApprovedDate = closeoutSigningOfficialApprovedDate; } @@ -284,14 +269,18 @@ public void setCloseoutSigningOfficialApprovedDate(Timestamp closeoutSigningOffi public Map convertToSimplifiedDar() { // Serialize dates/timestamps as longs, but do not deserialize longs into dates so we can // output long values in the final result. - Gson gson = new GsonBuilder() - .registerTypeAdapter(Date.class, - (JsonSerializer) (date, type, jsonSerializationContext) -> new JsonPrimitive( - date.getTime())) - .registerTypeAdapter(Timestamp.class, - (JsonSerializer) (timestamp, type, jsonSerializationContext) -> new JsonPrimitive( - timestamp.getTime())) - .create(); + Gson gson = + new GsonBuilder() + .registerTypeAdapter( + Date.class, + (JsonSerializer) + (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime())) + .registerTypeAdapter( + Timestamp.class, + (JsonSerializer) + (timestamp, type, jsonSerializationContext) -> + new JsonPrimitive(timestamp.getTime())) + .create(); DataAccessRequestData dataCopy = this.getData(); this.setData(null); @@ -311,35 +300,31 @@ public Map convertToSimplifiedDar() { dar.add(camelCasedDataKey, darData.get(dataKey)); } } - Type darMapType = new TypeToken>() { - }.getType(); + Type darMapType = new TypeToken>() {}.getType(); return gson.fromJson(dar.toString(), darMapType); } public boolean requiresManualReview() { - return - Objects.nonNull(this.getData()) && ( - (Objects.nonNull(this.getData().getPoa()) && this.getData().getPoa()) || - (Objects.nonNull(this.getData().getPopulation()) && this.getData().getPopulation()) - || - (Objects.nonNull(this.getData().getOther()) && this.getData().getOther()) || - (Objects.nonNull(this.getData().getOtherText()) && !this.getData().getOtherText() - .isBlank()) || - (Objects.nonNull(this.getData().getIllegalBehavior()) && this.getData() - .getIllegalBehavior()) || - (Objects.nonNull(this.getData().getAddiction()) && this.getData().getAddiction()) || - (Objects.nonNull(this.getData().getSexualDiseases()) && this.getData() - .getSexualDiseases()) || - (Objects.nonNull(this.getData().getStigmatizedDiseases()) && this.getData() - .getStigmatizedDiseases()) || - (Objects.nonNull(this.getData().getVulnerablePopulation()) && this.getData() - .getVulnerablePopulation()) || - (Objects.nonNull(this.getData().getPopulationMigration()) && this.getData() - .getPopulationMigration()) || - (Objects.nonNull(this.getData().getPsychiatricTraits()) && this.getData() - .getPsychiatricTraits()) || - (Objects.nonNull(this.getData().getNotHealth()) && this.getData().getNotHealth()) - ); + return Objects.nonNull(this.getData()) + && ((Objects.nonNull(this.getData().getPoa()) && this.getData().getPoa()) + || (Objects.nonNull(this.getData().getPopulation()) && this.getData().getPopulation()) + || (Objects.nonNull(this.getData().getOther()) && this.getData().getOther()) + || (Objects.nonNull(this.getData().getOtherText()) + && !this.getData().getOtherText().isBlank()) + || (Objects.nonNull(this.getData().getIllegalBehavior()) + && this.getData().getIllegalBehavior()) + || (Objects.nonNull(this.getData().getAddiction()) && this.getData().getAddiction()) + || (Objects.nonNull(this.getData().getSexualDiseases()) + && this.getData().getSexualDiseases()) + || (Objects.nonNull(this.getData().getStigmatizedDiseases()) + && this.getData().getStigmatizedDiseases()) + || (Objects.nonNull(this.getData().getVulnerablePopulation()) + && this.getData().getVulnerablePopulation()) + || (Objects.nonNull(this.getData().getPopulationMigration()) + && this.getData().getPopulationMigration()) + || (Objects.nonNull(this.getData().getPsychiatricTraits()) + && this.getData().getPsychiatricTraits()) + || (Objects.nonNull(this.getData().getNotHealth()) && this.getData().getNotHealth())); } /** @@ -347,16 +332,16 @@ public boolean requiresManualReview() { * Copies all the data from the parent dar, then overwrites the collaborators and datasets. Adds * all progress report specific fields. * - * @param json The JSON string to populate the new Progress Report. + * @param json The JSON string to populate the new Progress Report. * @param parentDar The parent Data Access Request to copy data from. * @return A new Progress Report populated with the provided JSON string and parent DAR data. */ - public static DataAccessRequest populateProgressReportFromJsonString(String json, - DataAccessRequest parentDar) { + public static DataAccessRequest populateProgressReportFromJsonString( + String json, DataAccessRequest parentDar) { DataAccessRequest newDar = new DataAccessRequest(); DataAccessRequestData newData = DataAccessRequestData.populateDARData(json); - DataAccessRequestData originalDataCopy = DataAccessRequestData.fromString( - parentDar.getData().toString()); + DataAccessRequestData originalDataCopy = + DataAccessRequestData.fromString(parentDar.getData().toString()); String referenceId = UUID.randomUUID().toString(); newDar.setReferenceId(referenceId); @@ -413,11 +398,11 @@ protected static void validateCloseoutSupplement(CloseoutSupplement closeoutSupp } if (Objects.isNull(closeoutSupplement.signingOfficialId())) { - throw new BadRequestException("A closeout supplement must have a signing official id provided."); + throw new BadRequestException( + "A closeout supplement must have a signing official id provided."); } } - /** * Make a shallow copy of the dar. This is mostly a workaround for problems serializing dates when * calling Gson.toJson on `this` @@ -464,10 +449,12 @@ private Map shallowCopy(DataAccessRequest dar) { copy.put("eraCommonsId", dar.getEraCommonsId()); } if (dar.getCloseoutSigningOfficialApprovedUserId() != null) { - copy.put("closeoutSigningOfficialApprovedUserId", dar.getCloseoutSigningOfficialApprovedUserId()); + copy.put( + "closeoutSigningOfficialApprovedUserId", dar.getCloseoutSigningOfficialApprovedUserId()); } if (dar.getCloseoutSigningOfficialApprovedDate() != null) { - copy.put("closeoutSigningOfficialApprovedDate", dar.getCloseoutSigningOfficialApprovedUserId()); + copy.put( + "closeoutSigningOfficialApprovedDate", dar.getCloseoutSigningOfficialApprovedUserId()); } return copy; } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequestData.java b/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequestData.java index 99b7f1d86a..e24d3ed76e 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequestData.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DataAccessRequestData.java @@ -21,22 +21,55 @@ public class DataAccessRequestData { * fields. See DUOS-728 for * more info. */ - public static final List DEPRECATED_PROPS = Arrays - .asList("referenceId", "investigator", "datasets", "darCode", - "institution", "department", "address1", "address2", "city", "zipcode", "zipCode", - "state", "country", "researcher", "userId", "isThePi", "havePi", - "profileName", "pubmedId", "scientificUrl", "eraExpiration", "academicEmail", - "eraAuthorized", "nihUsername", "linkedIn", "orcid", "researcherGate", "datasetDetail", - "datasets", "datasetId", "validRestriction", "restriction", "translatedUseRestriction", - "createDate", "sortDate", "additionalEmail", "checkNotifications", "partialDarCode"); - - @Deprecated - private String referenceId; + public static final List DEPRECATED_PROPS = + Arrays.asList( + "referenceId", + "investigator", + "datasets", + "darCode", + "institution", + "department", + "address1", + "address2", + "city", + "zipcode", + "zipCode", + "state", + "country", + "researcher", + "userId", + "isThePi", + "havePi", + "profileName", + "pubmedId", + "scientificUrl", + "eraExpiration", + "academicEmail", + "eraAuthorized", + "nihUsername", + "linkedIn", + "orcid", + "researcherGate", + "datasetDetail", + "datasets", + "datasetId", + "validRestriction", + "restriction", + "translatedUseRestriction", + "createDate", + "sortDate", + "additionalEmail", + "checkNotifications", + "partialDarCode"); + + @Deprecated private String referenceId; private String projectTitle; private Boolean checkNihDataOnly; private String rus; + @SerializedName(value = "nonTechRus", alternate = "non_tech_rus") private String nonTechRus; + private Boolean diseases; private Boolean methods; private Boolean aiLlmUse; @@ -46,32 +79,47 @@ public class DataAccessRequestData { private String otherText; private List ontologies; private Boolean forProfit; + @SerializedName(value = "oneGender", alternate = "onegender") private Boolean oneGender; + private String gender; private Boolean pediatric; + @SerializedName(value = "illegalBehavior", alternate = "illegalbehave") private Boolean illegalBehavior; + private Boolean addiction; + @SerializedName(value = "sexualDiseases", alternate = "sexualdiseases") private Boolean sexualDiseases; + @SerializedName(value = "stigmatizedDiseases", alternate = "stigmatizediseases") private Boolean stigmatizedDiseases; + @SerializedName(value = "vulnerablePopulation", alternate = "vulnerablepop") private Boolean vulnerablePopulation; + @SerializedName(value = "populationMigration", alternate = "popmigration") private Boolean populationMigration; + @SerializedName(value = "psychiatricTraits", alternate = "psychtraits") private Boolean psychiatricTraits; + @SerializedName(value = "notHealth", alternate = "nothealth") private Boolean notHealth; + private Boolean hmb; private String status; private Boolean poa; private Object restriction; + @SerializedName(value = "validRestriction", alternate = "valid_restriction") private Boolean validRestriction; - @SerializedName(value = "datasetIds", alternate = {"datasetId", "datasetid"}) + + @SerializedName( + value = "datasetIds", + alternate = {"datasetId", "datasetid"}) private List datasetIds; // Progress Report/Closeout Fields @@ -516,8 +564,7 @@ public List getLabCollaborators() { return labCollaborators; } - public void setLabCollaborators( - List labCollaborators) { + public void setLabCollaborators(List labCollaborators) { this.labCollaborators = labCollaborators; } @@ -528,8 +575,7 @@ public List getInternalCollaborators() { return internalCollaborators; } - public void setInternalCollaborators( - List internalCollaborators) { + public void setInternalCollaborators(List internalCollaborators) { this.internalCollaborators = internalCollaborators; } @@ -546,8 +592,7 @@ public List getExternalCollaborators() { return externalCollaborators; } - public void setExternalCollaborators( - List externalCollaborators) { + public void setExternalCollaborators(List externalCollaborators) { this.externalCollaborators = externalCollaborators; } @@ -641,8 +686,7 @@ public void setPiEmail(String piEmail) { // Validate all ontology entries private static void validateOntologyEntries(DataAccessRequestData data) { - if (Objects.nonNull(data) - && !data.getOntologies().isEmpty()) { + if (Objects.nonNull(data) && !data.getOntologies().isEmpty()) { List filteredEntries = data.getOntologies().stream() .filter(Objects::nonNull) @@ -669,8 +713,7 @@ public List getIntellectualProperties() { return intellectualProperties; } - public void setIntellectualProperties( - List intellectualProperties) { + public void setIntellectualProperties(List intellectualProperties) { this.intellectualProperties = intellectualProperties; } @@ -678,8 +721,7 @@ public List getPublications() { return publications; } - public void setPublications( - List publications) { + public void setPublications(List publications) { this.publications = publications; } @@ -687,8 +729,7 @@ public List getPresentations() { return presentations; } - public void setPresentations( - List presentations) { + public void setPresentations(List presentations) { this.presentations = presentations; } @@ -712,8 +753,7 @@ public CloseoutSupplement getCloseoutSupplement() { return closeoutSupplement; } - public void setCloseoutSupplement( - CloseoutSupplement closeoutSupplement) { + public void setCloseoutSupplement(CloseoutSupplement closeoutSupplement) { this.closeoutSupplement = closeoutSupplement; } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DataManagementIncident.java b/src/main/java/org/broadinstitute/consent/http/models/DataManagementIncident.java index 4acb48fe71..f4cfc0cb26 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DataManagementIncident.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DataManagementIncident.java @@ -2,6 +2,4 @@ import java.util.List; -public record DataManagementIncident(List incidents, String description) { - -} +public record DataManagementIncident(List incidents, String description) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/DataUse.java b/src/main/java/org/broadinstitute/consent/http/models/DataUse.java index cb02fc04c7..1273597f34 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DataUse.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DataUse.java @@ -253,12 +253,15 @@ public boolean equals(Object o) { DataUse dataUse = (DataUse) o; - return new EqualsBuilder().append(generalUse, dataUse.generalUse) + return new EqualsBuilder() + .append(generalUse, dataUse.generalUse) .append(hmbResearch, dataUse.hmbResearch) .append(diseaseRestrictions, dataUse.diseaseRestrictions) .append(populationOriginsAncestry, dataUse.populationOriginsAncestry) - .append(methodsResearch, dataUse.methodsResearch).append(nonProfitUse, dataUse.nonProfitUse) - .append(other, dataUse.other).append(secondaryOther, dataUse.secondaryOther) + .append(methodsResearch, dataUse.methodsResearch) + .append(nonProfitUse, dataUse.nonProfitUse) + .append(other, dataUse.other) + .append(secondaryOther, dataUse.secondaryOther) .append(ethicsApprovalRequired, dataUse.ethicsApprovalRequired) .append(collaboratorRequired, dataUse.collaboratorRequired) .append(geographicalRestrictions, dataUse.geographicalRestrictions) @@ -266,8 +269,10 @@ public boolean equals(Object o) { .append(publicationResults, dataUse.publicationResults) .append(publicationMoratorium, dataUse.publicationMoratorium) .append(aiLlmUse, dataUse.aiLlmUse) - .append(controls, dataUse.controls).append(gender, dataUse.gender) - .append(pediatric, dataUse.pediatric).append(population, dataUse.population) + .append(controls, dataUse.controls) + .append(gender, dataUse.gender) + .append(pediatric, dataUse.pediatric) + .append(population, dataUse.population) .append(illegalBehavior, dataUse.illegalBehavior) .append(sexualDiseases, dataUse.sexualDiseases) .append(stigmatizeDiseases, dataUse.stigmatizeDiseases) @@ -279,13 +284,32 @@ public boolean equals(Object o) { @Override public int hashCode() { - return new HashCodeBuilder(17, 37).append(generalUse).append(hmbResearch) - .append(diseaseRestrictions).append(populationOriginsAncestry).append(methodsResearch) - .append(nonProfitUse).append(other).append(secondaryOther).append(ethicsApprovalRequired) - .append(collaboratorRequired).append(geographicalRestrictions).append(geneticStudiesOnly) - .append(publicationResults).append(publicationMoratorium).append(aiLlmUse).append(controls).append(gender) - .append(pediatric).append(population).append(illegalBehavior).append(sexualDiseases) - .append(stigmatizeDiseases).append(vulnerablePopulations).append(psychologicalTraits) - .append(notHealth).toHashCode(); + return new HashCodeBuilder(17, 37) + .append(generalUse) + .append(hmbResearch) + .append(diseaseRestrictions) + .append(populationOriginsAncestry) + .append(methodsResearch) + .append(nonProfitUse) + .append(other) + .append(secondaryOther) + .append(ethicsApprovalRequired) + .append(collaboratorRequired) + .append(geographicalRestrictions) + .append(geneticStudiesOnly) + .append(publicationResults) + .append(publicationMoratorium) + .append(aiLlmUse) + .append(controls) + .append(gender) + .append(pediatric) + .append(population) + .append(illegalBehavior) + .append(sexualDiseases) + .append(stigmatizeDiseases) + .append(vulnerablePopulations) + .append(psychologicalTraits) + .append(notHealth) + .toHashCode(); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DataUseBuilder.java b/src/main/java/org/broadinstitute/consent/http/models/DataUseBuilder.java index 95a5dda1c8..93ae52b006 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DataUseBuilder.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DataUseBuilder.java @@ -19,7 +19,6 @@ public DataUse build() { return du; } - public DataUseBuilder setGeneralUse(Boolean generalUse) { du.setGeneralUse(generalUse); return this; @@ -144,5 +143,4 @@ public DataUseBuilder setNotHealth(Boolean notHealth) { du.setNotHealth(notHealth); return this; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Dataset.java b/src/main/java/org/broadinstitute/consent/http/models/Dataset.java index 88debfa8c9..8ee4e37773 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Dataset.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Dataset.java @@ -60,11 +60,17 @@ public class Dataset implements ConsentLogger { private Date indexedDate; - public Dataset() { - } - - public Dataset(Integer datasetId, String objectId, String name, Date createDate, - Integer createUserId, Date updateDate, Integer updateUserId, Integer alias) { + public Dataset() {} + + public Dataset( + Integer datasetId, + String objectId, + String name, + Date createDate, + Integer createUserId, + Date updateDate, + Integer updateUserId, + Integer alias) { this.datasetId = datasetId; this.objectId = objectId; this.name = name; @@ -171,7 +177,6 @@ public List getPropertyName() { return propertyName; } - public void setProperties(Set properties) { this.properties = properties; } @@ -267,12 +272,13 @@ public void setDeletable(Boolean deletable) { * data use properties. Has optional parameter accessManagement which will search datasets on both * the raw search query and the access management type. * - * @param query Raw string query + * @param query Raw string query * @param accessManagement One of controlled, open, or external * @return if the Dataset matched query */ - // TODO: investigate whether we can try to coerce getPropertyValue to a boolean instead of comparing strings + // TODO: investigate whether we can try to coerce getPropertyValue to a boolean instead of + // comparing strings public boolean isDatasetMatch(@NonNull String query, AccessManagement accessManagement) { String lowerCaseQuery = query.toLowerCase(); List queryTerms = List.of(lowerCaseQuery.split("\\s+")); @@ -282,27 +288,28 @@ public boolean isDatasetMatch(@NonNull String query, AccessManagement accessMana matchTerms.add(this.getDatasetIdentifier()); if (Objects.nonNull(getProperties()) && !getProperties().isEmpty()) { - Optional accessManagementProp = getProperties() - .stream() - .filter((dp) -> Objects.nonNull(dp.getPropertyValue())) - .filter((dp) -> Objects.equals(dp.getPropertyName(), "Access Management")) - .findFirst(); + Optional accessManagementProp = + getProperties().stream() + .filter((dp) -> Objects.nonNull(dp.getPropertyValue())) + .filter((dp) -> Objects.equals(dp.getPropertyName(), "Access Management")) + .findFirst(); if (accessManagementProp.isEmpty()) { if (accessManagement.equals(AccessManagement.OPEN)) { return false; } - } else if (!accessManagement.toString() + } else if (!accessManagement + .toString() .equals(accessManagementProp.get().getPropertyValueAsString())) { return false; } - List propVals = getProperties() - .stream() - .filter((dp) -> Objects.nonNull(dp.getPropertyValue())) - .map(DatasetProperty::getPropertyValueAsString) - .map(String::toLowerCase) - .toList(); + List propVals = + getProperties().stream() + .filter((dp) -> Objects.nonNull(dp.getPropertyValue())) + .map(DatasetProperty::getPropertyValueAsString) + .map(String::toLowerCase) + .toList(); matchTerms.addAll(propVals); } @@ -312,8 +319,7 @@ public boolean isDatasetMatch(@NonNull String query, AccessManagement accessMana matchTerms.add("irb"); } - if (Objects.nonNull(dataUse.getCollaboratorRequired()) - && dataUse.getCollaboratorRequired()) { + if (Objects.nonNull(dataUse.getCollaboratorRequired()) && dataUse.getCollaboratorRequired()) { matchTerms.add("collaborator"); } @@ -322,18 +328,15 @@ public boolean isDatasetMatch(@NonNull String query, AccessManagement accessMana } } - return queryTerms - .stream() + return queryTerms.stream() .filter(Objects::nonNull) // all terms must match at least one thing - .allMatch((q) -> - matchTerms - .stream() - .filter(Objects::nonNull) - .map(String::toLowerCase) - .anyMatch( - (t) -> t.contains(q)) - ); + .allMatch( + (q) -> + matchTerms.stream() + .filter(Objects::nonNull) + .map(String::toLowerCase) + .anyMatch((t) -> t.contains(q))); } public Study getStudy() { @@ -368,21 +371,18 @@ public void setIndexedDate(Date indexedDate) { */ public boolean isCustodian(User user) { if (getStudy() != null && getStudy().getProperties() != null) { - Optional dataCustodians = getStudy() - .getProperties() - .stream() - .filter(p -> p.getKey().equals(DatasetRegistrationSchemaV1Builder.dataCustodianEmail)) - .findFirst(); + Optional dataCustodians = + getStudy().getProperties().stream() + .filter(p -> p.getKey().equals(DatasetRegistrationSchemaV1Builder.dataCustodianEmail)) + .findFirst(); if (dataCustodians.isPresent()) { JsonArray jsonArray = (JsonArray) dataCustodians.get().getValue(); return jsonArray.contains(new JsonPrimitive(user.getEmail())); } else { - logWarn( - "No data custodians found for dataset: %s".formatted(getDatasetIdentifier())); + logWarn("No data custodians found for dataset: %s".formatted(getDatasetIdentifier())); } } else { - logWarn( - "No study properties found for dataset: %s".formatted(getDatasetIdentifier())); + logWarn("No study properties found for dataset: %s".formatted(getDatasetIdentifier())); } return false; } @@ -391,8 +391,7 @@ public boolean isCreator(User user) { if (Objects.equals(user.getUserId(), getCreateUserId())) { return true; } - return getStudy() != null && Objects.equals(user.getUserId(), - getStudy().getCreateUserId()); + return getStudy() != null && Objects.equals(user.getUserId(), getStudy().getCreateUserId()); } @Override @@ -428,5 +427,4 @@ public User getCreateUser() { public void setCreateUser(User createUser) { this.createUser = createUser; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DatasetAudit.java b/src/main/java/org/broadinstitute/consent/http/models/DatasetAudit.java index 53224ac3e3..b75ec0fdc7 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DatasetAudit.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DatasetAudit.java @@ -5,41 +5,28 @@ public class DatasetAudit { - @JsonProperty - private Integer dataSetAuditId; + @JsonProperty private Integer dataSetAuditId; - @JsonProperty - private Integer datasetId; + @JsonProperty private Integer datasetId; - @JsonProperty - private String objectId; + @JsonProperty private String objectId; - @JsonProperty - private String name; + @JsonProperty private String name; - @JsonProperty - private Date date; + @JsonProperty private Date date; @Deprecated(forRemoval = true) @JsonProperty private Boolean active; - @JsonProperty - private Integer user; + @JsonProperty private Integer user; - @JsonProperty - private String action; + @JsonProperty private String action; - public DatasetAudit() { - } + public DatasetAudit() {} public DatasetAudit( - Integer datasetId, - String objectId, - String name, - Date date, - Integer user, - String action) { + Integer datasetId, String objectId, String name, Date date, Integer user, String action) { this.datasetId = datasetId; this.objectId = objectId; this.name = name; diff --git a/src/main/java/org/broadinstitute/consent/http/models/DatasetMetrics.java b/src/main/java/org/broadinstitute/consent/http/models/DatasetMetrics.java index e0240723cf..a0d3fb9f17 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DatasetMetrics.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DatasetMetrics.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.models; - import java.util.List; import org.broadinstitute.consent.http.service.MetricsService.DarMetricsSummary; diff --git a/src/main/java/org/broadinstitute/consent/http/models/DatasetPatch.java b/src/main/java/org/broadinstitute/consent/http/models/DatasetPatch.java index 884dfef410..648a6d6ad7 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DatasetPatch.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DatasetPatch.java @@ -10,7 +10,7 @@ /** * This model represents the values of a dataset that are modifiable via the PATCH operation * - * @param name Dataset name + * @param name Dataset name * @param properties List of DatasetProperties */ public record DatasetPatch(String name, List properties) { @@ -26,46 +26,52 @@ public boolean isPatchable(Dataset dataset) { return true; } // Find any cases where the new property value is different from the existing one - return properties().stream().anyMatch(p -> { - Optional existingProp = dataset.getProperties() - .stream() - .filter(eProp -> { - // Favor the property name as the primary comparator - if (eProp.getPropertyName() != null) { - return eProp.getPropertyName().equalsIgnoreCase(p.getPropertyName()); - } else if (eProp.getPropertyKey() != null) { - return eProp.getPropertyKey().equals(p.getPropertyKey()); - } else if (eProp.getSchemaProperty() != null) { - return eProp.getSchemaProperty().equalsIgnoreCase(p.getSchemaProperty()); - } - return false; - }) - .findFirst(); - return existingProp.map( - eProp -> - // If the existing prop value is different from the new one, this is patchable - (!eProp.getPropertyValueAsString().equals(p.getPropertyValueAsString()))) - // If no existing prop, we're adding a new prop, and therefore patchable. - .orElse(true); - }); + return properties().stream() + .anyMatch( + p -> { + Optional existingProp = + dataset.getProperties().stream() + .filter( + eProp -> { + // Favor the property name as the primary comparator + if (eProp.getPropertyName() != null) { + return eProp.getPropertyName().equalsIgnoreCase(p.getPropertyName()); + } else if (eProp.getPropertyKey() != null) { + return eProp.getPropertyKey().equals(p.getPropertyKey()); + } else if (eProp.getSchemaProperty() != null) { + return eProp + .getSchemaProperty() + .equalsIgnoreCase(p.getSchemaProperty()); + } + return false; + }) + .findFirst(); + return existingProp + .map( + eProp -> + // If the existing prop value is different from the new one, this is + // patchable + (!eProp.getPropertyValueAsString().equals(p.getPropertyValueAsString()))) + // If no existing prop, we're adding a new prop, and therefore patchable. + .orElse(true); + }); } public boolean validateProperties() { // The following properties are patch-able: - Map> validators = Map.of( - "# of participants", this::isNumeric, - "url", this::isUrl, - "data location", this::isDataLocation - ); + Map> validators = + Map.of( + "# of participants", this::isNumeric, + "url", this::isUrl, + "data location", this::isDataLocation); return properties.stream() - .map(p -> { - if (!validators.containsKey(p.getPropertyName().toLowerCase())) { - return false; - } - return validators - .get(p.getPropertyName().toLowerCase()) - .apply(p.getPropertyValue()); - }) + .map( + p -> { + if (!validators.containsKey(p.getPropertyName().toLowerCase())) { + return false; + } + return validators.get(p.getPropertyName().toLowerCase()).apply(p.getPropertyValue()); + }) .distinct() .allMatch(valid -> valid); } @@ -95,5 +101,4 @@ private boolean isDataLocation(Object obj) { return false; } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DatasetProperty.java b/src/main/java/org/broadinstitute/consent/http/models/DatasetProperty.java index c0335a08ad..7844ea7809 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DatasetProperty.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DatasetProperty.java @@ -15,11 +15,11 @@ public class DatasetProperty { private String schemaProperty; private PropertyType propertyType; - public DatasetProperty() { - } + public DatasetProperty() {} @Deprecated - public DatasetProperty(Integer propertyId, + public DatasetProperty( + Integer propertyId, Integer datasetId, Integer propertyKey, String propertyValue, @@ -30,7 +30,8 @@ public DatasetProperty(Integer propertyId, } @Deprecated - public DatasetProperty(Integer datasetId, + public DatasetProperty( + Integer datasetId, Integer propertyKey, String propertyValue, PropertyType type, @@ -42,7 +43,8 @@ public DatasetProperty(Integer datasetId, this.createDate = createDate; } - public DatasetProperty(Integer propertyId, + public DatasetProperty( + Integer propertyId, Integer datasetId, Integer propertyKey, String schemaProperty, @@ -53,7 +55,8 @@ public DatasetProperty(Integer propertyId, this.propertyId = propertyId; } - public DatasetProperty(Integer datasetId, + public DatasetProperty( + Integer datasetId, Integer propertyKey, String schemaProperty, String propertyValue, @@ -156,12 +159,13 @@ public boolean equals(Object o) { return false; } DatasetProperty that = (DatasetProperty) o; - return Objects.equal(datasetId, that.datasetId) && Objects.equal(propertyName, - that.propertyName) && Objects.equal(propertyValue, that.propertyValue); + return Objects.equal(datasetId, that.datasetId) + && Objects.equal(propertyName, that.propertyName) + && Objects.equal(propertyValue, that.propertyValue); } @Override public int hashCode() { return Objects.hashCode(datasetId, propertyName, propertyValue); } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/models/DatasetUpdate.java b/src/main/java/org/broadinstitute/consent/http/models/DatasetUpdate.java index 7ad0c68b9e..a82aabec29 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DatasetUpdate.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DatasetUpdate.java @@ -4,16 +4,13 @@ import java.util.List; import org.broadinstitute.consent.http.util.gson.GsonUtil; -public record DatasetUpdate( - String name, - Integer dacId, - List properties -) { +public record DatasetUpdate(String name, Integer dacId, List properties) { private static final Gson GSON = GsonUtil.gsonBuilderWithAdapters().create(); public DatasetUpdate(String json) { - this(GSON.fromJson(json, DatasetUpdate.class).getName(), + this( + GSON.fromJson(json, DatasetUpdate.class).getName(), GSON.fromJson(json, DatasetUpdate.class).getDacId(), GSON.fromJson(json, DatasetUpdate.class).getDatasetProperties()); } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Dictionary.java b/src/main/java/org/broadinstitute/consent/http/models/Dictionary.java index b0a62842a2..284eef81d5 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Dictionary.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Dictionary.java @@ -4,15 +4,12 @@ public class Dictionary { private Integer keyId; private String key; - @Deprecated - private Boolean required; - @Deprecated - private Integer displayOrder; - @Deprecated - private Integer receiveOrder; + @Deprecated private Boolean required; + @Deprecated private Integer displayOrder; + @Deprecated private Integer receiveOrder; - public Dictionary(Integer keyId, String key, Boolean required, Integer displayOrder, - Integer receiveOrder) { + public Dictionary( + Integer keyId, String key, Boolean required, Integer displayOrder, Integer receiveOrder) { this(key, required, displayOrder, receiveOrder); this.keyId = keyId; } @@ -69,4 +66,4 @@ public Integer getReceiveOrder() { public void setReceiveOrder(Integer receiveOrder) { this.receiveOrder = receiveOrder; } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/models/DraftBuilder.java b/src/main/java/org/broadinstitute/consent/http/models/DraftBuilder.java index afe9ce2665..21be54b9fe 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DraftBuilder.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DraftBuilder.java @@ -5,7 +5,7 @@ public class DraftBuilder { public static DraftInterface from(DraftType draftType) { - //Expecting new draft types to be implemented later, leaving as switch for pattern. + // Expecting new draft types to be implemented later, leaving as switch for pattern. return switch (draftType) { case STUDY_DATASET_SUBMISSION_V1 -> new DraftStudyDataset(); }; diff --git a/src/main/java/org/broadinstitute/consent/http/models/DraftInterface.java b/src/main/java/org/broadinstitute/consent/http/models/DraftInterface.java index 0da3e2c2b7..aaba7542f8 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DraftInterface.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DraftInterface.java @@ -5,7 +5,6 @@ import java.util.UUID; import org.broadinstitute.consent.http.enumeration.DraftType; - public interface DraftInterface { String getJson(); @@ -41,5 +40,4 @@ public interface DraftInterface { Set getStoredFiles(); DraftType getType(); - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/DraftStudyDataset.java b/src/main/java/org/broadinstitute/consent/http/models/DraftStudyDataset.java index 92e0a54db6..9e01181657 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DraftStudyDataset.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DraftStudyDataset.java @@ -10,8 +10,8 @@ import org.broadinstitute.consent.http.models.dataset_registration_v1.DatasetRegistrationSchemaV1; /** - * Draft represents a partial submission of 0 or more elements. This is - * an internal structure, not intended to be serialized back to the client in the entirety. + * Draft represents a partial submission of 0 or more elements. This is an internal structure, not + * intended to be serialized back to the client in the entirety. */ public class DraftStudyDataset implements DraftInterface { diff --git a/src/main/java/org/broadinstitute/consent/http/models/DraftSummary.java b/src/main/java/org/broadinstitute/consent/http/models/DraftSummary.java index 494f78b94f..3fc6ed3309 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/DraftSummary.java +++ b/src/main/java/org/broadinstitute/consent/http/models/DraftSummary.java @@ -52,7 +52,11 @@ public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } - public DraftType getDraftType() { return draftType; } + public DraftType getDraftType() { + return draftType; + } - public void setDraftType(DraftType draftType) { this.draftType = draftType; } + public void setDraftType(DraftType draftType) { + this.draftType = draftType; + } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Election.java b/src/main/java/org/broadinstitute/consent/http/models/Election.java index 58f1ca0864..9424a5c3e5 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Election.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Election.java @@ -22,69 +22,55 @@ public class Election { + " e.archived AS e_archived, " + " e.latest AS e_latest "; - @JsonProperty - private Integer electionId; + @JsonProperty private Integer electionId; - @JsonProperty - private String electionType; + @JsonProperty private String electionType; - @JsonProperty - private Boolean finalVote; + @JsonProperty private Boolean finalVote; - @JsonProperty - private String status; + @JsonProperty private String status; - @JsonProperty - private Date createDate; + @JsonProperty private Date createDate; - @JsonProperty - private Date lastUpdate; + @JsonProperty private Date lastUpdate; - @JsonProperty - private Date finalVoteDate; + @JsonProperty private Date finalVoteDate; - @JsonProperty - private String referenceId; + @JsonProperty private String referenceId; - @JsonProperty - private String finalRationale; + @JsonProperty private String finalRationale; - @JsonProperty - private Boolean finalAccessVote; + @JsonProperty private Boolean finalAccessVote; - @JsonProperty - private Integer datasetId; + @JsonProperty private Integer datasetId; - @JsonProperty - private String displayId; + @JsonProperty private String displayId; - @JsonProperty - private String dataUseLetter; + @JsonProperty private String dataUseLetter; - @JsonProperty - private String dulName; + @JsonProperty private String dulName; - @JsonProperty - private Boolean archived; + @JsonProperty private Boolean archived; - @JsonProperty - private Integer version; + @JsonProperty private Integer version; - @JsonProperty - private String consentGroupName; + @JsonProperty private String consentGroupName; - @JsonProperty - private String projectTitle; + @JsonProperty private String projectTitle; - @JsonProperty - private Map votes; + @JsonProperty private Map votes; - public Election() { - } + public Election() {} - public Election(Integer electionId, String electionType, - String status, Date createDate, - String referenceId, Date lastUpdate, Boolean finalAccessVote, Integer datasetId) { + public Election( + Integer electionId, + String electionType, + String status, + Date createDate, + String referenceId, + Date lastUpdate, + Boolean finalAccessVote, + Integer datasetId) { this.electionId = electionId; this.electionType = electionType; this.status = status; @@ -96,11 +82,18 @@ public Election(Integer electionId, String electionType, this.votes = new HashMap<>(); } - public Election(Integer electionId, String electionType, - String status, Date createDate, - String referenceId, Date lastUpdate, Boolean finalAccessVote, Integer datasetId, + public Election( + Integer electionId, + String electionType, + String status, + Date createDate, + String referenceId, + Date lastUpdate, + Boolean finalAccessVote, + Integer datasetId, Boolean archived, - String dulName, String dataUseLetter) { + String dulName, + String dataUseLetter) { this.electionId = electionId; this.electionType = electionType; this.status = status; @@ -288,13 +281,12 @@ public boolean equals(Object o) { return false; } Election election = (Election) o; - return Objects.equal(electionId, election.electionId) && - Objects.equal(referenceId, election.referenceId); + return Objects.equal(electionId, election.electionId) + && Objects.equal(referenceId, election.referenceId); } @Override public int hashCode() { return Objects.hashCode(electionId, referenceId); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Error.java b/src/main/java/org/broadinstitute/consent/http/models/Error.java index adf945950a..7efc25cc19 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Error.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Error.java @@ -1,5 +1,3 @@ package org.broadinstitute.consent.http.models; -public record Error(String message, Integer code) { - -} \ No newline at end of file +public record Error(String message, Integer code) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/FileStorageObject.java b/src/main/java/org/broadinstitute/consent/http/models/FileStorageObject.java index 8b1142ddfb..80686cd4f2 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/FileStorageObject.java +++ b/src/main/java/org/broadinstitute/consent/http/models/FileStorageObject.java @@ -160,10 +160,7 @@ public void setBlobId(BlobId blobId) { * @return The last time the file has been changed. */ public Instant getLatestUpdateDate() { - return Stream.of( - this.getCreateDate(), - this.getUpdateDate(), - this.getDeleteDate()) + return Stream.of(this.getCreateDate(), this.getUpdateDate(), this.getDeleteDate()) .filter(Objects::nonNull) .max(Instant::compareTo) // there should always at least be a create date, but if somehow not, send very old date @@ -184,7 +181,15 @@ public boolean equals(Object o) { @Override public int hashCode() { - return Objects.hash(fileStorageObjectId, entityId, fileName, blobId, category, mediaType, - createUserId, createDate, deleted); + return Objects.hash( + fileStorageObjectId, + entityId, + fileName, + blobId, + category, + mediaType, + createUserId, + createDate, + deleted); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Institution.java b/src/main/java/org/broadinstitute/consent/http/models/Institution.java index d0ecfc9e0e..152df5e8e2 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Institution.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Institution.java @@ -13,12 +13,12 @@ public class Institution { public static final String QUERY_FIELDS_WITH_I_PREFIX = - " i.institution_id as i_id, " + - " i.institution_name as i_name, " + - " i.it_director_name as i_it_director_name, " + - " i.it_director_email as i_it_director_email, " + - " i.create_date as i_create_date, " + - " i.update_date as i_update_date "; + " i.institution_id as i_id, " + + " i.institution_name as i_name, " + + " i.it_director_name as i_it_director_name, " + + " i.it_director_email as i_it_director_email, " + + " i.create_date as i_create_date, " + + " i.update_date as i_update_date "; private Integer id; private String name; @@ -39,7 +39,7 @@ public class Institution { private User createUser; private User updateUser; - //empty constructor sets all null values except create Date + // empty constructor sets all null values except create Date public Institution() { this.createDate = new Date(); } @@ -206,7 +206,6 @@ public void setUpdateUser(User updateUser) { this.updateUser = updateUser; } - @Override public boolean equals(Object institution) { if (institution == this) { @@ -216,9 +215,7 @@ public boolean equals(Object institution) { return false; } Institution other = (Institution) institution; - return new EqualsBuilder() - .append(id, other.getId()) - .isEquals(); + return new EqualsBuilder().append(id, other.getId()).isEquals(); } @Override @@ -233,7 +230,7 @@ public int hashCode() { * intentional field deletion. * * @param existing The existing institution to merge from. Must be a full institution entity with - * all required fields populated. + * all required fields populated. */ public Institution mergeUpdatableFields(Institution existing) { // These fields are not updatable, so we set them directly from the existing institution. @@ -245,20 +242,22 @@ public Institution mergeUpdatableFields(Institution existing) { // The following fields are updatable, so we merge them from the existing institution. // Institution.name is not nullable, but it is updatable to a valid value. - if (this.getName() == null || StringUtils.isBlank(this.getName()) ) { + if (this.getName() == null || StringUtils.isBlank(this.getName())) { this.setName(existing.getName()); } mergeStringField(this::getItDirectorName, existing::getItDirectorName, this::setItDirectorName); - mergeStringField(this::getItDirectorEmail, existing::getItDirectorEmail, - this::setItDirectorEmail); + mergeStringField( + this::getItDirectorEmail, existing::getItDirectorEmail, this::setItDirectorEmail); if (this.getDunsNumber() == null) { this.setDunsNumber(existing.getDunsNumber()); } mergeStringField(this::getInstitutionUrl, existing::getInstitutionUrl, this::setInstitutionUrl); mergeStringField(this::getOrgChartUrl, existing::getOrgChartUrl, this::setOrgChartUrl); - mergeStringField(this::getVerificationUrl, existing::getVerificationUrl, - this::setVerificationUrl); - mergeStringField(this::getVerificationFilename, existing::getVerificationFilename, + mergeStringField( + this::getVerificationUrl, existing::getVerificationUrl, this::setVerificationUrl); + mergeStringField( + this::getVerificationFilename, + existing::getVerificationFilename, this::setVerificationFilename); if (this.getOrganizationType() == null) { this.setOrganizationType(existing.getOrganizationType()); @@ -278,15 +277,14 @@ public Institution mergeUpdatableFields(Institution existing) { * the payload is null. If the payload value is an empty string, it will be set to null to * represent an intentionally empty value. * - * @param payloadGetter The getter for the payload field. + * @param payloadGetter The getter for the payload field. * @param existingGetter The getter for the existing field. - * @param payloadSetter The setter for the payload field. + * @param payloadSetter The setter for the payload field. */ private void mergeStringField( java.util.function.Supplier payloadGetter, java.util.function.Supplier existingGetter, - java.util.function.Consumer payloadSetter - ) { + java.util.function.Consumer payloadSetter) { String value = payloadGetter.get(); if (value == null) { payloadSetter.accept(existingGetter.get()); @@ -294,5 +292,4 @@ private void mergeStringField( payloadSetter.accept(null); } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/IntellectualProperty.java b/src/main/java/org/broadinstitute/consent/http/models/IntellectualProperty.java index d08d9a0a1e..4a30f55f67 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/IntellectualProperty.java +++ b/src/main/java/org/broadinstitute/consent/http/models/IntellectualProperty.java @@ -2,17 +2,16 @@ import java.util.List; -public record IntellectualProperty(String type, - String title, - String date, - String assignee, - String patentNumber, - Boolean filingDate, - String status, - String url, - String contact, - String ipId, - String studyId, - List tags) { - -} +public record IntellectualProperty( + String type, + String title, + String date, + String assignee, + String patentNumber, + Boolean filingDate, + String status, + String url, + String contact, + String ipId, + String studyId, + List tags) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/LibraryCard.java b/src/main/java/org/broadinstitute/consent/http/models/LibraryCard.java index e46eeea680..343af153ab 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/LibraryCard.java +++ b/src/main/java/org/broadinstitute/consent/http/models/LibraryCard.java @@ -9,13 +9,13 @@ public class LibraryCard { public static final String QUERY_FIELDS_WITH_LC_PREFIX = - " lc.id AS lc_id, " + - " lc.user_id AS lc_user_id, " + - " lc.user_name AS lc_user_name, " + - " lc.user_email AS lc_user_email, " + - " lc.create_user_id AS lc_create_user_id, " + - " lc.create_date AS lc_create_date, " + - " lc.update_user_id AS lc_update_user_id "; + " lc.id AS lc_id, " + + " lc.user_id AS lc_user_id, " + + " lc.user_name AS lc_user_name, " + + " lc.user_email AS lc_user_email, " + + " lc.create_user_id AS lc_create_user_id, " + + " lc.create_date AS lc_create_date, " + + " lc.update_user_id AS lc_update_user_id "; private Integer id; private Integer userId; @@ -97,13 +97,21 @@ public void setUpdateUserId(Integer updateUser) { this.updateUserId = updateUser; } - public List getDaaIds() {return daaIds;} + public List getDaaIds() { + return daaIds; + } - public void setDaaIds(List daaIds) {this.daaIds = daaIds;} + public void setDaaIds(List daaIds) { + this.daaIds = daaIds; + } - public List getDaas() {return daas;} + public List getDaas() { + return daas; + } - public void setDaas(List daas) {this.daas = daas;} + public void setDaas(List daas) { + this.daas = daas; + } @Override public boolean equals(Object libraryCard) { @@ -119,17 +127,23 @@ public boolean equals(Object libraryCard) { @Override public int hashCode() { - return Objects.hash(id, userId, userName, userEmail, createDate, createUserId, updateDate, - updateUserId, daaIds); + return Objects.hash( + id, + userId, + userName, + userEmail, + createDate, + createUserId, + updateDate, + updateUserId, + daaIds); } public void addDaa(Integer daaId) { if (this.daaIds == null) { this.daaIds = new ArrayList<>(); } - if (this.daaIds - .stream() - .noneMatch(d -> d.equals(daaId))) { + if (this.daaIds.stream().noneMatch(d -> d.equals(daaId))) { this.daaIds.add(daaId); } } @@ -138,9 +152,7 @@ public void removeDaa(Integer daaId) { if (this.daaIds == null) { return; } - if (this.daaIds - .stream() - .anyMatch(d -> d.equals(daaId))) { + if (this.daaIds.stream().anyMatch(d -> d.equals(daaId))) { this.daaIds.remove(daaId); } } @@ -149,9 +161,7 @@ public void addDaaObject(DataAccessAgreement daa) { if (this.daas == null) { this.daas = new ArrayList<>(); } - if (this.daas - .stream() - .noneMatch(d -> d.equals(daa))) { + if (this.daas.stream().noneMatch(d -> d.equals(daa))) { this.daas.add(daa); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Match.java b/src/main/java/org/broadinstitute/consent/http/models/Match.java index 2d30a1ce99..e035751465 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Match.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Match.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.models; - import static org.broadinstitute.consent.http.models.matching.DataUseMatchResultType.Abstain; import static org.broadinstitute.consent.http.models.matching.DataUseMatchResultType.Approve; @@ -31,8 +30,15 @@ public class Match { private List rationales; - public Match(Integer id, String consent, String purpose, Boolean match, Boolean abstain, - Boolean failed, Date createDate, String algorithmVersion) { + public Match( + Integer id, + String consent, + String purpose, + Boolean match, + Boolean abstain, + Boolean failed, + Date createDate, + String algorithmVersion) { this.id = id; this.consent = consent; this.purpose = purpose; @@ -43,8 +49,14 @@ public Match(Integer id, String consent, String purpose, Boolean match, Boolean this.algorithmVersion = algorithmVersion; } - public Match(String consentId, String purposeId, boolean match, boolean abstain, boolean failed, - MatchAlgorithm algorithm, List rationales) { + public Match( + String consentId, + String purposeId, + boolean match, + boolean abstain, + boolean failed, + MatchAlgorithm algorithm, + List rationales) { this.setConsent(consentId); this.setPurpose(purposeId); this.setMatch(match); @@ -55,8 +67,7 @@ public Match(String consentId, String purposeId, boolean match, boolean abstain, this.setRationales(rationales); } - public Match() { - } + public Match() {} public Integer getId() { return id; @@ -142,14 +153,13 @@ public void addRationale(String reason) { } } - public static Match matchFailure(String consentId, String purposeId, - List rationales) { + public static Match matchFailure(String consentId, String purposeId, List rationales) { return new Match(consentId, purposeId, false, false, true, MatchAlgorithm.V4, rationales); } - public static Match matchSuccess(String consentId, String purposeId, DataUseMatchResultType match, - List rationales) { - return new Match(consentId, purposeId, Approve(match), Abstain(match), false, MatchAlgorithm.V4, - rationales); + public static Match matchSuccess( + String consentId, String purposeId, DataUseMatchResultType match, List rationales) { + return new Match( + consentId, purposeId, Approve(match), Abstain(match), false, MatchAlgorithm.V4, rationales); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/NIHUserAccount.java b/src/main/java/org/broadinstitute/consent/http/models/NIHUserAccount.java index 798e56a0b6..ac1b7886cc 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/NIHUserAccount.java +++ b/src/main/java/org/broadinstitute/consent/http/models/NIHUserAccount.java @@ -13,8 +13,7 @@ public class NIHUserAccount { private Boolean status; - public NIHUserAccount() { - } + public NIHUserAccount() {} public NIHUserAccount(String nihUsername, String eraExpiration, Boolean status) { this.nihUsername = nihUsername; @@ -51,8 +50,9 @@ public boolean equals(Object o) { if (!(o instanceof NIHUserAccount that)) { return false; } - return Objects.equals(nihUsername, that.nihUsername) && Objects.equals( - eraExpiration, that.eraExpiration) && Objects.equals(status, that.status); + return Objects.equals(nihUsername, that.nihUsername) + && Objects.equals(eraExpiration, that.eraExpiration) + && Objects.equals(status, that.status); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/models/OidcAuthorityConfiguration.java b/src/main/java/org/broadinstitute/consent/http/models/OidcAuthorityConfiguration.java index 3795e92e1b..dd87958409 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/OidcAuthorityConfiguration.java +++ b/src/main/java/org/broadinstitute/consent/http/models/OidcAuthorityConfiguration.java @@ -1,3 +1,4 @@ package org.broadinstitute.consent.http.models; -public record OidcAuthorityConfiguration(String issuer, String authorization_endpoint, String token_endpoint) {} +public record OidcAuthorityConfiguration( + String issuer, String authorization_endpoint, String token_endpoint) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/OntologyEntry.java b/src/main/java/org/broadinstitute/consent/http/models/OntologyEntry.java index 91d9258624..b13b97f335 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/OntologyEntry.java +++ b/src/main/java/org/broadinstitute/consent/http/models/OntologyEntry.java @@ -9,8 +9,7 @@ public class OntologyEntry { String definition; List synonyms; - public OntologyEntry() { - } + public OntologyEntry() {} public String getId() { return id; @@ -43,5 +42,4 @@ public List getSynonyms() { public void setSynonyms(List synonyms) { this.synonyms = synonyms; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Presentation.java b/src/main/java/org/broadinstitute/consent/http/models/Presentation.java index 760a4929fb..c065c81eac 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Presentation.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Presentation.java @@ -2,19 +2,18 @@ import java.util.List; -public record Presentation(String title, - String url, - String date, - String authors, - String datasetCitation, - Boolean citation, - String presentationId, - String studyId, - Presenter presenter, - String event, - String location, - String format, - String access, - List tags) { - -} +public record Presentation( + String title, + String url, + String date, + String authors, + String datasetCitation, + Boolean citation, + String presentationId, + String studyId, + Presenter presenter, + String event, + String location, + String format, + String access, + List tags) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/Presenter.java b/src/main/java/org/broadinstitute/consent/http/models/Presenter.java index 001877fc8a..8386b6f301 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Presenter.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Presenter.java @@ -1,5 +1,3 @@ package org.broadinstitute.consent.http.models; -public record Presenter(String name, String email) { - -} +public record Presenter(String name, String email) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/Publication.java b/src/main/java/org/broadinstitute/consent/http/models/Publication.java index ff7e6e3d1e..3129227f95 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Publication.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Publication.java @@ -2,20 +2,18 @@ import java.util.List; -public record Publication(String title, - String pubmedId, - String publishedDate, - List authors, - String bibliographicCitation, - String datasetCitation, - Boolean citation, - String publicationId, - String studyId, - String journal, - String doi, - String url, - String access, - List tags -) { - -} +public record Publication( + String title, + String pubmedId, + String publishedDate, + List authors, + String bibliographicCitation, + String datasetCitation, + Boolean citation, + String publicationId, + String studyId, + String journal, + String doi, + String url, + String access, + List tags) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/Role.java b/src/main/java/org/broadinstitute/consent/http/models/Role.java index 4a08fbbf22..d09486caae 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Role.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Role.java @@ -4,11 +4,9 @@ public class Role { - @JsonProperty - private Integer roleId; + @JsonProperty private Integer roleId; - @JsonProperty - private String name; + @JsonProperty private String name; public Role(Integer roleId, String name) { this.roleId = roleId; diff --git a/src/main/java/org/broadinstitute/consent/http/models/Study.java b/src/main/java/org/broadinstitute/consent/http/models/Study.java index da5407b8fe..dd12caef9d 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Study.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Study.java @@ -25,7 +25,6 @@ public class Study { private Integer updateUserId; private UUID uuid; - public Integer getStudyId() { return studyId; } diff --git a/src/main/java/org/broadinstitute/consent/http/models/StudyConversion.java b/src/main/java/org/broadinstitute/consent/http/models/StudyConversion.java index f2c0812a1f..d5cbb3149c 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/StudyConversion.java +++ b/src/main/java/org/broadinstitute/consent/http/models/StudyConversion.java @@ -91,8 +91,7 @@ public String getNihAnvilUse() { return nihAnvilUse; } - public void setNihAnvilUse( - String nihAnvilUse) { + public void setNihAnvilUse(String nihAnvilUse) { this.nihAnvilUse = nihAnvilUse; } @@ -167,5 +166,4 @@ public Collection getStudyProperties() { } return props; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/StudyProperty.java b/src/main/java/org/broadinstitute/consent/http/models/StudyProperty.java index b9a172e7af..41942d579b 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/StudyProperty.java +++ b/src/main/java/org/broadinstitute/consent/http/models/StudyProperty.java @@ -11,8 +11,7 @@ public class StudyProperty { private PropertyType type; private Object value; - public StudyProperty() { - } + public StudyProperty() {} public StudyProperty(String key, Object value, PropertyType type) { this.key = key; @@ -70,8 +69,10 @@ public boolean equals(Object o) { } StudyProperty that = (StudyProperty) o; return Objects.equals(studyPropertyId, that.studyPropertyId) - && Objects.equals(studyId, that.studyId) && Objects.equals(key, that.key) - && type == that.type && Objects.equals(value, that.value); + && Objects.equals(studyId, that.studyId) + && Objects.equals(key, that.key) + && type == that.type + && Objects.equals(value, that.value); } @Override diff --git a/src/main/java/org/broadinstitute/consent/http/models/Summary.java b/src/main/java/org/broadinstitute/consent/http/models/Summary.java index a5cb5dec3d..7933ddc540 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Summary.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Summary.java @@ -4,48 +4,35 @@ public class Summary { - @JsonProperty - private Integer reviewedPositiveCases; + @JsonProperty private Integer reviewedPositiveCases; - @JsonProperty - private Integer reviewedNegativeCases; + @JsonProperty private Integer reviewedNegativeCases; - @JsonProperty - private Integer pendingCases; - - - public Summary() { - } + @JsonProperty private Integer pendingCases; + public Summary() {} public Integer getReviewedPositiveCases() { return reviewedPositiveCases; } - public void setReviewedPositiveCases(Integer reviewedPositiveCases) { this.reviewedPositiveCases = reviewedPositiveCases; } - public Integer getReviewedNegativeCases() { return reviewedNegativeCases; } - public void setReviewedNegativeCases(Integer reviewedNegativeCases) { this.reviewedNegativeCases = reviewedNegativeCases; } - public Integer getPendingCases() { return pendingCases; } - public void setPendingCases(Integer pendingCases) { this.pendingCases = pendingCases; } - - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/User.java b/src/main/java/org/broadinstitute/consent/http/models/User.java index adf0332a5e..b373f7657a 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/User.java +++ b/src/main/java/org/broadinstitute/consent/http/models/User.java @@ -21,47 +21,37 @@ public class User { public static final String QUERY_FIELDS_WITH_U_PREFIX = - " u.user_id as u_user_id, " + - " u.email as u_email, " + - " u.display_name as u_display_name, " + - " u.create_date as u_create_date, " + - " u.email_preference as u_email_preference, " + - " u.institution_id as u_institution_id," + - " u.era_commons_id as u_era_commons_id "; + " u.user_id as u_user_id, " + + " u.email as u_email, " + + " u.display_name as u_display_name, " + + " u.create_date as u_create_date, " + + " u.email_preference as u_email_preference, " + + " u.institution_id as u_institution_id," + + " u.era_commons_id as u_era_commons_id "; - @JsonProperty - private Integer userId; + @JsonProperty private Integer userId; - @JsonProperty - private String email; + @JsonProperty private String email; - @JsonProperty - private String displayName; + @JsonProperty private String displayName; - @JsonProperty - private Date createDate; + @JsonProperty private Date createDate; - @JsonProperty - private List roles; + @JsonProperty private List roles; - @JsonProperty - private List properties; + @JsonProperty private List properties; - @JsonProperty - private Boolean emailPreference; + @JsonProperty private Boolean emailPreference; - @JsonProperty - private Integer institutionId; + @JsonProperty private Integer institutionId; - @JsonProperty - private String eraCommonsId; + @JsonProperty private String eraCommonsId; private Institution institution; private LibraryCard libraryCard; - public User() { - } + public User() {} public Integer getUserId() { return userId; @@ -78,8 +68,8 @@ public User(Integer userId, String email, String displayName, Date createDate) { this.createDate = createDate; } - public User(Integer userId, String email, String displayName, Date createDate, - List roles) { + public User( + Integer userId, String email, String displayName, Date createDate, List roles) { this.userId = userId; this.email = email; this.displayName = displayName; @@ -100,9 +90,8 @@ public User(String json) { JsonObject userJsonObject = gson.fromJson(json, JsonObject.class); // There are no cases where we want to pull the create date/update date from user-provided data. // Nor do we need to retrieve the full institution object from user-provided data. - JsonObject filteredUserJsonObject = filterFields( - userJsonObject, - Arrays.asList("createDate", "institution", "libraryCard")); + JsonObject filteredUserJsonObject = + filterFields(userJsonObject, Arrays.asList("createDate", "institution", "libraryCard")); User u = gson.fromJson(filteredUserJsonObject.toString(), User.class); setUserId(u); setEmail(u); @@ -115,17 +104,18 @@ public User(String json) { /** * Private method to filter out fields that we do not want to parse from json objects. * - * @param obj The json object + * @param obj The json object * @param fields The fields to remove * @return Filtered Clone of the object. */ private JsonObject filterFields(JsonObject obj, List fields) { JsonObject copy = obj.deepCopy(); - fields.forEach(f -> { - if (copy.has(f)) { - copy.remove(f); - } - }); + fields.forEach( + f -> { + if (copy.has(f)) { + copy.remove(f); + } + }); return copy; } @@ -343,8 +333,13 @@ public boolean hasAnyUserRole(List roles) { if (null == this.getRoles() || this.getRoles().isEmpty() || null == roles || roles.isEmpty()) { return false; } else { - Set roleIds = roles.stream().filter(Objects::nonNull).map(UserRoles::getRoleId).collect(Collectors.toSet()); - Set userRoleIds = this.getRoles().stream().map(UserRole::getRoleId).collect(Collectors.toSet()); + Set roleIds = + roles.stream() + .filter(Objects::nonNull) + .map(UserRoles::getRoleId) + .collect(Collectors.toSet()); + Set userRoleIds = + this.getRoles().stream().map(UserRole::getRoleId).collect(Collectors.toSet()); return userRoleIds.stream().anyMatch(roleIds::contains); } } @@ -354,10 +349,7 @@ public List getUserRoleIdsFromUser() { if (Objects.isNull(this.getRoles())) { return List.of(); } - return this.getRoles() - .stream() - .map(UserRole::getRoleId) - .toList(); + return this.getRoles().stream().map(UserRole::getRoleId).toList(); } @Transient @@ -367,13 +359,14 @@ public boolean verifyDACRole(String roleName, Integer dacId) { if (Objects.isNull(currentRoles) || Objects.isNull(role)) { return false; } - List targetRoles = currentRoles.stream() - .filter(r -> r.getName().equals(role.getRoleName()) - && r.getRoleId().equals(role.getRoleId()) - && Objects.equals(r.getDacId(), dacId)) - .toList(); + List targetRoles = + currentRoles.stream() + .filter( + r -> + r.getName().equals(role.getRoleName()) + && r.getRoleId().equals(role.getRoleId()) + && Objects.equals(r.getDacId(), dacId)) + .toList(); return !targetRoles.isEmpty(); - } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/UserProperty.java b/src/main/java/org/broadinstitute/consent/http/models/UserProperty.java index f36af30492..89f29660ba 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/UserProperty.java +++ b/src/main/java/org/broadinstitute/consent/http/models/UserProperty.java @@ -1,35 +1,28 @@ package org.broadinstitute.consent.http.models; - import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; public class UserProperty { public static final String QUERY_FIELDS_WITH_UP_PREFIX = - " up.property_id AS up_property_id, " + - " up.user_id AS up_user_id, " + - " up.property_key AS up_property_key, " + - " up.property_value AS up_property_value "; - - @JsonProperty - private Integer propertyId; + " up.property_id AS up_property_id, " + + " up.user_id AS up_user_id, " + + " up.property_key AS up_property_key, " + + " up.property_value AS up_property_value "; - @JsonProperty - private Integer userId; + @JsonProperty private Integer propertyId; - @JsonProperty - private String propertyKey; + @JsonProperty private Integer userId; - @JsonProperty - private String propertyValue; + @JsonProperty private String propertyKey; + @JsonProperty private String propertyValue; - public UserProperty() { - } + public UserProperty() {} - public UserProperty(Integer propertyId, Integer userId, String propertyKey, - String propertyValue) { + public UserProperty( + Integer propertyId, Integer userId, String propertyKey, String propertyValue) { this.propertyId = propertyId; this.userId = userId; this.propertyKey = propertyKey; diff --git a/src/main/java/org/broadinstitute/consent/http/models/UserRole.java b/src/main/java/org/broadinstitute/consent/http/models/UserRole.java index bfa38cbc4a..5ffaa832ea 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/UserRole.java +++ b/src/main/java/org/broadinstitute/consent/http/models/UserRole.java @@ -6,23 +6,17 @@ public class UserRole { - @JsonProperty - private Integer userRoleId; + @JsonProperty private Integer userRoleId; - @JsonProperty - private Integer userId; + @JsonProperty private Integer userId; - @JsonProperty - private Integer roleId; + @JsonProperty private Integer roleId; - @JsonProperty - private String name; + @JsonProperty private String name; - @JsonProperty - private Integer dacId; + @JsonProperty private Integer dacId; - public UserRole() { - } + public UserRole() {} public UserRole(Integer roleId, String name) { this.roleId = roleId; @@ -97,5 +91,4 @@ public boolean equals(Object o) { public String toString() { return new Gson().toJson(this); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/UserUpdateFields.java b/src/main/java/org/broadinstitute/consent/http/models/UserUpdateFields.java index 440163258f..c5df732023 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/UserUpdateFields.java +++ b/src/main/java/org/broadinstitute/consent/http/models/UserUpdateFields.java @@ -14,10 +14,10 @@ public class UserUpdateFields { // We can only update non-DAC-related roles so always filter those out for addition or removal - protected static final List IGNORE_ROLE_IDS = List.of(UserRoles.CHAIRPERSON.getRoleId(), - UserRoles.MEMBER.getRoleId()); - private static final List VALID_ROLE_IDS = Arrays.stream(UserRoles.values()) - .map(UserRoles::getRoleId).toList(); + protected static final List IGNORE_ROLE_IDS = + List.of(UserRoles.CHAIRPERSON.getRoleId(), UserRoles.MEMBER.getRoleId()); + private static final List VALID_ROLE_IDS = + Arrays.stream(UserRoles.values()).map(UserRoles::getRoleId).toList(); private String displayName; private Boolean emailPreference; private List userRoleIds; @@ -92,9 +92,11 @@ public List getRoleIdsToAdd(List currentUserRoleIds) { return this.getUserRoleIds().stream() .filter( id -> - !currentUserRoleIds.contains(id) && // Don't add any that already exist - !IGNORE_ROLE_IDS.contains(id) && // Never add ignorable roles - VALID_ROLE_IDS.contains(id) // Only add roles we know about + !currentUserRoleIds.contains(id) + && // Don't add any that already exist + !IGNORE_ROLE_IDS.contains(id) + && // Never add ignorable roles + VALID_ROLE_IDS.contains(id) // Only add roles we know about ) .toList(); } @@ -110,14 +112,17 @@ public List getRoleIdsToAdd(List currentUserRoleIds) { public List getRoleIdsToRemove(List currentUserRoleIds) { return currentUserRoleIds.stream() .filter( - id -> !getUserRoleIds().contains(id) && - // Remove roles that are NOT in the new role id list - !Objects.equals(id, UserRoles.RESEARCHER.getRoleId()) && - // Never remove the researcher role - !IGNORE_ROLE_IDS.contains(id) && - // Never remove ignorable roles - VALID_ROLE_IDS.contains( - id) // Only remove roles we know about + id -> + !getUserRoleIds().contains(id) + && + // Remove roles that are NOT in the new role id list + !Objects.equals(id, UserRoles.RESEARCHER.getRoleId()) + && + // Never remove the researcher role + !IGNORE_ROLE_IDS.contains(id) + && + // Never remove ignorable roles + VALID_ROLE_IDS.contains(id) // Only remove roles we know about ) .toList(); } @@ -129,14 +134,15 @@ public boolean equals(Object o) { } UserUpdateFields that = (UserUpdateFields) o; - return Objects.equals(displayName, that.displayName) && Objects.equals(emailPreference, that.emailPreference) - && Objects.equals(userRoleIds, that.userRoleIds) && Objects.equals(eraCommonsId, - that.eraCommonsId) && Objects.equals(daaAcceptance, that.daaAcceptance); + return Objects.equals(displayName, that.displayName) + && Objects.equals(emailPreference, that.emailPreference) + && Objects.equals(userRoleIds, that.userRoleIds) + && Objects.equals(eraCommonsId, that.eraCommonsId) + && Objects.equals(daaAcceptance, that.daaAcceptance); } @Override public int hashCode() { - return Objects.hash(displayName, emailPreference, userRoleIds, eraCommonsId, - daaAcceptance); + return Objects.hash(displayName, emailPreference, userRoleIds, eraCommonsId, daaAcceptance); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/Vote.java b/src/main/java/org/broadinstitute/consent/http/models/Vote.java index 172b6fd3d5..10b0a8e4a2 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/Vote.java +++ b/src/main/java/org/broadinstitute/consent/http/models/Vote.java @@ -20,44 +20,40 @@ public class Vote { + " v.update_date as v_update_date, " + " v.type as v_type "; - @JsonProperty - private Integer voteId; + @JsonProperty private Integer voteId; - @JsonProperty - private Boolean vote; + @JsonProperty private Boolean vote; - @JsonProperty - private Integer userId; + @JsonProperty private Integer userId; - @JsonProperty - private Date createDate; + @JsonProperty private Date createDate; - @JsonProperty - private Date updateDate; + @JsonProperty private Date updateDate; - @JsonProperty - private Integer electionId; + @JsonProperty private Integer electionId; - @JsonProperty - private String rationale; + @JsonProperty private String rationale; - @JsonProperty - private String type; + @JsonProperty private String type; - @JsonProperty - private Boolean isReminderSent; + @JsonProperty private Boolean isReminderSent; - @JsonProperty - private Boolean hasConcerns; + @JsonProperty private Boolean hasConcerns; - @JsonProperty - private String displayName; + @JsonProperty private String displayName; - public Vote() { - } + public Vote() {} - public Vote(Integer voteId, Boolean vote, Integer userId, Date createDate, Date updateDate, - Integer electionId, String rationale, String type, Boolean isReminderSent, + public Vote( + Integer voteId, + Boolean vote, + Integer userId, + Date createDate, + Date updateDate, + Integer electionId, + String rationale, + String type, + Boolean isReminderSent, Boolean hasConcerns) { this.voteId = voteId; this.vote = vote; @@ -164,15 +160,13 @@ public String toString() { return new Gson().toJson(this); } - public static class VoteUpdate { private Boolean vote; private String rationale; private List voteIds; - public VoteUpdate() { - } + public VoteUpdate() {} public VoteUpdate(Boolean vote, String rationale, List voteIds) { this.vote = vote; @@ -210,8 +204,7 @@ public static class RationaleUpdate { private List voteIds; private String rationale; - public RationaleUpdate() { - } + public RationaleUpdate() {} public List getVoteIds() { return voteIds; @@ -229,4 +222,4 @@ public void setRationale(String rationale) { this.rationale = rationale; } } -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/AlternativeDataSharingPlanReason.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/AlternativeDataSharingPlanReason.java index 0b0285da97..e1b207bc37 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/AlternativeDataSharingPlanReason.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/AlternativeDataSharingPlanReason.java @@ -6,7 +6,6 @@ import java.util.Map; public enum AlternativeDataSharingPlanReason { - LEGAL_RESTRICTIONS("Legal Restrictions"), INFORMED_CONSENT_PROCESSES_ARE_INADEQUATE_TO_SUPPORT_DATA_FOR_SHARING_FOR_THE_FOLLOWING_REASONS( "Informed consent processes are inadequate to support data for sharing for the following reasons:"), @@ -21,7 +20,8 @@ public enum AlternativeDataSharingPlanReason { OTHER_INFORMED_CONSENT_LIMITATIONS_OR_CONCERNS("Other informed consent limitations or concerns"), OTHER("Other"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map CONSTANTS = + new HashMap(); static { for (AlternativeDataSharingPlanReason c : values()) { @@ -52,5 +52,4 @@ public static AlternativeDataSharingPlanReason fromValue(String value) { return constant; } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/ConsentGroup.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/ConsentGroup.java index 86b00b6f90..68e4e1288a 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/ConsentGroup.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/ConsentGroup.java @@ -14,557 +14,436 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "datasetId", - "datasetIdentifier", - "consentGroupName", - "accessManagement", - "generalResearchUse", - "hmb", - "diseaseSpecificUse", - "poa", - "otherPrimary", - "nmds", - "gso", - "pub", - "col", - "irb", - "gs", - "mor", - "morDate", - "npu", - "otherSecondary", - "dataAccessCommitteeId", - "dataLocation", - "url", - "numberOfParticipants", - "fileTypes" + "datasetId", + "datasetIdentifier", + "consentGroupName", + "accessManagement", + "generalResearchUse", + "hmb", + "diseaseSpecificUse", + "poa", + "otherPrimary", + "nmds", + "gso", + "pub", + "col", + "irb", + "gs", + "mor", + "morDate", + "npu", + "otherSecondary", + "dataAccessCommitteeId", + "dataLocation", + "url", + "numberOfParticipants", + "fileTypes" }) public class ConsentGroup { - /** - * Dataset Id - */ + /** Dataset Id */ @JsonProperty("datasetId") @JsonPropertyDescription("Dataset Id") private Integer datasetId; - /** - * Dataset Identifier - */ + + /** Dataset Identifier */ @JsonProperty("datasetIdentifier") @JsonPropertyDescription("Dataset Identifier") private String datasetIdentifier; - /** - * Consent Group Name - */ + + /** Consent Group Name */ @JsonProperty("consentGroupName") @JsonPropertyDescription("Consent Group Name") private String consentGroupName; - /** - * No Restrictions - */ + + /** No Restrictions */ @JsonProperty("accessManagement") @JsonPropertyDescription("One of Controlled, Open, or External") private AccessManagement accessManagement; - /** - * General Research Use - */ + + /** General Research Use */ @JsonProperty("generalResearchUse") @JsonPropertyDescription("General Research Use") private Boolean generalResearchUse; - /** - * Health/Medical/Biomedical Research Use - */ + + /** Health/Medical/Biomedical Research Use */ @JsonProperty("hmb") @JsonPropertyDescription("Health/Medical/Biomedical Research Use") private Boolean hmb; - /** - * Disease-Specific Research Use - */ + + /** Disease-Specific Research Use */ @JsonProperty("diseaseSpecificUse") @JsonPropertyDescription("Disease-Specific Research Use") private List diseaseSpecificUse = new ArrayList(); - /** - * Populations, Origins, Ancestry Use - */ + + /** Populations, Origins, Ancestry Use */ @JsonProperty("poa") @JsonPropertyDescription("Populations, Origins, Ancestry Use") private Boolean poa; - /** - * Other - */ + + /** Other */ @JsonProperty("otherPrimary") @JsonPropertyDescription("Other") private String otherPrimary; - /** - * No Methods Development or validation studies (NMDS) - */ + + /** No Methods Development or validation studies (NMDS) */ @JsonProperty("nmds") @JsonPropertyDescription("No Methods Development or validation studies (NMDS)") private Boolean nmds; - /** - * Genetic studies only (GSO) - */ + + /** Genetic studies only (GSO) */ @JsonProperty("gso") @JsonPropertyDescription("Genetic studies only (GSO)") private Boolean gso; - /** - * Publication Required (PUB) - */ + + /** Publication Required (PUB) */ @JsonProperty("pub") @JsonPropertyDescription("Publication Required (PUB)") private Boolean pub; - /** - * Collaboration Required (COL) - */ + + /** Collaboration Required (COL) */ @JsonProperty("col") @JsonPropertyDescription("Collaboration Required (COL)") private Boolean col; - /** - * Ethics Approval Required (IRB) - */ + + /** Ethics Approval Required (IRB) */ @JsonProperty("irb") @JsonPropertyDescription("Ethics Approval Required (IRB)") private Boolean irb; - /** - * Geographic Restriction (GS-) - */ + + /** Geographic Restriction (GS-) */ @JsonProperty("gs") @JsonPropertyDescription("Geographic Restriction (GS-)") private String gs; - /** - * Publication Moratorium (MOR) - */ + + /** Publication Moratorium (MOR) */ @JsonProperty("mor") @JsonPropertyDescription("Publication Moratorium (MOR)") private Boolean mor; - /** - * Publication Moratorium Date (MOR) - */ + + /** Publication Moratorium Date (MOR) */ @JsonProperty("morDate") @JsonPropertyDescription("Publication Moratorium Date (MOR)") private String morDate; - /** - * Non-profit Use Only (NPU) - */ + + /** Non-profit Use Only (NPU) */ @JsonProperty("npu") @JsonPropertyDescription("Non-profit Use Only (NPU)") private Boolean npu; - /** - * Other - */ + + /** Other */ @JsonProperty("otherSecondary") @JsonPropertyDescription("Other") private String otherSecondary; - /** - * Data Access Committee ID - */ + + /** Data Access Committee ID */ @JsonProperty("dataAccessCommitteeId") @JsonPropertyDescription("Data Access Committee ID") private Integer dataAccessCommitteeId; - /** - * Data Location - */ + + /** Data Location */ @JsonProperty("dataLocation") @JsonPropertyDescription("Data Location") private ConsentGroup.DataLocation dataLocation; - /** - * Free text field for entering URL of data - */ + + /** Free text field for entering URL of data */ @JsonProperty("url") @JsonPropertyDescription("Free text field for entering URL of data") private URI url; - /** - * # of Participants (Required) - */ + + /** # of Participants (Required) */ @JsonProperty("numberOfParticipants") @JsonPropertyDescription("# of Participants") private Integer numberOfParticipants; - /** - * List of File Types - */ + + /** List of File Types */ @JsonProperty("fileTypes") @JsonPropertyDescription("List of File Types") private List fileTypes = new ArrayList(); - /** - * Dataset Id - */ + /** Dataset Id */ @JsonProperty("datasetId") public Integer getDatasetId() { return datasetId; } - /** - * Dataset Id - */ + /** Dataset Id */ @JsonProperty("datasetId") public void setDatasetId(Integer datasetId) { this.datasetId = datasetId; } - /** - * Dataset Identifier - */ + /** Dataset Identifier */ @JsonProperty("datasetIdentifier") public String getDatasetIdentifier() { return datasetIdentifier; } - /** - * Dataset Identifier - */ + /** Dataset Identifier */ @JsonProperty("datasetIdentifier") public void setDatasetIdentifier(String datasetIdentifier) { this.datasetIdentifier = datasetIdentifier; } - /** - * Consent Group Name - */ + /** Consent Group Name */ @JsonProperty("consentGroupName") public String getConsentGroupName() { return consentGroupName; } - /** - * Consent Group Name - */ + /** Consent Group Name */ @JsonProperty("consentGroupName") public void setConsentGroupName(String consentGroupName) { this.consentGroupName = consentGroupName; } - /** - * No Restrictions - */ + /** No Restrictions */ @JsonProperty("accessManagement") public AccessManagement getAccessManagement() { return accessManagement; } - /** - * No Restrictions - */ + /** No Restrictions */ @JsonProperty("accessManagement") public void setAccessManagement(AccessManagement accessManagement) { this.accessManagement = accessManagement; } - /** - * General Research Use - */ + /** General Research Use */ @JsonProperty("generalResearchUse") public Boolean getGeneralResearchUse() { return generalResearchUse; } - /** - * General Research Use - */ + /** General Research Use */ @JsonProperty("generalResearchUse") public void setGeneralResearchUse(Boolean generalResearchUse) { this.generalResearchUse = generalResearchUse; } - /** - * Health/Medical/Biomedical Research Use - */ + /** Health/Medical/Biomedical Research Use */ @JsonProperty("hmb") public Boolean getHmb() { return hmb; } - /** - * Health/Medical/Biomedical Research Use - */ + /** Health/Medical/Biomedical Research Use */ @JsonProperty("hmb") public void setHmb(Boolean hmb) { this.hmb = hmb; } - /** - * Disease-Specific Research Use - */ + /** Disease-Specific Research Use */ @JsonProperty("diseaseSpecificUse") public List getDiseaseSpecificUse() { return diseaseSpecificUse; } - /** - * Disease-Specific Research Use - */ + /** Disease-Specific Research Use */ @JsonProperty("diseaseSpecificUse") public void setDiseaseSpecificUse(List diseaseSpecificUse) { this.diseaseSpecificUse = diseaseSpecificUse; } - /** - * Populations, Origins, Ancestry Use - */ + /** Populations, Origins, Ancestry Use */ @JsonProperty("poa") public Boolean getPoa() { return poa; } - /** - * Populations, Origins, Ancestry Use - */ + /** Populations, Origins, Ancestry Use */ @JsonProperty("poa") public void setPoa(Boolean poa) { this.poa = poa; } - /** - * Other - */ + /** Other */ @JsonProperty("otherPrimary") public String getOtherPrimary() { return otherPrimary; } - /** - * Other - */ + /** Other */ @JsonProperty("otherPrimary") public void setOtherPrimary(String otherPrimary) { this.otherPrimary = otherPrimary; } - /** - * No Methods Development or validation studies (NMDS) - */ + /** No Methods Development or validation studies (NMDS) */ @JsonProperty("nmds") public Boolean getNmds() { return nmds; } - /** - * No Methods Development or validation studies (NMDS) - */ + /** No Methods Development or validation studies (NMDS) */ @JsonProperty("nmds") public void setNmds(Boolean nmds) { this.nmds = nmds; } - /** - * Genetic studies only (GSO) - */ + /** Genetic studies only (GSO) */ @JsonProperty("gso") public Boolean getGso() { return gso; } - /** - * Genetic studies only (GSO) - */ + /** Genetic studies only (GSO) */ @JsonProperty("gso") public void setGso(Boolean gso) { this.gso = gso; } - /** - * Publication Required (PUB) - */ + /** Publication Required (PUB) */ @JsonProperty("pub") public Boolean getPub() { return pub; } - /** - * Publication Required (PUB) - */ + /** Publication Required (PUB) */ @JsonProperty("pub") public void setPub(Boolean pub) { this.pub = pub; } - /** - * Collaboration Required (COL) - */ + /** Collaboration Required (COL) */ @JsonProperty("col") public Boolean getCol() { return col; } - /** - * Collaboration Required (COL) - */ + /** Collaboration Required (COL) */ @JsonProperty("col") public void setCol(Boolean col) { this.col = col; } - /** - * Ethics Approval Required (IRB) - */ + /** Ethics Approval Required (IRB) */ @JsonProperty("irb") public Boolean getIrb() { return irb; } - /** - * Ethics Approval Required (IRB) - */ + /** Ethics Approval Required (IRB) */ @JsonProperty("irb") public void setIrb(Boolean irb) { this.irb = irb; } - /** - * Geographic Restriction (GS-) - */ + /** Geographic Restriction (GS-) */ @JsonProperty("gs") public String getGs() { return gs; } - /** - * Geographic Restriction (GS-) - */ + /** Geographic Restriction (GS-) */ @JsonProperty("gs") public void setGs(String gs) { this.gs = gs; } - /** - * Publication Moratorium (MOR) - */ + /** Publication Moratorium (MOR) */ @JsonProperty("mor") public Boolean getMor() { return mor; } - /** - * Publication Moratorium (MOR) - */ + /** Publication Moratorium (MOR) */ @JsonProperty("mor") public void setMor(Boolean mor) { this.mor = mor; } - /** - * Publication Moratorium Date (MOR) - */ + /** Publication Moratorium Date (MOR) */ @JsonProperty("morDate") public String getMorDate() { return morDate; } - /** - * Publication Moratorium Date (MOR) - */ + /** Publication Moratorium Date (MOR) */ @JsonProperty("morDate") public void setMorDate(String morDate) { this.morDate = morDate; } - /** - * Non-profit Use Only (NPU) - */ + /** Non-profit Use Only (NPU) */ @JsonProperty("npu") public Boolean getNpu() { return npu; } - /** - * Non-profit Use Only (NPU) - */ + /** Non-profit Use Only (NPU) */ @JsonProperty("npu") public void setNpu(Boolean npu) { this.npu = npu; } - /** - * Other - */ + /** Other */ @JsonProperty("otherSecondary") public String getOtherSecondary() { return otherSecondary; } - /** - * Other - */ + /** Other */ @JsonProperty("otherSecondary") public void setOtherSecondary(String otherSecondary) { this.otherSecondary = otherSecondary; } - /** - * Data Access Committee ID - */ + /** Data Access Committee ID */ @JsonProperty("dataAccessCommitteeId") public Integer getDataAccessCommitteeId() { return dataAccessCommitteeId; } - /** - * Data Access Committee ID - */ + /** Data Access Committee ID */ @JsonProperty("dataAccessCommitteeId") public void setDataAccessCommitteeId(Integer dataAccessCommitteeId) { this.dataAccessCommitteeId = dataAccessCommitteeId; } - /** - * Data Location - */ + /** Data Location */ @JsonProperty("dataLocation") public ConsentGroup.DataLocation getDataLocation() { return dataLocation; } - /** - * Data Location - */ + /** Data Location */ @JsonProperty("dataLocation") public void setDataLocation(ConsentGroup.DataLocation dataLocation) { this.dataLocation = dataLocation; } - /** - * Free text field for entering URL of data - */ + /** Free text field for entering URL of data */ @JsonProperty("url") public URI getUrl() { return url; } - /** - * Free text field for entering URL of data - */ + /** Free text field for entering URL of data */ @JsonProperty("url") public void setUrl(URI url) { this.url = url; } - /** - * # of Participants (Required) - */ + /** # of Participants (Required) */ @JsonProperty("numberOfParticipants") public Integer getNumberOfParticipants() { return numberOfParticipants; } - /** - * # of Participants (Required) - */ + /** # of Participants (Required) */ @JsonProperty("numberOfParticipants") public void setNumberOfParticipants(Integer numberOfParticipants) { this.numberOfParticipants = numberOfParticipants; } - /** - * List of File Types - */ + /** List of File Types */ @JsonProperty("fileTypes") public List getFileTypes() { return fileTypes; } - /** - * List of File Types - */ + /** List of File Types */ @JsonProperty("fileTypes") public void setFileTypes(List fileTypes) { this.fileTypes = fileTypes; @@ -573,8 +452,10 @@ public void setFileTypes(List fileTypes) { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(ConsentGroup.class.getName()).append('@') - .append(Integer.toHexString(System.identityHashCode(this))).append('['); + sb.append(ConsentGroup.class.getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(this))) + .append('['); sb.append("datasetId"); sb.append('='); sb.append(((this.datasetId == null) ? "" : this.datasetId)); @@ -684,30 +565,35 @@ public int hashCode() { int result = 1; result = ((result * 31) + ((this.col == null) ? 0 : this.col.hashCode())); result = ((result * 31) + ((this.gso == null) ? 0 : this.gso.hashCode())); - result = ((result * 31) + ((this.generalResearchUse == null) ? 0 - : this.generalResearchUse.hashCode())); + result = + ((result * 31) + + ((this.generalResearchUse == null) ? 0 : this.generalResearchUse.hashCode())); result = ((result * 31) + ((this.poa == null) ? 0 : this.poa.hashCode())); result = ((result * 31) + ((this.morDate == null) ? 0 : this.morDate.hashCode())); - result = ((result * 31) + ((this.dataAccessCommitteeId == null) ? 0 - : this.dataAccessCommitteeId.hashCode())); + result = + ((result * 31) + + ((this.dataAccessCommitteeId == null) ? 0 : this.dataAccessCommitteeId.hashCode())); result = ((result * 31) + ((this.otherPrimary == null) ? 0 : this.otherPrimary.hashCode())); result = ((result * 31) + ((this.gs == null) ? 0 : this.gs.hashCode())); result = ((result * 31) + ((this.url == null) ? 0 : this.url.hashCode())); - result = ((result * 31) + ((this.numberOfParticipants == null) ? 0 - : this.numberOfParticipants.hashCode())); + result = + ((result * 31) + + ((this.numberOfParticipants == null) ? 0 : this.numberOfParticipants.hashCode())); result = ((result * 31) + ((this.fileTypes == null) ? 0 : this.fileTypes.hashCode())); - result = ((result * 31) + ((this.diseaseSpecificUse == null) ? 0 - : this.diseaseSpecificUse.hashCode())); + result = + ((result * 31) + + ((this.diseaseSpecificUse == null) ? 0 : this.diseaseSpecificUse.hashCode())); result = ((result * 31) + ((this.datasetId == null) ? 0 : this.datasetId.hashCode())); - result = ((result * 31) + ((this.datasetIdentifier == null) ? 0 - : this.datasetIdentifier.hashCode())); - result = ((result * 31) + ((this.consentGroupName == null) ? 0 - : this.consentGroupName.hashCode())); + result = + ((result * 31) + + ((this.datasetIdentifier == null) ? 0 : this.datasetIdentifier.hashCode())); + result = + ((result * 31) + ((this.consentGroupName == null) ? 0 : this.consentGroupName.hashCode())); result = ((result * 31) + ((this.mor == null) ? 0 : this.mor.hashCode())); result = ((result * 31) + ((this.npu == null) ? 0 : this.npu.hashCode())); result = ((result * 31) + ((this.dataLocation == null) ? 0 : this.dataLocation.hashCode())); - result = ((result * 31) + ((this.accessManagement == null) ? 0 - : this.accessManagement.hashCode())); + result = + ((result * 31) + ((this.accessManagement == null) ? 0 : this.accessManagement.hashCode())); result = ((result * 31) + ((this.irb == null) ? 0 : this.irb.hashCode())); result = ((result * 31) + ((this.hmb == null) ? 0 : this.hmb.hashCode())); result = ((result * 31) + ((this.pub == null) ? 0 : this.pub.hashCode())); @@ -725,57 +611,115 @@ public boolean equals(Object other) { return false; } ConsentGroup rhs = ((ConsentGroup) other); - return (((((((((((((((( - ((((((this.col == rhs.col) || ((this.col != null) && this.col.equals(rhs.col))) && ( - (this.gso == rhs.gso) || ((this.gso != null) && this.gso.equals(rhs.gso)))) && ( - (this.generalResearchUse == rhs.generalResearchUse) || ( - (this.generalResearchUse != null) && this.generalResearchUse.equals( - rhs.generalResearchUse)))) && ((this.poa == rhs.poa) || ((this.poa != null) - && this.poa.equals(rhs.poa)))) && ((this.morDate == rhs.morDate) || ( - (this.morDate != null) && this.morDate.equals(rhs.morDate)))) && ( - (this.dataAccessCommitteeId == rhs.dataAccessCommitteeId) || ( - (this.dataAccessCommitteeId != null) && this.dataAccessCommitteeId.equals( - rhs.dataAccessCommitteeId)))) && ((this.otherPrimary == rhs.otherPrimary) || ( - (this.otherPrimary != null) && this.otherPrimary.equals(rhs.otherPrimary)))) && ( - (this.gs == rhs.gs) || ((this.gs != null) && this.gs.equals(rhs.gs)))) && ( - (this.url == rhs.url) || ((this.url != null) && this.url.equals(rhs.url)))) && ( - (this.fileTypes == rhs.fileTypes) || ((this.fileTypes != null) && this.fileTypes.equals( - rhs.fileTypes)))) && ((this.diseaseSpecificUse == rhs.diseaseSpecificUse) || ( - (this.diseaseSpecificUse != null) && this.diseaseSpecificUse.equals( - rhs.diseaseSpecificUse)))) && ((this.datasetId == rhs.datasetId) || ( - (this.datasetId != null) && this.datasetId.equals(rhs.datasetId))) && ( - (this.datasetIdentifier == rhs.datasetIdentifier) || ( - (this.datasetIdentifier != null) && this.datasetIdentifier.equals( - rhs.datasetIdentifier))) && ( - (this.consentGroupName == rhs.consentGroupName) || ( - (this.consentGroupName != null) && this.consentGroupName.equals(rhs.consentGroupName)))) - && ((this.mor == rhs.mor) || ((this.mor != null) && this.mor.equals(rhs.mor)))) && ( - (this.npu == rhs.npu) || ((this.npu != null) && this.npu.equals(rhs.npu)))) && ( - (this.dataLocation == rhs.dataLocation) || ((this.dataLocation != null) - && this.dataLocation.equals(rhs.dataLocation)))) && ( - (this.accessManagement == rhs.accessManagement) - || ((this.accessManagement != null) && this.accessManagement.equals( - rhs.accessManagement)))) && ( - (this.irb == rhs.irb) || ((this.irb != null) && this.irb.equals(rhs.irb)))) && ( - (this.hmb == rhs.hmb) || ((this.hmb != null) && this.hmb.equals(rhs.hmb)))) && ( - (this.pub == rhs.pub) || ((this.pub != null) && this.pub.equals(rhs.pub)))) && ( - (this.nmds == rhs.nmds) || ((this.nmds != null) && this.nmds.equals(rhs.nmds)))) && ( - (this.otherSecondary == rhs.otherSecondary) || ((this.otherSecondary != null) - && this.otherSecondary.equals(rhs.otherSecondary)))); - } - - - /** - * Data Location - */ + return ((((((((((((((((((((((this.col == rhs.col) + || ((this + .col + != null) + && this + .col + .equals( + rhs.col))) + && ((this.gso + == rhs.gso) + || ((this + .gso + != null) + && this + .gso + .equals( + rhs.gso)))) + && ((this + .generalResearchUse + == rhs.generalResearchUse) + || ((this + .generalResearchUse + != null) + && this + .generalResearchUse + .equals( + rhs.generalResearchUse)))) + && ((this.poa + == rhs.poa) + || ((this.poa + != null) + && this.poa + .equals( + rhs.poa)))) + && ((this.morDate + == rhs.morDate) + || ((this.morDate + != null) + && this.morDate + .equals( + rhs.morDate)))) + && ((this.dataAccessCommitteeId + == rhs.dataAccessCommitteeId) + || ((this + .dataAccessCommitteeId + != null) + && this + .dataAccessCommitteeId + .equals( + rhs.dataAccessCommitteeId)))) + && ((this.otherPrimary + == rhs.otherPrimary) + || ((this.otherPrimary != null) + && this.otherPrimary.equals( + rhs.otherPrimary)))) + && ((this.gs == rhs.gs) + || ((this.gs != null) + && this.gs.equals(rhs.gs)))) + && ((this.url == rhs.url) + || ((this.url != null) + && this.url.equals(rhs.url)))) + && ((this.fileTypes == rhs.fileTypes) + || ((this.fileTypes != null) + && this.fileTypes.equals( + rhs.fileTypes)))) + && ((this.diseaseSpecificUse + == rhs.diseaseSpecificUse) + || ((this.diseaseSpecificUse != null) + && this.diseaseSpecificUse.equals( + rhs.diseaseSpecificUse)))) + && ((this.datasetId == rhs.datasetId) + || ((this.datasetId != null) + && this.datasetId.equals(rhs.datasetId))) + && ((this.datasetIdentifier == rhs.datasetIdentifier) + || ((this.datasetIdentifier != null) + && this.datasetIdentifier.equals( + rhs.datasetIdentifier))) + && ((this.consentGroupName == rhs.consentGroupName) + || ((this.consentGroupName != null) + && this.consentGroupName.equals( + rhs.consentGroupName)))) + && ((this.mor == rhs.mor) + || ((this.mor != null) && this.mor.equals(rhs.mor)))) + && ((this.npu == rhs.npu) + || ((this.npu != null) && this.npu.equals(rhs.npu)))) + && ((this.dataLocation == rhs.dataLocation) + || ((this.dataLocation != null) + && this.dataLocation.equals(rhs.dataLocation)))) + && ((this.accessManagement == rhs.accessManagement) + || ((this.accessManagement != null) + && this.accessManagement.equals(rhs.accessManagement)))) + && ((this.irb == rhs.irb) + || ((this.irb != null) && this.irb.equals(rhs.irb)))) + && ((this.hmb == rhs.hmb) || ((this.hmb != null) && this.hmb.equals(rhs.hmb)))) + && ((this.pub == rhs.pub) || ((this.pub != null) && this.pub.equals(rhs.pub)))) + && ((this.nmds == rhs.nmds) || ((this.nmds != null) && this.nmds.equals(rhs.nmds)))) + && ((this.otherSecondary == rhs.otherSecondary) + || ((this.otherSecondary != null) && this.otherSecondary.equals(rhs.otherSecondary)))); + } + + /** Data Location */ public enum DataLocation { - AN_VIL_WORKSPACE("AnVIL Workspace"), TERRA_WORKSPACE("Terra Workspace"), TDR_LOCATION("TDR Location"), NOT_DETERMINED("Not Determined"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map CONSTANTS = + new HashMap(); static { for (ConsentGroup.DataLocation c : values()) { @@ -806,7 +750,6 @@ public static ConsentGroup.DataLocation fromValue(String value) { return constant; } } - } /* @@ -817,7 +760,8 @@ public enum AccessManagement { CONTROLLED("controlled"), EXTERNAL("external"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map CONSTANTS = + new HashMap(); static { for (ConsentGroup.AccessManagement c : values()) { @@ -849,5 +793,4 @@ public static ConsentGroup.AccessManagement fromValue(String value) { } } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1.java index 8e9ca90d0f..03b8c4edca 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1.java @@ -11,728 +11,595 @@ import java.util.List; import java.util.Map; - /** * Dataset Registration Schema - *

- * Dynamically generated java class from jsonschema2pojo - *

- * See: https://github.com/joelittlejohn/jsonschema2pojo - * jsonschema2pojo --source src/main/resources/dataset-registration-schema_v1.json --target + * + *

Dynamically generated java class from jsonschema2pojo + * + *

See: https://github.com/joelittlejohn/jsonschema2pojo + * jsonschema2pojo --source src/main/resources/dataset-registration-schema_v1.json --target * java-gen - *

- * Also see https://jsonschemalint.com/#/version/draft-04/markup/json for validating json. + * + *

Also see https://jsonschemalint.com/#/version/draft-04/markup/json for validating json. */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "studyId", - "studyName", - "studyType", - "studyDescription", - "dataTypes", - "phenotypeIndication", - "species", - "piName", - "dataSubmitterUserId", - "dataCustodianEmail", - "publicVisibility", - "nihAnvilUse", - "submittingToAnvil", - "dbGaPPhsID", - "dbGaPStudyRegistrationName", - "embargoReleaseDate", - "sequencingCenter", - "piInstitution", - "nihGrantContractNumber", - "nihICsSupportingStudy", - "nihProgramOfficerName", - "nihInstitutionCenterSubmission", - "nihGenomicProgramAdministratorName", - "multiCenterStudy", - "collaboratingSites", - "controlledAccessRequiredForGenomicSummaryResultsGSR", - "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation", - "alternativeDataSharingPlan", - "alternativeDataSharingPlanReasons", - "alternativeDataSharingPlanExplanation", - "alternativeDataSharingPlanFileName", - "alternativeDataSharingPlanDataSubmitted", - "alternativeDataSharingPlanDataReleased", - "alternativeDataSharingPlanTargetDeliveryDate", - "alternativeDataSharingPlanTargetPublicReleaseDate", - "alternativeDataSharingPlanAccessManagement", - "consentGroups", - "assets" + "studyId", + "studyName", + "studyType", + "studyDescription", + "dataTypes", + "phenotypeIndication", + "species", + "piName", + "dataSubmitterUserId", + "dataCustodianEmail", + "publicVisibility", + "nihAnvilUse", + "submittingToAnvil", + "dbGaPPhsID", + "dbGaPStudyRegistrationName", + "embargoReleaseDate", + "sequencingCenter", + "piInstitution", + "nihGrantContractNumber", + "nihICsSupportingStudy", + "nihProgramOfficerName", + "nihInstitutionCenterSubmission", + "nihGenomicProgramAdministratorName", + "multiCenterStudy", + "collaboratingSites", + "controlledAccessRequiredForGenomicSummaryResultsGSR", + "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation", + "alternativeDataSharingPlan", + "alternativeDataSharingPlanReasons", + "alternativeDataSharingPlanExplanation", + "alternativeDataSharingPlanFileName", + "alternativeDataSharingPlanDataSubmitted", + "alternativeDataSharingPlanDataReleased", + "alternativeDataSharingPlanTargetDeliveryDate", + "alternativeDataSharingPlanTargetPublicReleaseDate", + "alternativeDataSharingPlanAccessManagement", + "consentGroups", + "assets" }) public class DatasetRegistrationSchemaV1 { - /** - * The study id - */ + /** The study id */ @JsonProperty("studyId") @JsonPropertyDescription("The study id") private Integer studyId; - /** - * The study name (Required) - */ + /** The study name (Required) */ @JsonProperty("studyName") @JsonPropertyDescription("The study name") private String studyName; - /** - * The study type - */ + + /** The study type */ @JsonProperty("studyType") @JsonPropertyDescription("The study type") private DatasetRegistrationSchemaV1.StudyType studyType; - /** - * Description of the study (Required) - */ + + /** Description of the study (Required) */ @JsonProperty("studyDescription") @JsonPropertyDescription("Description of the study") private String studyDescription; - /** - * All data types that study encompasses (Required) - */ + + /** All data types that study encompasses (Required) */ @JsonProperty("dataTypes") @JsonPropertyDescription("All data types that study encompasses") private List dataTypes = new ArrayList(); - /** - * Phenotype/Indication Studied - */ + + /** Phenotype/Indication Studied */ @JsonProperty("phenotypeIndication") @JsonPropertyDescription("Phenotype/Indication Studied") private String phenotypeIndication; - /** - * Species - */ + + /** Species */ @JsonProperty("species") @JsonPropertyDescription("Species") private String species; - /** - * Principal Investigator Name (Required) - */ + + /** Principal Investigator Name (Required) */ @JsonProperty("piName") @JsonPropertyDescription("Principal Investigator Name") private String piName; - /** - * The user creating the dataset submission (Required) - */ + + /** The user creating the dataset submission (Required) */ @JsonProperty("dataSubmitterUserId") @JsonPropertyDescription("The user creating the dataset submission") private Integer dataSubmitterUserId; - /** - * Data Custodian Email - */ + + /** Data Custodian Email */ @JsonProperty("dataCustodianEmail") @JsonPropertyDescription("Data Custodian Email") private List dataCustodianEmail = new ArrayList(); - /** - * Public Visibility of this study (Required) - */ + + /** Public Visibility of this study (Required) */ @JsonProperty("publicVisibility") @JsonPropertyDescription("Public Visibility of this study") private Boolean publicVisibility; - /** - * NIH Anvil Use (Required) - */ + + /** NIH Anvil Use (Required) */ @JsonProperty("nihAnvilUse") @JsonPropertyDescription("NIH Anvil Use") private DatasetRegistrationSchemaV1.NihAnvilUse nihAnvilUse; - /** - * Are you planning to submit to AnVIL? - */ + + /** Are you planning to submit to AnVIL? */ @JsonProperty("submittingToAnvil") @JsonPropertyDescription("Are you planning to submit to AnVIL?") private Boolean submittingToAnvil; - /** - * dbGaP phs ID - */ + + /** dbGaP phs ID */ @JsonProperty("dbGaPPhsID") @JsonPropertyDescription("dbGaP phs ID") private String dbGaPPhsID; - /** - * dbGaP Study Registration Name - */ + + /** dbGaP Study Registration Name */ @JsonProperty("dbGaPStudyRegistrationName") @JsonPropertyDescription("dbGaP Study Registration Name") private String dbGaPStudyRegistrationName; - /** - * Embargo Release Date - */ + + /** Embargo Release Date */ @JsonProperty("embargoReleaseDate") @JsonPropertyDescription("Embargo Release Date") private String embargoReleaseDate; - /** - * Sequencing Center - */ + + /** Sequencing Center */ @JsonProperty("sequencingCenter") @JsonPropertyDescription("Sequencing Center") private String sequencingCenter; - /** - * Principal Investigator Institution - */ + + /** Principal Investigator Institution */ @JsonProperty("piInstitution") @JsonPropertyDescription("Principal Investigator Institution") private Integer piInstitution; - /** - * NIH Grant or Contract Number - */ + + /** NIH Grant or Contract Number */ @JsonProperty("nihGrantContractNumber") @JsonPropertyDescription("NIH Grant or Contract Number") private String nihGrantContractNumber; - /** - * NIH ICs Supporting the Study - */ + + /** NIH ICs Supporting the Study */ @JsonProperty("nihICsSupportingStudy") @JsonPropertyDescription("NIH ICs Supporting the Study") - private List nihICsSupportingStudy = new ArrayList(); - /** - * NIH Program Officer Name - */ + private List nihICsSupportingStudy = + new ArrayList(); + + /** NIH Program Officer Name */ @JsonProperty("nihProgramOfficerName") @JsonPropertyDescription("NIH Program Officer Name") private String nihProgramOfficerName; - /** - * NIH Institution/Center for Submission - */ + + /** NIH Institution/Center for Submission */ @JsonProperty("nihInstitutionCenterSubmission") @JsonPropertyDescription("NIH Institution/Center for Submission") private DatasetRegistrationSchemaV1.NihInstitutionCenterSubmission nihInstitutionCenterSubmission; - /** - * NIH Genomic Program Administrator Name - */ + + /** NIH Genomic Program Administrator Name */ @JsonProperty("nihGenomicProgramAdministratorName") @JsonPropertyDescription("NIH Genomic Program Administrator Name") private String nihGenomicProgramAdministratorName; - /** - * Is this a multi-center study? - */ + + /** Is this a multi-center study? */ @JsonProperty("multiCenterStudy") @JsonPropertyDescription("Is this a multi-center study?") private Boolean multiCenterStudy; - /** - * What are the collaborating sites? - */ + + /** What are the collaborating sites? */ @JsonProperty("collaboratingSites") @JsonPropertyDescription("What are the collaborating sites?") private List collaboratingSites = new ArrayList(); - /** - * Is controlled access required for genomic summary results (GSR)? - */ + + /** Is controlled access required for genomic summary results (GSR)? */ @JsonProperty("controlledAccessRequiredForGenomicSummaryResultsGSR") @JsonPropertyDescription("Is controlled access required for genomic summary results (GSR)?") private Boolean controlledAccessRequiredForGenomicSummaryResultsGSR; - /** - * If yes, explain why controlled access is required for GSR - */ + + /** If yes, explain why controlled access is required for GSR */ @JsonProperty("controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation") @JsonPropertyDescription("If yes, explain why controlled access is required for GSR") private String controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation; + /** * Are you requesting an Alternative Data Sharing Plan for samples that cannot be shared through a * public repository or database? */ @JsonProperty("alternativeDataSharingPlan") - @JsonPropertyDescription("Are you requesting an Alternative Data Sharing Plan for samples that cannot be shared through a public repository or database?") + @JsonPropertyDescription( + "Are you requesting an Alternative Data Sharing Plan for samples that cannot be shared through a public repository or database?") private Boolean alternativeDataSharingPlan; + /** * Please mark the reasons for which you are requesting an Alternative Data Sharing Plan (check * all that apply) */ @JsonProperty("alternativeDataSharingPlanReasons") - @JsonPropertyDescription("Please mark the reasons for which you are requesting an Alternative Data Sharing Plan (check all that apply)") - private List alternativeDataSharingPlanReasons = new ArrayList(); - /** - * Explanation of Request - */ + @JsonPropertyDescription( + "Please mark the reasons for which you are requesting an Alternative Data Sharing Plan (check all that apply)") + private List alternativeDataSharingPlanReasons = + new ArrayList(); + + /** Explanation of Request */ @JsonProperty("alternativeDataSharingPlanExplanation") @JsonPropertyDescription("Explanation of Request") private String alternativeDataSharingPlanExplanation; - /** - * Upload your alternative sharing plan (file upload) - */ + + /** Upload your alternative sharing plan (file upload) */ @JsonProperty("alternativeDataSharingPlanFileName") @JsonPropertyDescription("Upload your alternative sharing plan (file upload)") private String alternativeDataSharingPlanFileName; - /** - * Upload your alternative sharing plan (file upload) - */ + + /** Upload your alternative sharing plan (file upload) */ @JsonProperty("alternativeDataSharingPlanDataSubmitted") @JsonPropertyDescription("Upload your alternative sharing plan (file upload)") - private DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted alternativeDataSharingPlanDataSubmitted; + private DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted + alternativeDataSharingPlanDataSubmitted; + /** * Data to be released will meet the timeframes specified in the NHGRI Guidance for Data * Submission and Data Release */ @JsonProperty("alternativeDataSharingPlanDataReleased") - @JsonPropertyDescription("Data to be released will meet the timeframes specified in the NHGRI Guidance for Data Submission and Data Release") + @JsonPropertyDescription( + "Data to be released will meet the timeframes specified in the NHGRI Guidance for Data Submission and Data Release") private Boolean alternativeDataSharingPlanDataReleased; - /** - * Target Delivery Date - */ + + /** Target Delivery Date */ @JsonProperty("alternativeDataSharingPlanTargetDeliveryDate") @JsonPropertyDescription("Target Delivery Date") private String alternativeDataSharingPlanTargetDeliveryDate; - /** - * Target Public Release Date - */ + + /** Target Public Release Date */ @JsonProperty("alternativeDataSharingPlanTargetPublicReleaseDate") @JsonPropertyDescription("Target Public Release Date") private String alternativeDataSharingPlanTargetPublicReleaseDate; - /** - * Does the data need to be managed under Controlled, Open, or External Access? - */ + + /** Does the data need to be managed under Controlled, Open, or External Access? */ @JsonProperty("alternativeDataSharingPlanAccessManagement") - @JsonPropertyDescription("Does the data need to be managed under Controlled, Open, or External Access?") - private DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement alternativeDataSharingPlanAccessManagement; - /** - * Consent Groups (Required) - */ + @JsonPropertyDescription( + "Does the data need to be managed under Controlled, Open, or External Access?") + private DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement + alternativeDataSharingPlanAccessManagement; + + /** Consent Groups (Required) */ @JsonProperty("consentGroups") @JsonPropertyDescription("Consent Groups") private List consentGroups = new ArrayList(); - /** - * Additional assets or metadata associated with this study registration - */ + /** Additional assets or metadata associated with this study registration */ @JsonProperty("assets") @JsonPropertyDescription("Additional assets or metadata associated with this study registration") private Map assets = new HashMap<>(); - /** - * The study id - */ + /** The study id */ @JsonProperty("studyId") public Integer getStudyId() { return studyId; } - /** - * The study id - */ + /** The study id */ @JsonProperty("studyId") public void setStudyId(Integer studyId) { this.studyId = studyId; } - /** - * The study name (Required) - */ + /** The study name (Required) */ @JsonProperty("studyName") public String getStudyName() { return studyName; } - /** - * The study name (Required) - */ + /** The study name (Required) */ @JsonProperty("studyName") public void setStudyName(String studyName) { this.studyName = studyName; } - /** - * The study type - */ + /** The study type */ @JsonProperty("studyType") public DatasetRegistrationSchemaV1.StudyType getStudyType() { return studyType; } - /** - * The study type - */ + /** The study type */ @JsonProperty("studyType") public void setStudyType(DatasetRegistrationSchemaV1.StudyType studyType) { this.studyType = studyType; } - /** - * Description of the study (Required) - */ + /** Description of the study (Required) */ @JsonProperty("studyDescription") public String getStudyDescription() { return studyDescription; } - /** - * Description of the study (Required) - */ + /** Description of the study (Required) */ @JsonProperty("studyDescription") public void setStudyDescription(String studyDescription) { this.studyDescription = studyDescription; } - /** - * All data types that study encompasses (Required) - */ + /** All data types that study encompasses (Required) */ @JsonProperty("dataTypes") public List getDataTypes() { return dataTypes; } - /** - * All data types that study encompasses (Required) - */ + /** All data types that study encompasses (Required) */ @JsonProperty("dataTypes") public void setDataTypes(List dataTypes) { this.dataTypes = dataTypes; } - /** - * Phenotype/Indication Studied - */ + /** Phenotype/Indication Studied */ @JsonProperty("phenotypeIndication") public String getPhenotypeIndication() { return phenotypeIndication; } - /** - * Phenotype/Indication Studied - */ + /** Phenotype/Indication Studied */ @JsonProperty("phenotypeIndication") public void setPhenotypeIndication(String phenotypeIndication) { this.phenotypeIndication = phenotypeIndication; } - /** - * Species - */ + /** Species */ @JsonProperty("species") public String getSpecies() { return species; } - /** - * Species - */ + /** Species */ @JsonProperty("species") public void setSpecies(String species) { this.species = species; } - /** - * Principal Investigator Name (Required) - */ + /** Principal Investigator Name (Required) */ @JsonProperty("piName") public String getPiName() { return piName; } - /** - * Principal Investigator Name (Required) - */ + /** Principal Investigator Name (Required) */ @JsonProperty("piName") public void setPiName(String piName) { this.piName = piName; } - /** - * The user creating the dataset submission (Required) - */ + /** The user creating the dataset submission (Required) */ @JsonProperty("dataSubmitterUserId") public Integer getDataSubmitterUserId() { return dataSubmitterUserId; } - /** - * The user creating the dataset submission (Required) - */ + /** The user creating the dataset submission (Required) */ @JsonProperty("dataSubmitterUserId") public void setDataSubmitterUserId(Integer dataSubmitterUserId) { this.dataSubmitterUserId = dataSubmitterUserId; } - /** - * Data Custodian Email - */ + /** Data Custodian Email */ @JsonProperty("dataCustodianEmail") public List getDataCustodianEmail() { return dataCustodianEmail; } - /** - * Data Custodian Email - */ + /** Data Custodian Email */ @JsonProperty("dataCustodianEmail") public void setDataCustodianEmail(List dataCustodianEmail) { this.dataCustodianEmail = dataCustodianEmail; } - /** - * Public Visibility of this study (Required) - */ + /** Public Visibility of this study (Required) */ @JsonProperty("publicVisibility") public Boolean getPublicVisibility() { return publicVisibility; } - /** - * Public Visibility of this study (Required) - */ + /** Public Visibility of this study (Required) */ @JsonProperty("publicVisibility") public void setPublicVisibility(Boolean publicVisibility) { this.publicVisibility = publicVisibility; } - /** - * NIH Anvil Use (Required) - */ + /** NIH Anvil Use (Required) */ @JsonProperty("nihAnvilUse") public DatasetRegistrationSchemaV1.NihAnvilUse getNihAnvilUse() { return nihAnvilUse; } - /** - * NIH Anvil Use (Required) - */ + /** NIH Anvil Use (Required) */ @JsonProperty("nihAnvilUse") public void setNihAnvilUse(DatasetRegistrationSchemaV1.NihAnvilUse nihAnvilUse) { this.nihAnvilUse = nihAnvilUse; } - /** - * Are you planning to submit to AnVIL? - */ + /** Are you planning to submit to AnVIL? */ @JsonProperty("submittingToAnvil") public Boolean getSubmittingToAnvil() { return submittingToAnvil; } - /** - * Are you planning to submit to AnVIL? - */ + /** Are you planning to submit to AnVIL? */ @JsonProperty("submittingToAnvil") public void setSubmittingToAnvil(Boolean submittingToAnvil) { this.submittingToAnvil = submittingToAnvil; } - /** - * dbGaP phs ID - */ + /** dbGaP phs ID */ @JsonProperty("dbGaPPhsID") public String getDbGaPPhsID() { return dbGaPPhsID; } - /** - * dbGaP phs ID - */ + /** dbGaP phs ID */ @JsonProperty("dbGaPPhsID") public void setDbGaPPhsID(String dbGaPPhsID) { this.dbGaPPhsID = dbGaPPhsID; } - /** - * dbGaP Study Registration Name - */ + /** dbGaP Study Registration Name */ @JsonProperty("dbGaPStudyRegistrationName") public String getDbGaPStudyRegistrationName() { return dbGaPStudyRegistrationName; } - /** - * dbGaP Study Registration Name - */ + /** dbGaP Study Registration Name */ @JsonProperty("dbGaPStudyRegistrationName") public void setDbGaPStudyRegistrationName(String dbGaPStudyRegistrationName) { this.dbGaPStudyRegistrationName = dbGaPStudyRegistrationName; } - /** - * Embargo Release Date - */ + /** Embargo Release Date */ @JsonProperty("embargoReleaseDate") public String getEmbargoReleaseDate() { return embargoReleaseDate; } - /** - * Embargo Release Date - */ + /** Embargo Release Date */ @JsonProperty("embargoReleaseDate") public void setEmbargoReleaseDate(String embargoReleaseDate) { this.embargoReleaseDate = embargoReleaseDate; } - /** - * Sequencing Center - */ + /** Sequencing Center */ @JsonProperty("sequencingCenter") public String getSequencingCenter() { return sequencingCenter; } - /** - * Sequencing Center - */ + /** Sequencing Center */ @JsonProperty("sequencingCenter") public void setSequencingCenter(String sequencingCenter) { this.sequencingCenter = sequencingCenter; } - /** - * Principal Investigator Institution - */ + /** Principal Investigator Institution */ @JsonProperty("piInstitution") public Integer getPiInstitution() { return piInstitution; } - /** - * Principal Investigator Institution - */ + /** Principal Investigator Institution */ @JsonProperty("piInstitution") public void setPiInstitution(Integer piInstitution) { this.piInstitution = piInstitution; } - /** - * NIH Grant or Contract Number - */ + /** NIH Grant or Contract Number */ @JsonProperty("nihGrantContractNumber") public String getNihGrantContractNumber() { return nihGrantContractNumber; } - /** - * NIH Grant or Contract Number - */ + /** NIH Grant or Contract Number */ @JsonProperty("nihGrantContractNumber") public void setNihGrantContractNumber(String nihGrantContractNumber) { this.nihGrantContractNumber = nihGrantContractNumber; } - /** - * NIH ICs Supporting the Study - */ + /** NIH ICs Supporting the Study */ @JsonProperty("nihICsSupportingStudy") public List getNihICsSupportingStudy() { return nihICsSupportingStudy; } - /** - * NIH ICs Supporting the Study - */ + /** NIH ICs Supporting the Study */ @JsonProperty("nihICsSupportingStudy") public void setNihICsSupportingStudy(List nihICsSupportingStudy) { this.nihICsSupportingStudy = nihICsSupportingStudy; } - /** - * NIH Program Officer Name - */ + /** NIH Program Officer Name */ @JsonProperty("nihProgramOfficerName") public String getNihProgramOfficerName() { return nihProgramOfficerName; } - /** - * NIH Program Officer Name - */ + /** NIH Program Officer Name */ @JsonProperty("nihProgramOfficerName") public void setNihProgramOfficerName(String nihProgramOfficerName) { this.nihProgramOfficerName = nihProgramOfficerName; } - /** - * NIH Institution/Center for Submission - */ + /** NIH Institution/Center for Submission */ @JsonProperty("nihInstitutionCenterSubmission") - public DatasetRegistrationSchemaV1.NihInstitutionCenterSubmission getNihInstitutionCenterSubmission() { + public DatasetRegistrationSchemaV1.NihInstitutionCenterSubmission + getNihInstitutionCenterSubmission() { return nihInstitutionCenterSubmission; } - /** - * NIH Institution/Center for Submission - */ + /** NIH Institution/Center for Submission */ @JsonProperty("nihInstitutionCenterSubmission") public void setNihInstitutionCenterSubmission( DatasetRegistrationSchemaV1.NihInstitutionCenterSubmission nihInstitutionCenterSubmission) { this.nihInstitutionCenterSubmission = nihInstitutionCenterSubmission; } - /** - * NIH Genomic Program Administrator Name - */ + /** NIH Genomic Program Administrator Name */ @JsonProperty("nihGenomicProgramAdministratorName") public String getNihGenomicProgramAdministratorName() { return nihGenomicProgramAdministratorName; } - /** - * NIH Genomic Program Administrator Name - */ + /** NIH Genomic Program Administrator Name */ @JsonProperty("nihGenomicProgramAdministratorName") public void setNihGenomicProgramAdministratorName(String nihGenomicProgramAdministratorName) { this.nihGenomicProgramAdministratorName = nihGenomicProgramAdministratorName; } - /** - * Is this a multi-center study? - */ + /** Is this a multi-center study? */ @JsonProperty("multiCenterStudy") public Boolean getMultiCenterStudy() { return multiCenterStudy; } - /** - * Is this a multi-center study? - */ + /** Is this a multi-center study? */ @JsonProperty("multiCenterStudy") public void setMultiCenterStudy(Boolean multiCenterStudy) { this.multiCenterStudy = multiCenterStudy; } - /** - * What are the collaborating sites? - */ + /** What are the collaborating sites? */ @JsonProperty("collaboratingSites") public List getCollaboratingSites() { return collaboratingSites; } - /** - * What are the collaborating sites? - */ + /** What are the collaborating sites? */ @JsonProperty("collaboratingSites") public void setCollaboratingSites(List collaboratingSites) { this.collaboratingSites = collaboratingSites; } - /** - * Is controlled access required for genomic summary results (GSR)? - */ + /** Is controlled access required for genomic summary results (GSR)? */ @JsonProperty("controlledAccessRequiredForGenomicSummaryResultsGSR") public Boolean getControlledAccessRequiredForGenomicSummaryResultsGSR() { return controlledAccessRequiredForGenomicSummaryResultsGSR; } - /** - * Is controlled access required for genomic summary results (GSR)? - */ + /** Is controlled access required for genomic summary results (GSR)? */ @JsonProperty("controlledAccessRequiredForGenomicSummaryResultsGSR") public void setControlledAccessRequiredForGenomicSummaryResultsGSR( Boolean controlledAccessRequiredForGenomicSummaryResultsGSR) { - this.controlledAccessRequiredForGenomicSummaryResultsGSR = controlledAccessRequiredForGenomicSummaryResultsGSR; + this.controlledAccessRequiredForGenomicSummaryResultsGSR = + controlledAccessRequiredForGenomicSummaryResultsGSR; } - /** - * If yes, explain why controlled access is required for GSR - */ + /** If yes, explain why controlled access is required for GSR */ @JsonProperty("controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation") public String getControlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation() { return controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation; } - /** - * If yes, explain why controlled access is required for GSR - */ + /** If yes, explain why controlled access is required for GSR */ @JsonProperty("controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation") public void setControlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation( String controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation) { - this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation = controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation; + this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation = + controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation; } /** @@ -772,53 +639,43 @@ public void setAlternativeDataSharingPlanReasons( this.alternativeDataSharingPlanReasons = alternativeDataSharingPlanReasons; } - /** - * Explanation of Request - */ + /** Explanation of Request */ @JsonProperty("alternativeDataSharingPlanExplanation") public String getAlternativeDataSharingPlanExplanation() { return alternativeDataSharingPlanExplanation; } - /** - * Explanation of Request - */ + /** Explanation of Request */ @JsonProperty("alternativeDataSharingPlanExplanation") public void setAlternativeDataSharingPlanExplanation( String alternativeDataSharingPlanExplanation) { this.alternativeDataSharingPlanExplanation = alternativeDataSharingPlanExplanation; } - /** - * Upload your alternative sharing plan (file upload) - */ + /** Upload your alternative sharing plan (file upload) */ @JsonProperty("alternativeDataSharingPlanFileName") public String getAlternativeDataSharingPlanFileName() { return alternativeDataSharingPlanFileName; } - /** - * Upload your alternative sharing plan (file upload) - */ + /** Upload your alternative sharing plan (file upload) */ @JsonProperty("alternativeDataSharingPlanFileName") public void setAlternativeDataSharingPlanFileName(String alternativeDataSharingPlanFileName) { this.alternativeDataSharingPlanFileName = alternativeDataSharingPlanFileName; } - /** - * Upload your alternative sharing plan (file upload) - */ + /** Upload your alternative sharing plan (file upload) */ @JsonProperty("alternativeDataSharingPlanDataSubmitted") - public DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted getAlternativeDataSharingPlanDataSubmitted() { + public DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted + getAlternativeDataSharingPlanDataSubmitted() { return alternativeDataSharingPlanDataSubmitted; } - /** - * Upload your alternative sharing plan (file upload) - */ + /** Upload your alternative sharing plan (file upload) */ @JsonProperty("alternativeDataSharingPlanDataSubmitted") public void setAlternativeDataSharingPlanDataSubmitted( - DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted alternativeDataSharingPlanDataSubmitted) { + DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted + alternativeDataSharingPlanDataSubmitted) { this.alternativeDataSharingPlanDataSubmitted = alternativeDataSharingPlanDataSubmitted; } @@ -841,84 +698,68 @@ public void setAlternativeDataSharingPlanDataReleased( this.alternativeDataSharingPlanDataReleased = alternativeDataSharingPlanDataReleased; } - /** - * Target Delivery Date - */ + /** Target Delivery Date */ @JsonProperty("alternativeDataSharingPlanTargetDeliveryDate") public String getAlternativeDataSharingPlanTargetDeliveryDate() { return alternativeDataSharingPlanTargetDeliveryDate; } - /** - * Target Delivery Date - */ + /** Target Delivery Date */ @JsonProperty("alternativeDataSharingPlanTargetDeliveryDate") public void setAlternativeDataSharingPlanTargetDeliveryDate( String alternativeDataSharingPlanTargetDeliveryDate) { - this.alternativeDataSharingPlanTargetDeliveryDate = alternativeDataSharingPlanTargetDeliveryDate; + this.alternativeDataSharingPlanTargetDeliveryDate = + alternativeDataSharingPlanTargetDeliveryDate; } - /** - * Target Public Release Date - */ + /** Target Public Release Date */ @JsonProperty("alternativeDataSharingPlanTargetPublicReleaseDate") public String getAlternativeDataSharingPlanTargetPublicReleaseDate() { return alternativeDataSharingPlanTargetPublicReleaseDate; } - /** - * Target Public Release Date - */ + /** Target Public Release Date */ @JsonProperty("alternativeDataSharingPlanTargetPublicReleaseDate") public void setAlternativeDataSharingPlanTargetPublicReleaseDate( String alternativeDataSharingPlanTargetPublicReleaseDate) { - this.alternativeDataSharingPlanTargetPublicReleaseDate = alternativeDataSharingPlanTargetPublicReleaseDate; + this.alternativeDataSharingPlanTargetPublicReleaseDate = + alternativeDataSharingPlanTargetPublicReleaseDate; } - /** - * Does the data need to be managed under Controlled, Open, or External Access? - */ + /** Does the data need to be managed under Controlled, Open, or External Access? */ @JsonProperty("alternativeDataSharingPlanAccessManagement") - public DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement getAlternativeDataSharingPlanAccessManagement() { + public DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement + getAlternativeDataSharingPlanAccessManagement() { return alternativeDataSharingPlanAccessManagement; } - /** - * Does the data need to be managed under Controlled, Open, or External Access? - */ + /** Does the data need to be managed under Controlled, Open, or External Access? */ @JsonProperty("alternativeDataSharingPlanAccessManagement") public void setAlternativeDataSharingPlanAccessManagement( - DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement alternativeDataSharingPlanAccessManagement) { + DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement + alternativeDataSharingPlanAccessManagement) { this.alternativeDataSharingPlanAccessManagement = alternativeDataSharingPlanAccessManagement; } - /** - * Consent Groups (Required) - */ + /** Consent Groups (Required) */ @JsonProperty("consentGroups") public List getConsentGroups() { return consentGroups; } - /** - * Consent Groups (Required) - */ + /** Consent Groups (Required) */ @JsonProperty("consentGroups") public void setConsentGroups(List consentGroups) { this.consentGroups = consentGroups; } - /** - * Additional assets or metadata associated with this study registration - */ + /** Additional assets or metadata associated with this study registration */ @JsonProperty("assets") public Map getAssets() { return assets; } - /** - * Additional assets or metadata associated with this study registration - */ + /** Additional assets or metadata associated with this study registration */ @JsonProperty("assets") public void setAssets(Map assets) { this.assets = assets; @@ -927,8 +768,10 @@ public void setAssets(Map assets) { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(DatasetRegistrationSchemaV1.class.getName()).append('@') - .append(Integer.toHexString(System.identityHashCode(this))).append('['); + sb.append(DatasetRegistrationSchemaV1.class.getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(this))) + .append('['); sb.append("studyId"); sb.append('='); sb.append(((this.studyId == null) ? "" : this.studyId)); @@ -1016,13 +859,17 @@ public String toString() { sb.append(','); sb.append("nihInstitutionCenterSubmission"); sb.append('='); - sb.append(((this.nihInstitutionCenterSubmission == null) ? "" - : this.nihInstitutionCenterSubmission)); + sb.append( + ((this.nihInstitutionCenterSubmission == null) + ? "" + : this.nihInstitutionCenterSubmission)); sb.append(','); sb.append("nihGenomicProgramAdministratorName"); sb.append('='); - sb.append(((this.nihGenomicProgramAdministratorName == null) ? "" - : this.nihGenomicProgramAdministratorName)); + sb.append( + ((this.nihGenomicProgramAdministratorName == null) + ? "" + : this.nihGenomicProgramAdministratorName)); sb.append(','); sb.append("multiCenterStudy"); sb.append('='); @@ -1034,13 +881,17 @@ public String toString() { sb.append(','); sb.append("controlledAccessRequiredForGenomicSummaryResultsGSR"); sb.append('='); - sb.append(((this.controlledAccessRequiredForGenomicSummaryResultsGSR == null) ? "" - : this.controlledAccessRequiredForGenomicSummaryResultsGSR)); + sb.append( + ((this.controlledAccessRequiredForGenomicSummaryResultsGSR == null) + ? "" + : this.controlledAccessRequiredForGenomicSummaryResultsGSR)); sb.append(','); sb.append("controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation"); sb.append('='); - sb.append(((this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation == null) - ? "" : this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation)); + sb.append( + ((this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation == null) + ? "" + : this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation)); sb.append(','); sb.append("alternativeDataSharingPlan"); sb.append('='); @@ -1049,43 +900,59 @@ public String toString() { sb.append(','); sb.append("alternativeDataSharingPlanReasons"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanReasons == null) ? "" - : this.alternativeDataSharingPlanReasons)); + sb.append( + ((this.alternativeDataSharingPlanReasons == null) + ? "" + : this.alternativeDataSharingPlanReasons)); sb.append(','); sb.append("alternativeDataSharingPlanExplanation"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanExplanation == null) ? "" - : this.alternativeDataSharingPlanExplanation)); + sb.append( + ((this.alternativeDataSharingPlanExplanation == null) + ? "" + : this.alternativeDataSharingPlanExplanation)); sb.append(','); sb.append("alternativeDataSharingPlanFileName"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanFileName == null) ? "" - : this.alternativeDataSharingPlanFileName)); + sb.append( + ((this.alternativeDataSharingPlanFileName == null) + ? "" + : this.alternativeDataSharingPlanFileName)); sb.append(','); sb.append("alternativeDataSharingPlanDataSubmitted"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanDataSubmitted == null) ? "" - : this.alternativeDataSharingPlanDataSubmitted)); + sb.append( + ((this.alternativeDataSharingPlanDataSubmitted == null) + ? "" + : this.alternativeDataSharingPlanDataSubmitted)); sb.append(','); sb.append("alternativeDataSharingPlanDataReleased"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanDataReleased == null) ? "" - : this.alternativeDataSharingPlanDataReleased)); + sb.append( + ((this.alternativeDataSharingPlanDataReleased == null) + ? "" + : this.alternativeDataSharingPlanDataReleased)); sb.append(','); sb.append("alternativeDataSharingPlanTargetDeliveryDate"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanTargetDeliveryDate == null) ? "" - : this.alternativeDataSharingPlanTargetDeliveryDate)); + sb.append( + ((this.alternativeDataSharingPlanTargetDeliveryDate == null) + ? "" + : this.alternativeDataSharingPlanTargetDeliveryDate)); sb.append(','); sb.append("alternativeDataSharingPlanTargetPublicReleaseDate"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanTargetPublicReleaseDate == null) ? "" - : this.alternativeDataSharingPlanTargetPublicReleaseDate)); + sb.append( + ((this.alternativeDataSharingPlanTargetPublicReleaseDate == null) + ? "" + : this.alternativeDataSharingPlanTargetPublicReleaseDate)); sb.append(','); sb.append("alternativeDataSharingPlanAccessManagement"); sb.append('='); - sb.append(((this.alternativeDataSharingPlanAccessManagement == null) ? "" - : this.alternativeDataSharingPlanAccessManagement)); + sb.append( + ((this.alternativeDataSharingPlanAccessManagement == null) + ? "" + : this.alternativeDataSharingPlanAccessManagement)); sb.append(','); sb.append("consentGroups"); sb.append('='); @@ -1106,70 +973,121 @@ public String toString() { @Override public int hashCode() { int result = 1; - result = ((result * 31) + ((this.nihGenomicProgramAdministratorName == null) ? 0 - : this.nihGenomicProgramAdministratorName.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanFileName == null) ? 0 - : this.alternativeDataSharingPlanFileName.hashCode())); + result = + ((result * 31) + + ((this.nihGenomicProgramAdministratorName == null) + ? 0 + : this.nihGenomicProgramAdministratorName.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanFileName == null) + ? 0 + : this.alternativeDataSharingPlanFileName.hashCode())); result = ((result * 31) + ((this.studyId == null) ? 0 : this.studyId.hashCode())); result = ((result * 31) + ((this.studyName == null) ? 0 : this.studyName.hashCode())); - result = ((result * 31) + ((this.dataSubmitterUserId == null) ? 0 - : this.dataSubmitterUserId.hashCode())); - result = ((result * 31) + ((this.publicVisibility == null) ? 0 - : this.publicVisibility.hashCode())); - result = ((result * 31) + ((this.dataCustodianEmail == null) ? 0 - : this.dataCustodianEmail.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanDataSubmitted == null) ? 0 - : this.alternativeDataSharingPlanDataSubmitted.hashCode())); - result = ((result * 31) + ((this.submittingToAnvil == null) ? 0 - : this.submittingToAnvil.hashCode())); - result = ((result * 31) + ((this.dbGaPStudyRegistrationName == null) ? 0 - : this.dbGaPStudyRegistrationName.hashCode())); - result = ((result * 31) + ((this.collaboratingSites == null) ? 0 - : this.collaboratingSites.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanTargetDeliveryDate == null) ? 0 - : this.alternativeDataSharingPlanTargetDeliveryDate.hashCode())); - result = ((result * 31) + ((this.nihProgramOfficerName == null) ? 0 - : this.nihProgramOfficerName.hashCode())); + result = + ((result * 31) + + ((this.dataSubmitterUserId == null) ? 0 : this.dataSubmitterUserId.hashCode())); + result = + ((result * 31) + ((this.publicVisibility == null) ? 0 : this.publicVisibility.hashCode())); + result = + ((result * 31) + + ((this.dataCustodianEmail == null) ? 0 : this.dataCustodianEmail.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanDataSubmitted == null) + ? 0 + : this.alternativeDataSharingPlanDataSubmitted.hashCode())); + result = + ((result * 31) + + ((this.submittingToAnvil == null) ? 0 : this.submittingToAnvil.hashCode())); + result = + ((result * 31) + + ((this.dbGaPStudyRegistrationName == null) + ? 0 + : this.dbGaPStudyRegistrationName.hashCode())); + result = + ((result * 31) + + ((this.collaboratingSites == null) ? 0 : this.collaboratingSites.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanTargetDeliveryDate == null) + ? 0 + : this.alternativeDataSharingPlanTargetDeliveryDate.hashCode())); + result = + ((result * 31) + + ((this.nihProgramOfficerName == null) ? 0 : this.nihProgramOfficerName.hashCode())); result = ((result * 31) + ((this.dataTypes == null) ? 0 : this.dataTypes.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanTargetPublicReleaseDate == null) ? 0 - : this.alternativeDataSharingPlanTargetPublicReleaseDate.hashCode())); - result = ((result * 31) + ((this.nihGrantContractNumber == null) ? 0 - : this.nihGrantContractNumber.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanTargetPublicReleaseDate == null) + ? 0 + : this.alternativeDataSharingPlanTargetPublicReleaseDate.hashCode())); + result = + ((result * 31) + + ((this.nihGrantContractNumber == null) ? 0 : this.nihGrantContractNumber.hashCode())); result = ((result * 31) + ((this.studyType == null) ? 0 : this.studyType.hashCode())); - result = ((result * 31) + ((this.phenotypeIndication == null) ? 0 - : this.phenotypeIndication.hashCode())); - result = ((result * 31) + ( - (this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation == null) ? 0 - : this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanAccessManagement == null) ? 0 - : this.alternativeDataSharingPlanAccessManagement.hashCode())); - result = ((result * 31) + ((this.sequencingCenter == null) ? 0 - : this.sequencingCenter.hashCode())); - result = ((result * 31) + ((this.multiCenterStudy == null) ? 0 - : this.multiCenterStudy.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanDataReleased == null) ? 0 - : this.alternativeDataSharingPlanDataReleased.hashCode())); + result = + ((result * 31) + + ((this.phenotypeIndication == null) ? 0 : this.phenotypeIndication.hashCode())); + result = + ((result * 31) + + ((this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation == null) + ? 0 + : this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation + .hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanAccessManagement == null) + ? 0 + : this.alternativeDataSharingPlanAccessManagement.hashCode())); + result = + ((result * 31) + ((this.sequencingCenter == null) ? 0 : this.sequencingCenter.hashCode())); + result = + ((result * 31) + ((this.multiCenterStudy == null) ? 0 : this.multiCenterStudy.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanDataReleased == null) + ? 0 + : this.alternativeDataSharingPlanDataReleased.hashCode())); result = ((result * 31) + ((this.consentGroups == null) ? 0 : this.consentGroups.hashCode())); - result = ((result * 31) + ((this.studyDescription == null) ? 0 - : this.studyDescription.hashCode())); + result = + ((result * 31) + ((this.studyDescription == null) ? 0 : this.studyDescription.hashCode())); result = ((result * 31) + ((this.nihAnvilUse == null) ? 0 : this.nihAnvilUse.hashCode())); - result = ((result * 31) + ((this.nihICsSupportingStudy == null) ? 0 - : this.nihICsSupportingStudy.hashCode())); + result = + ((result * 31) + + ((this.nihICsSupportingStudy == null) ? 0 : this.nihICsSupportingStudy.hashCode())); result = ((result * 31) + ((this.piName == null) ? 0 : this.piName.hashCode())); result = ((result * 31) + ((this.dbGaPPhsID == null) ? 0 : this.dbGaPPhsID.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlan == null) ? 0 - : this.alternativeDataSharingPlan.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanReasons == null) ? 0 - : this.alternativeDataSharingPlanReasons.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlan == null) + ? 0 + : this.alternativeDataSharingPlan.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanReasons == null) + ? 0 + : this.alternativeDataSharingPlanReasons.hashCode())); result = ((result * 31) + ((this.species == null) ? 0 : this.species.hashCode())); - result = ((result * 31) + ((this.embargoReleaseDate == null) ? 0 - : this.embargoReleaseDate.hashCode())); - result = ((result * 31) + ((this.alternativeDataSharingPlanExplanation == null) ? 0 - : this.alternativeDataSharingPlanExplanation.hashCode())); - result = ((result * 31) + ((this.nihInstitutionCenterSubmission == null) ? 0 - : this.nihInstitutionCenterSubmission.hashCode())); - result = ((result * 31) + ((this.controlledAccessRequiredForGenomicSummaryResultsGSR == null) - ? 0 : this.controlledAccessRequiredForGenomicSummaryResultsGSR.hashCode())); + result = + ((result * 31) + + ((this.embargoReleaseDate == null) ? 0 : this.embargoReleaseDate.hashCode())); + result = + ((result * 31) + + ((this.alternativeDataSharingPlanExplanation == null) + ? 0 + : this.alternativeDataSharingPlanExplanation.hashCode())); + result = + ((result * 31) + + ((this.nihInstitutionCenterSubmission == null) + ? 0 + : this.nihInstitutionCenterSubmission.hashCode())); + result = + ((result * 31) + + ((this.controlledAccessRequiredForGenomicSummaryResultsGSR == null) + ? 0 + : this.controlledAccessRequiredForGenomicSummaryResultsGSR.hashCode())); result = ((result * 31) + ((this.piInstitution == null) ? 0 : this.piInstitution.hashCode())); result = ((result * 31) + ((this.assets == null) ? 0 : this.assets.hashCode())); return result; @@ -1185,125 +1103,307 @@ public boolean equals(Object other) { } DatasetRegistrationSchemaV1 rhs = ((DatasetRegistrationSchemaV1) other); // nosemgrep - return ((((((((((((((((((((((((((((((( - ((((((this.nihGenomicProgramAdministratorName == rhs.nihGenomicProgramAdministratorName) - || ((this.nihGenomicProgramAdministratorName != null) - && this.nihGenomicProgramAdministratorName.equals( - rhs.nihGenomicProgramAdministratorName))) && ( - (this.alternativeDataSharingPlanFileName == rhs.alternativeDataSharingPlanFileName) || ( - (this.alternativeDataSharingPlanFileName != null) - && this.alternativeDataSharingPlanFileName.equals( - rhs.alternativeDataSharingPlanFileName)))) && - ((this.studyName == rhs.studyName) || ((this.studyName != null) - && this.studyName.equals(rhs.studyName))) && - ((this.studyId == rhs.studyId) || ((this.studyId != null) && this.studyId.equals( - rhs.studyId)))) && ( - (this.dataSubmitterUserId == rhs.dataSubmitterUserId) || ( - (this.dataSubmitterUserId != null) && this.dataSubmitterUserId.equals( - rhs.dataSubmitterUserId)))) && ((this.publicVisibility == rhs.publicVisibility) - || ((this.publicVisibility != null) && this.publicVisibility.equals( - rhs.publicVisibility)))) && ((this.dataCustodianEmail == rhs.dataCustodianEmail) || ( - (this.dataCustodianEmail != null) && this.dataCustodianEmail.equals( - rhs.dataCustodianEmail)))) && ((this.alternativeDataSharingPlanDataSubmitted - == rhs.alternativeDataSharingPlanDataSubmitted) || ( - (this.alternativeDataSharingPlanDataSubmitted != null) - && this.alternativeDataSharingPlanDataSubmitted.equals( - rhs.alternativeDataSharingPlanDataSubmitted)))) && ( - (this.submittingToAnvil == rhs.submittingToAnvil) || ((this.submittingToAnvil != null) - && this.submittingToAnvil.equals(rhs.submittingToAnvil)))) && ( - (this.dbGaPStudyRegistrationName == rhs.dbGaPStudyRegistrationName) || ( - (this.dbGaPStudyRegistrationName != null) && this.dbGaPStudyRegistrationName.equals( - rhs.dbGaPStudyRegistrationName)))) && ( - (this.collaboratingSites == rhs.collaboratingSites) || ((this.collaboratingSites != null) - && this.collaboratingSites.equals(rhs.collaboratingSites)))) && ( - (this.alternativeDataSharingPlanTargetDeliveryDate - == rhs.alternativeDataSharingPlanTargetDeliveryDate) || ( - (this.alternativeDataSharingPlanTargetDeliveryDate != null) - && this.alternativeDataSharingPlanTargetDeliveryDate.equals( - rhs.alternativeDataSharingPlanTargetDeliveryDate)))) && ( - (this.nihProgramOfficerName == rhs.nihProgramOfficerName) || ( - (this.nihProgramOfficerName != null) && this.nihProgramOfficerName.equals( - rhs.nihProgramOfficerName)))) && ((this.dataTypes == rhs.dataTypes) || ( - (this.dataTypes != null) && this.dataTypes.equals(rhs.dataTypes)))) && ( - (this.alternativeDataSharingPlanTargetPublicReleaseDate - == rhs.alternativeDataSharingPlanTargetPublicReleaseDate) || ( - (this.alternativeDataSharingPlanTargetPublicReleaseDate != null) - && this.alternativeDataSharingPlanTargetPublicReleaseDate.equals( - rhs.alternativeDataSharingPlanTargetPublicReleaseDate)))) && ( - (this.nihGrantContractNumber == rhs.nihGrantContractNumber) || ( - (this.nihGrantContractNumber != null) && this.nihGrantContractNumber.equals( - rhs.nihGrantContractNumber)))) && ((this.studyType == rhs.studyType) || ( - (this.studyType != null) && this.studyType.equals(rhs.studyType)))) && ( - (this.phenotypeIndication == rhs.phenotypeIndication) || ((this.phenotypeIndication != null) - && this.phenotypeIndication.equals(rhs.phenotypeIndication)))) && ( - (this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation - == rhs.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation) || ( - (this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation != null) - && this.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation.equals( - rhs.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation)))) && ( - (this.alternativeDataSharingPlanAccessManagement - == rhs.alternativeDataSharingPlanAccessManagement) || ( - (this.alternativeDataSharingPlanAccessManagement != null) - && this.alternativeDataSharingPlanAccessManagement.equals( - rhs.alternativeDataSharingPlanAccessManagement)))) && ( - (this.sequencingCenter == rhs.sequencingCenter) || ((this.sequencingCenter != null) - && this.sequencingCenter.equals(rhs.sequencingCenter)))) && ( - (this.multiCenterStudy == rhs.multiCenterStudy) || ((this.multiCenterStudy != null) - && this.multiCenterStudy.equals(rhs.multiCenterStudy)))) && ( - (this.alternativeDataSharingPlanDataReleased == rhs.alternativeDataSharingPlanDataReleased) - || ((this.alternativeDataSharingPlanDataReleased != null) - && this.alternativeDataSharingPlanDataReleased.equals( - rhs.alternativeDataSharingPlanDataReleased)))) && ( - (this.consentGroups == rhs.consentGroups) || ((this.consentGroups != null) - && this.consentGroups.equals(rhs.consentGroups)))) && ( - (this.studyDescription == rhs.studyDescription) || ((this.studyDescription != null) - && this.studyDescription.equals(rhs.studyDescription)))) && ( - (this.nihAnvilUse == rhs.nihAnvilUse) || ((this.nihAnvilUse != null) - && this.nihAnvilUse.equals(rhs.nihAnvilUse)))) && ( - (this.nihICsSupportingStudy == rhs.nihICsSupportingStudy) || ( - (this.nihICsSupportingStudy != null) && this.nihICsSupportingStudy.equals( - rhs.nihICsSupportingStudy)))) && ((this.piName == rhs.piName) || ( - (this.piName != null) && this.piName.equals(rhs.piName)))) && ( - (this.dbGaPPhsID == rhs.dbGaPPhsID) || ((this.dbGaPPhsID != null) && this.dbGaPPhsID.equals( - rhs.dbGaPPhsID)))) && ( - (this.alternativeDataSharingPlan == rhs.alternativeDataSharingPlan) || ( - (this.alternativeDataSharingPlan != null) && this.alternativeDataSharingPlan.equals( - rhs.alternativeDataSharingPlan)))) && ( - (this.alternativeDataSharingPlanReasons == rhs.alternativeDataSharingPlanReasons) || ( - (this.alternativeDataSharingPlanReasons != null) - && this.alternativeDataSharingPlanReasons.equals( - rhs.alternativeDataSharingPlanReasons)))) && ((this.species == rhs.species) || ( - (this.species != null) && this.species.equals(rhs.species)))) && ( - (this.embargoReleaseDate == rhs.embargoReleaseDate) || ((this.embargoReleaseDate != null) - && this.embargoReleaseDate.equals(rhs.embargoReleaseDate)))) && ( - (this.alternativeDataSharingPlanExplanation == rhs.alternativeDataSharingPlanExplanation) - || ((this.alternativeDataSharingPlanExplanation != null) - && this.alternativeDataSharingPlanExplanation.equals( - rhs.alternativeDataSharingPlanExplanation)))) && ( - (this.nihInstitutionCenterSubmission == rhs.nihInstitutionCenterSubmission) || ( - (this.nihInstitutionCenterSubmission != null) - && this.nihInstitutionCenterSubmission.equals(rhs.nihInstitutionCenterSubmission)))) - && ((this.controlledAccessRequiredForGenomicSummaryResultsGSR - == rhs.controlledAccessRequiredForGenomicSummaryResultsGSR) || ( - (this.controlledAccessRequiredForGenomicSummaryResultsGSR != null) - && this.controlledAccessRequiredForGenomicSummaryResultsGSR.equals( - rhs.controlledAccessRequiredForGenomicSummaryResultsGSR)))) && ( - (this.piInstitution == rhs.piInstitution) || ((this.piInstitution != null) - && this.piInstitution.equals(rhs.piInstitution)))) && ((this.assets == rhs.assets) - || ((this.assets != null) && this.assets.equals(rhs.assets))); - } - - - /** - * Does the data need to be managed under Controlled, Open, or External Access? - */ + return (((((((((((((((((((((((((((((((((((((this.nihGenomicProgramAdministratorName + == rhs.nihGenomicProgramAdministratorName) + || ((this + .nihGenomicProgramAdministratorName + != null) + && this + .nihGenomicProgramAdministratorName + .equals( + rhs.nihGenomicProgramAdministratorName))) + && ((this + .alternativeDataSharingPlanFileName + == rhs.alternativeDataSharingPlanFileName) + || ((this + .alternativeDataSharingPlanFileName + != null) + && this + .alternativeDataSharingPlanFileName + .equals( + rhs.alternativeDataSharingPlanFileName)))) + && ((this + .studyName + == rhs.studyName) + || ((this + .studyName + != null) + && this + .studyName + .equals( + rhs.studyName))) + && ((this + .studyId + == rhs.studyId) + || ((this + .studyId + != null) + && this + .studyId + .equals( + rhs.studyId)))) + && ((this + .dataSubmitterUserId + == rhs.dataSubmitterUserId) + || ((this + .dataSubmitterUserId + != null) + && this + .dataSubmitterUserId + .equals( + rhs.dataSubmitterUserId)))) + && ((this + .publicVisibility + == rhs.publicVisibility) + || ((this + .publicVisibility + != null) + && this + .publicVisibility + .equals( + rhs.publicVisibility)))) + && ((this + .dataCustodianEmail + == rhs.dataCustodianEmail) + || ((this + .dataCustodianEmail + != null) + && this + .dataCustodianEmail + .equals( + rhs.dataCustodianEmail)))) + && ((this + .alternativeDataSharingPlanDataSubmitted + == rhs.alternativeDataSharingPlanDataSubmitted) + || ((this + .alternativeDataSharingPlanDataSubmitted + != null) + && this + .alternativeDataSharingPlanDataSubmitted + .equals( + rhs.alternativeDataSharingPlanDataSubmitted)))) + && ((this + .submittingToAnvil + == rhs.submittingToAnvil) + || ((this + .submittingToAnvil + != null) + && this + .submittingToAnvil + .equals( + rhs.submittingToAnvil)))) + && ((this + .dbGaPStudyRegistrationName + == rhs.dbGaPStudyRegistrationName) + || ((this + .dbGaPStudyRegistrationName + != null) + && this + .dbGaPStudyRegistrationName + .equals( + rhs.dbGaPStudyRegistrationName)))) + && ((this + .collaboratingSites + == rhs.collaboratingSites) + || ((this + .collaboratingSites + != null) + && this + .collaboratingSites + .equals( + rhs.collaboratingSites)))) + && ((this + .alternativeDataSharingPlanTargetDeliveryDate + == rhs.alternativeDataSharingPlanTargetDeliveryDate) + || ((this + .alternativeDataSharingPlanTargetDeliveryDate + != null) + && this + .alternativeDataSharingPlanTargetDeliveryDate + .equals( + rhs.alternativeDataSharingPlanTargetDeliveryDate)))) + && ((this + .nihProgramOfficerName + == rhs.nihProgramOfficerName) + || ((this + .nihProgramOfficerName + != null) + && this + .nihProgramOfficerName + .equals( + rhs.nihProgramOfficerName)))) + && ((this + .dataTypes + == rhs.dataTypes) + || ((this + .dataTypes + != null) + && this + .dataTypes + .equals( + rhs.dataTypes)))) + && ((this + .alternativeDataSharingPlanTargetPublicReleaseDate + == rhs.alternativeDataSharingPlanTargetPublicReleaseDate) + || ((this + .alternativeDataSharingPlanTargetPublicReleaseDate + != null) + && this + .alternativeDataSharingPlanTargetPublicReleaseDate + .equals( + rhs.alternativeDataSharingPlanTargetPublicReleaseDate)))) + && ((this + .nihGrantContractNumber + == rhs.nihGrantContractNumber) + || ((this + .nihGrantContractNumber + != null) + && this + .nihGrantContractNumber + .equals( + rhs.nihGrantContractNumber)))) + && ((this + .studyType + == rhs.studyType) + || ((this + .studyType + != null) + && this + .studyType + .equals( + rhs.studyType)))) + && ((this + .phenotypeIndication + == rhs.phenotypeIndication) + || ((this + .phenotypeIndication + != null) + && this + .phenotypeIndication + .equals( + rhs.phenotypeIndication)))) + && ((this + .controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation + == rhs.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation) + || ((this + .controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation + != null) + && this + .controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation + .equals( + rhs.controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation)))) + && ((this + .alternativeDataSharingPlanAccessManagement + == rhs.alternativeDataSharingPlanAccessManagement) + || ((this + .alternativeDataSharingPlanAccessManagement + != null) + && this + .alternativeDataSharingPlanAccessManagement + .equals( + rhs.alternativeDataSharingPlanAccessManagement)))) + && ((this + .sequencingCenter + == rhs.sequencingCenter) + || ((this + .sequencingCenter + != null) + && this + .sequencingCenter + .equals( + rhs.sequencingCenter)))) + && ((this.multiCenterStudy + == rhs.multiCenterStudy) + || ((this + .multiCenterStudy + != null) + && this + .multiCenterStudy + .equals( + rhs.multiCenterStudy)))) + && ((this + .alternativeDataSharingPlanDataReleased + == rhs.alternativeDataSharingPlanDataReleased) + || ((this + .alternativeDataSharingPlanDataReleased + != null) + && this + .alternativeDataSharingPlanDataReleased + .equals( + rhs.alternativeDataSharingPlanDataReleased)))) + && ((this.consentGroups + == rhs.consentGroups) + || ((this.consentGroups != null) + && this.consentGroups + .equals( + rhs.consentGroups)))) + && ((this.studyDescription + == rhs.studyDescription) + || ((this.studyDescription != null) + && this.studyDescription.equals( + rhs.studyDescription)))) + && ((this.nihAnvilUse == rhs.nihAnvilUse) + || ((this.nihAnvilUse != null) + && this.nihAnvilUse.equals( + rhs.nihAnvilUse)))) + && ((this.nihICsSupportingStudy + == rhs.nihICsSupportingStudy) + || ((this.nihICsSupportingStudy != null) + && this.nihICsSupportingStudy.equals( + rhs.nihICsSupportingStudy)))) + && ((this.piName == rhs.piName) + || ((this.piName != null) + && this.piName.equals(rhs.piName)))) + && ((this.dbGaPPhsID == rhs.dbGaPPhsID) + || ((this.dbGaPPhsID != null) + && this.dbGaPPhsID.equals(rhs.dbGaPPhsID)))) + && ((this.alternativeDataSharingPlan + == rhs.alternativeDataSharingPlan) + || ((this.alternativeDataSharingPlan != null) + && this.alternativeDataSharingPlan.equals( + rhs.alternativeDataSharingPlan)))) + && ((this.alternativeDataSharingPlanReasons + == rhs.alternativeDataSharingPlanReasons) + || ((this.alternativeDataSharingPlanReasons != null) + && this.alternativeDataSharingPlanReasons.equals( + rhs.alternativeDataSharingPlanReasons)))) + && ((this.species == rhs.species) + || ((this.species != null) + && this.species.equals(rhs.species)))) + && ((this.embargoReleaseDate == rhs.embargoReleaseDate) + || ((this.embargoReleaseDate != null) + && this.embargoReleaseDate.equals(rhs.embargoReleaseDate)))) + && ((this.alternativeDataSharingPlanExplanation + == rhs.alternativeDataSharingPlanExplanation) + || ((this.alternativeDataSharingPlanExplanation != null) + && this.alternativeDataSharingPlanExplanation.equals( + rhs.alternativeDataSharingPlanExplanation)))) + && ((this.nihInstitutionCenterSubmission == rhs.nihInstitutionCenterSubmission) + || ((this.nihInstitutionCenterSubmission != null) + && this.nihInstitutionCenterSubmission.equals( + rhs.nihInstitutionCenterSubmission)))) + && ((this.controlledAccessRequiredForGenomicSummaryResultsGSR + == rhs.controlledAccessRequiredForGenomicSummaryResultsGSR) + || ((this.controlledAccessRequiredForGenomicSummaryResultsGSR != null) + && this.controlledAccessRequiredForGenomicSummaryResultsGSR.equals( + rhs.controlledAccessRequiredForGenomicSummaryResultsGSR)))) + && ((this.piInstitution == rhs.piInstitution) + || ((this.piInstitution != null) && this.piInstitution.equals(rhs.piInstitution)))) + && ((this.assets == rhs.assets) + || ((this.assets != null) && this.assets.equals(rhs.assets))); + } + + /** Does the data need to be managed under Controlled, Open, or External Access? */ public enum AlternativeDataSharingPlanAccessManagement { - CONTROLLED_ACCESS("Controlled Access"), OPEN_ACCESS("Open Access"), EXTERNAL_ACCESS("External Access"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map< + String, DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement> + CONSTANTS = + new HashMap< + String, DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement>(); static { for (DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement c : values()) { @@ -1328,29 +1428,28 @@ public String value() { @JsonCreator public static DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement fromValue( String value) { - DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement constant = CONSTANTS.get( - value); + DatasetRegistrationSchemaV1.AlternativeDataSharingPlanAccessManagement constant = + CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } - } - - /** - * Upload your alternative sharing plan (file upload) - */ + /** Upload your alternative sharing plan (file upload) */ public enum AlternativeDataSharingPlanDataSubmitted { - WITHIN_3_MONTHS_OF_THE_LAST_DATA_GENERATED_OR_LAST_CLINICAL_VISIT( "Within 3 months of the last data generated or last clinical visit"), BY_BATCHES_OVER_STUDY_TIMELINE_E_G_BASED_ON_CLINICAL_TRIAL_ENROLLMENT_BENCHMARKS( "By batches over Study Timeline (e.g. based on clinical trial enrollment benchmarks)"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map< + String, DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted> + CONSTANTS = + new HashMap< + String, DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted>(); static { for (DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted c : values()) { @@ -1375,23 +1474,18 @@ public String value() { @JsonCreator public static DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted fromValue( String value) { - DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted constant = CONSTANTS.get( - value); + DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted constant = + CONSTANTS.get(value); if (constant == null) { throw new IllegalArgumentException(value); } else { return constant; } } - } - - /** - * NIH Anvil Use - */ + /** NIH Anvil Use */ public enum NihAnvilUse { - I_AM_NHGRI_FUNDED_AND_I_HAVE_A_DB_GA_P_PHS_ID_ALREADY( "I am NHGRI funded and I have a dbGaP PHS ID already"), I_AM_NHGRI_FUNDED_AND_I_DO_NOT_HAVE_A_DB_GA_P_PHS_ID( @@ -1401,7 +1495,8 @@ public enum NihAnvilUse { I_AM_NOT_NHGRI_FUNDED_AND_DO_NOT_PLAN_TO_STORE_DATA_IN_AN_VIL( "I am not NHGRI funded and do not plan to store data in AnVIL"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map CONSTANTS = + new HashMap(); static { for (DatasetRegistrationSchemaV1.NihAnvilUse c : values()) { @@ -1432,15 +1527,10 @@ public static DatasetRegistrationSchemaV1.NihAnvilUse fromValue(String value) { return constant; } } - } - - /** - * NIH Institution/Center for Submission - */ + /** NIH Institution/Center for Submission */ public enum NihInstitutionCenterSubmission { - NCI("NCI"), NEI("NEI"), NHLBI("NHLBI"), @@ -1469,7 +1559,9 @@ public enum NihInstitutionCenterSubmission { NCATS("NCATS"), NCCIH("NCCIH"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map + CONSTANTS = + new HashMap(); static { for (DatasetRegistrationSchemaV1.NihInstitutionCenterSubmission c : values()) { @@ -1501,15 +1593,10 @@ public static DatasetRegistrationSchemaV1.NihInstitutionCenterSubmission fromVal return constant; } } - } - - /** - * The study type - */ + /** The study type */ public enum StudyType { - OBSERVATIONAL("Observational"), INTERVENTIONAL("Interventional"), DESCRIPTIVE("Descriptive"), @@ -1521,7 +1608,8 @@ public enum StudyType { CROSS_SECTIONAL("Cross-sectional"), COHORT_STUDY("Cohort study"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map CONSTANTS = + new HashMap(); static { for (DatasetRegistrationSchemaV1.StudyType c : values()) { @@ -1552,7 +1640,5 @@ public static DatasetRegistrationSchemaV1.StudyType fromValue(String value) { return constant; } } - } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidator.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidator.java index 20614a4248..2b729ce569 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidator.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidator.java @@ -28,49 +28,52 @@ public DatasetRegistrationSchemaV1UpdateValidator(DatasetService datasetService) this.datasetService = datasetService; } - private final ExclusionStrategy studyExclusionStrategy = new ExclusionStrategy() { - @Override - public boolean shouldSkipField(FieldAttributes fieldAttributes) { - return fieldAttributes.getName().equalsIgnoreCase("dataSubmitterUserId"); - } + private final ExclusionStrategy studyExclusionStrategy = + new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes fieldAttributes) { + return fieldAttributes.getName().equalsIgnoreCase("dataSubmitterUserId"); + } - @Override - public boolean shouldSkipClass(Class aClass) { - return aClass.getSimpleName().equalsIgnoreCase("ConsentGroup"); - } - }; - - private final ExclusionStrategy consentGroupExclusionStrategy = new ExclusionStrategy() { - @Override - public boolean shouldSkipField(FieldAttributes fieldAttributes) { - final HashSet exclusions = new HashSet<>(List.of( - DatasetRegistrationSchemaV1Builder.accessManagement, - DatasetRegistrationSchemaV1Builder.col, - DatasetRegistrationSchemaV1Builder.dataAccessCommitteeId, - DatasetRegistrationSchemaV1Builder.datasetIdentifier, - DatasetRegistrationSchemaV1Builder.diseaseSpecificUse, - DatasetRegistrationSchemaV1Builder.generalResearchUse, - DatasetRegistrationSchemaV1Builder.gs, - DatasetRegistrationSchemaV1Builder.gso, - DatasetRegistrationSchemaV1Builder.hmb, - DatasetRegistrationSchemaV1Builder.irb, - DatasetRegistrationSchemaV1Builder.nmds, - DatasetRegistrationSchemaV1Builder.mor, - DatasetRegistrationSchemaV1Builder.morDate, - DatasetRegistrationSchemaV1Builder.npu, - DatasetRegistrationSchemaV1Builder.otherPrimary, - DatasetRegistrationSchemaV1Builder.otherSecondary, - DatasetRegistrationSchemaV1Builder.pub, - DatasetRegistrationSchemaV1Builder.poa - )); - return exclusions.contains(fieldAttributes.getName()); - } + @Override + public boolean shouldSkipClass(Class aClass) { + return aClass.getSimpleName().equalsIgnoreCase("ConsentGroup"); + } + }; + + private final ExclusionStrategy consentGroupExclusionStrategy = + new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes fieldAttributes) { + final HashSet exclusions = + new HashSet<>( + List.of( + DatasetRegistrationSchemaV1Builder.accessManagement, + DatasetRegistrationSchemaV1Builder.col, + DatasetRegistrationSchemaV1Builder.dataAccessCommitteeId, + DatasetRegistrationSchemaV1Builder.datasetIdentifier, + DatasetRegistrationSchemaV1Builder.diseaseSpecificUse, + DatasetRegistrationSchemaV1Builder.generalResearchUse, + DatasetRegistrationSchemaV1Builder.gs, + DatasetRegistrationSchemaV1Builder.gso, + DatasetRegistrationSchemaV1Builder.hmb, + DatasetRegistrationSchemaV1Builder.irb, + DatasetRegistrationSchemaV1Builder.nmds, + DatasetRegistrationSchemaV1Builder.mor, + DatasetRegistrationSchemaV1Builder.morDate, + DatasetRegistrationSchemaV1Builder.npu, + DatasetRegistrationSchemaV1Builder.otherPrimary, + DatasetRegistrationSchemaV1Builder.otherSecondary, + DatasetRegistrationSchemaV1Builder.pub, + DatasetRegistrationSchemaV1Builder.poa)); + return exclusions.contains(fieldAttributes.getName()); + } - @Override - public boolean shouldSkipClass(Class aClass) { - return false; - } - }; + @Override + public boolean shouldSkipClass(Class aClass) { + return false; + } + }; /** * Create a registration object suitable for the Update operation. @@ -79,34 +82,40 @@ public boolean shouldSkipClass(Class aClass) { * @return DatasetRegistrationSchemaV1 */ public DatasetRegistrationSchemaV1 deserializeRegistration(String json) { - Gson studyGson = GsonUtil.gsonBuilderWithAdapters() - .addDeserializationExclusionStrategy(studyExclusionStrategy) - .create(); + Gson studyGson = + GsonUtil.gsonBuilderWithAdapters() + .addDeserializationExclusionStrategy(studyExclusionStrategy) + .create(); // Create the registration without any ConsentGroups - DatasetRegistrationSchemaV1 registration = studyGson.fromJson(json, - DatasetRegistrationSchemaV1.class); + DatasetRegistrationSchemaV1 registration = + studyGson.fromJson(json, DatasetRegistrationSchemaV1.class); // Ensure that we have no null entries before parsing them. registration.setConsentGroups(new ArrayList<>()); // Conditionally parse the consent groups Gson gson = GsonUtil.getInstance(); - Gson filteredCGGson = GsonUtil.gsonBuilderWithAdapters() - .addDeserializationExclusionStrategy(consentGroupExclusionStrategy).create(); + Gson filteredCGGson = + GsonUtil.gsonBuilderWithAdapters() + .addDeserializationExclusionStrategy(consentGroupExclusionStrategy) + .create(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); JsonArray jsonArray = jsonObject.getAsJsonArray("consentGroups"); if (jsonArray != null) { - jsonArray.asList().forEach(jsonElement -> { - JsonObject cgJson = jsonElement.getAsJsonObject(); - if (cgJson.has("datasetId")) { - // If we have a dataset id, we're updating. Filter out non-updatable fields - ConsentGroup cg = filteredCGGson.fromJson(cgJson, ConsentGroup.class); - registration.getConsentGroups().add(cg); - } else { - // If we have don't have a dataset id, we're trying to add a new one to the study. - ConsentGroup cg = gson.fromJson(cgJson, ConsentGroup.class); - registration.getConsentGroups().add(cg); - } - }); + jsonArray + .asList() + .forEach( + jsonElement -> { + JsonObject cgJson = jsonElement.getAsJsonObject(); + if (cgJson.has("datasetId")) { + // If we have a dataset id, we're updating. Filter out non-updatable fields + ConsentGroup cg = filteredCGGson.fromJson(cgJson, ConsentGroup.class); + registration.getConsentGroups().add(cg); + } else { + // If we have don't have a dataset id, we're trying to add a new one to the study. + ConsentGroup cg = gson.fromJson(cgJson, ConsentGroup.class); + registration.getConsentGroups().add(cg); + } + }); } return registration; } @@ -115,8 +124,8 @@ public boolean validate(Study existingStudy, DatasetRegistrationSchemaV1 registr // Validate that the new study name is unique Set studyNames = datasetService.findAllStudyNames(); - if (studyNames.contains(registration.getStudyName()) && - !registration.getStudyName().equals(existingStudy.getName())) { + if (studyNames.contains(registration.getStudyName()) + && !registration.getStudyName().equals(existingStudy.getName())) { throw new BadRequestException("Invalid change to Study Name"); } @@ -132,41 +141,42 @@ public boolean validate(Study existingStudy, DatasetRegistrationSchemaV1 registr } // Ensure that all consent group changes are for datasets in the current study - List nonStudyConsentGroups = registration.getConsentGroups() - .stream() - .filter(cg -> Objects.nonNull(cg.getDatasetId())) - .filter(cg -> existingStudy - .getDatasetIds() - .stream() - .noneMatch(id -> id.equals(cg.getDatasetId()))) - .toList(); + List nonStudyConsentGroups = + registration.getConsentGroups().stream() + .filter(cg -> Objects.nonNull(cg.getDatasetId())) + .filter( + cg -> + existingStudy.getDatasetIds().stream() + .noneMatch(id -> id.equals(cg.getDatasetId()))) + .toList(); if (!nonStudyConsentGroups.isEmpty()) { throw new BadRequestException("Invalid Consent Group changes to study"); } // Consent Name changes are not allowed for existing datasets unless it is empty - List invalidConsentGroupNameChanges = registration.getConsentGroups() - .stream() - .filter(cg -> Objects.nonNull(cg.getDatasetId())) - .filter(cg -> Objects.nonNull(cg.getConsentGroupName())) - // If the dataset already has a name, this consent group is invalid - .filter(cg -> { - Optional dataset = SetUtils.emptyIfNull(existingStudy.getDatasets()) - .stream() - .filter(d -> d.getDatasetId().equals(cg.getDatasetId())) - .findFirst(); - return dataset.isPresent() && !dataset.get().getName().isBlank(); - }) - .toList(); + List invalidConsentGroupNameChanges = + registration.getConsentGroups().stream() + .filter(cg -> Objects.nonNull(cg.getDatasetId())) + .filter(cg -> Objects.nonNull(cg.getConsentGroupName())) + // If the dataset already has a name, this consent group is invalid + .filter( + cg -> { + Optional dataset = + SetUtils.emptyIfNull(existingStudy.getDatasets()).stream() + .filter(d -> d.getDatasetId().equals(cg.getDatasetId())) + .findFirst(); + return dataset.isPresent() && !dataset.get().getName().isBlank(); + }) + .toList(); if (!invalidConsentGroupNameChanges.isEmpty()) { throw new BadRequestException("Invalid Name changes to existing Consent Groups"); } // Data Location required for all consent groups - List missingDataLocationConsentGroups = registration.getConsentGroups() - .stream() - .filter(cg -> Objects.isNull(cg.getDataLocation())) - .toList(); + List missingDataLocationConsentGroups = + registration.getConsentGroups().stream() + .filter(cg -> Objects.isNull(cg.getDataLocation())) + .toList(); if (!missingDataLocationConsentGroups.isEmpty()) { throw new BadRequestException("Missing Data Location for Consent Groups"); } @@ -175,13 +185,15 @@ public boolean validate(Study existingStudy, DatasetRegistrationSchemaV1 registr // The list of non-null dataset ids in the consent groups MUST be the same as the list of // existing dataset ids. HashSet existingDatasetIds = - Objects.nonNull(existingStudy.getDatasetIds()) ? new HashSet<>( - existingStudy.getDatasetIds()) : new HashSet<>(); - HashSet consentGroupDatasetIds = new HashSet<>(registration.getConsentGroups() - .stream() - .map(ConsentGroup::getDatasetId) - .filter(Objects::nonNull) - .toList()); + Objects.nonNull(existingStudy.getDatasetIds()) + ? new HashSet<>(existingStudy.getDatasetIds()) + : new HashSet<>(); + HashSet consentGroupDatasetIds = + new HashSet<>( + registration.getConsentGroups().stream() + .map(ConsentGroup::getDatasetId) + .filter(Objects::nonNull) + .toList()); if (!consentGroupDatasetIds.containsAll(existingDatasetIds)) { throw new BadRequestException("Invalid removal of Consent Groups"); } @@ -211,8 +223,8 @@ public boolean validate(Study existingStudy, DatasetRegistrationSchemaV1 registr throw new BadRequestException("NIH Grant of Contract Number is required"); } } - if (anvilUse.equals(NihAnvilUse.I_AM_NHGRI_FUNDED_AND_I_DO_NOT_HAVE_A_DB_GA_P_PHS_ID) || - anvilUse.equals( + if (anvilUse.equals(NihAnvilUse.I_AM_NHGRI_FUNDED_AND_I_DO_NOT_HAVE_A_DB_GA_P_PHS_ID) + || anvilUse.equals( NihAnvilUse.I_AM_NOT_NHGRI_FUNDED_BUT_I_AM_SEEKING_TO_SUBMIT_DATA_TO_AN_VIL)) { if (Objects.isNull(registration.getPiInstitution())) { throw new BadRequestException("PI Institution is required"); @@ -227,5 +239,4 @@ public boolean validate(Study existingStudy, DatasetRegistrationSchemaV1 registr return true; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/FileTypeObject.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/FileTypeObject.java index b4df994053..a9a52f802c 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/FileTypeObject.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/FileTypeObject.java @@ -10,52 +10,38 @@ import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "fileType", - "functionalEquivalence" -}) +@JsonPropertyOrder({"fileType", "functionalEquivalence"}) public class FileTypeObject { - /** - * File Type - */ + /** File Type */ @JsonProperty("fileType") @JsonPropertyDescription("File Type") private FileTypeObject.FileType fileType; - /** - * Functional Equivalence - */ + + /** Functional Equivalence */ @JsonProperty("functionalEquivalence") @JsonPropertyDescription("Functional Equivalence") private String functionalEquivalence; - /** - * File Type - */ + /** File Type */ @JsonProperty("fileType") public FileTypeObject.FileType getFileType() { return fileType; } - /** - * File Type - */ + /** File Type */ @JsonProperty("fileType") public void setFileType(FileTypeObject.FileType fileType) { this.fileType = fileType; } - /** - * Functional Equivalence - */ + /** Functional Equivalence */ @JsonProperty("functionalEquivalence") public String getFunctionalEquivalence() { return functionalEquivalence; } - /** - * Functional Equivalence - */ + /** Functional Equivalence */ @JsonProperty("functionalEquivalence") public void setFunctionalEquivalence(String functionalEquivalence) { this.functionalEquivalence = functionalEquivalence; @@ -64,8 +50,10 @@ public void setFunctionalEquivalence(String functionalEquivalence) { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(FileTypeObject.class.getName()).append('@') - .append(Integer.toHexString(System.identityHashCode(this))).append('['); + sb.append(FileTypeObject.class.getName()) + .append('@') + .append(Integer.toHexString(System.identityHashCode(this))) + .append('['); sb.append("fileType"); sb.append('='); sb.append(((this.fileType == null) ? "" : this.fileType)); @@ -85,8 +73,9 @@ public String toString() { @Override public int hashCode() { int result = 1; - result = ((result * 31) + ((this.functionalEquivalence == null) ? 0 - : this.functionalEquivalence.hashCode())); + result = + ((result * 31) + + ((this.functionalEquivalence == null) ? 0 : this.functionalEquivalence.hashCode())); result = ((result * 31) + ((this.fileType == null) ? 0 : this.fileType.hashCode())); return result; } @@ -100,25 +89,23 @@ public boolean equals(Object other) { return false; } FileTypeObject rhs = ((FileTypeObject) other); - return (((this.functionalEquivalence == rhs.functionalEquivalence) || ( - (this.functionalEquivalence != null) && this.functionalEquivalence.equals( - rhs.functionalEquivalence)))) && ((this.fileType == rhs.fileType) || ( - (this.fileType != null) && this.fileType.equals(rhs.fileType))); + return (((this.functionalEquivalence == rhs.functionalEquivalence) + || ((this.functionalEquivalence != null) + && this.functionalEquivalence.equals(rhs.functionalEquivalence)))) + && ((this.fileType == rhs.fileType) + || ((this.fileType != null) && this.fileType.equals(rhs.fileType))); } - - /** - * File Type - */ + /** File Type */ public enum FileType { - ARRAYS("Arrays"), GENOME("Genome"), EXOME("Exome"), SURVEY("Survey"), PHENOTYPE("Phenotype"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map CONSTANTS = + new HashMap(); static { for (FileTypeObject.FileType c : values()) { @@ -149,7 +136,5 @@ public static FileTypeObject.FileType fromValue(String value) { return constant; } } - } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/NihICsSupportingStudy.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/NihICsSupportingStudy.java index de069dd39b..1e130062bf 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/NihICsSupportingStudy.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/NihICsSupportingStudy.java @@ -6,7 +6,6 @@ import java.util.Map; public enum NihICsSupportingStudy { - NCI("NCI"), NEI("NEI"), NHLBI("NHLBI"), @@ -35,7 +34,8 @@ public enum NihICsSupportingStudy { NCATS("NCATS"), NCCIH("NCCIH"); private final String value; - private static final Map CONSTANTS = new HashMap(); + private static final Map CONSTANTS = + new HashMap(); static { for (NihICsSupportingStudy c : values()) { @@ -66,5 +66,4 @@ public static NihICsSupportingStudy fromValue(String value) { return constant; } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/ConsentGroupFromDataset.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/ConsentGroupFromDataset.java index e9d3e7cc79..ee31660414 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/ConsentGroupFromDataset.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/ConsentGroupFromDataset.java @@ -77,9 +77,10 @@ public ConsentGroup build(Dataset dataset) { @Nullable private String findStringDSPropValue(Set props, String propName) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() - .filter(p -> p.getSchemaProperty() != null && p.getSchemaProperty().equalsIgnoreCase(propName)) + return props.stream() + .filter( + p -> + p.getSchemaProperty() != null && p.getSchemaProperty().equalsIgnoreCase(propName)) .map(DatasetProperty::getPropertyValueAsString) .findFirst() .orElse(null); @@ -90,9 +91,10 @@ private String findStringDSPropValue(Set props, String propName @Nullable private Integer findIntegerDSPropValue(Set props, String propName) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() - .filter(p -> p.getSchemaProperty() != null && p.getSchemaProperty().equalsIgnoreCase(propName)) + return props.stream() + .filter( + p -> + p.getSchemaProperty() != null && p.getSchemaProperty().equalsIgnoreCase(propName)) .map(DatasetProperty::getPropertyValue) .map(Object::toString) .map(Integer::valueOf) @@ -105,9 +107,11 @@ private Integer findIntegerDSPropValue(Set props, String propNa @Nullable private List findListFTSODSPropValue(Set props) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() - .filter(p -> p.getSchemaProperty() != null && p.getSchemaProperty().equalsIgnoreCase(fileTypes)) + return props.stream() + .filter( + p -> + p.getSchemaProperty() != null + && p.getSchemaProperty().equalsIgnoreCase(fileTypes)) .map(DatasetProperty::getPropertyValueAsString) .map(p -> GsonUtil.getInstance().fromJson(p, JsonArray.class)) .map(JsonArray::asList) @@ -117,5 +121,4 @@ private List findListFTSODSPropValue(Set props) } return null; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/DatasetRegistrationSchemaV1Builder.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/DatasetRegistrationSchemaV1Builder.java index e18599d4cc..4fc10d1d7c 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/DatasetRegistrationSchemaV1Builder.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/DatasetRegistrationSchemaV1Builder.java @@ -24,19 +24,31 @@ public class DatasetRegistrationSchemaV1Builder { public static final String nihICsSupportingStudy = "nihICsSupportingStudy"; public static final String nihProgramOfficerName = "nihProgramOfficerName"; public static final String nihInstitutionCenterSubmission = "nihInstitutionCenterSubmission"; - public static final String nihGenomicProgramAdministratorName = "nihGenomicProgramAdministratorName"; + public static final String nihGenomicProgramAdministratorName = + "nihGenomicProgramAdministratorName"; public static final String multiCenterStudy = "multiCenterStudy"; public static final String collaboratingSites = "collaboratingSites"; - public static final String controlledAccessRequiredForGenomicSummaryResultsGSR = "controlledAccessRequiredForGenomicSummaryResultsGSR"; - public static final String controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation = "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation"; - public static final String alternativeDataSharingPlanReasons = "alternativeDataSharingPlanReasons"; - public static final String alternativeDataSharingPlanExplanation = "alternativeDataSharingPlanExplanation"; - public static final String alternativeDataSharingPlanFileName = "alternativeDataSharingPlanFileName"; - public static final String alternativeDataSharingPlanDataSubmitted = "alternativeDataSharingPlanDataSubmitted"; - public static final String alternativeDataSharingPlanDataReleased = "alternativeDataSharingPlanDataReleased"; - public static final String alternativeDataSharingPlanTargetDeliveryDate = "alternativeDataSharingPlanTargetDeliveryDate"; - public static final String alternativeDataSharingPlanTargetPublicReleaseDate = "alternativeDataSharingPlanTargetPublicReleaseDate"; - public static final String alternativeDataSharingPlanAccessManagement = "alternativeDataSharingPlanAccessManagement"; + public static final String controlledAccessRequiredForGenomicSummaryResultsGSR = + "controlledAccessRequiredForGenomicSummaryResultsGSR"; + public static final String + controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation = + "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation"; + public static final String alternativeDataSharingPlanReasons = + "alternativeDataSharingPlanReasons"; + public static final String alternativeDataSharingPlanExplanation = + "alternativeDataSharingPlanExplanation"; + public static final String alternativeDataSharingPlanFileName = + "alternativeDataSharingPlanFileName"; + public static final String alternativeDataSharingPlanDataSubmitted = + "alternativeDataSharingPlanDataSubmitted"; + public static final String alternativeDataSharingPlanDataReleased = + "alternativeDataSharingPlanDataReleased"; + public static final String alternativeDataSharingPlanTargetDeliveryDate = + "alternativeDataSharingPlanTargetDeliveryDate"; + public static final String alternativeDataSharingPlanTargetPublicReleaseDate = + "alternativeDataSharingPlanTargetPublicReleaseDate"; + public static final String alternativeDataSharingPlanAccessManagement = + "alternativeDataSharingPlanAccessManagement"; public static final String assets = "assets"; public static final String accessManagement = "accessManagement"; public static final String generalResearchUse = "generalResearchUse"; @@ -65,16 +77,12 @@ public DatasetRegistrationSchemaV1 build(Study study, List datasets) { DatasetRegistrationSchemaV1 schema = new SchemaFromStudy().build(study); if (!datasets.isEmpty()) { ConsentGroupFromDataset consentGroupFromDataset = new ConsentGroupFromDataset(); - List consentGroups = datasets - .stream() - .filter(Objects::nonNull) - .map(consentGroupFromDataset::build) - .toList(); + List consentGroups = + datasets.stream().filter(Objects::nonNull).map(consentGroupFromDataset::build).toList(); if (!consentGroups.isEmpty()) { schema.setConsentGroups(consentGroups); } } return schema; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/SchemaFromStudy.java b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/SchemaFromStudy.java index 853ca7f345..8e3d8c395e 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/SchemaFromStudy.java +++ b/src/main/java/org/broadinstitute/consent/http/models/dataset_registration_v1/builder/SchemaFromStudy.java @@ -50,7 +50,7 @@ public class SchemaFromStudy { public DatasetRegistrationSchemaV1 build(Study study) { - DatasetRegistrationSchemaV1 schemaV1 = new DatasetRegistrationSchemaV1(); + DatasetRegistrationSchemaV1 schemaV1 = new DatasetRegistrationSchemaV1(); if (Objects.nonNull(study)) { schemaV1.setStudyId(study.getStudyId()); @@ -86,8 +86,8 @@ public DatasetRegistrationSchemaV1 build(Study study) { schemaV1.setNihICsSupportingStudy(findListNICSSPropValue(study.getProperties())); schemaV1.setNihProgramOfficerName( findStringPropValue(study.getProperties(), nihProgramOfficerName)); - String nihInstitutionCenterSubmissionVal = findStringPropValue(study.getProperties(), - nihInstitutionCenterSubmission); + String nihInstitutionCenterSubmissionVal = + findStringPropValue(study.getProperties(), nihInstitutionCenterSubmission); if (Objects.nonNull(nihInstitutionCenterSubmissionVal)) { schemaV1.setNihInstitutionCenterSubmission( NihInstitutionCenterSubmission.fromValue(nihInstitutionCenterSubmissionVal)); @@ -98,10 +98,11 @@ public DatasetRegistrationSchemaV1 build(Study study) { schemaV1.setCollaboratingSites( findListStringPropValue(study.getProperties(), collaboratingSites)); schemaV1.setControlledAccessRequiredForGenomicSummaryResultsGSR( - findBooleanPropValue(study.getProperties(), - controlledAccessRequiredForGenomicSummaryResultsGSR)); + findBooleanPropValue( + study.getProperties(), controlledAccessRequiredForGenomicSummaryResultsGSR)); schemaV1.setControlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation( - findStringPropValue(study.getProperties(), + findStringPropValue( + study.getProperties(), controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation)); if (Objects.nonNull(study.getAlternativeDataSharingPlan())) { schemaV1.setAlternativeDataSharingPlan(Boolean.TRUE); @@ -111,8 +112,8 @@ public DatasetRegistrationSchemaV1 build(Study study) { findStringPropValue(study.getProperties(), alternativeDataSharingPlanExplanation)); schemaV1.setAlternativeDataSharingPlanFileName( findStringPropValue(study.getProperties(), alternativeDataSharingPlanFileName)); - String alternativeDataSharingPlanDataSubmittedVal = findStringPropValue(study.getProperties(), - alternativeDataSharingPlanDataSubmitted); + String alternativeDataSharingPlanDataSubmittedVal = + findStringPropValue(study.getProperties(), alternativeDataSharingPlanDataSubmitted); if (Objects.nonNull(alternativeDataSharingPlanDataSubmittedVal)) { schemaV1.setAlternativeDataSharingPlanDataSubmitted( AlternativeDataSharingPlanDataSubmitted.fromValue( @@ -123,10 +124,10 @@ public DatasetRegistrationSchemaV1 build(Study study) { schemaV1.setAlternativeDataSharingPlanTargetDeliveryDate( findStringPropValue(study.getProperties(), alternativeDataSharingPlanTargetDeliveryDate)); schemaV1.setAlternativeDataSharingPlanTargetPublicReleaseDate( - findStringPropValue(study.getProperties(), - alternativeDataSharingPlanTargetPublicReleaseDate)); - String alternativeDataSharingPlanAccessManagementVal = findStringPropValue( - study.getProperties(), alternativeDataSharingPlanAccessManagement); + findStringPropValue( + study.getProperties(), alternativeDataSharingPlanTargetPublicReleaseDate)); + String alternativeDataSharingPlanAccessManagementVal = + findStringPropValue(study.getProperties(), alternativeDataSharingPlanAccessManagement); if (Objects.nonNull(alternativeDataSharingPlanAccessManagementVal)) { schemaV1.setAlternativeDataSharingPlanAccessManagement( AlternativeDataSharingPlanAccessManagement.fromValue( @@ -138,12 +139,10 @@ public DatasetRegistrationSchemaV1 build(Study study) { return schemaV1; } - @Nullable private List findListStringPropValue(Set props, String key) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() + return props.stream() .filter(p -> p.getKey().equalsIgnoreCase(key)) .map(StudyProperty::getValue) .map(p -> GsonUtil.getInstance().fromJson(p.toString(), JsonElement.class)) @@ -159,8 +158,7 @@ private List findListStringPropValue(Set props, String ke @Nullable private List findListADSPRPropValue(Set props) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() + return props.stream() .filter(p -> p.getKey().equalsIgnoreCase(alternativeDataSharingPlanReasons)) .map(StudyProperty::getValue) .map(p -> GsonUtil.getInstance().fromJson(p.toString(), JsonElement.class)) @@ -177,8 +175,7 @@ private List findListADSPRPropValue(Set findListNICSSPropValue(Set props) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() + return props.stream() .filter(p -> p.getKey().equalsIgnoreCase(nihICsSupportingStudy)) .map(StudyProperty::getValue) .map(p -> GsonUtil.getInstance().fromJson(p.toString(), JsonElement.class)) @@ -195,8 +192,7 @@ private List findListNICSSPropValue(Set pr @Nullable private String findStringPropValue(Set props, String propName) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() + return props.stream() .filter(p -> p.getKey().equalsIgnoreCase(propName)) .map(StudyProperty::getValue) .map(Object::toString) @@ -209,8 +205,7 @@ private String findStringPropValue(Set props, String propName) { @Nullable private Boolean findBooleanPropValue(Set props, String propName) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() + return props.stream() .filter(p -> p.getKey().equalsIgnoreCase(propName)) .map(StudyProperty::getValue) .map(Object::toString) @@ -223,8 +218,7 @@ private Boolean findBooleanPropValue(Set props, String propName) private Integer findIntegerPropValue(Set props, String propName) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() + return props.stream() .filter(p -> p.getKey().equalsIgnoreCase(propName)) .map(StudyProperty::getValue) .map(Object::toString) @@ -236,18 +230,23 @@ private Integer findIntegerPropValue(Set props, String propName) } @Nullable - private java.util.Map findMapPropValue(Set props, String propName) { + private java.util.Map findMapPropValue( + Set props, String propName) { if (Objects.nonNull(props) && !props.isEmpty()) { - return props - .stream() + return props.stream() .filter(p -> p.getKey().equalsIgnoreCase(propName)) .map(StudyProperty::getValue) - .map(p -> (java.util.Map) GsonUtil.getInstance().fromJson(p.toString(), - new com.google.gson.reflect.TypeToken>(){}.getType())) + .map( + p -> + (java.util.Map) + GsonUtil.getInstance() + .fromJson( + p.toString(), + new com.google.gson.reflect.TypeToken< + java.util.Map>() {}.getType())) .findFirst() .orElse(null); } return null; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/ecm/LinkInfo.java b/src/main/java/org/broadinstitute/consent/http/models/ecm/LinkInfo.java index 85bf271ba5..cfc2367faf 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/ecm/LinkInfo.java +++ b/src/main/java/org/broadinstitute/consent/http/models/ecm/LinkInfo.java @@ -1,4 +1,3 @@ package org.broadinstitute.consent.http.models.ecm; -public record LinkInfo(String externalUserId, String expirationTimestamp, Boolean authenticated) { -} +public record LinkInfo(String externalUserId, String expirationTimestamp, Boolean authenticated) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/elastic_search/DacTerm.java b/src/main/java/org/broadinstitute/consent/http/models/elastic_search/DacTerm.java index feab66b759..877e7c9bcc 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/elastic_search/DacTerm.java +++ b/src/main/java/org/broadinstitute/consent/http/models/elastic_search/DacTerm.java @@ -1,5 +1,3 @@ package org.broadinstitute.consent.http.models.elastic_search; -public record DacTerm(Integer dacId, String dacName, String dacEmail) { - -} +public record DacTerm(Integer dacId, String dacName, String dacEmail) {} diff --git a/src/main/java/org/broadinstitute/consent/http/models/elastic_search/ElasticSearchHitsInternal.java b/src/main/java/org/broadinstitute/consent/http/models/elastic_search/ElasticSearchHitsInternal.java index 4d54715c80..75170f99e1 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/elastic_search/ElasticSearchHitsInternal.java +++ b/src/main/java/org/broadinstitute/consent/http/models/elastic_search/ElasticSearchHitsInternal.java @@ -12,7 +12,8 @@ public ElasticSearchHitsInternal(LinkedTreeMap[] hits) { } public LinkedTreeMap[] getHits() { - return Arrays.stream(hits).map(hit -> (LinkedTreeMap) hit.get("_source")) + return Arrays.stream(hits) + .map(hit -> (LinkedTreeMap) hit.get("_source")) .toArray(LinkedTreeMap[]::new); } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/elastic_search/StudyTerm.java b/src/main/java/org/broadinstitute/consent/http/models/elastic_search/StudyTerm.java index 79a60f4f85..32181381eb 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/elastic_search/StudyTerm.java +++ b/src/main/java/org/broadinstitute/consent/http/models/elastic_search/StudyTerm.java @@ -19,7 +19,6 @@ public class StudyTerm { private List dataTypes; private Map assets; - public String getDescription() { return description; } @@ -44,9 +43,13 @@ public void setStudyId(Integer studyId) { this.studyId = studyId; } - public String getPhsId() { return phsId; } + public String getPhsId() { + return phsId; + } - public void setPhsId(String phsId) { this.phsId = phsId; } + public void setPhsId(String phsId) { + this.phsId = phsId; + } public String getPhenotype() { return phenotype; @@ -84,8 +87,7 @@ public Integer getDataSubmitterId() { return dataSubmitterId; } - public void setDataSubmitterId( - Integer dataSubmitterId) { + public void setDataSubmitterId(Integer dataSubmitterId) { this.dataSubmitterId = dataSubmitterId; } diff --git a/src/main/java/org/broadinstitute/consent/http/models/mail/MailMessage.java b/src/main/java/org/broadinstitute/consent/http/models/mail/MailMessage.java index 7293898661..94d6bb09c6 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/mail/MailMessage.java +++ b/src/main/java/org/broadinstitute/consent/http/models/mail/MailMessage.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.models.mail; - import java.util.Date; public class MailMessage { @@ -15,8 +14,15 @@ public class MailMessage { private Integer sendgridStatus; private Date createDate; - public MailMessage(Integer emailId, Integer voteId, Integer dacUserId, String emailType, - Date dateSent, String emailText, String sendgridResponse, Integer sendgridStatus, + public MailMessage( + Integer emailId, + Integer voteId, + Integer dacUserId, + String emailType, + Date dateSent, + String emailText, + String sendgridResponse, + Integer sendgridStatus, Date createDate) { this.emailId = emailId; this.voteId = voteId; @@ -100,6 +106,4 @@ public Date getCreateDate() { public void setCreateDate(Date createDate) { this.createDate = createDate; } - - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseMatchResultType.java b/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseMatchResultType.java index d7d9a4aa7b..a2456be989 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseMatchResultType.java +++ b/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseMatchResultType.java @@ -2,8 +2,8 @@ // Copied from MatchResultPair in consent-ontology public enum DataUseMatchResultType { - APPROVE, // true - DENY, // false + APPROVE, // true + DENY, // false ABSTAIN; public static Boolean Approve(DataUseMatchResultType x) { diff --git a/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseRequestMatchingObject.java b/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseRequestMatchingObject.java index d66b562227..63b1341de1 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseRequestMatchingObject.java +++ b/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseRequestMatchingObject.java @@ -29,5 +29,4 @@ public DataUse getPurpose() { public void setPurpose(DataUse purpose) { this.purpose = purpose; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseResponseMatchingObject.java b/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseResponseMatchingObject.java index 6c40a63230..7269f9badd 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseResponseMatchingObject.java +++ b/src/main/java/org/broadinstitute/consent/http/models/matching/DataUseResponseMatchingObject.java @@ -12,8 +12,10 @@ public class DataUseResponseMatchingObject { public List rationale; - public DataUseResponseMatchingObject(DataUseMatchResultType result, - DataUseRequestMatchingObject matchPair, List rationale) { + public DataUseResponseMatchingObject( + DataUseMatchResultType result, + DataUseRequestMatchingObject matchPair, + List rationale) { this.result = result; this.matchPair = matchPair; this.rationale = rationale; diff --git a/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseSummary.java b/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseSummary.java index 2e2c86a01c..20991bc884 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseSummary.java +++ b/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseSummary.java @@ -7,8 +7,7 @@ public class DataUseSummary { private List primary; private List secondary; - public DataUseSummary() { - } + public DataUseSummary() {} public DataUseSummary(List primary, List secondary) { this.primary = primary; @@ -19,8 +18,7 @@ public List getPrimary() { return primary; } - public void setPrimary( - List primary) { + public void setPrimary(List primary) { this.primary = primary; } @@ -28,8 +26,7 @@ public List getSecondary() { return secondary; } - public void setSecondary( - List secondary) { + public void setSecondary(List secondary) { this.secondary = secondary; } } diff --git a/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseTerm.java b/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseTerm.java index 08a948c43b..4da7fa3d7b 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseTerm.java +++ b/src/main/java/org/broadinstitute/consent/http/models/ontology/DataUseTerm.java @@ -5,8 +5,7 @@ public class DataUseTerm { private String code; private String description; - public DataUseTerm() { - } + public DataUseTerm() {} public DataUseTerm(String code, String description) { this.code = code; diff --git a/src/main/java/org/broadinstitute/consent/http/models/sam/ActionPattern.java b/src/main/java/org/broadinstitute/consent/http/models/sam/ActionPattern.java index 33bfda7083..a61f42b4dc 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/sam/ActionPattern.java +++ b/src/main/java/org/broadinstitute/consent/http/models/sam/ActionPattern.java @@ -2,9 +2,7 @@ import com.google.gson.Gson; -/** - * This represents part of the Sam response to GET /api/config/v1/resourceTypes - */ +/** This represents part of the Sam response to GET /api/config/v1/resourceTypes */ public class ActionPattern { private Boolean authDomainConstrainable; diff --git a/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceType.java b/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceType.java index ce70b322b6..af2cd1a855 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceType.java +++ b/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceType.java @@ -3,9 +3,7 @@ import com.google.gson.Gson; import java.util.List; -/** - * This represents the Sam response to GET /api/config/v1/resourceTypes - */ +/** This represents the Sam response to GET /api/config/v1/resourceTypes */ public class ResourceType { private List actionPatterns; diff --git a/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceTypeRole.java b/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceTypeRole.java index e3292ba3dc..c2904aa8ad 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceTypeRole.java +++ b/src/main/java/org/broadinstitute/consent/http/models/sam/ResourceTypeRole.java @@ -4,9 +4,7 @@ import java.util.List; import java.util.Map; -/** - * This represents part of the Sam response to GET /api/config/v1/resourceTypes - */ +/** This represents part of the Sam response to GET /api/config/v1/resourceTypes */ public class ResourceTypeRole { private List actions; diff --git a/src/main/java/org/broadinstitute/consent/http/models/sam/TosResponse.java b/src/main/java/org/broadinstitute/consent/http/models/sam/TosResponse.java index 69ab72cf0e..15d9af51c3 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/sam/TosResponse.java +++ b/src/main/java/org/broadinstitute/consent/http/models/sam/TosResponse.java @@ -2,12 +2,14 @@ import com.google.gson.Gson; -public record TosResponse(String acceptedOn, Boolean isCurrentVersion, String latestAcceptedVersion, - Boolean permitsSystemUsage) { +public record TosResponse( + String acceptedOn, + Boolean isCurrentVersion, + String latestAcceptedVersion, + Boolean permitsSystemUsage) { @Override public String toString() { return new Gson().toJson(this); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatus.java b/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatus.java index 0d8c98bddd..6e7a691323 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatus.java +++ b/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatus.java @@ -2,9 +2,7 @@ import com.google.gson.Gson; -/** - * This represents the Sam response when a new user is created via POST /register/user/v2/self - */ +/** This represents the Sam response when a new user is created via POST /register/user/v2/self */ public class UserStatus { private UserInfo userInfo; diff --git a/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusDiagnostics.java b/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusDiagnostics.java index ebeadc5336..a0a2236467 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusDiagnostics.java +++ b/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusDiagnostics.java @@ -2,9 +2,7 @@ import com.google.gson.Gson; -/** - * This represents the Sam response to GET /register/user/v2/self/diagnostics - */ +/** This represents the Sam response to GET /register/user/v2/self/diagnostics */ public class UserStatusDiagnostics { private Boolean adminEnabled; diff --git a/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusInfo.java b/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusInfo.java index 5eee15b9d7..5f3f5847db 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusInfo.java +++ b/src/main/java/org/broadinstitute/consent/http/models/sam/UserStatusInfo.java @@ -2,9 +2,7 @@ import com.google.gson.Gson; -/** - * This represents the Sam response to GET /register/user/v2/self/info - */ +/** This represents the Sam response to GET /register/user/v2/self/info */ public class UserStatusInfo { private Boolean adminEnabled; diff --git a/src/main/java/org/broadinstitute/consent/http/models/support/DuosTicket.java b/src/main/java/org/broadinstitute/consent/http/models/support/DuosTicket.java index 7670a9fbeb..963a009d3c 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/support/DuosTicket.java +++ b/src/main/java/org/broadinstitute/consent/http/models/support/DuosTicket.java @@ -7,14 +7,15 @@ /** * Wrapper around org.zendesk.client.v2.model.Ticket to do the following: + * *

*/ public class DuosTicket { @@ -36,5 +37,4 @@ public String toString() { throw new RuntimeException(e); } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/support/TicketFactory.java b/src/main/java/org/broadinstitute/consent/http/models/support/TicketFactory.java index ab3057aa87..253cdd0cc4 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/support/TicketFactory.java +++ b/src/main/java/org/broadinstitute/consent/http/models/support/TicketFactory.java @@ -31,5 +31,4 @@ public static DuosTicket createTicket(TicketFields ticketFields) { Ticket ticket = ticketFields.toTicket(); return new DuosTicket(ticket); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/models/support/TicketFields.java b/src/main/java/org/broadinstitute/consent/http/models/support/TicketFields.java index 50883ba4f4..3289a3f215 100644 --- a/src/main/java/org/broadinstitute/consent/http/models/support/TicketFields.java +++ b/src/main/java/org/broadinstitute/consent/http/models/support/TicketFields.java @@ -6,8 +6,14 @@ import org.zendesk.client.v2.model.CustomFieldValue; import org.zendesk.client.v2.model.Ticket; -public record TicketFields(String name, SupportRequestType type, String email, String subject, - String description, String url, List uploads) { +public record TicketFields( + String name, + SupportRequestType type, + String email, + String subject, + String description, + String url, + List uploads) { private static void validate(boolean condition, String prefix) { if (condition) { @@ -46,11 +52,11 @@ private Comment createComment() { * @return List List of custom fields */ private List createCustomFields() { - return List.of(new CustomFieldValue(360012744452L, new String[]{type.name()}), - new CustomFieldValue(360007369412L, new String[]{description}), - new CustomFieldValue(360012744292L, new String[]{name}), - new CustomFieldValue(360012782111L, new String[]{email}), - new CustomFieldValue(360018545031L, new String[]{email})); + return List.of( + new CustomFieldValue(360012744452L, new String[] {type.name()}), + new CustomFieldValue(360007369412L, new String[] {description}), + new CustomFieldValue(360012744292L, new String[] {name}), + new CustomFieldValue(360012782111L, new String[] {email}), + new CustomFieldValue(360018545031L, new String[] {email})); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java index c8e8f9dad9..8490f33540 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResource.java @@ -32,8 +32,8 @@ public class DACAutomationRuleResource extends Resource { private final UserService userService; @Inject - public DACAutomationRuleResource(DACAutomationRuleService ruleService, DacService dacService, - UserService userService) { + public DACAutomationRuleResource( + DACAutomationRuleService ruleService, DacService dacService, UserService userService) { this.ruleService = ruleService; this.dacService = dacService; this.userService = userService; @@ -77,8 +77,11 @@ public Response getAvailableRules(@Auth AuthUser authUser, @PathParam("dacId") I @Path("{dacId}/rules/audit") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({Resource.ADMIN, Resource.CHAIRPERSON}) - public Response getDacRuleAuditRecords(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId, - @QueryParam("page") Integer page, @QueryParam("pageSize") Integer pageSize) { + public Response getDacRuleAuditRecords( + @Auth AuthUser authUser, + @PathParam("dacId") Integer dacId, + @QueryParam("page") Integer page, + @QueryParam("pageSize") Integer pageSize) { try { User user = userService.findUserByEmail(authUser.getEmail()); validateAdminOrChairForDAC(user, dacId); @@ -99,7 +102,9 @@ public Response getDacRuleAuditRecords(@Auth AuthUser authUser, @PathParam("dacI @Path("{dacId}/rules/{ruleId}/toggle") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({Resource.CHAIRPERSON}) - public Response toggleRule(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId, + public Response toggleRule( + @Auth AuthUser authUser, + @PathParam("dacId") Integer dacId, @PathParam("ruleId") Integer ruleId) { try { User user = userService.findUserByEmail(authUser.getEmail()); @@ -138,7 +143,5 @@ private void validateOffsetAndLimit(Integer offset, Integer limit) { if (limit > 100) { throw new IllegalArgumentException("PageSize must be less than or equal to 100"); } - } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DACUserResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DACUserResource.java index 621a4b125c..128fb1f649 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DACUserResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DACUserResource.java @@ -38,14 +38,14 @@ public Response createDACUser(@Auth AuthUser authUser, @Context UriInfo info, St try { User user = userService.createUser(new User(json)); // Update email preference - getEmailPreferenceValueFromUserJson(json).ifPresent(aBoolean -> - userService.updateEmailPreference(aBoolean, user.getUserId()) - ); + getEmailPreferenceValueFromUserJson(json) + .ifPresent(aBoolean -> userService.updateEmailPreference(aBoolean, user.getUserId())); URI uri = info.getRequestUriBuilder().path("{email}").build(user.getEmail()); return Response.created(uri).entity(user).build(); } catch (Exception e) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())).build(); + .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) + .build(); } } @@ -54,7 +54,7 @@ public Response createDACUser(@Auth AuthUser authUser, @Context UriInfo info, St * * @param json Raw json string from client * @return Optional value of the "emailPreference" boolean value set in either the legacy json or - * the new DacUser model. + * the new DacUser model. */ private Optional getEmailPreferenceValueFromUserJson(String json) { String memberName = "emailPreference"; @@ -68,12 +68,12 @@ private Optional getEmailPreferenceValueFromUserJson(String json) { } else if (userObj.has("roles") && !userObj.get("roles").isJsonNull()) { List rolesElements = new ArrayList<>(); userObj.get("roles").getAsJsonArray().forEach(rolesElements::add); - List emailPrefs = rolesElements. - stream(). - filter(e -> e.getAsJsonObject().has(memberName)). - map(e -> e.getAsJsonObject().get(memberName).getAsBoolean()). - distinct(). - toList(); + List emailPrefs = + rolesElements.stream() + .filter(e -> e.getAsJsonObject().has(memberName)) + .map(e -> e.getAsJsonObject().get(memberName).getAsBoolean()) + .distinct() + .toList(); // In practice, there should only be a single email preference value, if any. if (emailPrefs.size() == 1) { aBoolean = Optional.of(emailPrefs.get(0)); @@ -85,5 +85,4 @@ private Optional getEmailPreferenceValueFromUserJson(String json) { } return aBoolean; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DaaResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DaaResource.java index 58a93d63db..a115da7610 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DaaResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DaaResource.java @@ -49,7 +49,10 @@ public class DaaResource extends Resource implements ConsentLogger { private final LibraryCardService libraryCardService; @Inject - public DaaResource(DaaService daaService, DacService dacService, UserService userService, + public DaaResource( + DaaService daaService, + DacService dacService, + UserService userService, LibraryCardService libraryCardService) { this.daaService = daaService; this.dacService = dacService; @@ -81,12 +84,13 @@ public Response createDaaForDac( return Response.status(Status.FORBIDDEN).build(); } } - DataAccessAgreement daa = daaService.createDaaWithFso(user.getUserId(), dacId, - uploadInputStream, fileDetail); - URI uri = info.getBaseUriBuilder() - // This will be the GET endpoint for the created DAA - .replacePath("api/daa/{daaId}") - .build(daa.getDaaId()); + DataAccessAgreement daa = + daaService.createDaaWithFso(user.getUserId(), dacId, uploadInputStream, fileDetail); + URI uri = + info.getBaseUriBuilder() + // This will be the GET endpoint for the created DAA + .replacePath("api/daa/{daaId}") + .build(daa.getDaaId()); return Response.created(uri).entity(daa).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -110,18 +114,22 @@ public Response createLibraryCardDaaRelation( // Assert that the user has the correct institution permissions to add a DAA-LC relationship. // Admins can add a DAA with any DAC, but signing officials can only create relationships for // library cards associated with the same institution they are associated with. - if (!authedUser.hasUserRole(UserRoles.ADMIN) && !authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL)) { + if (!authedUser.hasUserRole(UserRoles.ADMIN) + && !authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL)) { + return Response.status(Status.FORBIDDEN).build(); + } else if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) + && authedUserInstitutionId != userInstitutionId) { return Response.status(Status.FORBIDDEN).build(); - } else if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) && authedUserInstitutionId != userInstitutionId) { - return Response.status(Status.FORBIDDEN).build(); } - LibraryCard libraryCard = user.getLibraryCard() == null ? - libraryCardService.createLibraryCardForSigningOfficial(user, authedUser) : - user.getLibraryCard(); + LibraryCard libraryCard = + user.getLibraryCard() == null + ? libraryCardService.createLibraryCardForSigningOfficial(user, authedUser) + : user.getLibraryCard(); libraryCardService.addDaaToLibraryCard(libraryCard.getId(), daaId); - URI uri = info.getBaseUriBuilder() - .replacePath("api/libraryCards/{libraryCardId}") - .build(libraryCard.getId()); + URI uri = + info.getBaseUriBuilder() + .replacePath("api/libraryCards/{libraryCardId}") + .build(libraryCard.getId()); return Response.ok().location(uri).entity(libraryCard).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -144,9 +152,7 @@ public Response findAll(@Auth DuosUser duosUser) { @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, MEMBER, CHAIRPERSON, RESEARCHER}) @Path("{daaId}") - public Response findDaaById( - @Auth AuthUser authUser, - @PathParam("daaId") Integer daaId) { + public Response findDaaById(@Auth AuthUser authUser, @PathParam("daaId") Integer daaId) { try { DataAccessAgreement daa = daaService.findById(daaId); return Response.ok(daa).build(); @@ -159,8 +165,7 @@ public Response findDaaById( @PermitAll @Path("{daaId}/file") @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) - public Response findFileById(@Auth DuosUser duosUser, - @PathParam("daaId") Integer daaId) { + public Response findFileById(@Auth DuosUser duosUser, @PathParam("daaId") Integer daaId) { try { InputStream daa = daaService.findFileById(daaId); StreamingOutput stream = createStreamingOutput(daa); @@ -196,9 +201,7 @@ public Response deleteDaaForUser( @Path("{daaId}") @Produces("application/json") @RolesAllowed({ADMIN}) - public Response adminDeleteDaa( - @Auth AuthUser authUser, - @PathParam("daaId") Integer daaId) { + public Response adminDeleteDaa(@Auth AuthUser authUser, @PathParam("daaId") Integer daaId) { try { daaService.findById(daaId); User user = userService.findUserByEmail(authUser.getEmail()); @@ -213,18 +216,20 @@ public Response adminDeleteDaa( @PermitAll @Path("/request/{daaId}") public Response sendDaaRequestMessage( - @Auth DuosUser duosUser, - @PathParam("daaId") Integer daaId) { + @Auth DuosUser duosUser, @PathParam("daaId") Integer daaId) { try { User user = duosUser.getUser(); if (user.getInstitutionId() == null) { - throw new BadRequestException("This user has not set their institution: " + user.getDisplayName()); + throw new BadRequestException( + "This user has not set their institution: " + user.getDisplayName()); } if (user.getLibraryCard() == null) { - throw new BadRequestException("This user does not have a library card: " + user.getDisplayName()); + throw new BadRequestException( + "This user does not have a library card: " + user.getDisplayName()); } if (user.getLibraryCard().getDaaIds().contains(daaId)) { - throw new IllegalArgumentException("User already has this DAA associated with their Library Card"); + throw new IllegalArgumentException( + "User already has this DAA associated with their Library Card"); } daaService.sendDaaRequestEmails(user, daaId); return Response.ok().build(); @@ -238,13 +243,12 @@ public Response sendDaaRequestMessage( @RolesAllowed({ADMIN, SIGNINGOFFICIAL}) @Path("/bulk/{daaId}") public Response bulkAddUsersToDaa( - @Auth AuthUser authUser, - @PathParam("daaId") Integer daaId, - String json) { + @Auth AuthUser authUser, @PathParam("daaId") Integer daaId, String json) { try { User authedUser = userService.findUserByEmail(authUser.getEmail()); List users = userService.findUsersInJsonArray(json, "users"); - if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) && !authedUser.hasUserRole(UserRoles.ADMIN)) { + if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) + && !authedUser.hasUserRole(UserRoles.ADMIN)) { for (User user : users) { if (!Objects.equals(authedUser.getInstitutionId(), user.getInstitutionId())) { return Response.status(Status.FORBIDDEN).build(); @@ -266,13 +270,12 @@ public Response bulkAddUsersToDaa( @RolesAllowed({ADMIN, SIGNINGOFFICIAL}) @Path("/bulk/{daaId}") public Response bulkRemoveUsersFromDaa( - @Auth AuthUser authUser, - @PathParam("daaId") Integer daaId, - String json) { + @Auth AuthUser authUser, @PathParam("daaId") Integer daaId, String json) { try { User authedUser = userService.findUserByEmail(authUser.getEmail()); List users = userService.findUsersInJsonArray(json, "users"); - if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) && !authedUser.hasUserRole(UserRoles.ADMIN)) { + if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) + && !authedUser.hasUserRole(UserRoles.ADMIN)) { for (User user : users) { if (!Objects.equals(authedUser.getInstitutionId(), user.getInstitutionId())) { return Response.status(Status.FORBIDDEN).build(); @@ -294,13 +297,12 @@ public Response bulkRemoveUsersFromDaa( @RolesAllowed({ADMIN, SIGNINGOFFICIAL}) @Path("/bulk/user/{userId}") public Response bulkAddDAAsToUser( - @Auth AuthUser authUser, - @PathParam("userId") Integer userId, - String json) { + @Auth AuthUser authUser, @PathParam("userId") Integer userId, String json) { try { User authedUser = userService.findUserByEmail(authUser.getEmail()); User user = userService.findUserById(userId); - if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) && !Objects.equals(authedUser.getInstitutionId(), user.getInstitutionId())) { + if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) + && !Objects.equals(authedUser.getInstitutionId(), user.getInstitutionId())) { return Response.status(Status.FORBIDDEN).build(); } List daaList = daaService.findDAAsInJsonArray(json, "daaList"); @@ -318,13 +320,12 @@ public Response bulkAddDAAsToUser( @RolesAllowed({ADMIN, SIGNINGOFFICIAL}) @Path("/bulk/user/{userId}") public Response bulkRemoveDAAsFromUser( - @Auth AuthUser authUser, - @PathParam("userId") Integer userId, - String json) { + @Auth AuthUser authUser, @PathParam("userId") Integer userId, String json) { try { User authedUser = userService.findUserByEmail(authUser.getEmail()); User user = userService.findUserById(userId); - if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) && !Objects.equals(authedUser.getInstitutionId(), user.getInstitutionId())) { + if (authedUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) + && !Objects.equals(authedUser.getInstitutionId(), user.getInstitutionId())) { return Response.status(Status.FORBIDDEN).build(); } List daaList = daaService.findDAAsInJsonArray(json, "daaList"); @@ -348,12 +349,13 @@ public Response modifyDacDaaRelationship( try { dacService.findById(dacId); User user = userService.findUserByEmail(authUser.getEmail()); - // Assert that the user has the correct DAC permissions to add a DAC to a DAA for the provided DacId. - // Admins can add a DAC to a DAA with any DAC, but chairpersons can only add DACs to DAAs for DACs they are a + // Assert that the user has the correct DAC permissions to add a DAC to a DAA for the provided + // DacId. + // Admins can add a DAC to a DAA with any DAC, but chairpersons can only add DACs to DAAs for + // DACs they are a // chairperson for. if (!user.hasUserRole(UserRoles.ADMIN)) { - if (user.getRoles() - .stream() + if (user.getRoles().stream() .filter(r -> r.getRoleId().equals(UserRoles.Chairperson().getRoleId())) .map(UserRole::getDacId) .noneMatch(dacId::equals)) { @@ -363,12 +365,11 @@ public Response modifyDacDaaRelationship( DataAccessAgreement daa = daaService.findById(daaId); Optional matchingDac = Optional.empty(); if (daa.getDacs() != null) { - matchingDac = daa.getDacs().stream() - .filter(dac -> Objects.equals(dac.getDacId(), dacId)) - .findFirst(); + matchingDac = + daa.getDacs().stream().filter(dac -> Objects.equals(dac.getDacId(), dacId)).findFirst(); } if (matchingDac.isEmpty()) { - daaService.addDacToDaa(dacId,daaId); + daaService.addDacToDaa(dacId, daaId); } DataAccessAgreement updatedDaa = daaService.findById(daaId); return Response.ok().entity(updatedDaa).build(); @@ -388,17 +389,18 @@ public Response removeDacDaaRelationship( try { dacService.findById(dacId); User user = userService.findUserByEmail(authUser.getEmail()); - // Assert that the user has the correct DAC permissions to add a DAC to a DAA for the provided DacId. - // Admins can add a DAC to a DAA with any DAC, but chairpersons can only add DACs to DAAs for DACs they are a + // Assert that the user has the correct DAC permissions to add a DAC to a DAA for the provided + // DacId. + // Admins can add a DAC to a DAA with any DAC, but chairpersons can only add DACs to DAAs for + // DACs they are a // chairperson for. if (!user.hasUserRole(UserRoles.ADMIN)) { - List matchedChairpersonDacIds = user - .getRoles() - .stream() - .filter(r -> r.getRoleId().equals(UserRoles.Chairperson().getRoleId())) - .map(UserRole::getDacId) - .filter(id -> Objects.equals(id, dacId)) - .toList(); + List matchedChairpersonDacIds = + user.getRoles().stream() + .filter(r -> r.getRoleId().equals(UserRoles.Chairperson().getRoleId())) + .map(UserRole::getDacId) + .filter(id -> Objects.equals(id, dacId)) + .toList(); if (matchedChairpersonDacIds.isEmpty()) { return Response.status(Status.FORBIDDEN).build(); } @@ -406,9 +408,8 @@ public Response removeDacDaaRelationship( DataAccessAgreement daa = daaService.findById(daaId); Optional matchingDac = Optional.empty(); if (daa.getDacs() != null) { - matchingDac = daa.getDacs().stream() - .filter(dac -> Objects.equals(dac.getDacId(), dacId)) - .findFirst(); + matchingDac = + daa.getDacs().stream().filter(dac -> Objects.equals(dac.getDacId(), dacId)).findFirst(); } if (matchingDac.isEmpty()) { throw new BadRequestException("The given DAC is not associated with the provided DAA."); @@ -429,8 +430,7 @@ public Response sendNewDaaMessage( @Auth AuthUser authUser, @PathParam("dacId") Integer dacId, @PathParam("oldDaaId") Integer oldDaaId, - @PathParam("newDaaName") String newDaaName - ) { + @PathParam("newDaaName") String newDaaName) { try { daaService.findById(oldDaaId); User user = userService.findUserByEmail(authUser.getEmail()); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java index 71e5a746b5..7ab9d93698 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DacResource.java @@ -41,7 +41,8 @@ public class DacResource extends Resource { private final DatasetService datasetService; @Inject - public DacResource(DacService dacService, UserService userService, DatasetService datasetService) { + public DacResource( + DacService dacService, UserService userService, DatasetService datasetService) { this.dacService = dacService; this.userService = userService; this.datasetService = datasetService; @@ -50,8 +51,8 @@ public DacResource(DacService dacService, UserService userService, DatasetServic @GET @Produces("application/json") @RolesAllowed({ADMIN, MEMBER, CHAIRPERSON, RESEARCHER}) - public Response findAll(@Auth AuthUser authUser, - @QueryParam("withUsers") Optional withUsers) { + public Response findAll( + @Auth AuthUser authUser, @QueryParam("withUsers") Optional withUsers) { try { final Boolean includeUsers = withUsers.orElse(true); List dacs = dacService.findDacsWithMembersOption(includeUsers); @@ -83,8 +84,12 @@ public Response createDac(@Auth AuthUser authUser, String json) { dacId = dacService.createDac(dac.getName(), dac.getDescription(), dac.getEmail()); } if (dacId == null) { - throw new ServerErrorException("Unable to create DAC with name: " + dac.getName() + " and description: " - + dac.getDescription(), HttpStatusCodes.STATUS_CODE_SERVER_ERROR); + throw new ServerErrorException( + "Unable to create DAC with name: " + + dac.getName() + + " and description: " + + dac.getDescription(), + HttpStatusCodes.STATUS_CODE_SERVER_ERROR); } Dac savedDac = dacService.findById(dacId); return Response.ok().entity(unmarshal(savedDac)).build(); @@ -162,7 +167,9 @@ public Response deleteDac(@Auth AuthUser authUser, @PathParam("dacId") Integer d @POST @Path("{dacId}/member/{userId}") @RolesAllowed({ADMIN, CHAIRPERSON}) - public Response addDacMember(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId, + public Response addDacMember( + @Auth AuthUser authUser, + @PathParam("dacId") Integer dacId, @PathParam("userId") Integer userId) { try { checkUserExistsInDac(dacId, userId); @@ -180,7 +187,9 @@ public Response addDacMember(@Auth AuthUser authUser, @PathParam("dacId") Intege @DELETE @Path("{dacId}/member/{userId}") @RolesAllowed({ADMIN, CHAIRPERSON}) - public Response removeDacMember(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId, + public Response removeDacMember( + @Auth AuthUser authUser, + @PathParam("dacId") Integer dacId, @PathParam("userId") Integer userId) { try { Role role = dacService.getMemberRole(); @@ -198,7 +207,9 @@ public Response removeDacMember(@Auth AuthUser authUser, @PathParam("dacId") Int @POST @Path("{dacId}/chair/{userId}") @RolesAllowed({ADMIN, CHAIRPERSON}) - public Response addDacChair(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId, + public Response addDacChair( + @Auth AuthUser authUser, + @PathParam("dacId") Integer dacId, @PathParam("userId") Integer userId) { try { checkUserExistsInDac(dacId, userId); @@ -216,7 +227,9 @@ public Response addDacChair(@Auth AuthUser authUser, @PathParam("dacId") Integer @DELETE @Path("{dacId}/chair/{userId}") @RolesAllowed({ADMIN, CHAIRPERSON}) - public Response removeDacChair(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId, + public Response removeDacChair( + @Auth AuthUser authUser, + @PathParam("dacId") Integer dacId, @PathParam("userId") Integer userId) { try { Role role = dacService.getChairpersonRole(); @@ -264,13 +277,16 @@ public Response filterUsers(@Auth AuthUser authUser, @PathParam("term") String t @Produces("application/json") @Path("{dacId}/dataset/{datasetId}") @RolesAllowed({CHAIRPERSON}) - public Response approveDataset(@Auth AuthUser authUser, @PathParam("dacId") Integer dacId, - @PathParam("datasetId") Integer datasetId, String json) { + public Response approveDataset( + @Auth AuthUser authUser, + @PathParam("dacId") Integer dacId, + @PathParam("datasetId") Integer datasetId, + String json) { try { User user = userService.findUserByEmail(authUser.getEmail()); Dataset dataset = datasetService.findDatasetWithoutFSOInformation(datasetId); if (Objects.isNull(dataset) || !Objects.equals(dataset.getDacId(), dacId)) { - //Vague message is intentional, don't want to reveal too much info + // Vague message is intentional, don't want to reveal too much info throw new NotFoundException("Dataset not found"); } boolean userHasRole = user.verifyDACRole(UserRoles.CHAIRPERSON.getRoleName(), dacId); @@ -309,20 +325,17 @@ private Dac findDacOrThrow(Integer dacId) { } /** - * Validate that a user is not already a member of a DAC. If they are, throw a conflict - * exception. + * Validate that a user is not already a member of a DAC. If they are, throw a conflict exception. * - * @param dacId The DAC Id + * @param dacId The DAC Id * @param userId The User Id * @throws UnsupportedOperationException Conflicts */ private void checkUserExistsInDac(Integer dacId, Integer userId) throws UnsupportedOperationException { List currentMembers = dacService.findMembersByDacId(dacId); - Optional isMember = currentMembers. - stream(). - filter(u -> u.getUserId().equals(userId)). - findFirst(); + Optional isMember = + currentMembers.stream().filter(u -> u.getUserId().equals(userId)).findFirst(); if (isMember.isPresent()) { // This is handled as a 409 Conflict throw new UnsupportedOperationException( @@ -334,7 +347,7 @@ private void checkUserExistsInDac(Integer dacId, Integer userId) * - Admins can make any modifications to any Dac chairs or members - Chairpersons can only make * modifications to chairs and members in a DAC that they are a chairperson in. * - * @param dac The Dac + * @param dac The Dac * @param authUser The AuthUser * @throws NotAuthorizedException Not authorized */ @@ -350,9 +363,10 @@ private void checkUserRoleInDac(Dac dac, AuthUser authUser) throws NotAuthorized throw e; } - Optional chair = dac.getChairpersons().stream() - .filter(u -> u.getUserId().equals(user.getUserId())) - .findFirst(); + Optional chair = + dac.getChairpersons().stream() + .filter(u -> u.getUserId().equals(user.getUserId())) + .findFirst(); if (chair.isEmpty()) { throw e; } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DarCollectionResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DarCollectionResource.java index 0e0f9d6f5d..1205c9c18a 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DarCollectionResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DarCollectionResource.java @@ -23,10 +23,10 @@ import java.util.Objects; import org.broadinstitute.consent.http.enumeration.DarStatus; import org.broadinstitute.consent.http.enumeration.UserRoles; -import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.DarCollection; import org.broadinstitute.consent.http.models.DarCollectionSummary; import org.broadinstitute.consent.http.models.Dataset; +import org.broadinstitute.consent.http.models.DuosUser; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.service.DarCollectionService; import org.broadinstitute.consent.http.util.ComplianceLogger; @@ -48,46 +48,52 @@ public DarCollectionResource(DarCollectionService darCollectionService) { @Produces("application/json") @RolesAllowed({ADMIN, CHAIRPERSON, MEMBER, SIGNINGOFFICIAL, RESEARCHER}) @Timed - public Response getCollectionSummariesForUserByRole(@Auth DuosUser duosUser, - @PathParam("roleName") String roleName) { + public Response getCollectionSummariesForUserByRole( + @Auth DuosUser duosUser, @PathParam("roleName") String roleName) { try { User user = duosUser.getUser(); var role = validateUserHasRoleName(user, roleName); List summaries = darCollectionService.getSummariesForRole(user, role); // When querying in list context, we only want the exposed fields - Gson gson = GsonUtil.gsonBuilderWithAdapters().excludeFieldsWithoutExposeAnnotation().create(); + Gson gson = + GsonUtil.gsonBuilderWithAdapters().excludeFieldsWithoutExposeAnnotation().create(); return Response.ok().entity(gson.toJson(summaries)).build(); } catch (Exception e) { return createExceptionResponse(e); } } - @GET @Path("role/{roleName}/summary/{collectionId}") @Produces("application/json") @RolesAllowed({ADMIN, CHAIRPERSON, MEMBER, SIGNINGOFFICIAL, RESEARCHER}) - public Response getCollectionSummaryForRoleById(@Auth DuosUser duosUser, - @PathParam("roleName") String roleName, @PathParam("collectionId") Integer collectionId) { + public Response getCollectionSummaryForRoleById( + @Auth DuosUser duosUser, + @PathParam("roleName") String roleName, + @PathParam("collectionId") Integer collectionId) { try { User user = duosUser.getUser(); // throws BadRequestException if user does not have roleName var role = validateUserHasRoleName(user, roleName); - DarCollectionSummary summary = darCollectionService.getSummaryForRoleByCollectionId(user, role, collectionId); + DarCollectionSummary summary = + darCollectionService.getSummaryForRoleByCollectionId(user, role, collectionId); - boolean allowedAccess = switch (role) { - case ADMIN -> true; - case CHAIRPERSON, MEMBER -> { - List userDatasetIds = darCollectionService.findDatasetIdsByDACUser(user); - yield summary.getDatasetIds().stream().anyMatch(userDatasetIds::contains); - } - case SIGNINGOFFICIAL -> Objects.nonNull(user.getInstitutionId()) && - user.getInstitutionId().equals(summary.getInstitutionId()); - case RESEARCHER -> user.getUserId().equals(summary.getResearcherId()); - default -> throw new BadRequestException("Invalid role selection: " + roleName); - }; + boolean allowedAccess = + switch (role) { + case ADMIN -> true; + case CHAIRPERSON, MEMBER -> { + List userDatasetIds = darCollectionService.findDatasetIdsByDACUser(user); + yield summary.getDatasetIds().stream().anyMatch(userDatasetIds::contains); + } + case SIGNINGOFFICIAL -> + Objects.nonNull(user.getInstitutionId()) + && user.getInstitutionId().equals(summary.getInstitutionId()); + case RESEARCHER -> user.getUserId().equals(summary.getResearcherId()); + default -> throw new BadRequestException("Invalid role selection: " + roleName); + }; if (!allowedAccess) { - // user has role but is not allowed to view collection; throw NotFoundException to avoid leaking existence + // user has role but is not allowed to view collection; throw NotFoundException to avoid + // leaking existence throw new NotFoundException( "Collection with the collection id of " + collectionId + " was not found"); } @@ -103,13 +109,13 @@ public Response getCollectionSummaryForRoleById(@Auth DuosUser duosUser, @Produces("application/json") @PermitAll public Response getCollectionById( - @Auth DuosUser duosUser, - @PathParam("collectionId") Integer collectionId) { + @Auth DuosUser duosUser, @PathParam("collectionId") Integer collectionId) { try { User user = duosUser.getUser(); DarCollection collection = darCollectionService.getByCollectionId(user, collectionId); - if (user.hasUserRole(UserRoles.ADMIN) || checkSoPermissionsForCollection(user, collection) + if (user.hasUserRole(UserRoles.ADMIN) + || checkSoPermissionsForCollection(user, collection) || checkDacPermissionsForCollection(user, collection)) { return Response.ok().entity(collection).build(); } @@ -126,17 +132,21 @@ public Response getCollectionById( @Produces("application/json") @RolesAllowed({ADMIN, CHAIRPERSON, MEMBER}) public Response getCollectionWithAllElectionsByCollectionId( - @Auth DuosUser duosUser, - @PathParam("collectionId") Integer collectionId) { + @Auth DuosUser duosUser, @PathParam("collectionId") Integer collectionId) { try { if (duosUser.getUser().hasUserRole(UserRoles.ADMIN)) { - DarCollection collection = darCollectionService.getCollectionWithAllElectionsByCollectionId(duosUser.getUser(), collectionId); + DarCollection collection = + darCollectionService.getCollectionWithAllElectionsByCollectionId( + duosUser.getUser(), collectionId); return Response.ok().entity(collection).build(); } // if user is only a member or chair, get the list of datasets they have access to // this will be used to filter the collection's elections - List userDatasetIds = darCollectionService.findDatasetIdsByDACUser(duosUser.getUser()); - DarCollection collection = darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds(duosUser.getUser(), userDatasetIds, collectionId); + List userDatasetIds = + darCollectionService.findDatasetIdsByDACUser(duosUser.getUser()); + DarCollection collection = + darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds( + duosUser.getUser(), userDatasetIds, collectionId); if (!checkDacPermissionsForCollection(duosUser.getUser(), collection)) { throw new NotFoundException(); } @@ -157,8 +167,9 @@ private boolean checkDacPermissionsForCollection(User user, DarCollection collec private boolean checkSoPermissionsForCollection(User user, DarCollection collection) { Integer creatorInstitutionId = collection.getCreateUser().getInstitutionId(); - boolean institutionsMatch = Objects.nonNull(creatorInstitutionId) - && creatorInstitutionId.equals(user.getInstitutionId()); + boolean institutionsMatch = + Objects.nonNull(creatorInstitutionId) + && creatorInstitutionId.equals(user.getInstitutionId()); return user.hasUserRole(UserRoles.SIGNINGOFFICIAL) && institutionsMatch; } @@ -168,8 +179,7 @@ private boolean checkSoPermissionsForCollection(User user, DarCollection collect @Produces("application/json") @PermitAll public Response getCollectionByReferenceId( - @Auth DuosUser duosUser, - @PathParam("referenceId") String referenceId) { + @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId) { try { User user = duosUser.getUser(); DarCollection collection = darCollectionService.getByReferenceId(user, referenceId); @@ -200,9 +210,13 @@ public Response cancelDarCollectionByCollectionId( actingRole = validateUserHasRoleName(user, roleName); } - DarCollection cancelledCollection = darCollectionService.cancelDarCollectionByRole(user, collection, actingRole); - ComplianceLogger.logDARCancellation(user, cancelledCollection.getDatasets().stream().toList(), - (ContainerRequest) request, Response.Status.OK.getStatusCode()); + DarCollection cancelledCollection = + darCollectionService.cancelDarCollectionByRole(user, collection, actingRole); + ComplianceLogger.logDARCancellation( + user, + cancelledCollection.getDatasets().stream().toList(), + (ContainerRequest) request, + Response.Status.OK.getStatusCode()); return Response.ok().entity(cancelledCollection).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -213,16 +227,16 @@ public Response cancelDarCollectionByCollectionId( @Path("{id}/resubmit") @Produces("application/json") @RolesAllowed(RESEARCHER) - public Response resubmitDarCollection(@Auth DuosUser duosUser, - @PathParam("id") Integer collectionId) { + public Response resubmitDarCollection( + @Auth DuosUser duosUser, @PathParam("id") Integer collectionId) { try { User user = duosUser.getUser(); DarCollection sourceCollection = darCollectionService.getByCollectionId(user, collectionId); isCollectionPresent(sourceCollection); validateUserIsCreator(user, sourceCollection); validateCollectionIsCanceled(sourceCollection); - DarCollectionSummary draftDar = darCollectionService.updateCollectionToDraftStatus( - sourceCollection); + DarCollectionSummary draftDar = + darCollectionService.updateCollectionToDraftStatus(sourceCollection); return Response.ok().entity(draftDar).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -234,14 +248,13 @@ public Response resubmitDarCollection(@Auth DuosUser duosUser, @Consumes("application/json") @RolesAllowed({ADMIN, CHAIRPERSON}) public Response createElectionsForCollection( - @Auth DuosUser duosUser, - @PathParam("collectionId") Integer collectionId) { + @Auth DuosUser duosUser, @PathParam("collectionId") Integer collectionId) { try { User user = duosUser.getUser(); DarCollection sourceCollection = darCollectionService.getByCollectionId(user, collectionId); isCollectionPresent(sourceCollection); - DarCollection updatedCollection = darCollectionService.createElectionsForDarCollection(user, - sourceCollection); + DarCollection updatedCollection = + darCollectionService.createElectionsForDarCollection(user, sourceCollection); return Response.ok(updatedCollection).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -251,8 +264,7 @@ public Response createElectionsForCollection( private void validateCollectionIsCanceled(DarCollection collection) { boolean isCanceled = collection.getDars().values().stream() - .anyMatch( - d -> d.getData().getStatus().equalsIgnoreCase(DarStatus.CANCELED.getValue())); + .anyMatch(d -> d.getData().getStatus().equalsIgnoreCase(DarStatus.CANCELED.getValue())); if (!isCanceled) { throw new BadRequestException(); } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java index 42af5de066..0ed29c4c47 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DataAccessRequestResource.java @@ -78,8 +78,7 @@ public DataAccessRequestResource( UserService userService, DatasetService datasetService, MatchService matchService, - DarCollectionService darCollectionService - ) { + DarCollectionService darCollectionService) { this.daaService = daaService; this.dataAccessRequestService = dataAccessRequestService; this.gcsService = gcsService; @@ -109,20 +108,20 @@ public Response getDataAccessRequests(@Auth DuosUser duosUser) { @RolesAllowed(RESEARCHER) @Path("/v2") public Response createDataAccessRequest( - @Auth AuthUser authUser, - @Context Request request, - @Context UriInfo info, - String dar) { + @Auth AuthUser authUser, @Context Request request, @Context UriInfo info, String dar) { try { User user = findUserByEmail(authUser.getEmail()); DataAccessRequest payload = populateDarFromJsonString(user, dar); - DataAccessRequest newDar = dataAccessRequestService.createDataAccessRequest(user, payload, (ContainerRequest) request); + DataAccessRequest newDar = + dataAccessRequestService.createDataAccessRequest( + user, payload, (ContainerRequest) request); sendNewDarCollectionMessage(newDar.getCollectionId()); URI uri = info.getRequestUriBuilder().build(); matchService.reprocessMatchesForPurpose(newDar.getReferenceId()); List datasets = datasetService.findDatasetsByIds(user, newDar.getDatasetIds()); - ComplianceLogger.logDARSubmission(user, datasets, ((ContainerRequest) request), HttpStatusCodes.STATUS_CODE_CREATED); + ComplianceLogger.logDARSubmission( + user, datasets, ((ContainerRequest) request), HttpStatusCodes.STATUS_CODE_CREATED); return Response.created(uri).entity(newDar.convertToSimplifiedDar()).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -135,20 +134,21 @@ public Response createDataAccessRequest( @RolesAllowed(RESEARCHER) @Path("/v3") public Response createDataAccessRequestWithDAARestrictions( - @Auth AuthUser authUser, - @Context Request request, - @Context UriInfo info, String dar) { + @Auth AuthUser authUser, @Context Request request, @Context UriInfo info, String dar) { try { User user = findUserByEmail(authUser.getEmail()); DataAccessRequest payload = populateDarFromJsonString(user, dar); // DAA Enforcement datasetService.enforceDAARestrictions(user, payload.getDatasetIds()); - DataAccessRequest newDar = dataAccessRequestService.createDataAccessRequest(user, payload, (ContainerRequest) request); + DataAccessRequest newDar = + dataAccessRequestService.createDataAccessRequest( + user, payload, (ContainerRequest) request); sendNewDarCollectionMessage(newDar.getCollectionId()); URI uri = info.getRequestUriBuilder().build(); matchService.reprocessMatchesForPurpose(newDar.getReferenceId()); List datasets = datasetService.findDatasetsByIds(user, newDar.getDatasetIds()); - ComplianceLogger.logDARSubmission(user, datasets, ((ContainerRequest) request), HttpStatusCodes.STATUS_CODE_CREATED); + ComplianceLogger.logDARSubmission( + user, datasets, ((ContainerRequest) request), HttpStatusCodes.STATUS_CODE_CREATED); return Response.created(uri).entity(newDar.convertToSimplifiedDar()).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -162,9 +162,10 @@ public Response createDataAccessRequestWithDAARestrictions( public Response getByReferenceId( @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId) { validateAuthedRoleUser( - List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER, - UserRoles.SIGNINGOFFICIAL), - duosUser, referenceId); + List.of( + UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER, UserRoles.SIGNINGOFFICIAL), + duosUser, + referenceId); try { DataAccessRequest dar = dataAccessRequestService.findByReferenceId(referenceId); if (Objects.nonNull(dar)) { @@ -189,8 +190,7 @@ public Response getDAAsByReferenceId( @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId) { try { validateAuthedRoleUser( - List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER), - duosUser, referenceId); + List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER), duosUser, referenceId); List dataAccessAgreements = daaService.findByDarReferenceId(referenceId); return Response.status(Response.Status.OK).entity(dataAccessAgreements).build(); } catch (Exception e) { @@ -229,8 +229,8 @@ public Response updateByReferenceId( public Response getDraftDataAccessRequests(@Auth AuthUser authUser) { try { User user = findUserByEmail(authUser.getEmail()); - List draftDars = dataAccessRequestService.findAllDraftDataAccessRequestsByUser( - user.getUserId()); + List draftDars = + dataAccessRequestService.findAllDraftDataAccessRequestsByUser(user.getUserId()); return Response.ok().entity(draftDars).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -351,17 +351,14 @@ public Response updatePartialDataAccessRequestWithDAARestrictions( @Path("/v2/{referenceId}/irbDocument") @RolesAllowed({ADMIN, CHAIRPERSON, MEMBER, RESEARCHER}) public Response getIrbDocument( - @Auth DuosUser duosUser, - @PathParam("referenceId") String referenceId) { + @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId) { try { DataAccessRequest dar = getDarById(referenceId); validateAuthedRoleUser( - List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER), - duosUser, referenceId); - if (dar.getData() != null && - StringUtils.isNotEmpty(dar.getData().getIrbDocumentLocation()) && - StringUtils.isNotEmpty(dar.getData().getIrbDocumentName()) - ) { + List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER), duosUser, referenceId); + if (dar.getData() != null + && StringUtils.isNotEmpty(dar.getData().getIrbDocumentLocation()) + && StringUtils.isNotEmpty(dar.getData().getIrbDocumentName())) { String blobIdName = dar.getData().getIrbDocumentLocation(); String fileName = dar.getData().getIrbDocumentName(); InputStream is = gcsService.getDocument(blobIdName); @@ -390,8 +387,9 @@ public Response uploadIrbDocument( User user = findUserByEmail(authUser.getEmail()); DataAccessRequest dar = getDarById(referenceId); checkAuthorizedUpdateUser(user, dar); - DataAccessRequest updatedDar = updateDarWithDocumentContents(DarDocumentType.IRB, user, dar, - uploadInputStream, fileDetail); + DataAccessRequest updatedDar = + updateDarWithDocumentContents( + DarDocumentType.IRB, user, dar, uploadInputStream, fileDetail); return Response.ok(updatedDar.convertToSimplifiedDar()).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -401,15 +399,17 @@ public Response uploadIrbDocument( @PUT @RolesAllowed({SIGNINGOFFICIAL}) @Path("/{referenceId}/approveCloseout") - public Response approveCloseout(@Auth DuosUser duosUser, + public Response approveCloseout( + @Auth DuosUser duosUser, @Context Request request, @PathParam("referenceId") String referenceId) { try { dataAccessRequestService.approveDataAccessRequestCloseout(duosUser.getUser(), referenceId); DataAccessRequest dar = getDarById(referenceId); - List datasets = datasetService.findDatasetsByIds(duosUser.getUser(), dar.getDatasetIds()); - ComplianceLogger.logCloseoutApprovalBySigningOfficial(duosUser.getUser(), datasets, - (ContainerRequest) request, HttpStatusCodes.STATUS_CODE_OK); + List datasets = + datasetService.findDatasetsByIds(duosUser.getUser(), dar.getDatasetIds()); + ComplianceLogger.logCloseoutApprovalBySigningOfficial( + duosUser.getUser(), datasets, (ContainerRequest) request, HttpStatusCodes.STATUS_CODE_OK); return Response.ok().build(); } catch (Exception e) { return createExceptionResponse(e); @@ -442,24 +442,40 @@ public Response postProgressReport( throw new ForbiddenException("User not authorized to update this Data Access Request"); } // Prevent creation if there are open DataAccess elections for the parent DAR - List openElections = dataAccessRequestService.findOpenElectionsByReferenceId(parentDar.getReferenceId()); - boolean hasOpenDataAccessElections = openElections - .stream() - .anyMatch(election -> election.getElectionType().equalsIgnoreCase(ElectionType.DATA_ACCESS.getValue())); + List openElections = + dataAccessRequestService.findOpenElectionsByReferenceId(parentDar.getReferenceId()); + boolean hasOpenDataAccessElections = + openElections.stream() + .anyMatch( + election -> + election + .getElectionType() + .equalsIgnoreCase(ElectionType.DATA_ACCESS.getValue())); if (hasOpenDataAccessElections) { - throw new BadRequestException("Cannot create a progress report for a DAR with an open election: " + parentDar.getReferenceId()); + throw new BadRequestException( + "Cannot create a progress report for a DAR with an open election: " + + parentDar.getReferenceId()); } - DataAccessRequest payload = DataAccessRequest.populateProgressReportFromJsonString(dar, parentDar); - populateProgressReportWithDocuments(user, collabInputStream, collabFileDetails, ethicsInputStream, - ethicsFileDetails, payload, parentDar); - DataAccessRequest progressReport = dataAccessRequestService.createProgressReport(user, - payload, parentDar, (ContainerRequest) request); + DataAccessRequest payload = + DataAccessRequest.populateProgressReportFromJsonString(dar, parentDar); + populateProgressReportWithDocuments( + user, + collabInputStream, + collabFileDetails, + ethicsInputStream, + ethicsFileDetails, + payload, + parentDar); + DataAccessRequest progressReport = + dataAccessRequestService.createProgressReport( + user, payload, parentDar, (ContainerRequest) request); if (Objects.nonNull(progressReport) && !progressReport.getIsCloseoutProgressReport()) { sendNewDarCollectionMessage(parentDar.getCollectionId()); } - List datasets = datasetService.findDatasetsByIds(user, progressReport.getDatasetIds()); - ComplianceLogger.logDARSubmission(user, datasets, ((ContainerRequest) request), - HttpStatusCodes.STATUS_CODE_CREATED); + List datasets = + datasetService.findDatasetsByIds(user, progressReport.getDatasetIds()); + ComplianceLogger.logDARSubmission( + user, datasets, ((ContainerRequest) request), HttpStatusCodes.STATUS_CODE_CREATED); return Response.ok(progressReport.convertToSimplifiedDar()).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -480,10 +496,15 @@ private void logCaughtEmailException(Integer collectionId, Exception e) { logException("Exception sending email for collection id: " + collectionId, e); } - public void populateProgressReportWithDocuments(User user, InputStream collabInputStream, - FormDataContentDisposition collabFileDetails, InputStream ethicsInputStream, - FormDataContentDisposition ethicsFileDetails, DataAccessRequest childDar, - DataAccessRequest parentDar) throws IOException { + public void populateProgressReportWithDocuments( + User user, + InputStream collabInputStream, + FormDataContentDisposition collabFileDetails, + InputStream ethicsInputStream, + FormDataContentDisposition ethicsFileDetails, + DataAccessRequest childDar, + DataAccessRequest parentDar) + throws IOException { for (Integer datasetId : childDar.getDatasetIds()) { Dataset dataset = datasetService.findDatasetById(user, datasetId); if (dataset == null) { @@ -499,8 +520,8 @@ public void populateProgressReportWithDocuments(User user, InputStream collabInp && Strings.isNullOrEmpty(parentCollabLocation)) { throw new BadRequestException("Collaboration document is required"); } - uploadDocumentContents(DarDocumentType.COLLABORATION, childDar, - collabInputStream, collabFileDetails); + uploadDocumentContents( + DarDocumentType.COLLABORATION, childDar, collabInputStream, collabFileDetails); } if (Boolean.TRUE.equals(dataUse.getEthicsApprovalRequired())) { String parentEthicsLocation = parentDar.getData().getIrbDocumentLocation(); @@ -508,8 +529,7 @@ public void populateProgressReportWithDocuments(User user, InputStream collabInp && Strings.isNullOrEmpty(parentEthicsLocation)) { throw new BadRequestException("Ethics approval document is required"); } - uploadDocumentContents(DarDocumentType.IRB, childDar, - ethicsInputStream, ethicsFileDetails); + uploadDocumentContents(DarDocumentType.IRB, childDar, ethicsInputStream, ethicsFileDetails); } } } @@ -519,17 +539,14 @@ public void populateProgressReportWithDocuments(User user, InputStream collabInp @Path("/v2/{referenceId}/collaborationDocument") @RolesAllowed({ADMIN, CHAIRPERSON, MEMBER, RESEARCHER}) public Response getCollaborationDocument( - @Auth DuosUser duosUser, - @PathParam("referenceId") String referenceId) { + @Auth DuosUser duosUser, @PathParam("referenceId") String referenceId) { try { DataAccessRequest dar = getDarById(referenceId); validateAuthedRoleUser( - List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER), - duosUser, referenceId); - if (dar.getData() != null && - StringUtils.isNotEmpty(dar.getData().getCollaborationLetterLocation()) && - StringUtils.isNotEmpty(dar.getData().getCollaborationLetterName()) - ) { + List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON, UserRoles.MEMBER), duosUser, referenceId); + if (dar.getData() != null + && StringUtils.isNotEmpty(dar.getData().getCollaborationLetterLocation()) + && StringUtils.isNotEmpty(dar.getData().getCollaborationLetterName())) { String blobIdName = dar.getData().getCollaborationLetterLocation(); String fileName = dar.getData().getCollaborationLetterName(); InputStream is = gcsService.getDocument(blobIdName); @@ -558,8 +575,9 @@ public Response uploadCollaborationDocument( User user = findUserByEmail(authUser.getEmail()); DataAccessRequest dar = getDarById(referenceId); checkAuthorizedUpdateUser(user, dar); - DataAccessRequest updatedDar = updateDarWithDocumentContents(DarDocumentType.COLLABORATION, - user, dar, uploadInputStream, fileDetail); + DataAccessRequest updatedDar = + updateDarWithDocumentContents( + DarDocumentType.COLLABORATION, user, dar, uploadInputStream, fileDetail); return Response.ok(updatedDar.convertToSimplifiedDar()).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -572,7 +590,8 @@ public Response uploadCollaborationDocument( @RolesAllowed({ADMIN, RESEARCHER}) public Response deleteDar(@Auth DuosUser duosUser, @PathParam("referenceId") String referenceId) { try { - DataAccessRequest dataAccessRequest = validateAuthedRoleUser(Collections.singletonList(UserRoles.ADMIN), duosUser, referenceId); + DataAccessRequest dataAccessRequest = + validateAuthedRoleUser(Collections.singletonList(UserRoles.ADMIN), duosUser, referenceId); dataAccessRequestService.deleteDataAccessRequest(dataAccessRequest); return Response.ok().build(); } catch (Exception e) { @@ -637,7 +656,8 @@ private DataAccessRequest updateDarWithDocumentContents( User user, DataAccessRequest dar, InputStream uploadInputStream, - FormDataContentDisposition fileDetail) throws IOException { + FormDataContentDisposition fileDetail) + throws IOException { // When we move updateDarWithDocumentContents to the service tier, we should incorporate the // code below into that method if (!dar.getDraft()) { @@ -650,15 +670,18 @@ private DataAccessRequest updateDarWithDocumentContents( /** * Uploads the document contents to GCS and mutates the dar data object with the blobId. * - * @param type The type of document (IRB or Collaboration) - * @param dar The Data Access Request + * @param type The type of document (IRB or Collaboration) + * @param dar The Data Access Request * @param uploadInputStream The input stream of the file to be uploaded - * @param fileDetail The file details + * @param fileDetail The file details * @throws IOException if an error occurs during upload */ - public void uploadDocumentContents(DarDocumentType type, DataAccessRequest dar, + public void uploadDocumentContents( + DarDocumentType type, + DataAccessRequest dar, InputStream uploadInputStream, - FormDataContentDisposition fileDetail) throws IOException { + FormDataContentDisposition fileDetail) + throws IOException { // This should be moved to service tier logic and the transactions should be coordinated validateFileDetails(fileDetail); String fileName = fileDetail.getFileName(); @@ -690,9 +713,10 @@ private void deleteDarDocument(DataAccessRequest dar, String blobIdName) { try { gcsService.deleteDocument(blobIdName); } catch (Exception e) { - String message = String.format( - "Unable to delete document for DAR ID: %s; dar document location: %s", - dar.getReferenceId(), blobIdName); + String message = + String.format( + "Unable to delete document for DAR ID: %s; dar document location: %s", + dar.getReferenceId(), blobIdName); logWarn(message); } } @@ -713,12 +737,12 @@ private DataAccessRequest getDarById(String referenceId) { * (i.e. Admin) so they can also have access to the DAR. * * @param allowableRoles List of roles that would allow the user to access the resource - * @param duosUser The DuosUser - * @param referenceId The referenceId of the resource. + * @param duosUser The DuosUser + * @param referenceId The referenceId of the resource. * @return dataAccessRequest The data access request underlying the referenceId */ - private DataAccessRequest validateAuthedRoleUser(final List allowableRoles, DuosUser duosUser, - String referenceId) { + private DataAccessRequest validateAuthedRoleUser( + final List allowableRoles, DuosUser duosUser, String referenceId) { DataAccessRequest dataAccessRequest = getDarById(referenceId); User user = duosUser.getUser(); if (Objects.nonNull(dataAccessRequest.getUserId()) && dataAccessRequest.getUserId() > 0) { diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java index 974cae2e50..cdbb164d7d 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DatasetResource.java @@ -64,7 +64,6 @@ import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.FormDataParam; - @Path("api/dataset") public class DatasetResource extends Resource { @@ -78,10 +77,13 @@ public class DatasetResource extends Resource { private final GCSService gcsService; @Inject - public DatasetResource(DatasetService datasetService, UserService userService, + public DatasetResource( + DatasetService datasetService, + UserService userService, DatasetRegistrationService datasetRegistrationService, ElasticSearchService elasticSearchService, - TDRService tdrService, GCSService gcsService) { + TDRService tdrService, + GCSService gcsService) { this.datasetService = datasetService; this.userService = userService; this.datasetRegistrationService = datasetRegistrationService; @@ -102,9 +104,7 @@ public DatasetResource(DatasetService datasetService, UserService userService, * With that object, we can fully create datasets from the provided values. */ public Response createDatasetRegistration( - @Auth AuthUser authUser, - FormDataMultiPart multipart, - @FormDataParam("dataset") String json) { + @Auth AuthUser authUser, FormDataMultiPart multipart, @FormDataParam("dataset") String json) { try { Set errors = jsonSchemaUtil.validateSchema_v1(json); if (!errors.isEmpty()) { @@ -113,18 +113,16 @@ public Response createDatasetRegistration( + String.join("\n", errors.stream().map(ValidationMessage::getMessage).toList())); } - DatasetRegistrationSchemaV1 registration = jsonSchemaUtil.deserializeDatasetRegistration( - json); + DatasetRegistrationSchemaV1 registration = + jsonSchemaUtil.deserializeDatasetRegistration(json); User user = userService.findUserByEmail(authUser.getEmail()); // key: field name (not file name), value: file body part Map files = extractFilesFromMultiPart(multipart); // Generate datasets from registration - List datasets = datasetRegistrationService.createDatasetsFromRegistration( - registration, - user, - files); + List datasets = + datasetRegistrationService.createDatasetsFromRegistration(registration, user, files); Integer studyId = datasets.get(0).getStudyId(); Study study = datasetService.findStudy(studyId); DatasetRegistrationSchemaV1Builder builder = new DatasetRegistrationSchemaV1Builder(); @@ -135,8 +133,8 @@ public Response createDatasetRegistration( logException(entityException); throw entityException; } - URI uri = UriBuilder.fromPath(String.format("/api/dataset/study/%s", study.getStudyId())) - .build(); + URI uri = + UriBuilder.fromPath(String.format("/api/dataset/study/%s", study.getStudyId())).build(); String entity = GsonUtil.buildGsonNullSerializer().toJson(createdRegistration); return Response.created(uri).entity(entity).build(); } catch (Exception e) { @@ -144,9 +142,7 @@ public Response createDatasetRegistration( } } - /** - * This endpoint updates the dataset. - */ + /** This endpoint updates the dataset. */ @PUT @Consumes({MediaType.MULTIPART_FORM_DATA}) @Produces({MediaType.APPLICATION_JSON}) @@ -172,24 +168,22 @@ public Response updateByDatasetUpdate( // key: field name (not file name), value: file body part Map files = extractFilesFromMultiPart(multipart); - Dataset updatedDataset = datasetRegistrationService.updateDataset(datasetId, user, update, - files); + Dataset updatedDataset = + datasetRegistrationService.updateDataset(datasetId, user, update, files); return Response.ok().entity(updatedDataset).build(); } catch (Exception e) { return createExceptionResponse(e); } } - /** - * This endpoint updates the dataset. - */ + /** This endpoint updates the dataset. */ @PATCH @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @Path("/{datasetId}") @RolesAllowed({ADMIN, CHAIRPERSON, DATASUBMITTER}) - public Response patchByDatasetUpdate(@Auth DuosUser duosUser, - @PathParam("datasetId") Integer datasetId, String json) { + public Response patchByDatasetUpdate( + @Auth DuosUser duosUser, @PathParam("datasetId") Integer datasetId, String json) { try { User user = duosUser.getUser(); Dataset existingDataset = datasetService.findDatasetById(user, datasetId); @@ -217,7 +211,8 @@ public Response patchByDatasetUpdate(@Auth DuosUser duosUser, } // Validate DatasetPatch values List existingNames = datasetService.findAllDatasetNames(); - if (patch.name() != null && !patch.name().equals(existingDataset.getName()) + if (patch.name() != null + && !patch.name().equals(existingDataset.getName()) && existingNames.contains(patch.name())) { throw new BadRequestException( "The new name for this dataset already exists: " + patch.name()); @@ -239,7 +234,8 @@ public Response patchByDatasetUpdate(@Auth DuosUser duosUser, @Path("/v3") public Response findAllDatasetStudySummaries(@Auth DuosUser duosUser) { try { - List summaries = datasetService.findAllDatasetStudySummaries(duosUser.getUser()); + List summaries = + datasetService.findAllDatasetStudySummaries(duosUser.getUser()); return Response.ok(summaries).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -267,8 +263,8 @@ public Response getDataset(@Auth DuosUser duosUser, @PathParam("datasetId") Inte @Produces(MediaType.APPLICATION_JSON) @PermitAll @Timed - public Response getRegistrationFromDatasetIdentifier(@Auth DuosUser duosUser, - @PathParam("datasetIdentifier") String datasetIdentifier) { + public Response getRegistrationFromDatasetIdentifier( + @Auth DuosUser duosUser, @PathParam("datasetIdentifier") String datasetIdentifier) { try { User user = duosUser.getUser(); Dataset dataset = datasetService.findDatasetByIdentifier(user, datasetIdentifier); @@ -279,8 +275,8 @@ public Response getRegistrationFromDatasetIdentifier(@Auth DuosUser duosUser, if (dataset.getStudy() == null || dataset.getStudy().getStudyId() == null) { throw new NotFoundException("No study exists for dataset identifier: " + datasetIdentifier); } - DatasetRegistrationSchemaV1 registration = new DatasetRegistrationSchemaV1Builder().build( - dataset.getStudy(), List.of(dataset)); + DatasetRegistrationSchemaV1 registration = + new DatasetRegistrationSchemaV1Builder().build(dataset.getStudy(), List.of(dataset)); String entity = GsonUtil.buildGsonNullSerializer().toJson(registration); return Response.ok().entity(entity).build(); } catch (Exception e) { @@ -292,24 +288,24 @@ public Response getRegistrationFromDatasetIdentifier(@Auth DuosUser duosUser, @Path("/batch") @Produces("application/json") @PermitAll - public Response getDatasets(@Auth DuosUser duosUser, - @QueryParam("ids") List datasetIds) { + public Response getDatasets( + @Auth DuosUser duosUser, @QueryParam("ids") List datasetIds) { try { List datasets = datasetService.findDatasetsByIds(duosUser.getUser(), datasetIds); - Set foundIds = datasets.stream().map(Dataset::getDatasetId) - .collect(Collectors.toSet()); + Set foundIds = + datasets.stream().map(Dataset::getDatasetId).collect(Collectors.toSet()); if (!foundIds.containsAll(datasetIds)) { // find the differences - List differences = new ArrayList<>(datasetIds) - .stream() - .filter(Objects::nonNull) - .filter(Predicate.not(foundIds::contains)) - .toList(); + List differences = + new ArrayList<>(datasetIds) + .stream() + .filter(Objects::nonNull) + .filter(Predicate.not(foundIds::contains)) + .toList(); throw new NotFoundException( "Could not find datasets with ids: " - + String.join(",", - differences.stream().map(Object::toString).collect(Collectors.toSet()))); - + + String.join( + ",", differences.stream().map(Object::toString).collect(Collectors.toSet()))); } return Response.ok(datasets).build(); } catch (Exception e) { @@ -418,8 +414,8 @@ public Response indexDataset(@Auth AuthUser authUser, @PathParam("datasetId") In @DELETE @Path("/index/{datasetId}") @RolesAllowed(ADMIN) - public Response deleteDatasetIndex(@Auth AuthUser authUser, - @PathParam("datasetId") Integer datasetId) { + public Response deleteDatasetIndex( + @Auth AuthUser authUser, @PathParam("datasetId") Integer datasetId) { try { User user = userService.findUserByEmail(authUser.getEmail()); return elasticSearchService.deleteIndex(datasetId, user.getUserId()); @@ -446,8 +442,8 @@ public Response searchDatasetIndex(@Auth DuosUser duosUser, String query) { @Produces("application/json") @RolesAllowed(ADMIN) @Path("/{id}/datause") - public Response updateDatasetDataUse(@Auth AuthUser authUser, @PathParam("id") Integer id, - String dataUseJson) { + public Response updateDatasetDataUse( + @Auth AuthUser authUser, @PathParam("id") Integer id, String dataUseJson) { try { User user = userService.findUserByEmail(authUser.getEmail()); Gson gson = new Gson(); @@ -498,10 +494,11 @@ private void validateDatasetDacAccess(User user, Dataset dataset) { throw new NotFoundException(); } } - List dacIds = user.getRoles().stream() - .filter(r -> r.getRoleId().equals(UserRoles.CHAIRPERSON.getRoleId())) - .map(UserRole::getDacId) - .toList(); + List dacIds = + user.getRoles().stream() + .filter(r -> r.getRoleId().equals(UserRoles.CHAIRPERSON.getRoleId())) + .map(UserRole::getDacId) + .toList(); if (dacIds.isEmpty()) { // Something went very wrong here. A chairperson with no dac ids is an error logWarn("Unable to find dac ids for chairperson user: " + user.getEmail()); @@ -523,10 +520,10 @@ private void validateDatasetDacAccess(User user, Dataset dataset) { @RolesAllowed(ADMIN) @Path("/{id}/authorizedAccessReaders") public Response getAuthorizedReaders(@Auth DuosUser duosUser, @PathParam("id") Long id) { - try{ + try { return Response.ok(datasetService.getAuthorizationReaders(id)).build(); } catch (Exception e) { - return createExceptionResponse(e); + return createExceptionResponse(e); } } @@ -535,9 +532,7 @@ public Response getAuthorizedReaders(@Auth DuosUser duosUser, @PathParam("id") L @RolesAllowed(ADMIN) @Path("/{id}/authorizedAccessReaders/{userId}") public Response addAuthorizedReaders( - @Auth DuosUser duosUser, - @PathParam("id") long datasetId, - @PathParam("userId") int userId) { + @Auth DuosUser duosUser, @PathParam("id") long datasetId, @PathParam("userId") int userId) { try { User targetUser = userService.findUserById(userId); if (targetUser == null || !targetUser.hasUserRole(UserRoles.RESEARCHER)) { @@ -549,7 +544,6 @@ public Response addAuthorizedReaders( } catch (Exception e) { return createExceptionResponse(e); } - } @DELETE @@ -557,9 +551,7 @@ public Response addAuthorizedReaders( @RolesAllowed(ADMIN) @Path("/{id}/authorizedAccessReaders/{userId}") public Response removeAuthorizedReaders( - @Auth DuosUser duosUser, - @PathParam("id") long datasetId, - @PathParam("userId") long userId) { + @Auth DuosUser duosUser, @PathParam("id") long datasetId, @PathParam("userId") long userId) { try { datasetService.removeAuthorizedAccessReader(datasetId, userId); return Response.ok().build(); @@ -572,13 +564,17 @@ public Response removeAuthorizedReaders( @Produces("application/json") @RolesAllowed(RESEARCHER) @Path("/{identifier}/approvedUsers") - public Response getApprovedUsers(@Auth DuosUser duosUser, @PathParam("identifier") String datasetIdentifier) { + public Response getApprovedUsers( + @Auth DuosUser duosUser, @PathParam("identifier") String datasetIdentifier) { try { - Dataset dataset = datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), datasetIdentifier, false); + Dataset dataset = + datasetService.findMinimalDatasetByIdentifier( + duosUser.getUser(), datasetIdentifier, false); if (Objects.isNull(dataset)) { return Response.status(Response.Status.NOT_FOUND).build(); } - if (!datasetService.isAuthorizedToListUsers(dataset.getDatasetId(), duosUser.getUser().getUserId())) { + if (!datasetService.isAuthorizedToListUsers( + dataset.getDatasetId(), duosUser.getUser().getUserId())) { return Response.status(Response.Status.FORBIDDEN).build(); } return Response.ok(tdrService.getApprovedUsersForDataset(duosUser, dataset)).build(); @@ -591,7 +587,8 @@ public Response getApprovedUsers(@Auth DuosUser duosUser, @PathParam("identifier @Produces(MediaType.APPLICATION_OCTET_STREAM) @Path("/{id}/nihInstitutionalCertification") @RolesAllowed({ADMIN, DATASUBMITTER, CHAIRPERSON, MEMBER}) - public Response getNihInstitutionalCertification(@Auth DuosUser duosUser, @PathParam("id") Integer id) { + public Response getNihInstitutionalCertification( + @Auth DuosUser duosUser, @PathParam("id") Integer id) { try { User requestingUser = duosUser.getUser(); Dataset dataset = datasetService.findDatasetById(requestingUser, id); @@ -599,19 +596,22 @@ public Response getNihInstitutionalCertification(@Auth DuosUser duosUser, @PathP return Response.status(Response.Status.NOT_FOUND).build(); } FileStorageObject nihFile = dataset.getNihInstitutionalCertificationFile(); - if (nihFile != null && - !nihFile.getDeleted() && - nihFile.getFileName() != null && - nihFile.getBlobId() != null && - (requestingUser.hasUserRole(UserRoles.ADMIN) + if (nihFile != null + && !nihFile.getDeleted() + && nihFile.getFileName() != null + && nihFile.getBlobId() != null + && (requestingUser.hasUserRole(UserRoles.ADMIN) || dataset.isCreator(requestingUser) || dataset.isCustodian(requestingUser) || requestingUser.verifyDACRole(CHAIRPERSON, dataset.getDacId()) || requestingUser.verifyDACRole(MEMBER, dataset.getDacId()))) { InputStream fileStream = gcsService.getDocument(nihFile.getBlobId()); StreamingOutput streamOutput = createStreamingOutput(fileStream); - return Response.ok(streamOutput).header(HttpHeaders.CONTENT_DISPOSITION, - String.format("attachment; filename=\"%s\"", nihFile.getFileName())).build(); + return Response.ok(streamOutput) + .header( + HttpHeaders.CONTENT_DISPOSITION, + String.format("attachment; filename=\"%s\"", nihFile.getFileName())) + .build(); } else { return Response.status(Status.NOT_FOUND).build(); } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java b/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java index 93c0f32061..5d326f9445 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/DraftResource.java @@ -46,8 +46,7 @@ public class DraftResource extends Resource { private final DraftService draftService; @Inject - public DraftResource(UserService userService, - DraftService draftService) { + public DraftResource(UserService userService, DraftService draftService) { this.userService = userService; this.draftService = draftService; } @@ -59,13 +58,11 @@ public DraftResource(UserService userService, public Response getDrafts(@Auth AuthUser authUser) { try { User user = userService.findUserByEmail(authUser.getEmail()); - Collection draftSummaries = draftService.findDraftSummariesForUser( - user); + Collection draftSummaries = draftService.findDraftSummariesForUser(user); return Response.ok().entity(draftSummaries).build(); } catch (Exception e) { return createExceptionResponse(e); } - } @POST @@ -89,18 +86,16 @@ public Response createDraftRegistration(@Auth AuthUser authUser, String json) { @Produces({MediaType.APPLICATION_JSON}) @Path("/v1/{draftUUID}") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response getDraftDocument(@Auth AuthUser authUser, - @PathParam("draftUUID") String draftUUID) { + public Response getDraftDocument( + @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID) { try { User user = userService.findUserByEmail(authUser.getEmail()); - DraftInterface draft = draftService.getAuthorizedDraft( - validateUUID(draftUUID), user); + DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); StreamingOutput output = draftService.draftAsJson(draft); return Response.ok().entity(output).build(); } catch (Exception e) { return createExceptionResponse(e); } - } @PUT @@ -108,12 +103,11 @@ public Response getDraftDocument(@Auth AuthUser authUser, @Consumes({MediaType.APPLICATION_JSON}) @Path("/v1/{draftUUID}") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response updateDraft(@Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, - String json) { + public Response updateDraft( + @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, String json) { try { User user = userService.findUserByEmail(authUser.getEmail()); - DraftInterface draft = draftService.getAuthorizedDraft( - validateUUID(draftUUID), user); + DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); draft.setJson(json); DraftInterface responseDraft = draftService.updateDraft(draft, user); return Response.ok().entity(draftService.draftAsJson(responseDraft)).build(); @@ -127,8 +121,8 @@ public Response updateDraft(@Auth AuthUser authUser, @PathParam("draftUUID") Str @Consumes({MediaType.TEXT_PLAIN}) @Path("/v1/{draftUUID}") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response patchDraftName(@Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, - String name) { + public Response patchDraftName( + @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, String name) { try { User user = userService.findUserByEmail(authUser.getEmail()); DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); @@ -147,8 +141,7 @@ public Response patchDraftName(@Auth AuthUser authUser, @PathParam("draftUUID") public Response deleteDraft(@Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID) { try { User user = userService.findUserByEmail(authUser.getEmail()); - DraftInterface draft = draftService.getAuthorizedDraft( - validateUUID(draftUUID), user); + DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); draftService.deleteDraft(draft, user); } catch (Exception e) { return createExceptionResponse(e); @@ -160,17 +153,15 @@ public Response deleteDraft(@Auth AuthUser authUser, @PathParam("draftUUID") Str @Produces({MediaType.APPLICATION_JSON}) @Path("/v1/{draftUUID}/attachments") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response getAttachments(@Auth AuthUser authUser, - @PathParam("draftUUID") String draftUUID) { + public Response getAttachments( + @Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID) { try { User user = userService.findUserByEmail(authUser.getEmail()); - DraftInterface draft = draftService.getAuthorizedDraft( - validateUUID(draftUUID), user); + DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); return Response.ok().entity(draft.getStoredFiles()).build(); } catch (Exception e) { return createExceptionResponse(e); } - } @POST @@ -178,15 +169,15 @@ public Response getAttachments(@Auth AuthUser authUser, @Consumes({MediaType.MULTIPART_FORM_DATA}) @Path("/v1/{draftUUID}/attachments") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response addAttachments(@Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, + public Response addAttachments( + @Auth AuthUser authUser, + @PathParam("draftUUID") String draftUUID, FormDataMultiPart multipart) { try { User user = userService.findUserByEmail(authUser.getEmail()); - DraftInterface draft = draftService.getAuthorizedDraft( - validateUUID(draftUUID), user); + DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); Map files = extractFilesFromMultiPart(multipart); - List storedFiles = draftService.addAttachments(draft, user, - files); + List storedFiles = draftService.addAttachments(draft, user, files); return Response.ok().entity(storedFiles).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -197,28 +188,34 @@ public Response addAttachments(@Auth AuthUser authUser, @PathParam("draftUUID") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Path("/v1/{draftUUID}/attachments/{fileId}") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response getAttachment(@Auth AuthUser authUser, @PathParam("draftUUID") String draftUUID, + public Response getAttachment( + @Auth AuthUser authUser, + @PathParam("draftUUID") String draftUUID, @PathParam("fileId") Integer fileId) { try { User user = userService.findUserByEmail(authUser.getEmail()); - DraftInterface draft = draftService.getAuthorizedDraft( - validateUUID(draftUUID), user); - Set filteredAttachments = draft.getStoredFiles().stream() - .filter((fileStorageObject) -> fileStorageObject.getFileStorageObjectId().equals(fileId)) - .collect( - Collectors.toSet()); + DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); + Set filteredAttachments = + draft.getStoredFiles().stream() + .filter( + (fileStorageObject) -> fileStorageObject.getFileStorageObjectId().equals(fileId)) + .collect(Collectors.toSet()); if (filteredAttachments.isEmpty()) { return Response.status(Response.Status.NOT_FOUND).build(); } else if (filteredAttachments.size() == 1) { FileStorageObject targetAttachment = filteredAttachments.iterator().next(); InputStream fileStream = draftService.getDraftAttachmentStream(targetAttachment); StreamingOutput streamOutput = createStreamingOutput(fileStream); - return Response.ok(streamOutput).header(HttpHeaders.CONTENT_DISPOSITION, - String.format("attachment; filename=\"%s\"", targetAttachment.getFileName())).build(); + return Response.ok(streamOutput) + .header( + HttpHeaders.CONTENT_DISPOSITION, + String.format("attachment; filename=\"%s\"", targetAttachment.getFileName())) + .build(); } else { - logWarn(String.format( - "More than one file attachment matches requested draft ID and file ID combination. draftid: %s, fileid: %d", - draftUUID, fileId)); + logWarn( + String.format( + "More than one file attachment matches requested draft ID and file ID combination. draftid: %s, fileid: %d", + draftUUID, fileId)); throw new InternalServerErrorException("Disambiguation error encountered."); } } catch (Exception e) { @@ -230,12 +227,13 @@ public Response getAttachment(@Auth AuthUser authUser, @PathParam("draftUUID") S @Produces(MediaType.APPLICATION_JSON) @Path("/v1/{draftUUID}/attachments/{fileId}") @RolesAllowed({ADMIN, DATASUBMITTER}) - public Response deleteDraftAttachment(@Auth AuthUser authUser, - @PathParam("draftUUID") String draftUUID, @PathParam("fileId") Integer fileId) { + public Response deleteDraftAttachment( + @Auth AuthUser authUser, + @PathParam("draftUUID") String draftUUID, + @PathParam("fileId") Integer fileId) { try { User user = userService.findUserByEmail(authUser.getEmail()); - DraftInterface draft = draftService.getAuthorizedDraft( - validateUUID(draftUUID), user); + DraftInterface draft = draftService.getAuthorizedDraft(validateUUID(draftUUID), user); draftService.deleteDraftAttachment(draft, user, fileId); return Response.ok().build(); } catch (Exception e) { diff --git a/src/main/java/org/broadinstitute/consent/http/resources/ErrorResource.java b/src/main/java/org/broadinstitute/consent/http/resources/ErrorResource.java index 67c9a94100..582f6e54fd 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/ErrorResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/ErrorResource.java @@ -18,12 +18,12 @@ public class ErrorResource { /** - * Explanatory note about this 404 handler: - * In order to provide the original URI that resulted in a 404, we need to access the underlying - * request information. The HttpServletRequest passed to this method is actually a wrapper around - * the original request. By unwrapping it to get to the ServletApiRequest, we can retrieve the - * original URI that was requested. This allows us to construct a more informative error message - * for the client. + * Explanatory note about this 404 handler: In order to provide the original URI that resulted in + * a 404, we need to access the underlying request information. The HttpServletRequest passed to + * this method is actually a wrapper around the original request. By unwrapping it to get to the + * ServletApiRequest, we can retrieve the original URI that was requested. This allows us to + * construct a more informative error message for the client. + * * @param httpServletRequest The HttpServletRequest * @return Response */ diff --git a/src/main/java/org/broadinstitute/consent/http/resources/InstitutionResource.java b/src/main/java/org/broadinstitute/consent/http/resources/InstitutionResource.java index 926266bbff..eb493f9b68 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/InstitutionResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/InstitutionResource.java @@ -78,7 +78,8 @@ public Response getInstitution(@Auth DuosUser duosUser, @PathParam("id") Integer public Response createInstitution(@Auth DuosUser duosUser, String institution) { try { Institution payload = GsonUtil.getInstance().fromJson(institution, Institution.class); - Institution newInstitution = institutionService.createInstitution(payload, duosUser.getUser().getUserId()); + Institution newInstitution = + institutionService.createInstitution(payload, duosUser.getUser().getUserId()); return Response.ok().entity(newInstitution).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -90,14 +91,14 @@ public Response createInstitution(@Auth DuosUser duosUser, String institution) { @Produces("application/json") @Path("/{id}") @RolesAllowed(ADMIN) - public Response patchInstitution(@Auth DuosUser duosUser, @PathParam("id") Integer id, - String institution) { + public Response patchInstitution( + @Auth DuosUser duosUser, @PathParam("id") Integer id, String institution) { try { Institution existingInstitution = institutionService.findInstitutionById(id); Institution payload = GsonUtil.getInstance().fromJson(institution, Institution.class); Institution mergedPayload = payload.mergeUpdatableFields(existingInstitution); - Institution updatedInstitution = institutionService.updateInstitutionById(mergedPayload, id, - duosUser.getUserId()); + Institution updatedInstitution = + institutionService.updateInstitutionById(mergedPayload, id, duosUser.getUserId()); return Response.ok().entity(updatedInstitution).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -109,12 +110,12 @@ public Response patchInstitution(@Auth DuosUser duosUser, @PathParam("id") Integ @Produces("application/json") @Path("/{id}") @RolesAllowed(ADMIN) - public Response updateInstitution(@Auth DuosUser duosUser, @PathParam("id") Integer id, - String institution) { + public Response updateInstitution( + @Auth DuosUser duosUser, @PathParam("id") Integer id, String institution) { try { Institution payload = GsonUtil.getInstance().fromJson(institution, Institution.class); - Institution updatedInstitution = institutionService.updateInstitutionById(payload, id, - duosUser.getUserId()); + Institution updatedInstitution = + institutionService.updateInstitutionById(payload, id, duosUser.getUserId()); return Response.ok().entity(updatedInstitution).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -142,28 +143,34 @@ public Response deleteInstitution(@Auth DuosUser duosUser, @PathParam("id") Inte public Response updateInstitutionDomains(@Auth DuosUser duosUser, String institutionDomainMap) { try { List updatedInstitutions = new ArrayList<>(); - InstitutionDomainMap domainMap = GsonUtil.getInstance().fromJson(institutionDomainMap, InstitutionDomainMap.class); - domainMap.getInstitutionDomainMap().forEach((institutionName, value) -> { - List domains = value.stream().toList(); - List institutions = institutionService.findAllInstitutionsByName( - institutionName); - if (institutions.isEmpty()) { - logWarn("No institution found with name: [%s]".formatted(institutionName)); - } else if (institutions.size() == 1) { - Institution institution = institutions.get(0); - institution.setDomains(domains); - try { - updatedInstitutions.add(institutionService.updateInstitutionById( - institution, - institution.getId(), - duosUser.getUserId())); - } catch (Exception e) { - logException("Failed to update institution: [%s] with domains: %s".formatted(institutionName, domains), e); - } - } else { - logWarn("Multiple institutions found with name: [%s]".formatted(institutionName)); - } - }); + InstitutionDomainMap domainMap = + GsonUtil.getInstance().fromJson(institutionDomainMap, InstitutionDomainMap.class); + domainMap + .getInstitutionDomainMap() + .forEach( + (institutionName, value) -> { + List domains = value.stream().toList(); + List institutions = + institutionService.findAllInstitutionsByName(institutionName); + if (institutions.isEmpty()) { + logWarn("No institution found with name: [%s]".formatted(institutionName)); + } else if (institutions.size() == 1) { + Institution institution = institutions.get(0); + institution.setDomains(domains); + try { + updatedInstitutions.add( + institutionService.updateInstitutionById( + institution, institution.getId(), duosUser.getUserId())); + } catch (Exception e) { + logException( + "Failed to update institution: [%s] with domains: %s" + .formatted(institutionName, domains), + e); + } + } else { + logWarn("Multiple institutions found with name: [%s]".formatted(institutionName)); + } + }); return Response.ok(updatedInstitutions).build(); } catch (Exception e) { return createExceptionResponse(e); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/LibraryCardResource.java b/src/main/java/org/broadinstitute/consent/http/resources/LibraryCardResource.java index 0c43f40566..960a2cef05 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/LibraryCardResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/LibraryCardResource.java @@ -30,10 +30,7 @@ public class LibraryCardResource extends Resource { private final LibraryCardService libraryCardService; @Inject - public LibraryCardResource( - UserService userService, - LibraryCardService libraryCardService - ) { + public LibraryCardResource(UserService userService, LibraryCardService libraryCardService) { this.userService = userService; this.libraryCardService = libraryCardService; } @@ -67,8 +64,8 @@ public Response getLibraryCardById(@Auth AuthUser authUser, @PathParam("id") Int @Produces("application/json") @Path("/institution/{id}") @RolesAllowed({ADMIN}) - public Response getLibraryCardsByInstitutionId(@Auth AuthUser authUser, - @PathParam("id") Integer id) { + public Response getLibraryCardsByInstitutionId( + @Auth AuthUser authUser, @PathParam("id") Integer id) { try { List libraryCards = libraryCardService.findLibraryCardsByInstitutionId(id); return Response.ok().entity(libraryCards).build(); @@ -108,7 +105,9 @@ public Response deleteLibraryCard(@Auth AuthUser authUser, @PathParam("id") Inte } try { // If user is not an admin and SO institutionID doesn't match the user's throw an exception - if (lcUser != null && !checkIsAdmin(user) && !lcUser.getInstitution().equals(user.getInstitution())) { + if (lcUser != null + && !checkIsAdmin(user) + && !lcUser.getInstitution().equals(user.getInstitution())) { throw new ForbiddenException("You are not authorized to delete this library card"); } libraryCardService.deleteLibraryCardById(id); @@ -119,8 +118,7 @@ public Response deleteLibraryCard(@Auth AuthUser authUser, @PathParam("id") Inte } private boolean checkIsAdmin(User user) { - return user.getRoles() - .stream() + return user.getRoles().stream() .anyMatch(role -> role.getName().equalsIgnoreCase(UserRoles.ADMIN.getRoleName())); } } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java b/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java index cbeea22707..03037aeaea 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/MailResource.java @@ -38,12 +38,14 @@ public MailResource(EmailService emailService) { @Produces("application/json") @Path("/type/{type}") @RolesAllowed({ADMIN}) - public Response getEmailByType(@Auth AuthUser authUser, + public Response getEmailByType( + @Auth AuthUser authUser, @PathParam("type") EmailType emailType, @DefaultValue("20") @QueryParam("limit") Integer limit, @DefaultValue("0") @QueryParam("offset") Integer offset) { validateLimitAndOffset(limit, offset); - return Response.ok().entity(emailService.fetchEmailMessagesByType(emailType, limit, offset)) + return Response.ok() + .entity(emailService.fetchEmailMessagesByType(emailType, limit, offset)) .build(); } @@ -51,12 +53,14 @@ public Response getEmailByType(@Auth AuthUser authUser, @Produces("application/json") @Path("/user/{userId}") @RolesAllowed({ADMIN}) - public Response getEmailByUser(@Auth AuthUser authUser, + public Response getEmailByUser( + @Auth AuthUser authUser, @PathParam("userId") Integer userId, @DefaultValue("20") @QueryParam("limit") Integer limit, @DefaultValue("0") @QueryParam("offset") Integer offset) { validateLimitAndOffset(limit, offset); - return Response.ok().entity(emailService.fetchEmailMessagesByUserId(userId, limit, offset)) + return Response.ok() + .entity(emailService.fetchEmailMessagesByUserId(userId, limit, offset)) .build(); } @@ -64,25 +68,29 @@ public Response getEmailByUser(@Auth AuthUser authUser, @Produces("application/json") @Path("/range") @RolesAllowed({ADMIN}) - public Response getEmailByDateRange(@Auth AuthUser authUser, + public Response getEmailByDateRange( + @Auth AuthUser authUser, @QueryParam("start") String start, @QueryParam("end") String end, @DefaultValue("20") @QueryParam("limit") Integer limit, @DefaultValue("0") @QueryParam("offset") Integer offset) { validateLimitAndOffset(limit, offset); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); - //if df.setLenient(false) were not set, dates like 55/97/2022 would parse and the year would be advanced. + // if df.setLenient(false) were not set, dates like 55/97/2022 would parse and the year would be + // advanced. df.setLenient(false); try { Date startDate = df.parse(start); - Date endDate = StringUtils.isNotBlank(end) ? - df.parse(end) : - Date.from(LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.UTC)); + Date endDate = + StringUtils.isNotBlank(end) + ? df.parse(end) + : Date.from(LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.UTC)); return Response.ok() .entity(emailService.fetchEmailMessagesByCreateDate(startDate, endDate, limit, offset)) .build(); } catch (ParseException pe) { - return Response.status(Response.Status.BAD_REQUEST).entity( + return Response.status(Response.Status.BAD_REQUEST) + .entity( "Invalid date format provided for begin or end. Please use MM/dd/yyyy (e.g. 05/21/2022)") .build(); } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java b/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java index ede3d177e6..1a74440e28 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/MatchResource.java @@ -39,17 +39,17 @@ public Response getMatchesForLatestDataAccessElectionsByPurposeIds( if (Objects.isNull(purposeIds) || purposeIds.isBlank()) { throw new BadRequestException("No purpose ids were provided"); } else { - List purposeIdsList = Arrays.asList(purposeIds.split(",")) - .stream() - .filter(id -> !id.isBlank()) - .map(id -> id.strip()) - .collect(Collectors.toList()); + List purposeIdsList = + Arrays.asList(purposeIds.split(",")).stream() + .filter(id -> !id.isBlank()) + .map(id -> id.strip()) + .collect(Collectors.toList()); if (purposeIdsList.isEmpty()) { throw new BadRequestException("Invalid query params provided"); } else { - List matchList = service.findMatchesForLatestDataAccessElectionsByPurposeIds( - purposeIdsList); + List matchList = + service.findMatchesForLatestDataAccessElectionsByPurposeIds(purposeIdsList); return Response.ok().entity(matchList).build(); } } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/MetricsResource.java b/src/main/java/org/broadinstitute/consent/http/resources/MetricsResource.java index e1087cf3a0..4b6f853069 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/MetricsResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/MetricsResource.java @@ -30,5 +30,4 @@ public Response getDatasetMetricsData(@PathParam("datasetId") Integer datasetId) return createExceptionResponse(e); } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/OAuth2Resource.java b/src/main/java/org/broadinstitute/consent/http/resources/OAuth2Resource.java index 8496130e8e..c45c44ef8c 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/OAuth2Resource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/OAuth2Resource.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.resources; -import jakarta.annotation.security.PermitAll; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; @@ -13,7 +12,6 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.Response.Status; import jakarta.ws.rs.core.UriInfo; -import org.apache.commons.lang3.StringUtils; import org.broadinstitute.consent.http.service.OidcService; @Path("oauth2") @@ -28,7 +26,9 @@ public OAuth2Resource(OidcService oidcService) { @Path("authorize") @GET public Response getAuthorizationEndpoint(@Context UriInfo uriInfo) { - return Response.status(Status.FOUND).location(oidcService.getAuthorizationURI(uriInfo.getQueryParameters())).build(); + return Response.status(Status.FOUND) + .location(oidcService.getAuthorizationURI(uriInfo.getQueryParameters())) + .build(); } @Path("token") @@ -36,7 +36,10 @@ public Response getAuthorizationEndpoint(@Context UriInfo uriInfo) { @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Response getToken(@Context UriInfo uriInfo, MultivaluedMap bodyParams) { - return Response.ok(oidcService.tokenExchange(bodyParams, uriInfo.getQueryParameters()), MediaType.APPLICATION_JSON).build(); + return Response.ok( + oidcService.tokenExchange(bodyParams, uriInfo.getQueryParameters()), + MediaType.APPLICATION_JSON) + .build(); } @Path("configuration") diff --git a/src/main/java/org/broadinstitute/consent/http/resources/Resource.java b/src/main/java/org/broadinstitute/consent/http/resources/Resource.java index d5f148ed0b..02050a28c7 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/Resource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/Resource.java @@ -42,13 +42,12 @@ import org.postgresql.util.PSQLState; import org.slf4j.LoggerFactory; - /** * Created by egolin on 9/17/14. - *

- * Abstract superclass for all Resources. + * + *

Abstract superclass for all Resources. */ -abstract public class Resource implements ConsentLogger { +public abstract class Resource implements ConsentLogger { // Resource based role names public static final String ADMIN = "Admin"; @@ -63,91 +62,152 @@ abstract public class Resource implements ConsentLogger { public static final String ITDIRECTOR = "ITDirector"; // NOTE: implement more Postgres vendor codes as we encounter them - private static final Map> vendorCodeStatusMap = Map.ofEntries( - Map.entry(PSQLState.UNKNOWN_STATE.getState(), - ImmutablePair.of(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), - "Database error")), - Map.entry(PSQLState.UNIQUE_VIOLATION.getState(), - ImmutablePair.of(Response.Status.CONFLICT.getStatusCode(), "Database conflict")), - Map.entry("22021", - ImmutablePair.of(Response.Status.BAD_REQUEST.getStatusCode(), "Invalid byte sequence")) - ); + private static final Map> vendorCodeStatusMap = + Map.ofEntries( + Map.entry( + PSQLState.UNKNOWN_STATE.getState(), + ImmutablePair.of( + Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), "Database error")), + Map.entry( + PSQLState.UNIQUE_VIOLATION.getState(), + ImmutablePair.of(Response.Status.CONFLICT.getStatusCode(), "Database conflict")), + Map.entry( + "22021", + ImmutablePair.of( + Response.Status.BAD_REQUEST.getStatusCode(), "Invalid byte sequence"))); private static final Map, ExceptionHandler> DISPATCH = new HashMap<>(); static { - DISPATCH.put(SubmittedDARCannotBeEditedException.class, e -> - Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) - .type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) - .build()); - DISPATCH.put(LibraryCardRequiredException.class, e -> - Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) - .type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) - .build()); - DISPATCH.put(NIHComplianceRuleException.class, e -> - Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) - .type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) - .build()); - DISPATCH.put(ConsentConflictException.class, e -> - Response.status(Response.Status.CONFLICT).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.CONFLICT.getStatusCode())).build()); - DISPATCH.put(UnprocessableEntityException.class, e -> - Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) - .type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) - .build()); - DISPATCH.put(UnsupportedOperationException.class, e -> - Response.status(Response.Status.CONFLICT).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.CONFLICT.getStatusCode())).build()); - DISPATCH.put(IllegalArgumentException.class, e -> - Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) - .build()); - DISPATCH.put(IOException.class, e -> - Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) - .build()); - DISPATCH.put(BadRequestException.class, e -> - Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) - .build()); - DISPATCH.put(MalformedJsonException.class, e -> - Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) - .build()); - DISPATCH.put(JsonSyntaxException.class, e -> - Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) - .build()); - DISPATCH.put(NotAuthorizedException.class, e -> - Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.UNAUTHORIZED.getStatusCode())) - .build()); - DISPATCH.put(ForbiddenException.class, e -> - Response.status(Response.Status.FORBIDDEN).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.FORBIDDEN.getStatusCode())).build()); - DISPATCH.put(NotFoundException.class, e -> - Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.NOT_FOUND.getStatusCode())).build()); - DISPATCH.put(UnknownIdentifierException.class, e -> - Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON) - .entity(new Error(e.getMessage(), Response.Status.NOT_FOUND.getStatusCode())).build()); - DISPATCH.put(UnableToExecuteStatementException.class, - Resource::unableToExecuteExceptionHandler); - DISPATCH.put(PSQLException.class, - Resource::unableToExecuteExceptionHandler); - DISPATCH.put(SQLSyntaxErrorException.class, e -> - errorLoggedExceptionHandler(e, - new Error("Database Error", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()))); - DISPATCH.put(SQLException.class, e -> - errorLoggedExceptionHandler(e, - new Error("Database Error", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()))); - DISPATCH.put(Exception.class, e -> - errorLoggedExceptionHandler(e, - new Error(Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), - Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()))); + DISPATCH.put( + SubmittedDARCannotBeEditedException.class, + e -> + Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) + .build()); + DISPATCH.put( + LibraryCardRequiredException.class, + e -> + Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) + .build()); + DISPATCH.put( + NIHComplianceRuleException.class, + e -> + Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) + .build()); + DISPATCH.put( + ConsentConflictException.class, + e -> + Response.status(Response.Status.CONFLICT) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.CONFLICT.getStatusCode())) + .build()); + DISPATCH.put( + UnprocessableEntityException.class, + e -> + Response.status(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)) + .build()); + DISPATCH.put( + UnsupportedOperationException.class, + e -> + Response.status(Response.Status.CONFLICT) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.CONFLICT.getStatusCode())) + .build()); + DISPATCH.put( + IllegalArgumentException.class, + e -> + Response.status(Response.Status.BAD_REQUEST) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) + .build()); + DISPATCH.put( + IOException.class, + e -> + Response.status(Response.Status.BAD_REQUEST) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) + .build()); + DISPATCH.put( + BadRequestException.class, + e -> + Response.status(Response.Status.BAD_REQUEST) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) + .build()); + DISPATCH.put( + MalformedJsonException.class, + e -> + Response.status(Response.Status.BAD_REQUEST) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) + .build()); + DISPATCH.put( + JsonSyntaxException.class, + e -> + Response.status(Response.Status.BAD_REQUEST) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.BAD_REQUEST.getStatusCode())) + .build()); + DISPATCH.put( + NotAuthorizedException.class, + e -> + Response.status(Response.Status.UNAUTHORIZED) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.UNAUTHORIZED.getStatusCode())) + .build()); + DISPATCH.put( + ForbiddenException.class, + e -> + Response.status(Response.Status.FORBIDDEN) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.FORBIDDEN.getStatusCode())) + .build()); + DISPATCH.put( + NotFoundException.class, + e -> + Response.status(Response.Status.NOT_FOUND) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.NOT_FOUND.getStatusCode())) + .build()); + DISPATCH.put( + UnknownIdentifierException.class, + e -> + Response.status(Response.Status.NOT_FOUND) + .type(MediaType.APPLICATION_JSON) + .entity(new Error(e.getMessage(), Response.Status.NOT_FOUND.getStatusCode())) + .build()); + DISPATCH.put( + UnableToExecuteStatementException.class, Resource::unableToExecuteExceptionHandler); + DISPATCH.put(PSQLException.class, Resource::unableToExecuteExceptionHandler); + DISPATCH.put( + SQLSyntaxErrorException.class, + e -> + errorLoggedExceptionHandler( + e, + new Error( + "Database Error", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()))); + DISPATCH.put( + SQLException.class, + e -> + errorLoggedExceptionHandler( + e, + new Error( + "Database Error", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()))); + DISPATCH.put( + Exception.class, + e -> + errorLoggedExceptionHandler( + e, + new Error( + Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), + Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()))); } private static Response errorLoggedExceptionHandler(Exception e, Error error) { @@ -157,9 +217,9 @@ private static Response errorLoggedExceptionHandler(Exception e, Error error) { return Response.serverError().type(MediaType.APPLICATION_JSON).entity(error).build(); } - //Helper method to process generic JDBI Postgres exceptions for responses + // Helper method to process generic JDBI Postgres exceptions for responses protected static Response unableToExecuteExceptionHandler(Exception e) { - //default status definition + // default status definition LoggerFactory.getLogger(Resource.class.getName()).error(e.getMessage()); // static makes using the interface less flexible Sentry.captureEvent(new SentryEvent(e)); @@ -174,7 +234,7 @@ protected static Response unableToExecuteExceptionHandler(Exception e) { } } } catch (Exception error) { - //no need to handle, default status already assigned + // no need to handle, default status already assigned } int statusCode = status.getLeft(); @@ -194,13 +254,16 @@ protected Response createExceptionResponse(Exception e) { return handler.handle(e); } else { logException(e); - return Response.serverError().type(MediaType.APPLICATION_JSON).entity( + return Response.serverError() + .type(MediaType.APPLICATION_JSON) + .entity( new Error(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())) .build(); } } catch (Throwable t) { logThrowable(t); - return Response.serverError().type(MediaType.APPLICATION_JSON) + return Response.serverError() + .type(MediaType.APPLICATION_JSON) .entity(new Error(e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())) .build(); } @@ -219,15 +282,17 @@ StreamingOutput createStreamingOutput(InputStream inputStream) { protected void validateFileDetails(ContentDisposition contentDisposition) { FileValidator validator = new FileValidator(); - boolean validName = validator.isValidFileName("validating uploaded file name", - contentDisposition.getFileName(), true); + boolean validName = + validator.isValidFileName( + "validating uploaded file name", contentDisposition.getFileName(), true); if (!validName) { throw new IllegalArgumentException("File name is invalid"); } boolean validSize = validator.getMaxFileUploadSize() >= contentDisposition.getSize(); if (!validSize) { throw new IllegalArgumentException( - "File size is invalid. Max size is: " + validator.getMaxFileUploadSize() / 1000000 + "File size is invalid. Max size is: " + + validator.getMaxFileUploadSize() / 1000000 + " MB"); } } @@ -236,23 +301,23 @@ protected void validateFileDetails(ContentDisposition contentDisposition) { * Validate that the current authenticated user can access this resource. If the user has one of * the provided roles, then access is allowed. If not, then the authenticated user must have the * same identity as the `userId` parameter they are requesting information for. - *

- * Typically, we use this to ensure that a non-privileged user is the creator of an entity. In + * + *

Typically, we use this to ensure that a non-privileged user is the creator of an entity. In * those cases, pass in an empty list of privileged roles. - *

- * Privileged users such as admins, chairpersons, and members, may be allowed access to some + * + *

Privileged users such as admins, chairpersons, and members, may be allowed access to some * resources even if they are not the creator/owner. * * @param privilegedRoles List of privileged UserRoles enums - * @param authedUser The authenticated User - * @param userId The user id that the authenticated user is requesting access for + * @param authedUser The authenticated User + * @param userId The user id that the authenticated user is requesting access for */ - void validateAuthedRoleUser(final List privilegedRoles, final User authedUser, - final Integer userId) { - List authedRoleIds = privilegedRoles.stream(). - map(UserRoles::getRoleId).toList(); - boolean authedUserHasRole = authedUser.getRoles().stream(). - anyMatch(userRole -> authedRoleIds.contains(userRole.getRoleId())); + void validateAuthedRoleUser( + final List privilegedRoles, final User authedUser, final Integer userId) { + List authedRoleIds = privilegedRoles.stream().map(UserRoles::getRoleId).toList(); + boolean authedUserHasRole = + authedUser.getRoles().stream() + .anyMatch(userRole -> authedRoleIds.contains(userRole.getRoleId())); if (!authedUserHasRole && !authedUser.getUserId().equals(userId)) { throw new ForbiddenException("User does not have permission"); } @@ -262,11 +327,11 @@ void validateAuthedRoleUser(final List privilegedRoles, final User au * Validate that the user has the actual role name provided. This is useful for determining when a * user hits an endpoint that is permitted to multiple different roles and is requesting a * role-specific view of a data entity. - *

- * In these cases, we need to make sure that the role name provided is a real one and that the + * + *

In these cases, we need to make sure that the role name provided is a real one and that the * user actually has that role to prevent escalated privilege violations. * - * @param user The User + * @param user The User * @param roleName The UserRole name * @return the user's role */ @@ -294,7 +359,7 @@ protected String unmarshal(Object o) { * * @param multipart Form data * @return Map of file body parts, where the key is the name of the field and the value is the - * body part including the file(s). + * body part including the file(s). */ protected Map extractFilesFromMultiPart(FormDataMultiPart multipart) { if (Objects.isNull(multipart)) { diff --git a/src/main/java/org/broadinstitute/consent/http/resources/SamResource.java b/src/main/java/org/broadinstitute/consent/http/resources/SamResource.java index f402417271..fd4c0cf77b 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/SamResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/SamResource.java @@ -111,7 +111,6 @@ public Response postSelfTos(@Auth DuosUser duosUser) { } } - @Path("register/self/tos") @DELETE @Produces("application/json") diff --git a/src/main/java/org/broadinstitute/consent/http/resources/SchemaResource.java b/src/main/java/org/broadinstitute/consent/http/resources/SchemaResource.java index e507ae6ca7..df0e992ac8 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/SchemaResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/SchemaResource.java @@ -25,5 +25,4 @@ public Response getDatasetRegistrationSchemaV1() { String content = jsonSchemaUtil.getDatasetRegistrationSchemaV1(); return Response.ok().entity(content).type(MediaType.APPLICATION_JSON).build(); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/StatusResource.java b/src/main/java/org/broadinstitute/consent/http/resources/StatusResource.java index 0c4187753f..3a96871a45 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/StatusResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/StatusResource.java @@ -31,17 +31,20 @@ public StatusResource(HealthCheckRegistry healthChecks) { @Produces("application/json") public Response getStatus() { Map results = healthChecks.runHealthChecks(); - HealthCheck.Result postgresql = results.getOrDefault(DB_ENV, - HealthCheck.Result.unhealthy("Unable to access postgresql database")); + HealthCheck.Result postgresql = + results.getOrDefault( + DB_ENV, HealthCheck.Result.unhealthy("Unable to access postgresql database")); if (postgresql.isHealthy()) { return Response.ok(formatResults(results)).build(); } else { - results.entrySet(). - stream(). - filter(e -> !e.getValue().isHealthy()). - forEach(e -> logWarn( - "Error in service " + e.getKey() + ": " + formatResultError(e.getValue()))); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(formatResults(results)) + results.entrySet().stream() + .filter(e -> !e.getValue().isHealthy()) + .forEach( + e -> + logWarn( + "Error in service " + e.getKey() + ": " + formatResultError(e.getValue()))); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(formatResults(results)) .build(); } } @@ -51,27 +54,37 @@ private Map formatResults(Map result // add all other entries after that. Map formattedResults = new LinkedHashMap<>(); boolean healthy = false; - HealthCheck.Result postgresql = results.getOrDefault(DB_ENV, - HealthCheck.Result.unhealthy("Unable to access postgresql database")); + HealthCheck.Result postgresql = + results.getOrDefault( + DB_ENV, HealthCheck.Result.unhealthy("Unable to access postgresql database")); if (postgresql.isHealthy()) { healthy = true; } formattedResults.put(OK, healthy); - HealthCheck.Result gcs = results.getOrDefault(ConsentApplication.GCS_CHECK, - HealthCheck.Result.unhealthy("Unable to access Google Cloud Storage")); - HealthCheck.Result elasticSearch = results.getOrDefault(ConsentApplication.ES_CHECK, - HealthCheck.Result.unhealthy("Unable to access Elastic Search")); - HealthCheck.Result ontology = results.getOrDefault(ConsentApplication.ONTOLOGY_CHECK, - HealthCheck.Result.unhealthy("Unable to access Ontology")); - HealthCheck.Result sam = results.getOrDefault(ConsentApplication.SAM_CHECK, - HealthCheck.Result.unhealthy("Unable to access Sam")); - HealthCheck.Result sendGrid = results.getOrDefault(ConsentApplication.SG_CHECK, - HealthCheck.Result.unhealthy("Unable to access SendGrid")); - boolean degraded = (!gcs.isHealthy() - || !elasticSearch.isHealthy() - || !ontology.isHealthy() - || !sam.isHealthy() - || !sendGrid.isHealthy()); + HealthCheck.Result gcs = + results.getOrDefault( + ConsentApplication.GCS_CHECK, + HealthCheck.Result.unhealthy("Unable to access Google Cloud Storage")); + HealthCheck.Result elasticSearch = + results.getOrDefault( + ConsentApplication.ES_CHECK, + HealthCheck.Result.unhealthy("Unable to access Elastic Search")); + HealthCheck.Result ontology = + results.getOrDefault( + ConsentApplication.ONTOLOGY_CHECK, + HealthCheck.Result.unhealthy("Unable to access Ontology")); + HealthCheck.Result sam = + results.getOrDefault( + ConsentApplication.SAM_CHECK, HealthCheck.Result.unhealthy("Unable to access Sam")); + HealthCheck.Result sendGrid = + results.getOrDefault( + ConsentApplication.SG_CHECK, HealthCheck.Result.unhealthy("Unable to access SendGrid")); + boolean degraded = + (!gcs.isHealthy() + || !elasticSearch.isHealthy() + || !ontology.isHealthy() + || !sam.isHealthy() + || !sendGrid.isHealthy()); formattedResults.put(DEGRADED, degraded); formattedResults.put(SYSTEMS, results); return formattedResults; @@ -85,5 +98,4 @@ private String formatResultError(HealthCheck.Result result) { } return "Healthcheck Result Error"; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java b/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java index c15b214c26..02e581dedc 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/StudyResource.java @@ -55,9 +55,10 @@ public class StudyResource extends Resource { private final UserService userService; private final ElasticSearchService elasticSearchService; - @Inject - public StudyResource(DatasetService datasetService, UserService userService, + public StudyResource( + DatasetService datasetService, + UserService userService, DatasetRegistrationService datasetRegistrationService, ElasticSearchService elasticSearchService) { this.datasetService = datasetService; @@ -76,8 +77,10 @@ public StudyResource(DatasetService datasetService, UserService userService, @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN}) - public Response convertToStudy(@Auth DuosUser duosUser, - @PathParam("datasetIdentifier") String datasetIdentifier, String json) { + public Response convertToStudy( + @Auth DuosUser duosUser, + @PathParam("datasetIdentifier") String datasetIdentifier, + String json) { try { User user = duosUser.getUser(); Dataset dataset = datasetService.findDatasetByIdentifier(user, datasetIdentifier); @@ -98,8 +101,8 @@ public Response convertToStudy(@Auth DuosUser duosUser, @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN}) - public Response updateCustodians(@Auth AuthUser authUser, - @PathParam("studyId") Integer studyId, String json) { + public Response updateCustodians( + @Auth AuthUser authUser, @PathParam("studyId") Integer studyId, String json) { try { User user = userService.findUserByEmail(authUser.getEmail()); Gson gson = new Gson(); @@ -147,30 +150,30 @@ public Response deleteStudyById(@Auth AuthUser authUser, @PathParam("studyId") I } // If the user is not an admin, ensure that they are the study/dataset creator - if (!user.hasUserRole(UserRoles.ADMIN) && (!Objects.equals(study.getCreateUserId(), - user.getUserId()))) { + if (!user.hasUserRole(UserRoles.ADMIN) + && (!Objects.equals(study.getCreateUserId(), user.getUserId()))) { throw new NotFoundException("Study not found"); } boolean deletable = - (study.getDatasets() == null || study.getDatasets().isEmpty()) || study.getDatasets() - .stream() - .allMatch(Dataset::getDeletable); + (study.getDatasets() == null || study.getDatasets().isEmpty()) + || study.getDatasets().stream().allMatch(Dataset::getDeletable); if (!deletable) { throw new BadRequestException("Study has datasets that are in use and cannot be deleted."); } Set studyDatasetIds = study.getDatasetIds(); datasetService.deleteStudy(study, user); // Remove from ES index - studyDatasetIds.forEach(id -> { - try (Response indexResponse = elasticSearchService.deleteIndex(id, user.getUserId())) { - if (indexResponse.getStatus() >= Status.BAD_REQUEST.getStatusCode()) { - logWarn("Non-OK response when deleting index for dataset with id: " + id); - } - } catch (IOException e) { - logException(e); - } - }); + studyDatasetIds.forEach( + id -> { + try (Response indexResponse = elasticSearchService.deleteIndex(id, user.getUserId())) { + if (indexResponse.getStatus() >= Status.BAD_REQUEST.getStatusCode()) { + logWarn("Non-OK response when deleting index for dataset with id: " + id); + } + } catch (IOException e) { + logException(e); + } + }); return Response.ok().build(); } catch (Exception e) { return createExceptionResponse(e); @@ -182,15 +185,15 @@ public Response deleteStudyById(@Auth AuthUser authUser, @PathParam("studyId") I @Produces(MediaType.APPLICATION_JSON) @PermitAll @Timed - public Response getRegistrationFromStudy(@Auth DuosUser duosUser, - @PathParam("studyId") Integer studyId) { + public Response getRegistrationFromStudy( + @Auth DuosUser duosUser, @PathParam("studyId") Integer studyId) { try { Study study = datasetService.getStudyWithDatasetsById(duosUser.getUser(), studyId); checkPublicVisibilityForUser(study, duosUser.getUser()); List datasets = Objects.nonNull(study.getDatasets()) ? study.getDatasets().stream().toList() : List.of(); - DatasetRegistrationSchemaV1 registration = new DatasetRegistrationSchemaV1Builder().build( - study, datasets); + DatasetRegistrationSchemaV1 registration = + new DatasetRegistrationSchemaV1Builder().build(study, datasets); String entity = GsonUtil.buildGsonNullSerializer().toJson(registration); return Response.ok().entity(entity).build(); } catch (Exception e) { @@ -223,18 +226,16 @@ public Response updateStudyByRegistration( // Manually validate the schema from an editing context. Validation with the schema tools // enforces it in a creation context but doesn't work for editing purposes. - DatasetRegistrationSchemaV1UpdateValidator updateValidator = new DatasetRegistrationSchemaV1UpdateValidator( - datasetService); + DatasetRegistrationSchemaV1UpdateValidator updateValidator = + new DatasetRegistrationSchemaV1UpdateValidator(datasetService); DatasetRegistrationSchemaV1 registration = updateValidator.deserializeRegistration(json); if (updateValidator.validate(existingStudy, registration)) { // Update study from registration Map files = extractFilesFromMultiPart(multipart); - Study updatedStudy = datasetRegistrationService.updateStudyFromRegistration( - studyId, - registration, - user, - files); + Study updatedStudy = + datasetRegistrationService.updateStudyFromRegistration( + studyId, registration, user, files); try (Response indexResponse = elasticSearchService.indexStudy(studyId, user)) { if (indexResponse.getStatus() >= Status.BAD_REQUEST.getStatusCode()) { logWarn("Non-OK response when reindexing study with id: " + studyId); diff --git a/src/main/java/org/broadinstitute/consent/http/resources/SupportResource.java b/src/main/java/org/broadinstitute/consent/http/resources/SupportResource.java index 2e1ccf5c51..e52cdbf7d8 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/SupportResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/SupportResource.java @@ -62,5 +62,4 @@ public Response postUpload(byte[] content) { return createExceptionResponse(e); } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/SwaggerResource.java b/src/main/java/org/broadinstitute/consent/http/resources/SwaggerResource.java index 086d109f5a..e105d1b9da 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/SwaggerResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/SwaggerResource.java @@ -16,11 +16,12 @@ @Path("/") public class SwaggerResource implements ConsentLogger { - private static final String DEFAULT_SWAGGER_UI_PATH = "META-INF/resources/webjars/swagger-ui/latest/"; + private static final String DEFAULT_SWAGGER_UI_PATH = + "META-INF/resources/webjars/swagger-ui/latest/"; private static final String MEDIA_TYPE_GIF = new MediaType("image", "gif").toString(); protected static final String MEDIA_TYPE_CSS = new MediaType("text", "css").toString(); - protected static final String MEDIA_TYPE_JS = new MediaType("application", - "javascript").toString(); + protected static final String MEDIA_TYPE_JS = + new MediaType("application", "javascript").toString(); protected static final String MEDIA_TYPE_PNG = new MediaType("image", "png").toString(); private final GoogleOAuth2Config config; @@ -33,8 +34,8 @@ public SwaggerResource(GoogleOAuth2Config config) { } /** - * Load the Swagger UI path from mvn.properties, which is populated from pom.xml - * during the Maven build process. + * Load the Swagger UI path from mvn.properties, which is populated from pom.xml during the Maven + * build process. */ private String loadSwaggerUiPath() { try (InputStream is = getClass().getResourceAsStream("/mvn.properties")) { @@ -92,7 +93,8 @@ private String getIndex() { } private String getInitializer() { - String initString = """ + String initString = + """ window.onload = function() { const ui = SwaggerUIBundle({ syntaxHighlight: false, diff --git a/src/main/java/org/broadinstitute/consent/http/resources/TDRResource.java b/src/main/java/org/broadinstitute/consent/http/resources/TDRResource.java index 1c7b59ef8b..e5332be1b0 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/TDRResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/TDRResource.java @@ -18,14 +18,12 @@ import org.broadinstitute.consent.http.service.DatasetService; import org.broadinstitute.consent.http.service.TDRService; - @Path("api/tdr") public class TDRResource extends Resource { private final TDRService tdrService; private final DatasetService datasetService; - @Inject public TDRResource(TDRService tdrService, DatasetService datasetService) { this.datasetService = datasetService; @@ -37,10 +35,11 @@ public TDRResource(TDRService tdrService, DatasetService datasetService) { @RolesAllowed({ADMIN, SERVICE_ACCOUNT}) @Path("/{identifier}/approved/users") @Timed - public Response getApprovedUsers(@Auth DuosUser duosUser, - @PathParam("identifier") String identifier) { + public Response getApprovedUsers( + @Auth DuosUser duosUser, @PathParam("identifier") String identifier) { try { - Dataset dataset = datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), identifier, false); + Dataset dataset = + datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), identifier, false); if (Objects.isNull(dataset)) { throw new NotFoundException("Could not find dataset " + identifier); } @@ -57,10 +56,11 @@ public Response getApprovedUsers(@Auth DuosUser duosUser, @PermitAll @Path("/{identifier}") @Timed - public Response getDatasetByIdentifier(@Auth DuosUser duosUser, - @PathParam("identifier") String identifier) { + public Response getDatasetByIdentifier( + @Auth DuosUser duosUser, @PathParam("identifier") String identifier) { try { - Dataset dataset = datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), identifier, true); + Dataset dataset = + datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), identifier, true); if (Objects.isNull(dataset)) { throw new NotFoundException("Could not find dataset " + identifier); } @@ -70,5 +70,4 @@ public Response getDatasetByIdentifier(@Auth DuosUser duosUser, return createExceptionResponse(e); } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java b/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java index c5193748fb..d87e1618b4 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/UserResource.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.resources; - import com.codahale.metrics.annotation.Timed; import com.google.api.client.http.HttpStatusCodes; import com.google.gson.Gson; @@ -61,8 +60,11 @@ public class UserResource extends Resource { private final NihService nihService; @Inject - public UserResource(SamService samService, UserService userService, - DatasetService datasetService, AcknowledgementService acknowledgementService, + public UserResource( + SamService samService, + UserService userService, + DatasetService datasetService, + AcknowledgementService acknowledgementService, NihService nihService) { this.samService = samService; this.userService = userService; @@ -80,9 +82,9 @@ public Response getUsers(@Auth AuthUser authUser, @PathParam("roleName") String User user = userService.findUserByEmail(authUser.getEmail()); boolean valid = UserRoles.isValidRole(roleName); if (valid) { - //if there is a valid roleName but it is not SO or Admin then throw an exception - if (!roleName.equals(UserRoles.ADMIN.getRoleName()) && !roleName.equals( - UserRoles.SIGNINGOFFICIAL.getRoleName())) { + // if there is a valid roleName but it is not SO or Admin then throw an exception + if (!roleName.equals(UserRoles.ADMIN.getRoleName()) + && !roleName.equals(UserRoles.SIGNINGOFFICIAL.getRoleName())) { throw new BadRequestException("Unsupported role name: " + roleName); } if (!user.hasUserRole(UserRoles.getUserRoleFromName(roleName))) { @@ -132,10 +134,8 @@ public Response getDatasetsFromUserDacs(@Auth AuthUser authUser) { public Response getDatasetsFromUserDacsV2(@Auth AuthUser authUser) { try { User user = userService.findUserByEmail(authUser.getEmail()); - List dacIds = user.getRoles().stream() - .map(UserRole::getDacId) - .filter(Objects::nonNull) - .toList(); + List dacIds = + user.getRoles().stream().map(UserRole::getDacId).filter(Objects::nonNull).toList(); List datasets = dacIds.isEmpty() ? List.of() : datasetService.findDatasetListByDacIds(dacIds); if (datasets.isEmpty()) { @@ -198,8 +198,8 @@ public Response update(@Auth DuosUser duosUser, @PathParam("id") Integer userId, // Ensure that we have a real user with this ID, fail if we do not. userService.findUserById(userId); User updatedUser = userService.updateUserFieldsById(userUpdateFields, userId); - JsonObject jsonUser = userService.findUserWithPropertiesByIdAsJsonObject(duosUser, - updatedUser.getUserId()); + JsonObject jsonUser = + userService.findUserWithPropertiesByIdAsJsonObject(duosUser, updatedUser.getUserId()); return Response.ok().entity(gson.toJson(jsonUser)).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -215,14 +215,14 @@ public Response updateSelf(@Auth DuosUser duosUser, @Context UriInfo info, Strin User user = duosUser.getUser(); UserUpdateFields userUpdateFields = gson.fromJson(json, UserUpdateFields.class); - if (Objects.nonNull(userUpdateFields.getUserRoleIds()) && !user.hasUserRole( - UserRoles.ADMIN)) { + if (Objects.nonNull(userUpdateFields.getUserRoleIds()) + && !user.hasUserRole(UserRoles.ADMIN)) { throw new BadRequestException("Cannot change user's roles."); } user = userService.updateUserFieldsById(userUpdateFields, user.getUserId()); - JsonObject jsonUser = userService.findUserWithPropertiesByIdAsJsonObject(duosUser, - user.getUserId()); + JsonObject jsonUser = + userService.findUserWithPropertiesByIdAsJsonObject(duosUser, user.getUserId()); return Response.ok().entity(gson.toJson(jsonUser)).build(); } catch (Exception e) { @@ -234,7 +234,9 @@ public Response updateSelf(@Auth DuosUser duosUser, @Context UriInfo info, Strin @Path("/{userId}/{roleId}") @Produces("application/json") @RolesAllowed({ADMIN, SIGNINGOFFICIAL}) - public Response addRoleToUser(@Auth DuosUser duosUser, @PathParam("userId") Integer userId, + public Response addRoleToUser( + @Auth DuosUser duosUser, + @PathParam("userId") Integer userId, @PathParam("roleId") Integer roleId) { UserRoles targetRole = UserRoles.getUserRoleFromId(roleId); if (Objects.isNull(targetRole)) { @@ -245,8 +247,8 @@ public Response addRoleToUser(@Auth DuosUser duosUser, @PathParam("userId") Inte User activeUser = duosUser.getUser(); User user = userService.findUserById(userId); List currentUserRoleIds = user.getUserRoleIdsFromUser(); - if ((activeUser.hasUserRole(UserRoles.ADMIN) && UserRoles.isValidNonDACRoleId(targetRole)) || - signingOfficialMeetsRequirements(targetRole, activeUser, user)) { + if ((activeUser.hasUserRole(UserRoles.ADMIN) && UserRoles.isValidNonDACRoleId(targetRole)) + || signingOfficialMeetsRequirements(targetRole, activeUser, user)) { if (!currentUserRoleIds.contains(roleId)) { userService.insertRoleAndInstitutionForUser(role, user); return getUserResponse(duosUser, userId); @@ -261,13 +263,13 @@ public Response addRoleToUser(@Auth DuosUser duosUser, @PathParam("userId") Inte } } - private static boolean signingOfficialMeetsRequirements(UserRoles role, User activeUser, - User user) { + private static boolean signingOfficialMeetsRequirements( + UserRoles role, User activeUser, User user) { return activeUser.hasUserRole(UserRoles.SIGNINGOFFICIAL) && activeUser.getInstitutionId() != null && UserRoles.isValidSoAdjustableRoleId(role) - && (user.getInstitutionId() == null || user.getInstitutionId() - .equals(activeUser.getInstitutionId())); + && (user.getInstitutionId() == null + || user.getInstitutionId().equals(activeUser.getInstitutionId())); } private Response getUserResponse(DuosUser duosUser, Integer userId) { @@ -279,7 +281,9 @@ private Response getUserResponse(DuosUser duosUser, Integer userId) { @Path("/{userId}/{roleId}") @Produces("application/json") @RolesAllowed({ADMIN, SIGNINGOFFICIAL}) - public Response deleteRoleFromUser(@Auth DuosUser duosUser, @PathParam("userId") Integer userId, + public Response deleteRoleFromUser( + @Auth DuosUser duosUser, + @PathParam("userId") Integer userId, @PathParam("roleId") Integer roleId) { UserRoles targetRole = UserRoles.getUserRoleFromId(roleId); if (Objects.isNull(targetRole)) { @@ -317,8 +321,8 @@ public Response deleteRoleFromUser(@Auth DuosUser duosUser, @PathParam("userId") } } - private Response doDelete(DuosUser duosUser, Integer userId, Integer roleId, User activeUser, - User user) { + private Response doDelete( + DuosUser duosUser, Integer userId, Integer roleId, User activeUser, User user) { List currentUserRoleIds = user.getUserRoleIdsFromUser(); if (!currentUserRoleIds.contains(roleId)) { JsonObject userJson = userService.findUserWithPropertiesByIdAsJsonObject(duosUser, userId); @@ -335,18 +339,17 @@ private Response doDelete(DuosUser duosUser, Integer userId, Integer roleId, Use @PermitAll public Response createResearcher(@Context UriInfo info, @Auth AuthUser authUser) { if (authUser == null || authUser.getEmail() == null || authUser.getName() == null) { - return Response. - status(Response.Status.BAD_REQUEST). - entity(new Error("Unable to verify google identity", - Response.Status.BAD_REQUEST.getStatusCode())). - build(); + return Response.status(Response.Status.BAD_REQUEST) + .entity( + new Error( + "Unable to verify google identity", Response.Status.BAD_REQUEST.getStatusCode())) + .build(); } try { if (userService.findUserByEmail(authUser.getEmail()) != null) { - return Response. - status(Response.Status.CONFLICT). - entity(new Error("Registered user exists", Response.Status.CONFLICT.getStatusCode())). - build(); + return Response.status(Response.Status.CONFLICT) + .entity(new Error("Registered user exists", Response.Status.CONFLICT.getStatusCode())) + .build(); } } catch (NotFoundException nfe) { // no-op, we expect to not find the new user in this case. @@ -359,7 +362,8 @@ public Response createResearcher(@Context UriInfo info, @Auth AuthUser authUser) URI uri; user = userService.createUser(user); uri = info.getRequestUriBuilder().path("{email}").build(user.getEmail()); - return Response.created(new URI(uri.toString().replace("user", "dacuser"))).entity(user) + return Response.created(new URI(uri.toString().replace("user", "dacuser"))) + .entity(user) .build(); } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR) @@ -376,8 +380,8 @@ public Response getSOsForInstitution(@Auth AuthUser authUser) { try { User user = userService.findUserByEmail(authUser.getEmail()); if (Objects.nonNull(user.getInstitutionId())) { - List signingOfficials = userService.findSOsByInstitutionId( - user.getInstitutionId()); + List signingOfficials = + userService.findSOsByInstitutionId(user.getInstitutionId()); return Response.ok().entity(signingOfficials).build(); } return Response.ok().entity(Collections.emptyList()).build(); @@ -393,8 +397,8 @@ public Response getSOsForInstitution(@Auth AuthUser authUser) { public Response getUserAcknowledgements(@Auth DuosUser duosUser) { try { User user = duosUser.getUser(); - Map acknowledgementMap = acknowledgementService.findAcknowledgementsForUser( - user); + Map acknowledgementMap = + acknowledgementService.findAcknowledgementsForUser(user); return Response.ok().entity(acknowledgementMap).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -461,8 +465,8 @@ public Response postAcknowledgements(@Auth DuosUser duosUser, String json) { } try { - Map acknowledgementMap = acknowledgementService.makeAcknowledgements( - keys, user); + Map acknowledgementMap = + acknowledgementService.makeAcknowledgements(keys, user); return Response.ok().entity(acknowledgementMap).build(); } catch (Exception e) { return createExceptionResponse(e); @@ -482,6 +486,4 @@ public Response getApprovedDatasets(@Auth DuosUser duosUser) { return createExceptionResponse(e); } } - - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/VersionResource.java b/src/main/java/org/broadinstitute/consent/http/resources/VersionResource.java index a066e76469..6337fd50c4 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/VersionResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/VersionResource.java @@ -49,10 +49,10 @@ private static class Version { this.version = "error"; } else { JsonObject jsonObject = new Gson().fromJson(props, JsonObject.class); - String longHash = Optional - .ofNullable(jsonObject.get("git.commit.id")) - .orElse(new JsonPrimitive("error")) - .getAsString(); + String longHash = + Optional.ofNullable(jsonObject.get("git.commit.id")) + .orElse(new JsonPrimitive("error")) + .getAsString(); String shortHash = longHash.substring(0, Math.min(longHash.length(), 12)); JsonElement buildVersion = jsonObject.get("git.build.version"); if (Objects.nonNull(buildVersion)) { @@ -70,5 +70,4 @@ public String getVersion() { return version; } } - } diff --git a/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java b/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java index bb1b2608fc..5167fedfd5 100644 --- a/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java +++ b/src/main/java/org/broadinstitute/consent/http/resources/VoteResource.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.resources; - import com.google.gson.Gson; import com.google.inject.Inject; import io.dropwizard.auth.Auth; @@ -37,8 +36,8 @@ public class VoteResource extends Resource { private final Gson gson = new Gson(); @Inject - public VoteResource(UserService userService, VoteService voteService, - ElectionService electionService) { + public VoteResource( + UserService userService, VoteService voteService, ElectionService electionService) { this.userService = userService; this.voteService = voteService; this.electionService = electionService; @@ -47,38 +46,34 @@ public VoteResource(UserService userService, VoteService voteService, /** * This API will take a boolean vote value as a query param and apply it to the list of vote ids * passed in as a list of integer vote ids. - *

- * Error cases are: 1. Vote is null 2. Auth user is not the owner of all votes being updated 3. No - * votes match the list of ids provided + * + *

Error cases are: 1. Vote is null 2. Auth user is not the owner of all votes being updated 3. + * No votes match the list of ids provided * * @param authUser The AuthUser - * @param request The request - * @param json The boolean value to update votes to, string value for all rationales, and list - * of vote ids, in json format + * @param request The request + * @param json The boolean value to update votes to, string value for all rationales, and list of + * vote ids, in json format * @return Response with results of the update. */ @PUT @Consumes("application/json") @Produces("application/json") @RolesAllowed({CHAIRPERSON, MEMBER}) - public Response updateVotes( - @Auth AuthUser authUser, - @Context Request request, - String json) { + public Response updateVotes(@Auth AuthUser authUser, @Context Request request, String json) { Vote.VoteUpdate voteUpdate; try { voteUpdate = gson.fromJson(json, Vote.VoteUpdate.class); } catch (Exception e) { return createExceptionResponse( - new BadRequestException("Unable to parse required vote update information") - ); + new BadRequestException("Unable to parse required vote update information")); } - if (Objects.isNull(voteUpdate) || Objects.isNull(voteUpdate.getVoteIds()) + if (Objects.isNull(voteUpdate) + || Objects.isNull(voteUpdate.getVoteIds()) || voteUpdate.getVoteIds().isEmpty()) { return createExceptionResponse( - new BadRequestException("Unable to update empty vote ids: " + json) - ); + new BadRequestException("Unable to update empty vote ids: " + json)); } if (Objects.isNull(voteUpdate.getVote())) { return createExceptionResponse( @@ -93,8 +88,8 @@ public Response updateVotes( // Validate that the user is only updating their own votes: User user = userService.findUserByEmail(authUser.getEmail()); - boolean authed = votes.stream().map(Vote::getUserId) - .allMatch(id -> id.equals(user.getUserId())); + boolean authed = + votes.stream().map(Vote::getUserId).allMatch(id -> id.equals(user.getUserId())); if (!authed) { return createExceptionResponse(new NotFoundException()); } @@ -104,12 +99,18 @@ public Response updateVotes( voteUpdateLCCheck(votes); } - if (votes.stream().anyMatch(vote -> vote.getType() != null && vote.getType().equalsIgnoreCase(VoteType.RADAR_APPROVE.getValue()))) { - return createExceptionResponse(new BadRequestException("Manual Rule Automated DAR (RADAR) Approval is not permitted")); + if (votes.stream() + .anyMatch( + vote -> + vote.getType() != null + && vote.getType().equalsIgnoreCase(VoteType.RADAR_APPROVE.getValue()))) { + return createExceptionResponse( + new BadRequestException("Manual Rule Automated DAR (RADAR) Approval is not permitted")); } - List updatedVotes = voteService.updateVotesWithValue(votes, voteUpdate.getVote(), - voteUpdate.getRationale(), user); + List updatedVotes = + voteService.updateVotesWithValue( + votes, voteUpdate.getVote(), voteUpdate.getRationale(), user); voteService.logDARApprovalOrRejection(user, updatedVotes, (ContainerRequest) request); return Response.ok().entity(updatedVotes).build(); } catch (Exception e) { @@ -123,7 +124,7 @@ public Response updateVotes( * OPEN elections. In all cases, one can only update their own votes. * * @param authUser The AuthUser - * @param json The rationale and vote ids to update + * @param json The rationale and vote ids to update * @return Response with results of the update. */ @Path("rationale") @@ -138,14 +139,13 @@ public Response updateVoteRationale(@Auth AuthUser authUser, String json) { update = new Gson().fromJson(json, Vote.RationaleUpdate.class); } catch (Exception e) { return createExceptionResponse( - new BadRequestException("Unable to parse rationale update: " + json) - ); + new BadRequestException("Unable to parse rationale update: " + json)); } - if (Objects.isNull(update) || Objects.isNull(update.getVoteIds()) || update.getVoteIds() - .isEmpty()) { + if (Objects.isNull(update) + || Objects.isNull(update.getVoteIds()) + || update.getVoteIds().isEmpty()) { return createExceptionResponse( - new BadRequestException("Unable to update empty vote ids: " + json) - ); + new BadRequestException("Unable to update empty vote ids: " + json)); } List votes = voteService.findVotesByIds(update.getVoteIds()); if (votes.isEmpty()) { @@ -159,40 +159,45 @@ public Response updateVoteRationale(@Auth AuthUser authUser, String json) { } try { - List updatedVotes = voteService.updateRationaleByVoteIds(update.getVoteIds(), - update.getRationale()); + List updatedVotes = + voteService.updateRationaleByVoteIds(update.getVoteIds(), update.getRationale()); return Response.ok().entity(updatedVotes).build(); } catch (Exception e) { return createExceptionResponse(e); } } - //Private helper function, checks to see if user has library card for chair votes that are getting an incoming "yes" update + // Private helper function, checks to see if user has library card for chair votes that are + // getting an incoming "yes" update private void voteUpdateLCCheck(List votes) { - //filter for chair or final votes - List targetVotes = votes.stream() - .filter(v -> { - String type = v.getType(); - return type.equalsIgnoreCase(VoteType.CHAIRPERSON.getValue()) || type.equalsIgnoreCase( - VoteType.FINAL.getValue()); - }) - .collect(Collectors.toList()); - //if the filtered list is populated, get the vote ids and get the full vote records for those that have type = 'DataAccess' + // filter for chair or final votes + List targetVotes = + votes.stream() + .filter( + v -> { + String type = v.getType(); + return type.equalsIgnoreCase(VoteType.CHAIRPERSON.getValue()) + || type.equalsIgnoreCase(VoteType.FINAL.getValue()); + }) + .collect(Collectors.toList()); + // if the filtered list is populated, get the vote ids and get the full vote records for those + // that have type = 'DataAccess' if (!targetVotes.isEmpty()) { - List voteIds = targetVotes.stream() - .map(Vote::getVoteId) - .collect(Collectors.toList()); - List targetElections = electionService.findElectionsByVoteIdsAndType(voteIds, - ElectionType.DATA_ACCESS.getValue()); - //If DataAccess votes are present, get elections from DARs created by users with LCs + List voteIds = + targetVotes.stream().map(Vote::getVoteId).collect(Collectors.toList()); + List targetElections = + electionService.findElectionsByVoteIdsAndType( + voteIds, ElectionType.DATA_ACCESS.getValue()); + // If DataAccess votes are present, get elections from DARs created by users with LCs if (!targetElections.isEmpty()) { - List targetElectionIds = targetElections.stream() - .map(Election::getElectionId) - .collect(Collectors.toList()); - List electionsWithCardHoldingUsers = electionService.findElectionsWithCardHoldingUsersByElectionIds( - targetElectionIds); - //We want to make sure that each election is associated with a card holding user - //Therefore, if the number of electionsWithCardHoldingUsers does not equal the number of target elections, we can assume that there exists an election where a user does not have a LC + List targetElectionIds = + targetElections.stream().map(Election::getElectionId).collect(Collectors.toList()); + List electionsWithCardHoldingUsers = + electionService.findElectionsWithCardHoldingUsersByElectionIds(targetElectionIds); + // We want to make sure that each election is associated with a card holding user + // Therefore, if the number of electionsWithCardHoldingUsers does not equal the number of + // target elections, we can assume that there exists an election where a user does not have + // a LC if (electionsWithCardHoldingUsers.size() != targetElections.size()) { throw new BadRequestException( "Some Data Access Requests have been submitted by users with no library card"); diff --git a/src/main/java/org/broadinstitute/consent/http/rules/AuditPageResults.java b/src/main/java/org/broadinstitute/consent/http/rules/AuditPageResults.java index c87d3e4e1e..25c9df2444 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/AuditPageResults.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/AuditPageResults.java @@ -4,11 +4,17 @@ public class AuditPageResults { private final List auditRecords; - private final Integer totalRecords; // total number of records that would have been satisfied by the query without pagination. + private final Integer + totalRecords; // total number of records that would have been satisfied by the query without + // pagination. private final Integer pageSize; // number of entries on this page private final Integer page; // page number - public AuditPageResults(List auditRecords, Integer totalRecords, Integer pageSize, Integer page) { + public AuditPageResults( + List auditRecords, + Integer totalRecords, + Integer pageSize, + Integer page) { this.auditRecords = auditRecords; this.totalRecords = totalRecords; this.pageSize = pageSize; diff --git a/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRule.java b/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRule.java index deb2068b20..960bbeacdb 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRule.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRule.java @@ -2,8 +2,12 @@ import java.sql.Timestamp; -public record DACAutomationRule(Integer id, DACAutomationRuleType ruleType, String description, - RuleState ruleState, Timestamp activationDate, Integer enabledByUserId, String displayName, - String userEmail) { - -} +public record DACAutomationRule( + Integer id, + DACAutomationRuleType ruleType, + String description, + RuleState ruleState, + Timestamp activationDate, + Integer enabledByUserId, + String displayName, + String userEmail) {} diff --git a/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRuleAudit.java b/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRuleAudit.java index e40ef8f2e9..ab62e6aa6c 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRuleAudit.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/DACAutomationRuleAudit.java @@ -2,6 +2,9 @@ import java.sql.Timestamp; -public record DACAutomationRuleAudit(RuleAuditAction action, Timestamp actionDate, DACAutomationRuleType rule, String email, String displayName) { - -} +public record DACAutomationRuleAudit( + RuleAuditAction action, + Timestamp actionDate, + DACAutomationRuleType rule, + String email, + String displayName) {} diff --git a/src/main/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1.java b/src/main/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1.java index 829acf47a4..df5aba6703 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1.java @@ -14,5 +14,4 @@ && hasNoModifiers(dataset.getDataUse()) public DACAutomationRuleType getRuleType() { return DACAutomationRuleType.GRU_V1; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1.java b/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1.java index 81910f8e51..b662876177 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1.java @@ -3,10 +3,12 @@ import org.broadinstitute.consent.http.models.DataAccessRequest; import org.broadinstitute.consent.http.models.Dataset; -public class HealthMedicalBioMedicalV1 implements RuleImplementationInterface{ +public class HealthMedicalBioMedicalV1 implements RuleImplementationInterface { @Override - public DACAutomationRuleType getRuleType() { return DACAutomationRuleType.HMB_V1; } + public DACAutomationRuleType getRuleType() { + return DACAutomationRuleType.HMB_V1; + } @Override public boolean compare(Dataset dataset, DataAccessRequest dataAccessRequest) { diff --git a/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1.java b/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1.java index 2d0e3f43d8..dadddfde86 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1.java @@ -6,7 +6,9 @@ public class HealthMedicalBioMedicalWithDiseaseSpecificV1 implements RuleImplementationInterface { @Override - public DACAutomationRuleType getRuleType() { return DACAutomationRuleType.HMB_DSV1;} + public DACAutomationRuleType getRuleType() { + return DACAutomationRuleType.HMB_DSV1; + } @Override public boolean compare(Dataset dataset, DataAccessRequest dataAccessRequest) { diff --git a/src/main/java/org/broadinstitute/consent/http/rules/RuleAuditAction.java b/src/main/java/org/broadinstitute/consent/http/rules/RuleAuditAction.java index 9ca0ebc80c..a5a8df2fb0 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/RuleAuditAction.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/RuleAuditAction.java @@ -3,4 +3,4 @@ public enum RuleAuditAction { REMOVE, ADD -} \ No newline at end of file +} diff --git a/src/main/java/org/broadinstitute/consent/http/rules/RuleImplementationInterface.java b/src/main/java/org/broadinstitute/consent/http/rules/RuleImplementationInterface.java index cad96beffe..ebf749d2fb 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/RuleImplementationInterface.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/RuleImplementationInterface.java @@ -11,6 +11,7 @@ public interface RuleImplementationInterface { DACAutomationRuleType getRuleType(); boolean compare(Dataset dataset, DataAccessRequest dataAccessRequest); + default boolean hasNoModifiers(DataUse data) { if (Boolean.TRUE.equals(data.getCollaboratorRequired())) { return false; diff --git a/src/main/java/org/broadinstitute/consent/http/rules/Rules.java b/src/main/java/org/broadinstitute/consent/http/rules/Rules.java index f0e21142c4..32298308eb 100644 --- a/src/main/java/org/broadinstitute/consent/http/rules/Rules.java +++ b/src/main/java/org/broadinstitute/consent/http/rules/Rules.java @@ -4,8 +4,8 @@ public class Rules { - public static List implementationList = List.of( - new GeneralResearchUseV1(), new GeneralResearchUseWithDiseaseSpecificV1(), - new HealthMedicalBioMedicalV1(), new HealthMedicalBioMedicalWithDiseaseSpecificV1()); - + public static List implementationList = + List.of( + new GeneralResearchUseV1(), new GeneralResearchUseWithDiseaseSpecificV1(), + new HealthMedicalBioMedicalV1(), new HealthMedicalBioMedicalWithDiseaseSpecificV1()); } diff --git a/src/main/java/org/broadinstitute/consent/http/service/AcknowledgementService.java b/src/main/java/org/broadinstitute/consent/http/service/AcknowledgementService.java index 2506dd8b39..cd791a2644 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/AcknowledgementService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/AcknowledgementService.java @@ -21,7 +21,10 @@ public class AcknowledgementService implements ConsentLogger { private final DataAccessRequestDAO dataAccessRequestDAO; private final EmailService emailService; - public AcknowledgementService(AcknowledgementDAO acknowledgementDAO, DataAccessRequestDAO dataAccessRequestDAO, EmailService emailService) { + public AcknowledgementService( + AcknowledgementDAO acknowledgementDAO, + DataAccessRequestDAO dataAccessRequestDAO, + EmailService emailService) { this.acknowledgementDAO = acknowledgementDAO; this.dataAccessRequestDAO = dataAccessRequestDAO; this.emailService = emailService; @@ -42,8 +45,8 @@ public Map makeAcknowledgements(List keys, User for (String key : keys) { acknowledgementDAO.upsertAcknowledgement(key, userId); } - List acknowledgementList = acknowledgementDAO.findAcknowledgementsForUser(keys, - userId); + List acknowledgementList = + acknowledgementDAO.findAcknowledgementsForUser(keys, userId); return acknowledgementListToMap(acknowledgementList); } @@ -51,17 +54,24 @@ private void handleCloseoutAcknowledgement(String key, User user) { if (key.startsWith(DAR_CLOSEOUT_CHAIR_REF)) { String referenceId = key.replace(DAR_CLOSEOUT_CHAIR_REF, ""); DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId(referenceId); - Acknowledgement existingAck = acknowledgementDAO.findAcknowledgementsByKeyForUser(key, user.getUserId()); + Acknowledgement existingAck = + acknowledgementDAO.findAcknowledgementsByKeyForUser(key, user.getUserId()); if (existingAck != null) { - throw new BadRequestException("Closeout acknowledgement already exists for %s".formatted(dar.getDarCode())); + throw new BadRequestException( + "Closeout acknowledgement already exists for %s".formatted(dar.getDarCode())); } if (!dar.getIsCloseoutProgressReport()) { - throw new BadRequestException("Closeout acknowledgement is only valid for closeout progress reports for DAR %s".formatted(dar.getDarCode())); + throw new BadRequestException( + "Closeout acknowledgement is only valid for closeout progress reports for DAR %s" + .formatted(dar.getDarCode())); } try { emailService.sendResearcherCloseoutCompletedMessage(user, dar.getDarCode(), referenceId); } catch (IOException | TemplateException e) { - logException("Unable to send researcher closeout completed message for DAR %s".formatted(dar.getDarCode()), e); + logException( + "Unable to send researcher closeout completed message for DAR %s" + .formatted(dar.getDarCode()), + e); } } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/CounterService.java b/src/main/java/org/broadinstitute/consent/http/service/CounterService.java index 8856744168..37c5125a42 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/CounterService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/CounterService.java @@ -16,5 +16,4 @@ public CounterService(CounterDAO counterDAO) { public Integer getNextDarSequence() { return counterDAO.incrementCountByName(DAR_COUNTER); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/DACAutomationRuleService.java b/src/main/java/org/broadinstitute/consent/http/service/DACAutomationRuleService.java index efb966458c..e25b7c3793 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DACAutomationRuleService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DACAutomationRuleService.java @@ -150,7 +150,6 @@ public void triggerDACRuleSettings( } catch (Exception e) { logWarn("Error triggering DAC Rule Settings", e); } - } @VisibleForTesting @@ -194,13 +193,14 @@ protected Vote openElectionAndApprove( voteDAO.insertVote(rule.enabledByUserId(), electionId, VoteType.RADAR_APPROVE.getValue()); Vote vote = voteDAO.findVoteById(voteId); try { - List updatedVotes = voteServiceDAO.updateVotesWithValue( - List.of(vote), - true, - String.format( - "Rule Automated DAR (RADAR) Approval using rule: %s", - ruleImplementation.getRuleType())); - assert(updatedVotes.size() == 1); + List updatedVotes = + voteServiceDAO.updateVotesWithValue( + List.of(vote), + true, + String.format( + "Rule Automated DAR (RADAR) Approval using rule: %s", + ruleImplementation.getRuleType())); + assert (updatedVotes.size() == 1); vote = updatedVotes.get(0); } catch (Exception e) { logException("Error updating vote", e); diff --git a/src/main/java/org/broadinstitute/consent/http/service/DaaService.java b/src/main/java/org/broadinstitute/consent/http/service/DaaService.java index ff30d94d81..b13ebc88e8 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DaaService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DaaService.java @@ -15,7 +15,6 @@ import java.util.List; import java.util.Optional; import java.util.UUID; -import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.broadinstitute.consent.http.cloudstore.GCSService; import org.broadinstitute.consent.http.db.DaaDAO; @@ -43,7 +42,14 @@ public class DaaService implements ConsentLogger { private final DacDAO dacDAO; @Inject - public DaaService(DaaServiceDAO daaServiceDAO, DaaDAO daaDAO, GCSService gcsService, EmailService emailService, UserService userService, InstitutionDAO institutionDAO, DacDAO dacDAO) { + public DaaService( + DaaServiceDAO daaServiceDAO, + DaaDAO daaDAO, + GCSService gcsService, + EmailService emailService, + UserService userService, + InstitutionDAO institutionDAO, + DacDAO dacDAO) { this.daaServiceDAO = daaServiceDAO; this.daaDAO = daaDAO; this.gcsService = gcsService; @@ -63,24 +69,26 @@ public DaaService(DaaServiceDAO daaServiceDAO, DaaDAO daaDAO, GCSService gcsServ * @return The created DataAccessAgreement * @throws ServerErrorException The Exception */ - public DataAccessAgreement createDaaWithFso(Integer userId, Integer dacId, - InputStream inputStream, - FormDataContentDisposition fileDetail) + public DataAccessAgreement createDaaWithFso( + Integer userId, Integer dacId, InputStream inputStream, FormDataContentDisposition fileDetail) throws ServerErrorException { UUID id = UUID.randomUUID(); BlobId blobId; try { blobId = gcsService.storeDocument(inputStream, fileDetail.getType(), id); } catch (IOException e) { - logException(String.format("Error storing DAA file in GCS. User ID: %s; Dac ID: %s. ", userId, dacId), e); + logException( + String.format("Error storing DAA file in GCS. User ID: %s; Dac ID: %s. ", userId, dacId), + e); throw new ServerErrorException("Error storing DAA file in GCS.", 500); } Integer daaId; try { - String mediaType = switch (StringUtils.substringAfterLast(fileDetail.getFileName(), ".")) { - case "png", "gif", "jpg", "jpeg" -> "image"; - default -> MediaType.APPLICATION_OCTET_STREAM; - }; + String mediaType = + switch (StringUtils.substringAfterLast(fileDetail.getFileName(), ".")) { + case "png", "gif", "jpg", "jpeg" -> "image"; + default -> MediaType.APPLICATION_OCTET_STREAM; + }; FileStorageObject fso = new FileStorageObject(); fso.setBlobId(blobId); fso.setFileName(fileDetail.getFileName()); @@ -91,7 +99,10 @@ public DataAccessAgreement createDaaWithFso(Integer userId, Integer dacId, try { gcsService.deleteDocument(blobId.getName()); } catch (Exception ex) { - logException(String.format("Error deleting DAA file from GCS. User ID: %s; Dac ID: %s. ", userId, dacId), ex); + logException( + String.format( + "Error deleting DAA file from GCS. User ID: %s; Dac ID: %s. ", userId, dacId), + ex); } logException(String.format("Error saving DAA. User ID: %s; Dac ID: %s. ", userId, dacId), e); throw new ServerErrorException("Error saving DAA.", 500); @@ -111,18 +122,22 @@ public void removeDacFromDaa(Integer dacId, Integer daaId) { // Work is ticketed to refactor this logic. public boolean isBroadDAA(int daaId, List allDaas, List allDacs) { // Artificially tag the Broad/DUOS DAA as a reference DAA. - Optional broadDac = allDacs.stream() - .filter(dac -> dac.getName().toLowerCase().contains("broad")).findFirst(); + Optional broadDac = + allDacs.stream().filter(dac -> dac.getName().toLowerCase().contains("broad")).findFirst(); if (broadDac.isPresent()) { - Optional broadDAA = allDaas.stream() - .filter(daa -> daa.getInitialDacId().equals(broadDac.get().getDacId())).findFirst(); + Optional broadDAA = + allDaas.stream() + .filter(daa -> daa.getInitialDacId().equals(broadDac.get().getDacId())) + .findFirst(); broadDAA.ifPresent(daa -> daa.setBroadDaa(true)); } else { // In this case, we want the first created DAA to be the Broad default DAA. - allDaas.stream().min(Comparator.comparing(DataAccessAgreement::getDaaId)) + allDaas.stream() + .min(Comparator.comparing(DataAccessAgreement::getDaaId)) .ifPresent(daa -> daa.setBroadDaa(true)); } - Optional broadDaa = allDaas.stream().filter(daa -> daa.getDaaId().equals(daaId)).findFirst(); + Optional broadDaa = + allDaas.stream().filter(daa -> daa.getDaaId().equals(daaId)).findFirst(); if (broadDaa.isPresent()) { return broadDaa.get().getBroadDaa(); } else { @@ -131,16 +146,15 @@ public boolean isBroadDAA(int daaId, List allDaas, List findAll() { - List daas = daaDAO.findAll(); - List allDacs = dacDAO.findAll(); - if (daas != null) { - daas.forEach(daa -> { - daa.setBroadDaa( - isBroadDAA(daa.getDaaId(), daas, allDacs) - ); - }); - return daas; - } + List daas = daaDAO.findAll(); + List allDacs = dacDAO.findAll(); + if (daas != null) { + daas.forEach( + daa -> { + daa.setBroadDaa(isBroadDAA(daa.getDaaId(), daas, allDacs)); + }); + return daas; + } return List.of(); } @@ -156,11 +170,13 @@ public void sendDaaRequestEmails(User user, Integer daaId) throws Exception { try { Institution institution = institutionDAO.findInstitutionWithSOById(user.getInstitutionId()); if (institution == null) { - throw new BadRequestException("This user has not set their institution: " + user.getDisplayName()); + throw new BadRequestException( + "This user has not set their institution: " + user.getDisplayName()); } List signingOfficials = institution.getSigningOfficials(); if (signingOfficials.isEmpty()) { - throw new NotFoundException("No signing officials found for user: " + user.getDisplayName()); + throw new NotFoundException( + "No signing officials found for user: " + user.getDisplayName()); } for (SimplifiedUser signingOfficial : signingOfficials) { DataAccessAgreement daa = findById(daaId); @@ -172,36 +188,42 @@ public void sendDaaRequestEmails(User user, Integer daaId) throws Exception { } } catch (Exception e) { logException(e); - throw(e); + throw (e); } } - public void sendNewDaaEmails(User user, Integer daaId, String dacName, String newDaaName) throws Exception { + public void sendNewDaaEmails(User user, Integer daaId, String dacName, String newDaaName) + throws Exception { try { DataAccessAgreement daa = findById(daaId); if (daa != null) { String previousDaaName = daa.getFile().getFileName(); List researchers = userService.getUsersByDaaId(daaId); - List signingOfficials = researchers.stream() - .flatMap(researcher -> userService.findSOsByInstitutionId(researcher.getInstitutionId()).stream()) - .distinct() - .toList(); + List signingOfficials = + researchers.stream() + .flatMap( + researcher -> + userService.findSOsByInstitutionId(researcher.getInstitutionId()).stream()) + .distinct() + .toList(); User toUser = new User(); for (SimplifiedUser researcher : researchers) { toUser.setEmail(researcher.getEmail()); toUser.setDisplayName(researcher.getDisplayName()); - emailService.sendNewDAAUploadResearcherMessage(toUser, dacName, previousDaaName, newDaaName, user.getUserId()); + emailService.sendNewDAAUploadResearcherMessage( + toUser, dacName, previousDaaName, newDaaName, user.getUserId()); } for (SimplifiedUser signingOfficial : signingOfficials) { toUser.setEmail(signingOfficial.getEmail()); toUser.setDisplayName(signingOfficial.getDisplayName()); - emailService.sendNewDAAUploadSOMessage(toUser, dacName, previousDaaName, newDaaName, user.getUserId()); + emailService.sendNewDAAUploadSOMessage( + toUser, dacName, previousDaaName, newDaaName, user.getUserId()); } } } catch (Exception e) { logException(e); - throw(e); + throw (e); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/DacService.java b/src/main/java/org/broadinstitute/consent/http/service/DacService.java index ae77ab8b47..a48241f23b 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DacService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DacService.java @@ -11,7 +11,6 @@ import java.util.Date; import java.util.EnumSet; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -50,10 +49,16 @@ public class DacService implements ConsentLogger { private final DACAutomationRuleDAO ruleDAO; @Inject - public DacService(DacDAO dacDAO, UserDAO userDAO, DatasetDAO dataSetDAO, - ElectionDAO electionDAO, DataAccessRequestDAO dataAccessRequestDAO, - VoteService voteService, DaaService daaService, - DacServiceDAO dacServiceDAO, DACAutomationRuleDAO ruleDAO) { + public DacService( + DacDAO dacDAO, + UserDAO userDAO, + DatasetDAO dataSetDAO, + ElectionDAO electionDAO, + DataAccessRequestDAO dataAccessRequestDAO, + VoteService voteService, + DaaService daaService, + DacServiceDAO dacServiceDAO, + DACAutomationRuleDAO ruleDAO) { this.dacDAO = dacDAO; this.userDAO = userDAO; this.dataSetDAO = dataSetDAO; @@ -69,63 +74,80 @@ public List findAll() { List dacs = dacDAO.findAll(); for (Dac dac : dacs) { DataAccessAgreement associatedDaa = dac.getAssociatedDaa(); - associatedDaa.setBroadDaa(daaService.isBroadDAA(associatedDaa.getDaaId(), List.of(associatedDaa), List.of(dac))); + associatedDaa.setBroadDaa( + daaService.isBroadDAA(associatedDaa.getDaaId(), List.of(associatedDaa), List.of(dac))); dac.setAssociatedDaa(associatedDaa); } return dacs; } public List findAllDACUsersBySearchString(String term) { - return dacDAO.findAllDACUsersBySearchString(term).stream().distinct() + return dacDAO.findAllDACUsersBySearchString(term).stream() + .distinct() .collect(Collectors.toList()); } private List addMemberInfoToDacs(List dacs) { - List allDacMembers = dacDAO.findAllDACUserMemberships().stream().distinct() - .collect(Collectors.toList()); + List allDacMembers = + dacDAO.findAllDACUserMemberships().stream().distinct().collect(Collectors.toList()); Map> dacToUserMap = groupUsersByDacs(dacs, allDacMembers); - return dacs.stream().peek(d -> { - List chairs = dacToUserMap.get(d).stream(). - filter(u -> u.getRoles().stream(). - anyMatch( - ur -> ur.getRoleId().equals(UserRoles.CHAIRPERSON.getRoleId()) && ur.getDacId() - .equals(d.getDacId()))). - collect(Collectors.toList()); - List members = dacToUserMap.get(d).stream(). - filter(u -> u.getRoles().stream(). - anyMatch(ur -> ur.getRoleId().equals(UserRoles.MEMBER.getRoleId()) && ur.getDacId() - .equals(d.getDacId()))). - collect(Collectors.toList()); - d.setChairpersons(chairs); - d.setMembers(members); - }).collect(Collectors.toList()); + return dacs.stream() + .peek( + d -> { + List chairs = + dacToUserMap.get(d).stream() + .filter( + u -> + u.getRoles().stream() + .anyMatch( + ur -> + ur.getRoleId().equals(UserRoles.CHAIRPERSON.getRoleId()) + && ur.getDacId().equals(d.getDacId()))) + .collect(Collectors.toList()); + List members = + dacToUserMap.get(d).stream() + .filter( + u -> + u.getRoles().stream() + .anyMatch( + ur -> + ur.getRoleId().equals(UserRoles.MEMBER.getRoleId()) + && ur.getDacId().equals(d.getDacId()))) + .collect(Collectors.toList()); + d.setChairpersons(chairs); + d.setMembers(members); + }) + .collect(Collectors.toList()); } /** * Convenience method to group DACUsers into their associated Dacs. Users can be in more than a * single Dac, and a Dac can have multiple types of users, either Chairpersons or Members. * - * @param dacs List of all Dacs + * @param dacs List of all Dacs * @param allDacMembers List of all DACUsers, i.e. users that are in any Dac. * @return Map of Dac to list of DACUser */ private Map> groupUsersByDacs(List dacs, List allDacMembers) { Map dacMap = dacs.stream().collect(Collectors.toMap(Dac::getDacId, d -> d)); - Map userMap = allDacMembers.stream() - .collect(Collectors.toMap(User::getUserId, u -> u)); + Map userMap = + allDacMembers.stream().collect(Collectors.toMap(User::getUserId, u -> u)); Map> dacToUserMap = new HashMap<>(); dacs.forEach(d -> dacToUserMap.put(d, new ArrayList<>())); - allDacMembers.stream(). - flatMap(u -> u.getRoles().stream()). - filter(ur -> ur.getRoleId().equals(UserRoles.CHAIRPERSON.getRoleId()) || - ur.getRoleId().equals(UserRoles.MEMBER.getRoleId())). - forEach(ur -> { - Dac d = dacMap.get(ur.getDacId()); - User u = userMap.get(ur.getUserId()); - if (d != null && u != null && dacToUserMap.containsKey(d)) { - dacToUserMap.get(d).add(u); - } - }); + allDacMembers.stream() + .flatMap(u -> u.getRoles().stream()) + .filter( + ur -> + ur.getRoleId().equals(UserRoles.CHAIRPERSON.getRoleId()) + || ur.getRoleId().equals(UserRoles.MEMBER.getRoleId())) + .forEach( + ur -> { + Dac d = dacMap.get(ur.getDacId()); + User u = userMap.get(ur.getUserId()); + if (d != null && u != null && dacToUserMap.containsKey(d)) { + dacToUserMap.get(d).add(u); + } + }); return dacToUserMap; } @@ -139,15 +161,16 @@ public List findDacsWithMembersOption(Boolean withMembers) { public Dac findById(Integer dacId) { Dac dac = dacDAO.findById(dacId); - List chairs = dacDAO.findMembersByDacIdAndRoleId(dacId, - UserRoles.CHAIRPERSON.getRoleId()); + List chairs = + dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.CHAIRPERSON.getRoleId()); List members = dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.MEMBER.getRoleId()); if (Objects.nonNull(dac)) { dac.setChairpersons(chairs); dac.setMembers(members); if (dac.getAssociatedDaa() != null) { DataAccessAgreement associatedDaa = dac.getAssociatedDaa(); - associatedDaa.setBroadDaa(daaService.isBroadDAA(associatedDaa.getDaaId(), List.of(associatedDaa), List.of(dac))); + associatedDaa.setBroadDaa( + daaService.isBroadDAA(associatedDaa.getDaaId(), List.of(associatedDaa), List.of(dac))); dac.setAssociatedDaa(associatedDaa); } return dac; @@ -200,22 +223,20 @@ public List findDatasetsByDacId(Integer dacId) { public List findMembersByDacId(Integer dacId) { List users = dacDAO.findMembersByDacId(dacId); - List allUserIds = users. - stream(). - map(User::getUserId). - distinct(). - collect(Collectors.toList()); + List allUserIds = + users.stream().map(User::getUserId).distinct().collect(Collectors.toList()); Map> userRoleMap = new HashMap<>(); if (!allUserIds.isEmpty()) { - userRoleMap.putAll(dacDAO.findUserRolesForUsers(allUserIds). - stream(). - collect(groupingBy(UserRole::getUserId))); + userRoleMap.putAll( + dacDAO.findUserRolesForUsers(allUserIds).stream() + .collect(groupingBy(UserRole::getUserId))); } - users.forEach(u -> { - if (userRoleMap.containsKey(u.getUserId())) { - u.setRoles(userRoleMap.get(u.getUserId())); - } - }); + users.forEach( + u -> { + if (userRoleMap.containsKey(u.getUserId())) { + u.setRoles(userRoleMap.get(u.getUserId())); + } + }); return users; } @@ -224,13 +245,16 @@ public User addDacMember(Role role, User user, Dac dac) throws IllegalArgumentEx User updatedUser = userDAO.findUserById(user.getUserId()); List elections = electionDAO.findOpenElectionsByDacId(dac.getDacId()); for (Election e : elections) { - IllegalArgumentException noTypeException = new IllegalArgumentException( - "Unable to determine election type for election id: " + e.getElectionId()); + IllegalArgumentException noTypeException = + new IllegalArgumentException( + "Unable to determine election type for election id: " + e.getElectionId()); if (Objects.isNull(e.getElectionType())) { throw noTypeException; } - Optional type = EnumSet.allOf(ElectionType.class).stream(). - filter(t -> t.getValue().equalsIgnoreCase(e.getElectionType())).findFirst(); + Optional type = + EnumSet.allOf(ElectionType.class).stream() + .filter(t -> t.getValue().equalsIgnoreCase(e.getElectionType())) + .findFirst(); if (!type.isPresent()) { throw noTypeException; } @@ -241,20 +265,20 @@ public User addDacMember(Role role, User user, Dac dac) throws IllegalArgumentEx return userDAO.findUserById(updatedUser.getUserId()); } - public void removeDacMember(Role role, User user, Dac dac, Integer auditUser) throws BadRequestException { + public void removeDacMember(Role role, User user, Dac dac, Integer auditUser) + throws BadRequestException { if (role.getRoleId().equals(UserRoles.CHAIRPERSON.getRoleId())) { if (dac.getChairpersons().size() <= 1) { throw new BadRequestException("Dac requires at least one chairperson."); } ruleDAO.auditedDeleteDACRuleSettingByUser(dac.getDacId(), user.getUserId(), auditUser); } - List dacRoles = user. - getRoles(). - stream(). - filter(r -> Objects.nonNull(r.getDacId())). - filter(r -> r.getDacId().equals(dac.getDacId())). - filter(r -> r.getRoleId().equals(role.getRoleId())). - toList(); + List dacRoles = + user.getRoles().stream() + .filter(r -> Objects.nonNull(r.getDacId())) + .filter(r -> r.getDacId().equals(dac.getDacId())) + .filter(r -> r.getRoleId().equals(role.getRoleId())) + .toList(); dacRoles.forEach(userRole -> dacDAO.removeDacMember(userRole.getUserRoleId())); voteService.deleteOpenDacVotesForUser(dac, user); } @@ -269,16 +293,14 @@ public Role getMemberRole() { private boolean hasUseRestriction(String referenceId) { DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId(referenceId); - return Objects.nonNull(dar) && - Objects.nonNull(dar.getData()) && - Objects.nonNull(dar.getData().getRestriction()); + return Objects.nonNull(dar) + && Objects.nonNull(dar.getData()) + && Objects.nonNull(dar.getData().getRestriction()); } - /** - * Filter data access requests by the DAC they are associated with. - */ - List filterDataAccessRequestsByDac(List documents, - User user) { + /** Filter data access requests by the DAC they are associated with. */ + List filterDataAccessRequestsByDac( + List documents, User user) { if (Objects.nonNull(user)) { if (user.hasUserRole(UserRoles.ADMIN)) { return documents; @@ -286,21 +308,21 @@ List filterDataAccessRequestsByDac(List do // Chair and Member users can see data access requests that they have DAC access to if (user.hasUserRole(UserRoles.MEMBER) || user.hasUserRole(UserRoles.CHAIRPERSON)) { List accessibleDatasetIds = dataSetDAO.findDatasetIdsByDACUserId(user.getUserId()); - return documents. - stream(). - filter(d -> { - List datasetIds = d.getDatasetIds(); - return accessibleDatasetIds.stream().anyMatch(datasetIds::contains); - }). - collect(Collectors.toList()); + return documents.stream() + .filter( + d -> { + List datasetIds = d.getDatasetIds(); + return accessibleDatasetIds.stream().anyMatch(datasetIds::contains); + }) + .collect(Collectors.toList()); } } return Collections.emptyList(); } public Set findByDatasetId(List datasetIds) { - return dacDAO.findDacsForDatasetIds(datasetIds).stream().map(dac -> findById(dac.getDacId())).collect( - Collectors.toUnmodifiableSet()); + return dacDAO.findDacsForDatasetIds(datasetIds).stream() + .map(dac -> findById(dac.getDacId())) + .collect(Collectors.toUnmodifiableSet()); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/DarCollectionService.java b/src/main/java/org/broadinstitute/consent/http/service/DarCollectionService.java index ba74e8899e..3bac73dd8a 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DarCollectionService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DarCollectionService.java @@ -64,8 +64,8 @@ public class DarCollectionService implements ConsentLogger { private final EmailService emailService; @Inject - public DarCollectionService(Jdbi jdbi, DarCollectionServiceDAO darCollectionServiceDAO, - EmailService emailService) { + public DarCollectionService( + Jdbi jdbi, DarCollectionServiceDAO darCollectionServiceDAO, EmailService emailService) { this.dacDAO = jdbi.onDemand(DacDAO.class); this.darCollectionDAO = jdbi.onDemand(DarCollectionDAO.class); this.darCollectionSummaryDAO = jdbi.onDemand(DarCollectionSummaryDAO.class); @@ -83,11 +83,14 @@ private void updateStatusCount(Map statusCount, String status) statusCount.merge(Objects.requireNonNullElse(status, "Undefined"), 1, Integer::sum); } - private void determineCollectionStatus(DarCollectionSummary summary, - Map statusCount, Integer datasetCount, Integer electionCount) { - //If there are no elections, status is unreviewed - //if there are some elections open, status is in process - //if all elections are closed or canceled and electionCount == datasetCount, status is complete + private void determineCollectionStatus( + DarCollectionSummary summary, + Map statusCount, + Integer datasetCount, + Integer electionCount) { + // If there are no elections, status is unreviewed + // if there are some elections open, status is in process + // if all elections are closed or canceled and electionCount == datasetCount, status is complete if (electionCount.equals(0)) { summary.setStatus(DarCollectionStatus.SUBMITTED.getValue()); } else if (electionCount.equals(datasetCount)) { @@ -103,30 +106,34 @@ private void determineCollectionStatus(DarCollectionSummary summary, } private void processDarCollectionSummariesForAdmin(List summaries) { - //if at least one election is open, show cancel - //if at least one non-open/absent election, show open - summaries.forEach(s -> { - Map statusCount = new HashMap<>(); - Map elections = s.getElections(); - if (elections.isEmpty()) { - s.addAction(DarCollectionActions.OPEN); - s.setStatus(DarCollectionStatus.SUBMITTED.getValue()); - } else { - elections.values().forEach(e -> { - String status = e.getStatus(); - updateStatusCount(statusCount, status); - if (status.equals(ElectionStatus.OPEN.getValue())) { - s.addAction(DarCollectionActions.CANCEL); - } else { + // if at least one election is open, show cancel + // if at least one non-open/absent election, show open + summaries.forEach( + s -> { + Map statusCount = new HashMap<>(); + Map elections = s.getElections(); + if (elections.isEmpty()) { s.addAction(DarCollectionActions.OPEN); + s.setStatus(DarCollectionStatus.SUBMITTED.getValue()); + } else { + elections + .values() + .forEach( + e -> { + String status = e.getStatus(); + updateStatusCount(statusCount, status); + if (status.equals(ElectionStatus.OPEN.getValue())) { + s.addAction(DarCollectionActions.CANCEL); + } else { + s.addAction(DarCollectionActions.OPEN); + } + }); + determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); + } + if (s.getCloseoutSupplement() != null) { + s.getActions().clear(); } }); - determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); - } - if (s.getCloseoutSupplement() != null) { - s.getActions().clear(); - } - }); } private DarCollectionSummary processDraftAsSummary(DataAccessRequest d) { @@ -147,87 +154,100 @@ private DarCollectionSummary processDraftAsSummary(DataAccessRequest d) { } private void processDarCollectionSummariesForResearcher(List summaries) { - //if an election exists, cancel does not appear - //if there are no elections, review and cancel are present - //if the collection is canceled, revise and review is present - summaries.forEach(s -> { - Map statusCount = new HashMap<>(); - Map elections = s.getElections(); - int electionCount = elections.size(); - elections.values().forEach(election -> updateStatusCount(statusCount, election.getStatus())); - s.addAction(DarCollectionActions.REVIEW); - //if the latest DAR in the collection has at least one approved dataset, - //include the create progress report action - Set datasetIds = dataAccessRequestDAO.findDatasetApprovalsByDar( - s.getLatestReferenceId()); - // Can only create a progress report if there are approved datasets, no closeout supplement, - // and no open elections. - boolean hasOpenElections = statusCount.getOrDefault(ElectionStatus.OPEN.getValue(), 0) > 0; - if (!hasOpenElections && !datasetIds.isEmpty() && s.getCloseoutSupplement() == null) { - s.addAction(DarCollectionActions.CREATE_PROGRESS_REPORT); - } - - //check dar statuses, if they're all canceled show revise (but only if there are no elections) - if (electionCount == 0) { - Collection darStatuses = s.getDarStatuses().values(); - boolean isCanceled = !darStatuses.isEmpty() && darStatuses.stream() - .allMatch(st -> st.equalsIgnoreCase(DarStatus.CANCELED.getValue())); - if (isCanceled) { - s.addAction(DarCollectionActions.REVISE); - s.setStatus(DarCollectionStatus.CANCELED.getValue()); - } else { - if (!s.getProgressReport()) { - s.addAction(DarCollectionActions.CANCEL); + // if an election exists, cancel does not appear + // if there are no elections, review and cancel are present + // if the collection is canceled, revise and review is present + summaries.forEach( + s -> { + Map statusCount = new HashMap<>(); + Map elections = s.getElections(); + int electionCount = elections.size(); + elections + .values() + .forEach(election -> updateStatusCount(statusCount, election.getStatus())); + s.addAction(DarCollectionActions.REVIEW); + // if the latest DAR in the collection has at least one approved dataset, + // include the create progress report action + Set datasetIds = + dataAccessRequestDAO.findDatasetApprovalsByDar(s.getLatestReferenceId()); + // Can only create a progress report if there are approved datasets, no closeout + // supplement, + // and no open elections. + boolean hasOpenElections = + statusCount.getOrDefault(ElectionStatus.OPEN.getValue(), 0) > 0; + if (!hasOpenElections && !datasetIds.isEmpty() && s.getCloseoutSupplement() == null) { + s.addAction(DarCollectionActions.CREATE_PROGRESS_REPORT); } - s.setStatus(DarCollectionStatus.SUBMITTED.getValue()); - } - } else { - determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); - } - }); - } - - private void processDarCollectionSummariesForMember(List summaries, - Integer userId) { - summaries.forEach(s -> { - Collection elections = s.getElections().values(); - Integer electionCount = elections.size(); - //if there are no elections present, unreviewed - //if there are elections present. in process - if (electionCount == 0) { - s.setStatus(DarCollectionStatus.SUBMITTED.getValue()); - } else { - boolean isVotable = elections - .stream() - .anyMatch( - election -> election.getStatus().equalsIgnoreCase(ElectionStatus.OPEN.getValue())); - - if (isVotable) { - s.setStatus(DarCollectionStatus.IN_PROCESS.getValue()); - List votes = s.getVotes().stream() - .filter( - v -> v.getUserId().equals(userId) && v.getType().equals(VoteType.DAC.getValue())) - .toList(); - if (!votes.isEmpty()) { - boolean hasVoted = votes.stream().map(Vote::getVote).allMatch(Objects::nonNull); - DarCollectionActions targetAction = hasVoted ? DarCollectionActions.UPDATE - : DarCollectionActions.VOTE; - s.addAction(targetAction); + + // check dar statuses, if they're all canceled show revise (but only if there are no + // elections) + if (electionCount == 0) { + Collection darStatuses = s.getDarStatuses().values(); + boolean isCanceled = + !darStatuses.isEmpty() + && darStatuses.stream() + .allMatch(st -> st.equalsIgnoreCase(DarStatus.CANCELED.getValue())); + if (isCanceled) { + s.addAction(DarCollectionActions.REVISE); + s.setStatus(DarCollectionStatus.CANCELED.getValue()); + } else { + if (!s.getProgressReport()) { + s.addAction(DarCollectionActions.CANCEL); + } + s.setStatus(DarCollectionStatus.SUBMITTED.getValue()); + } + } else { + determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); } - } else { - //non-votable states - //all canceled (complete) - //some datasets do not have elections (in process) - //all voted on (complete) - //no elections - if (electionCount < s.getDatasetCount()) { - s.setStatus(DarCollectionStatus.IN_PROCESS.getValue()); + }); + } + + private void processDarCollectionSummariesForMember( + List summaries, Integer userId) { + summaries.forEach( + s -> { + Collection elections = s.getElections().values(); + Integer electionCount = elections.size(); + // if there are no elections present, unreviewed + // if there are elections present. in process + if (electionCount == 0) { + s.setStatus(DarCollectionStatus.SUBMITTED.getValue()); } else { - s.setStatus(DarCollectionStatus.COMPLETE.getValue()); + boolean isVotable = + elections.stream() + .anyMatch( + election -> + election.getStatus().equalsIgnoreCase(ElectionStatus.OPEN.getValue())); + + if (isVotable) { + s.setStatus(DarCollectionStatus.IN_PROCESS.getValue()); + List votes = + s.getVotes().stream() + .filter( + v -> + v.getUserId().equals(userId) + && v.getType().equals(VoteType.DAC.getValue())) + .toList(); + if (!votes.isEmpty()) { + boolean hasVoted = votes.stream().map(Vote::getVote).allMatch(Objects::nonNull); + DarCollectionActions targetAction = + hasVoted ? DarCollectionActions.UPDATE : DarCollectionActions.VOTE; + s.addAction(targetAction); + } + } else { + // non-votable states + // all canceled (complete) + // some datasets do not have elections (in process) + // all voted on (complete) + // no elections + if (electionCount < s.getDatasetCount()) { + s.setStatus(DarCollectionStatus.IN_PROCESS.getValue()); + } else { + s.setStatus(DarCollectionStatus.COMPLETE.getValue()); + } + } } - } - } - }); + }); } /** @@ -237,31 +257,32 @@ private void processDarCollectionSummariesForMember(List s * @param summaries The list of DarCollectionSummaries to process */ private void processDarCollectionSummariesForChair(List summaries) { - summaries.forEach(s -> { - Map statusCount = new HashMap<>(); - Map elections = s.getElections(); - if (elections.size() < s.getDatasetCount()) { - s.addAction(DarCollectionActions.OPEN); - } - elections.values().forEach(election -> updateStatusCount(statusCount, election.getStatus())); - Integer closedCount = statusCount.get(ElectionStatus.CLOSED.getValue()); - Integer openCount = statusCount.get(ElectionStatus.OPEN.getValue()); - determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); - updateSummaryActionsForChair(s, closedCount, openCount); - }); + summaries.forEach( + s -> { + Map statusCount = new HashMap<>(); + Map elections = s.getElections(); + if (elections.size() < s.getDatasetCount()) { + s.addAction(DarCollectionActions.OPEN); + } + elections + .values() + .forEach(election -> updateStatusCount(statusCount, election.getStatus())); + Integer closedCount = statusCount.get(ElectionStatus.CLOSED.getValue()); + Integer openCount = statusCount.get(ElectionStatus.OPEN.getValue()); + determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); + updateSummaryActionsForChair(s, closedCount, openCount); + }); } /** * Update the summary actions for a chairperson based on the summary and election counts. * - * @param summary The DarCollectionSummary to update + * @param summary The DarCollectionSummary to update * @param closedCount The count of closed elections - * @param openCount The count of open elections + * @param openCount The count of open elections */ private void updateSummaryActionsForChair( - DarCollectionSummary summary, - Integer closedCount, - Integer openCount) { + DarCollectionSummary summary, Integer closedCount, Integer openCount) { // By default, no actions can be taken on a closeout supplement if (summary.getCloseoutSupplement() != null) { @@ -280,19 +301,23 @@ private void updateSummaryActionsForChair( // If there are closed or canceled elections, show open // If there are any open elections, show vote - summary.getElections().values().forEach(election -> { - ElectionStatus status = ElectionStatus.getStatusFromString(election.getStatus()); - switch (Objects.requireNonNull(status)) { - case CLOSED, CANCELED: - summary.addAction(DarCollectionActions.OPEN); - break; - case OPEN: - summary.addAction(DarCollectionActions.VOTE); - break; - default: - break; - } - }); + summary + .getElections() + .values() + .forEach( + election -> { + ElectionStatus status = ElectionStatus.getStatusFromString(election.getStatus()); + switch (Objects.requireNonNull(status)) { + case CLOSED, CANCELED: + summary.addAction(DarCollectionActions.OPEN); + break; + case OPEN: + summary.addAction(DarCollectionActions.VOTE); + break; + default: + break; + } + }); // Add cancel if there are no closed elections and at least one open election if (Objects.isNull(closedCount) && Objects.nonNull(openCount)) { @@ -301,13 +326,15 @@ private void updateSummaryActionsForChair( } private void processDarCollectionSummariesForSO(List summaries) { - summaries.forEach(s -> { - Map statusCount = new HashMap<>(); - s.getElections().values() - .forEach(election -> updateStatusCount(statusCount, election.getStatus())); - determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); - updateSummaryActionsForSO(s); - }); + summaries.forEach( + s -> { + Map statusCount = new HashMap<>(); + s.getElections() + .values() + .forEach(election -> updateStatusCount(statusCount, election.getStatus())); + determineCollectionStatus(s, statusCount, s.getDatasetCount(), s.getElections().size()); + updateSummaryActionsForSO(s); + }); } private void updateSummaryActionsForSO(DarCollectionSummary summary) { @@ -340,13 +367,15 @@ public List getSummariesForRole(User user, UserRoles role) processDarCollectionSummariesForSO(summaries); break; case CHAIRPERSON: - summaries = darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(userId, - UserRoles.CHAIRPERSON.getRoleId()); + summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + userId, UserRoles.CHAIRPERSON.getRoleId()); processDarCollectionSummariesForChair(summaries); break; case MEMBER: - summaries = darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(userId, - UserRoles.MEMBER.getRoleId()); + summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + userId, UserRoles.MEMBER.getRoleId()); processDarCollectionSummariesForMember(summaries, userId); break; case RESEARCHER: @@ -367,25 +396,26 @@ public List getSummariesForRole(User user, UserRoles role) } private List getDatasetIdsForUserAndRoleId(User user, Integer roleId) { - List roleDacIds = user.getRoles().stream() - .filter(ur -> Objects.nonNull(ur.getRoleId())) - .filter(ur -> ur.getRoleId().equals(roleId)) - .map(UserRole::getDacId) - .filter(Objects::nonNull) - .toList(); + List roleDacIds = + user.getRoles().stream() + .filter(ur -> Objects.nonNull(ur.getRoleId())) + .filter(ur -> ur.getRoleId().equals(roleId)) + .map(UserRole::getDacId) + .filter(Objects::nonNull) + .toList(); return datasetDAO.findDatasetIdsByDacIds(roleDacIds); } /** * Finds the DarCollectionSummary for a given darCollectionId, processed by the given role. * - * @param user The user making the request - * @param role The role the user is making the request as + * @param user The user making the request + * @param role The role the user is making the request as * @param collectionId The darCollectionId of the requested DarCollectionSummary * @return A DarCollectionSummary object */ - public DarCollectionSummary getSummaryForRoleByCollectionId(User user, UserRoles role, - Integer collectionId) { + public DarCollectionSummary getSummaryForRoleByCollectionId( + User user, UserRoles role, Integer collectionId) { DarCollectionSummary summary = null; Integer userId = user.getUserId(); List datasetIds; @@ -401,14 +431,16 @@ public DarCollectionSummary getSummaryForRoleByCollectionId(User user, UserRoles break; case CHAIRPERSON: datasetIds = getDatasetIdsForUserAndRoleId(user, UserRoles.CHAIRPERSON.getRoleId()); - summary = darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(userId, - datasetIds, collectionId); + summary = + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userId, datasetIds, collectionId); processDarCollectionSummariesForChair(List.of(summary)); break; case MEMBER: datasetIds = getDatasetIdsForUserAndRoleId(user, UserRoles.MEMBER.getRoleId()); - summary = darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(userId, - datasetIds, collectionId); + summary = + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userId, datasetIds, collectionId); processDarCollectionSummariesForMember(List.of(summary), userId); break; case RESEARCHER: @@ -426,25 +458,24 @@ public DarCollectionSummary getSummaryForRoleByCollectionId(User user, UserRoles } public DarCollectionSummary updateCollectionToDraftStatus(DarCollection sourceCollection) { - sourceCollection.getDars().values().forEach((d) -> { - Date now = new Date(); - DataAccessRequestData newData = new Gson().fromJson(d.getData().toString(), - DataAccessRequestData.class); - newData.setStatus(null); - newData.setReferenceId(d.getReferenceId()); - dataAccessRequestDAO.updateDataByReferenceId( - d.getReferenceId(), - d.getUserId(), - null, - now, - newData, - null - ); - }); + sourceCollection + .getDars() + .values() + .forEach( + (d) -> { + Date now = new Date(); + DataAccessRequestData newData = + new Gson().fromJson(d.getData().toString(), DataAccessRequestData.class); + newData.setStatus(null); + newData.setReferenceId(d.getReferenceId()); + dataAccessRequestDAO.updateDataByReferenceId( + d.getReferenceId(), d.getUserId(), null, now, newData, null); + }); // get updated collection - sourceCollection = this.darCollectionDAO.findDARCollectionByCollectionId( - sourceCollection.getDarCollectionId()); + sourceCollection = + this.darCollectionDAO.findDARCollectionByCollectionId( + sourceCollection.getDarCollectionId()); return this.processDraftAsSummary(new ArrayList<>(sourceCollection.getDars().values()).get(0)); } @@ -459,7 +490,6 @@ public List findDatasetIdsByDACUser(User user) { return datasetDAO.findDatasetIdsByDACUserId(user.getUserId()); } - public DarCollection getByReferenceId(User user, String referenceId) { DarCollection collection = darCollectionDAO.findDARCollectionByReferenceId(referenceId); if (Objects.isNull(collection)) { @@ -482,27 +512,30 @@ public DarCollection getByCollectionId(User user, Integer collectionId) { * Given a DarCollection, remove all votes from elections for roles that should not see them. This * method mutates the given collection. * - * @param user The User requesting the collection + * @param user The User requesting the collection * @param collection DarCollection to filter votes from * @return DarCollection */ private DarCollection filterCollectionVotesForUser(User user, DarCollection collection) { // Individual votes are only visible to CHAIRPERSON, MEMBER, and ADMIN roles - List voteViewRoles = List.of(UserRoles.CHAIRPERSON, UserRoles.MEMBER, - UserRoles.ADMIN); + List voteViewRoles = + List.of(UserRoles.CHAIRPERSON, UserRoles.MEMBER, UserRoles.ADMIN); if (user.hasAnyUserRole(voteViewRoles)) { return collection; } // Remove votes from elections for all other users - collection.getDars().values().forEach( - dar -> dar.getElections().values().forEach(election -> election.setVotes(Map.of()))); + collection + .getDars() + .values() + .forEach( + dar -> dar.getElections().values().forEach(election -> election.setVotes(Map.of()))); return collection; } - public DarCollection getCollectionWithAllElectionsByCollectionId(User user, - Integer collectionId) { - DarCollection collection = darCollectionDAO.findCollectionWithAllElectionsByCollectionId( - collectionId); + public DarCollection getCollectionWithAllElectionsByCollectionId( + User user, Integer collectionId) { + DarCollection collection = + darCollectionDAO.findCollectionWithAllElectionsByCollectionId(collectionId); if (Objects.isNull(collection)) { throw new NotFoundException( "Collection with the collection id of " + collectionId + " was not found"); @@ -510,10 +543,11 @@ public DarCollection getCollectionWithAllElectionsByCollectionId(User user, return filterCollectionVotesForUser(user, addDatasetsToCollection(collection)); } - public DarCollection getCollectionWithElectionsByCollectionIdAndDatasetIds(User user, - List datasetIds, Integer collectionId) { - DarCollection collection = darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( - datasetIds, collectionId); + public DarCollection getCollectionWithElectionsByCollectionIdAndDatasetIds( + User user, List datasetIds, Integer collectionId) { + DarCollection collection = + darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetIds, collectionId); if (Objects.isNull(collection)) { throw new NotFoundException( "Collection with the collection id of " + collectionId + " was not found"); @@ -531,20 +565,23 @@ public DarCollection getCollectionWithElectionsByCollectionIdAndDatasetIds(User protected DarCollection addDatasetsToCollection(DarCollection collection) { // get datasetIds from each DAR from each collection List referenceIds = List.copyOf(collection.getDars().keySet()); - List datasetIds = referenceIds.isEmpty() ? List.of() - : dataAccessRequestDAO.findAllDARDatasetRelations(referenceIds); + List datasetIds = + referenceIds.isEmpty() + ? List.of() + : dataAccessRequestDAO.findAllDARDatasetRelations(referenceIds); if (!datasetIds.isEmpty()) { - Map datasetMap = datasetDAO.findDatasetsByIdList(datasetIds) - .stream() - .distinct() - .collect(Collectors.toMap(Dataset::getDatasetId, Function.identity())); - - Set collectionDatasets = collection.getDars().values().stream() - .map(DataAccessRequest::getDatasetIds) - .flatMap(Collection::stream) - .map(datasetMap::get) - .filter(Objects::nonNull) // filtering out nulls which were getting captured by map - .collect(Collectors.toSet()); + Map datasetMap = + datasetDAO.findDatasetsByIdList(datasetIds).stream() + .distinct() + .collect(Collectors.toMap(Dataset::getDatasetId, Function.identity())); + + Set collectionDatasets = + collection.getDars().values().stream() + .map(DataAccessRequest::getDatasetIds) + .flatMap(Collection::stream) + .map(datasetMap::get) + .filter(Objects::nonNull) // filtering out nulls which were getting captured by map + .collect(Collectors.toSet()); collection.setDatasets(collectionDatasets); return collection.deepCopy(); } @@ -556,45 +593,48 @@ protected DarCollection addDatasetsToCollection(DarCollection collection) { * Cancel Elections or a dar for a DarCollection, given a user and a role. If the user is a chair, * or admin, cancel elections. If the user is a researcher, cancel the dar. * - * @param user The User initiating the cancel + * @param user The User initiating the cancel * @param collection The DarCollection - * @param role The role of the user, must be one of ADMIN, CHAIRPERSON, or RESEARCHER + * @param role The role of the user, must be one of ADMIN, CHAIRPERSON, or RESEARCHER * @return The DarCollection that has been canceled */ - public DarCollection cancelDarCollectionByRole(User user, DarCollection collection, - UserRoles role) { + public DarCollection cancelDarCollectionByRole( + User user, DarCollection collection, UserRoles role) { Collection dars = collection.getDars().values(); if (dars.isEmpty()) { - logWarn("DAR Collection ID: [%s] does not have any associated DAR ids".formatted( - collection.getDarCollectionId())); + logWarn( + "DAR Collection ID: [%s] does not have any associated DAR ids" + .formatted(collection.getDarCollectionId())); return collection; } - DarCollection cancelledCollection = switch (role) { - case ADMIN -> cancelDarCollectionElectionsAsAdmin(collection, user); - case CHAIRPERSON -> cancelDarCollectionElectionsAsChair(collection, user); - default -> cancelDarCollectionAsResearcher(collection, user); - }; + DarCollection cancelledCollection = + switch (role) { + case ADMIN -> cancelDarCollectionElectionsAsAdmin(collection, user); + case CHAIRPERSON -> cancelDarCollectionElectionsAsChair(collection, user); + default -> cancelDarCollectionAsResearcher(collection, user); + }; return getByCollectionId(user, cancelledCollection.getDarCollectionId()); } /** * Cancel a DarCollection as a researcher. - *

- * If an election exists for a DAR within the collection, that DAR cannot be cancelled by the + * + *

If an election exists for a DAR within the collection, that DAR cannot be cancelled by the * researcher. Since it's now under DAC review, it's up to the DAC Chair (or admin) to ultimately * decline or cancel the elections for the collection. * * @param collection The DarCollection - * @param user the researcher requesting the cancel + * @param user the researcher requesting the cancel * @return The canceled DarCollection */ private DarCollection cancelDarCollectionAsResearcher(DarCollection collection, User user) { if (!user.getUserId().equals(collection.getCreateUserId())) { throw new NotFoundException(); } - DarCollectionSummary summary = darCollectionSummaryDAO - .getDarCollectionSummaryByCollectionId(collection.getDarCollectionId()); + DarCollectionSummary summary = + darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( + collection.getDarCollectionId()); if (summary.getProgressReport()) { throw new BadRequestException("Cannot cancel a progress report"); } @@ -608,10 +648,11 @@ private DarCollection cancelDarCollectionAsResearcher(DarCollection collection, } // Cancel active dars for the researcher - List activeDarIds = dars.stream() - .filter(d -> !DataAccessRequest.isCanceled(d)) - .map(DataAccessRequest::getReferenceId) - .toList(); + List activeDarIds = + dars.stream() + .filter(d -> !DataAccessRequest.isCanceled(d)) + .map(DataAccessRequest::getReferenceId) + .toList(); if (!activeDarIds.isEmpty()) { dataAccessRequestDAO.cancelByReferenceIds(activeDarIds); } @@ -621,8 +662,8 @@ private DarCollection cancelDarCollectionAsResearcher(DarCollection collection, /** * Cancel Elections for a DarCollection as an admin. - *

- * Admins can cancel all elections in a DarCollection + * + *

Admins can cancel all elections in a DarCollection * * @param collection The DarCollection * @return The DarCollection whose elections have been canceled @@ -639,8 +680,8 @@ private DarCollection cancelDarCollectionElectionsAsAdmin(DarCollection collecti /** * Cancel Elections for a DarCollection as a chairperson. - *

- * Chairs can only cancel Elections that reference a dataset the chair is a DAC member for. + * + *

Chairs can only cancel Elections that reference a dataset the chair is a DAC member for. * * @param collection The DarCollection * @return The DarCollection whose elections have been canceled @@ -650,15 +691,16 @@ private DarCollection cancelDarCollectionElectionsAsChair(DarCollection collecti Set datasetIds = Set.copyOf(datasetDAO.findDatasetIdsByDACUserId(user.getUserId())); // Filter the list of DARs we can operate on by the datasets accessible to this chairperson - List referenceIds = collection.getDars().values().stream() - .filter(d -> datasetIds.containsAll(d.getDatasetIds())) - .map(DataAccessRequest::getReferenceId) - .toList(); + List referenceIds = + collection.getDars().values().stream() + .filter(d -> datasetIds.containsAll(d.getDatasetIds())) + .map(DataAccessRequest::getReferenceId) + .toList(); if (referenceIds.isEmpty()) { logWarn( - "DAR Collection ID: [%s] does not have any associated DARs that this chairperson can access".formatted( - collection.getDarCollectionId())); + "DAR Collection ID: [%s] does not have any associated DARs that this chairperson can access" + .formatted(collection.getDarCollectionId())); return collection; } @@ -673,7 +715,7 @@ private DarCollection cancelDarCollectionElectionsAsChair(DarCollection collecti * initiating a new set of elections. Elections in open, closed, pending, or final states are not * valid. * - * @param user The User initiating new elections for a collection + * @param user The User initiating new elections for a collection * @param collection The DarCollection * @return The updated DarCollection */ @@ -681,33 +723,37 @@ public DarCollection createElectionsForDarCollection(User user, DarCollection co throws Exception { try { DataAccessRequest dar = collection.getMostRecentDar(); - List createdElectionReferenceIds = collectionServiceDAO.createElectionsForDarByUser( - user, dar); + List createdElectionReferenceIds = + collectionServiceDAO.createElectionsForDarByUser(user, dar); if (createdElectionReferenceIds.isEmpty()) { - var e = new IllegalStateException( - "No elections were created for DAR Collection: %s %s".formatted( - collection.getDarCode(), dar.getReferenceId())); + var e = + new IllegalStateException( + "No elections were created for DAR Collection: %s %s" + .formatted(collection.getDarCode(), dar.getReferenceId())); logException(e); throw e; } try { - List voteUsers = voteDAO.findVoteUsersByElectionReferenceIdList( - createdElectionReferenceIds); + List voteUsers = + voteDAO.findVoteUsersByElectionReferenceIdList(createdElectionReferenceIds); if (dar.getProgressReport()) { - emailService.sendProgressReportNewCollectionElectionMessage(voteUsers, - collection.getDarCode()); + emailService.sendProgressReportNewCollectionElectionMessage( + voteUsers, collection.getDarCode()); } else { emailService.sendDarNewCollectionElectionMessage(voteUsers, collection.getDarCode()); } } catch (Exception e) { logException( - "Unable to send new case message to DAC members for DAR Collection: %s".formatted( - collection.getDarCode()), e); + "Unable to send new case message to DAC members for DAR Collection: %s" + .formatted(collection.getDarCode()), + e); } } catch (Exception e) { - logException("Exception creating elections and votes for collection: %s".formatted( - collection.getDarCollectionId()), e); + logException( + "Exception creating elections and votes for collection: %s" + .formatted(collection.getDarCollectionId()), + e); throw e; } return getByCollectionId(user, collection.getDarCollectionId()); @@ -716,15 +762,15 @@ public DarCollection createElectionsForDarCollection(User user, DarCollection co // Private helper method to mark Elections as 'Canceled' private void cancelElectionsForReferenceIds(List referenceIds) { List elections = electionDAO.findOpenElectionsByReferenceIds(referenceIds); - elections.forEach(election -> { - if (!election.getStatus().equals(ElectionStatus.CANCELED.getValue())) { - electionDAO.updateElectionById(election.getElectionId(), ElectionStatus.CANCELED.getValue(), - new Date()); - } - }); + elections.forEach( + election -> { + if (!election.getStatus().equals(ElectionStatus.CANCELED.getValue())) { + electionDAO.updateElectionById( + election.getElectionId(), ElectionStatus.CANCELED.getValue(), new Date()); + } + }); } - public void sendNewDARCollectionMessage(Integer collectionId) throws IOException, TemplateException { DarCollection collection = darCollectionDAO.findDARCollectionByCollectionId(collectionId); @@ -762,40 +808,41 @@ public void sendNewDARCollectionMessage(Integer collectionId) if (dar.getProgressReport()) { // Use the reference ID to link the fact that this progress report will have been noted. // the DAR Code at this point will be ambiguous. - emailService.sendNewProgressReportRequestEmail(user, dacDatasetMap, researcherName, - collection.getDarCode(), dar.getReferenceId()); + emailService.sendNewProgressReportRequestEmail( + user, dacDatasetMap, researcherName, collection.getDarCode(), dar.getReferenceId()); } else { - emailService.sendNewDARRequestEmail(user, dacDatasetMap, researcherName, - collection.getDarCode()); + emailService.sendNewDARRequestEmail( + user, dacDatasetMap, researcherName, collection.getDarCode()); } } notifySigningOfficialsOfDARSubmission(dar, researcher, collection.getDarCode()); } @VisibleForTesting - protected void notifySigningOfficialsOfDARSubmission(DataAccessRequest dar, User researcher, - String darCode) throws TemplateException, IOException { + protected void notifySigningOfficialsOfDARSubmission( + DataAccessRequest dar, User researcher, String darCode) + throws TemplateException, IOException { if (researcher == null) { logWarn( - "Unable to send new DAR/PR message to Signing Officials: Researcher does not exist: %s".formatted( - dar.getUserId())); + "Unable to send new DAR/PR message to Signing Officials: Researcher does not exist: %s" + .formatted(dar.getUserId())); return; } if (researcher.getInstitutionId() == null) { logWarn( - "Unable to send new DAR/PR message to Signing Officials: Researcher does not have an institution id: %s".formatted( - dar.getUserId())); + "Unable to send new DAR/PR message to Signing Officials: Researcher does not have an institution id: %s" + .formatted(dar.getUserId())); return; } List signingOfficials = userDAO.getSOsByInstitution(researcher.getInstitutionId()); List datasets = datasetDAO.findDatasetsByIdList(dar.getDatasetIds()); for (User so : signingOfficials) { if (dar.getProgressReport()) { - emailService.sendNewSoProgressReportSubmittedEmail(so, darCode, researcher, - dar.getReferenceId(), datasets); + emailService.sendNewSoProgressReportSubmittedEmail( + so, darCode, researcher, dar.getReferenceId(), datasets); } else { - emailService.sendNewSoDARSubmittedEmail(so, darCode, researcher, dar.getReferenceId(), - datasets); + emailService.sendNewSoDARSubmittedEmail( + so, darCode, researcher, dar.getReferenceId(), datasets); } } } @@ -807,25 +854,20 @@ private List getDistinctAdminAndChairUsersForDAR(DataAccessRequest dar) { private List getDistinctAdminAndChairUsersForDatasetIds(List datasetIds) { List admins = userDAO.findUsersByRoleId(UserRoles.ADMIN.getRoleId()); - Set chairPersons = userDAO.findUsersForDatasetsByRole(datasetIds, - Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId())); + Set chairPersons = + userDAO.findUsersForDatasetsByRole( + datasetIds, Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId())); // Ensure that admins/chairs are not double emailed - return Streams.concat(admins.stream(), chairPersons.stream()) - .distinct() - .toList(); + return Streams.concat(admins.stream(), chairPersons.stream()).distinct().toList(); } private List getMatchingDacs(User user, Collection dacsInDAR) { if (user.hasUserRole(UserRoles.ADMIN)) { return new ArrayList<>(dacsInDAR); } - List dacIDs = user.getRoles().stream() - .map(UserRole::getDacId) - .filter(Objects::nonNull) - .toList(); - return dacsInDAR.stream() - .filter(dac -> dacIDs.contains(dac.getDacId())) - .toList(); + List dacIDs = + user.getRoles().stream().map(UserRole::getDacId).filter(Objects::nonNull).toList(); + return dacsInDAR.stream().filter(dac -> dacIDs.contains(dac.getDacId())).toList(); } private List getMatchingDatasets(Dac dac, List datasetsInDAR) { @@ -834,5 +876,4 @@ private List getMatchingDatasets(Dac dac, List datasetsInDAR) { .map(Dataset::getDatasetIdentifier) .toList(); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/DataAccessReportsParser.java b/src/main/java/org/broadinstitute/consent/http/service/DataAccessReportsParser.java index afe47d5b67..03aff67c4f 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DataAccessReportsParser.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DataAccessReportsParser.java @@ -25,63 +25,107 @@ public class DataAccessReportsParser implements ConsentLogger { private static final String END_OF_LINE = System.lineSeparator(); - public DataAccessReportsParser(DatasetDAO datasetDAO, - UseRestrictionConverter useRestrictionConverter) { + public DataAccessReportsParser( + DatasetDAO datasetDAO, UseRestrictionConverter useRestrictionConverter) { this.datasetDAO = datasetDAO; this.useRestrictionConverter = useRestrictionConverter; } public void setApprovedDARHeader(FileWriter darWriter) throws IOException { darWriter.write( - HeaderDAR.DAR_ID.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATASET_NAME.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATASET_ID.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.CONSENT_ID.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATA_REQUESTER_NAME.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.ORGANIZATION.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.CODED_VERSION_SDUL.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.CODED_VERSION_DAR.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.RESEARCH_PURPOSE.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATE_REQUEST_SUBMISSION.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATE_REQUEST_APPROVAL.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATE_REQUEST_RE_ATTESTATION.getValue() + END_OF_LINE); + HeaderDAR.DAR_ID.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATASET_NAME.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATASET_ID.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.CONSENT_ID.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATA_REQUESTER_NAME.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.ORGANIZATION.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.CODED_VERSION_SDUL.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.CODED_VERSION_DAR.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.RESEARCH_PURPOSE.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATE_REQUEST_SUBMISSION.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATE_REQUEST_APPROVAL.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATE_REQUEST_RE_ATTESTATION.getValue() + + END_OF_LINE); } public void setReviewedDARHeader(FileWriter darWriter) throws IOException { darWriter.write( - HeaderDAR.DAR_ID.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATASET_NAME.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATASET_ID.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.CONSENT_ID.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.CODED_VERSION_SDUL.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.CODED_VERSION_DAR.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.DATE_REQUEST_APPROVAL_DISAPROVAL.getValue() + DEFAULT_SEPARATOR + - HeaderDAR.APPROVED_DISAPPROVED.getValue() + END_OF_LINE); + HeaderDAR.DAR_ID.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATASET_NAME.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATASET_ID.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.CONSENT_ID.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.CODED_VERSION_SDUL.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.CODED_VERSION_DAR.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.DATE_REQUEST_APPROVAL_DISAPROVAL.getValue() + + DEFAULT_SEPARATOR + + HeaderDAR.APPROVED_DISAPPROVED.getValue() + + END_OF_LINE); } - public void addApprovedDARLine(FileWriter darWriter, Election election, DataAccessRequest dar, - String darCode, String profileName, String institution, String consentName, - String translatedUseRestriction) throws IOException { + public void addApprovedDARLine( + FileWriter darWriter, + Election election, + DataAccessRequest dar, + String darCode, + String profileName, + String institution, + String consentName, + String translatedUseRestriction) + throws IOException { String rusSummary = Objects.nonNull(dar.getData()) && StringUtils.isNotEmpty(dar.getData().getNonTechRus()) - ? dar.getData().getNonTechRus().replace("\n", " ") : ""; + ? dar.getData().getNonTechRus().replace("\n", " ") + : ""; String content1 = profileName + DEFAULT_SEPARATOR + institution + DEFAULT_SEPARATOR; - String electionDate = (Objects.nonNull(election.getFinalVoteDate())) ? formatTimeToDate( - election.getFinalVoteDate().getTime()) : ""; - String updateDate = (Objects.nonNull(dar.getUpdateDate())) ? formatTimeToDate( - dar.getUpdateDate().getTime()) : ""; - String content2 = rusSummary + DEFAULT_SEPARATOR + - updateDate + DEFAULT_SEPARATOR + - electionDate + DEFAULT_SEPARATOR + - "--"; + String electionDate = + (Objects.nonNull(election.getFinalVoteDate())) + ? formatTimeToDate(election.getFinalVoteDate().getTime()) + : ""; + String updateDate = + (Objects.nonNull(dar.getUpdateDate())) + ? formatTimeToDate(dar.getUpdateDate().getTime()) + : ""; + String content2 = + rusSummary + + DEFAULT_SEPARATOR + + updateDate + + DEFAULT_SEPARATOR + + electionDate + + DEFAULT_SEPARATOR + + "--"; addDARLine(darWriter, dar, darCode, content1, content2, consentName, translatedUseRestriction); } - public void addReviewedDARLine(FileWriter darWriter, Election election, DataAccessRequest dar, - String darCode, String consentName, String translatedUseRestriction) throws IOException { + public void addReviewedDARLine( + FileWriter darWriter, + Election election, + DataAccessRequest dar, + String darCode, + String consentName, + String translatedUseRestriction) + throws IOException { String finalVote = election.getFinalVote() ? "Yes" : "No"; - String electionDate = (Objects.nonNull(election.getFinalVoteDate())) ? formatTimeToDate( - election.getFinalVoteDate().getTime()) : ""; + String electionDate = + (Objects.nonNull(election.getFinalVoteDate())) + ? formatTimeToDate(election.getFinalVoteDate().getTime()) + : ""; String customContent2 = electionDate + DEFAULT_SEPARATOR + finalVote; addDARLine(darWriter, dar, darCode, "", customContent2, consentName, translatedUseRestriction); } @@ -95,9 +139,15 @@ private String formatTimeToDate(long time) { return String.format("%s/%s/%s", month, day, year); } - private void addDARLine(FileWriter darWriter, DataAccessRequest dar, String darCode, - String customContent1, String customContent2, String consentName, - String translatedUseRestriction) throws IOException { + private void addDARLine( + FileWriter darWriter, + DataAccessRequest dar, + String darCode, + String customContent1, + String customContent2, + String consentName, + String translatedUseRestriction) + throws IOException { List datasetNames = new ArrayList<>(); List datasetIds = dar.getDatasetIds(); List datasets = @@ -109,24 +159,29 @@ private void addDARLine(FileWriter darWriter, DataAccessRequest dar, String darC datasetNames.add(dataset.getName()); } String sDUL = - StringUtils.isNotEmpty(translatedUseRestriction) ? translatedUseRestriction.replace("\n", - " ") : ""; + StringUtils.isNotEmpty(translatedUseRestriction) + ? translatedUseRestriction.replace("\n", " ") + : ""; DataUse dataUse = useRestrictionConverter.parseDataUsePurpose(dar); - String sDAR = useRestrictionConverter.translateDataUse(dataUse, - DataUseTranslationType.PURPOSE); + String sDAR = + useRestrictionConverter.translateDataUse(dataUse, DataUseTranslationType.PURPOSE); String formattedSDAR = sDAR.replace("\n", " "); darWriter.write( - darCode + DEFAULT_SEPARATOR + - StringUtils.join(datasetNames, ",") + DEFAULT_SEPARATOR + - StringUtils.join(datasetIdentifiers, ",") + DEFAULT_SEPARATOR + - consentName + DEFAULT_SEPARATOR + - customContent1 + - sDUL + DEFAULT_SEPARATOR + - formattedSDAR + DEFAULT_SEPARATOR + - customContent2 + END_OF_LINE); - + darCode + + DEFAULT_SEPARATOR + + StringUtils.join(datasetNames, ",") + + DEFAULT_SEPARATOR + + StringUtils.join(datasetIdentifiers, ",") + + DEFAULT_SEPARATOR + + consentName + + DEFAULT_SEPARATOR + + customContent1 + + sDUL + + DEFAULT_SEPARATOR + + formattedSDAR + + DEFAULT_SEPARATOR + + customContent2 + + END_OF_LINE); } } - - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/DataAccessRequestService.java b/src/main/java/org/broadinstitute/consent/http/service/DataAccessRequestService.java index 3e9d190714..e10104f161 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DataAccessRequestService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DataAccessRequestService.java @@ -8,13 +8,13 @@ import jakarta.ws.rs.NotAcceptableException; import jakarta.ws.rs.NotFoundException; import java.io.IOException; -import java.util.ArrayList; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; @@ -58,13 +58,14 @@ public class DataAccessRequestService implements ConsentLogger { public static final String EXPIRE_WARN_INTERVAL = "11 months"; public static final String EXPIRE_NOTICE_INTERVAL = "1 year"; - protected static final Timestamp MINIMUM_SUBMITTED_DATE_FOR_DAR_EXPIRATIONS = Timestamp.from( - Instant.ofEpochSecond( - LocalDate.of(2024, 9, 30).toEpochSecond(LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC))); + protected static final Timestamp MINIMUM_SUBMITTED_DATE_FOR_DAR_EXPIRATIONS = + Timestamp.from( + Instant.ofEpochSecond( + LocalDate.of(2024, 9, 30).toEpochSecond(LocalTime.of(0, 0, 0, 0), ZoneOffset.UTC))); private static final String MEMBER = "member"; private static final String MEMBERS = MEMBER + "s: "; public static final String ALL_LISTED_PERSONNEL_MUST_SHARE_THE_SAME_INSTITUTION = - """ + """ All listed personnel must share the same institutional affiliation and have a library card. The following list of \ roles and members must have email addresses associated with your institution or library cards issued:\s"""; private static final String INTERNAL_COLLABORATOR = "Internal Collaborator"; @@ -87,8 +88,16 @@ public class DataAccessRequestService implements ConsentLogger { private final String serverUrl; @Inject - public DataAccessRequestService(CounterService counterService, DAOContainer container, - DacService dacService, DataAccessRequestServiceDAO dataAccessRequestServiceDAO, UserService userService, InstitutionService institutionService, EmailService emailService, DACAutomationRuleService ruleService, ConsentConfiguration config) { + public DataAccessRequestService( + CounterService counterService, + DAOContainer container, + DacService dacService, + DataAccessRequestServiceDAO dataAccessRequestServiceDAO, + UserService userService, + InstitutionService institutionService, + EmailService emailService, + DACAutomationRuleService ruleService, + ConsentConfiguration config) { this.counterService = counterService; this.dataAccessRequestDAO = container.getDataAccessRequestDAO(); this.darCollectionDAO = container.getDarCollectionDAO(); @@ -114,18 +123,20 @@ public List findAllDraftDataAccessRequestsByUser(Integer user return dataAccessRequestDAO.findAllDraftsByUserId(userId); } - public void deleteDataAccessRequest(DataAccessRequest dataAccessRequest) throws NotAcceptableException { + public void deleteDataAccessRequest(DataAccessRequest dataAccessRequest) + throws NotAcceptableException { String referenceId = dataAccessRequest.getReferenceId(); if (!dataAccessRequest.getDraft()) { throw new BadRequestException("Only draft data access requests can be deleted"); } List elections = electionDAO.findElectionsByReferenceId(referenceId); if (!elections.isEmpty()) { - String message = String.format( - "Unable to delete DAR: '%s', there are existing elections that reference it.", - referenceId); - logWarn(message); - throw new NotAcceptableException(message); + String message = + String.format( + "Unable to delete DAR: '%s', there are existing elections that reference it.", + referenceId); + logWarn(message); + throw new NotAcceptableException(message); } matchDAO.deleteRationalesByPurposeIds(List.of(referenceId)); matchDAO.deleteMatchesByPurposeId(referenceId); @@ -141,10 +152,12 @@ public DataAccessRequest findByReferenceId(String referencedId) { return dar; } - //NOTE: rewrite method into new service DAO method on another ticket + // NOTE: rewrite method into new service DAO method on another ticket public DataAccessRequest insertDraftDataAccessRequest(User user, DataAccessRequest dar) { - if (Objects.isNull(user) || Objects.isNull(dar) || Objects.isNull( - dar.getReferenceId()) || Objects.isNull(dar.getData())) { + if (Objects.isNull(user) + || Objects.isNull(dar) + || Objects.isNull(dar.getReferenceId()) + || Objects.isNull(dar.getData())) { throw new IllegalArgumentException("User and DataAccessRequest are required"); } @@ -154,12 +167,7 @@ public DataAccessRequest insertDraftDataAccessRequest(User user, DataAccessReque Date now = new Date(); dataAccessRequestDAO.insertDraftDataAccessRequest( - dar.getReferenceId(), - user.getUserId(), - now, - now, - dar.getData() - ); + dar.getReferenceId(), user.getUserId(), now, now, dar.getData()); syncDataAccessRequestDatasets(dar.getDatasetIds(), dar.getReferenceId()); return findByReferenceId(dar.getReferenceId()); @@ -170,13 +178,12 @@ public DataAccessRequest insertDraftDataAccessRequest(User user, DataAccessReque * dataset_id) unique Takes in a list of datasetIds and a referenceId and adds them to the * dar_dataset collection * - * @param datasetIds List of Integers that represent the datasetIds + * @param datasetIds List of Integers that represent the datasetIds * @param referenceId ReferenceId of the corresponding DAR */ private void syncDataAccessRequestDatasets(List datasetIds, String referenceId) { - List darDatasets = datasetIds.stream() - .map(datasetId -> new DarDataset(referenceId, datasetId)) - .toList(); + List darDatasets = + datasetIds.stream().map(datasetId -> new DarDataset(referenceId, datasetId)).toList(); dataAccessRequestDAO.deleteDARDatasetRelationByReferenceId(referenceId); if (!darDatasets.isEmpty()) { @@ -198,18 +205,19 @@ public List getDataAccessRequestsByUserRole(User user) { * draft form, so it covers both cases of converting an existing draft to submitted and creating a * brand-new DAR from scratch. * - * @param user The creating User + * @param user The creating User * @param dataAccessRequest DataAccessRequest with populated DAR data * @return The created DAR. */ - public DataAccessRequest createDataAccessRequest(User user, DataAccessRequest dataAccessRequest, ContainerRequest request) { + public DataAccessRequest createDataAccessRequest( + User user, DataAccessRequest dataAccessRequest, ContainerRequest request) { validateDar(user, dataAccessRequest); Date now = new Date(); DataAccessRequestData darData = dataAccessRequest.getData(); - DataAccessRequest existingDar = dataAccessRequestDAO.findByReferenceId( - dataAccessRequest.getReferenceId()); + DataAccessRequest existingDar = + dataAccessRequestDAO.findByReferenceId(dataAccessRequest.getReferenceId()); if (existingDar != null && !existingDar.getDraft()) { throw new SubmittedDARCannotBeEditedException(); } @@ -225,15 +233,9 @@ public DataAccessRequest createDataAccessRequest(User user, DataAccessRequest da List datasetIds = dataAccessRequest.getDatasetIds(); if (Objects.nonNull(existingDar)) { referenceId = dataAccessRequest.getReferenceId(); - dataAccessRequestDAO.updateDraftToSubmittedForCollection(collectionId, - referenceId); + dataAccessRequestDAO.updateDraftToSubmittedForCollection(collectionId, referenceId); dataAccessRequestDAO.updateDataByReferenceId( - referenceId, - user.getUserId(), - now, - now, - darData, - user.getEraCommonsId()); + referenceId, user.getUserId(), now, now, darData, user.getEraCommonsId()); } else { referenceId = UUID.randomUUID().toString(); dataAccessRequestDAO.insertDataAccessRequest( @@ -252,22 +254,28 @@ public DataAccessRequest createDataAccessRequest(User user, DataAccessRequest da } /** - * Create a progress report for the given DataAccessRequest. - * The parent DAR is just passed in for validation purposes. + * Create a progress report for the given DataAccessRequest. The parent DAR is just passed in for + * validation purposes. * - * @param user The User - * @param progressReport The DataAccessRequest - * @param parentDar The parent DataAccessRequest + * @param user The User + * @param progressReport The DataAccessRequest + * @param parentDar The parent DataAccessRequest * @return The created progress report. */ - public DataAccessRequest createProgressReport(User user, DataAccessRequest progressReport, DataAccessRequest parentDar, ContainerRequest request) { + public DataAccessRequest createProgressReport( + User user, + DataAccessRequest progressReport, + DataAccessRequest parentDar, + ContainerRequest request) { validateProgressReport(user, progressReport, parentDar); String referenceId = progressReport.getReferenceId(); List progressReportDatasetIds = progressReport.getDatasetIds(); - Set darDatasetIds = dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId()); + Set darDatasetIds = + dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId()); if (!darDatasetIds.containsAll(progressReportDatasetIds)) { - throw new BadRequestException("Progress report can only be created for approved datasets in the parent DAR"); + throw new BadRequestException( + "Progress report can only be created for approved datasets in the parent DAR"); } try { dataAccessRequestDAO.insertProgressReport( @@ -288,7 +296,10 @@ public DataAccessRequest createProgressReport(User user, DataAccessRequest progr userService.findUserById( progressReport.getData().getCloseoutSupplement().signingOfficialId()); emailService.sendSubmittedCloseoutMessage( - signingOfficialUser, parentDar.getDarCode(), referenceId, serverUrl + "dar_application_review/%d".formatted(parentDar.getCollectionId())); + signingOfficialUser, + parentDar.getDarCode(), + referenceId, + serverUrl + "dar_application_review/%d".formatted(parentDar.getCollectionId())); } catch (TemplateException | IOException e) { throw new InternalServerErrorException(e); } @@ -325,25 +336,32 @@ public void approveDataAccessRequestCloseout(User signingOfficial, String refere } @VisibleForTesting - protected void validateCloseoutApproval(User signingOfficial, DataAccessRequest dataAccessRequest) { + protected void validateCloseoutApproval( + User signingOfficial, DataAccessRequest dataAccessRequest) { // Note: we will allow a signing official to approve their own closeout. if (!dataAccessRequest.getIsCloseoutProgressReport()) { - throw new BadRequestException("Signing officials can only approve closeout progress reports."); + throw new BadRequestException( + "Signing officials can only approve closeout progress reports."); } if (dataAccessRequest.getHasSOCloseoutApproval()) { - throw new BadRequestException("This progress report closeout has already been approved by a signing official."); + throw new BadRequestException( + "This progress report closeout has already been approved by a signing official."); } - if (!signingOfficial.getUserId().equals(dataAccessRequest.getData().getCloseoutSupplement().signingOfficialId())) { - throw new BadRequestException("This request can only be approved by the signing official selected in the closeout request."); + if (!signingOfficial + .getUserId() + .equals(dataAccessRequest.getData().getCloseoutSupplement().signingOfficialId())) { + throw new BadRequestException( + "This request can only be approved by the signing official selected in the closeout request."); } try { User submitter = userService.findUserById(dataAccessRequest.getUserId()); if (!submitter.getInstitutionId().equals(signingOfficial.getInstitutionId())) { - throw new BadRequestException("Signing Officials must be in the same institution as the creator of the closeout request."); + throw new BadRequestException( + "Signing Officials must be in the same institution as the creator of the closeout request."); } } catch (NotFoundException e) { @@ -355,7 +373,8 @@ protected void validateCloseoutApproval(User signingOfficial, DataAccessRequest } } - public void validateProgressReport(User user, DataAccessRequest progressReport, DataAccessRequest parentDar) { + public void validateProgressReport( + User user, DataAccessRequest progressReport, DataAccessRequest parentDar) { validateCommonDarAndProgressReportElements(user, progressReport); validateInternalCollaborators(user, progressReport); validateCountryOfOperation(progressReport.data, true); @@ -364,14 +383,15 @@ public void validateProgressReport(User user, DataAccessRequest progressReport, throw new BadRequestException( "Cannot create a progress report for a draft Data Access Request"); } - if (progressReport.getDatasetIds() == null || progressReport.getDatasetIds().isEmpty() ) { + if (progressReport.getDatasetIds() == null || progressReport.getDatasetIds().isEmpty()) { throw new BadRequestException("At least one dataset is required"); } if (!Set.copyOf(parentDar.getDatasetIds()).containsAll(progressReport.getDatasetIds())) { - throw new BadRequestException("Progress report can only be created for datasets in the parent DAR"); + throw new BadRequestException( + "Progress report can only be created for datasets in the parent DAR"); } - if (progressReport.getData().getProgressReportSummary() == null || - progressReport.getData().getProgressReportSummary().isEmpty()) { + if (progressReport.getData().getProgressReportSummary() == null + || progressReport.getData().getProgressReportSummary().isEmpty()) { throw new BadRequestException("Progress report summary is required"); } @@ -388,15 +408,18 @@ public void validateProgressReport(User user, DataAccessRequest progressReport, throw new BadRequestException("The selected signing official is not a signing official"); } } catch (NotFoundException nfe) { - throw new BadRequestException("The selected signing official in the closeout was not found."); + throw new BadRequestException( + "The selected signing official in the closeout was not found."); } } } @VisibleForTesting protected void validateCommonDarAndProgressReportElements(User user, DataAccessRequest dar) { - if (Objects.isNull(user) || Objects.isNull(dar) || Objects.isNull( - dar.getReferenceId()) || Objects.isNull(dar.getData())) { + if (Objects.isNull(user) + || Objects.isNull(dar) + || Objects.isNull(dar.getReferenceId()) + || Objects.isNull(dar.getData())) { throw new IllegalArgumentException("User and DataAccessRequest are required"); } if (user.getLibraryCard() == null) { @@ -409,8 +432,10 @@ protected void validateCommonDarAndProgressReportElements(User user, DataAccessR public void validateDar(User user, DataAccessRequest dar) { validateCommonDarAndProgressReportElements(user, dar); - if (!Objects.equals(user.getEmail(), dar.getData().getPiEmail()) || !Objects.equals(user.getDisplayName(), dar.getData().getPiName())) { - throw new BadRequestException("The PI in the DAR must have the same name and email as the user submitting the DAR."); + if (!Objects.equals(user.getEmail(), dar.getData().getPiEmail()) + || !Objects.equals(user.getDisplayName(), dar.getData().getPiName())) { + throw new BadRequestException( + "The PI in the DAR must have the same name and email as the user submitting the DAR."); } validateNoKeyPersonnelDuplicates(dar.getData()); @@ -447,19 +472,26 @@ protected void validateInternalCollaborators(User user, DataAccessRequest progre List errorSummary = getCollaboratorAndLibraryCardErrors(user, progressReport.getData()); if (!errorSummary.isEmpty()) { - throw new BadRequestException( ALL_LISTED_PERSONNEL_MUST_SHARE_THE_SAME_INSTITUTION - + String.join(", ", errorSummary)); + throw new BadRequestException( + ALL_LISTED_PERSONNEL_MUST_SHARE_THE_SAME_INSTITUTION + String.join(", ", errorSummary)); } } - private List getCollaboratorAndLibraryCardErrors(User user, DataAccessRequestData darData) { + private List getCollaboratorAndLibraryCardErrors( + User user, DataAccessRequestData darData) { List errorSummary = new ArrayList<>(); getErrorSummary( - darData.getInternalCollaborators().stream().map(Collaborator::email).toList(), user.getInstitution(), - INTERNAL_COLLABORATOR + " " + MEMBER + ": ", INTERNAL_COLLABORATOR + " " + MEMBERS, errorSummary); + darData.getInternalCollaborators().stream().map(Collaborator::email).toList(), + user.getInstitution(), + INTERNAL_COLLABORATOR + " " + MEMBER + ": ", + INTERNAL_COLLABORATOR + " " + MEMBERS, + errorSummary); getErrorSummary( - darData.getLabCollaborators().stream().map(Collaborator::email).toList(), user.getInstitution(), - LAB_STAFF + " " + MEMBER + ": ", LAB_STAFF + " " + MEMBERS, errorSummary); + darData.getLabCollaborators().stream().map(Collaborator::email).toList(), + user.getInstitution(), + LAB_STAFF + " " + MEMBER + ": ", + LAB_STAFF + " " + MEMBERS, + errorSummary); return errorSummary; } @@ -467,7 +499,7 @@ private List getCollaboratorAndLibraryCardErrors(User user, DataAccessRe * Update an existing DataAccessRequest. Replaces DataAccessRequestData. * * @param user The User - * @param dar The DataAccessRequest + * @param dar The DataAccessRequest * @return The updated DataAccessRequest */ public DataAccessRequest updateByReferenceId(User user, DataAccessRequest dar) { @@ -479,9 +511,10 @@ public DataAccessRequest updateByReferenceId(User user, DataAccessRequest dar) { } catch (SQLException e) { // If I simply rethrow the error then I'll have to redefine any method that // calls this function to "throw SQLException" - //Instead I'm going to throw an UnableToExecuteStatementException - //Response class will catch it, log it, and throw a 500 through the "unableToExecuteExceptionHandler" - //on the Resource class, just like it would with a SQLException + // Instead I'm going to throw an UnableToExecuteStatementException + // Response class will catch it, log it, and throw a 500 through the + // "unableToExecuteExceptionHandler" + // on the Resource class, just like it would with a SQLException throw new UnableToExecuteStatementException(e.getMessage()); } } @@ -499,7 +532,8 @@ public void validateNoKeyPersonnelDuplicates(DataAccessRequestData darData) { String soEmail = darData.getSigningOfficialEmail(); String itEmail = darData.getItDirectorEmail(); - if (!emailValidator.isValid(piEmail) || !emailValidator.isValid(soEmail) + if (!emailValidator.isValid(piEmail) + || !emailValidator.isValid(soEmail) || !emailValidator.isValid(itEmail)) { throw new IllegalArgumentException( "Principal Investigator, Signing Official, and IT Director emails must be valid"); @@ -517,7 +551,8 @@ public void validateNoKeyPersonnelDuplicates(DataAccessRequestData darData) { } @VisibleForTesting - protected void validatePersonnelInstitutionAndLibraryCardRequirements(User user, DataAccessRequestData darData) { + protected void validatePersonnelInstitutionAndLibraryCardRequirements( + User user, DataAccessRequestData darData) { Institution submitterInstitution = user.getInstitution(); String piEmail = darData.getPiEmail(); String soEmail = darData.getSigningOfficialEmail(); @@ -532,12 +567,12 @@ protected void validatePersonnelInstitutionAndLibraryCardRequirements(User user, if (!invalidMembers.isEmpty()) { throw new IllegalArgumentException( - ALL_LISTED_PERSONNEL_MUST_SHARE_THE_SAME_INSTITUTION - + String.join(", ", invalidMembers)); + ALL_LISTED_PERSONNEL_MUST_SHARE_THE_SAME_INSTITUTION + String.join(", ", invalidMembers)); } } - private void verifyInstitution(Institution submitterInstitution, String email, String role, List invalidMembers) { + private void verifyInstitution( + Institution submitterInstitution, String email, String role, List invalidMembers) { if (emailDoesNotMatchInstitution(submitterInstitution, email)) { invalidMembers.add(role + ": " + email); } @@ -545,12 +580,13 @@ private void verifyInstitution(Institution submitterInstitution, String email, S private List findCollaboratorsWithoutLibraryCards(List usersToCheck) { List usersWithoutLibraryCards = new ArrayList<>(); - usersToCheck.forEach(email -> { - User collabUser = userDAO.findUserByEmail(email); - if (collabUser == null || collabUser.getLibraryCard() == null) { - usersWithoutLibraryCards.add(email); - } - }); + usersToCheck.forEach( + email -> { + User collabUser = userDAO.findUserByEmail(email); + if (collabUser == null || collabUser.getLibraryCard() == null) { + usersWithoutLibraryCards.add(email); + } + }); return usersWithoutLibraryCards; } @@ -565,12 +601,20 @@ private void getErrorSummary( if (!institutionErrors.isEmpty()) { String missingInstitution = " (missing institution) "; - invalidMembers.add(buildSingleErrorFromErrorList(institutionErrors, categorySingular + missingInstitution, categoryPlural + missingInstitution)); + invalidMembers.add( + buildSingleErrorFromErrorList( + institutionErrors, + categorySingular + missingInstitution, + categoryPlural + missingInstitution)); } if (!libraryCardErrors.isEmpty()) { String missingLibraryCard = " (missing library card) "; - invalidMembers.add(buildSingleErrorFromErrorList(libraryCardErrors, categorySingular + missingLibraryCard, categoryPlural + missingLibraryCard)); + invalidMembers.add( + buildSingleErrorFromErrorList( + libraryCardErrors, + categorySingular + missingLibraryCard, + categoryPlural + missingLibraryCard)); } } @@ -662,11 +706,12 @@ private void sendDARMessageToList(EmailType type, String interval) { public void sendReminderMessage(Integer voteId) throws IOException, TemplateException { Vote vote = voteDAO.findVoteById(voteId); Election election = electionDAO.findElectionWithFinalVoteById(vote.getElectionId()); - DarCollection collection = darCollectionDAO.findDARCollectionByReferenceId( - election.getReferenceId()); + DarCollection collection = + darCollectionDAO.findDARCollectionByReferenceId(election.getReferenceId()); User user = findUserById(vote.getUserId()); String voteUrl = serverUrl + "dar_collection/%d".formatted(collection.getDarCollectionId()); - emailService.sendReminderMessage(user, vote, collection.getDarCode(), election.getElectionType(), voteUrl); + emailService.sendReminderMessage( + user, vote, collection.getDarCode(), election.getElectionType(), voteUrl); voteDAO.updateVoteReminderFlag(voteId, true); } diff --git a/src/main/java/org/broadinstitute/consent/http/service/DatasetRegistrationService.java b/src/main/java/org/broadinstitute/consent/http/service/DatasetRegistrationService.java index b2d13bd4d1..8699cce6e6 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DatasetRegistrationService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DatasetRegistrationService.java @@ -58,9 +58,14 @@ public class DatasetRegistrationService implements ConsentLogger { private final StudyDAO studyDAO; private final EmailService emailService; - public DatasetRegistrationService(DatasetDAO datasetDAO, DacDAO dacDAO, - DatasetServiceDAO datasetServiceDAO, GCSService gcsService, - ElasticSearchService elasticSearchService, StudyDAO studyDAO, EmailService emailService) { + public DatasetRegistrationService( + DatasetDAO datasetDAO, + DacDAO dacDAO, + DatasetServiceDAO datasetServiceDAO, + GCSService gcsService, + ElasticSearchService elasticSearchService, + StudyDAO studyDAO, + EmailService emailService) { this.datasetDAO = datasetDAO; this.dacDAO = dacDAO; this.datasetServiceDAO = datasetServiceDAO; @@ -93,8 +98,8 @@ public Study findStudyById(Integer studyId) { * associated datasets from it. * * @param registration The DatasetRegistrationSchemaV1.yaml - * @param user The User updating the study - * @param files Map of files, where the key is the name of the field + * @param user The User updating the study + * @param files Map of files, where the key is the name of the field * @return The updated Study */ public Study updateStudyFromRegistration( @@ -109,55 +114,47 @@ public Study updateStudyFromRegistration( List datasetInserts = new ArrayList<>(); // Dataset updates and inserts: IntStream.range(0, registration.getConsentGroups().size()) - .forEach(idx -> { - ConsentGroup cg = registration.getConsentGroups().get(idx); - if (Objects.nonNull(cg.getDatasetId())) { - Dataset existingDataset = datasetDAO.findDatasetById(cg.getDatasetId()); - try { - DatasetUpdate datasetUpdate = new DatasetUpdate( - cg.getConsentGroupName(), - existingDataset.getDacId(), - convertConsentGroupToDatasetProperties(cg) - ); - DatasetServiceDAO.DatasetUpdate update = createDatasetUpdate( - cg.getDatasetId(), - user, - datasetUpdate, - files, - uploadedFileCache - ); - datasetUpdates.add(update); - } catch (Exception e) { - logException(e); - } - } else { - try { - DatasetServiceDAO.DatasetInsert insert = createDatasetInsert( - registration, - user, - files, - uploadedFileCache, - idx - ); - datasetInserts.add(insert); - } catch (Exception e) { - logException(e); - } - } - }); + .forEach( + idx -> { + ConsentGroup cg = registration.getConsentGroups().get(idx); + if (Objects.nonNull(cg.getDatasetId())) { + Dataset existingDataset = datasetDAO.findDatasetById(cg.getDatasetId()); + try { + DatasetUpdate datasetUpdate = + new DatasetUpdate( + cg.getConsentGroupName(), + existingDataset.getDacId(), + convertConsentGroupToDatasetProperties(cg)); + DatasetServiceDAO.DatasetUpdate update = + createDatasetUpdate( + cg.getDatasetId(), user, datasetUpdate, files, uploadedFileCache); + datasetUpdates.add(update); + } catch (Exception e) { + logException(e); + } + } else { + try { + DatasetServiceDAO.DatasetInsert insert = + createDatasetInsert(registration, user, files, uploadedFileCache, idx); + datasetInserts.add(insert); + } catch (Exception e) { + logException(e); + } + } + }); List studyProps = convertRegistrationToStudyProperties(registration); - DatasetServiceDAO.StudyUpdate studyUpdate = new StudyUpdate( - registration.getStudyName(), - studyId, - registration.getStudyDescription(), - registration.getDataTypes(), - registration.getPiName(), - registration.getPublicVisibility(), - user.getUserId(), - studyProps, - uploadFiles - ); + DatasetServiceDAO.StudyUpdate studyUpdate = + new StudyUpdate( + registration.getStudyName(), + studyId, + registration.getStudyDescription(), + registration.getDataTypes(), + registration.getPiName(), + registration.getPublicVisibility(), + user.getUserId(), + studyProps, + uploadFiles); Study updatedStudy = datasetServiceDAO.updateStudy(studyUpdate, datasetUpdates, datasetInserts); sendDatasetSubmittedEmails(createdDatasetsFromUpdatedStudy(updatedStudy, datasetUpdates)); @@ -169,14 +166,12 @@ public Study updateStudyFromRegistration( * There will be one dataset per ConsentGroup in the dataset. * * @param registration The DatasetRegistrationSchemaV1.yaml - * @param user The User creating these datasets - * @param files Map of files, where the key is the name of the field + * @param user The User creating these datasets + * @param files Map of files, where the key is the name of the field * @return List of created Datasets from the provided registration schema */ public List createDatasetsFromRegistration( - DatasetRegistrationSchemaV1 registration, - User user, - Map files) + DatasetRegistrationSchemaV1 registration, User user, Map files) throws SQLException, IllegalArgumentException, IOException { registration.setDataSubmitterUserId(user.getUserId()); @@ -189,7 +184,8 @@ public List createDatasetsFromRegistration( try { studyInsert = createStudyInsert(registration, user, files, uploadedFileCache); - for (int consentGroupIdx = 0; consentGroupIdx < registration.getConsentGroups().size(); + for (int consentGroupIdx = 0; + consentGroupIdx < registration.getConsentGroups().size(); consentGroupIdx++) { datasetInserts.add( createDatasetInsert(registration, user, files, uploadedFileCache, consentGroupIdx)); @@ -201,15 +197,15 @@ public List createDatasetsFromRegistration( } List createdDatasetIds = - datasetServiceDAO.insertDatasetRegistration( - studyInsert, - datasetInserts); + datasetServiceDAO.insertDatasetRegistration(studyInsert, datasetInserts); List datasets = datasetDAO.findDatasetsByIdList(createdDatasetIds); sendDatasetSubmittedEmails(datasets); try (Response response = elasticSearchService.indexDatasets(createdDatasetIds, user)) { if (response.getStatus() >= 400) { - logWarn(String.format("Error indexing datasets from registration: %s", registration.getStudyName())); + logWarn( + String.format( + "Error indexing datasets from registration: %s", registration.getStudyName())); } } catch (Exception e) { logException(e); @@ -221,15 +217,15 @@ private BlobId uploadFile(FormDataBodyPart file) throws IOException { String mediaType = file.getContentDisposition().getType(); return gcsService.storeDocument( - file.getValueAs(InputStream.class), - mediaType, - UUID.randomUUID()); + file.getValueAs(InputStream.class), mediaType, UUID.randomUUID()); } - private DatasetServiceDAO.StudyInsert createStudyInsert(DatasetRegistrationSchemaV1 registration, + private DatasetServiceDAO.StudyInsert createStudyInsert( + DatasetRegistrationSchemaV1 registration, User user, Map files, - Map uploadedFileCache) throws IOException { + Map uploadedFileCache) + throws IOException { return new DatasetServiceDAO.StudyInsert( registration.getStudyName(), registration.getStudyDescription(), @@ -238,22 +234,19 @@ private DatasetServiceDAO.StudyInsert createStudyInsert(DatasetRegistrationSchem registration.getPublicVisibility(), user.getUserId(), convertRegistrationToStudyProperties(registration), - uploadFilesForStudy(files, uploadedFileCache, user) - ); + uploadFilesForStudy(files, uploadedFileCache, user)); } /** * This method takes an instance of a dataset registration schema and updates the dataset. * - * @param user The User creating these datasets + * @param user The User creating these datasets * @param files Map of files, where the key is the name of the field * @return List of created Datasets from the provided registration schema */ public Dataset updateDataset( - Integer datasetId, - User user, - DatasetUpdate update, - Map files) throws IOException, SQLException { + Integer datasetId, User user, DatasetUpdate update, Map files) + throws IOException, SQLException { if (Objects.isNull(update.getName())) { throw new BadRequestException("Dataset name is required"); @@ -272,8 +265,8 @@ public Dataset updateDataset( Map uploadedFileCache = new HashMap<>(); try { - DatasetServiceDAO.DatasetUpdate datasetUpdates = createDatasetUpdate(datasetId, user, update, - files, uploadedFileCache); + DatasetServiceDAO.DatasetUpdate datasetUpdates = + createDatasetUpdate(datasetId, user, update, files, uploadedFileCache); // Update or create the objects in the database datasetServiceDAO.updateDataset(datasetUpdates); @@ -297,7 +290,8 @@ private DatasetServiceDAO.DatasetInsert createDatasetInsert( User user, Map files, Map uploadedFileCache, - Integer consentGroupIdx) throws IOException { + Integer consentGroupIdx) + throws IOException { ConsentGroup consentGroup = registration.getConsentGroups().get(consentGroupIdx); if (Objects.nonNull(consentGroup.getDataAccessCommitteeId()) @@ -307,8 +301,8 @@ private DatasetServiceDAO.DatasetInsert createDatasetInsert( List props = convertConsentGroupToDatasetProperties(consentGroup); DataUse dataUse = generateDataUseFromConsentGroup(consentGroup); - List fileStorageObjects = uploadFilesForDataset(files, uploadedFileCache, - consentGroupIdx, user); + List fileStorageObjects = + uploadFilesForDataset(files, uploadedFileCache, consentGroupIdx, user); return new DatasetServiceDAO.DatasetInsert( consentGroup.getConsentGroupName(), @@ -316,8 +310,7 @@ private DatasetServiceDAO.DatasetInsert createDatasetInsert( dataUse, user.getUserId(), props, - fileStorageObjects - ); + fileStorageObjects); } private DatasetServiceDAO.DatasetUpdate createDatasetUpdate( @@ -325,12 +318,13 @@ private DatasetServiceDAO.DatasetUpdate createDatasetUpdate( User user, DatasetUpdate datasetUpdate, Map files, - Map uploadedFileCache) throws IOException { + Map uploadedFileCache) + throws IOException { List props = datasetUpdate.getDatasetProperties(); - List fileStorageObjects = uploadFilesForDatasetUpdate(files, - uploadedFileCache, user); + List fileStorageObjects = + uploadFilesForDatasetUpdate(files, uploadedFileCache, user); return new DatasetServiceDAO.DatasetUpdate( datasetId, @@ -338,8 +332,7 @@ private DatasetServiceDAO.DatasetUpdate createDatasetUpdate( user.getUserId(), datasetUpdate.getDacId(), props, - fileStorageObjects - ); + fileStorageObjects); } private DataUse generateDataUseFromConsentGroup(ConsentGroup group) { @@ -367,48 +360,56 @@ private DataUse generateDataUseFromConsentGroup(ConsentGroup group) { private static final String ALTERNATIVE_DATA_SHARING_PLAN_NAME = "alternativeDataSharingPlan"; // nosemgrep - private static final String NIH_INSTITUTIONAL_CERTIFICATION_NAME = "consentGroups[%s].nihInstitutionalCertificationFile"; + private static final String NIH_INSTITUTIONAL_CERTIFICATION_NAME = + "consentGroups[%s].nihInstitutionalCertificationFile"; /** * Uploads the files related to the Dataset Registration's dataset object to Google Cloud and * returns references to them as FileStorageObjects. * - * @param files The files the user provided: fileType (e.g., - * alternativeDataSharingPlan) -> FormDataBodyPart + * @param files The files the user provided: fileType (e.g., alternativeDataSharingPlan) -> + * FormDataBodyPart * @param uploadedFileCache Previously uploaded files - ensures that the same file is not - * reuploaded if used on different datasets. - * @param consentGroupIdx The index of the consent group that this dataset is associated to - * @param user The create user + * reuploaded if used on different datasets. + * @param consentGroupIdx The index of the consent group that this dataset is associated to + * @param user The create user * @return The list of FSOs created for this study * @throws IOException if GCS upload fails */ - private List uploadFilesForDataset(Map files, + private List uploadFilesForDataset( + Map files, Map uploadedFileCache, Integer consentGroupIdx, - User user) throws IOException { + User user) + throws IOException { List consentGroupFSOs = new ArrayList<>(); if (files.containsKey(String.format(NIH_INSTITUTIONAL_CERTIFICATION_NAME, consentGroupIdx))) { - consentGroupFSOs.add(uploadFile( - files, uploadedFileCache, user, - String.format(NIH_INSTITUTIONAL_CERTIFICATION_NAME, consentGroupIdx), - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION)); + consentGroupFSOs.add( + uploadFile( + files, + uploadedFileCache, + user, + String.format(NIH_INSTITUTIONAL_CERTIFICATION_NAME, consentGroupIdx), + FileCategory.NIH_INSTITUTIONAL_CERTIFICATION)); } return consentGroupFSOs; - } - private List uploadFilesForDatasetUpdate(Map files, - Map uploadedFileCache, - User user) throws IOException { + private List uploadFilesForDatasetUpdate( + Map files, Map uploadedFileCache, User user) + throws IOException { List updateDatasetFSOs = new ArrayList<>(); if (files.containsKey(String.format(NIH_INSTITUTIONAL_CERTIFICATION_NAME, 0))) { - updateDatasetFSOs.add(uploadFile( - files, uploadedFileCache, user, - String.format(NIH_INSTITUTIONAL_CERTIFICATION_NAME, 0), - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION)); + updateDatasetFSOs.add( + uploadFile( + files, + uploadedFileCache, + user, + String.format(NIH_INSTITUTIONAL_CERTIFICATION_NAME, 0), + FileCategory.NIH_INSTITUTIONAL_CERTIFICATION)); } return updateDatasetFSOs; @@ -418,34 +419,39 @@ private List uploadFilesForDatasetUpdate(Map FormDataBodyPart + * @param files The files the user provided: fileType (e.g., alternativeDataSharingPlan) -> + * FormDataBodyPart * @param uploadedFileCache Previously uploaded files - ensures that the same file is not - * reuploaded if used on different datasets. - * @param user The create user + * reuploaded if used on different datasets. + * @param user The create user * @return The list of FSOs created for this study * @throws IOException if GCS upload fails */ - private List uploadFilesForStudy(Map files, - Map uploadedFileCache, - User user) throws IOException { + private List uploadFilesForStudy( + Map files, Map uploadedFileCache, User user) + throws IOException { List studyFSOs = new ArrayList<>(); if (files.containsKey(ALTERNATIVE_DATA_SHARING_PLAN_NAME)) { - studyFSOs.add(uploadFile( - files, uploadedFileCache, user, - ALTERNATIVE_DATA_SHARING_PLAN_NAME, - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN)); + studyFSOs.add( + uploadFile( + files, + uploadedFileCache, + user, + ALTERNATIVE_DATA_SHARING_PLAN_NAME, + FileCategory.ALTERNATIVE_DATA_SHARING_PLAN)); } return studyFSOs; } - private FileStorageObject uploadFile(Map files, + private FileStorageObject uploadFile( + Map files, Map uploadedFileCache, User user, String name, - FileCategory category) throws IOException { + FileCategory category) + throws IOException { FormDataBodyPart bodyPart = files.get(name); @@ -466,16 +472,17 @@ private FileStorageObject uploadFile(Map files, return fso; } - // TODO: refactor these DatasetPropertyExtractors into something cleaner - they work, but they feel a bit clunky. + // TODO: refactor these DatasetPropertyExtractors into something cleaner - they work, but they + // feel a bit clunky. // perhaps a separate class which is more generic would work better. /** * Extracts an individual field as a dataset property. * - * @param name The human-readable name of the field + * @param name The human-readable name of the field * @param schemaProp The schema property name (camelCase) - * @param type The type of the field, e.g. Boolean, String - * @param getField Lambda which gets the field's value + * @param type The type of the field, e.g. Boolean, String + * @param getField Lambda which gets the field's value */ public record DatasetPropertyExtractor( String name, @@ -485,8 +492,7 @@ public record DatasetPropertyExtractor( * Takes in: Dataset registration object and consent group * Produces: The value of the field, can be null if field not present. */ - Function getField - ) { + Function getField) { /** * Converts a field on the given registration to a DatasetProperty. @@ -507,7 +513,6 @@ Optional extract(ConsentGroup consentGroup) { datasetProperty.setPropertyValue(this.type.coerce(value.toString())); return Optional.of(datasetProperty); - } } @@ -518,14 +523,13 @@ public record StudyPropertyExtractor( * Takes in: Dataset registration object * Produces: The value of the field, can be null if field not present. */ - Function getField - ) { + Function getField) { /** * Converts a field on the given registration to a StudyProperty. * - * @param registration The registration object to extract from = * @return The study - * property, if the field has a value, otherwise Optional.empty() + * @param registration The registration object to extract from = * @return The study property, + * if the field has a value, otherwise Optional.empty() */ Optional extract(DatasetRegistrationSchemaV1 registration) { Object value = this.getField.apply(registration); @@ -539,199 +543,239 @@ Optional extract(DatasetRegistrationSchemaV1 registration) { studyProperty.setValue(this.type.coerce(value.toString())); return Optional.of(studyProperty); - } } - - private static final List DATASET_REGISTRATION_V1_STUDY_PROPERTY_EXTRACTORS = List.of( - new StudyPropertyExtractor( - "studyType", PropertyType.String, - (registration) -> { - if (Objects.nonNull(registration.getStudyType())) { - return registration.getStudyType().value(); - } - return null; - }), - new StudyPropertyExtractor( - "phenotypeIndication", PropertyType.String, - DatasetRegistrationSchemaV1::getPhenotypeIndication), - new StudyPropertyExtractor( - "species", PropertyType.String, - DatasetRegistrationSchemaV1::getSpecies), - new StudyPropertyExtractor( - "dataCustodianEmail", PropertyType.Json, - (registration) -> { - if (Objects.nonNull(registration.getDataCustodianEmail())) { - return GsonUtil.getInstance().toJson(registration.getDataCustodianEmail()); - } - return null; - - }), - new StudyPropertyExtractor( - "nihAnvilUse", PropertyType.String, - DatasetRegistrationSchemaV1::getNihAnvilUse), - new StudyPropertyExtractor( - "submittingToAnvil", PropertyType.Boolean, - DatasetRegistrationSchemaV1::getSubmittingToAnvil), - new StudyPropertyExtractor( - "dbGaPPhsID", PropertyType.String, - DatasetRegistrationSchemaV1::getDbGaPPhsID), - new StudyPropertyExtractor( - "dbGaPStudyRegistrationName", PropertyType.String, - DatasetRegistrationSchemaV1::getDbGaPStudyRegistrationName), - new StudyPropertyExtractor( - "embargoReleaseDate", PropertyType.Date, - DatasetRegistrationSchemaV1::getEmbargoReleaseDate), - new StudyPropertyExtractor( - "sequencingCenter", PropertyType.String, - DatasetRegistrationSchemaV1::getSequencingCenter), - new StudyPropertyExtractor( - "piInstitution", PropertyType.Number, - DatasetRegistrationSchemaV1::getPiInstitution), - new StudyPropertyExtractor( - "nihGrantContractNumber", PropertyType.String, - DatasetRegistrationSchemaV1::getNihGrantContractNumber), - new StudyPropertyExtractor( - "nihICsSupportingStudy", PropertyType.Json, - (registration) -> { - if (Objects.nonNull(registration.getNihICsSupportingStudy())) { - return GsonUtil.getInstance().toJson( - registration.getNihICsSupportingStudy().stream().map(NihICsSupportingStudy::value) - .toList()); - } - return null; - }), - new StudyPropertyExtractor( - "nihProgramOfficerName", PropertyType.String, - DatasetRegistrationSchemaV1::getNihProgramOfficerName), - new StudyPropertyExtractor( - "nihInstitutionCenterSubmission", PropertyType.String, - (registration) -> { - if (Objects.nonNull(registration.getNihInstitutionCenterSubmission())) { - return registration.getNihInstitutionCenterSubmission().value(); - } - return null; - }), - new StudyPropertyExtractor( - "nihGenomicProgramAdministratorName", PropertyType.String, - DatasetRegistrationSchemaV1::getNihGenomicProgramAdministratorName), - new StudyPropertyExtractor( - "multiCenterStudy", PropertyType.Boolean, - DatasetRegistrationSchemaV1::getMultiCenterStudy), - new StudyPropertyExtractor( - "collaboratingSites", PropertyType.Json, - (registration) -> { - if (Objects.nonNull(registration.getCollaboratingSites())) { - return GsonUtil.getInstance().toJson(registration.getCollaboratingSites()); - } - return null; - }), - new StudyPropertyExtractor( - "controlledAccessRequiredForGenomicSummaryResultsGSR", PropertyType.Boolean, - DatasetRegistrationSchemaV1::getControlledAccessRequiredForGenomicSummaryResultsGSR), - new StudyPropertyExtractor( - "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation", - PropertyType.String, - DatasetRegistrationSchemaV1::getControlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation), - new StudyPropertyExtractor( - "alternativeDataSharingPlan", PropertyType.Boolean, - DatasetRegistrationSchemaV1::getAlternativeDataSharingPlan), - new StudyPropertyExtractor( - "alternativeDataSharingPlanReasons", PropertyType.Json, - (registration) -> { - if (Objects.nonNull(registration.getAlternativeDataSharingPlanReasons())) { - return GsonUtil.getInstance().toJson( - registration.getAlternativeDataSharingPlanReasons().stream() - .map(AlternativeDataSharingPlanReason::value).toList()); - } - return null; - }), - new StudyPropertyExtractor( - "alternativeDataSharingPlanExplanation", PropertyType.String, - DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanExplanation), - new StudyPropertyExtractor( - "alternativeDataSharingPlanFileName", PropertyType.String, - DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanFileName), - new StudyPropertyExtractor( - "alternativeDataSharingPlanDataSubmitted", PropertyType.String, - (registration) -> { - if (Objects.nonNull(registration.getAlternativeDataSharingPlanDataSubmitted())) { - return registration.getAlternativeDataSharingPlanDataSubmitted().value(); - } - return null; - }), - new StudyPropertyExtractor( - "alternativeDataSharingPlanDataReleased", PropertyType.Boolean, - DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanDataReleased), - new StudyPropertyExtractor( - "alternativeDataSharingPlanTargetDeliveryDate", PropertyType.Date, - DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanTargetDeliveryDate), - new StudyPropertyExtractor( - "alternativeDataSharingPlanTargetPublicReleaseDate", PropertyType.Date, - DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanTargetPublicReleaseDate), - new StudyPropertyExtractor( - "alternativeDataSharingPlanAccessManagement", PropertyType.String, - (registration) -> { - if (Objects.nonNull(registration.getAlternativeDataSharingPlanAccessManagement())) { - return registration.getAlternativeDataSharingPlanAccessManagement().value(); - } - return null; - }), - new StudyPropertyExtractor( - "assets", PropertyType.Json, - (registration) -> { - if (Objects.nonNull(registration.getAssets()) && !registration.getAssets().isEmpty()) { - return GsonUtil.getInstance().toJson(registration.getAssets()); - } - return null; - }) - ); - - - private static final List DATASET_REGISTRATION_V1_DATASET_PROPERTY_EXTRACTORS = List.of( - new DatasetPropertyExtractor( - "Data Location", "dataLocation", PropertyType.String, - (consentGroup) -> { - if (Objects.nonNull(consentGroup.getDataLocation())) { - return consentGroup.getDataLocation().value(); - } - return null; - }), - new DatasetPropertyExtractor( - "# of participants", "numberOfParticipants", PropertyType.Number, - ConsentGroup::getNumberOfParticipants), - new DatasetPropertyExtractor( - "File Types", "fileTypes", PropertyType.Json, - (consentGroup) -> { - if (Objects.nonNull(consentGroup.getFileTypes())) { - return GsonUtil.getInstance().toJson(consentGroup.getFileTypes()); - } - return null; - }), - new DatasetPropertyExtractor( - "URL", "url", PropertyType.String, - (consentGroup) -> { - if (Objects.nonNull(consentGroup.getUrl())) { - return consentGroup.getUrl(); - } - return null; - }), - new DatasetPropertyExtractor( - "Access Management", "accessManagement", PropertyType.String, - (consentGroup) -> { - if (Objects.nonNull(consentGroup.getAccessManagement())) { - return consentGroup.getAccessManagement().value(); - } - return null; - }) - ); + private static final List + DATASET_REGISTRATION_V1_STUDY_PROPERTY_EXTRACTORS = + List.of( + new StudyPropertyExtractor( + "studyType", + PropertyType.String, + (registration) -> { + if (Objects.nonNull(registration.getStudyType())) { + return registration.getStudyType().value(); + } + return null; + }), + new StudyPropertyExtractor( + "phenotypeIndication", + PropertyType.String, + DatasetRegistrationSchemaV1::getPhenotypeIndication), + new StudyPropertyExtractor( + "species", PropertyType.String, DatasetRegistrationSchemaV1::getSpecies), + new StudyPropertyExtractor( + "dataCustodianEmail", + PropertyType.Json, + (registration) -> { + if (Objects.nonNull(registration.getDataCustodianEmail())) { + return GsonUtil.getInstance().toJson(registration.getDataCustodianEmail()); + } + return null; + }), + new StudyPropertyExtractor( + "nihAnvilUse", PropertyType.String, DatasetRegistrationSchemaV1::getNihAnvilUse), + new StudyPropertyExtractor( + "submittingToAnvil", + PropertyType.Boolean, + DatasetRegistrationSchemaV1::getSubmittingToAnvil), + new StudyPropertyExtractor( + "dbGaPPhsID", PropertyType.String, DatasetRegistrationSchemaV1::getDbGaPPhsID), + new StudyPropertyExtractor( + "dbGaPStudyRegistrationName", + PropertyType.String, + DatasetRegistrationSchemaV1::getDbGaPStudyRegistrationName), + new StudyPropertyExtractor( + "embargoReleaseDate", + PropertyType.Date, + DatasetRegistrationSchemaV1::getEmbargoReleaseDate), + new StudyPropertyExtractor( + "sequencingCenter", + PropertyType.String, + DatasetRegistrationSchemaV1::getSequencingCenter), + new StudyPropertyExtractor( + "piInstitution", + PropertyType.Number, + DatasetRegistrationSchemaV1::getPiInstitution), + new StudyPropertyExtractor( + "nihGrantContractNumber", + PropertyType.String, + DatasetRegistrationSchemaV1::getNihGrantContractNumber), + new StudyPropertyExtractor( + "nihICsSupportingStudy", + PropertyType.Json, + (registration) -> { + if (Objects.nonNull(registration.getNihICsSupportingStudy())) { + return GsonUtil.getInstance() + .toJson( + registration.getNihICsSupportingStudy().stream() + .map(NihICsSupportingStudy::value) + .toList()); + } + return null; + }), + new StudyPropertyExtractor( + "nihProgramOfficerName", + PropertyType.String, + DatasetRegistrationSchemaV1::getNihProgramOfficerName), + new StudyPropertyExtractor( + "nihInstitutionCenterSubmission", + PropertyType.String, + (registration) -> { + if (Objects.nonNull(registration.getNihInstitutionCenterSubmission())) { + return registration.getNihInstitutionCenterSubmission().value(); + } + return null; + }), + new StudyPropertyExtractor( + "nihGenomicProgramAdministratorName", + PropertyType.String, + DatasetRegistrationSchemaV1::getNihGenomicProgramAdministratorName), + new StudyPropertyExtractor( + "multiCenterStudy", + PropertyType.Boolean, + DatasetRegistrationSchemaV1::getMultiCenterStudy), + new StudyPropertyExtractor( + "collaboratingSites", + PropertyType.Json, + (registration) -> { + if (Objects.nonNull(registration.getCollaboratingSites())) { + return GsonUtil.getInstance().toJson(registration.getCollaboratingSites()); + } + return null; + }), + new StudyPropertyExtractor( + "controlledAccessRequiredForGenomicSummaryResultsGSR", + PropertyType.Boolean, + DatasetRegistrationSchemaV1 + ::getControlledAccessRequiredForGenomicSummaryResultsGSR), + new StudyPropertyExtractor( + "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation", + PropertyType.String, + DatasetRegistrationSchemaV1 + ::getControlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation), + new StudyPropertyExtractor( + "alternativeDataSharingPlan", + PropertyType.Boolean, + DatasetRegistrationSchemaV1::getAlternativeDataSharingPlan), + new StudyPropertyExtractor( + "alternativeDataSharingPlanReasons", + PropertyType.Json, + (registration) -> { + if (Objects.nonNull(registration.getAlternativeDataSharingPlanReasons())) { + return GsonUtil.getInstance() + .toJson( + registration.getAlternativeDataSharingPlanReasons().stream() + .map(AlternativeDataSharingPlanReason::value) + .toList()); + } + return null; + }), + new StudyPropertyExtractor( + "alternativeDataSharingPlanExplanation", + PropertyType.String, + DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanExplanation), + new StudyPropertyExtractor( + "alternativeDataSharingPlanFileName", + PropertyType.String, + DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanFileName), + new StudyPropertyExtractor( + "alternativeDataSharingPlanDataSubmitted", + PropertyType.String, + (registration) -> { + if (Objects.nonNull( + registration.getAlternativeDataSharingPlanDataSubmitted())) { + return registration.getAlternativeDataSharingPlanDataSubmitted().value(); + } + return null; + }), + new StudyPropertyExtractor( + "alternativeDataSharingPlanDataReleased", + PropertyType.Boolean, + DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanDataReleased), + new StudyPropertyExtractor( + "alternativeDataSharingPlanTargetDeliveryDate", + PropertyType.Date, + DatasetRegistrationSchemaV1::getAlternativeDataSharingPlanTargetDeliveryDate), + new StudyPropertyExtractor( + "alternativeDataSharingPlanTargetPublicReleaseDate", + PropertyType.Date, + DatasetRegistrationSchemaV1 + ::getAlternativeDataSharingPlanTargetPublicReleaseDate), + new StudyPropertyExtractor( + "alternativeDataSharingPlanAccessManagement", + PropertyType.String, + (registration) -> { + if (Objects.nonNull( + registration.getAlternativeDataSharingPlanAccessManagement())) { + return registration.getAlternativeDataSharingPlanAccessManagement().value(); + } + return null; + }), + new StudyPropertyExtractor( + "assets", + PropertyType.Json, + (registration) -> { + if (Objects.nonNull(registration.getAssets()) + && !registration.getAssets().isEmpty()) { + return GsonUtil.getInstance().toJson(registration.getAssets()); + } + return null; + })); + + private static final List + DATASET_REGISTRATION_V1_DATASET_PROPERTY_EXTRACTORS = + List.of( + new DatasetPropertyExtractor( + "Data Location", + "dataLocation", + PropertyType.String, + (consentGroup) -> { + if (Objects.nonNull(consentGroup.getDataLocation())) { + return consentGroup.getDataLocation().value(); + } + return null; + }), + new DatasetPropertyExtractor( + "# of participants", + "numberOfParticipants", + PropertyType.Number, + ConsentGroup::getNumberOfParticipants), + new DatasetPropertyExtractor( + "File Types", + "fileTypes", + PropertyType.Json, + (consentGroup) -> { + if (Objects.nonNull(consentGroup.getFileTypes())) { + return GsonUtil.getInstance().toJson(consentGroup.getFileTypes()); + } + return null; + }), + new DatasetPropertyExtractor( + "URL", + "url", + PropertyType.String, + (consentGroup) -> { + if (Objects.nonNull(consentGroup.getUrl())) { + return consentGroup.getUrl(); + } + return null; + }), + new DatasetPropertyExtractor( + "Access Management", + "accessManagement", + PropertyType.String, + (consentGroup) -> { + if (Objects.nonNull(consentGroup.getAccessManagement())) { + return consentGroup.getAccessManagement().value(); + } + return null; + })); private List convertRegistrationToStudyProperties( DatasetRegistrationSchemaV1 registration) { - return DATASET_REGISTRATION_V1_STUDY_PROPERTY_EXTRACTORS - .stream() + return DATASET_REGISTRATION_V1_STUDY_PROPERTY_EXTRACTORS.stream() .map((e) -> e.extract(registration)) .filter(Optional::isPresent) .map(Optional::get) @@ -740,8 +784,7 @@ private List convertRegistrationToStudyProperties( private List convertConsentGroupToDatasetProperties(ConsentGroup consentGroup) { - return DATASET_REGISTRATION_V1_DATASET_PROPERTY_EXTRACTORS - .stream() + return DATASET_REGISTRATION_V1_DATASET_PROPERTY_EXTRACTORS.stream() .map((e) -> e.extract(consentGroup)) .filter(Optional::isPresent) .map(Optional::get) @@ -752,20 +795,22 @@ private List convertConsentGroupToDatasetProperties(ConsentGrou * Extracts the datasets that were created from the given study update by subtracting the updated * datasets from the list of datasets in the study. * - * @param updatedStudy The study that was updated + * @param updatedStudy The study that was updated * @param datasetUpdates The list of datasets that were updated in the study * @return The list of datasets that were created from updated study */ - public List createdDatasetsFromUpdatedStudy(Study updatedStudy, - List datasetUpdates) { - List datasetUpdateIds = (datasetUpdates == null) ? - List.of() : - datasetUpdates.stream().map(DatasetServiceDAO.DatasetUpdate::datasetId).toList(); + public List createdDatasetsFromUpdatedStudy( + Study updatedStudy, List datasetUpdates) { + List datasetUpdateIds = + (datasetUpdates == null) + ? List.of() + : datasetUpdates.stream().map(DatasetServiceDAO.DatasetUpdate::datasetId).toList(); if (updatedStudy.getDatasets() == null) { return List.of(); } - return updatedStudy.getDatasets().stream().filter( - dataset -> !datasetUpdateIds.contains(dataset.getDatasetId())).toList(); + return updatedStudy.getDatasets().stream() + .filter(dataset -> !datasetUpdateIds.contains(dataset.getDatasetId())) + .toList(); } /** @@ -778,22 +823,21 @@ public void sendDatasetSubmittedEmails(List datasets) { for (Dataset dataset : datasets) { Dac dac = dacDAO.findById(dataset.getDacId()); if (dac == null) { - logWarn("Could not find DAC for dataset with identifier: " + dataset.getDatasetIdentifier()); + logWarn( + "Could not find DAC for dataset with identifier: " + dataset.getDatasetIdentifier()); } - List chairPersons = (dac == null) ? List.of() : - dacDAO - .findMembersByDacId(dac.getDacId()) - .stream() - .filter(user -> user.hasUserRole(UserRoles.CHAIRPERSON)) - .toList(); + List chairPersons = + (dac == null) + ? List.of() + : dacDAO.findMembersByDacId(dac.getDacId()).stream() + .filter(user -> user.hasUserRole(UserRoles.CHAIRPERSON)) + .toList(); if (chairPersons.isEmpty()) { logWarn("No chairpersons found for Dataset " + dataset.getDatasetIdentifier()); } else { for (User dacChair : chairPersons) { - emailService.sendDatasetSubmittedMessage(dacChair, - dataset.getCreateUser(), - dac.getName(), - dataset.getName()); + emailService.sendDatasetSubmittedMessage( + dacChair, dataset.getCreateUser(), dac.getName(), dataset.getName()); } } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/DatasetService.java b/src/main/java/org/broadinstitute/consent/http/service/DatasetService.java index b5883f9271..860771d723 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DatasetService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DatasetService.java @@ -90,8 +90,8 @@ public List findDatasetListByDacIds(List dacIds) { } /** - * TODO: Refactor this to throw a NotFoundException instead of returning null - * Finds a Dataset by a formatted dataset identifier. + * TODO: Refactor this to throw a NotFoundException instead of returning null Finds a Dataset by a + * formatted dataset identifier. * * @param datasetIdentifier The formatted identifier, e.g. DUOS-123456 * @return the Dataset with the given identifier, if found. @@ -121,8 +121,8 @@ public Dataset findDatasetByIdentifier(User user, String datasetIdentifier) * @return the Dataset with the given identifier, if found. * @throws IllegalArgumentException if datasetIdentifier is invalid */ - public Dataset findMinimalDatasetByIdentifier(User user, String datasetIdentifier, boolean populateStudy) - throws IllegalArgumentException { + public Dataset findMinimalDatasetByIdentifier( + User user, String datasetIdentifier, boolean populateStudy) throws IllegalArgumentException { Integer alias = Dataset.parseIdentifierToAlias(datasetIdentifier); Dataset d = datasetDAO.findMinimalDatasetByAlias(alias); if (d == null) { @@ -700,8 +700,7 @@ private Integer updateStudyFromConversion( return studyId; } - public DatasetAuthorizationReader addAuthorizedReader( - long id, long userId, long operatorId) { + public DatasetAuthorizationReader addAuthorizedReader(long id, long userId, long operatorId) { long recordId = datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(id, userId, operatorId); return datasetAuthorizationReaderDAO.findAuthorizedReaderByRecordId(recordId); diff --git a/src/main/java/org/broadinstitute/consent/http/service/DraftService.java b/src/main/java/org/broadinstitute/consent/http/service/DraftService.java index 03a6f55ad8..e8f8d8847e 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/DraftService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/DraftService.java @@ -38,8 +38,8 @@ public DraftInterface getAuthorizedDraft(UUID uuid, User user) { return draftServiceDAO.getAuthorizedDraft(uuid, user); } - public List addAttachments(DraftInterface draft, User user, - Map files) + public List addAttachments( + DraftInterface draft, User user, Map files) throws SQLException, RuntimeException { return draftServiceDAO.addAttachments(draft, user, files); } diff --git a/src/main/java/org/broadinstitute/consent/http/service/ElasticSearchService.java b/src/main/java/org/broadinstitute/consent/http/service/ElasticSearchService.java index 9bcf3945fa..1deec29ee3 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/ElasticSearchService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/ElasticSearchService.java @@ -53,8 +53,8 @@ public class ElasticSearchService implements ConsentLogger { - private final ExecutorService executorService = new ThreadUtils().getExecutorService( - ElasticSearchService.class); + private final ExecutorService executorService = + new ThreadUtils().getExecutorService(ElasticSearchService.class); private final RestClient esClient; private final ElasticSearchConfiguration esConfig; private final DacDAO dacDAO; @@ -88,11 +88,13 @@ public ElasticSearchService( private static final int MAX_RESULT_WINDOW = 10000; - private static final String BULK_HEADER = """ + private static final String BULK_HEADER = + """ { "index": {"_type": "dataset", "_id": "%d"} } """; - private static final String DELETE_QUERY = """ + private static final String DELETE_QUERY = + """ { "query": { "bool": { "must": [ { "match": { "_type": "dataset" } }, { "match": { "_id": "%d" } } ] } } } """; @@ -102,38 +104,34 @@ private Response performRequest(Request request) throws IOException { if (status != 200) { throw new IOException("Invalid Elasticsearch query"); } - var body = new String(response.getEntity().getContent().readAllBytes(), - StandardCharsets.UTF_8); + var body = new String(response.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8); return Response.status(status).entity(body).build(); } public Response indexDatasetTerms(List datasets, User user) throws IOException { List bulkApiCall = new ArrayList<>(); - datasets.forEach(dsTerm -> { - bulkApiCall.add(BULK_HEADER.formatted(dsTerm.getDatasetId())); - bulkApiCall.add(GsonUtil.getInstance().toJson(dsTerm) + "\n"); - updateDatasetIndexDate(dsTerm.getDatasetId(), user.getUserId(), Instant.now()); - }); + datasets.forEach( + dsTerm -> { + bulkApiCall.add(BULK_HEADER.formatted(dsTerm.getDatasetId())); + bulkApiCall.add(GsonUtil.getInstance().toJson(dsTerm) + "\n"); + updateDatasetIndexDate(dsTerm.getDatasetId(), user.getUserId(), Instant.now()); + }); - Request bulkRequest = new Request( - HttpMethod.PUT, - "/" + esConfig.getDatasetIndexName() + "/_bulk"); + Request bulkRequest = + new Request(HttpMethod.PUT, "/" + esConfig.getDatasetIndexName() + "/_bulk"); - bulkRequest.setEntity(new NStringEntity( - String.join("", bulkApiCall) + "\n", - ContentType.APPLICATION_JSON)); + bulkRequest.setEntity( + new NStringEntity(String.join("", bulkApiCall) + "\n", ContentType.APPLICATION_JSON)); return performRequest(bulkRequest); } public Response deleteIndex(Integer datasetId, Integer userId) throws IOException { - Request deleteRequest = new Request( - HttpMethod.POST, - "/" + esConfig.getDatasetIndexName() + "/_delete_by_query"); - deleteRequest.setEntity(new NStringEntity( - DELETE_QUERY.formatted(datasetId), - ContentType.APPLICATION_JSON)); + Request deleteRequest = + new Request(HttpMethod.POST, "/" + esConfig.getDatasetIndexName() + "/_delete_by_query"); + deleteRequest.setEntity( + new NStringEntity(DELETE_QUERY.formatted(datasetId), ContentType.APPLICATION_JSON)); updateDatasetIndexDate(datasetId, userId, null); return performRequest(deleteRequest); } @@ -158,14 +156,14 @@ public boolean validateQuery(String query) throws IOException { } // Remove `sort`, `size` and `from` parameters from query, otherwise validation will fail - var modifiedQuery = query - .replaceAll("\"sort\": ?\\[(.*?)\\],?", "") - .replaceAll("\"size\": ?\\d+,?", "") - .replaceAll("\"from\": ?\\d+,?", ""); - - Request validateRequest = new Request( - HttpMethod.GET, - "/" + esConfig.getDatasetIndexName() + "/_validate/query"); + var modifiedQuery = + query + .replaceAll("\"sort\": ?\\[(.*?)\\],?", "") + .replaceAll("\"size\": ?\\d+,?", "") + .replaceAll("\"from\": ?\\d+,?", ""); + + Request validateRequest = + new Request(HttpMethod.GET, "/" + esConfig.getDatasetIndexName() + "/_validate/query"); validateRequest.setEntity(new NStringEntity(modifiedQuery, ContentType.APPLICATION_JSON)); Response response = performRequest(validateRequest); @@ -180,9 +178,8 @@ public Response searchDatasets(String query) throws IOException { throw new IOException("Invalid Elasticsearch query"); } - Request searchRequest = new Request( - HttpMethod.GET, - "/" + esConfig.getDatasetIndexName() + "/_search"); + Request searchRequest = + new Request(HttpMethod.GET, "/" + esConfig.getDatasetIndexName() + "/_search"); searchRequest.setEntity(new NStringEntity(query, ContentType.APPLICATION_JSON)); Response response = performRequest(searchRequest); @@ -208,34 +205,23 @@ public StudyTerm toStudyTerm(Study study) { term.setPiName(study.getPiName()); term.setPublicVisibility(study.getPublicVisibility()); - findStudyProperty( - study.getProperties(), "dbGaPPhsID" - ).ifPresent( - prop -> term.setPhsId(prop.getValue().toString()) - ); - - findStudyProperty( - study.getProperties(), "phenotypeIndication" - ).ifPresent( - prop -> term.setPhenotype(prop.getValue().toString()) - ); - - findStudyProperty( - study.getProperties(), "species" - ).ifPresent( - prop -> term.setSpecies(prop.getValue().toString()) - ); - - findStudyProperty( - study.getProperties(), "dataCustodianEmail" - ).ifPresent( - prop -> { - JsonArray jsonArray = (JsonArray) prop.getValue(); - List dataCustodianEmail = new ArrayList<>(); - jsonArray.forEach(email -> dataCustodianEmail.add(email.getAsString())); - term.setDataCustodianEmail(dataCustodianEmail); - } - ); + findStudyProperty(study.getProperties(), "dbGaPPhsID") + .ifPresent(prop -> term.setPhsId(prop.getValue().toString())); + + findStudyProperty(study.getProperties(), "phenotypeIndication") + .ifPresent(prop -> term.setPhenotype(prop.getValue().toString())); + + findStudyProperty(study.getProperties(), "species") + .ifPresent(prop -> term.setSpecies(prop.getValue().toString())); + + findStudyProperty(study.getProperties(), "dataCustodianEmail") + .ifPresent( + prop -> { + JsonArray jsonArray = (JsonArray) prop.getValue(); + List dataCustodianEmail = new ArrayList<>(); + jsonArray.forEach(email -> dataCustodianEmail.add(email.getAsString())); + term.setDataCustodianEmail(dataCustodianEmail); + }); if (Objects.nonNull(study.getCreateUserId())) { term.setDataSubmitterId(study.getCreateUserId()); @@ -249,31 +235,33 @@ public StudyTerm toStudyTerm(Study study) { term.setDataSubmitterEmail(study.getCreateUserEmail()); } - findStudyProperty( - study.getProperties(), "assets" - ).ifPresent( - prop -> { - Object value = prop.getValue(); - Map assetsMap; - // When property is loaded from db it is deserialized as JsonObject - if (value instanceof com.google.gson.JsonElement) { - assetsMap = GsonUtil.getInstance().fromJson( - (com.google.gson.JsonElement) value, - new com.google.gson.reflect.TypeToken>(){}.getType() - ); - // Otherwise Gson deserializes JSON and creates a LinkedTreeMap - } else if (value instanceof Map) { - assetsMap = (Map) value; - // Fallback: try to parse as JSON string - } else { - assetsMap = GsonUtil.getInstance().fromJson( - value.toString(), - new com.google.gson.reflect.TypeToken>(){}.getType() - ); - } - term.setAssets(assetsMap); - } - ); + findStudyProperty(study.getProperties(), "assets") + .ifPresent( + prop -> { + Object value = prop.getValue(); + Map assetsMap; + // When property is loaded from db it is deserialized as JsonObject + if (value instanceof com.google.gson.JsonElement) { + assetsMap = + GsonUtil.getInstance() + .fromJson( + (com.google.gson.JsonElement) value, + new com.google.gson.reflect.TypeToken< + Map>() {}.getType()); + // Otherwise Gson deserializes JSON and creates a LinkedTreeMap + } else if (value instanceof Map) { + assetsMap = (Map) value; + // Fallback: try to parse as JSON string + } else { + assetsMap = + GsonUtil.getInstance() + .fromJson( + value.toString(), + new com.google.gson.reflect.TypeToken< + Map>() {}.getType()); + } + term.setAssets(assetsMap); + }); return term; } @@ -282,9 +270,10 @@ public UserTerm toUserTerm(User user) { if (Objects.isNull(user)) { return null; } - InstitutionTerm institution = (Objects.nonNull(user.getInstitutionId())) ? - toInstitutionTerm(institutionDAO.findInstitutionById(user.getInstitutionId())) : - null; + InstitutionTerm institution = + (Objects.nonNull(user.getInstitutionId())) + ? toInstitutionTerm(institutionDAO.findInstitutionById(user.getInstitutionId())) + : null; return new UserTerm(user.getUserId(), user.getDisplayName(), institution); } @@ -303,31 +292,34 @@ public InstitutionTerm toInstitutionTerm(Institution institution) { } public void asyncDatasetInESIndex(Integer datasetId, User user, boolean force) { - ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator( - executorService); + ListeningExecutorService listeningExecutorService = + MoreExecutors.listeningDecorator(executorService); ListenableFuture syncFuture = - listeningExecutorService.submit(() -> { - Dataset dataset = datasetDAO.findDatasetById(datasetId); - synchronizeDatasetInESIndex(dataset, user, force); - return dataset; - }); + listeningExecutorService.submit( + () -> { + Dataset dataset = datasetDAO.findDatasetById(datasetId); + synchronizeDatasetInESIndex(dataset, user, force); + return dataset; + }); Futures.addCallback( syncFuture, new FutureCallback<>() { @Override public void onSuccess(Dataset d) { - logInfo("Successfully synchronized dataset in ES index: %s".formatted( - d.getDatasetIdentifier())); + logInfo( + "Successfully synchronized dataset in ES index: %s" + .formatted(d.getDatasetIdentifier())); } @Override public void onFailure(Throwable t) { - logWarn("Failed to synchronize dataset in ES index: %s".formatted(datasetId) + ": " - + t.getMessage()); + logWarn( + "Failed to synchronize dataset in ES index: %s".formatted(datasetId) + + ": " + + t.getMessage()); } }, - listeningExecutorService - ); + listeningExecutorService); } /** @@ -336,8 +328,8 @@ public void onFailure(Throwable t) { * update the dataset's last indexed date value. * * @param dataset The Dataset - * @param user The User - * @param force Boolean to force the index update regardless of dataset's indexed date status. + * @param user The User + * @param force Boolean to force the index update regardless of dataset's indexed date status. */ public void synchronizeDatasetInESIndex(Dataset dataset, User user, boolean force) { if (force || dataset.getIndexedDate() != null) { @@ -358,10 +350,8 @@ public Response indexDataset(Integer datasetId, User user) throws IOException { public Response indexDatasets(List datasetIds, User user) throws IOException { // Datasets in list context may not have their study populated, so we need to ensure that is // true before trying to index them in ES. - List datasetTerms = datasetIds.stream() - .map(datasetDAO::findDatasetById) - .map(this::toDatasetTerm) - .toList(); + List datasetTerms = + datasetIds.stream().map(datasetDAO::findDatasetById).map(this::toDatasetTerm).toList(); return indexDatasetTerms(datasetTerms, user); } @@ -377,17 +367,18 @@ public StreamingOutput indexDatasetIds(List datasetIds, User user) { Integer lastDatasetId = datasetIds.get(datasetIds.size() - 1); return output -> { output.write("[".getBytes()); - datasetIds.forEach(id -> { - try (Response response = indexDataset(id, user)) { - output.write(response.getEntity().toString().getBytes()); - if (!id.equals(lastDatasetId)) { - output.write(",".getBytes()); - } - output.write("\n".getBytes()); - } catch (IOException e) { - logException("Error indexing dataset term for dataset id: %d ".formatted(id), e); - } - }); + datasetIds.forEach( + id -> { + try (Response response = indexDataset(id, user)) { + output.write(response.getEntity().toString().getBytes()); + if (!id.equals(lastDatasetId)) { + output.write(",".getBytes()); + } + output.write("\n".getBytes()); + } catch (IOException e) { + logException("Error indexing dataset term for dataset id: %d ".formatted(id), e); + } + }); output.write("]".getBytes()); }; } @@ -414,12 +405,14 @@ public DatasetTerm toDatasetTerm(Dataset dataset) { DatasetTerm term = new DatasetTerm(); term.setDatasetId(dataset.getDatasetId()); - Optional.ofNullable(dataset.getCreateUserId()).ifPresent(userId -> { - User user = userDAO.findUserById(dataset.getCreateUserId()); - term.setCreateUserId(dataset.getCreateUserId()); - term.setCreateUserDisplayName(user.getDisplayName()); - term.setSubmitter(toUserTerm(user)); - }); + Optional.ofNullable(dataset.getCreateUserId()) + .ifPresent( + userId -> { + User user = userDAO.findUserById(dataset.getCreateUserId()); + term.setCreateUserId(dataset.getCreateUserId()); + term.setCreateUserDisplayName(user.getDisplayName()); + term.setSubmitter(toUserTerm(user)); + }); Optional.ofNullable(dataset.getUpdateUserId()) .map(userDAO::findUserById) .map(this::toUserTerm) @@ -432,14 +425,16 @@ public DatasetTerm toDatasetTerm(Dataset dataset) { term.setStudy(toStudyTerm(dataset.getStudy())); } - Optional.ofNullable(dataset.getDacId()).ifPresent(dacId -> { - Dac dac = dacDAO.findById(dataset.getDacId()); - term.setDacId(dataset.getDacId()); - if (Objects.nonNull(dataset.getDacApproval())) { - term.setDacApproval(dataset.getDacApproval()); - } - term.setDac(toDacTerm(dac)); - }); + Optional.ofNullable(dataset.getDacId()) + .ifPresent( + dacId -> { + Dac dac = dacDAO.findById(dataset.getDacId()); + term.setDacId(dataset.getDacId()); + if (Objects.nonNull(dataset.getDacApproval())) { + term.setDacApproval(dataset.getDacApproval()); + } + term.setDac(toDacTerm(dac)); + }); if (Objects.nonNull(dataset.getDataUse())) { DataUseSummary summary = ontologyService.translateDataUseSummary(dataset.getDataUse()); @@ -450,41 +445,34 @@ public DatasetTerm toDatasetTerm(Dataset dataset) { } } - Optional.ofNullable(dataset.getNihInstitutionalCertificationFile()).ifPresent( - obj -> term.setHasInstitutionCertification(true)); - - findDatasetProperty( - dataset.getProperties(), "accessManagement" - ).ifPresent( - datasetProperty -> term.setAccessManagement(datasetProperty.getPropertyValueAsString()) - ); - - findFirstDatasetPropertyByName( - dataset.getProperties(), "# of participants" - ).ifPresent( - datasetProperty -> { - String value = datasetProperty.getPropertyValueAsString(); - try { - term.setParticipantCount(Integer.valueOf(value)); - } catch (NumberFormatException e) { - logWarn( - String.format("Unable to coerce participant count to integer: %s for dataset: %s", - value, dataset.getDatasetIdentifier())); - } - } - ); - - findDatasetProperty( - dataset.getProperties(), "url" - ).ifPresent( - datasetProperty -> term.setUrl(datasetProperty.getPropertyValueAsString()) - ); - - findDatasetProperty( - dataset.getProperties(), "dataLocation" - ).ifPresent( - datasetProperty -> term.setDataLocation(datasetProperty.getPropertyValueAsString()) - ); + Optional.ofNullable(dataset.getNihInstitutionalCertificationFile()) + .ifPresent(obj -> term.setHasInstitutionCertification(true)); + + findDatasetProperty(dataset.getProperties(), "accessManagement") + .ifPresent( + datasetProperty -> + term.setAccessManagement(datasetProperty.getPropertyValueAsString())); + + findFirstDatasetPropertyByName(dataset.getProperties(), "# of participants") + .ifPresent( + datasetProperty -> { + String value = datasetProperty.getPropertyValueAsString(); + try { + term.setParticipantCount(Integer.valueOf(value)); + } catch (NumberFormatException e) { + logWarn( + String.format( + "Unable to coerce participant count to integer: %s for dataset: %s", + value, dataset.getDatasetIdentifier())); + } + }); + + findDatasetProperty(dataset.getProperties(), "url") + .ifPresent(datasetProperty -> term.setUrl(datasetProperty.getPropertyValueAsString())); + + findDatasetProperty(dataset.getProperties(), "dataLocation") + .ifPresent( + datasetProperty -> term.setDataLocation(datasetProperty.getPropertyValueAsString())); return term; } @@ -502,31 +490,28 @@ protected void updateDatasetIndexDate(Integer datasetId, Integer userId, Instant } } - Optional findDatasetProperty(Collection props, - String schemaProp) { - return - (props == null) ? Optional.empty() : props - .stream() + Optional findDatasetProperty( + Collection props, String schemaProp) { + return (props == null) + ? Optional.empty() + : props.stream() .filter(p -> Objects.nonNull(p.getSchemaProperty())) .filter(p -> p.getSchemaProperty().equals(schemaProp)) .findFirst(); } - Optional findFirstDatasetPropertyByName(Collection props, - String propertyName) { - return - (props == null) ? Optional.empty() : props - .stream() + Optional findFirstDatasetPropertyByName( + Collection props, String propertyName) { + return (props == null) + ? Optional.empty() + : props.stream() .filter(p -> p.getPropertyName().equalsIgnoreCase(propertyName)) .findFirst(); } Optional findStudyProperty(Collection props, String key) { - return - (props == null) ? Optional.empty() : props - .stream() - .filter(p -> p.getKey().equals(key)) - .findFirst(); + return (props == null) + ? Optional.empty() + : props.stream().filter(p -> p.getKey().equals(key)).findFirst(); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/ElectionService.java b/src/main/java/org/broadinstitute/consent/http/service/ElectionService.java index 092ee5be96..a6da505c4d 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/ElectionService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/ElectionService.java @@ -16,13 +16,14 @@ public ElectionService(ElectionDAO electionDAO) { } public List findElectionsWithCardHoldingUsersByElectionIds(List electionIds) { - return !electionIds.isEmpty() ? electionDAO.findElectionsWithCardHoldingUsersByElectionIds( - electionIds) : Collections.emptyList(); + return !electionIds.isEmpty() + ? electionDAO.findElectionsWithCardHoldingUsersByElectionIds(electionIds) + : Collections.emptyList(); } public List findElectionsByVoteIdsAndType(List voteIds, String electionType) { - return !voteIds.isEmpty() ? electionDAO.findElectionsByVoteIdsAndType(voteIds, electionType) + return !voteIds.isEmpty() + ? electionDAO.findElectionsByVoteIdsAndType(voteIds, electionType) : Collections.emptyList(); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/EmailService.java b/src/main/java/org/broadinstitute/consent/http/service/EmailService.java index e6ddf82513..106d4e3ae5 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/EmailService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/EmailService.java @@ -111,8 +111,12 @@ protected void sendMessage(MailMessage mailMessage, Integer userId) Template template = templateHelper.getTemplate(mailMessage.getTemplateName()); template.process(mailMessage.createModel(serverUrl), out); String content = out.toString(); - Mail message = new Mail(new Email(fromAccount), mailMessage.createSubject(), - new Email(mailMessage.toUser.getEmail()), new Content("text/html", content)); + Mail message = + new Mail( + new Email(fromAccount), + mailMessage.createSubject(), + new Email(mailMessage.toUser.getEmail()), + new Content("text/html", content)); // Checks that the user has not disabled email before sending Response response = sendGridAPI.sendMessage(message, mailMessage.toUser.getEmail()); saveEmailAndResponse( @@ -125,8 +129,7 @@ protected void sendMessage(MailMessage mailMessage, Integer userId) } public List fetchEmailMessagesByType( - EmailType emailType, Integer limit, - Integer offset) { + EmailType emailType, Integer limit, Integer offset) { return emailDAO.fetchMessagesByType(emailType.getTypeInt(), limit, offset); } @@ -135,13 +138,11 @@ public List fetchEmailM return emailDAO.fetchMessagesByUserId(userId, limit, offset); } - public List fetchEmailMessagesByCreateDate( - Date start, Date end, Integer limit, - Integer offset) { + public List + fetchEmailMessagesByCreateDate(Date start, Date end, Integer limit, Integer offset) { return emailDAO.fetchMessagesByCreateDate(start, end, limit, offset); } - public void sendResearcherDarApproved( String darCode, Integer researcherId, @@ -151,7 +152,9 @@ public void sendResearcherDarApproved( throws TemplateException, IOException { User user = userDAO.findUserById(researcherId); sendMessage( - new ResearcherDarApprovedMessage(user, darCode, datasets, dataUseRestriction, radarApproved), researcherId); + new ResearcherDarApprovedMessage( + user, darCode, datasets, dataUseRestriction, radarApproved), + researcherId); } public void sendResearcherProgressReportApproved( @@ -163,7 +166,9 @@ public void sendResearcherProgressReportApproved( throws TemplateException, IOException { User user = userDAO.findUserById(researcherId); sendMessage( - new ResearcherApprovedProgressReportMessage(user, darCode, datasets, dataUseRestriction, radarApproved), researcherId); + new ResearcherApprovedProgressReportMessage( + user, darCode, datasets, dataUseRestriction, radarApproved), + researcherId); } public void sendDataCustodianApprovalMessage( @@ -229,8 +234,7 @@ public void sendNewDAAUploadResearcherMessage( User researcher, String dacName, String previousDaaName, String newDaaName, Integer userId) throws TemplateException, IOException { sendMessage( - new NewDAAUploadResearcherMessage( - researcher, dacName, previousDaaName, newDaaName), + new NewDAAUploadResearcherMessage(researcher, dacName, previousDaaName, newDaaName), userId); } @@ -252,14 +256,20 @@ public void sendProgressReportNewCollectionElectionMessage(List users, Str public void sendNewDARRequestEmail( User user, Map> dacDatasetMap, String researcherName, String darCode) throws TemplateException, IOException { - sendMessage(new NewDARRequestMessage(user, darCode, dacDatasetMap, researcherName), - user.getUserId()); + sendMessage( + new NewDARRequestMessage(user, darCode, dacDatasetMap, researcherName), user.getUserId()); } public void sendNewProgressReportRequestEmail( - User user, Map> dacDatasetMap, String researcherName, String darCode, String referenceId) + User user, + Map> dacDatasetMap, + String researcherName, + String darCode, + String referenceId) throws TemplateException, IOException { - sendMessage(new NewProgressReportRequestMessage(user, darCode, referenceId, dacDatasetMap, researcherName), + sendMessage( + new NewProgressReportRequestMessage( + user, darCode, referenceId, dacDatasetMap, researcherName), user.getUserId()); } @@ -274,10 +284,11 @@ public void sendNewProgressReportRequestEmail( * @throws TemplateException Template processing exception * @throws IOException IOException when processing the template or sending the email */ - public void sendNewSoDARSubmittedEmail(User user, String darCode, User researcher, String referenceId, List datasets) + public void sendNewSoDARSubmittedEmail( + User user, String darCode, User researcher, String referenceId, List datasets) throws TemplateException, IOException { - sendMessage(new SoDARSubmitted(user, darCode, researcher, referenceId, datasets), - user.getUserId()); + sendMessage( + new SoDARSubmitted(user, darCode, researcher, referenceId, datasets), user.getUserId()); } /** @@ -291,10 +302,11 @@ public void sendNewSoDARSubmittedEmail(User user, String darCode, User researche * @throws TemplateException Template processing exception * @throws IOException IOException when processing the template or sending the email */ - public void sendNewSoProgressReportSubmittedEmail(User user, String darCode, User researcher, String referenceId, List datasets) + public void sendNewSoProgressReportSubmittedEmail( + User user, String darCode, User researcher, String referenceId, List datasets) throws TemplateException, IOException { - sendMessage(new SoPRSubmitted(user, darCode, researcher, referenceId, datasets), - user.getUserId()); + sendMessage( + new SoPRSubmitted(user, darCode, researcher, referenceId, datasets), user.getUserId()); } /** @@ -309,9 +321,18 @@ public void sendNewSoProgressReportSubmittedEmail(User user, String darCode, Use * @throws TemplateException Template processing exception * @throws IOException IOException when processing the template or sending the email */ - public void sendNewSoDARApprovedEmail(User user, String darCode, User researcher, String referenceId, List datasets, String dataUseRestriction, boolean radarApproved) + public void sendNewSoDARApprovedEmail( + User user, + String darCode, + User researcher, + String referenceId, + List datasets, + String dataUseRestriction, + boolean radarApproved) throws TemplateException, IOException { - sendMessage(new SoDARApproved(user, darCode, researcher, referenceId, datasets, dataUseRestriction, radarApproved), + sendMessage( + new SoDARApproved( + user, darCode, researcher, referenceId, datasets, dataUseRestriction, radarApproved), user.getUserId()); } @@ -323,26 +344,36 @@ public void sendNewSoDARApprovedEmail(User user, String darCode, User researcher * @param researcher The researcher whose progress report has been approved * @param referenceId The reference ID of the progress report * @param datasets The datasets associated with the progress report - * @param dataUseRestriction The data use restriction associated with the datasets in the progress report + * @param dataUseRestriction The data use restriction associated with the datasets in the progress + * report * @throws TemplateException Template processing exception * @throws IOException IOException when processing the template or sending the email */ - public void sendNewSoProgressReportApprovedEmail(User user, String darCode, User researcher, String referenceId, List datasets, String dataUseRestriction, boolean radarApproved) + public void sendNewSoProgressReportApprovedEmail( + User user, + String darCode, + User researcher, + String referenceId, + List datasets, + String dataUseRestriction, + boolean radarApproved) throws TemplateException, IOException { - sendMessage(new SoPRApproved(user, darCode, researcher, referenceId, datasets, dataUseRestriction, radarApproved), + sendMessage( + new SoPRApproved( + user, darCode, researcher, referenceId, datasets, dataUseRestriction, radarApproved), user.getUserId()); } /** * Send a message to a researcher that their data access request has expired. * - * @param researcher the researcher to send the message to - * @param darCode the data access request code that's expired - * @param userId the user id of the person sending the message + * @param researcher the researcher to send the message to + * @param darCode the data access request code that's expired + * @param userId the user id of the person sending the message * @param referenceId the data access request reference id that's expired */ - public void sendDarExpiredMessage(User researcher, String darCode, Integer userId, - String referenceId) + public void sendDarExpiredMessage( + User researcher, String darCode, Integer userId, String referenceId) throws TemplateException, IOException { sendMessage(new DarExpiredMessage(researcher, darCode, referenceId), userId); } @@ -350,18 +381,19 @@ public void sendDarExpiredMessage(User researcher, String darCode, Integer userI /** * Remind the user that their data access request is about to expire. * - * @param user the user to send the message to - * @param darCode the data access request code that's about to expire - * @param userId the user id of the person sending the message + * @param user the user to send the message to + * @param darCode the data access request code that's about to expire + * @param userId the user id of the person sending the message * @param referenceId the data access request reference id that is expiring */ - public void sendDarExpirationReminderMessage(User user, String darCode, Integer userId, - String referenceId) + public void sendDarExpirationReminderMessage( + User user, String darCode, Integer userId, String referenceId) throws TemplateException, IOException { sendMessage(new DarExpirationReminderMessage(user, darCode, referenceId), userId); } - public void sendReminderMessage(User user, Vote vote, String darCode, String electionType, String url) + public void sendReminderMessage( + User user, Vote vote, String darCode, String electionType, String url) throws TemplateException, IOException { sendMessage(new ReminderMessage(user, vote, darCode, electionType, url), user.getUserId()); } @@ -369,30 +401,32 @@ public void sendReminderMessage(User user, Vote vote, String darCode, String ele /** * Send a message to a user that their closeout has been completed. * - * @param user the user to send the message to - * @param darCode the data access request code for which closeout is completed + * @param user the user to send the message to + * @param darCode the data access request code for which closeout is completed * @param referenceId the data access request reference id for which closeout is completed */ public void sendResearcherCloseoutCompletedMessage(User user, String darCode, String referenceId) throws TemplateException, IOException { - sendMessage(new ResearcherCloseoutCompletedMessage(user, darCode, referenceId), - user.getUserId()); + sendMessage( + new ResearcherCloseoutCompletedMessage(user, darCode, referenceId), user.getUserId()); } /** * Send a message to a Signing Official or a DAC member that a closeout has been submitted for * review. * - * @param toUser The user to send the message to - * @param darId The Data Access Request ID associated with the closeout + * @param toUser The user to send the message to + * @param darId The Data Access Request ID associated with the closeout * @param referenceId The Reference ID of the closeout request * @param closeoutUrl The URL to the closeout request for review * @throws TemplateException Template processing exception - * @throws IOException IOException when processing the template or sending the email + * @throws IOException IOException when processing the template or sending the email */ - public void sendSubmittedCloseoutMessage(User toUser, String darId, String referenceId, String closeoutUrl) + public void sendSubmittedCloseoutMessage( + User toUser, String darId, String referenceId, String closeoutUrl) throws TemplateException, IOException { - sendMessage(new SubmittedCloseoutMessage(toUser, darId, referenceId, closeoutUrl), toUser.getUserId()); + sendMessage( + new SubmittedCloseoutMessage(toUser, darId, referenceId, closeoutUrl), toUser.getUserId()); } /** diff --git a/src/main/java/org/broadinstitute/consent/http/service/FileStorageObjectService.java b/src/main/java/org/broadinstitute/consent/http/service/FileStorageObjectService.java index fdaaf16d81..d2096fa533 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/FileStorageObjectService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/FileStorageObjectService.java @@ -20,9 +20,8 @@ public class FileStorageObjectService implements ConsentLogger { GCSService gcsService; FileStorageObjectDAO fileStorageObjectDAO; - - public FileStorageObjectService(FileStorageObjectDAO fileStorageObjectDAO, - GCSService gcsService) { + public FileStorageObjectService( + FileStorageObjectDAO fileStorageObjectDAO, GCSService gcsService) { this.fileStorageObjectDAO = fileStorageObjectDAO; this.gcsService = gcsService; } @@ -33,31 +32,28 @@ FileStorageObject uploadAndStoreFile( String mediaType, FileCategory category, String entityId, - Integer createUserId - ) throws IOException { + Integer createUserId) + throws IOException { BlobId blobId; try { // upload to GCS - blobId = gcsService.storeDocument( - content, - mediaType, - UUID.randomUUID()); + blobId = gcsService.storeDocument(content, mediaType, UUID.randomUUID()); } catch (Exception e) { logWarn("Failed to upload file for user id " + createUserId + ": " + e.getMessage()); throw e; } // insert file - Integer fileStorageObjectId = fileStorageObjectDAO.insertNewFile( - fileName, - category.getValue(), - blobId.toGsUtilUri(), - mediaType, - entityId, - createUserId, - Instant.now() - ); + Integer fileStorageObjectId = + fileStorageObjectDAO.insertNewFile( + fileName, + category.getValue(), + blobId.toGsUtilUri(), + mediaType, + entityId, + createUserId, + Instant.now()); return fileStorageObjectDAO.findFileById(fileStorageObjectId); } @@ -80,9 +76,11 @@ private void fetchAndPopulateUploadedFile(FileStorageObject fileStorageObject) private void fetchAndPopulateMultipleUploadedFiles(List fileStorageObjects) throws NotFoundException { try { - Map documentMap = gcsService.getDocuments( - fileStorageObjects.stream().map(FileStorageObject::getBlobId) - .collect(Collectors.toList())); + Map documentMap = + gcsService.getDocuments( + fileStorageObjects.stream() + .map(FileStorageObject::getBlobId) + .collect(Collectors.toList())); fileStorageObjects.forEach((fso) -> fso.setUploadedFile(documentMap.get(fso.getBlobId()))); } catch (NotFoundException e) { @@ -94,18 +92,14 @@ private void fetchAndPopulateMultipleUploadedFiles(List fileS } } - public FileStorageObject fetchById( - Integer fileStorageObjectId - ) throws NotFoundException { + public FileStorageObject fetchById(Integer fileStorageObjectId) throws NotFoundException { FileStorageObject fileStorageObject = fileStorageObjectDAO.findFileById(fileStorageObjectId); // download file from GCS fetchAndPopulateUploadedFile(fileStorageObject); return fileStorageObject; } - public List fetchAllByEntityId( - String entityId - ) throws NotFoundException { + public List fetchAllByEntityId(String entityId) throws NotFoundException { List fileStorageObjects = fileStorageObjectDAO.findFilesByEntityId(entityId); // download all files from GCS fetchAndPopulateMultipleUploadedFiles(fileStorageObjects); @@ -113,10 +107,9 @@ public List fetchAllByEntityId( } public List fetchAllByEntityIdAndCategory( - String entityId, FileCategory category - ) throws NotFoundException { - List fileStorageObjects = fileStorageObjectDAO.findFilesByEntityIdAndCategory( - entityId, category.getValue()); + String entityId, FileCategory category) throws NotFoundException { + List fileStorageObjects = + fileStorageObjectDAO.findFilesByEntityIdAndCategory(entityId, category.getValue()); // download all files from GCS fetchAndPopulateMultipleUploadedFiles(fileStorageObjects); return fileStorageObjects; diff --git a/src/main/java/org/broadinstitute/consent/http/service/InstitutionService.java b/src/main/java/org/broadinstitute/consent/http/service/InstitutionService.java index 20ab98468c..bafe7041da 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/InstitutionService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/InstitutionService.java @@ -23,7 +23,9 @@ public class InstitutionService implements ConsentLogger { private final InstitutionAndLibraryCardEnforcement institutionAndLibraryCardEnforcement; @Inject - public InstitutionService(InstitutionDAO institutionDAO, UserDAO userDAO, + public InstitutionService( + InstitutionDAO institutionDAO, + UserDAO userDAO, InstitutionAndLibraryCardEnforcement institutionAndLibraryCardEnforcement) { this.institutionDAO = institutionDAO; this.userDAO = userDAO; @@ -47,13 +49,13 @@ public Institution createInstitution(Institution institution, Integer userId) { enforceInstitutionAndLibraryCardRules(); return createdInstitution; } catch (SQLException e) { - throw new ServerErrorException("Could not create institution", - HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e); + throw new ServerErrorException( + "Could not create institution", HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e); } } - public Institution updateInstitutionById(Institution institutionPayload, Integer id, - Integer userId) throws SQLException { + public Institution updateInstitutionById( + Institution institutionPayload, Integer id, Integer userId) throws SQLException { checkUserId(userId); Institution targetInstitution = institutionDAO.findInstitutionById(id); isInstitutionNull(targetInstitution); @@ -61,15 +63,15 @@ public Institution updateInstitutionById(Institution institutionPayload, Integer // Name validation checkForEmptyName(institutionPayload); checkNameUniqueness(institutionPayload); - String canonicalName = InstitutionUtil.canonicalizeInstitutionName( - institutionPayload.getName()); + String canonicalName = + InstitutionUtil.canonicalizeInstitutionName(institutionPayload.getName()); institutionPayload.setName(canonicalName); // Domain validation InstitutionUtil.validateInstitutionDomains(institutionPayload); checkDomainUniqueness(institutionPayload); - Institution updatedInstitution = institutionDAO.updateFullInstitution(institutionPayload, - userId); + Institution updatedInstitution = + institutionDAO.updateFullInstitution(institutionPayload, userId); // Enforce Institution and Library Card rules for all users after an institution is updated enforceInstitutionAndLibraryCardRules(); return updatedInstitution; @@ -87,9 +89,8 @@ public Institution findInstitutionById(Integer id) throws NotFoundException { Institution institution = institutionDAO.findInstitutionById(id); isInstitutionNull(institution); - List signingOfficials = userDAO.getSOsByInstitution(id).stream() - .map(SimplifiedUser::new) - .toList(); + List signingOfficials = + userDAO.getSOsByInstitution(id).stream().map(SimplifiedUser::new).toList(); institution.setSigningOfficials(signingOfficials); return institution; @@ -135,12 +136,11 @@ private void isInstitutionNull(Institution institution) { } private void checkNameUniqueness(Institution institution) { - List conflicts = findAllInstitutionsByName(institution.getName()) - .stream() - // Filter out the institution being updated, so it doesn't conflict with itself - .filter(existingInstitution -> - !existingInstitution.getId().equals(institution.getId())) - .toList(); + List conflicts = + findAllInstitutionsByName(institution.getName()).stream() + // Filter out the institution being updated, so it doesn't conflict with itself + .filter(existingInstitution -> !existingInstitution.getId().equals(institution.getId())) + .toList(); if (!conflicts.isEmpty()) { throw new ConsentConflictException( @@ -157,23 +157,27 @@ private void checkDomainUniqueness(Institution institution) { throw new IllegalArgumentException("Institution domains must be unique"); } - List conflictingDomains = institution.getDomains().stream() - .map(domain -> { - Integer existingInstitutionId = institutionDAO.findInstitutionIdByDomain(domain); - if (existingInstitutionId != null && !existingInstitutionId.equals(institution.getId())) { - // Return the domain if it conflicts with another institution. - // If the domain is already associated with the institution being updated, it's not a conflict. - return domain; - } - return null; // No conflict - }) - .filter(Objects::nonNull) - .toList(); + List conflictingDomains = + institution.getDomains().stream() + .map( + domain -> { + Integer existingInstitutionId = institutionDAO.findInstitutionIdByDomain(domain); + if (existingInstitutionId != null + && !existingInstitutionId.equals(institution.getId())) { + // Return the domain if it conflicts with another institution. + // If the domain is already associated with the institution being updated, it's + // not a conflict. + return domain; + } + return null; // No conflict + }) + .filter(Objects::nonNull) + .toList(); if (!conflictingDomains.isEmpty()) { throw new IllegalArgumentException( - "Domain(s) already associated with another institution: " + String.join(", ", - conflictingDomains)); + "Domain(s) already associated with another institution: " + + String.join(", ", conflictingDomains)); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/LibraryCardService.java b/src/main/java/org/broadinstitute/consent/http/service/LibraryCardService.java index bffcb108a6..1b8b806e6f 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/LibraryCardService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/LibraryCardService.java @@ -12,7 +12,6 @@ import org.broadinstitute.consent.http.db.LibraryCardDAO; import org.broadinstitute.consent.http.db.UserDAO; import org.broadinstitute.consent.http.exceptions.ConsentConflictException; -import org.broadinstitute.consent.http.mail.message.NewLibraryCardIssuedMessage; import org.broadinstitute.consent.http.models.Institution; import org.broadinstitute.consent.http.models.LibraryCard; import org.broadinstitute.consent.http.models.User; @@ -27,9 +26,12 @@ public class LibraryCardService implements ConsentLogger { private final EmailService emailService; @Inject - public LibraryCardService(LibraryCardDAO libraryCardDAO, InstitutionDAO institutionDAO, + public LibraryCardService( + LibraryCardDAO libraryCardDAO, + InstitutionDAO institutionDAO, InstitutionService institutionService, - UserDAO userDAO, EmailService emailService) { + UserDAO userDAO, + EmailService emailService) { this.libraryCardDAO = libraryCardDAO; this.institutionDAO = institutionDAO; this.institutionService = institutionService; @@ -43,19 +45,21 @@ public LibraryCard createLibraryCard(LibraryCard libraryCard, User user) { processUserOnNewLC(libraryCard); checkForValidInstitution(user.getInstitutionId(), libraryCard.getUserEmail()); Date createDate = new Date(); - Integer id = libraryCardDAO.insertLibraryCard( - libraryCard.getUserId(), - libraryCard.getUserName(), - libraryCard.getUserEmail(), - libraryCard.getCreateUserId(), - createDate); + Integer id = + libraryCardDAO.insertLibraryCard( + libraryCard.getUserId(), + libraryCard.getUserName(), + libraryCard.getUserEmail(), + libraryCard.getCreateUserId(), + createDate); User toUser = userDAO.findUserByEmail(libraryCard.getUserEmail()); if (toUser != null) { try { emailService.sendNewLibraryCardIssuedMessage(toUser); } catch (IOException | TemplateException e) { - logWarn("Failed to send library card issuance notification for user " + user.getUserId(), e); - } + logWarn( + "Failed to send library card issuance notification for user " + user.getUserId(), e); + } } return libraryCardDAO.findLibraryCardById(id); } @@ -140,7 +144,8 @@ private void checkForValidInstitution(Integer institutionId, String userEmail) { var userInstitution = institutionService.findInstitutionForEmail(userEmail); if (userInstitution == null || !userInstitution.getId().equals(institutionId)) { throw new BadRequestException( - "User email %s does not match institution %s".formatted(userEmail, institution.getName())); + "User email %s does not match institution %s" + .formatted(userEmail, institution.getName())); } } @@ -156,7 +161,7 @@ private void throwIfNull(LibraryCard libraryCard) { } } - //helper method for create method, checks to see if card already exists + // helper method for create method, checks to see if card already exists private void checkIfCardExists(LibraryCard payload) { LibraryCard result = null; @@ -169,8 +174,11 @@ private void checkIfCardExists(LibraryCard payload) { } if (result != null) { - Boolean sameUserId = payload.getUserId() != null && result.getUserId().equals(payload.getUserId()); - Boolean sameUserEmail = payload.getUserEmail() != null && result.getUserEmail().equalsIgnoreCase(payload.getUserEmail()); + Boolean sameUserId = + payload.getUserId() != null && result.getUserId().equals(payload.getUserId()); + Boolean sameUserEmail = + payload.getUserEmail() != null + && result.getUserEmail().equalsIgnoreCase(payload.getUserEmail()); if (sameUserId || sameUserEmail) { throw new ConsentConflictException("Library card already exists for this user."); } diff --git a/src/main/java/org/broadinstitute/consent/http/service/MatchService.java b/src/main/java/org/broadinstitute/consent/http/service/MatchService.java index 0b7dace35c..c984763402 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/MatchService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/MatchService.java @@ -37,8 +37,12 @@ public class MatchService implements ConsentLogger { private final WebTarget matchServiceTargetV4; @Inject - public MatchService(Client client, ServicesConfiguration config, MatchDAO matchDAO, - DataAccessRequestDAO dataAccessRequestDAO, DatasetDAO datasetDAO, + public MatchService( + Client client, + ServicesConfiguration config, + MatchDAO matchDAO, + DataAccessRequestDAO dataAccessRequestDAO, + DatasetDAO datasetDAO, UseRestrictionConverter useRestrictionConverter) { this.matchDAO = matchDAO; this.dataAccessRequestDAO = dataAccessRequestDAO; @@ -52,22 +56,25 @@ public MatchService(Client client, ServicesConfiguration config, MatchDAO matchD } public void insertMatches(List match) { - match.forEach(m -> { - Integer id = matchDAO.insertMatch( - m.getConsent(), - m.getPurpose(), - m.getMatch(), - m.getFailed(), - new Date(), - m.getAlgorithmVersion(), - m.getAbstain() - ); - if (!m.getRationales().isEmpty()) { - m.getRationales().forEach(f -> { - matchDAO.insertRationale(id, f); + match.forEach( + m -> { + Integer id = + matchDAO.insertMatch( + m.getConsent(), + m.getPurpose(), + m.getMatch(), + m.getFailed(), + new Date(), + m.getAlgorithmVersion(), + m.getAbstain()); + if (!m.getRationales().isEmpty()) { + m.getRationales() + .forEach( + f -> { + matchDAO.insertRationale(id, f); + }); + } }); - } - }); } public Match findMatchById(Integer id) { @@ -98,19 +105,23 @@ public void removeMatchesForPurpose(String purposeId) { protected List createMatchesForDataAccessRequest(DataAccessRequest dar) { List matches = new ArrayList<>(); - dar.getDatasetIds().forEach(id -> { - Dataset dataset = datasetDAO.findDatasetById(id); - if (Objects.nonNull(dataset)) { - try { - matches.add(singleEntitiesMatchV3(dataset, dar)); - } catch (Exception e) { - String message = "Error finding single match for purpose: " + dar.getReferenceId(); - logWarn(message); - matches.add( - matchFailure(dataset.getDatasetIdentifier(), dar.getReferenceId(), List.of(message))); - } - } - }); + dar.getDatasetIds() + .forEach( + id -> { + Dataset dataset = datasetDAO.findDatasetById(id); + if (Objects.nonNull(dataset)) { + try { + matches.add(singleEntitiesMatchV3(dataset, dar)); + } catch (Exception e) { + String message = + "Error finding single match for purpose: " + dar.getReferenceId(); + logWarn(message); + matches.add( + matchFailure( + dataset.getDatasetIdentifier(), dar.getReferenceId(), List.of(message))); + } + } + }); return matches; } @@ -131,10 +142,9 @@ public Match singleEntitiesMatchV3(Dataset dataset, DataAccessRequest dar) { String darReferenceId = dar.getReferenceId(); if (res.getStatus() == Response.Status.OK.getStatusCode()) { String stringEntity = res.readEntity(String.class); - DataUseResponseMatchingObject entity = new Gson().fromJson(stringEntity, - DataUseResponseMatchingObject.class); - match = matchSuccess(datasetId, darReferenceId, entity.getResult(), - entity.getRationale()); + DataUseResponseMatchingObject entity = + new Gson().fromJson(stringEntity, DataUseResponseMatchingObject.class); + match = matchSuccess(datasetId, darReferenceId, entity.getResult(), entity.getRationale()); } else { match = matchFailure(datasetId, darReferenceId, List.of()); } @@ -146,7 +156,6 @@ private DataUseRequestMatchingObject createRequestObject(Dataset dataset, DataAc return new DataUseRequestMatchingObject(dataset.getDataUse(), dataUse); } - public List findMatchesByPurposeId(String purposeId) { return matchDAO.findMatchesByPurposeId(purposeId); } diff --git a/src/main/java/org/broadinstitute/consent/http/service/MetricsService.java b/src/main/java/org/broadinstitute/consent/http/service/MetricsService.java index 23243ff561..f3eb6785bd 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/MetricsService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/MetricsService.java @@ -28,8 +28,11 @@ public class MetricsService { private final ElectionDAO electionDAO; @Inject - public MetricsService(DatasetDAO dataSetDAO, DataAccessRequestDAO darDAO, - DarCollectionDAO darCollectionDAO, ElectionDAO electionDAO) { + public MetricsService( + DatasetDAO dataSetDAO, + DataAccessRequestDAO darDAO, + DarCollectionDAO darCollectionDAO, + ElectionDAO electionDAO) { this.dataSetDAO = dataSetDAO; this.darDAO = darDAO; this.darCollectionDAO = darCollectionDAO; @@ -39,14 +42,10 @@ public MetricsService(DatasetDAO dataSetDAO, DataAccessRequestDAO darDAO, public static class DarMetricsSummary { final Timestamp updateDate; - @JsonProperty - final String projectTitle; - @JsonProperty - final String darCode; - @JsonProperty - final String nonTechRus; - @JsonProperty - final String referenceId; + @JsonProperty final String projectTitle; + @JsonProperty final String darCode; + @JsonProperty final String nonTechRus; + @JsonProperty final String referenceId; public DarMetricsSummary(DataAccessRequest dar, String darCode) { if (dar != null && dar.data != null) { @@ -69,33 +68,42 @@ public DatasetMetrics generateDatasetMetrics(Integer datasetId) { DatasetMetrics metrics = new DatasetMetrics(); - //get datasetDTO with properties and data use restrictions + // get datasetDTO with properties and data use restrictions Dataset dataset = dataSetDAO.findDatasetById(datasetId); if (dataset == null) { throw new NotFoundException("Dataset with specified ID does not exist."); } - //find dars with the given datasetId in their list of datasetIds, datasetId is a String so it can be converted to jsonb in query - //convert all dars into smaller objects that only contain the information needed + // find dars with the given datasetId in their list of datasetIds, datasetId is a String so it + // can be converted to jsonb in query + // convert all dars into smaller objects that only contain the information needed List dars = darDAO.findApprovedDARsByDatasetId(datasetId); List darCollectionIds = dars.stream().map(DataAccessRequest::getCollectionId).toList(); - List darCollections = darCollectionIds.isEmpty() ? List.of() : - darCollectionDAO.findDARCollectionByCollectionIds(darCollectionIds); - Map collectionMap = darCollections.stream() - .collect(Collectors.toMap(DarCollection::getDarCollectionId, Function.identity())); + List darCollections = + darCollectionIds.isEmpty() + ? List.of() + : darCollectionDAO.findDARCollectionByCollectionIds(darCollectionIds); + Map collectionMap = + darCollections.stream() + .collect(Collectors.toMap(DarCollection::getDarCollectionId, Function.identity())); - List darInfo = dars.stream().map(dar -> { - DarCollection collection = collectionMap.get(dar.getCollectionId()); - String darCode = Objects.nonNull(collection) ? collection.getDarCode() : null; - return new DarMetricsSummary(dar, darCode); - }).collect(Collectors.toList()); + List darInfo = + dars.stream() + .map( + dar -> { + DarCollection collection = collectionMap.get(dar.getCollectionId()); + String darCode = Objects.nonNull(collection) ? collection.getDarCode() : null; + return new DarMetricsSummary(dar, darCode); + }) + .collect(Collectors.toList()); - //if there are associated dars, find associated access elections so we know how many and which dars are approved/denied - List referenceIds = dars.stream().map(dar -> (dar.referenceId)) - .collect(Collectors.toList()); + // if there are associated dars, find associated access elections so we know how many and which + // dars are approved/denied + List referenceIds = + dars.stream().map(dar -> (dar.referenceId)).collect(Collectors.toList()); if (!referenceIds.isEmpty()) { - List elections = electionDAO.findLastElectionsByReferenceIdsAndType(referenceIds, - "DataAccess"); + List elections = + electionDAO.findLastElectionsByReferenceIdsAndType(referenceIds, "DataAccess"); metrics.setElections(elections); } else { metrics.setElections(Collections.emptyList()); @@ -104,5 +112,4 @@ public DatasetMetrics generateDatasetMetrics(Integer datasetId) { metrics.setDars(darInfo); return metrics; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/NihService.java b/src/main/java/org/broadinstitute/consent/http/service/NihService.java index 1a2de8022b..54ae9af7a4 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/NihService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/NihService.java @@ -29,15 +29,18 @@ public class NihService implements ConsentLogger { private final ServicesConfiguration configuration; @Inject - public NihService(UserDAO userDAO, NihServiceDAO serviceDAO, - HttpClientUtil clientUtil, ServicesConfiguration configuration) { + public NihService( + UserDAO userDAO, + NihServiceDAO serviceDAO, + HttpClientUtil clientUtil, + ServicesConfiguration configuration) { this.userDAO = userDAO; this.serviceDAO = serviceDAO; this.clientUtil = clientUtil; this.configuration = configuration; } - public User syncAccount(DuosUser duosUser) throws Exception { + public User syncAccount(DuosUser duosUser) throws Exception { User user = duosUser.getUser(); GenericUrl ecmRasProviderUrl = new GenericUrl(configuration.getEcmRasProviderUrl()); HttpRequest request = clientUtil.buildGetRequest(ecmRasProviderUrl, duosUser); @@ -53,7 +56,9 @@ public User syncAccount(DuosUser duosUser) throws Exception { serviceDAO.deleteNihAccountById(user.getUserId()); } catch (NotAuthorizedException _) { // ECM will return a 401 if the user has not accepted ToS yet. - logWarn("ECM Response: not authorized user: %s. User needs to accept the ToS.".formatted(duosUser.getEmail())); + logWarn( + "ECM Response: not authorized user: %s. User needs to accept the ToS." + .formatted(duosUser.getEmail())); } return userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues()); } @@ -80,9 +85,9 @@ public void deleteNihAccountById(DuosUser duosUser) { "Failed to delete NIH account for user: " + duosUser.getEmail() + " - " + e.getMessage()); throw new ServerErrorException( "Failed to delete NIH account for user: " + duosUser.getEmail(), - HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e); + HttpStatusCodes.STATUS_CODE_SERVER_ERROR, + e); } - } private NIHUserAccount parseNihUserAccount(String body) { @@ -92,11 +97,13 @@ private NIHUserAccount parseNihUserAccount(String body) { // Historically, we store this value as epoch milliseconds Instant instant = Instant.parse(linkInfo.expirationTimestamp()); return new NIHUserAccount( - linkInfo.externalUserId(), String.valueOf(instant.toEpochMilli()), linkInfo.authenticated()); + linkInfo.externalUserId(), + String.valueOf(instant.toEpochMilli()), + linkInfo.authenticated()); } catch (Exception _) { logWarn("Failed to parse ECM response: " + body); - throw new ServerErrorException("Invalid response from ECM RAS Provider", - HttpStatusCodes.STATUS_CODE_SERVER_ERROR); + throw new ServerErrorException( + "Invalid response from ECM RAS Provider", HttpStatusCodes.STATUS_CODE_SERVER_ERROR); } } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/OidcService.java b/src/main/java/org/broadinstitute/consent/http/service/OidcService.java index 60e1892055..c72cbd7252 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/OidcService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/OidcService.java @@ -28,16 +28,21 @@ public OidcService(OidcAuthorityDAO oidcAuthorityDAO, OidcConfiguration configur } public URI getAuthorizationURI(MultivaluedMap parameters) { - var uriBuilder = UriBuilder.fromUri(oidcAuthorityDAO.getOidcAuthorityConfiguration().authorization_endpoint()); + var uriBuilder = + UriBuilder.fromUri( + oidcAuthorityDAO.getOidcAuthorityConfiguration().authorization_endpoint()); parameters.forEach((key, value) -> uriBuilder.queryParam(key, value.toArray())); getExtraAuthParams().forEach(param -> uriBuilder.queryParam(param.getName(), param.getValue())); if (configuration.isAddClientIdToScope()) { - uriBuilder.replaceQueryParam(SCOPE_PARAM, addClientIdToScopes(parameters.getFirst(SCOPE_PARAM))); + uriBuilder.replaceQueryParam( + SCOPE_PARAM, addClientIdToScopes(parameters.getFirst(SCOPE_PARAM))); } return uriBuilder.build(); } - public String tokenExchange(MultivaluedMap formParameters, MultivaluedMap queryParameters) { + public String tokenExchange( + MultivaluedMap formParameters, + MultivaluedMap queryParameters) { var updatedFormParams = new MultivaluedHashMap<>(formParameters); maybeAddClientSecret(updatedFormParams); return oidcAuthorityDAO.oauthTokenPost(updatedFormParams, queryParameters); @@ -62,7 +67,8 @@ private String addClientIdToScopes(String existingScopes) { } private void maybeAddClientSecret(MultivaluedMap formParameters) { - if (!StringUtils.isBlank(configuration.getClientSecret()) && !formParameters.containsKey(CLIENT_SECRET_PARAM)) { + if (!StringUtils.isBlank(configuration.getClientSecret()) + && !formParameters.containsKey(CLIENT_SECRET_PARAM)) { formParameters.add(CLIENT_SECRET_PARAM, configuration.getClientSecret()); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/OntologyService.java b/src/main/java/org/broadinstitute/consent/http/service/OntologyService.java index 6c93a31283..95c6b84c82 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/OntologyService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/OntologyService.java @@ -21,12 +21,10 @@ public OntologyService(Client client, ServicesConfiguration config) { this.servicesConfiguration = config; } - public DataUseSummary translateDataUseSummary(DataUse dataUse) { - WebTarget target = client.target( - servicesConfiguration.getOntologyURL() + "translate/summary"); - try (Response response = target.request(MediaType.APPLICATION_JSON) - .post(Entity.json(dataUse.toString()))) { + WebTarget target = client.target(servicesConfiguration.getOntologyURL() + "translate/summary"); + try (Response response = + target.request(MediaType.APPLICATION_JSON).post(Entity.json(dataUse.toString()))) { if (response.getStatus() >= 200 || response.getStatus() <= 299) { return response.readEntity(DataUseSummary.class); } @@ -38,10 +36,10 @@ public DataUseSummary translateDataUseSummary(DataUse dataUse) { } public String translateDataUse(DataUse dataUse, DataUseTranslationType type) { - WebTarget target = client.target( - servicesConfiguration.getOntologyURL() + "translate?for=" + type.getValue()); - try (Response response = target.request(MediaType.TEXT_PLAIN) - .post(Entity.json(dataUse.toString()))) { + WebTarget target = + client.target(servicesConfiguration.getOntologyURL() + "translate?for=" + type.getValue()); + try (Response response = + target.request(MediaType.TEXT_PLAIN).post(Entity.json(dataUse.toString()))) { if (response.getStatus() == 200) { return response.readEntity(String.class); } diff --git a/src/main/java/org/broadinstitute/consent/http/service/SupportRequestService.java b/src/main/java/org/broadinstitute/consent/http/service/SupportRequestService.java index fde65f1e28..1ccfa30c71 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/SupportRequestService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/SupportRequestService.java @@ -50,9 +50,9 @@ public JsonObject postAttachmentToSupport(byte[] content) throws Exception { if (!response.isSuccessStatusCode()) { String errorMessage = "Error sending attachment to support: " + response.getStatusMessage(); var errorException = - response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY ? - new UnprocessableEntityException(errorMessage) : - new ServerErrorException(response.getStatusMessage(), response.getStatusCode()); + response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY + ? new UnprocessableEntityException(errorMessage) + : new ServerErrorException(response.getStatusMessage(), response.getStatusCode()); logException(errorMessage, errorException); throw errorException; } @@ -61,8 +61,9 @@ public JsonObject postAttachmentToSupport(byte[] content) throws Exception { if (obj != null && obj.get("upload") != null) { return obj.get("upload").getAsJsonObject(); } else { - var errorException = new ServerErrorException(response.getStatusMessage(), - HttpStatusCodes.STATUS_CODE_SERVER_ERROR); + var errorException = + new ServerErrorException( + response.getStatusMessage(), HttpStatusCodes.STATUS_CODE_SERVER_ERROR); String errorMessage = "Error reading attachment response content: " + responseContent; logException(errorMessage, errorException); throw errorException; @@ -81,17 +82,18 @@ public JsonObject postAttachmentToSupport(byte[] content) throws Exception { public Request postTicketToSupport(DuosTicket ticket) throws Exception { if (configuration.isActivateSupportNotifications()) { GenericUrl genericUrl = new GenericUrl(configuration.postSupportRequestUrl()); - ByteArrayContent content = new ByteArrayContent("application/json", - ticket.toString().getBytes(StandardCharsets.UTF_8)); + ByteArrayContent content = + new ByteArrayContent( + "application/json", ticket.toString().getBytes(StandardCharsets.UTF_8)); HttpRequest request = clientUtil.buildUnAuthedPostRequest(genericUrl, content); HttpResponse response = clientUtil.handleHttpRequest(request); if (!response.isSuccessStatusCode()) { String errorMessage = "Error posting ticket to support: " + response.getStatusMessage(); var errorException = - response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY ? - new UnprocessableEntityException(errorMessage) : - new ServerErrorException(response.getStatusMessage(), response.getStatusCode()); + response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY + ? new UnprocessableEntityException(errorMessage) + : new ServerErrorException(response.getStatusMessage(), response.getStatusCode()); logException(errorMessage, errorException); throw errorException; } @@ -100,5 +102,4 @@ public Request postTicketToSupport(DuosTicket ticket) throws Exception { } throw new BadRequestException("Not configured to send support requests"); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/TDRService.java b/src/main/java/org/broadinstitute/consent/http/service/TDRService.java index 0b5b8f2d9c..ad796cb958 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/TDRService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/TDRService.java @@ -32,8 +32,12 @@ public class TDRService implements ConsentLogger { private final UserDAO userDAO; @Inject - public TDRService(DataAccessRequestService dataAccessRequestService, DatasetDAO datasetDAO, - LibraryCardDAO libraryCardDAO, SamDAO samDAO, UserDAO userDAO) { + public TDRService( + DataAccessRequestService dataAccessRequestService, + DatasetDAO datasetDAO, + LibraryCardDAO libraryCardDAO, + SamDAO samDAO, + UserDAO userDAO) { this.dataAccessRequestService = dataAccessRequestService; this.datasetDAO = datasetDAO; this.libraryCardDAO = libraryCardDAO; @@ -42,64 +46,64 @@ public TDRService(DataAccessRequestService dataAccessRequestService, DatasetDAO } public ApprovedUsers getApprovedUsersForDataset(AuthUser authUser, Dataset dataset) { - Collection dars = dataAccessRequestService.getApprovedDARsForDataset( - dataset); - List labCollaborators = dars.stream() - .map(DataAccessRequest::getData) - .filter(Objects::nonNull) - .map(DataAccessRequestData::getLabAndInternalCollaborators) - .flatMap(List::stream) - .filter(Objects::nonNull) - .map(Collaborator::email) - .filter(email -> !email.isBlank()) - // Sam has an endpoint for validating a single email at a time - .map(email -> { - try { - samDAO.getV1UserByEmail(new DuosUser(authUser, null), email); - return email; - } catch (NotAuthorizedException e) { - logWarn("User " + authUser.getEmail() + " is not authorized to look for users in Sam"); - return null; - } catch (Exception e) { - logWarn("Collaborator: " + email + " does not exist in Sam"); - return null; - } - }) - .filter(Objects::nonNull) - .toList(); + Collection dars = + dataAccessRequestService.getApprovedDARsForDataset(dataset); + List labCollaborators = + dars.stream() + .map(DataAccessRequest::getData) + .filter(Objects::nonNull) + .map(DataAccessRequestData::getLabAndInternalCollaborators) + .flatMap(List::stream) + .filter(Objects::nonNull) + .map(Collaborator::email) + .filter(email -> !email.isBlank()) + // Sam has an endpoint for validating a single email at a time + .map( + email -> { + try { + samDAO.getV1UserByEmail(new DuosUser(authUser, null), email); + return email; + } catch (NotAuthorizedException e) { + logWarn( + "User " + + authUser.getEmail() + + " is not authorized to look for users in Sam"); + return null; + } catch (Exception e) { + logWarn("Collaborator: " + email + " does not exist in Sam"); + return null; + } + }) + .filter(Objects::nonNull) + .toList(); List userIds = dars.stream().map(DataAccessRequest::getUserId).toList(); Collection users = userIds.isEmpty() ? List.of() : userDAO.findUsers(userIds); - List userEmails = users.stream() - .map(User::getEmail) - .filter(email -> !email.isBlank()) - .toList(); + List userEmails = + users.stream().map(User::getEmail).filter(email -> !email.isBlank()).toList(); // Filter to users where that have a library card - List allEmails = Stream.of(labCollaborators, userEmails) - .flatMap(List::stream) - .distinct() - .toList(); + List allEmails = + Stream.of(labCollaborators, userEmails).flatMap(List::stream).distinct().toList(); - List approvedUsers = libraryCardDAO.findByUserEmails(allEmails) - .stream() - .map(LibraryCard::getUserEmail) - .map(ApprovedUser::new) - .sorted(Comparator.comparing(ApprovedUser::email)) - .toList(); + List approvedUsers = + libraryCardDAO.findByUserEmails(allEmails).stream() + .map(LibraryCard::getUserEmail) + .map(ApprovedUser::new) + .sorted(Comparator.comparing(ApprovedUser::email)) + .toList(); - logInfo(String.format( - "Approved users requested. Requesting user: %s, Dataset: %s, Approved users: %s", - authUser.getEmail(), - dataset.getDatasetIdentifier(), - approvedUsers.stream().map(ApprovedUser::email).toList() - )); + logInfo( + String.format( + "Approved users requested. Requesting user: %s, Dataset: %s, Approved users: %s", + authUser.getEmail(), + dataset.getDatasetIdentifier(), + approvedUsers.stream().map(ApprovedUser::email).toList())); return new ApprovedUsers(approvedUsers); } public List getDatasetsByIdentifier(List aliases) { - return datasetDAO.findDatasetsByAlias(aliases) - .stream() + return datasetDAO.findDatasetsByAlias(aliases).stream() // technically, it is possible to have two dataset identifiers which // have the same alias but are not the same: e.g., DUOS-5 and DUOS-00005 .filter(d -> aliases.contains(d.getAlias())) diff --git a/src/main/java/org/broadinstitute/consent/http/service/UseRestrictionConverter.java b/src/main/java/org/broadinstitute/consent/http/service/UseRestrictionConverter.java index 91215540b3..612d23250a 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/UseRestrictionConverter.java +++ b/src/main/java/org/broadinstitute/consent/http/service/UseRestrictionConverter.java @@ -38,16 +38,20 @@ public DataUse parseDataUsePurpose(DataAccessRequest dar) { // // Research related entries // - if (Objects.nonNull(dar.getData().getAiLlmUse()) && Boolean.TRUE.equals(dar.getData().getAiLlmUse())) { + if (Objects.nonNull(dar.getData().getAiLlmUse()) + && Boolean.TRUE.equals(dar.getData().getAiLlmUse())) { dataUse.setAiLlmUse(dar.getData().getAiLlmUse()); } - if (Objects.nonNull(dar.getData().getMethods()) && Boolean.TRUE.equals(dar.getData().getMethods())) { + if (Objects.nonNull(dar.getData().getMethods()) + && Boolean.TRUE.equals(dar.getData().getMethods())) { dataUse.setMethodsResearch(dar.getData().getMethods()); } - if (Objects.nonNull(dar.getData().getPopulation()) && Boolean.TRUE.equals(dar.getData().getPopulation())) { + if (Objects.nonNull(dar.getData().getPopulation()) + && Boolean.TRUE.equals(dar.getData().getPopulation())) { dataUse.setPopulation(dar.getData().getPopulation()); } - if (Objects.nonNull(dar.getData().getControls()) && Boolean.TRUE.equals(dar.getData().getControls())) { + if (Objects.nonNull(dar.getData().getControls()) + && Boolean.TRUE.equals(dar.getData().getControls())) { dataUse.setControls(dar.getData().getControls()); } @@ -55,11 +59,8 @@ public DataUse parseDataUsePurpose(DataAccessRequest dar) { // Diseases related entries // - List ontologies = dar.getData() - .getOntologies() - .stream() - .map(OntologyEntry::getId) - .toList(); + List ontologies = + dar.getData().getOntologies().stream().map(OntologyEntry::getId).toList(); if (CollectionUtils.isNotEmpty(ontologies)) { dataUse.setDiseaseRestrictions(ontologies); } @@ -80,61 +81,61 @@ public DataUse parseDataUsePurpose(DataAccessRequest dar) { } } // pediatric - if (Objects.nonNull(dar.getData().getPediatric()) && (Boolean.TRUE.equals(dar.getData().getPediatric()))) { - dataUse.setPediatric(true); - + if (Objects.nonNull(dar.getData().getPediatric()) + && (Boolean.TRUE.equals(dar.getData().getPediatric()))) { + dataUse.setPediatric(true); } - if (Objects.nonNull(dar.getData().getHmb()) && (Boolean.TRUE.equals(dar.getData().getHmb()))) { - dataUse.setHmbResearch(true); - + if (Objects.nonNull(dar.getData().getHmb()) + && (Boolean.TRUE.equals(dar.getData().getHmb()))) { + dataUse.setHmbResearch(true); } // Other Conditions if (Objects.nonNull(dar.getData().getOther()) - && Boolean.TRUE.equals(dar.getData().getOther()) - && Objects.nonNull(dar.getData().getOtherText())) { + && Boolean.TRUE.equals(dar.getData().getOther()) + && Objects.nonNull(dar.getData().getOtherText())) { dataUse.setOther(dar.getData().getOtherText()); } - if ((Objects.nonNull(dar.getData().getIllegalBehavior())) && Boolean.TRUE.equals(dar.getData() - .getIllegalBehavior())) { + if ((Objects.nonNull(dar.getData().getIllegalBehavior())) + && Boolean.TRUE.equals(dar.getData().getIllegalBehavior())) { dataUse.setIllegalBehavior(dar.getData().getIllegalBehavior()); } - if ((Objects.nonNull(dar.getData().getSexualDiseases())) && Boolean.TRUE.equals(dar.getData() - .getSexualDiseases())) { + if ((Objects.nonNull(dar.getData().getSexualDiseases())) + && Boolean.TRUE.equals(dar.getData().getSexualDiseases())) { dataUse.setSexualDiseases(dar.getData().getSexualDiseases()); } - if ((Objects.nonNull(dar.getData().getStigmatizedDiseases())) && Boolean.TRUE.equals(dar.getData() - .getStigmatizedDiseases())) { + if ((Objects.nonNull(dar.getData().getStigmatizedDiseases())) + && Boolean.TRUE.equals(dar.getData().getStigmatizedDiseases())) { dataUse.setStigmatizeDiseases(dar.getData().getStigmatizedDiseases()); } - if ((Objects.nonNull(dar.getData().getVulnerablePopulation())) && Boolean.TRUE.equals(dar.getData() - .getVulnerablePopulation())) { + if ((Objects.nonNull(dar.getData().getVulnerablePopulation())) + && Boolean.TRUE.equals(dar.getData().getVulnerablePopulation())) { dataUse.setVulnerablePopulations(dar.getData().getVulnerablePopulation()); } - if ((Objects.nonNull(dar.getData().getPsychiatricTraits())) && Boolean.TRUE.equals(dar.getData() - .getPsychiatricTraits())) { + if ((Objects.nonNull(dar.getData().getPsychiatricTraits())) + && Boolean.TRUE.equals(dar.getData().getPsychiatricTraits())) { dataUse.setPsychologicalTraits(dar.getData().getPsychiatricTraits()); } - if ((Objects.nonNull(dar.getData().getNotHealth())) && Boolean.TRUE.equals(dar.getData().getNotHealth())) { + if ((Objects.nonNull(dar.getData().getNotHealth())) + && Boolean.TRUE.equals(dar.getData().getNotHealth())) { dataUse.setNotHealth(dar.getData().getNotHealth()); } - } return dataUse; } public String translateDataUse(DataUse dataUse, DataUseTranslationType type) { - WebTarget target = client.target( - servicesConfiguration.getOntologyURL() + "translate?for=" + type.getValue()); - Response response = target.request(MediaType.APPLICATION_JSON) - .post(Entity.json(dataUse.toString())); + WebTarget target = + client.target(servicesConfiguration.getOntologyURL() + "translate?for=" + type.getValue()); + Response response = + target.request(MediaType.APPLICATION_JSON).post(Entity.json(dataUse.toString())); if (response.getStatus() == 200) { try { return response.readEntity(String.class); @@ -142,8 +143,9 @@ public String translateDataUse(DataUse dataUse, DataUseTranslationType type) { logException("Error parsing response from Ontology service", e); } } - logException("Error response from Ontology service: " + response.readEntity(String.class), new InternalServerErrorException()); + logException( + "Error response from Ontology service: " + response.readEntity(String.class), + new InternalServerErrorException()); return null; } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/UserService.java b/src/main/java/org/broadinstitute/consent/http/service/UserService.java index e2e1f8e5d9..e08db97ae1 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/UserService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/UserService.java @@ -108,7 +108,7 @@ public UserService( * Update a select group of user fields for a user id. * * @param userUpdateFields A UserUpdateFields object for all update information - * @param userId The User's ID + * @param userId The User's ID * @return The updated User */ public User updateUserFieldsById(UserUpdateFields userUpdateFields, Integer userId) { @@ -133,18 +133,25 @@ public User updateUserFieldsById(UserUpdateFields userUpdateFields, Integer user } // Handle Roles - //TODO: Confirm if we need to prevent removing the chairperson role through this. We have other business logic in the application that checks to see if there's at least one other chairperson on a DAC. + // TODO: Confirm if we need to prevent removing the chairperson role through this. We have + // other business logic in the application that checks to see if there's at least one other + // chairperson on a DAC. if (Objects.nonNull(userUpdateFields.getUserRoleIds())) { - List currentRoleIds = userRoleDAO.findRolesByUserId(userId).stream() - .map(UserRole::getRoleId).toList(); + List currentRoleIds = + userRoleDAO.findRolesByUserId(userId).stream().map(UserRole::getRoleId).toList(); List roleIdsToAdd = userUpdateFields.getRoleIdsToAdd(currentRoleIds); List roleIdsToRemove = userUpdateFields.getRoleIdsToRemove(currentRoleIds); // Add the new role ids to the user if (!roleIdsToAdd.isEmpty()) { - List newRoles = roleIdsToAdd.stream() - .map(id -> new UserRole(id, - Objects.requireNonNull(UserRoles.getUserRoleFromId(id)).getRoleName())) - .toList(); + List newRoles = + roleIdsToAdd.stream() + .map( + id -> + new UserRole( + id, + Objects.requireNonNull(UserRoles.getUserRoleFromId(id)) + .getRoleName())) + .toList(); userRoleDAO.insertUserRoles(newRoles, userId); } // Remove the old role ids from the user @@ -152,7 +159,6 @@ public User updateUserFieldsById(UserUpdateFields userUpdateFields, Integer user userRoleDAO.removeUserRoles(userId, roleIdsToRemove); } } - } return findUserById(userId); } @@ -171,8 +177,7 @@ public void insertRoleAndInstitutionForUser(UserRole role, User user) { userRoleDAO.insertSingleUserRole(role.getRoleId(), userId); } } catch (Exception e) { - logException( - "Error when updating user: %s, role: %s".formatted(userId, role), e); + logException("Error when updating user: %s, role: %s".formatted(userId, role), e); throw e; } } @@ -191,8 +196,9 @@ public User createUser(User user) { if (institution != null) { user.setInstitutionId(institution.getId()); } - Integer userId = userDAO.insertUser(user.getEmail(), user.getDisplayName(), - user.getInstitutionId(), new Date()); + Integer userId = + userDAO.insertUser( + user.getEmail(), user.getDisplayName(), user.getInstitutionId(), new Date()); insertUserRoles(user.getRoles(), userId); assignExistingLibraryCardToUser(user); return userDAO.findUserById(userId); @@ -218,13 +224,14 @@ public User findUserByEmail(String email) throws NotFoundException { * Find users as a specific role, e.g., Admins can see all users, other roles can only see a * subset of users. * - * @param user The user making the request + * @param user The user making the request * @param roleName The role the user is making the request as * @return List of Users for specified role name */ public List getUsersAsRole(User user, String roleName) { switch (roleName) { - // SigningOfficial console is technically pulling LCs, it's just bringing associated users along for the ride + // SigningOfficial console is technically pulling LCs, it's just bringing associated users + // along for the ride // However LCs can be created for users not yet registered in the system // As such a more specialized query is needed to produce the proper listing case Resource.SIGNINGOFFICIAL: @@ -232,8 +239,10 @@ public List getUsersAsRole(User user, String roleName) { if (Objects.nonNull(user.getInstitutionId())) { return userDAO.getUsersFromInstitutionWithCards(institutionId); } else { - throw new NotFoundException("Signing Official (user: " + user.getDisplayName() - + ") is not associated with an Institution."); + throw new NotFoundException( + "Signing Official (user: " + + user.getDisplayName() + + ") is not associated with an Institution."); } case Resource.ADMIN: return userDAO.findUsersWithLCsAndInstitution(); @@ -261,11 +270,8 @@ public void deleteUserByEmail(String email, Integer auditUserId) { throw new NotFoundException("The user for the specified E-Mail address does not exist"); } Integer userId = user.getUserId(); - List roleIds = userRoleDAO. - findRolesByUserId(userId). - stream(). - map(UserRole::getRoleId). - toList(); + List roleIds = + userRoleDAO.findRolesByUserId(userId).stream().map(UserRole::getRoleId).toList(); if (!roleIds.isEmpty()) { userRoleDAO.removeUserRoles(userId, roleIds); } @@ -278,15 +284,19 @@ public void deleteUserByEmail(String email, Integer auditUserId) { draftServiceDAO.deleteDraftsByUser(user); } catch (Exception e) { logException( - String.format("Unable to delete all drafts and files for userId %d. Error was: %s", - userId, e.getMessage()), e); + String.format( + "Unable to delete all drafts and files for userId %d. Error was: %s", + userId, e.getMessage()), + e); } try { institutionDAO.deleteAllInstitutionsByUser(userId); } catch (Exception e) { logException( - String.format("Unable to delete all institutions for userId %d. Error was: %s", - userId, e.getMessage()), e); + String.format( + "Unable to delete all institutions for userId %d. Error was: %s", + userId, e.getMessage()), + e); } userPropertyDAO.deleteAllPropertiesByUser(userId); libraryCardDAO.deleteAllLibraryCardsByUser(userId); @@ -298,8 +308,8 @@ public void deleteUserByEmail(String email, Integer auditUserId) { } public List findAllUserProperties(Integer userId) { - return userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(userId, - UserFields.getValues()); + return userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + userId, UserFields.getValues()); } public void updateEmailPreference(boolean preference, Integer userId) { @@ -326,12 +336,11 @@ public List findUsersByInstitutionId(Integer institutionId) { return userDAO.findUsersByInstitution(institutionId); } - public void deleteUserRole(User authUser, Integer userId, Integer roleId) { userRoleDAO.removeSingleUserRole(userId, roleId); logInfo( - "User %s deleted roleId: %s from User ID: %s".formatted(authUser.getDisplayName(), roleId, - userId)); + "User %s deleted roleId: %s from User ID: %s" + .formatted(authUser.getDisplayName(), roleId, userId)); } public List findUsersWithNoInstitution() { @@ -342,7 +351,7 @@ public List findUsersWithNoInstitution() { * Convenience method to return a response-friendly json object of the user. * * @param duosUser The DuosUser. Used to determine if we should return auth user properties - * @param userId The User. This is the user we want to return properties for + * @param userId The User. This is the user we want to return properties for * @return JsonObject. */ public JsonObject findUserWithPropertiesByIdAsJsonObject(DuosUser duosUser, Integer userId) { @@ -356,10 +365,10 @@ public JsonObject findUserWithPropertiesByIdAsJsonObject(DuosUser duosUser, Inte JsonObject libraryCardJson = gson.toJsonTree(user.getLibraryCard()).getAsJsonObject(); userJson.add(LIBRARY_CARD_FIELD, libraryCardJson); } - if (duosUser.getEmail().equalsIgnoreCase(user.getEmail()) && Objects.nonNull( - duosUser.getUserStatusInfo())) { - JsonObject userStatusInfoJson = gson.toJsonTree(duosUser.getUserStatusInfo()) - .getAsJsonObject(); + if (duosUser.getEmail().equalsIgnoreCase(user.getEmail()) + && Objects.nonNull(duosUser.getUserStatusInfo())) { + JsonObject userStatusInfoJson = + gson.toJsonTree(duosUser.getUserStatusInfo()).getAsJsonObject(); userJson.add(USER_STATUS_INFO_FIELD, userStatusInfoJson); } return userJson; @@ -372,23 +381,28 @@ private void validateRequiredFields(User user) { if (StringUtils.isEmpty(user.getEmail())) { throw new BadRequestException("Email address cannot be empty"); } - List validRoleNameList = Stream.of(UserRoles.RESEARCHER, UserRoles.ALUMNI, - UserRoles.ADMIN).map(UserRoles::getRoleName).toList(); - user.getRoles().forEach(role -> { - if (!validRoleNameList.contains(role.getName())) { - String validRoleNames = String.join(", ", validRoleNameList); - throw new BadRequestException( - "Invalid role: " + role.getName() + ". Valid roles are: " + validRoleNames); - } - }); + List validRoleNameList = + Stream.of(UserRoles.RESEARCHER, UserRoles.ALUMNI, UserRoles.ADMIN) + .map(UserRoles::getRoleName) + .toList(); + user.getRoles() + .forEach( + role -> { + if (!validRoleNameList.contains(role.getName())) { + String validRoleNames = String.join(", ", validRoleNameList); + throw new BadRequestException( + "Invalid role: " + role.getName() + ". Valid roles are: " + validRoleNames); + } + }); } public void insertUserRoles(List roles, Integer userId) { - roles.forEach(r -> { - if (r.getRoleId() == null) { - r.setRoleId(userRoleDAO.findRoleIdByName(r.getName())); - } - }); + roles.forEach( + r -> { + if (r.getRoleId() == null) { + r.setRoleId(userRoleDAO.findRoleIdByName(r.getName())); + } + }); userRoleDAO.insertUserRoles(roles, userId); } @@ -405,7 +419,7 @@ private void assignExistingLibraryCardToUser(User user) { } } - public List findUsersInJsonArray(String json, String arrayKey) { + public List findUsersInJsonArray(String json, String arrayKey) { List jsonElementList; try { JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); @@ -425,13 +439,18 @@ public void validateActiveERACredentials(User user) { throw new BadRequestException("User does not have an Era Commons ID"); } List userProperties = findAllUserProperties(user.getUserId()); - List eraStatusProps = userProperties.stream().filter( - userProperty -> userProperty.getPropertyKey().equalsIgnoreCase(ERA_STATUS.getValue())) - .toList(); - List eraExpirationProps = userProperties.stream().filter( - userProperty -> userProperty.getPropertyKey() - .equalsIgnoreCase(ERA_EXPIRATION_DATE.getValue())) - .toList(); + List eraStatusProps = + userProperties.stream() + .filter( + userProperty -> + userProperty.getPropertyKey().equalsIgnoreCase(ERA_STATUS.getValue())) + .toList(); + List eraExpirationProps = + userProperties.stream() + .filter( + userProperty -> + userProperty.getPropertyKey().equalsIgnoreCase(ERA_EXPIRATION_DATE.getValue())) + .toList(); if (eraStatusProps.size() == 1 && eraExpirationProps.size() == 1) { if (!eraStatusProps.get(0).getPropertyValue().equalsIgnoreCase("true")) { throw new BadRequestException("User does not have an Era Commons ID that is authorized."); @@ -449,9 +468,10 @@ public void validateActiveERACredentials(User user) { /** * Compliance method that implements a set of rules in order to ensure Library Card and * Institution matching rules are adhered to when authorizing users of the system. + * * @param email of the user being evaluated * @return user with the Institution and Library Card rules applied or null if the requestor isn't - * a DUOS user. + * a DUOS user. */ public User enforceInstitutionAndLibraryCardRules(String email) { return institutionAndLibraryCardEnforcement.enforceInstitutionAndLibraryCardRules(email); @@ -471,8 +491,7 @@ public SimplifiedUser(User user) { this.institutionId = user.getInstitutionId(); } - public SimplifiedUser() { - } + public SimplifiedUser() {} public void setUserId(Integer userId) { this.userId = userId; diff --git a/src/main/java/org/broadinstitute/consent/http/service/VoteService.java b/src/main/java/org/broadinstitute/consent/http/service/VoteService.java index ebf99a3df9..9020c6357e 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/VoteService.java +++ b/src/main/java/org/broadinstitute/consent/http/service/VoteService.java @@ -10,7 +10,6 @@ import freemarker.template.TemplateException; import java.io.IOException; import java.lang.reflect.Type; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAO.java index 8bd359580e..427e6d3fb2 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAO.java @@ -23,38 +23,34 @@ public DaaServiceDAO(Jdbi jdbi, DaaDAO daaDAO, FileStorageObjectDAO fsoDAO) { this.fsoDAO = fsoDAO; } - public Integer createDaaWithFso(Integer userId, Integer dacId, FileStorageObject fso) throws Exception { + public Integer createDaaWithFso(Integer userId, Integer dacId, FileStorageObject fso) + throws Exception { List createdDaaIds = new ArrayList<>(); - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - Instant now = Instant.now(); - try { - Integer daaId = daaDAO.createDaa( - userId, - now, - userId, - now, - dacId); - createdDaaIds.add(daaId); - daaDAO.createDacDaaRelation(dacId, daaId); - if (fso != null) { - fsoDAO.insertNewFile( - fso.getFileName(), - fso.getCategory().getValue(), - fso.getBlobId().toGsUtilUri(), - fso.getMediaType(), - daaId.toString(), - userId, - now); - } - } catch (Exception e) { - handle.rollback(); - logException(e); - throw e; - } - handle.commit(); - }); + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + Instant now = Instant.now(); + try { + Integer daaId = daaDAO.createDaa(userId, now, userId, now, dacId); + createdDaaIds.add(daaId); + daaDAO.createDacDaaRelation(dacId, daaId); + if (fso != null) { + fsoDAO.insertNewFile( + fso.getFileName(), + fso.getCategory().getValue(), + fso.getBlobId().toGsUtilUri(), + fso.getMediaType(), + daaId.toString(), + userId, + now); + } + } catch (Exception e) { + handle.rollback(); + logException(e); + throw e; + } + handle.commit(); + }); return createdDaaIds.isEmpty() ? null : createdDaaIds.get(0); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DacServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DacServiceDAO.java index 7af3384ed3..cbd468e7df 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DacServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DacServiceDAO.java @@ -2,11 +2,7 @@ import com.google.inject.Inject; import java.sql.SQLException; -import java.util.List; -import java.util.Objects; -import org.broadinstitute.consent.http.db.DaaDAO; import org.broadinstitute.consent.http.models.Dac; -import org.broadinstitute.consent.http.models.DataAccessAgreement; import org.broadinstitute.consent.http.models.User; import org.broadinstitute.consent.http.util.ConsentLogger; import org.jdbi.v3.core.Jdbi; @@ -21,64 +17,71 @@ public DacServiceDAO(Jdbi jdbi) { this.jdbi = jdbi; } - public void deleteDacAndDaas(User user, Dac dac) - throws IllegalArgumentException, SQLException { + public void deleteDacAndDaas(User user, Dac dac) throws IllegalArgumentException, SQLException { // fail fast if (dac == null) { throw new IllegalArgumentException("Invalid DAC"); } - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); - jdbi.useTransaction(handler -> { - final String deleteFromLcDaa = "DELETE FROM lc_daa WHERE daa_id in (SELECT daa_id FROM data_access_agreement WHERE initial_dac_id = :dacId)"; - final String deleteFromDacDaa = "DELETE FROM dac_daa WHERE dac_id = :dacId"; - final String deleteFromDaa = "DELETE FROM data_access_agreement WHERE initial_dac_id = :dacId"; - final String deleteMembers = "DELETE FROM user_role WHERE dac_id = :dacId"; - final String updateDatasets = "UPDATE dataset SET dac_id = null, dac_approval = null WHERE dac_id = :dacId"; - final String deleteDacAutomationRules = "DELETE FROM dac_rule_settings WHERE dac_id = :dacId "; - final String deleteDacAutomationRulesDeletionAudit = """ + jdbi.useTransaction( + handler -> { + final String deleteFromLcDaa = + "DELETE FROM lc_daa WHERE daa_id in (SELECT daa_id FROM data_access_agreement WHERE initial_dac_id = :dacId)"; + final String deleteFromDacDaa = "DELETE FROM dac_daa WHERE dac_id = :dacId"; + final String deleteFromDaa = + "DELETE FROM data_access_agreement WHERE initial_dac_id = :dacId"; + final String deleteMembers = "DELETE FROM user_role WHERE dac_id = :dacId"; + final String updateDatasets = + "UPDATE dataset SET dac_id = null, dac_approval = null WHERE dac_id = :dacId"; + final String deleteDacAutomationRules = + "DELETE FROM dac_rule_settings WHERE dac_id = :dacId "; + final String deleteDacAutomationRulesDeletionAudit = + """ INSERT INTO dac_rule_audit(action, dac_id, rule_id, user_id, action_date) SELECT 'REMOVE', s.dac_id, s.rule_id, :userId, current_timestamp FROM dac_rule_settings s WHERE dac_id = :dacId """; - final String deleteDac = "DELETE FROM dac where dac_id = :dacId"; + final String deleteDac = "DELETE FROM dac where dac_id = :dacId"; - Update lcDaaDeletion = handler.createUpdate(deleteFromLcDaa); - lcDaaDeletion.bind("dacId", dac.getDacId()); - lcDaaDeletion.execute(); + Update lcDaaDeletion = handler.createUpdate(deleteFromLcDaa); + lcDaaDeletion.bind("dacId", dac.getDacId()); + lcDaaDeletion.execute(); - Update dacDaaDeletion = handler.createUpdate(deleteFromDacDaa); - dacDaaDeletion.bind("dacId", dac.getDacId()); - dacDaaDeletion.execute(); + Update dacDaaDeletion = handler.createUpdate(deleteFromDacDaa); + dacDaaDeletion.bind("dacId", dac.getDacId()); + dacDaaDeletion.execute(); - Update daaDeletion = handler.createUpdate(deleteFromDaa); - daaDeletion.bind("dacId", dac.getDacId()); - daaDeletion.execute(); + Update daaDeletion = handler.createUpdate(deleteFromDaa); + daaDeletion.bind("dacId", dac.getDacId()); + daaDeletion.execute(); - Update memberDeletion = handler.createUpdate(deleteMembers); - memberDeletion.bind("dacId", dac.getDacId()); - memberDeletion.execute(); + Update memberDeletion = handler.createUpdate(deleteMembers); + memberDeletion.bind("dacId", dac.getDacId()); + memberDeletion.execute(); - Update datasetUpdate = handler.createUpdate(updateDatasets); - datasetUpdate.bind("dacId", dac.getDacId()); - datasetUpdate.execute(); + Update datasetUpdate = handler.createUpdate(updateDatasets); + datasetUpdate.bind("dacId", dac.getDacId()); + datasetUpdate.execute(); - Update dacAutomationRulesDeletionAudit = handler.createUpdate(deleteDacAutomationRulesDeletionAudit); - dacAutomationRulesDeletionAudit.bind("dacId", dac.getDacId()); - dacAutomationRulesDeletionAudit.bind("userId", user.getUserId()); - dacAutomationRulesDeletionAudit.execute(); + Update dacAutomationRulesDeletionAudit = + handler.createUpdate(deleteDacAutomationRulesDeletionAudit); + dacAutomationRulesDeletionAudit.bind("dacId", dac.getDacId()); + dacAutomationRulesDeletionAudit.bind("userId", user.getUserId()); + dacAutomationRulesDeletionAudit.execute(); - Update dacAutomationRulesDeletion = handler.createUpdate(deleteDacAutomationRules); - dacAutomationRulesDeletion.bind("dacId", dac.getDacId()); - dacAutomationRulesDeletion.execute(); + Update dacAutomationRulesDeletion = handler.createUpdate(deleteDacAutomationRules); + dacAutomationRulesDeletion.bind("dacId", dac.getDacId()); + dacAutomationRulesDeletion.execute(); - Update dacDeletion = handler.createUpdate(deleteDac); - dacDeletion.bind("dacId", dac.getDacId()); - dacDeletion.execute(); - handler.commit(); - }); - }); + Update dacDeletion = handler.createUpdate(deleteDac); + dacDeletion.bind("dacId", dac.getDacId()); + dacDeletion.execute(); + handler.commit(); + }); + }); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAO.java index 87017aad33..43198ae91e 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAO.java @@ -28,8 +28,8 @@ public class DarCollectionServiceDAO { private final UserDAO userDAO; @Inject - public DarCollectionServiceDAO(DatasetDAO datasetDAO, ElectionDAO electionDAO, Jdbi jdbi, - UserDAO userDAO) { + public DarCollectionServiceDAO( + DatasetDAO datasetDAO, ElectionDAO electionDAO, Jdbi jdbi, UserDAO userDAO) { this.datasetDAO = datasetDAO; this.electionDAO = electionDAO; this.jdbi = jdbi; @@ -37,14 +37,14 @@ public DarCollectionServiceDAO(DatasetDAO datasetDAO, ElectionDAO electionDAO, J } /** - * Find all Dar + Dataset combinations that are available to the user. - Admins have - * all available to them - Chairs can only create elections for datasets in their DACs - *

- * DataAccessRequests with no elections, or with previously canceled elections, are valid for + * Find all Dar + Dataset combinations that are available to the user. - Admins have all available + * to them - Chairs can only create elections for datasets in their DACs + * + *

DataAccessRequests with no elections, or with previously canceled elections, are valid for * initiating a new set of elections. Any DAR elections in open state should be ignored. * - * @param user The User initiating new elections for a data access request - * @param dar The DataAccessRequest + * @param user The User initiating new elections for a data access request + * @param dar The DataAccessRequest * @return List of reference ids for which a DAR election was created */ public List createElectionsForDarByUser(User user, DataAccessRequest dar) @@ -52,9 +52,8 @@ public List createElectionsForDarByUser(User user, DataAccessRequest dar boolean isAdmin = user.hasUserRole(UserRoles.ADMIN); List createdElectionReferenceIds = new ArrayList<>(); // If the user is not an admin, we need to know what datasets they have access to. - List dacUserDatasetIds = isAdmin ? - List.of() : - datasetDAO.findDatasetIdsByDACUserId(user.getUserId()); + List dacUserDatasetIds = + isAdmin ? List.of() : datasetDAO.findDatasetIdsByDACUserId(user.getUserId()); jdbi.useHandle( handle -> { // By default, new connections are set to auto-commit which breaks our rollback strategy. @@ -76,71 +75,120 @@ public List createElectionsForDarByUser(User user, DataAccessRequest dar // Only take actions on the most recent DAR/Progress report in the collection // This means a chair cannot reopen an election in any other DAR in the collection besides // the most recently submitted progress report. - dar.getDatasetIds().forEach(datasetId -> { - // If there is an existing open election for this DAR+Dataset, we can ignore it - Election lastDataAccessElection = electionDAO.findLastElectionByReferenceIdDatasetIdAndType( - dar.getReferenceId(), datasetId, ElectionType.DATA_ACCESS.getValue()); - boolean ignore = - Objects.nonNull(lastDataAccessElection) && lastDataAccessElection.getStatus() - .equalsIgnoreCase(ElectionStatus.OPEN.getValue()); + dar.getDatasetIds() + .forEach( + datasetId -> { + // If there is an existing open election for this DAR+Dataset, we can ignore it + Election lastDataAccessElection = + electionDAO.findLastElectionByReferenceIdDatasetIdAndType( + dar.getReferenceId(), datasetId, ElectionType.DATA_ACCESS.getValue()); + boolean ignore = + Objects.nonNull(lastDataAccessElection) + && lastDataAccessElection + .getStatus() + .equalsIgnoreCase(ElectionStatus.OPEN.getValue()); - // If the user is not an admin, then the dataset must be in the list of the user's DAC Datasets - // Otherwise, we need to skip election creation for this DAR as well. - if (!isAdmin && !dacUserDatasetIds.contains(datasetId)) { - ignore = true; - } - if (!ignore) { - // Archive all old elections for this DAR + Dataset - List oldElectionIds = electionDAO - .findElectionsByReferenceIdAndDatasetId(dar.getReferenceId(), datasetId) - .stream().map(Election::getElectionId) - .toList(); - if (!oldElectionIds.isEmpty()) { - electionDAO.archiveElectionByIds(oldElectionIds, new Date()); - } - List voteUsers = findVoteUsersForDataset(datasetId); - inserts.add(createElectionInsert(handle, ElectionType.DATA_ACCESS.getValue(), - dar.getReferenceId(), datasetId)); - inserts.addAll(createVoteInsertsForUsers(handle, voteUsers, - ElectionType.DATA_ACCESS.getValue(), dar.getReferenceId(), datasetId, - dar.requiresManualReview())); - inserts.add( - createElectionInsert(handle, ElectionType.RP.getValue(), dar.getReferenceId(), - datasetId)); - inserts.addAll( - createVoteInsertsForUsers(handle, voteUsers, ElectionType.RP.getValue(), - dar.getReferenceId(), datasetId, - dar.requiresManualReview())); - createdElectionReferenceIds.add(dar.getReferenceId()); - } - }); + // If the user is not an admin, then the dataset must be in the list of the + // user's DAC Datasets + // Otherwise, we need to skip election creation for this DAR as well. + if (!isAdmin && !dacUserDatasetIds.contains(datasetId)) { + ignore = true; + } + if (!ignore) { + // Archive all old elections for this DAR + Dataset + List oldElectionIds = + electionDAO + .findElectionsByReferenceIdAndDatasetId( + dar.getReferenceId(), datasetId) + .stream() + .map(Election::getElectionId) + .toList(); + if (!oldElectionIds.isEmpty()) { + electionDAO.archiveElectionByIds(oldElectionIds, new Date()); + } + List voteUsers = findVoteUsersForDataset(datasetId); + inserts.add( + createElectionInsert( + handle, + ElectionType.DATA_ACCESS.getValue(), + dar.getReferenceId(), + datasetId)); + inserts.addAll( + createVoteInsertsForUsers( + handle, + voteUsers, + ElectionType.DATA_ACCESS.getValue(), + dar.getReferenceId(), + datasetId, + dar.requiresManualReview())); + inserts.add( + createElectionInsert( + handle, ElectionType.RP.getValue(), dar.getReferenceId(), datasetId)); + inserts.addAll( + createVoteInsertsForUsers( + handle, + voteUsers, + ElectionType.RP.getValue(), + dar.getReferenceId(), + datasetId, + dar.requiresManualReview())); + createdElectionReferenceIds.add(dar.getReferenceId()); + } + }); inserts.forEach(Update::execute); handle.commit(); }); return createdElectionReferenceIds; } - private List createVoteInsertsForUsers(Handle handle, List voteUsers, - String electionType, String referenceId, Integer datasetId, Boolean isManualReview) { + private List createVoteInsertsForUsers( + Handle handle, + List voteUsers, + String electionType, + String referenceId, + Integer datasetId, + Boolean isManualReview) { List userVotes = new ArrayList<>(); voteUsers.forEach( u -> { // All users get a minimum of one DAC vote type for both RP and DataAccess election types - userVotes.add(createVoteInsert(handle, VoteType.DAC.getValue(), electionType, referenceId, - datasetId, u.getUserId())); + userVotes.add( + createVoteInsert( + handle, + VoteType.DAC.getValue(), + electionType, + referenceId, + datasetId, + u.getUserId())); // Chairpersons get a Chairperson vote for both RP and DataAccess election types if (u.hasUserRole(UserRoles.CHAIRPERSON)) { userVotes.add( - createVoteInsert(handle, VoteType.CHAIRPERSON.getValue(), electionType, referenceId, - datasetId, u.getUserId())); + createVoteInsert( + handle, + VoteType.CHAIRPERSON.getValue(), + electionType, + referenceId, + datasetId, + u.getUserId())); // Chairpersons get Final and Agreement votes for DataAccess elections if (ElectionType.DATA_ACCESS.getValue().equals(electionType)) { - userVotes.add(createVoteInsert(handle, VoteType.FINAL.getValue(), - ElectionType.DATA_ACCESS.getValue(), referenceId, datasetId, u.getUserId())); + userVotes.add( + createVoteInsert( + handle, + VoteType.FINAL.getValue(), + ElectionType.DATA_ACCESS.getValue(), + referenceId, + datasetId, + u.getUserId())); if (!isManualReview) { - userVotes.add(createVoteInsert(handle, VoteType.AGREEMENT.getValue(), - ElectionType.DATA_ACCESS.getValue(), referenceId, datasetId, - u.getUserId())); + userVotes.add( + createVoteInsert( + handle, + VoteType.AGREEMENT.getValue(), + ElectionType.DATA_ACCESS.getValue(), + referenceId, + datasetId, + u.getUserId())); } } } @@ -148,9 +196,15 @@ private List createVoteInsertsForUsers(Handle handle, List voteUse return userVotes; } - private Update createVoteInsert(Handle handle, String voteType, String electionType, - String referenceId, Integer datasetId, Integer userId) { - final String sql = """ + private Update createVoteInsert( + Handle handle, + String voteType, + String electionType, + String referenceId, + Integer datasetId, + Integer userId) { + final String sql = + """ INSERT INTO vote (create_date, user_id, election_id, type, reminder_sent) (SELECT current_timestamp, :userId, election_id, :voteType, false FROM election @@ -171,17 +225,17 @@ INSERT INTO vote (create_date, user_id, election_id, type, reminder_sent) private List findVoteUsersForDataset(Integer datasetId) { List dacUsers = - new ArrayList<>(userDAO.findUsersForDatasetsByRole( - List.of(datasetId), - List.of(UserRoles.CHAIRPERSON.getRoleId(), UserRoles.MEMBER.getRoleId()))); - return dacUsers.isEmpty() ? - new ArrayList<>(userDAO.findNonDacUsersEnabledToVote()) : - dacUsers; + new ArrayList<>( + userDAO.findUsersForDatasetsByRole( + List.of(datasetId), + List.of(UserRoles.CHAIRPERSON.getRoleId(), UserRoles.MEMBER.getRoleId()))); + return dacUsers.isEmpty() ? new ArrayList<>(userDAO.findNonDacUsersEnabledToVote()) : dacUsers; } private Update createElectionInsert( Handle handle, String electionType, String referenceId, Integer datasetId) { - final String sql = """ + final String sql = + """ INSERT INTO election (election_type, status, create_date, reference_id, dataset_id, version) VALUES (:electionType, :status, current_timestamp, :referenceId, :datasetId, (SELECT coalesce (MAX(version), 0) + 1 diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAO.java index 7a16b96ef9..6696a33114 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAO.java @@ -20,8 +20,8 @@ public class DataAccessRequestServiceDAO { private final Jdbi jdbi; @Inject - public DataAccessRequestServiceDAO(DataAccessRequestDAO dataAccessRequestDAO, Jdbi jdbi, - DarCollectionDAO darCollectionDAO) { + public DataAccessRequestServiceDAO( + DataAccessRequestDAO dataAccessRequestDAO, Jdbi jdbi, DarCollectionDAO darCollectionDAO) { this.dataAccessRequestDAO = dataAccessRequestDAO; this.jdbi = jdbi; this.darCollectionDAO = darCollectionDAO; @@ -31,52 +31,57 @@ public DataAccessRequest updateByReferenceId(User user, DataAccessRequest dar) throws SQLException { Instant now = Instant.now(); String referenceId = dar.getReferenceId(); - final String updateDataByReferenceId = """ + final String updateDataByReferenceId = + """ UPDATE data_access_request SET data = regexp_replace(:data, '\\\\u0000', '', 'g')::jsonb, user_id = :userId, submission_date = :submissionDate, update_date = :updateDate WHERE reference_id = :referenceId """; - final String deleteDarDatasetRelationByReferenceId = """ + final String deleteDarDatasetRelationByReferenceId = + """ DELETE FROM dar_dataset WHERE reference_id = :referenceId """; - final String insertDarDataset = """ + final String insertDarDataset = + """ INSERT INTO dar_dataset (reference_id, dataset_id) VALUES (:referenceId, :datasetId) ON CONFLICT DO NOTHING """; - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - handle.useTransaction(h -> { + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + handle.useTransaction( + h -> { + Update darUpdate = h.createUpdate(updateDataByReferenceId); + darUpdate.bind("referenceId", referenceId); + darUpdate.bind("userId", user.getUserId()); + darUpdate.bind("updateDate", now); + darUpdate.bind("data", dar.getData().toString()); + darUpdate.bind("submissionDate", dar.getSubmissionDate()); + darUpdate.execute(); - Update darUpdate = h.createUpdate(updateDataByReferenceId); - darUpdate.bind("referenceId", referenceId); - darUpdate.bind("userId", user.getUserId()); - darUpdate.bind("updateDate", now); - darUpdate.bind("data", dar.getData().toString()); - darUpdate.bind("submissionDate", dar.getSubmissionDate()); - darUpdate.execute(); + if (Objects.nonNull(dar.getCollectionId())) { + darCollectionDAO.updateDarCollection( + dar.getCollectionId(), user.getUserId(), new Date(now.getEpochSecond())); + } - if (Objects.nonNull(dar.getCollectionId())) { - darCollectionDAO.updateDarCollection(dar.getCollectionId(), user.getUserId(), - new Date(now.getEpochSecond())); - } + Update darDatasetDelete = h.createUpdate(deleteDarDatasetRelationByReferenceId); + darDatasetDelete.bind("referenceId", dar.getReferenceId()); + darDatasetDelete.execute(); - Update darDatasetDelete = h.createUpdate(deleteDarDatasetRelationByReferenceId); - darDatasetDelete.bind("referenceId", dar.getReferenceId()); - darDatasetDelete.execute(); + List datasetIds = dar.getDatasetIds(); + datasetIds.forEach( + id -> { + Update darDatasetInsert = h.createUpdate(insertDarDataset); + darDatasetInsert.bind("referenceId", referenceId); + darDatasetInsert.bind("datasetId", id); + darDatasetInsert.execute(); + }); - List datasetIds = dar.getDatasetIds(); - datasetIds.forEach(id -> { - Update darDatasetInsert = h.createUpdate(insertDarDataset); - darDatasetInsert.bind("referenceId", referenceId); - darDatasetInsert.bind("datasetId", id); - darDatasetInsert.execute(); + h.commit(); + }); }); - - h.commit(); - }); - }); return dataAccessRequestDAO.findByReferenceId(referenceId); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetDeletionException.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetDeletionException.java index 0cb5e8e6bf..820c979cff 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetDeletionException.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetDeletionException.java @@ -5,5 +5,4 @@ public class DatasetDeletionException extends RuntimeException { public DatasetDeletionException(Throwable cause) { super(cause); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAO.java index c6cb59d24b..4423a25e80 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAO.java @@ -53,53 +53,60 @@ public DatasetServiceDAO( } public void deleteDataset(Dataset dataset, Integer userId) throws Exception { - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - // Some legacy dataset names can be null - String dsAuditName = - Objects.nonNull(dataset.getName()) ? dataset.getName() : dataset.getDatasetIdentifier(); - try { - addAuditRecord(dataset.getDatasetId(), dsAuditName, userId, AuditActions.DELETE); - datasetAuthorizationReaderDAO.deleteByDatasetId(dataset.getDatasetId()); - datasetDAO.deleteDatasetPropertiesByDatasetId(dataset.getDatasetId()); - datasetDAO.deleteDatasetById(dataset.getDatasetId()); - } catch (Exception e) { - handle.rollback(); - logException(e); - throw e; - } - handle.commit(); - }); + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + // Some legacy dataset names can be null + String dsAuditName = + Objects.nonNull(dataset.getName()) + ? dataset.getName() + : dataset.getDatasetIdentifier(); + try { + addAuditRecord(dataset.getDatasetId(), dsAuditName, userId, AuditActions.DELETE); + datasetAuthorizationReaderDAO.deleteByDatasetId(dataset.getDatasetId()); + datasetDAO.deleteDatasetPropertiesByDatasetId(dataset.getDatasetId()); + datasetDAO.deleteDatasetById(dataset.getDatasetId()); + } catch (Exception e) { + handle.rollback(); + logException(e); + throw e; + } + handle.commit(); + }); } public void deleteStudy(Study study, User user) throws Exception { - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - study.getDatasets().forEach(d -> { - try { - deleteDataset(d, user.getUserId()); - } catch (Exception e) { - handle.rollback(); - logException(e); - throw new DatasetDeletionException(e); - } - }); - try { - studyDAO.deleteStudyByStudyId(study.getStudyId()); - } catch (Exception e) { - handle.rollback(); - logException(e); - throw e; - } - handle.commit(); - }); + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + study + .getDatasets() + .forEach( + d -> { + try { + deleteDataset(d, user.getUserId()); + } catch (Exception e) { + handle.rollback(); + logException(e); + throw new DatasetDeletionException(e); + } + }); + try { + studyDAO.deleteStudyByStudyId(study.getStudyId()); + } catch (Exception e) { + handle.rollback(); + logException(e); + throw e; + } + handle.commit(); + }); } /** * Inserts a set of datasets, optionally under a study. * - * @param study If provided, creates a study and links all datasets to it; if null, no study is - * created. + * @param study If provided, creates a study and links all datasets to it; if null, no study is + * created. * @param datasets The datasets to create. * @return The IDs of the datasets created. * @throws SQLException if DB transaction fails. @@ -121,26 +128,27 @@ public List insertDatasetRegistration(StudyInsert study, List properties, List uploadedFiles) { // insert dataset - Integer datasetId = datasetDAO.insertDataset( - name, - new Timestamp(new Date().getTime()), - userId, - null, - dataUse.toString(), - dacId - ); + Integer datasetId = + datasetDAO.insertDataset( + name, new Timestamp(new Date().getTime()), userId, null, dataUse.toString(), dacId); addAuditRecord(datasetId, name, userId, AuditActions.CREATE); @@ -177,62 +180,60 @@ public Integer executeInsertDatasetWithFiles(Handle handle, * Updates the dataset index date and adds an audit record. * * @param datasetId The ID of the dataset to update. - * @param userId The ID of the user performing the update. + * @param userId The ID of the user performing the update. * @param indexDate The new index date, or null to un-index the dataset. * @throws SQLException if DB transaction fails. */ - public void updateDatasetIndex(Integer datasetId, Integer userId, Instant indexDate) throws SQLException { - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - Dataset dataset = datasetDAO.findDatasetById(datasetId); - AuditActions action = indexDate == null ? AuditActions.DEINDEXED : AuditActions.INDEXED; - String dsAuditName = dataset.getName() == null ? dataset.getDatasetIdentifier() : dataset.getName(); - try { - datasetDAO.updateDatasetIndexedDate(dataset.getDatasetId(), indexDate); - addAuditRecord(dataset.getDatasetId(), dsAuditName, userId, action); - } catch (Exception e) { - handle.rollback(); - logException(e); - throw e; - } - handle.commit(); - }); + public void updateDatasetIndex(Integer datasetId, Integer userId, Instant indexDate) + throws SQLException { + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + Dataset dataset = datasetDAO.findDatasetById(datasetId); + AuditActions action = indexDate == null ? AuditActions.DEINDEXED : AuditActions.INDEXED; + String dsAuditName = + dataset.getName() == null ? dataset.getDatasetIdentifier() : dataset.getName(); + try { + datasetDAO.updateDatasetIndexedDate(dataset.getDatasetId(), indexDate); + addAuditRecord(dataset.getDatasetId(), dsAuditName, userId, action); + } catch (Exception e) { + handle.rollback(); + logException(e); + throw e; + } + handle.commit(); + }); } private Integer executeInsertStudy(Handle handle, StudyInsert insert) { StudyDAO studyDAO = handle.attach(StudyDAO.class); UUID uuid = UUID.randomUUID(); - Integer studyId = studyDAO.insertStudy( - insert.name, - insert.description, - insert.piName, - insert.dataTypes, - insert.publicVisibility, - insert.userId, - Instant.now(), - uuid - ); + Integer studyId = + studyDAO.insertStudy( + insert.name, + insert.description, + insert.piName, + insert.dataTypes, + insert.publicVisibility, + insert.userId, + Instant.now(), + uuid); for (StudyProperty prop : insert.props) { studyDAO.insertStudyProperty( - studyId, - prop.getKey(), - prop.getType().toString(), - prop.getValue().toString() - ); + studyId, prop.getKey(), prop.getType().toString(), prop.getValue().toString()); } - executeInsertFiles( - handle, - insert.files, - insert.userId, - uuid.toString()); + executeInsertFiles(handle, insert.files, insert.userId, uuid.toString()); return studyId; } - public Study updateStudy(StudyUpdate studyUpdate, List datasetUpdates, - List datasetInserts) throws SQLException { + public Study updateStudy( + StudyUpdate studyUpdate, + List datasetUpdates, + List datasetInserts) + throws SQLException { jdbi.useHandle( handle -> { handle.getConnection().setAutoCommit(false); @@ -257,8 +258,7 @@ public Study updateStudy(StudyUpdate studyUpdate, List datasetUpd insert.dataUse, studyUpdate.userId, insert.props, - studyUpdate.files - ); + studyUpdate.files); } handle.commit(); }); @@ -276,40 +276,33 @@ private void executeUpdateStudy(Handle handle, StudyUpdate update) { update.dataTypes, update.publicVisibility, update.userId, - Instant.now() - ); + Instant.now()); // Handle property inserts and updates - Set existingStudyProperties = studyDAO.findStudyById(update.studyId) - .getProperties(); - update.props.forEach(p -> { - Optional existingProp = existingStudyProperties.stream().filter(ep -> - p.getKey().equals(ep.getKey()) && - p.getType().equals(ep.getType())).findFirst(); - if (existingProp.isPresent()) { - // Update existing study prop: - studyDAO.updateStudyProperty(update.studyId, p.getKey(), p.getType().toString(), - p.getValue().toString()); - } else { - // Add new study prop: - studyDAO.insertStudyProperty( - update.studyId, - p.getKey(), - p.getType().toString(), - p.getValue().toString() - ); - } - }); - - executeInsertFiles( - handle, - update.files, - update.userId, - study.getUuid().toString()); + Set existingStudyProperties = + studyDAO.findStudyById(update.studyId).getProperties(); + update.props.forEach( + p -> { + Optional existingProp = + existingStudyProperties.stream() + .filter(ep -> p.getKey().equals(ep.getKey()) && p.getType().equals(ep.getType())) + .findFirst(); + if (existingProp.isPresent()) { + // Update existing study prop: + studyDAO.updateStudyProperty( + update.studyId, p.getKey(), p.getType().toString(), p.getValue().toString()); + } else { + // Add new study prop: + studyDAO.insertStudyProperty( + update.studyId, p.getKey(), p.getType().toString(), p.getValue().toString()); + } + }); + + executeInsertFiles(handle, update.files, update.userId, study.getUuid().toString()); } - private void executeInsertFiles(Handle handle, List files, Integer userId, - String entityId) { + private void executeInsertFiles( + Handle handle, List files, Integer userId, String entityId) { FileStorageObjectDAO fileStorageObjectDAO = handle.attach(FileStorageObjectDAO.class); for (FileStorageObject file : files) { fileStorageObjectDAO.insertNewFile( @@ -319,8 +312,7 @@ private void executeInsertFiles(Handle handle, List files, In file.getMediaType(), entityId, userId, - Instant.now() - ); + Instant.now()); } } @@ -347,11 +339,11 @@ public void updateDataset(DatasetUpdate updates) throws SQLException { throw e; } handle.commit(); - } - ); + }); } - public void executeUpdateDatasetWithFiles(Handle handle, + public void executeUpdateDatasetWithFiles( + Handle handle, Integer datasetId, String datasetName, Integer userId, @@ -366,12 +358,7 @@ public void executeUpdateDatasetWithFiles(Handle handle, addAuditRecord(datasetId, updateName, userId, AuditActions.UPDATE); // update dataset datasetDAO.updateDatasetByDatasetId( - datasetId, - updateName, - new Timestamp(new Date().getTime()), - userId, - dacId - ); + datasetId, updateName, new Timestamp(new Date().getTime()), userId, dacId); // insert properties executeSynchronizeDatasetProperties(handle, datasetId, properties, executeDeletes); @@ -386,22 +373,18 @@ public void patchDataset(Integer datasetId, User user, DatasetPatch patch) throw handle.getConnection().setAutoCommit(false); try { executePatchDataset( - handle, - datasetId, - patch.name(), - user.getUserId(), - patch.properties()); + handle, datasetId, patch.name(), user.getUserId(), patch.properties()); } catch (Exception e) { handle.rollback(); logException(e); throw e; } handle.commit(); - } - ); + }); } - public void executePatchDataset(Handle handle, + public void executePatchDataset( + Handle handle, Integer datasetId, String datasetName, Integer userId, @@ -409,42 +392,30 @@ public void executePatchDataset(Handle handle, // update dataset if (datasetName == null || datasetName.isBlank()) { logWarn( - "Attempt to update dataset name with null or blank value: dataset id: %s; user id: %s".formatted( - datasetId, userId)); + "Attempt to update dataset name with null or blank value: dataset id: %s; user id: %s" + .formatted(datasetId, userId)); Dataset dataset = datasetDAO.findDatasetById(datasetId); addAuditRecord(datasetId, dataset.getDatasetName(), userId, AuditActions.UPDATE); - datasetDAO.updateDatasetUpdateUser( - datasetId, - new Timestamp(new Date().getTime()), - userId); + datasetDAO.updateDatasetUpdateUser(datasetId, new Timestamp(new Date().getTime()), userId); } else { addAuditRecord(datasetId, datasetName, userId, AuditActions.UPDATE); datasetDAO.updateDatasetNameWithUpdateUser( - datasetId, - datasetName, - new Timestamp(new Date().getTime()), - userId); + datasetId, datasetName, new Timestamp(new Date().getTime()), userId); } // insert properties executeSynchronizeDatasetProperties(handle, datasetId, properties, false); - } private void addAuditRecord(Integer datasetId, String name, Integer userId, AuditActions action) { - DatasetAudit audit = new DatasetAudit( - datasetId, - null, - name, - new Date(), - userId, - action.getValue().toUpperCase() - ); + DatasetAudit audit = + new DatasetAudit( + datasetId, null, name, new Date(), userId, action.getValue().toUpperCase()); datasetDAO.insertDatasetAudit(audit); } // Helper methods to generate Dictionary inserts - private void executeSynchronizeDatasetProperties(Handle handle, Integer datasetId, - List properties, boolean executeDeletes) { + private void executeSynchronizeDatasetProperties( + Handle handle, Integer datasetId, List properties, boolean executeDeletes) { List updates = new ArrayList<>(generateDictionaryInserts(handle, properties)); // We need to know existing properties for all property operations Set existingProps = datasetDAO.findDatasetPropertiesByDatasetId(datasetId); @@ -466,19 +437,21 @@ private void executeSynchronizeDatasetProperties(Handle handle, Integer datasetI private List generateDictionaryInserts(Handle handle, List properties) { List dictionaryTerms = datasetDAO.getDictionaryTerms(); - HashSet keyValues = new HashSet<>( - dictionaryTerms.stream().map(Dictionary::getKey).toList()); + HashSet keyValues = + new HashSet<>(dictionaryTerms.stream().map(Dictionary::getKey).toList()); List updates = new ArrayList<>(); - properties.forEach(prop -> { - if (!keyValues.contains(prop.getPropertyName())) { - updates.add(createDictionaryInsert(handle, prop.getPropertyName())); - } - }); + properties.forEach( + prop -> { + if (!keyValues.contains(prop.getPropertyName())) { + updates.add(createDictionaryInsert(handle, prop.getPropertyName())); + } + }); return updates; } private Update createDictionaryInsert(Handle handle, String key) { - final String sql = """ + final String sql = + """ INSERT INTO dictionary (key, required) VALUES (:key, FALSE) ON CONFLICT DO NOTHING @@ -488,25 +461,30 @@ INSERT INTO dictionary (key, required) return insert; } - private List generatePropertyInserts(Handle handle, Integer datasetId, - List properties, Set existingProps) { + private List generatePropertyInserts( + Handle handle, + Integer datasetId, + List properties, + Set existingProps) { Timestamp now = new Timestamp(new Date().getTime()); List updates = new ArrayList<>(); - HashSet existingPropNames = new HashSet<>( - existingProps.stream().map(DatasetProperty::getPropertyName).toList()); + HashSet existingPropNames = + new HashSet<>(existingProps.stream().map(DatasetProperty::getPropertyName).toList()); // Generate new inserts for props we don't know about yet - properties.forEach(prop -> { - if (!existingPropNames.contains(prop.getPropertyName())) { - prop.setDatasetId(datasetId); - prop.setCreateDate(now); - updates.add(createPropertyInsert(handle, prop, now)); - } - }); + properties.forEach( + prop -> { + if (!existingPropNames.contains(prop.getPropertyName())) { + prop.setDatasetId(datasetId); + prop.setCreateDate(now); + updates.add(createPropertyInsert(handle, prop, now)); + } + }); return updates; } private Update createPropertyInsert(Handle handle, DatasetProperty property, Timestamp now) { - final String sql = """ + final String sql = + """ INSERT INTO dataset_property (dataset_id, property_key, schema_property, property_value, property_type, create_date ) SELECT :datasetId, (SELECT DISTINCT key_id FROM dictionary WHERE LOWER(key) = LOWER(:propertyName) ORDER BY key_id LIMIT 1), @@ -523,34 +501,43 @@ INSERT INTO dataset_property (dataset_id, property_key, schema_property, propert return insert; } - private List generatePropertyUpdates(Handle handle, Integer datasetId, - List properties, Set existingProps) { + private List generatePropertyUpdates( + Handle handle, + Integer datasetId, + List properties, + Set existingProps) { List updates = new ArrayList<>(); // Generate value updates for props that exist - properties.forEach(prop -> { - List matchingProps = existingProps - .stream() - .filter(ep -> ep.getPropertyName().equals(prop.getPropertyName())) - .toList(); - if (matchingProps.size() > 1) { - logWarn( - String.format("Multiple properties exist for the same name [%s] for dataset id [%s]", - prop.getPropertyName(), datasetId) - ); - } - matchingProps.forEach(existingProp -> { - updates.add( - createPropertyUpdate(handle, datasetId, prop.getPropertyValueAsString(), - existingProp.getPropertyKey(), existingProp.getPropertyId())); - - }); - }); + properties.forEach( + prop -> { + List matchingProps = + existingProps.stream() + .filter(ep -> ep.getPropertyName().equals(prop.getPropertyName())) + .toList(); + if (matchingProps.size() > 1) { + logWarn( + String.format( + "Multiple properties exist for the same name [%s] for dataset id [%s]", + prop.getPropertyName(), datasetId)); + } + matchingProps.forEach( + existingProp -> { + updates.add( + createPropertyUpdate( + handle, + datasetId, + prop.getPropertyValueAsString(), + existingProp.getPropertyKey(), + existingProp.getPropertyId())); + }); + }); return updates; } - private Update createPropertyUpdate(Handle handle, Integer datasetId, String propValue, - Integer propKey, Integer propId) { - final String sql = """ + private Update createPropertyUpdate( + Handle handle, Integer datasetId, String propValue, Integer propKey, Integer propId) { + final String sql = + """ UPDATE dataset_property SET property_value = :propertyStringValue WHERE dataset_id = :datasetId @@ -567,22 +554,24 @@ private Update createPropertyUpdate(Handle handle, Integer datasetId, String pro // Helper methods to generate DatasetProperty inserts - private List generatePropertyDeletes(Handle handle, List properties, - Set existingProps) { + private List generatePropertyDeletes( + Handle handle, List properties, Set existingProps) { List updates = new ArrayList<>(); - HashSet newPropNames = new HashSet<>( - properties.stream().map(DatasetProperty::getPropertyName).toList()); + HashSet newPropNames = + new HashSet<>(properties.stream().map(DatasetProperty::getPropertyName).toList()); // Generate deletes for existing props that do not exist in the new props - existingProps.forEach(existingProp -> { - if (!newPropNames.contains(existingProp.getPropertyName())) { - updates.add(createPropertyDelete(handle, existingProp)); - } - }); + existingProps.forEach( + existingProp -> { + if (!newPropNames.contains(existingProp.getPropertyName())) { + updates.add(createPropertyDelete(handle, existingProp)); + } + }); return updates; } private Update createPropertyDelete(Handle handle, DatasetProperty property) { - final String sql = """ + final String sql = + """ DELETE FROM dataset_property WHERE dataset_id = :datasetId AND property_key = :propertyKey @@ -597,46 +586,42 @@ private Update createPropertyDelete(Handle handle, DatasetProperty property) { // Helper methods to generate DatasetProperty updates - public record StudyInsert(String name, - String description, - List dataTypes, - String piName, - Boolean publicVisibility, - Integer userId, - List props, - List files) { - - } - - public record StudyUpdate(String name, - Integer studyId, - String description, - List dataTypes, - String piName, - Boolean publicVisibility, - Integer userId, - List props, - List files) { + public record StudyInsert( + String name, + String description, + List dataTypes, + String piName, + Boolean publicVisibility, + Integer userId, + List props, + List files) {} - } + public record StudyUpdate( + String name, + Integer studyId, + String description, + List dataTypes, + String piName, + Boolean publicVisibility, + Integer userId, + List props, + List files) {} // Helper methods to generate DatasetProperty deletes - public record DatasetInsert(String name, - Integer dacId, - DataUse dataUse, - Integer userId, - List props, - List files) { - - } - - public record DatasetUpdate(Integer datasetId, - String name, - Integer userId, - Integer dacId, - List props, - List files) { + public record DatasetInsert( + String name, + Integer dacId, + DataUse dataUse, + Integer userId, + List props, + List files) {} - } + public record DatasetUpdate( + Integer datasetId, + String name, + Integer userId, + Integer dacId, + List props, + List files) {} } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAO.java index 823bf08536..01ca051b78 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAO.java @@ -27,54 +27,66 @@ public class DraftFileStorageServiceDAO implements ConsentLogger { FileStorageObjectDAO fileStorageObjectDAO; @Inject - public DraftFileStorageServiceDAO(Jdbi jdbi, GCSService gcsService, - FileStorageObjectDAO fileStorageObjectDAO) { + public DraftFileStorageServiceDAO( + Jdbi jdbi, GCSService gcsService, FileStorageObjectDAO fileStorageObjectDAO) { this.jdbi = jdbi; this.gcsService = gcsService; this.fileStorageObjectDAO = fileStorageObjectDAO; } - public List storeDraftFiles(UUID associatedId, User user, - Map files) throws SQLException { + public List storeDraftFiles( + UUID associatedId, User user, Map files) throws SQLException { List fileStorageObjects = new ArrayList<>(); - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - try { - files.forEach((String key, FormDataBodyPart file) -> { - fileStorageObjects.add(store(file, user, associatedId)); - }); - } catch (Exception e) { - fileStorageObjects.forEach(file -> { + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); try { - deleteStoredFile(file, user); - } catch (SQLException ex) { - logWarn(String.format("Error rolling back files in GCS for draft: %s, gcsuri: %s", - associatedId.toString(), file.getBlobId().toGsUtilUri())); - throw new RuntimeException(ex); + files.forEach( + (String key, FormDataBodyPart file) -> { + fileStorageObjects.add(store(file, user, associatedId)); + }); + } catch (Exception e) { + fileStorageObjects.forEach( + file -> { + try { + deleteStoredFile(file, user); + } catch (SQLException ex) { + logWarn( + String.format( + "Error rolling back files in GCS for draft: %s, gcsuri: %s", + associatedId.toString(), file.getBlobId().toGsUtilUri())); + throw new RuntimeException(ex); + } + }); + handle.getConnection().rollback(); } + handle.commit(); }); - handle.getConnection().rollback(); - } - handle.commit(); - }); return fileStorageObjects; } - public void deleteStoredFile(FileStorageObject fileStorageObject, User user) throws SQLException, NotFoundException { - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - try { - gcsService.deleteDocument(fileStorageObject.getBlobId().getName()); - fileStorageObjectDAO.deleteFileById(fileStorageObject.getFileStorageObjectId(), - user.getUserId(), new Date().toInstant()); - } catch (Exception e) { - logWarn(String.format("Error deleting stored file for user: %s, file obj id: %d, error: %s", - user.getEmail(), fileStorageObject.getFileStorageObjectId(), e)); - handle.rollback(); - throw new NotFoundException("Error deleting stored file for user: " + user.getEmail(), e); - } - handle.commit(); - }); + public void deleteStoredFile(FileStorageObject fileStorageObject, User user) + throws SQLException, NotFoundException { + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + try { + gcsService.deleteDocument(fileStorageObject.getBlobId().getName()); + fileStorageObjectDAO.deleteFileById( + fileStorageObject.getFileStorageObjectId(), + user.getUserId(), + new Date().toInstant()); + } catch (Exception e) { + logWarn( + String.format( + "Error deleting stored file for user: %s, file obj id: %d, error: %s", + user.getEmail(), fileStorageObject.getFileStorageObjectId(), e)); + handle.rollback(); + throw new NotFoundException( + "Error deleting stored file for user: " + user.getEmail(), e); + } + handle.commit(); + }); } private FileStorageObject store(FormDataBodyPart file, User user, UUID draftId) @@ -82,15 +94,26 @@ private FileStorageObject store(FormDataBodyPart file, User user, UUID draftId) BlobId blobId; try { // upload to GCS - blobId = gcsService.storeDocument(file.getValueAs(InputStream.class), - file.getMediaType().toString(), UUID.randomUUID()); - Integer fileStorageObjectId = fileStorageObjectDAO.insertNewFile(file.getName(), - FileCategory.DRAFT_UPLOADED_FILE.getValue(), blobId.toGsUtilUri(), - file.getMediaType().toString(), draftId.toString(), user.getUserId(), Instant.now()); + blobId = + gcsService.storeDocument( + file.getValueAs(InputStream.class), + file.getMediaType().toString(), + UUID.randomUUID()); + Integer fileStorageObjectId = + fileStorageObjectDAO.insertNewFile( + file.getName(), + FileCategory.DRAFT_UPLOADED_FILE.getValue(), + blobId.toGsUtilUri(), + file.getMediaType().toString(), + draftId.toString(), + user.getUserId(), + Instant.now()); return fileStorageObjectDAO.findFileById(fileStorageObjectId); } catch (Exception e) { - logWarn(String.format("Error storing file for user: %s, draft id : %s, error: %s", - user.getEmail(), draftId.toString(), e)); + logWarn( + String.format( + "Error storing file for user: %s, draft id : %s, error: %s", + user.getEmail(), draftId.toString(), e)); throw new RuntimeException(e); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAO.java index 5b1b7926aa..406867a6ec 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAO.java @@ -26,63 +26,72 @@ public class DraftServiceDAO { private final DraftFileStorageServiceDAO draftFileStorageServiceDAO; @Inject - public DraftServiceDAO(Jdbi jdbi, DraftDAO draftDAO, - DraftFileStorageServiceDAO draftFileStorageServiceDAO) { + public DraftServiceDAO( + Jdbi jdbi, DraftDAO draftDAO, DraftFileStorageServiceDAO draftFileStorageServiceDAO) { this.jdbi = jdbi; this.draftDAO = draftDAO; this.draftFileStorageServiceDAO = draftFileStorageServiceDAO; } - public void insertDraft(DraftInterface draft) - throws SQLException, BadRequestException { - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - try { - draftDAO.insert(draft.getName(), draft.getCreateDate().toInstant(), - draft.getCreateUser().getUserId(), draft.getJson(), draft.getUUID(), - draft.getType().getValue()); - } catch (Exception e) { - handle.rollback(); - throw new BadRequestException( - "Error submitting draft. Drafts require valid json to be submitted.", e); - } - handle.commit(); - }); + public void insertDraft(DraftInterface draft) throws SQLException, BadRequestException { + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + try { + draftDAO.insert( + draft.getName(), + draft.getCreateDate().toInstant(), + draft.getCreateUser().getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); + } catch (Exception e) { + handle.rollback(); + throw new BadRequestException( + "Error submitting draft. Drafts require valid json to be submitted.", e); + } + handle.commit(); + }); } public DraftInterface updateDraft(DraftInterface draft, User user) throws SQLException { draft.setUpdateUser(user); draft.setUpdateDate(new Date()); - jdbi.useHandle(handle -> { - handle.getConnection().setAutoCommit(false); - try { - draftDAO.updateDraftByDraftUUID(draft.getName(), - draft.getUpdateDate().toInstant(), draft.getUpdateUser().getUserId(), draft.getJson(), - draft.getUUID(), draft.getType().getValue()); - } catch (Exception e) { - handle.rollback(); - throw new BadRequestException( - "Error updating draft. Drafts require valid json to be updated.", e); - } - handle.commit(); - }); + jdbi.useHandle( + handle -> { + handle.getConnection().setAutoCommit(false); + try { + draftDAO.updateDraftByDraftUUID( + draft.getName(), + draft.getUpdateDate().toInstant(), + draft.getUpdateUser().getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); + } catch (Exception e) { + handle.rollback(); + throw new BadRequestException( + "Error updating draft. Drafts require valid json to be updated.", e); + } + handle.commit(); + }); return getAuthorizedDraft(draft.getUUID(), user); } - public DraftInterface getAuthorizedDraft(UUID draftUUID, User user) throws NotFoundException, NotAuthorizedException { + public DraftInterface getAuthorizedDraft(UUID draftUUID, User user) + throws NotFoundException, NotAuthorizedException { DraftInterface draft; try { draft = findDraftByDraftUUID(draftUUID); } catch (Exception e) { - throw new NotFoundException( - String.format("Draft with UUID %s not found.", draftUUID), e); + throw new NotFoundException(String.format("Draft with UUID %s not found.", draftUUID), e); } if (draft == null) { throw new NotFoundException( String.format("Draft with UUID %s not found.", draftUUID.toString())); } - if (!user.getUserId().equals(draft.getCreateUser().getUserId()) && !user.hasUserRole( - UserRoles.ADMIN)) { + if (!user.getUserId().equals(draft.getCreateUser().getUserId()) + && !user.hasUserRole(UserRoles.ADMIN)) { throw new NotAuthorizedException("User not authorized to modify resource."); } return draft; @@ -99,51 +108,51 @@ public Collection findDraftsForUser(User user) { return draftDAO.findDraftsByUserId(user.getUserId()); } - private DraftInterface findDraftByDraftUUID( - UUID draftUUID) { + private DraftInterface findDraftByDraftUUID(UUID draftUUID) { return draftDAO.findDraftById(draftUUID); } - public List addAttachments(DraftInterface draft, User user, - Map files) throws SQLException { - List storedFiles = draftFileStorageServiceDAO.storeDraftFiles( - draft.getUUID(), user, files); - draftDAO.updateDraftByDraftUUID(draft.getUUID(), - new Date().toInstant(), user.getUserId()); + public List addAttachments( + DraftInterface draft, User user, Map files) throws SQLException { + List storedFiles = + draftFileStorageServiceDAO.storeDraftFiles(draft.getUUID(), user, files); + draftDAO.updateDraftByDraftUUID(draft.getUUID(), new Date().toInstant(), user.getUserId()); return storedFiles; } public void deleteDraftAttachment(DraftInterface draft, User user, Integer fileId) throws SQLException { - Optional fileStorageObjectToDelete = draft.getStoredFiles().stream() - .filter(fileStorageObject -> fileStorageObject.getFileStorageObjectId().equals(fileId)) - .findFirst(); + Optional fileStorageObjectToDelete = + draft.getStoredFiles().stream() + .filter(fileStorageObject -> fileStorageObject.getFileStorageObjectId().equals(fileId)) + .findFirst(); if (fileStorageObjectToDelete.isPresent()) { draftFileStorageServiceDAO.deleteStoredFile(fileStorageObjectToDelete.get(), user); - draftDAO.updateDraftByDraftUUID(draft.getUUID(), - new Date().toInstant(), user.getUserId()); + draftDAO.updateDraftByDraftUUID(draft.getUUID(), new Date().toInstant(), user.getUserId()); } else { throw new NotFoundException( - String.format("Draft attachment is not found. Draft: %s, Attachment: %d", + String.format( + "Draft attachment is not found. Draft: %s, Attachment: %d", draft.getUUID(), fileId)); } } - public void deleteDraft(DraftInterface draft, User user) - throws SQLException, NotFoundException { - jdbi.useHandle(handle -> { - try { - handle.useTransaction(handler -> { - draftDAO.deleteDraftByUUIDList(List.of(draft.getUUID())); - for (FileStorageObject fileStorageObject : draft.getStoredFiles()) { - draftFileStorageServiceDAO.deleteStoredFile(fileStorageObject, user); + public void deleteDraft(DraftInterface draft, User user) throws SQLException, NotFoundException { + jdbi.useHandle( + handle -> { + try { + handle.useTransaction( + handler -> { + draftDAO.deleteDraftByUUIDList(List.of(draft.getUUID())); + for (FileStorageObject fileStorageObject : draft.getStoredFiles()) { + draftFileStorageServiceDAO.deleteStoredFile(fileStorageObject, user); + } + }); + } catch (Exception e) { + handle.rollback(); + throw e; } + handle.commit(); }); - } catch (Exception e) { - handle.rollback(); - throw e; - } - handle.commit(); - }); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/NihServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/NihServiceDAO.java index d41fe72ac1..92438f0b39 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/NihServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/NihServiceDAO.java @@ -25,34 +25,41 @@ public NihServiceDAO(Jdbi jdbi) { public void updateUserNihStatus(User user, NIHUserAccount nihAccount) throws IllegalArgumentException { // fail fast - if (Objects.isNull(nihAccount) || Objects.isNull(nihAccount.getStatus()) || Objects.isNull( - nihAccount.getEraExpiration())) { + if (Objects.isNull(nihAccount) + || Objects.isNull(nihAccount.getStatus()) + || Objects.isNull(nihAccount.getEraExpiration())) { throw new IllegalArgumentException("Invalid NIH account information"); } - jdbi.useTransaction(handler -> { - UserDAO userDAO = handler.attach(UserDAO.class); - UserPropertyDAO userPropertyDAO = handler.attach(UserPropertyDAO.class); - Collection properties = List.of( - new UserProperty(user.getUserId(), UserFields.ERA_STATUS.getValue(), - nihAccount.getStatus().toString()), - new UserProperty(user.getUserId(), UserFields.ERA_EXPIRATION_DATE.getValue(), - nihAccount.getEraExpiration()) - ); - userPropertyDAO.insertAll(properties); - userDAO.updateEraCommonsId(user.getUserId(), nihAccount.getNihUsername()); - }); + jdbi.useTransaction( + handler -> { + UserDAO userDAO = handler.attach(UserDAO.class); + UserPropertyDAO userPropertyDAO = handler.attach(UserPropertyDAO.class); + Collection properties = + List.of( + new UserProperty( + user.getUserId(), + UserFields.ERA_STATUS.getValue(), + nihAccount.getStatus().toString()), + new UserProperty( + user.getUserId(), + UserFields.ERA_EXPIRATION_DATE.getValue(), + nihAccount.getEraExpiration())); + userPropertyDAO.insertAll(properties); + userDAO.updateEraCommonsId(user.getUserId(), nihAccount.getNihUsername()); + }); } public void deleteNihAccountById(Integer userId) { - jdbi.useTransaction(handler -> { - UserDAO userDAO = handler.attach(UserDAO.class); - UserPropertyDAO userPropertyDAO = handler.attach(UserPropertyDAO.class); - Collection properties = List.of( - new UserProperty(userId, UserFields.ERA_EXPIRATION_DATE.getValue()), - new UserProperty(userId, UserFields.ERA_STATUS.getValue()) - ); - userDAO.updateEraCommonsId(userId, null); - userPropertyDAO.deletePropertiesByUserAndKey(properties); - }); + jdbi.useTransaction( + handler -> { + UserDAO userDAO = handler.attach(UserDAO.class); + UserPropertyDAO userPropertyDAO = handler.attach(UserPropertyDAO.class); + Collection properties = + List.of( + new UserProperty(userId, UserFields.ERA_EXPIRATION_DATE.getValue()), + new UserProperty(userId, UserFields.ERA_STATUS.getValue())); + userDAO.updateEraCommonsId(userId, null); + userPropertyDAO.deletePropertiesByUserAndKey(properties); + }); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/dao/UserServiceDAO.java b/src/main/java/org/broadinstitute/consent/http/service/dao/UserServiceDAO.java index ed0a85c194..d2c3c9b5fd 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/dao/UserServiceDAO.java +++ b/src/main/java/org/broadinstitute/consent/http/service/dao/UserServiceDAO.java @@ -15,7 +15,8 @@ public class UserServiceDAO { UserRoleDAO userRoleDAO; @Inject - public UserServiceDAO(Jdbi jdbi, LibraryCardDAO libraryCardDAO, UserDAO userDAO, UserRoleDAO userRoleDAO) { + public UserServiceDAO( + Jdbi jdbi, LibraryCardDAO libraryCardDAO, UserDAO userDAO, UserRoleDAO userRoleDAO) { this.jdbi = jdbi; this.libraryCardDAO = libraryCardDAO; this.userDAO = userDAO; @@ -23,20 +24,22 @@ public UserServiceDAO(Jdbi jdbi, LibraryCardDAO libraryCardDAO, UserDAO userDAO, } public void insertRoleAndInstitutionTxn(UserRole role, Integer institutionId, Integer userId) { - jdbi.useTransaction(transactionHandle -> { - UserDAO userDAOT = transactionHandle.attach(UserDAO.class); - UserRoleDAO userRoleDAOT = transactionHandle.attach(UserRoleDAO.class); - userDAOT.updateInstitutionId(userId, institutionId); - userRoleDAOT.insertSingleUserRole(role.getRoleId(), userId); - }); + jdbi.useTransaction( + transactionHandle -> { + UserDAO userDAOT = transactionHandle.attach(UserDAO.class); + UserRoleDAO userRoleDAOT = transactionHandle.attach(UserRoleDAO.class); + userDAOT.updateInstitutionId(userId, institutionId); + userRoleDAOT.insertSingleUserRole(role.getRoleId(), userId); + }); } public void updateInstitutionAndClearLibraryCardForUser(Integer userId, Integer institutionId) { - jdbi.useTransaction(transactionHandle -> { - UserDAO userDAOT = transactionHandle.attach(UserDAO.class); - LibraryCardDAO libraryCardDAOT = transactionHandle.attach(LibraryCardDAO.class); - userDAOT.updateInstitutionId(userId, institutionId); - libraryCardDAOT.deleteAllLibraryCardsByUser(userId); - }); + jdbi.useTransaction( + transactionHandle -> { + UserDAO userDAOT = transactionHandle.attach(UserDAO.class); + LibraryCardDAO libraryCardDAOT = transactionHandle.attach(LibraryCardDAO.class); + userDAOT.updateInstitutionId(userId, institutionId); + libraryCardDAOT.deleteAllLibraryCardsByUser(userId); + }); } } diff --git a/src/main/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcement.java b/src/main/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcement.java index fa4571a4e3..7caa77100a 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcement.java +++ b/src/main/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcement.java @@ -26,8 +26,8 @@ */ public class InstitutionAndLibraryCardEnforcement implements ConsentLogger { - private final ExecutorService executorService = new ThreadUtils().getExecutorService( - InstitutionAndLibraryCardEnforcement.class); + private final ExecutorService executorService = + new ThreadUtils().getExecutorService(InstitutionAndLibraryCardEnforcement.class); private final InstitutionDAO institutionDAO; private final LibraryCardDAO libraryCardDAO; private final UserDAO userDAO; @@ -47,7 +47,7 @@ public InstitutionAndLibraryCardEnforcement(Jdbi jdbi, UserServiceDAO userServic * * @param email of the user being evaluated * @return user with the Institution and Library Card rules applied or null if the requestor isn't - * a DUOS user. + * a DUOS user. * @throws NotFoundException when the user isn't found in our database */ public User enforceInstitutionAndLibraryCardRules(String email) { @@ -59,19 +59,22 @@ public User enforceInstitutionAndLibraryCardRules(String email) { } public void asyncEnforceInstitutionAndLibraryCardRulesForAllUsers() { - ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator( - executorService); - ListenableFuture enforceRulesFuture = listeningExecutorService.submit(() -> { - for (User user : userDAO.findUsersWithLCsAndInstitution()) { - try { - User updatedUser = enforceInstitutionAndLibraryCardRules(user); - logInfo("Enforced institution and LC rules for user: " + updatedUser.getEmail()); - } catch (Exception e) { - logWarn("Error enforcing institution and LC rules for user: " + user.getEmail(), e); - } - } - return null; - }); + ListeningExecutorService listeningExecutorService = + MoreExecutors.listeningDecorator(executorService); + ListenableFuture enforceRulesFuture = + listeningExecutorService.submit( + () -> { + for (User user : userDAO.findUsersWithLCsAndInstitution()) { + try { + User updatedUser = enforceInstitutionAndLibraryCardRules(user); + logInfo("Enforced institution and LC rules for user: " + updatedUser.getEmail()); + } catch (Exception e) { + logWarn( + "Error enforcing institution and LC rules for user: " + user.getEmail(), e); + } + } + return null; + }); Futures.addCallback( enforceRulesFuture, new FutureCallback<>() { @@ -79,6 +82,7 @@ public void asyncEnforceInstitutionAndLibraryCardRulesForAllUsers() { public void onSuccess(User result) { logInfo("Completed enforcing institution and LC rules for all users."); } + @Override public void onFailure(@NotNull Throwable t) { logWarn("Error completing enforcement of institution and LC rules for all users.", t); diff --git a/src/main/java/org/broadinstitute/consent/http/service/ontology/ElasticSearchSupport.java b/src/main/java/org/broadinstitute/consent/http/service/ontology/ElasticSearchSupport.java index 2250ea7f6b..ecdd26cae9 100644 --- a/src/main/java/org/broadinstitute/consent/http/service/ontology/ElasticSearchSupport.java +++ b/src/main/java/org/broadinstitute/consent/http/service/ontology/ElasticSearchSupport.java @@ -10,12 +10,11 @@ public class ElasticSearchSupport { public static RestClient createRestClient(ElasticSearchConfiguration configuration) { - HttpHost[] hosts = configuration. - getServers(). - stream(). - map(server -> new HttpHost(server, configuration.getPort(), "http")). - toList(). - toArray(new HttpHost[configuration.getServers().size()]); + HttpHost[] hosts = + configuration.getServers().stream() + .map(server -> new HttpHost(server, configuration.getPort(), "http")) + .toList() + .toArray(new HttpHost[configuration.getServers().size()]); return RestClient.builder(hosts).build(); } @@ -24,5 +23,4 @@ public static String getClusterHealthPath() { } public static Header jsonHeader = new BasicHeader("Content-Type", "application/json"); - } diff --git a/src/main/java/org/broadinstitute/consent/http/util/ComplianceLogger.java b/src/main/java/org/broadinstitute/consent/http/util/ComplianceLogger.java index 3b75c229b9..96f43d9f9b 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/ComplianceLogger.java +++ b/src/main/java/org/broadinstitute/consent/http/util/ComplianceLogger.java @@ -11,8 +11,7 @@ public class ComplianceLogger implements ConsentLogger { - private ComplianceLogger() { - } + private ComplianceLogger() {} private static ComplianceLogger getInstance() { return new ComplianceLogger(); @@ -27,7 +26,8 @@ public enum ComplianceEvent { CLOSEOUT_SO_APPROVAL } - private static final String MESSAGE = """ + private static final String MESSAGE = + """ _time: %s; \ src_ip: %s; \ dest_ip: %s; \ @@ -48,70 +48,80 @@ public enum ComplianceEvent { event_type: %s; \ """; - private void logEvent(User user, List datasets, ContainerRequest request, - int responseStatusCode, ComplianceEvent event) { + private void logEvent( + User user, + List datasets, + ContainerRequest request, + int responseStatusCode, + ComplianceEvent event) { Instant now = Instant.now(); String sourceIp = Objects.requireNonNullElse(request.getHeaderString("X-Forwarded-For"), "-"); - String destinationIp = Objects.requireNonNullElse(request.getHeaderString("X-Forwarded-Server"), - "-"); + String destinationIp = + Objects.requireNonNullElse(request.getHeaderString("X-Forwarded-Server"), "-"); String userId = Objects.requireNonNullElse(request.getHeaderString("oidc_claim_user_id"), "-"); - String userAgent = Objects.requireNonNullElse(request.getHeaderString(HttpHeaders.USER_AGENT), - "-"); + String userAgent = + Objects.requireNonNullElse(request.getHeaderString(HttpHeaders.USER_AGENT), "-"); String userIdProvider = user.getEraCommonsId() == null ? "-" : "RAS"; - String urlString = request.getRequestUri() == null ? "-" - : request.getRequestUri().toString(); + String urlString = request.getRequestUri() == null ? "-" : request.getRequestUri().toString(); String responseContentType = MediaType.APPLICATION_JSON; String institutionName = user.getInstitution() == null ? "-" : user.getInstitution().getName(); - datasets.forEach(dataset -> { - String logMessage = MESSAGE - .formatted( - now, - sourceIp, - destinationIp, - user.getDisplayName(), - userId, - userIdProvider, - urlString, - userAgent, - responseStatusCode, - responseContentType, - institutionName, - user.getEmail(), - dataset.getDatasetIdentifier(), - user.getEraCommonsId(), - event); - logInfo(logMessage); - }); + datasets.forEach( + dataset -> { + String logMessage = + MESSAGE.formatted( + now, + sourceIp, + destinationIp, + user.getDisplayName(), + userId, + userIdProvider, + urlString, + userAgent, + responseStatusCode, + responseContentType, + institutionName, + user.getEmail(), + dataset.getDatasetIdentifier(), + user.getEraCommonsId(), + event); + logInfo(logMessage); + }); } - public static void logDARApproval(User user, List datasets, ContainerRequest request, - int responseStatusCode) { - getInstance().logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_APPROVAL); + public static void logDARApproval( + User user, List datasets, ContainerRequest request, int responseStatusCode) { + getInstance() + .logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_APPROVAL); } - public static void logRadarApproval(User user, List datasets, ContainerRequest request, - int responseStatusCode) { - getInstance().logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.RADAR_APPROVAL); + public static void logRadarApproval( + User user, List datasets, ContainerRequest request, int responseStatusCode) { + getInstance() + .logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.RADAR_APPROVAL); } - public static void logDARRejection(User user, List datasets, ContainerRequest request, - int responseStatusCode) { - getInstance().logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_REJECTION); + public static void logDARRejection( + User user, List datasets, ContainerRequest request, int responseStatusCode) { + getInstance() + .logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_REJECTION); } - public static void logDARSubmission(User user, List datasets, ContainerRequest request, - int responseStatusCode) { - getInstance().logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_SUBMISSION); + public static void logDARSubmission( + User user, List datasets, ContainerRequest request, int responseStatusCode) { + getInstance() + .logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_SUBMISSION); } - public static void logDARCancellation(User user, List datasets, ContainerRequest request, - int responseStatusCode) { - getInstance().logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_CANCELLATION); + public static void logDARCancellation( + User user, List datasets, ContainerRequest request, int responseStatusCode) { + getInstance() + .logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.DAR_CANCELLATION); } - public static void logCloseoutApprovalBySigningOfficial(User user, List datasets, - ContainerRequest request, int responseStatusCode) { - getInstance().logEvent(user, datasets, request, responseStatusCode, ComplianceEvent.CLOSEOUT_SO_APPROVAL); + public static void logCloseoutApprovalBySigningOfficial( + User user, List datasets, ContainerRequest request, int responseStatusCode) { + getInstance() + .logEvent( + user, datasets, request, responseStatusCode, ComplianceEvent.CLOSEOUT_SO_APPROVAL); } - } diff --git a/src/main/java/org/broadinstitute/consent/http/util/ConsentLogger.java b/src/main/java/org/broadinstitute/consent/http/util/ConsentLogger.java index cde68094d5..8e760d4eb3 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/ConsentLogger.java +++ b/src/main/java/org/broadinstitute/consent/http/util/ConsentLogger.java @@ -36,7 +36,7 @@ default void logThrowable(Throwable t) { * Logs a message and exception to the console and to Sentry * * @param message The message - * @param e Exception + * @param e Exception */ default void logException(String message, Exception e) { getLogger(this.getClass()).error(message + e.getMessage()); @@ -56,7 +56,7 @@ default void logWarn(String message) { * Logs a warning message and throwable to the console * * @param message Error Message - * @param t Exception + * @param t Exception */ default void logWarn(String message, Throwable t) { getLogger(this.getClass()).warn(message, t); diff --git a/src/main/java/org/broadinstitute/consent/http/util/CountryValidator.java b/src/main/java/org/broadinstitute/consent/http/util/CountryValidator.java index d717abae15..a51b64418e 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/CountryValidator.java +++ b/src/main/java/org/broadinstitute/consent/http/util/CountryValidator.java @@ -2,8 +2,8 @@ import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; import com.google.gson.JsonParseException; +import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -30,8 +30,18 @@ public class CountryValidator { "macao", "russian federation (the)", "venezuela (bolivarian republic of)"); + private static final Set bannedCountriesCFR = - Set.of("china", "cuba", "hong kong", "iran", "macao", "macau", "north korea", "russia", "venezuela"); + Set.of( + "china", + "cuba", + "hong kong", + "iran", + "macao", + "macau", + "north korea", + "russia", + "venezuela"); public CountryValidator() { try (InputStream is = getClass().getClassLoader().getResourceAsStream(FILEPATH)) { @@ -51,14 +61,13 @@ public boolean isInCountryList(String country) { public static boolean containsBannedCountry(DataAccessRequest dar) { return dar.getData().getLabAndInternalCollaborators().stream() - .anyMatch(collaborator -> isInBannedCountryList(collaborator.countryOfOperation())) + .anyMatch(collaborator -> isInBannedCountryList(collaborator.countryOfOperation())) || isInBannedCountryList(dar.getData().getPiCountryOfOperation()); } private static boolean isInBannedCountryList(String countryOfOperation) { if (countryOfOperation == null) return false; return bannedCountriesCFR.contains(countryOfOperation.trim().toLowerCase()) - || bannedCountriesISO3166.contains( - countryOfOperation.trim().toLowerCase()); + || bannedCountriesISO3166.contains(countryOfOperation.trim().toLowerCase()); } } diff --git a/src/main/java/org/broadinstitute/consent/http/util/HttpClientUtil.java b/src/main/java/org/broadinstitute/consent/http/util/HttpClientUtil.java index 4d50b1c822..31fb5db264 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/HttpClientUtil.java +++ b/src/main/java/org/broadinstitute/consent/http/util/HttpClientUtil.java @@ -36,9 +36,7 @@ public class HttpClientUtil implements ConsentLogger { - public record SimpleResponse(int code, String entity) { - - } + public record SimpleResponse(int code, String entity) {} private final ServicesConfiguration configuration; @@ -49,16 +47,17 @@ public record SimpleResponse(int code, String entity) { public HttpClientUtil(ServicesConfiguration configuration) { this.configuration = configuration; httpClient = HttpClients.createDefault(); - CacheLoader loader = new CacheLoader<>() { - @Override - public SimpleResponse load(URI uri) throws Exception { - return getHttpResponse(new HttpGet(uri)); - } - }; - this.cache = CacheBuilder - .newBuilder() - .expireAfterWrite(configuration.getCacheExpireMinutes(), TimeUnit.MINUTES) - .build(loader); + CacheLoader loader = + new CacheLoader<>() { + @Override + public SimpleResponse load(URI uri) throws Exception { + return getHttpResponse(new HttpGet(uri)); + } + }; + this.cache = + CacheBuilder.newBuilder() + .expireAfterWrite(configuration.getCacheExpireMinutes(), TimeUnit.MINUTES) + .build(loader); } /** @@ -88,14 +87,15 @@ public SimpleResponse getCachedResponse(HttpGet request) throws IOException { * @throws IOException The exception */ public SimpleResponse getHttpResponse(HttpGet request) throws IOException { - final ScheduledExecutorService executor = Executors.newScheduledThreadPool( - configuration.getPoolSize()); + final ScheduledExecutorService executor = + Executors.newScheduledThreadPool(configuration.getPoolSize()); executor.schedule(request::cancel, configuration.getTimeoutSeconds(), TimeUnit.SECONDS); - return httpClient.execute(request, httpResponse -> - new SimpleResponse( - httpResponse.getCode(), - IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset())) - ); + return httpClient.execute( + request, + httpResponse -> + new SimpleResponse( + httpResponse.getCode(), + IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset()))); } public HttpRequest buildGetRequest(GenericUrl genericUrl, AuthUser authUser) throws Exception { @@ -144,8 +144,10 @@ public HttpRequest buildUnAuthedPostRequest(GenericUrl genericUrl, HttpContent c } public HttpResponse handleHttpRequest(HttpRequest request) { - String timerName = String.format("org.broadinstitute.consent.http.util.HttpClientUtil-%s-%s", - request.getRequestMethod(), request.getUrl().toString()); + String timerName = + String.format( + "org.broadinstitute.consent.http.util.HttpClientUtil-%s-%s", + request.getRequestMethod(), request.getUrl().toString()); if (SharedMetricRegistries.tryGetDefault() == null) { logWarn("Default SharedMetricRegistries is null, setting default"); SharedMetricRegistries.setDefault("org.broadinstitute.consent", new MetricRegistry()); @@ -174,7 +176,8 @@ public HttpResponse handleHttpRequest(HttpRequest request) { }; } } catch (IOException e) { - throw new ServerErrorException("Server Error (" + e.getMessage() + ")", HttpStatusCodes.STATUS_CODE_SERVER_ERROR); + throw new ServerErrorException( + "Server Error (" + e.getMessage() + ")", HttpStatusCodes.STATUS_CODE_SERVER_ERROR); } throw new ServerErrorException("Server Error", HttpStatusCodes.STATUS_CODE_SERVER_ERROR); } diff --git a/src/main/java/org/broadinstitute/consent/http/util/InstitutionUtil.java b/src/main/java/org/broadinstitute/consent/http/util/InstitutionUtil.java index 7025a62135..26a6ebfe90 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/InstitutionUtil.java +++ b/src/main/java/org/broadinstitute/consent/http/util/InstitutionUtil.java @@ -6,7 +6,6 @@ import com.google.gson.GsonBuilder; import jakarta.ws.rs.BadRequestException; import java.util.List; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.validator.routines.DomainValidator; import org.broadinstitute.consent.http.models.Institution; import org.broadinstitute.consent.http.util.gson.GsonUtil; @@ -34,21 +33,22 @@ private ExclusionStrategy getSerializationExclusionStrategy(Boolean isAdmin) { public boolean shouldSkipField(FieldAttributes field) { String fieldName = field.getName(); - return !isAdmin && !(fieldName.equals("id") - || fieldName.equals("name") - || fieldName.equals("signingOfficials") - || fieldName.equals("displayName") - || fieldName.equals("userId") - || fieldName.equals("email") - || fieldName.equals("itDirectorName") - || fieldName.equals("itDirectorEmail") - || fieldName.equals("institutionUrl") - || fieldName.equals("dunsNumber") - || fieldName.equals("orgChartUrl") - || fieldName.equals("verificationUrl") - || fieldName.equals("verificationFilename") - || fieldName.equals("organizationType") - || fieldName.equals("domains")); + return !isAdmin + && !(fieldName.equals("id") + || fieldName.equals("name") + || fieldName.equals("signingOfficials") + || fieldName.equals("displayName") + || fieldName.equals("userId") + || fieldName.equals("email") + || fieldName.equals("itDirectorName") + || fieldName.equals("itDirectorEmail") + || fieldName.equals("institutionUrl") + || fieldName.equals("dunsNumber") + || fieldName.equals("orgChartUrl") + || fieldName.equals("verificationUrl") + || fieldName.equals("verificationFilename") + || fieldName.equals("organizationType") + || fieldName.equals("domains")); } // NOTE: shouldSkipClass is mandatory when creating an ExclusionStrategy @@ -96,9 +96,7 @@ protected static List getInvalidInstitutionDomains(Institution instituti DomainValidator validator = DomainValidator.getInstance(); - return institution.getDomains().stream() - .filter(domain -> !validator.isValid(domain)) - .toList(); + return institution.getDomains().stream().filter(domain -> !validator.isValid(domain)).toList(); } public static void validateInstitutionDomains(Institution institution) { diff --git a/src/main/java/org/broadinstitute/consent/http/util/JsonSchemaUtil.java b/src/main/java/org/broadinstitute/consent/http/util/JsonSchemaUtil.java index a8e4edde5e..dc2d3c6192 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/JsonSchemaUtil.java +++ b/src/main/java/org/broadinstitute/consent/http/util/JsonSchemaUtil.java @@ -24,15 +24,15 @@ public class JsonSchemaUtil implements ConsentLogger { private final String datasetRegistrationSchemaV1 = "/dataset-registration-schema_v1.json"; private JsonSchemaFactory factory; - public JsonSchemaUtil() { factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909); - CacheLoader loader = new CacheLoader<>() { - @Override - public String load(String key) throws Exception { - return IOUtils.resourceToString(key, Charset.defaultCharset()); - } - }; + CacheLoader loader = + new CacheLoader<>() { + @Override + public String load(String key) throws Exception { + return IOUtils.resourceToString(key, Charset.defaultCharset()); + } + }; this.cache = CacheBuilder.newBuilder().build(loader); } @@ -45,7 +45,6 @@ public String getDatasetRegistrationSchemaV1() { } } - /** * Loads a Schema populated from the current dataset registration schema * diff --git a/src/main/java/org/broadinstitute/consent/http/util/OpenAPIBundler.java b/src/main/java/org/broadinstitute/consent/http/util/OpenAPIBundler.java index a6eff7068a..cae839c993 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/OpenAPIBundler.java +++ b/src/main/java/org/broadinstitute/consent/http/util/OpenAPIBundler.java @@ -2,89 +2,88 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; +import io.swagger.v3.core.util.Json; +import io.swagger.v3.core.util.Yaml; import io.swagger.v3.parser.OpenAPIV3Parser; import io.swagger.v3.parser.core.models.ParseOptions; import io.swagger.v3.parser.core.models.SwaggerParseResult; -import io.swagger.v3.core.util.Json; -import io.swagger.v3.core.util.Yaml; -import org.slf4j.LoggerFactory; - import java.io.File; import java.io.IOException; +import org.slf4j.LoggerFactory; /** * Utility class to bundle OpenAPI specifications with $ref resolution. * - * This class is invoked during a Maven build to create a single bundled openapi - * resource file. + *

This class is invoked during a Maven build to create a single bundled openapi resource file. */ public class OpenAPIBundler { - static final String INPUT_FILE = "src/main/resources/assets/api-docs.yaml"; - static final String OUTPUT_DIR = "target/classes/assets"; - - /** - * Bundle an OpenAPI specification file by resolving all $ref references. - * - * @throws IOException if file operations fail - */ - public static void bundleOpenAPI() throws IOException { - File inputFile = new File(INPUT_FILE); - File outputDir = new File(OUTPUT_DIR); - - if (!inputFile.exists()) { - throw new IOException("Input file does not exist: " + INPUT_FILE); - } - - if (!outputDir.exists() && !outputDir.mkdirs()) { - throw new IOException("Failed to create output directory: " + OUTPUT_DIR); - } - - System.out.println("Parsing OpenAPI spec from: " + inputFile.getAbsolutePath()); - - // Suppress "infinite loop" debug logging from OpenAPI due to circular refs - Logger parserLogger = (Logger) LoggerFactory.getLogger("io.swagger.v3.parser"); - Level originalLevel = parserLogger.getLevel(); - parserLogger.setLevel(Level.WARN); - - // Configure parser to resolve all references - ParseOptions parseOptions = new ParseOptions(); - parseOptions.setResolve(true); - parseOptions.setResolveFully(true); - - // Parse the OpenAPI specification - OpenAPIV3Parser parser = new OpenAPIV3Parser(); - SwaggerParseResult result = parser.readLocation(inputFile.getAbsolutePath(), null, parseOptions); - - // Restore original logging level - parserLogger.setLevel(originalLevel); - - // Check for messages/warnings - if (result.getMessages() != null && !result.getMessages().isEmpty()) { - System.out.println("Warning messages:"); - result.getMessages().forEach(msg -> System.out.println(" - " + msg)); - } - - // Ensure we got a valid OpenAPI object - if (result.getOpenAPI() == null) { - throw new IOException("Failed to parse OpenAPI specification. Check the messages above."); - } - - // Write bundled output in both JSON and YAML formats - File jsonFile = new File(outputDir, "openapi.json"); - File yamlFile = new File(outputDir, "openapi.yaml"); - - Json.pretty().writeValue(jsonFile, result.getOpenAPI()); - Yaml.pretty().writeValue(yamlFile, result.getOpenAPI()); + static final String INPUT_FILE = "src/main/resources/assets/api-docs.yaml"; + static final String OUTPUT_DIR = "target/classes/assets"; + + /** + * Bundle an OpenAPI specification file by resolving all $ref references. + * + * @throws IOException if file operations fail + */ + public static void bundleOpenAPI() throws IOException { + File inputFile = new File(INPUT_FILE); + File outputDir = new File(OUTPUT_DIR); + + if (!inputFile.exists()) { + throw new IOException("Input file does not exist: " + INPUT_FILE); + } + + if (!outputDir.exists() && !outputDir.mkdirs()) { + throw new IOException("Failed to create output directory: " + OUTPUT_DIR); + } + + System.out.println("Parsing OpenAPI spec from: " + inputFile.getAbsolutePath()); + + // Suppress "infinite loop" debug logging from OpenAPI due to circular refs + Logger parserLogger = (Logger) LoggerFactory.getLogger("io.swagger.v3.parser"); + Level originalLevel = parserLogger.getLevel(); + parserLogger.setLevel(Level.WARN); + + // Configure parser to resolve all references + ParseOptions parseOptions = new ParseOptions(); + parseOptions.setResolve(true); + parseOptions.setResolveFully(true); + + // Parse the OpenAPI specification + OpenAPIV3Parser parser = new OpenAPIV3Parser(); + SwaggerParseResult result = + parser.readLocation(inputFile.getAbsolutePath(), null, parseOptions); + + // Restore original logging level + parserLogger.setLevel(originalLevel); + + // Check for messages/warnings + if (result.getMessages() != null && !result.getMessages().isEmpty()) { + System.out.println("Warning messages:"); + result.getMessages().forEach(msg -> System.out.println(" - " + msg)); + } + + // Ensure we got a valid OpenAPI object + if (result.getOpenAPI() == null) { + throw new IOException("Failed to parse OpenAPI specification. Check the messages above."); } - public static void main(String[] args) { - try { - bundleOpenAPI(); - System.out.println("✓ OpenAPI bundling completed successfully."); - } catch (Exception e) { - System.err.println("Error bundling OpenAPI: " + e.getMessage()); - System.exit(1); - } + // Write bundled output in both JSON and YAML formats + File jsonFile = new File(outputDir, "openapi.json"); + File yamlFile = new File(outputDir, "openapi.yaml"); + + Json.pretty().writeValue(jsonFile, result.getOpenAPI()); + Yaml.pretty().writeValue(yamlFile, result.getOpenAPI()); + } + + public static void main(String[] args) { + try { + bundleOpenAPI(); + System.out.println("✓ OpenAPI bundling completed successfully."); + } catch (Exception e) { + System.err.println("Error bundling OpenAPI: " + e.getMessage()); + System.exit(1); } + } } diff --git a/src/main/java/org/broadinstitute/consent/http/util/ThreadUtils.java b/src/main/java/org/broadinstitute/consent/http/util/ThreadUtils.java index 4c5099692d..2eee001ff9 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/ThreadUtils.java +++ b/src/main/java/org/broadinstitute/consent/http/util/ThreadUtils.java @@ -13,12 +13,15 @@ public class ThreadUtils implements ConsentLogger { * @return A new ExecutorService instance. */ public ExecutorService getExecutorService(Class clazz) { - ExecutorService executorService = Executors.newFixedThreadPool( - Runtime.getRuntime().availableProcessors()); - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - logInfo("Shutting down %s executor service".formatted(clazz.getSimpleName())); - executorService.shutdown(); - })); + ExecutorService executorService = + Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + Runtime.getRuntime() + .addShutdownHook( + new Thread( + () -> { + logInfo("Shutting down %s executor service".formatted(clazz.getSimpleName())); + executorService.shutdown(); + })); return executorService; } } diff --git a/src/main/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapter.java b/src/main/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapter.java index d95eff9cb7..73569fd901 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapter.java +++ b/src/main/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapter.java @@ -9,11 +9,8 @@ import com.google.gson.JsonSerializer; import java.lang.reflect.Type; -/** - * Written to be clear this is an internal that should not be exposed via JSON. - */ -public class BlobIdTypeAdapter - implements JsonSerializer, JsonDeserializer { +/** Written to be clear this is an internal that should not be exposed via JSON. */ +public class BlobIdTypeAdapter implements JsonSerializer, JsonDeserializer { @Override public JsonElement serialize(BlobId src, Type srcType, JsonSerializationContext context) { diff --git a/src/main/java/org/broadinstitute/consent/http/util/gson/DateTypeAdapter.java b/src/main/java/org/broadinstitute/consent/http/util/gson/DateTypeAdapter.java index 0f07018c17..d761dbbe93 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/gson/DateTypeAdapter.java +++ b/src/main/java/org/broadinstitute/consent/http/util/gson/DateTypeAdapter.java @@ -12,8 +12,7 @@ import java.text.SimpleDateFormat; import java.util.Date; -public class DateTypeAdapter - implements JsonSerializer, JsonDeserializer { +public class DateTypeAdapter implements JsonSerializer, JsonDeserializer { @Override public JsonElement serialize(Date src, Type srcType, JsonSerializationContext context) { diff --git a/src/main/java/org/broadinstitute/consent/http/util/gson/GsonUtil.java b/src/main/java/org/broadinstitute/consent/http/util/gson/GsonUtil.java index aeaa0af771..1b5615c259 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/gson/GsonUtil.java +++ b/src/main/java/org/broadinstitute/consent/http/util/gson/GsonUtil.java @@ -31,20 +31,10 @@ public static Gson buildGsonNullSerializer() { public static GsonBuilder gsonBuilderWithAdapters() { return new GsonBuilder() .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) - .registerTypeAdapter( - Instant.class, - new InstantTypeAdapter()) - .registerTypeAdapter( - BlobId.class, - new BlobIdTypeAdapter()) - .registerTypeAdapter( - Date.class, - new DateTypeAdapter()) - .registerTypeAdapter( - Timestamp.class, - new TimestampTypeAdapter()) - .registerTypeHierarchyAdapter( - Throwable.class, - new ThrowableTypeAdapter()); + .registerTypeAdapter(Instant.class, new InstantTypeAdapter()) + .registerTypeAdapter(BlobId.class, new BlobIdTypeAdapter()) + .registerTypeAdapter(Date.class, new DateTypeAdapter()) + .registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()) + .registerTypeHierarchyAdapter(Throwable.class, new ThrowableTypeAdapter()); } } diff --git a/src/main/java/org/broadinstitute/consent/http/util/gson/InstantTypeAdapter.java b/src/main/java/org/broadinstitute/consent/http/util/gson/InstantTypeAdapter.java index 4d5d5e2683..43a294da02 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/gson/InstantTypeAdapter.java +++ b/src/main/java/org/broadinstitute/consent/http/util/gson/InstantTypeAdapter.java @@ -11,8 +11,7 @@ import java.time.Instant; import java.time.format.DateTimeParseException; -public class InstantTypeAdapter - implements JsonSerializer, JsonDeserializer { +public class InstantTypeAdapter implements JsonSerializer, JsonDeserializer { @Override public JsonElement serialize(Instant src, Type srcType, JsonSerializationContext context) { diff --git a/src/main/java/org/broadinstitute/consent/http/util/gson/JerseyGsonProvider.java b/src/main/java/org/broadinstitute/consent/http/util/gson/JerseyGsonProvider.java index cc4708a3b1..4838fc0bb4 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/gson/JerseyGsonProvider.java +++ b/src/main/java/org/broadinstitute/consent/http/util/gson/JerseyGsonProvider.java @@ -21,34 +21,43 @@ @Provider @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class JerseyGsonProvider implements MessageBodyWriter, - MessageBodyReader { +public class JerseyGsonProvider implements MessageBodyWriter, MessageBodyReader { @Override - public boolean isReadable(Class aClass, Type type, Annotation[] annotations, - MediaType mediaType) { + public boolean isReadable( + Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { return true; } @Override - public Object readFrom(Class aClass, Type type, Annotation[] annotations, - MediaType mediaType, MultivaluedMap multivaluedMap, InputStream inputStream) + public Object readFrom( + Class aClass, + Type type, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap multivaluedMap, + InputStream inputStream) throws JsonSyntaxException, WebApplicationException, IOException { try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { return GsonUtil.getInstance().fromJson(reader, type); } - } @Override - public boolean isWriteable(Class aClass, Type type, Annotation[] annotations, - MediaType mediaType) { + public boolean isWriteable( + Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { return true; } @Override - public void writeTo(Object object, Class aClass, Type type, Annotation[] annotations, - MediaType mediaType, MultivaluedMap multivaluedMap, OutputStream outputStream) + public void writeTo( + Object object, + Class aClass, + Type type, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap multivaluedMap, + OutputStream outputStream) throws IOException, WebApplicationException { try (OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) { GsonUtil.getInstance().toJson(object, type, writer); @@ -57,11 +66,7 @@ public void writeTo(Object object, Class aClass, Type type, Annotation[] anno @Override public long getSize( - Object o, - Class type, - Type genericType, - Annotation[] annotations, - MediaType mediaType) { + Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } } diff --git a/src/main/java/org/broadinstitute/consent/http/util/gson/ThrowableTypeAdapter.java b/src/main/java/org/broadinstitute/consent/http/util/gson/ThrowableTypeAdapter.java index ee9a6e9879..f6f7cef3f5 100644 --- a/src/main/java/org/broadinstitute/consent/http/util/gson/ThrowableTypeAdapter.java +++ b/src/main/java/org/broadinstitute/consent/http/util/gson/ThrowableTypeAdapter.java @@ -6,8 +6,7 @@ import com.google.gson.JsonSerializer; import java.lang.reflect.Type; -public class ThrowableTypeAdapter - implements JsonSerializer { +public class ThrowableTypeAdapter implements JsonSerializer { @Override public JsonElement serialize(Throwable src, Type srcType, JsonSerializationContext context) { diff --git a/src/test/java/org/broadinstitute/consent/http/AbstractTestHelper.java b/src/test/java/org/broadinstitute/consent/http/AbstractTestHelper.java index 42d57b30a4..ab1f4ceea9 100644 --- a/src/test/java/org/broadinstitute/consent/http/AbstractTestHelper.java +++ b/src/test/java/org/broadinstitute/consent/http/AbstractTestHelper.java @@ -25,5 +25,4 @@ public static int randomInt(int startInclusive, int endExclusive) { public static int nextInt() { return RandomUtils.secure().randomInt(); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/MockServerTestHelper.java b/src/test/java/org/broadinstitute/consent/http/MockServerTestHelper.java index 329773f957..be4cf04263 100644 --- a/src/test/java/org/broadinstitute/consent/http/MockServerTestHelper.java +++ b/src/test/java/org/broadinstitute/consent/http/MockServerTestHelper.java @@ -7,14 +7,13 @@ import org.testcontainers.containers.MockServerContainer; import org.testcontainers.containers.wait.strategy.Wait; -public class MockServerTestHelper extends AbstractTestHelper implements TestExecutionListener, - WithMockServer { +public class MockServerTestHelper extends AbstractTestHelper + implements TestExecutionListener, WithMockServer { - public static final MockServerContainer CONTAINER = new MockServerContainer(IMAGE).waitingFor( - Wait.forLogMessage(".*started on port:.*", 1)); + public static final MockServerContainer CONTAINER = + new MockServerContainer(IMAGE).waitingFor(Wait.forLogMessage(".*started on port:.*", 1)); public static MockServerClient mockServerClient; - @Override public void testPlanExecutionStarted(TestPlan testPlan) { try { diff --git a/src/test/java/org/broadinstitute/consent/http/authentication/AuthorizationHelperTest.java b/src/test/java/org/broadinstitute/consent/http/authentication/AuthorizationHelperTest.java index fbbc54a81a..616b5f387f 100644 --- a/src/test/java/org/broadinstitute/consent/http/authentication/AuthorizationHelperTest.java +++ b/src/test/java/org/broadinstitute/consent/http/authentication/AuthorizationHelperTest.java @@ -43,18 +43,12 @@ @ExtendWith(MockitoExtension.class) class AuthorizationHelperTest extends AbstractTestHelper { - @Mock - private SamService samService; - @Mock - private UserService userService; - @Mock - private AuthUser authorizedUser; - @Mock - private AuthUser unauthorizedUser; - @Mock - private DuosUser authorizedDuosUser; - @Mock - private DuosUser unauthorizedDuosUser; + @Mock private SamService samService; + @Mock private UserService userService; + @Mock private AuthUser authorizedUser; + @Mock private AuthUser unauthorizedUser; + @Mock private DuosUser authorizedDuosUser; + @Mock private DuosUser unauthorizedDuosUser; private AuthorizationHelper authorizationHelper; private DuosUserAuthenticator duosUserAuthenticator; @@ -85,8 +79,15 @@ void testAuthorized() { @ParameterizedTest @NullAndEmptySource - @ValueSource(strings = {Resource.MEMBER, Resource.CHAIRPERSON, Resource.SIGNINGOFFICIAL, - Resource.ADMIN, Resource.DATASUBMITTER, Resource.ITDIRECTOR}) + @ValueSource( + strings = { + Resource.MEMBER, + Resource.CHAIRPERSON, + Resource.SIGNINGOFFICIAL, + Resource.ADMIN, + Resource.DATASUBMITTER, + Resource.ITDIRECTOR + }) void testNotAuthorized(String roleName) { unauthorizedUser.setEmail("email"); unauthorizedDuosUser.setEmail(unauthorizedUser.getEmail()); @@ -119,9 +120,7 @@ void testAuthenticateGetUserInfoSuccess() { assertNotNull(authUser.getAuthToken()); } - /** - * Test that in the case of a header lookup failure, we don't fail the overall request. - */ + /** Test that in the case of a header lookup failure, we don't fail the overall request. */ @Test void testAuthenticateGetUserInfoFailure() { headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); @@ -136,9 +135,7 @@ void testAuthenticateGetUserInfoFailure() { assertFalse(duosUser.isPresent()); } - /** - * Test that in the case of a Sam user lookup failure, we then try to register the user - */ + /** Test that in the case of a Sam user lookup failure, we then try to register the user */ @Test void testAuthenticateGetUserWithStatusInfoFailurePostUserSuccess() throws Exception { headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); @@ -146,9 +143,10 @@ void testAuthenticateGetUserWithStatusInfoFailurePostUserSuccess() throws Except headerMap.put(ClaimsCache.OAUTH2_CLAIM_name, List.of("name")); headerCache.loadCache(bearerToken, headerMap); when(samService.getRegistrationInfo(any())).thenThrow(new NotFoundException()); - when(samService.postRegistrationInfo(any())).thenReturn( - new UserStatus() - .setUserInfo(new UserInfo().setUserEmail("email").setUserSubjectId("subjectId"))); + when(samService.postRegistrationInfo(any())) + .thenReturn( + new UserStatus() + .setUserInfo(new UserInfo().setUserEmail("email").setUserSubjectId("subjectId"))); Optional authUser = oAuthAuthenticator.authenticate(bearerToken); assertEquals(bearerToken, authUser.orElseThrow().getAuthToken()); @@ -166,13 +164,15 @@ void testAuthenticateGetUserWithStatusInfoFailurePostUserFailureWebAppEx() throw when(samService.getRegistrationInfo(any())).thenThrow(new NotFoundException()); when(samService.postRegistrationInfo(any())).thenThrow(new Exception("errorMessage")); - WebApplicationException ex = assertThrows(WebApplicationException.class, - () -> oAuthAuthenticator.authenticate(bearerToken)); + WebApplicationException ex = + assertThrows( + WebApplicationException.class, () -> oAuthAuthenticator.authenticate(bearerToken)); assertEquals("errorMessage", ex.getMessage()); } /** - * Test that in the case of a missing claim headers (other than email), we don't fail on Sam user lookup + * Test that in the case of a missing claim headers (other than email), we don't fail on Sam user + * lookup */ @Test void testAuthenticateGetUserWithStatusInfoIncompleteClaims() { @@ -184,21 +184,16 @@ void testAuthenticateGetUserWithStatusInfoIncompleteClaims() { assertEquals(authUser.orElseThrow().getAuthToken(), bearerToken); } - /** - * Test that in the case of a missing email header, we throw an exception. - */ + /** Test that in the case of a missing email header, we throw an exception. */ @Test void testAuthenticateGetUserWithStatusInfMissingEmailClaimsThrows() { headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); headerCache.loadCache(bearerToken, headerMap); - assertThrows(NotAuthorizedException.class, ()->oAuthAuthenticator.authenticate(bearerToken)); - + assertThrows(NotAuthorizedException.class, () -> oAuthAuthenticator.authenticate(bearerToken)); } - /** - * Test that if the name is "unknown" in the header, we use the email as the name - */ + /** Test that if the name is "unknown" in the header, we use the email as the name */ @Test void testUnknownNameDefaultsToEmail() { headerMap.put(ClaimsCache.OAUTH2_CLAIM_access_token, List.of(bearerToken)); @@ -209,5 +204,4 @@ void testUnknownNameDefaultsToEmail() { Optional authUser = oAuthAuthenticator.authenticate(bearerToken); assertEquals(authUser.orElseThrow().getName(), authUser.orElseThrow().getEmail()); } - -} \ No newline at end of file +} diff --git a/src/test/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilterTest.java b/src/test/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilterTest.java index 5a994096c1..2f6ace4db7 100644 --- a/src/test/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilterTest.java +++ b/src/test/java/org/broadinstitute/consent/http/authentication/OAuthCustomAuthFilterTest.java @@ -12,7 +12,6 @@ import jakarta.ws.rs.core.UriInfo; import java.security.Principal; import java.util.Optional; -import org.broadinstitute.consent.http.db.UserRoleDAO; import org.broadinstitute.consent.http.models.AuthUser; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -24,22 +23,15 @@ @ExtendWith(MockitoExtension.class) class OAuthCustomAuthFilterTest { - @Mock - private ContainerRequestContext requestContext; - @Mock - private MultivaluedMap headers; - @Mock - private UriInfo uriInfo; - @Mock - private OAuthAuthenticator authenticator; - @Mock - private AuthorizationHelper authorizationHelper; + @Mock private ContainerRequestContext requestContext; + @Mock private MultivaluedMap headers; + @Mock private UriInfo uriInfo; + @Mock private OAuthAuthenticator authenticator; + @Mock private AuthorizationHelper authorizationHelper; - @Mock - private OAuthCustomAuthFilter filter; + @Mock private OAuthCustomAuthFilter filter; - @Mock - private AuthUser user; + @Mock private AuthUser user; private final String token = "0cx2G9gKm4XZdK8BFxoWy7AE025tvq"; @@ -60,7 +52,6 @@ void testFilterSuccessful() { assertDoesNotThrow(() -> filter.filter(requestContext)); } - @Test void testFilterExceptionBadCredentials() { when(uriInfo.getPath()).thenReturn("api/something"); @@ -72,7 +63,8 @@ void testFilterExceptionBadCredentials() { void testFilterAuthWebApplicationException() { when(uriInfo.getPath()).thenReturn("api/something"); when(authenticator.authenticate(token)).thenThrow(new WebApplicationException("errorMessage")); - WebApplicationException ex = assertThrows(WebApplicationException.class, () -> filter.filter(requestContext)); + WebApplicationException ex = + assertThrows(WebApplicationException.class, () -> filter.filter(requestContext)); assertEquals("errorMessage", ex.getMessage()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/cloudstore/GCSServiceTest.java b/src/test/java/org/broadinstitute/consent/http/cloudstore/GCSServiceTest.java index 16ca89cd2b..2e05f2a4a4 100644 --- a/src/test/java/org/broadinstitute/consent/http/cloudstore/GCSServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/cloudstore/GCSServiceTest.java @@ -27,15 +27,12 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; - @ExtendWith(MockitoExtension.class) class GCSServiceTest extends AbstractTestHelper { - @Mock - private Storage storage; + @Mock private Storage storage; - @Mock - private Blob blob; + @Mock private Blob blob; private StoreConfiguration config; @@ -60,8 +57,8 @@ void testStoreDocument() throws Exception { UUID id = UUID.randomUUID(); BlobId blobId = BlobId.of(config.getEndpoint(), id.toString()); when(blob.getBlobId()).thenReturn(blobId); - when(storage.create(any(BlobInfo.class), any(), new Storage.BlobTargetOption[0])).thenReturn( - blob); + when(storage.create(any(BlobInfo.class), any(), new Storage.BlobTargetOption[0])) + .thenReturn(blob); initStore(); InputStream is = IOUtils.toInputStream("content", Charset.defaultCharset()); diff --git a/src/test/java/org/broadinstitute/consent/http/db/AcknowledgementDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/AcknowledgementDAOTest.java index 66953981e2..5e59b5e642 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/AcknowledgementDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/AcknowledgementDAOTest.java @@ -14,7 +14,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; - @ExtendWith(MockitoExtension.class) class AcknowledgementDAOTest extends DAOTestHelper { @@ -26,29 +25,32 @@ void createAndRetrieveAcknowledgement() throws InterruptedException { assertTrue(acknowledgementDAO.findAcknowledgementsForUser(user_id).isEmpty()); acknowledgementDAO.upsertAcknowledgement(key, user_id); - Acknowledgement newAcknowledgement = acknowledgementDAO.findAcknowledgementsByKeyForUser(key, - user_id); - assertEquals(newAcknowledgement.getFirstAcknowledged(), - newAcknowledgement.getLastAcknowledged()); + Acknowledgement newAcknowledgement = + acknowledgementDAO.findAcknowledgementsByKeyForUser(key, user_id); + assertEquals( + newAcknowledgement.getFirstAcknowledged(), newAcknowledgement.getLastAcknowledged()); assertEquals(key, newAcknowledgement.getAckKey()); assertEquals(user_id, newAcknowledgement.getUserId()); assertEquals(1, acknowledgementDAO.findAcknowledgementsForUser(user_id).size()); - assertEquals(newAcknowledgement, - acknowledgementDAO.findAcknowledgementsForUser(user_id).get(0)); + assertEquals( + newAcknowledgement, acknowledgementDAO.findAcknowledgementsForUser(user_id).get(0)); - //Theoretically possible that on a fast enough system not enough - //time will have passed to tick a millisecond in the clock. We should be lucky enough to see that. + // Theoretically possible that on a fast enough system not enough + // time will have passed to tick a millisecond in the clock. We should be lucky enough to see + // that. sleep(1); acknowledgementDAO.upsertAcknowledgement(key, user_id); assertEquals(1, acknowledgementDAO.findAcknowledgementsForUser(user_id).size()); Acknowledgement upsertResult = acknowledgementDAO.findAcknowledgementsForUser(user_id).get(0); assertNotEquals(newAcknowledgement, upsertResult); assertEquals(newAcknowledgement.getAckKey(), upsertResult.getAckKey()); - assertEquals(newAcknowledgement.getFirstAcknowledged().getTime(), + assertEquals( + newAcknowledgement.getFirstAcknowledged().getTime(), upsertResult.getFirstAcknowledged().getTime()); assertEquals(newAcknowledgement.getUserId(), upsertResult.getUserId()); - assertNotEquals(newAcknowledgement.getLastAcknowledged().getTime(), + assertNotEquals( + newAcknowledgement.getLastAcknowledged().getTime(), upsertResult.getLastAcknowledged().getTime()); } @@ -65,13 +67,12 @@ void createAndDeleteAcknowledgement() { Acknowledgement upsertResult = acknowledgementDAO.findAcknowledgementsForUser(user_id).get(0); assertEquals(2, acknowledgementDAO.findAcknowledgementsForUser(user_id).size()); - assertEquals(upsertResult, - acknowledgementDAO.findAcknowledgementsForUser(user_id).get(0)); + assertEquals(upsertResult, acknowledgementDAO.findAcknowledgementsForUser(user_id).get(0)); acknowledgementDAO.deleteAcknowledgement(key1, user_id); assertEquals(1, acknowledgementDAO.findAcknowledgementsForUser(user_id).size()); - Acknowledgement secondAcknowledgement = acknowledgementDAO.findAcknowledgementsForUser(user_id) - .get(0); + Acknowledgement secondAcknowledgement = + acknowledgementDAO.findAcknowledgementsForUser(user_id).get(0); assertEquals(key2, secondAcknowledgement.getAckKey()); } @@ -89,29 +90,29 @@ void ensureMissingAcknowledgementWorks() { acknowledgementDAO.upsertAcknowledgement(key1, user1Id); assertEquals(1, acknowledgementDAO.findAcknowledgementsForUser(user1Id).size()); - assertEquals(user1Id, - acknowledgementDAO.findAcknowledgementsByKeyForUser(key1, user1Id).getUserId()); + assertEquals( + user1Id, acknowledgementDAO.findAcknowledgementsByKeyForUser(key1, user1Id).getUserId()); acknowledgementDAO.upsertAcknowledgement(key1, user2Id); assertEquals(1, acknowledgementDAO.findAcknowledgementsForUser(user2Id).size()); - assertEquals(user2Id, - acknowledgementDAO.findAcknowledgementsByKeyForUser(key1, user2Id).getUserId()); + assertEquals( + user2Id, acknowledgementDAO.findAcknowledgementsByKeyForUser(key1, user2Id).getUserId()); acknowledgementDAO.upsertAcknowledgement(key2, user1Id); assertEquals(1, acknowledgementDAO.findAcknowledgementsForUser(user2Id).size()); - assertEquals(user2Id, - acknowledgementDAO.findAcknowledgementsByKeyForUser(key1, user2Id).getUserId()); + assertEquals( + user2Id, acknowledgementDAO.findAcknowledgementsByKeyForUser(key1, user2Id).getUserId()); - List user1Acknowledgements = acknowledgementDAO.findAcknowledgementsForUser( - user1Id); + List user1Acknowledgements = + acknowledgementDAO.findAcknowledgementsForUser(user1Id); assertEquals(2, user1Acknowledgements.size()); user1Acknowledgements.forEach((ack) -> assertEquals(user1Id, ack.getUserId())); - List user1AcknowledgementsWithList = acknowledgementDAO.findAcknowledgementsForUser( - key_list, user1Id); + List user1AcknowledgementsWithList = + acknowledgementDAO.findAcknowledgementsForUser(key_list, user1Id); assertEquals(2, user1AcknowledgementsWithList.size()); - List user2AcknowledgementsWithList = acknowledgementDAO.findAcknowledgementsForUser( - key_list, user2Id); + List user2AcknowledgementsWithList = + acknowledgementDAO.findAcknowledgementsForUser(key_list, user2Id); assertEquals(1, user2AcknowledgementsWithList.size()); } @@ -120,10 +121,8 @@ void testDeleteAcknowledgmentByUserId() { User user = createUser(); String ack = RandomStringUtils.randomAlphabetic(100); acknowledgementDAO.upsertAcknowledgement(ack, user.getUserId()); - assertEquals(1, - acknowledgementDAO.findAcknowledgementsForUser(user.getUserId()).size()); + assertEquals(1, acknowledgementDAO.findAcknowledgementsForUser(user.getUserId()).size()); acknowledgementDAO.deleteAllAcknowledgementsByUser(user.getUserId()); - assertEquals(0, - acknowledgementDAO.findAcknowledgementsForUser(user.getUserId()).size()); + assertEquals(0, acknowledgementDAO.findAcknowledgementsForUser(user.getUserId()).size()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAOTest.java index 2517c70605..63c82c0cdd 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DACAutomationRuleDAOTest.java @@ -34,8 +34,9 @@ void testInsertDACRuleSetting() { User user = createUser(); Integer dacId = createRandomDAC(); List rules = dacAutomationRuleDAO.findAll(); - Integer settingId = dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId, rules.get(0).id(), - user.getUserId(), Instant.now()); + Integer settingId = + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId, rules.get(0).id(), user.getUserId(), Instant.now()); Assertions.assertNotNull(settingId); } @@ -44,10 +45,10 @@ void testAuditedInsertDACRuleSetting() { User user = createUser(); Integer dacId1 = createRandomDAC(); List rulesByDacId = dacAutomationRuleDAO.findAll(); - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId1, rulesByDacId.get(0).id(), - user.getUserId(), Instant.now()); - List auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId1, 5, 0); + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId1, rulesByDacId.get(0).id(), user.getUserId(), Instant.now()); + List auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, 5, 0); Assertions.assertNotNull(auditRecords); Assertions.assertFalse(auditRecords.isEmpty()); Assertions.assertEquals(1, auditRecords.size()); @@ -61,22 +62,20 @@ void testAuditedInsertDACRuleSetting() { void testAuditedInsertDACRuleSettingRollback() { Integer dacId = createRandomDAC(); List rulesByDacId = dacAutomationRuleDAO.findAll(); - List auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId, 5, 0 - ); + List auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId, 5, 0); Assertions.assertEquals(0, auditRecords.size()); Integer ruleId = rulesByDacId.get(0).id(); Instant now = Instant.now(); // Use -1 userId to force a failure and trigger a rollback - Assertions.assertThrows(UnableToExecuteStatementException.class, () -> - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId, ruleId, -1, now) - ); + Assertions.assertThrows( + UnableToExecuteStatementException.class, + () -> dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId, ruleId, -1, now)); - List auditRecordsAfter = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId, 5, 0 - ); + List auditRecordsAfter = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId, 5, 0); Assertions.assertEquals(0, auditRecordsAfter.size()); } @@ -84,40 +83,42 @@ void testAuditedInsertDACRuleSettingRollback() { @Test void testFindRulesByDacIdAddSetting() { Integer dacId = createRandomDAC(); - List rulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId); + List rulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId); Assertions.assertNotNull(rulesByDacId); Assertions.assertFalse(rulesByDacId.isEmpty()); rulesByDacId.forEach(r -> Assertions.assertNull(r.enabledByUserId())); User user = createUser(); - Integer settingId = dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId, - rulesByDacId.get(0).id(), - user.getUserId(), Instant.now()); + Integer settingId = + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId, rulesByDacId.get(0).id(), user.getUserId(), Instant.now()); Assertions.assertNotNull(settingId); - List updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId); - assertTrue(updatedRulesByDacId.stream() - .anyMatch(r -> Objects.equals(r.enabledByUserId(), user.getUserId()))); + List updatedRulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId); + assertTrue( + updatedRulesByDacId.stream() + .anyMatch(r -> Objects.equals(r.enabledByUserId(), user.getUserId()))); assertTrue( updatedRulesByDacId.stream().anyMatch(r -> Objects.equals(r.userEmail(), user.getEmail()))); - assertTrue(updatedRulesByDacId.stream() - .anyMatch(r -> Objects.equals(r.displayName(), user.getDisplayName()))); + assertTrue( + updatedRulesByDacId.stream() + .anyMatch(r -> Objects.equals(r.displayName(), user.getDisplayName()))); } @Test void testFindRulesByDacIdRemoveSetting() { Integer dacId = createRandomDAC(); - List rulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId); + List rulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId); User user = createUser(); - Integer settingId = dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId, - rulesByDacId.get(0).id(), - user.getUserId(), Instant.now()); + Integer settingId = + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId, rulesByDacId.get(0).id(), user.getUserId(), Instant.now()); Assertions.assertNotNull(settingId); - dacAutomationRuleDAO.auditedDeleteDACRuleSetting(dacId, rulesByDacId.get(0).id(), - user.getUserId()); - List updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId); + dacAutomationRuleDAO.auditedDeleteDACRuleSetting( + dacId, rulesByDacId.get(0).id(), user.getUserId()); + List updatedRulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId); updatedRulesByDacId.forEach(r -> Assertions.assertNull(r.enabledByUserId())); } @@ -127,24 +128,21 @@ void testAuditedDeleteDACRuleSetting() { User auditUser = createUser(); Integer dacId1 = createRandomDAC(); List rulesByDacId = dacAutomationRuleDAO.findAll(); - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId1, rulesByDacId.get(0).id(), - user.getUserId(), Instant.now()); + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId1, rulesByDacId.get(0).id(), user.getUserId(), Instant.now()); - dacAutomationRuleDAO.auditedDeleteDACRuleSetting(dacId1, rulesByDacId.get(0).id(), - auditUser.getUserId()); - List auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId1, 5, 0); + dacAutomationRuleDAO.auditedDeleteDACRuleSetting( + dacId1, rulesByDacId.get(0).id(), auditUser.getUserId()); + List auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, 5, 0); Assertions.assertEquals(2, auditRecords.size()); - Assertions.assertEquals(auditRecords.size(), - dacAutomationRuleDAO.findCountOfAutomationAuditsForDac(dacId1)); - var remove = auditRecords.stream() - .filter(r -> r.action().equals(RuleAuditAction.REMOVE)) - .findFirst(); + Assertions.assertEquals( + auditRecords.size(), dacAutomationRuleDAO.findCountOfAutomationAuditsForDac(dacId1)); + var remove = + auditRecords.stream().filter(r -> r.action().equals(RuleAuditAction.REMOVE)).findFirst(); assertTrue(remove.isPresent()); assertEquals(remove.get().email(), auditUser.getEmail()); - var add = auditRecords.stream() - .filter(r -> r.action().equals(RuleAuditAction.ADD)) - .findFirst(); + var add = auditRecords.stream().filter(r -> r.action().equals(RuleAuditAction.ADD)).findFirst(); assertTrue(add.isPresent()); assertEquals(add.get().email(), user.getEmail()); } @@ -154,22 +152,22 @@ void testDeleteDACRuleSettingByUserId() { User user = createUser(); User auditUser = createUser(); Integer dacId = createRandomDAC(); - List rulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId); - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId, rulesByDacId.get(0).id(), - user.getUserId(), Instant.now()); - Integer deletedCount = dacAutomationRuleDAO.auditedDeleteDACRuleSettingByUser(dacId, - user.getUserId(), auditUser.getUserId()); + List rulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId); + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId, rulesByDacId.get(0).id(), user.getUserId(), Instant.now()); + Integer deletedCount = + dacAutomationRuleDAO.auditedDeleteDACRuleSettingByUser( + dacId, user.getUserId(), auditUser.getUserId()); Assertions.assertEquals(1, deletedCount); - List updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId); + List updatedRulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId); updatedRulesByDacId.forEach(r -> Assertions.assertNull(r.enabledByUserId())); - List auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId, 5, 0); + List auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId, 5, 0); Assertions.assertEquals(2, auditRecords.size()); - var remove = auditRecords.stream() - .filter(r -> r.action().equals(RuleAuditAction.REMOVE)) - .findFirst(); + var remove = + auditRecords.stream().filter(r -> r.action().equals(RuleAuditAction.REMOVE)).findFirst(); assertTrue(remove.isPresent()); assertEquals(remove.get().email(), auditUser.getEmail()); } @@ -180,24 +178,25 @@ void testDeleteDACRuleSetting() { Integer dacId1 = createRandomDAC(); Integer dacId2 = createRandomDAC(); List rulesByDacId = dacAutomationRuleDAO.findAll(); - rulesByDacId.forEach(r -> { - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId1, r.id(), user.getUserId(), - Instant.now()); - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId2, r.id(), user.getUserId(), - Instant.now()); - }); - Integer deletedCount = dacAutomationRuleDAO.auditedDeleteDACRuleSettingByUser(dacId1, - user.getUserId(), user.getUserId()); + rulesByDacId.forEach( + r -> { + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId1, r.id(), user.getUserId(), Instant.now()); + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId2, r.id(), user.getUserId(), Instant.now()); + }); + Integer deletedCount = + dacAutomationRuleDAO.auditedDeleteDACRuleSettingByUser( + dacId1, user.getUserId(), user.getUserId()); Assertions.assertEquals(rulesByDacId.size(), deletedCount); - Assertions.assertEquals(rulesByDacId.size() * 2, - dacAutomationRuleDAO.findCountOfAutomationAuditsForDac(dacId1)); - Assertions.assertEquals(rulesByDacId.size(), - dacAutomationRuleDAO.findCountOfAutomationAuditsForDac(dacId2)); - List updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId1); + Assertions.assertEquals( + rulesByDacId.size() * 2, dacAutomationRuleDAO.findCountOfAutomationAuditsForDac(dacId1)); + Assertions.assertEquals( + rulesByDacId.size(), dacAutomationRuleDAO.findCountOfAutomationAuditsForDac(dacId2)); + List updatedRulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId1); updatedRulesByDacId.forEach(r -> Assertions.assertNull(r.enabledByUserId())); - updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId2); + updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId2); updatedRulesByDacId.forEach(r -> Assertions.assertNotNull(r.enabledByUserId())); } @@ -208,13 +207,15 @@ void testAuditedDeleteDACRuleSettingByUser() { Integer dacId1 = createRandomDAC(); List rulesByDacId = dacAutomationRuleDAO.findAll(); rulesByDacId.forEach( - r -> dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId1, r.id(), user.getUserId(), - Instant.now())); - Integer deletedCount = dacAutomationRuleDAO.auditedDeleteDACRuleSettingByUser(dacId1, - user.getUserId(), auditUser.getUserId()); + r -> + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId1, r.id(), user.getUserId(), Instant.now())); + Integer deletedCount = + dacAutomationRuleDAO.auditedDeleteDACRuleSettingByUser( + dacId1, user.getUserId(), auditUser.getUserId()); Assertions.assertEquals(rulesByDacId.size(), deletedCount); - List deleteByUserAudits = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId1, rulesByDacId.size(), 0); + List deleteByUserAudits = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, rulesByDacId.size(), 0); Assertions.assertEquals(rulesByDacId.size(), deleteByUserAudits.size()); deleteByUserAudits.forEach(r -> Assertions.assertEquals(RuleAuditAction.REMOVE, r.action())); } @@ -225,21 +226,21 @@ void testDeleteAllSettingsByUserId() { Integer dacId1 = createRandomDAC(); Integer dacId2 = createRandomDAC(); List rulesByDacId = dacAutomationRuleDAO.findAll(); - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId1, rulesByDacId.get(0).id(), - user.getUserId(), Instant.now()); - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId2, rulesByDacId.get(0).id(), - user.getUserId(), Instant.now()); - Integer deletedCount = dacAutomationRuleDAO.auditedDeleteAllDACRuleSettingForUser( - user.getUserId(), user.getUserId()); + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId1, rulesByDacId.get(0).id(), user.getUserId(), Instant.now()); + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId2, rulesByDacId.get(0).id(), user.getUserId(), Instant.now()); + Integer deletedCount = + dacAutomationRuleDAO.auditedDeleteAllDACRuleSettingForUser( + user.getUserId(), user.getUserId()); Assertions.assertEquals(2, deletedCount); - List updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId1); + List updatedRulesByDacId = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId1); updatedRulesByDacId.forEach(r -> Assertions.assertNull(r.enabledByUserId())); - updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId2); + updatedRulesByDacId = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId2); updatedRulesByDacId.forEach(r -> Assertions.assertNull(r.enabledByUserId())); - List auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId1, rulesByDacId.size(), 0); + List auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, rulesByDacId.size(), 0); Assertions.assertEquals(2, auditRecords.size()); } @@ -249,22 +250,22 @@ void testDacAutomationRuleAudit() { Integer dacId1 = createRandomDAC(); List rulesByDacId = dacAutomationRuleDAO.findAll(); rulesByDacId.forEach( - r -> dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId1, r.id(), user.getUserId(), - Instant.now())); - List auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac( - dacId1, rulesByDacId.size(), 0); + r -> + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId1, r.id(), user.getUserId(), Instant.now())); + List auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, rulesByDacId.size(), 0); Assertions.assertEquals(rulesByDacId.size(), auditRecords.size()); - auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, rulesByDacId.size() - 1, - 0); + auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, rulesByDacId.size() - 1, 0); Assertions.assertEquals(rulesByDacId.size() - 1, auditRecords.size()); - auditRecords = dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, 1, - rulesByDacId.size() * 2); + auditRecords = + dacAutomationRuleDAO.findAutomationAuditsForDac(dacId1, 1, rulesByDacId.size() * 2); assertTrue(auditRecords.isEmpty()); } private Integer createRandomDAC() { - return dacDAO.createDac("Test_" + randomAlphabetic(20), "Test_" + randomAlphanumeric(20), - new Date()); + return dacDAO.createDac( + "Test_" + randomAlphabetic(20), "Test_" + randomAlphanumeric(20), new Date()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DAOTestHelper.java b/src/test/java/org/broadinstitute/consent/http/db/DAOTestHelper.java index 65f0c73783..3af490b954 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DAOTestHelper.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DAOTestHelper.java @@ -37,8 +37,8 @@ public class DAOTestHelper extends AbstractTestHelper implements TestExecutionLi public static final String POSTGRES_IMAGE = "postgres:16.10-alpine"; public static final String EMPTY_JSON_DOCUMENT = "{}"; private static final int maxConnections = 100; - private static final ConfigOverride maxConnectionsOverride = ConfigOverride.config( - "database.maxSize", String.valueOf(maxConnections)); + private static final ConfigOverride maxConnectionsOverride = + ConfigOverride.config("database.maxSize", String.valueOf(maxConnections)); protected static Jdbi jdbi; protected static CounterDAO counterDAO; protected static DacDAO dacDAO; @@ -89,43 +89,46 @@ public void testPlanExecutionStarted(TestPlan testPlan) { public void startUp() throws Exception { // Start the database - postgresContainer = new PostgreSQLContainer<>(POSTGRES_IMAGE). - withCommand("postgres -c max_connections=" + maxConnections). - waitingFor(Wait.forListeningPorts()); + postgresContainer = + new PostgreSQLContainer<>(POSTGRES_IMAGE) + .withCommand("postgres -c max_connections=" + maxConnections) + .waitingFor(Wait.forListeningPorts()); postgresContainer.start(); - ConfigOverride driverOverride = ConfigOverride.config("database.driverClass", - postgresContainer.getDriverClassName()); - ConfigOverride urlOverride = ConfigOverride.config("database.url", - postgresContainer.getJdbcUrl()); - ConfigOverride userOverride = ConfigOverride.config("database.user", - postgresContainer.getUsername()); - ConfigOverride passwordOverride = ConfigOverride.config("database.password", - postgresContainer.getPassword()); - ConfigOverride validationQueryOverride = ConfigOverride.config("database.validationQuery", - postgresContainer.getTestQueryString()); + ConfigOverride driverOverride = + ConfigOverride.config("database.driverClass", postgresContainer.getDriverClassName()); + ConfigOverride urlOverride = + ConfigOverride.config("database.url", postgresContainer.getJdbcUrl()); + ConfigOverride userOverride = + ConfigOverride.config("database.user", postgresContainer.getUsername()); + ConfigOverride passwordOverride = + ConfigOverride.config("database.password", postgresContainer.getPassword()); + ConfigOverride validationQueryOverride = + ConfigOverride.config("database.validationQuery", postgresContainer.getTestQueryString()); // Start the app - testApp = new DropwizardTestSupport<>( - ConsentApplication.class, - ResourceHelpers.resourceFilePath("consent-config.yml"), - driverOverride, urlOverride, - userOverride, passwordOverride, - validationQueryOverride, - maxConnectionsOverride); + testApp = + new DropwizardTestSupport<>( + ConsentApplication.class, + ResourceHelpers.resourceFilePath("consent-config.yml"), + driverOverride, + urlOverride, + userOverride, + passwordOverride, + validationQueryOverride, + maxConnectionsOverride); testApp.before(); // Initialize DAOs String dbiExtension = "_" + RandomStringUtils.secureStrong().nextAlphabetic(10); ConsentConfiguration configuration = testApp.getConfiguration(); Environment environment = testApp.getEnvironment(); - jdbi = new JdbiFactory().build(environment, configuration.getDataSourceFactory(), - DB_ENV + dbiExtension); + jdbi = + new JdbiFactory() + .build(environment, configuration.getDataSourceFactory(), DB_ENV + dbiExtension); jdbi.installPlugin(new SqlObjectPlugin()); jdbi.installPlugin(new Gson2Plugin()); jdbi.installPlugin(new GuavaPlugin()); - jdbi.getConfig().get(Gson2Config.class).setGson( - GsonUtil.buildGson() - ); + jdbi.getConfig().get(Gson2Config.class).setGson(GsonUtil.buildGson()); counterDAO = jdbi.onDemand(CounterDAO.class); dacDAO = jdbi.onDemand(DacDAO.class); @@ -157,11 +160,11 @@ void before() { testingDAO.truncateAllTables(); } - /* - Utility methods in this class need to be complete from the perspective of the - entity. When testing, if you need a specific modification to an object, call - dao methods directly to do any manipulation. - */ + /* + Utility methods in this class need to be complete from the perspective of the + entity. When testing, if you need a specific modification to an object, call + dao methods directly to do any manipulation. + */ /** * Creates a user with default role of Researcher and random user properties @@ -181,8 +184,8 @@ protected User createUser() { protected DataAccessRequest createDataAccessRequestV3() { User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 999999999); - Integer collection_id = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collection_id = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); for (int i = 0; i < 4; i++) { createDataAccessRequest(user.getUserId(), collection_id); } @@ -202,12 +205,7 @@ private DataAccessRequest createDataAccessRequest(Integer userId, Integer collec String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDataAccessRequest( - collectionId, - referenceId, - userId, - now, now, now, - data, - randomAlphabetic(10)); + collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -234,17 +232,19 @@ protected User createUserWithRole(Integer roleId, Integer institutionId) { protected User createUserWithInstitution() { User admin = createUserWithRole(UserRoles.ADMIN.getRoleId()); Integer adminId = admin.getUserId(); - Integer institutionId = institutionDAO.insertInstitution(randomAlphabetic(20), - "itDirectorName", - "itDirectorEmail", - randomAlphabetic(10), - new Random().nextInt(), - randomAlphabetic(10), - randomAlphabetic(10), - randomAlphabetic(10), - OrganizationType.NON_PROFIT.getValue(), - adminId, - new Date()); + Integer institutionId = + institutionDAO.insertInstitution( + randomAlphabetic(20), + "itDirectorName", + "itDirectorEmail", + randomAlphabetic(10), + new Random().nextInt(), + randomAlphabetic(10), + randomAlphabetic(10), + randomAlphabetic(10), + OrganizationType.NON_PROFIT.getValue(), + adminId, + new Date()); User user = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), institutionId); return userDAO.findUserById(user.getUserId()); } @@ -253,25 +253,34 @@ protected Institution getUserInstitution(User user) { return institutionDAO.findInstitutionById(user.getInstitutionId()); } - protected void updateVote(Boolean vote, String rationale, Date updateDate, Integer voteId, - boolean reminder, Integer electionId, Date createDate, Boolean hasConcerns) { - jdbi.useHandle(handle -> { - String sql = """ + protected void updateVote( + Boolean vote, + String rationale, + Date updateDate, + Integer voteId, + boolean reminder, + Integer electionId, + Date createDate, + Boolean hasConcerns) { + jdbi.useHandle( + handle -> { + String sql = + """ UPDATE vote SET vote = :vote, update_date = :updateDate, rationale = :rationale, reminder_sent = :reminderSent, create_date = :createDate, has_concerns = :hasConcerns WHERE vote_id = :voteId """; - handle.createUpdate(sql) - .bind("vote", vote) - .bind("rationale", rationale) - .bind("updateDate", updateDate) - .bind("voteId", voteId) - .bind("reminderSent", reminder) - .bind("electionId", electionId) - .bind("createDate", createDate) - .bind("hasConcerns", hasConcerns) - .execute(); - }); + handle + .createUpdate(sql) + .bind("vote", vote) + .bind("rationale", rationale) + .bind("updateDate", updateDate) + .bind("voteId", voteId) + .bind("reminderSent", reminder) + .bind("electionId", electionId) + .bind("createDate", createDate) + .bind("hasConcerns", hasConcerns) + .execute(); + }); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DaaDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DaaDAOTest.java index b74f4f4405..87850da0ef 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DaaDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DaaDAOTest.java @@ -34,18 +34,22 @@ private Integer createUserId() { @Test void testInsert() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); assertNotNull(daaId); } @Test void testInsertMultipleDaasOneDacId() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId3 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId3 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); assertNotNull(daaId1); assertNotNull(daaId2); assertNotNull(daaId3); @@ -60,8 +64,9 @@ void testInsertMultipleDaasOneDacId() { @Test void testFindAllOneDaa() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); assertNotNull(daaId); List daas = daaDAO.findAll(); assertNotNull(daas); @@ -71,10 +76,13 @@ void testFindAllOneDaa() { @Test void testFindAllMultipleDaas() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId3 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId3 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); assertNotNull(daaId1); assertNotNull(daaId2); assertNotNull(daaId3); @@ -93,9 +101,11 @@ void testFindAllNoDaas() { @Test void testFindById() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); assertNotNull(daaId1); assertNotNull(daaId2); DataAccessAgreement daa1 = daaDAO.findById(daaId1); @@ -115,10 +125,12 @@ void testFindByIdInvalid() { @Test void testFindByDacId() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); assertNotNull(daaId1); DataAccessAgreement daa1 = daaDAO.findByDacId(dacId); assertNotNull(daa1); @@ -133,8 +145,8 @@ void testFindByDacId() { @Test void testFindByDacIdInvalid() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); DataAccessAgreement daa1 = daaDAO.findByDacId(dacId); @@ -148,11 +160,13 @@ void testFindByDacIdInvalid() { @Test void testCreateDaaDacRelation() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer dacId3 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId3 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); assertNotNull(daaId1); DataAccessAgreement daa1 = daaDAO.findByDacId(dacId); assertNotNull(daa1); @@ -169,11 +183,13 @@ void testCreateDaaDacRelation() { @Test void testDeleteDaaDacRelation() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer dacId3 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId3 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); assertNotNull(daaId1); DataAccessAgreement daa1 = daaDAO.findByDacId(dacId); assertNotNull(daa1); @@ -193,17 +209,18 @@ void testDeleteDaaDacRelation() { @Test void testFindWithFileStorageObject() { Integer userId = createUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); - Integer fsoId = fileStorageObjectDAO.insertNewFile( - randomAlphabetic(10), - FileCategory.DATA_ACCESS_AGREEMENT.getValue(), - randomAlphabetic(10), - MediaType.TEXT_PLAIN_TYPE.getType(), - daaId.toString(), - userId, - Instant.now() - ); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer fsoId = + fileStorageObjectDAO.insertNewFile( + randomAlphabetic(10), + FileCategory.DATA_ACCESS_AGREEMENT.getValue(), + randomAlphabetic(10), + MediaType.TEXT_PLAIN_TYPE.getType(), + daaId.toString(), + userId, + Instant.now()); DataAccessAgreement daa = daaDAO.findById(daaId); assertNotNull(daa); assertNotNull(daa.getFile()); @@ -213,10 +230,14 @@ void testFindWithFileStorageObject() { @Test void testFindWithDacs() { Integer userId = createUser().getUserId(); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), "Dac 1", randomAlphabetic(15), new Date()); - Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), "Dac 2", randomAlphabetic(15), new Date()); - Integer dacId3 = dacDAO.createDac(randomAlphabetic(5), "Dac 3", randomAlphabetic(15), new Date()); - Integer daaId = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer dacId = + dacDAO.createDac(randomAlphabetic(5), "Dac 1", randomAlphabetic(15), new Date()); + Integer dacId2 = + dacDAO.createDac(randomAlphabetic(5), "Dac 2", randomAlphabetic(15), new Date()); + Integer dacId3 = + dacDAO.createDac(randomAlphabetic(5), "Dac 3", randomAlphabetic(15), new Date()); + Integer daaId = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); daaDAO.createDacDaaRelation(dacId, daaId); daaDAO.createDacDaaRelation(dacId2, daaId); daaDAO.createDacDaaRelation(dacId3, daaId); @@ -227,10 +248,11 @@ void testFindWithDacs() { assertEquals(3, daa.getDacs().size()); } - @Test + @Test void testFindDaaDatasetIdsByUserId() { // Testing the case of a user requesting DAR access to a dataset. - // That user must have an LC with a DAA associated to the same DAC that the dataset is associated to. + // That user must have an LC with a DAA associated to the same DAC that the dataset is + // associated to. User user = createUserWithInstitution(); LibraryCard lc = createRandomLibraryCard(user); Dac dac1 = createRandomDac(); @@ -264,8 +286,9 @@ void testFindDaaDatasetIdsByUserIdNullUser() { void testDeleteDaa() { Integer userId = createUserId(); User user = userDAO.findUserById(userId); - Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); LibraryCard lc = createRandomLibraryCard(user); DataAccessAgreement daa1 = daaDAO.findById(daaId1); @@ -288,25 +311,43 @@ void testFindByDarReferenceId() { User dataSubmitter = userDAO.findUserById(dataSubmitterId); // DAC/Dataset/DAA 1 - Integer dac1Id = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dac1Id = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); Dac dac1 = dacDAO.findById(dac1Id); - Integer daaId1 = daaDAO.createDaa(dataSubmitterId, new Date().toInstant(), dataSubmitterId, new Date().toInstant(), dac1Id); + Integer daaId1 = + daaDAO.createDaa( + dataSubmitterId, + new Date().toInstant(), + dataSubmitterId, + new Date().toInstant(), + dac1Id); daaDAO.createDacDaaRelation(dac1Id, daaId1); DataAccessAgreement daa1 = daaDAO.findById(daaId1); Dataset d1 = createRandomDataset(dataSubmitter, dac1); // Dac/Dataset/DAA 2 - Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); Dac dac2 = dacDAO.findById(dacId2); - Integer daaId2 = daaDAO.createDaa(dataSubmitterId, new Date().toInstant(), dataSubmitterId, new Date().toInstant(), dacId2); + Integer daaId2 = + daaDAO.createDaa( + dataSubmitterId, + new Date().toInstant(), + dataSubmitterId, + new Date().toInstant(), + dacId2); daaDAO.createDacDaaRelation(dacId2, daaId2); DataAccessAgreement daa2 = daaDAO.findById(daaId2); Dataset d2 = createRandomDataset(dataSubmitter, dac2); // Dac/Dataset/DAA 3 which should not be in the returned results - Integer dacId3 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); + Integer dacId3 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); Dac dac3 = dacDAO.findById(dacId3); - Integer daaId3 = daaDAO.createDaa(dataSubmitterId, new Date().toInstant(), dataSubmitterId, new Date().toInstant(), dacId3); + Integer daaId3 = + daaDAO.createDaa( + dataSubmitterId, + new Date().toInstant(), + dataSubmitterId, + new Date().toInstant(), + dacId3); daaDAO.createDacDaaRelation(dacId3, daaId3); DataAccessAgreement daa3 = daaDAO.findById(daaId3); createRandomDataset(dataSubmitter, dac3); @@ -326,42 +367,37 @@ void testFindByDarReferenceId() { } private LibraryCard createRandomLibraryCard(User user) { - int lcId = libraryCardDAO.insertLibraryCard( - user.getUserId(), - randomAlphabetic(5), - randomAlphabetic(5), - user.getUserId(), - new Date()); + int lcId = + libraryCardDAO.insertLibraryCard( + user.getUserId(), + randomAlphabetic(5), + randomAlphabetic(5), + user.getUserId(), + new Date()); return libraryCardDAO.findLibraryCardById(lcId); } private Dac createRandomDac() { - int dacId = dacDAO.createDac( - randomAlphabetic(5), - randomAlphabetic(5), - new Date()); + int dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), new Date()); return dacDAO.findById(dacId); } private DataAccessAgreement createRandomDataAccessAgreement(User user, Dac dac) { - int daaId = daaDAO.createDaa( - user.getUserId(), - Instant.now(), - user.getUserId(), - Instant.now(), - dac.getDacId()); + int daaId = + daaDAO.createDaa( + user.getUserId(), Instant.now(), user.getUserId(), Instant.now(), dac.getDacId()); return daaDAO.findById(daaId); } private Dataset createRandomDataset(User user, Dac dac) { - int datasetId = datasetDAO.insertDataset( - randomAlphabetic(5), - new Timestamp(Instant.now().getEpochSecond()), - user.getUserId(), - null, - new DataUseBuilder().setGeneralUse(true).build().toString(), - dac.getDacId()); + int datasetId = + datasetDAO.insertDataset( + randomAlphabetic(5), + new Timestamp(Instant.now().getEpochSecond()), + user.getUserId(), + null, + new DataUseBuilder().setGeneralUse(true).build().toString(), + dac.getDacId()); return datasetDAO.findDatasetById(datasetId); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DacDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DacDAOTest.java index d372c8d80b..1620872cd1 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DacDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DacDAOTest.java @@ -124,9 +124,14 @@ void testFindAllWithDataset() { Integer dacId1 = createRandomDAC(); Integer dacId2 = createRandomDAC(); User user = createUser(); - Integer datasetId = datasetDAO.insertDataset(randomAlphabetic(20), - new Timestamp(new Date().getTime()), user.getUserId(), randomAlphabetic(20), - new DataUseBuilder().setGeneralUse(true).build().toString(), dacId1); + Integer datasetId = + datasetDAO.insertDataset( + randomAlphabetic(20), + new Timestamp(new Date().getTime()), + user.getUserId(), + randomAlphabetic(20), + new DataUseBuilder().setGeneralUse(true).build().toString(), + dacId1); List list = new ArrayList<>(); DatasetProperty dsp = new DatasetProperty(); dsp.setDatasetId(datasetId); @@ -135,9 +140,14 @@ void testFindAllWithDataset() { dsp.setCreateDate(new Date()); list.add(dsp); datasetDAO.insertDatasetProperties(list); - Integer datasetId2 = datasetDAO.insertDataset(randomAlphabetic(20), - new Timestamp(new Date().getTime()), user.getUserId(), randomAlphabetic(20), - new DataUseBuilder().setGeneralUse(true).build().toString(), dacId2); + Integer datasetId2 = + datasetDAO.insertDataset( + randomAlphabetic(20), + new Timestamp(new Date().getTime()), + user.getUserId(), + randomAlphabetic(20), + new DataUseBuilder().setGeneralUse(true).build().toString(), + dacId2); List dacs = dacDAO.findAll(); @@ -159,21 +169,24 @@ void testFindAllWithDAAs() { User user = createUser(); Integer dacId1 = createRandomDAC(); - Integer daaId1 = daaDAO.createDaa(user.getUserId(), Instant.now(), user.getUserId(), - Instant.now(), dacId1); + Integer daaId1 = + daaDAO.createDaa(user.getUserId(), Instant.now(), user.getUserId(), Instant.now(), dacId1); createFSO(user.getUserId(), daaId1); daaDAO.createDacDaaRelation(dacId1, daaId1); Integer dacId2 = createRandomDAC(); - Integer daaId2 = daaDAO.createDaa(user.getUserId(), Instant.now(), user.getUserId(), - Instant.now(), dacId2); + Integer daaId2 = + daaDAO.createDaa(user.getUserId(), Instant.now(), user.getUserId(), Instant.now(), dacId2); createFSO(user.getUserId(), daaId2); daaDAO.createDacDaaRelation(dacId2, daaId2); - dacDAO.findAll().forEach(dac -> { - assertNotNull(dac.getAssociatedDaa()); - assertNotNull(dac.getAssociatedDaa().getFile()); - }); + dacDAO + .findAll() + .forEach( + dac -> { + assertNotNull(dac.getAssociatedDaa()); + assertNotNull(dac.getAssociatedDaa().getFile()); + }); } @Test @@ -188,8 +201,8 @@ void testFindByIdNoDaa() { void testFindByIdWithDaa() { Integer id = createRandomDAC(); User user = createUser(); - Integer daaId = daaDAO.createDaa(user.getUserId(), Instant.now(), user.getUserId(), - Instant.now(), id); + Integer daaId = + daaDAO.createDaa(user.getUserId(), Instant.now(), user.getUserId(), Instant.now(), id); DataAccessAgreement daa = daaDAO.findById(daaId); daaDAO.createDacDaaRelation(id, daaId); Dac dac = dacDAO.findById(id); @@ -305,7 +318,8 @@ void testAddDacMember() { dacDAO.addDacMember(roleId, user.getUserId(), dac.getDacId()); List memberRoles = userDAO.findUserById(user.getUserId()).getRoles(); assertFalse(memberRoles.isEmpty()); - UserRole userRole = memberRoles.stream().filter(r -> r.getRoleId().equals(roleId)).findFirst().orElseThrow(); + UserRole userRole = + memberRoles.stream().filter(r -> r.getRoleId().equals(roleId)).findFirst().orElseThrow(); assertEquals(userRole.getDacId(), dac.getDacId()); } @@ -317,7 +331,8 @@ void testAddDacChair() { dacDAO.addDacMember(roleId, user.getUserId(), dac.getDacId()); List chairRoles = userDAO.findUserById(user.getUserId()).getRoles(); assertFalse(chairRoles.isEmpty()); - UserRole userRole = chairRoles.stream().filter(r -> r.getRoleId().equals(roleId)).findFirst().orElseThrow(); + UserRole userRole = + chairRoles.stream().filter(r -> r.getRoleId().equals(roleId)).findFirst().orElseThrow(); assertEquals(userRole.getDacId(), dac.getDacId()); } @@ -339,19 +354,17 @@ void testRemoveDacMember() { @Test void testGetRoleById() { Role chair = dacDAO.getRoleById(UserRoles.CHAIRPERSON.getRoleId()); - assertEquals(chair.getName().toLowerCase(), - UserRoles.CHAIRPERSON.getRoleName().toLowerCase()); + assertEquals(chair.getName().toLowerCase(), UserRoles.CHAIRPERSON.getRoleName().toLowerCase()); Role member = dacDAO.getRoleById(UserRoles.MEMBER.getRoleId()); - assertEquals(member.getName().toLowerCase(), - UserRoles.MEMBER.getRoleName().toLowerCase()); + assertEquals(member.getName().toLowerCase(), UserRoles.MEMBER.getRoleName().toLowerCase()); } @Test void testFindUserRolesForUser() { Dac dac = insertDacWithEmail(); User chair = createUser(); // Creates a user with researcher role; UserRole #1 - dacDAO.addDacMember(UserRoles.CHAIRPERSON.getRoleId(), chair.getUserId(), - dac.getDacId()); // ; UserRole #2 + dacDAO.addDacMember( + UserRoles.CHAIRPERSON.getRoleId(), chair.getUserId(), dac.getDacId()); // ; UserRole #2 List userRoles = userDAO.findUserById(chair.getUserId()).getRoles(); assertEquals(2, userRoles.size()); } @@ -361,10 +374,10 @@ void testFindUserRolesForUsers() { Dac dac = insertDacWithEmail(); User chair = createUser(); // Creates a user with researcher role; UserRole #1 User member = createUser(); // Creates a user with researcher role; UserRole #2 - dacDAO.addDacMember(UserRoles.CHAIRPERSON.getRoleId(), chair.getUserId(), - dac.getDacId()); // ; UserRole #3 - dacDAO.addDacMember(UserRoles.MEMBER.getRoleId(), member.getUserId(), - dac.getDacId()); // ; UserRole #4 + dacDAO.addDacMember( + UserRoles.CHAIRPERSON.getRoleId(), chair.getUserId(), dac.getDacId()); // ; UserRole #3 + dacDAO.addDacMember( + UserRoles.MEMBER.getRoleId(), member.getUserId(), dac.getDacId()); // ; UserRole #4 List userIds = Arrays.asList(chair.getUserId(), member.getUserId()); List userRoles = dacDAO.findUserRolesForUsers(userIds).stream().distinct().toList(); assertEquals(4, userRoles.size()); @@ -393,14 +406,16 @@ void testFindDatasetsAssociatedWithDac_SuggestedDacId() { Dac dac = insertDacWithEmail(); Dataset datasetSuggestedDac = createDataset(); - datasetDAO.insertDatasetProperties(List.of(new DatasetProperty( - 1, - datasetSuggestedDac.getDatasetId(), - 1, - "dataAccessCommitteeId", - dac.getDacId().toString(), - PropertyType.Number, - Date.from(Instant.now())))); + datasetDAO.insertDatasetProperties( + List.of( + new DatasetProperty( + 1, + datasetSuggestedDac.getDatasetId(), + 1, + "dataAccessCommitteeId", + dac.getDacId().toString(), + PropertyType.Number, + Date.from(Instant.now())))); List results = datasetDAO.findDatasetsAssociatedWithDac(dac.getDacId()); assertEquals(1, results.size()); @@ -421,11 +436,9 @@ void testFindDacsForCollectionId() { private Dac insertDacWithEmail() { String testEmail = "test@email.com"; - Integer id = dacDAO.createDac( - "Test_" + randomAlphabetic(20), - "Test_" + randomAlphabetic(20), - testEmail, - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphabetic(20), "Test_" + randomAlphabetic(20), testEmail, new Date()); return dacDAO.findById(id); } @@ -437,8 +450,8 @@ private Dac createDac() { private DarCollection createDarCollection() { User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 10000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); Dataset dataset = createDataset(); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset.getDatasetId()); @@ -454,19 +467,11 @@ private DataAccessRequest createDataAccessRequest(Integer userId, Integer collec String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDataAccessRequest( - collectionId, - referenceId, - userId, - now, now, now, - data, - randomAlphabetic(10)); + collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } - private void createDataAccessRequestInCollectionWithDataset( - DarCollection collection, - Dataset d - ) { + private void createDataAccessRequestInCollectionWithDataset(DarCollection collection, Dataset d) { User user = createUser(); String randomUUID = UUID.randomUUID().toString(); dataAccessRequestDAO.insertDataAccessRequest( @@ -477,8 +482,7 @@ private void createDataAccessRequestInCollectionWithDataset( new Date(), new Date(), new DataAccessRequestData(), - user.getEraCommonsId() - ); + user.getEraCommonsId()); dataAccessRequestDAO.insertDARDatasetRelation(randomUUID, d.getDatasetId()); } @@ -488,8 +492,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphabetic(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), - null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -511,22 +515,18 @@ private Dataset createDatasetWithDac(Integer dacId) { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphabetic(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), dacId); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), dacId); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } private Integer createRandomDACWithName(String name) { - return dacDAO.createDac( - name, - "Test_" + randomAlphabetic(20), - new Date()); + return dacDAO.createDac(name, "Test_" + randomAlphabetic(20), new Date()); } private Integer createRandomDAC() { - return createRandomDACWithName( - "Test_" + randomAlphabetic(20)); + return createRandomDACWithName("Test_" + randomAlphabetic(20)); } private void createFSO(Integer userId, Integer daaId) { @@ -537,8 +537,6 @@ private void createFSO(Integer userId, Integer daaId) { MediaType.TEXT_PLAIN_TYPE.getType(), daaId.toString(), userId, - Instant.now() - ); - + Instant.now()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DarCollectionDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DarCollectionDAOTest.java index 41ce74170a..397816e63a 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DarCollectionDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DarCollectionDAOTest.java @@ -44,8 +44,11 @@ class DarCollectionDAOTest extends DAOTestHelper { private void generateDatasetElectionForCollection(DarCollection collection) { - DataAccessRequest dar = collection.getDars().values().stream() - .filter(d -> !d.getElections().isEmpty()).findFirst().orElseThrow(); + DataAccessRequest dar = + collection.getDars().values().stream() + .filter(d -> !d.getElections().isEmpty()) + .findFirst() + .orElseThrow(); String referenceId = dar.getReferenceId(); Election election = dar.getElections().values().stream().findFirst().orElse(null); assertNotNull(election); @@ -62,9 +65,7 @@ private List getElectionsFromCollection(DarCollection collection) { } private List getDatasetElectionsFromElection(List elections) { - return elections.stream() - .filter(e -> e.getElectionType().equalsIgnoreCase("dataset")) - .toList(); + return elections.stream().filter(e -> e.getElectionType().equalsIgnoreCase("dataset")).toList(); } @Test @@ -83,8 +84,7 @@ void testFindAllDARCollections() { assertFalse(elections.isEmpty()); List datasetElections = getDatasetElectionsFromElection(elections); assertEquals(0, datasetElections.size()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); } @Test @@ -95,36 +95,35 @@ void testFindAllDarCollectionsMultipleUserProperties() { assertEquals(1, allAfter.size()); List userProperties = allAfter.get(0).getCreateUser().getProperties(); assertFalse(userProperties.isEmpty()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); } @Test void testFindDARCollectionByReferenceId() { DataAccessRequest dar = createDataAccessRequestV3(); - DarCollection collection = darCollectionDAO.findDARCollectionByReferenceId( - dar.getReferenceId()); + DarCollection collection = + darCollectionDAO.findDARCollectionByReferenceId(dar.getReferenceId()); assertNotNull(collection); assertEquals(dar.getCollectionId(), collection.getDarCollectionId()); - List ids = collection.getDars().values().stream().map(DataAccessRequest::getReferenceId) - .toList(); + List ids = + collection.getDars().values().stream().map(DataAccessRequest::getReferenceId).toList(); assertTrue(ids.contains(dar.getReferenceId())); } @Test void testFindDARCollectionByReferenceIdNegative() { - //dar without a collection ID + // dar without a collection ID DataAccessRequest dar = createDraftDataAccessRequest(); - DarCollection collection = darCollectionDAO.findDARCollectionByReferenceId( - dar.getReferenceId()); + DarCollection collection = + darCollectionDAO.findDARCollectionByReferenceId(dar.getReferenceId()); assertNull(collection); } @Test void testFindDARCollectionByCollectionId() { DarCollection collection = createDarCollectionMultipleUserProperties(); - DarCollection returned = darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId()); + DarCollection returned = + darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId()); assertNotNull(returned); assertNotNull(returned.getMostRecentDar().getEraCommonsId()); assertEquals(collection.getDarCode(), returned.getDarCode()); @@ -144,8 +143,7 @@ void testFindDARCollectionByCollectionId() { List userProperties = returned.getCreateUser().getProperties(); assertFalse(userProperties.isEmpty()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); assertNull(returned.getCreateUser().getLibraryCard()); } @@ -153,8 +151,8 @@ void testFindDARCollectionByCollectionId() { @Test void testFindDARCollectionByCollectionIdMultipleUserProperties() { DarCollection collection = createDarCollectionMultipleUserProperties(); - DarCollection returned = darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId()); + DarCollection returned = + darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId()); assertNotNull(returned); List userProperties = returned.getCreateUser().getProperties(); @@ -169,8 +167,8 @@ void testFindDARCollectionByCollectionIdLibraryCard() { createLibraryCard(user); User updatedUser = userDAO.findUserById(user.getUserId()); String darCode = "DAR-" + randomInt(100, 1000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, updatedUser.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, updatedUser.getUserId(), new Date()); createDataAccessRequest(updatedUser.getUserId(), collectionId); DarCollection collection = darCollectionDAO.findDARCollectionByCollectionId(collectionId); @@ -184,8 +182,8 @@ void testFindDARCollectionByCollectionIdLibraryCard() { @Test void testFindDARCollectionByCollectionIdNegative() { - DarCollection returned = darCollectionDAO.findDARCollectionByCollectionId( - randomInt(1000, 2000)); + DarCollection returned = + darCollectionDAO.findDARCollectionByCollectionId(randomInt(1000, 2000)); assertNull(returned); } @@ -198,38 +196,44 @@ void testFindDarCollectionByIdWithSigningOfficial() { DataAccessRequest testDar2 = createDAR(user, dataset, testDar1.getCollectionId()); dataAccessRequestDAO.updateDarCloseoutSO(user.getUserId(), testDar2.getReferenceId()); - DataAccessRequest testDar2Stored = dataAccessRequestDAO.findByReferenceId( - testDar2.getReferenceId()); + DataAccessRequest testDar2Stored = + dataAccessRequestDAO.findByReferenceId(testDar2.getReferenceId()); assertNotNull(testDar2Stored.getCloseoutSigningOfficialApprovedUserId()); assertNotNull(testDar2Stored.getCloseoutSigningOfficialApprovedDate()); - DarCollection darCollection = darCollectionDAO.findDARCollectionByCollectionId( - testDar2.getCollectionId()); + DarCollection darCollection = + darCollectionDAO.findDARCollectionByCollectionId(testDar2.getCollectionId()); assertNotNull(darCollection.getMostRecentDar().getCloseoutSigningOfficialApprovedDate()); - assertEquals(user.getUserId(), + assertEquals( + user.getUserId(), darCollection.getMostRecentDar().getCloseoutSigningOfficialApprovedUserId()); - DarCollection darCollectionByReferenceId = darCollectionDAO.findDARCollectionByReferenceId( - testDar2.getReferenceId()); + DarCollection darCollectionByReferenceId = + darCollectionDAO.findDARCollectionByReferenceId(testDar2.getReferenceId()); assertNotNull( darCollectionByReferenceId.getMostRecentDar().getCloseoutSigningOfficialApprovedDate()); - assertEquals(user.getUserId(), + assertEquals( + user.getUserId(), darCollectionByReferenceId.getMostRecentDar().getCloseoutSigningOfficialApprovedUserId()); - DarCollection darCollectionWithElectionsById = darCollectionDAO.findCollectionWithAllElectionsByCollectionId( - testDar2.getCollectionId()); + DarCollection darCollectionWithElectionsById = + darCollectionDAO.findCollectionWithAllElectionsByCollectionId(testDar2.getCollectionId()); assertNotNull( darCollectionWithElectionsById.getMostRecentDar().getCloseoutSigningOfficialApprovedDate()); - assertEquals(user.getUserId(), darCollectionWithElectionsById.getMostRecentDar() - .getCloseoutSigningOfficialApprovedUserId()); + assertEquals( + user.getUserId(), + darCollectionWithElectionsById + .getMostRecentDar() + .getCloseoutSigningOfficialApprovedUserId()); - List darCollectionList = darCollectionDAO.findDARCollectionByCollectionIds( - List.of(testDar2.getCollectionId())); + List darCollectionList = + darCollectionDAO.findDARCollectionByCollectionIds(List.of(testDar2.getCollectionId())); assertEquals(1, darCollectionList.size()); assertNotNull( darCollectionList.get(0).getMostRecentDar().getCloseoutSigningOfficialApprovedDate()); - assertEquals(user.getUserId(), + assertEquals( + user.getUserId(), darCollectionList.get(0).getMostRecentDar().getCloseoutSigningOfficialApprovedUserId()); } @@ -239,17 +243,18 @@ void testFindCollectionWithAllElectionsByCollectionId() { // each election has one vote (final) // uses findDarCollectionById internally DarCollection collection = createDarCollectionMultipleUserProperties(); - DarCollection returned = darCollectionDAO.findCollectionWithAllElectionsByCollectionId( - collection.getDarCollectionId()); + DarCollection returned = + darCollectionDAO.findCollectionWithAllElectionsByCollectionId( + collection.getDarCollectionId()); assertNotNull(returned); // all values should be the same as the collection returned by findDarCollectionById // except the collection returned by findCollectionWithAllDataAccessElectionsById will include // both the created elections assertCollectionEqualExceptForElections(collection, returned); - List elections = getElectionsFromCollection(returned) - .stream() - .sorted(Comparator.comparing(Election::getCreateDate)) - .toList(); + List elections = + getElectionsFromCollection(returned).stream() + .sorted(Comparator.comparing(Election::getCreateDate)) + .toList(); assertEquals(2, elections.size()); Election firstElection = elections.get(0); assertExpectedElection(firstElection, ElectionStatus.CANCELED.getValue()); @@ -258,8 +263,7 @@ void testFindCollectionWithAllElectionsByCollectionId() { List userProperties = returned.getCreateUser().getProperties(); assertFalse(userProperties.isEmpty()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); assertNull(returned.getCreateUser().getLibraryCard()); } @@ -270,12 +274,12 @@ void testFindCollectionWithAllElectionsByCollectionIdLC() { createLibraryCard(user); User updatedUser = userDAO.findUserById(user.getUserId()); String darCode = "DAR-" + randomInt(100, 1000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, updatedUser.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, updatedUser.getUserId(), new Date()); createDataAccessRequest(updatedUser.getUserId(), collectionId); - DarCollection collection = darCollectionDAO.findCollectionWithAllElectionsByCollectionId( - collectionId); + DarCollection collection = + darCollectionDAO.findCollectionWithAllElectionsByCollectionId(collectionId); User returnedUser = collection.getCreateUser(); assertEquals(updatedUser, returnedUser); @@ -286,8 +290,8 @@ void testFindCollectionWithAllElectionsByCollectionIdLC() { @Test void testFindCollectionWithAllElectionsByCollectionIdNegative() { - DarCollection returned = darCollectionDAO.findCollectionWithAllElectionsByCollectionId( - randomInt(1000, 2000)); + DarCollection returned = + darCollectionDAO.findCollectionWithAllElectionsByCollectionId(randomInt(1000, 2000)); assertNull(returned); } @@ -298,20 +302,24 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetIds() { // each election has one vote (final) // uses findDarCollectionById internally DarCollection collection = createDarCollectionMultipleDatasetElections(); - List datasetIds = collection.getDatasets().stream() - .sorted(Comparator.comparing(Dataset::getDatasetId)) - .map(Dataset::getDatasetId).toList(); - DarCollection returnedAll = darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( - datasetIds, collection.getDarCollectionId()); + List datasetIds = + collection.getDatasets().stream() + .sorted(Comparator.comparing(Dataset::getDatasetId)) + .map(Dataset::getDatasetId) + .toList(); + DarCollection returnedAll = + darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetIds, collection.getDarCollectionId()); assertNotNull(returnedAll); // all values should be the same as the collection returned by findDarCollectionById - // except the collection returned by findCollectionWithDataAccessElectionsByCollectionIdAndDatasetIds will include + // except the collection returned by + // findCollectionWithDataAccessElectionsByCollectionIdAndDatasetIds will include // all the created elections for the specified datasets in the collection assertCollectionEqualExceptForElections(collection, returnedAll); - List elections = getElectionsFromCollection(returnedAll) - .stream() - .sorted(Comparator.comparing(Election::getCreateDate)) - .toList(); + List elections = + getElectionsFromCollection(returnedAll).stream() + .sorted(Comparator.comparing(Election::getCreateDate)) + .toList(); assertEquals(4, elections.size()); Election firstElection = elections.get(0); assertEquals(datasetIds.get(0), firstElection.getDatasetId()); @@ -328,8 +336,7 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetIds() { List userProperties = returnedAll.getCreateUser().getProperties(); assertFalse(userProperties.isEmpty()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); assertNull(returnedAll.getCreateUser().getLibraryCard()); } @@ -341,19 +348,21 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetIdsOneDataset() { // each election has one vote (final) // uses findDarCollectionById internally DarCollection collection = createDarCollectionMultipleDatasetElections(); - List datasetId = List.of(collection.getDatasets().stream() - .map(Dataset::getDatasetId).toList().get(0)); - DarCollection returnedAll = darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( - datasetId, collection.getDarCollectionId()); + List datasetId = + List.of(collection.getDatasets().stream().map(Dataset::getDatasetId).toList().get(0)); + DarCollection returnedAll = + darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetId, collection.getDarCollectionId()); assertNotNull(returnedAll); // all values should be the same as the collection returned by findDarCollectionById - // except the collection returned by findCollectionWithAllDataAccessElectionsByCollectionIdAndDatasetIds + // except the collection returned by + // findCollectionWithAllDataAccessElectionsByCollectionIdAndDatasetIds // will include all the created elections for the specified datasets in the collection assertCollectionEqualExceptForElections(collection, returnedAll); - List elections = getElectionsFromCollection(returnedAll) - .stream() - .sorted(Comparator.comparing(Election::getCreateDate)) - .toList(); + List elections = + getElectionsFromCollection(returnedAll).stream() + .sorted(Comparator.comparing(Election::getCreateDate)) + .toList(); assertEquals(2, elections.size()); Election firstElection = elections.get(0); assertEquals(datasetId.get(0), firstElection.getDatasetId()); @@ -364,8 +373,7 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetIdsOneDataset() { List userProperties = returnedAll.getCreateUser().getProperties(); assertFalse(userProperties.isEmpty()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); assertNull(returnedAll.getCreateUser().getLibraryCard()); } @@ -378,19 +386,20 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetIdsNoDataset() { // uses findDarCollectionById internally DarCollection collection = createDarCollectionMultipleDatasetElections(); List datasetIds = List.of(); - DarCollection returnedAll = darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( - datasetIds, collection.getDarCollectionId()); + DarCollection returnedAll = + darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetIds, collection.getDarCollectionId()); assertNotNull(returnedAll); // all values should be the same as the collection returned by findDarCollectionById - // except the collection returned by findCollectionWithDataAccessElectionsByCollectionIdAndDatasetIds will include + // except the collection returned by + // findCollectionWithDataAccessElectionsByCollectionIdAndDatasetIds will include // no elections because no dataset was specified assertCollectionEqualExceptForElections(collection, returnedAll); List elections = getElectionsFromCollection(returnedAll); assertEquals(0, elections.size()); List userProperties = returnedAll.getCreateUser().getProperties(); assertFalse(userProperties.isEmpty()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); assertNull(returnedAll.getCreateUser().getLibraryCard()); } @@ -403,19 +412,20 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetIdsOtherDataset() { // uses findDarCollectionById internally DarCollection collection = createDarCollectionMultipleDatasetElections(); List datasetIds = List.of(randomInt(1000, 2000)); - DarCollection returnedAll = darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( - datasetIds, collection.getDarCollectionId()); + DarCollection returnedAll = + darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetIds, collection.getDarCollectionId()); assertNotNull(returnedAll); // all values should be the same as the collection returned by findDarCollectionById - // except the collection returned by findCollectionWithDataAccessElectionsByCollectionIdAndDatasetIds will include + // except the collection returned by + // findCollectionWithDataAccessElectionsByCollectionIdAndDatasetIds will include // no elections since the specified dataset is not in the collection assertCollectionEqualExceptForElections(collection, returnedAll); List elections = getElectionsFromCollection(returnedAll); assertEquals(0, elections.size()); List userProperties = returnedAll.getCreateUser().getProperties(); assertFalse(userProperties.isEmpty()); - userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), - p.getUserId())); + userProperties.forEach(p -> assertEquals(collection.getCreateUserId(), p.getUserId())); assertNull(returnedAll.getCreateUser().getLibraryCard()); } @@ -426,11 +436,13 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetsLC() { createLibraryCard(user); User updatedUser = userDAO.findUserById(user.getUserId()); String darCode = "DAR-" + randomInt(100, 1000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, updatedUser.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, updatedUser.getUserId(), new Date()); createDataAccessRequest(updatedUser.getUserId(), collectionId); - DarCollection collection = darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds(List.of(), collectionId); + DarCollection collection = + darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + List.of(), collectionId); User returnedUser = collection.getCreateUser(); assertEquals(updatedUser, returnedUser); @@ -441,8 +453,9 @@ void testFindCollectionWithElectionsByCollectionIdAndDatasetsLC() { @Test void testFindCollectionWithElectionsByCollectionIdAndDatasetsNegative() { - DarCollection returned = darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds(List.of(1), - randomInt(1000, 2000)); + DarCollection returned = + darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + List.of(1), randomInt(1000, 2000)); assertNull(returned); } @@ -462,15 +475,15 @@ void testInsertDarCollectionNegative() { try { darCollectionDAO.insertDarCollection("darCode", 0, new Date()); } catch (Exception e) { - assertEquals(PSQLState.FOREIGN_KEY_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.FOREIGN_KEY_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } try { darCollectionDAO.insertDarCollection("darCode", userId, new Date()); darCollectionDAO.insertDarCollection("darCode", userId, new Date()); } catch (Exception e) { - assertEquals(PSQLState.UNIQUE_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.UNIQUE_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } } @@ -483,8 +496,8 @@ void testUpdateDARCollection() { User user = createUser(); Date date = new Date(); darCollectionDAO.updateDarCollection(collection.getDarCollectionId(), user.getUserId(), date); - DarCollection updated = darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId()); + DarCollection updated = + darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId()); assertEquals(user.getUserId(), updated.getUpdateUserId()); assertEquals(date, updated.getUpdateDate()); } @@ -495,15 +508,15 @@ void testUpdateDarCollectionNegative() { try { darCollectionDAO.updateDarCollection(0, userId, new Date()); } catch (Exception e) { - assertEquals(PSQLState.FOREIGN_KEY_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.FOREIGN_KEY_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } try { DarCollection collection = createDarCollection(); darCollectionDAO.updateDarCollection(collection.getDarCollectionId(), 0, new Date()); } catch (Exception e) { - assertEquals(PSQLState.FOREIGN_KEY_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.FOREIGN_KEY_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } } @@ -529,24 +542,23 @@ DataAccessRequest createDAR(User user, Dataset dataset, Integer collectionId) { testDar.getSubmissionDate(), testDar.getUpdateDate(), testDar.getData(), - user.getEraCommonsId() - ); + user.getEraCommonsId()); dataAccessRequestDAO.insertDARDatasetRelation(testDar.getReferenceId(), dataset.getDatasetId()); return testDar; } // local method to create a test DAC Dac createDAC() { - Integer id = dacDAO.createDac( - "Test_" + randomAlphanumeric(20), - "Test_" + randomAlphanumeric(20), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphanumeric(20), "Test_" + randomAlphanumeric(20), new Date()); return dacDAO.findById(id); } // local method to create a test DAR Collection and dataset // takes in user as a parameter so we can test multiple collections with the same user - // this method returns a list that includes: user, now, dataset, collectionId, testDar, dac, testDarCollection + // this method returns a list that includes: user, now, dataset, collectionId, testDar, dac, + // testDarCollection List createDarCollectionWithDataset(User user) { Timestamp now = new Timestamp(new Date().getTime()); String darCode = "DAR-" + randomAlphanumeric(25); @@ -559,8 +571,8 @@ List createDarCollectionWithDataset(User user) { // create a DAC Dac dac = createDAC(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); - DarCollection testDarCollection = darCollectionDAO.findDARCollectionByCollectionId( - collectionId); + DarCollection testDarCollection = + darCollectionDAO.findDARCollectionByCollectionId(collectionId); return List.of(user, now, dataset, collectionId, testDar, dac, testDarCollection); } @@ -578,13 +590,11 @@ void testFindDARCollectionIdsByCollectionIdsArchived() { dataAccessRequestDAO.archiveByReferenceIds(List.of(testDar1.getReferenceId())); - List collectionIds = List.of( - testDarCollection1.getDarCollectionId(), - testDarCollection2.getDarCollectionId() - ); + List collectionIds = + List.of(testDarCollection1.getDarCollectionId(), testDarCollection2.getDarCollectionId()); - List returnedCollections = darCollectionDAO.findDARCollectionByCollectionIds( - collectionIds); + List returnedCollections = + darCollectionDAO.findDARCollectionByCollectionIds(collectionIds); assertEquals(1, returnedCollections.size()); assertFalse(returnedCollections.contains(testDarCollection1)); @@ -625,10 +635,10 @@ void testFindDARCollectionByReferenceIdArchived() { dataAccessRequestDAO.archiveByReferenceIds(List.of(testDar1.getReferenceId())); - DarCollection archivedCollection = darCollectionDAO.findDARCollectionByReferenceId( - testDar1.getReferenceId()); - DarCollection validCollection = darCollectionDAO.findDARCollectionByReferenceId( - testDar2.getReferenceId()); + DarCollection archivedCollection = + darCollectionDAO.findDARCollectionByReferenceId(testDar1.getReferenceId()); + DarCollection validCollection = + darCollectionDAO.findDARCollectionByReferenceId(testDar2.getReferenceId()); assertNull(archivedCollection); assertEquals(validCollection, testDarCollection2); @@ -641,7 +651,8 @@ void testFindDARCollectionByReferenceIdIncludesERACommonsId() { user.setEraCommonsId(eraCommonsId); List newDarCollection1 = createDarCollectionWithDataset(user); DataAccessRequest testDar1 = (DataAccessRequest) newDarCollection1.get(4); - DarCollection testDarCollection = darCollectionDAO.findDARCollectionByReferenceId(testDar1.getReferenceId()); + DarCollection testDarCollection = + darCollectionDAO.findDARCollectionByReferenceId(testDar1.getReferenceId()); assertNotNull(testDarCollection.getMostRecentDar().getEraCommonsId()); } @@ -656,8 +667,8 @@ void testFindDARCollectionByCollectionIdArchived() { dataAccessRequestDAO.archiveByReferenceIds(List.of(testDar.getReferenceId())); - DarCollection returnedCollection = darCollectionDAO.findDARCollectionByCollectionId( - collectionId); + DarCollection returnedCollection = + darCollectionDAO.findDARCollectionByCollectionId(collectionId); assertNull(returnedCollection); } @@ -668,7 +679,8 @@ void testFindMostRecentDarInCollection() { DataAccessRequest testDar1 = (DataAccessRequest) newDarCollection1.get(4); Dataset dataset = (Dataset) newDarCollection1.get(2); DataAccessRequest testDar2 = createDAR(user, dataset, testDar1.getCollectionId()); - DarCollection returnedCollection = darCollectionDAO.findDARCollectionByCollectionId(testDar1.getCollectionId()); + DarCollection returnedCollection = + darCollectionDAO.findDARCollectionByCollectionId(testDar1.getCollectionId()); assertTrue(testDar2.getSubmissionDate().after(testDar1.getSubmissionDate())); assertNotEquals(testDar2.getReferenceId(), testDar1.getReferenceId()); assertEquals(testDar2.getReferenceId(), returnedCollection.getMostRecentDar().getReferenceId()); @@ -687,12 +699,7 @@ private DataAccessRequest createDataAccessRequest(Integer userId, Integer collec String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDataAccessRequest( - collectionId, - referenceId, - userId, - now, now, now, - data, - randomAlphabetic(10)); + collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -702,8 +709,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -720,8 +727,9 @@ private void createDatasetProperties(Integer datasetId) { } private LibraryCard createLibraryCard(User user) { - Integer id = libraryCardDAO.insertLibraryCard(user.getUserId(), - user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); + Integer id = + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); return libraryCardDAO.findLibraryCardById(id); } @@ -730,13 +738,13 @@ private DarCollection createDarCollectionMultipleUserProperties() { Integer userId = user.getUserId(); createUserProperty(userId, UserFields.ERA_STATUS.getValue()); String darCode = "DAR-" + randomInt(100, 1000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); Dataset dataset = createDataset(); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset.getDatasetId()); - Election cancelled = createCancelledAccessElection(dar.getReferenceId(), - dataset.getDatasetId()); + Election cancelled = + createCancelledAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Election access = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); createFinalVote(user.getUserId(), cancelled.getElectionId()); createFinalVote(user.getUserId(), access.getElectionId()); @@ -750,22 +758,22 @@ private DarCollection createDarCollectionMultipleDatasetElections() { Integer userId = user.getUserId(); createUserProperty(userId, UserFields.ERA_STATUS.getValue()); String darCode = "DAR-" + randomInt(100, 1000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset dataset1 = createDataset(); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset1.getDatasetId()); - Election cancelled1 = createCancelledAccessElection(dar.getReferenceId(), - dataset1.getDatasetId()); + Election cancelled1 = + createCancelledAccessElection(dar.getReferenceId(), dataset1.getDatasetId()); Election access1 = createDataAccessElection(dar.getReferenceId(), dataset1.getDatasetId()); createFinalVote(user.getUserId(), cancelled1.getElectionId()); createFinalVote(user.getUserId(), access1.getElectionId()); Dataset dataset2 = createDataset(); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset2.getDatasetId()); - Election cancelled2 = createCancelledAccessElection(dar.getReferenceId(), - dataset2.getDatasetId()); + Election cancelled2 = + createCancelledAccessElection(dar.getReferenceId(), dataset2.getDatasetId()); Election access2 = createDataAccessElection(dar.getReferenceId(), dataset2.getDatasetId()); createFinalVote(user.getUserId(), cancelled2.getElectionId()); createFinalVote(user.getUserId(), access2.getElectionId()); @@ -786,26 +794,26 @@ private void createUserProperty(Integer userId, String field) { } private Election createCancelledAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.CANCELED.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.CANCELED.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } private DarCollection createDarCollection() { User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 10000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); Dataset dataset = createDataset(); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset.getDatasetId()); - Election cancelled = createCancelledAccessElection(dar.getReferenceId(), - dataset.getDatasetId()); + Election cancelled = + createCancelledAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Election access = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); createFinalVote(user.getUserId(), cancelled.getElectionId()); createFinalVote(user.getUserId(), access.getElectionId()); @@ -821,12 +829,7 @@ private DataAccessRequest createDraftDataAccessRequest() { String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDraftDataAccessRequest( - referenceId, - user.getUserId(), - now, - now, - data - ); + referenceId, user.getUserId(), now, now, data); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -836,13 +839,13 @@ private void createFinalVote(Integer userId, Integer electionId) { } private Election createDataAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } @@ -862,7 +865,8 @@ private void assertExpectedElection(Election e, String status) { assertEquals(vote.getElectionId(), e.getElectionId()); } - private void assertCollectionEqualExceptForElections(DarCollection collection, DarCollection returned) { + private void assertCollectionEqualExceptForElections( + DarCollection collection, DarCollection returned) { DarCollection collectionCopy = collection.deepCopy(); collectionCopy.getDars().values().forEach(dar -> dar.setElections(new HashMap<>())); DarCollection returnedCopy = returned.deepCopy(); diff --git a/src/test/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAOTest.java index 09a33dbaa5..773259b219 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DarCollectionSummaryDAOTest.java @@ -43,8 +43,15 @@ private DataAccessRequest createDataAccessRequest(Integer collectionId, Integer DataAccessRequestData data = new DataAccessRequestData(); data.setProjectTitle(randomAlphabetic(20)); data.setStatus("test"); - dataAccessRequestDAO.insertDataAccessRequest(collectionId, referenceId, userId, createDate, - submissionDate, new Date(), data, randomAlphabetic(10)); + dataAccessRequestDAO.insertDataAccessRequest( + collectionId, + referenceId, + userId, + createDate, + submissionDate, + new Date(), + data, + randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -70,24 +77,33 @@ private Integer createDarCollection(Integer createUserId) { } private Dataset createDataset(Integer userId) { - Integer datasetId = datasetDAO.insertDataset(randomAlphabetic(20), - new Timestamp(System.currentTimeMillis()), userId, null, - new DataUseBuilder().setGeneralUse(true).build().toString(), null); + Integer datasetId = + datasetDAO.insertDataset( + randomAlphabetic(20), + new Timestamp(System.currentTimeMillis()), + userId, + null, + new DataUseBuilder().setGeneralUse(true).build().toString(), + null); return datasetDAO.findDatasetById(datasetId); } private Dataset createDatasetWithDac(Integer userId, Integer dacId) { - Integer datasetId = datasetDAO.insertDataset(randomAlphabetic(20), - new Timestamp(System.currentTimeMillis()), userId, null, - new DataUseBuilder().setGeneralUse(true).build().toString(), dacId); + Integer datasetId = + datasetDAO.insertDataset( + randomAlphabetic(20), + new Timestamp(System.currentTimeMillis()), + userId, + null, + new DataUseBuilder().setGeneralUse(true).build().toString(), + dacId); return datasetDAO.findDatasetById(datasetId); } private Dac createDac() { - Integer id = dacDAO.createDac( - "Test_" + randomAlphanumeric(20), - "Test_" + randomAlphanumeric(20), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphanumeric(20), "Test_" + randomAlphanumeric(20), new Date()); return dacDAO.findById(id); } @@ -103,8 +119,8 @@ private Vote createVote(Integer dacUserId, Integer electionId, String type) { return voteDAO.findVoteById(voteId); } - - private Election createElectionWithVotes(User userChair, Integer userId, String darReferenceId, Integer datasetId) { + private Election createElectionWithVotes( + User userChair, Integer userId, String darReferenceId, Integer datasetId) { User userTwo = createUser(); Integer userTwoId = userTwo.getUserId(); Integer userChairId = userChair.getUserId(); @@ -114,12 +130,12 @@ private Election createElectionWithVotes(User userChair, Integer userId, String Vote voteTwo = createVote(userTwoId, electionId, VoteType.DAC.getValue()); Vote voteThree = createVote(userChairId, electionId, VoteType.DAC.getValue()); Vote voteFinal = createVote(userChairId, electionId, VoteType.FINAL.getValue()); - election.setVotes(Map.of( - voteOne.getVoteId(), voteOne, - voteTwo.getVoteId(), voteTwo, - voteThree.getVoteId(), voteThree, - voteFinal.getVoteId(), voteFinal - )); + election.setVotes( + Map.of( + voteOne.getVoteId(), voteOne, + voteTwo.getVoteId(), voteTwo, + voteThree.getVoteId(), voteThree, + voteFinal.getVoteId(), voteFinal)); return election; } @@ -137,8 +153,8 @@ void testGetDarCollectionSummaryForDAC() { Dataset datasetTwo = createDataset(userTwoId); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); datasetDAO.updateDatasetDacId(datasetTwo.getDatasetId(), dac.getDacId()); - Dataset excludedDataset = createDataset( - userOneId); //represents dataset that does not fall under user DAC's purview + Dataset excludedDataset = + createDataset(userOneId); // represents dataset that does not fall under user DAC's purview Integer collectionOneId = createDarCollection(userOneId); Integer collectionTwoId = createDarCollection(userTwoId); Integer excludedDarCollectionId = createDarCollection(userOneId); @@ -147,18 +163,17 @@ void testGetDarCollectionSummaryForDAC() { DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(excludedDar.getReferenceId(), - excludedDataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + excludedDar.getReferenceId(), excludedDataset.getDatasetId()); Election collectionOnePrevElection = createElection( ElectionStatus.CANCELED.getValue(), darOne.getReferenceId(), - dataset - .getDatasetId()); // non-latest dataset, need to make sure this isn't pulled into - // query results + dataset.getDatasetId()); // non-latest dataset, need to make sure this isn't pulled into + // query results Election collectionOneElection = createElection( ElectionStatus.OPEN.getValue(), darOne.getReferenceId(), dataset.getDatasetId()); @@ -176,32 +191,33 @@ void testGetDarCollectionSummaryForDAC() { Integer collectionTwoElectionId = collectionTwoElection.getElectionId(); Integer excludedElectionId = excludedElection.getElectionId(); - //create old votes to ensure that they don't get pulled in by the query + // create old votes to ensure that they don't get pulled in by the query createVote(userOneId, collectionOnePrevElectionId, VoteType.DAC.getValue()); createVote(userTwoId, collectionOnePrevElectionId, VoteType.DAC.getValue()); createVote(userChairId, collectionOnePrevElectionId, VoteType.DAC.getValue()); createVote(userChairId, collectionOnePrevElectionId, VoteType.CHAIRPERSON.getValue()); - //create votes for dataset that should NOT be pulled by the query (tied to excluded dataset) + // create votes for dataset that should NOT be pulled by the query (tied to excluded dataset) createVote(userOneId, excludedElectionId, VoteType.DAC.getValue()); createVote(userOneId, collectionOneElectionId, VoteType.DAC.getValue()); createVote(userTwoId, collectionOneElectionId, VoteType.DAC.getValue()); - Vote collectionOneVoteThree = createVote(userChairId, collectionOneElectionId, - VoteType.DAC.getValue()); - Vote collectionOneVoteChair = createVote(userChairId, collectionOneElectionId, - VoteType.CHAIRPERSON.getValue()); + Vote collectionOneVoteThree = + createVote(userChairId, collectionOneElectionId, VoteType.DAC.getValue()); + Vote collectionOneVoteChair = + createVote(userChairId, collectionOneElectionId, VoteType.CHAIRPERSON.getValue()); createVote(userOneId, collectionTwoElectionId, VoteType.DAC.getValue()); createVote(userTwoId, collectionTwoElectionId, VoteType.DAC.getValue()); - Vote collectionTwoVoteThree = createVote(userChairId, collectionTwoElectionId, - VoteType.DAC.getValue()); - Vote collectionTwoVoteChair = createVote(userChairId, collectionTwoElectionId, - VoteType.CHAIRPERSON.getValue()); + Vote collectionTwoVoteThree = + createVote(userChairId, collectionTwoElectionId, VoteType.DAC.getValue()); + Vote collectionTwoVoteChair = + createVote(userChairId, collectionTwoElectionId, VoteType.CHAIRPERSON.getValue()); List targetDatasets = List.of(dataset.getDatasetId(), datasetTwo.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( - userChairId, UserRoles.CHAIRPERSON.getRoleId()); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + userChairId, UserRoles.CHAIRPERSON.getRoleId()); assertNotNull(summaries); assertEquals(2, summaries.size()); @@ -249,8 +265,8 @@ void testGetDarCollectionSummaryForDAC_NoElectionsPresent() { DataAccessRequest darOne = createDataAccessRequest(collectionOneId, userOneId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(excludedDar.getReferenceId(), - excludedDataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + excludedDar.getReferenceId(), excludedDataset.getDatasetId()); Election excludedElection = createElection( @@ -263,26 +279,26 @@ void testGetDarCollectionSummaryForDAC_NoElectionsPresent() { createVote(userOneId, excludedElectionId, VoteType.DAC.getValue()); List targetDatasets = List.of(dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( - userChairId, - UserRoles.CHAIRPERSON.getRoleId()); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + userChairId, UserRoles.CHAIRPERSON.getRoleId()); assertNotNull(summaries); assertEquals(1, summaries.size()); - summaries.forEach(s -> { - assertEquals(1, s.getDatasetIds().size()); - s.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); - assertFalse(s.isExpired()); - assertTrue(s.getExpiresAt().after(new Date())); - assertEquals(0, s.getElections().size()); - assertEquals(0, s.getVotes().size()); - assertEquals(1, s.getDatasetCount()); - - assertNotNull(s.getDacNames()); - assertEquals(1, s.getDacNames().size()); - assertTrue(s.getDacNames().contains(dac.getName())); - }); + summaries.forEach( + s -> { + assertEquals(1, s.getDatasetIds().size()); + s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); + assertFalse(s.isExpired()); + assertTrue(s.getExpiresAt().after(new Date())); + assertEquals(0, s.getElections().size()); + assertEquals(0, s.getVotes().size()); + assertEquals(1, s.getDatasetCount()); + + assertNotNull(s.getDacNames()); + assertEquals(1, s.getDacNames().size()); + assertTrue(s.getDacNames().contains(dac.getName())); + }); } @Test @@ -300,13 +316,14 @@ void testGetDarCollectionSummaryForDAC_ArchivedCollection() { dataAccessRequestDAO.archiveByReferenceIds(List.of(archivedDar.getReferenceId())); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(archivedDar.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + archivedDar.getReferenceId(), dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( - userOneId, UserRoles.CHAIRPERSON.getRoleId()); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + userOneId, UserRoles.CHAIRPERSON.getRoleId()); - //test that only the non-archived collection was pulled by the query + // test that only the non-archived collection was pulled by the query assertNotNull(summaries); assertEquals(1, summaries.size()); assertEquals(collectionOneId, summaries.get(0).getDarCollectionId()); @@ -337,8 +354,8 @@ void testGetDarCollectionSummaryForSO() { dataAccessRequestDAO.updateDarCloseoutSO(userOneId, darTwo.getReferenceId()); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); createElection( ElectionStatus.CLOSED.getValue(), darOne.getReferenceId(), dataset.getDatasetId()); @@ -349,25 +366,26 @@ void testGetDarCollectionSummaryForSO() { ElectionStatus.OPEN.getValue(), darTwo.getReferenceId(), datasetTwo.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForSO( - institutionId); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForSO(institutionId); assertNotNull(summaries); assertEquals(1, summaries.size()); - summaries.forEach(s -> { - assertEquals(1, s.getDatasetIds().size()); - s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); - - assertNotNull(s.getDacNames()); - assertEquals(1, s.getDacNames().size()); - assertTrue(s.getDacNames().contains(dacOneName)); - - Integer electionId = collectionOneElection.getElectionId(); - s.getElections().forEach((key, value) -> assertEquals(electionId, key)); - assertEquals(1, s.getDatasetCount()); - assertEquals(userOneId, s.getCloseoutSigningOfficialApprovalId()); - assertNotNull(s.getCloseoutSigningOfficialApprovalDate()); - }); + summaries.forEach( + s -> { + assertEquals(1, s.getDatasetIds().size()); + s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); + + assertNotNull(s.getDacNames()); + assertEquals(1, s.getDacNames().size()); + assertTrue(s.getDacNames().contains(dacOneName)); + + Integer electionId = collectionOneElection.getElectionId(); + s.getElections().forEach((key, value) -> assertEquals(electionId, key)); + assertEquals(1, s.getDatasetCount()); + assertEquals(userOneId, s.getCloseoutSigningOfficialApprovalId()); + assertNotNull(s.getCloseoutSigningOfficialApprovalDate()); + }); } @Test @@ -386,22 +404,23 @@ void testGetDarCollectionSummaryForSO_NoElectionsPresent() { dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForSO( - institutionId); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForSO(institutionId); assertNotNull(summaries); assertEquals(1, summaries.size()); - summaries.forEach(s -> { - assertEquals(1, s.getDatasetIds().size()); - s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); + summaries.forEach( + s -> { + assertEquals(1, s.getDatasetIds().size()); + s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); - assertNotNull(s.getDacNames()); - assertEquals(1, s.getDacNames().size()); - assertTrue(s.getDacNames().contains(dacOneName)); + assertNotNull(s.getDacNames()); + assertEquals(1, s.getDacNames().size()); + assertTrue(s.getDacNames().contains(dacOneName)); - assertEquals(0, s.getElections().size()); - assertEquals(1, s.getDatasetCount()); - }); + assertEquals(0, s.getElections().size()); + assertEquals(1, s.getDatasetCount()); + }); } @Test @@ -418,13 +437,13 @@ void testGetDarCollectionSummaryForSO_ArchivedCollection() { dataAccessRequestDAO.archiveByReferenceIds(List.of(archivedDar.getReferenceId())); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(archivedDar.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + archivedDar.getReferenceId(), dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForSO( - institutionId); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForSO(institutionId); - //test that only the non-archived collection was pulled by the query + // test that only the non-archived collection was pulled by the query assertNotNull(summaries); assertEquals(1, summaries.size()); assertEquals(collectionOneId, summaries.get(0).getDarCollectionId()); @@ -448,8 +467,8 @@ void testGetDarCollectionSummaryForResearcher() { DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); createElection( ElectionStatus.CLOSED.getValue(), darOne.getReferenceId(), dataset.getDatasetId()); @@ -460,26 +479,26 @@ void testGetDarCollectionSummaryForResearcher() { ElectionStatus.OPEN.getValue(), darTwo.getReferenceId(), datasetTwo.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForResearcher( - userOneId); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userOneId); assertNotNull(summaries); assertEquals(1, summaries.size()); - summaries.forEach(s -> { - assertEquals(1, s.getDatasetIds().size()); - s.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); - - assertNotNull(s.getDacNames()); - assertEquals(1, s.getDacNames().size()); - assertTrue(s.getDacNames().contains(dacOneName)); - - Integer electionId = collectionOneElection.getElectionId(); - s.getElections().forEach((key, value) -> assertEquals(electionId, key)); - assertEquals(1, s.getDarStatuses().size()); - s.getDarStatuses().values().forEach(status -> assertEquals("test", status)); - assertEquals(1, s.getDatasetCount()); - }); + summaries.forEach( + s -> { + assertEquals(1, s.getDatasetIds().size()); + s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); + + assertNotNull(s.getDacNames()); + assertEquals(1, s.getDacNames().size()); + assertTrue(s.getDacNames().contains(dacOneName)); + + Integer electionId = collectionOneElection.getElectionId(); + s.getElections().forEach((key, value) -> assertEquals(electionId, key)); + assertEquals(1, s.getDarStatuses().size()); + s.getDarStatuses().values().forEach(status -> assertEquals("test", status)); + assertEquals(1, s.getDatasetCount()); + }); } @Test @@ -501,28 +520,28 @@ void testGetDarCollectionSummaryForResearcher_NoElectionsPresent() { DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); createElection( ElectionStatus.OPEN.getValue(), darTwo.getReferenceId(), datasetTwo.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForResearcher( - userOneId); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userOneId); assertNotNull(summaries); assertEquals(1, summaries.size()); - summaries.forEach(s -> { - assertEquals(1, s.getDatasetIds().size()); - s.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); - assertEquals(0, s.getElections().size()); - assertEquals(1, s.getDatasetCount()); - assertNotNull(s.getDacNames()); - assertEquals(1, s.getDacNames().size()); - assertTrue(s.getDacNames().contains(dacOneName)); - }); + summaries.forEach( + s -> { + assertEquals(1, s.getDatasetIds().size()); + s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); + assertEquals(0, s.getElections().size()); + assertEquals(1, s.getDatasetCount()); + assertNotNull(s.getDacNames()); + assertEquals(1, s.getDacNames().size()); + assertTrue(s.getDacNames().contains(dacOneName)); + }); } @Test @@ -537,13 +556,13 @@ void testGetDarCollectionSummaryForResearcher_ArchivedCollection() { dataAccessRequestDAO.archiveByReferenceIds(List.of(archivedDar.getReferenceId())); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(archivedDar.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + archivedDar.getReferenceId(), dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForResearcher( - userOneId); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userOneId); - //test that only the non-archived collection was pulled by the query + // test that only the non-archived collection was pulled by the query assertNotNull(summaries); assertEquals(1, summaries.size()); assertEquals(collectionOneId, summaries.get(0).getDarCollectionId()); @@ -559,14 +578,18 @@ void testGetDarCollectionSummaryForResearcher_DraftedDarCollection() { DataAccessRequest dar = createDataAccessRequest(collectionId, userId); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.updateDataByReferenceId(dar.getReferenceId(), dar.userId, null, - new Date(), dar.getData(), randomAlphabetic(10)); // draft DAR + dataAccessRequestDAO.updateDataByReferenceId( + dar.getReferenceId(), + dar.userId, + null, + new Date(), + dar.getData(), + randomAlphabetic(10)); // draft DAR - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForResearcher( - userId); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); assertEquals(0, summaries.size()); - } @Test @@ -590,8 +613,8 @@ void testGetDarCollectionSummaryForAdmin() { DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); createElection( ElectionStatus.CLOSED.getValue(), darOne.getReferenceId(), dataset.getDatasetId()); @@ -604,28 +627,29 @@ void testGetDarCollectionSummaryForAdmin() { List targetDatasets = List.of(dataset.getDatasetId(), datasetTwo.getDatasetId()); List targetDatasetDacNames = List.of(dacOneName, dacTwoName); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); assertNotNull(summaries); assertEquals(2, summaries.size()); - summaries.forEach(s -> { - assertEquals(1, s.getDatasetIds().size()); - s.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); + summaries.forEach( + s -> { + assertEquals(1, s.getDatasetIds().size()); + s.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); - assertEquals(1, s.getDacNames().size()); - s.getDacNames().forEach(dacName -> assertTrue(targetDatasetDacNames.contains(dacName))); + assertEquals(1, s.getDacNames().size()); + s.getDacNames().forEach(dacName -> assertTrue(targetDatasetDacNames.contains(dacName))); - Integer electionId; + Integer electionId; - if (Objects.equals(s.getDarCollectionId(), collectionOneId)) { - electionId = collectionOneElection.getElectionId(); - } else { - electionId = collectionTwoElection.getElectionId(); - } + if (Objects.equals(s.getDarCollectionId(), collectionOneId)) { + electionId = collectionOneElection.getElectionId(); + } else { + electionId = collectionTwoElection.getElectionId(); + } - s.getElections().forEach((key, value) -> assertEquals(electionId, key)); - assertEquals(1, s.getDatasetCount()); - }); + s.getElections().forEach((key, value) -> assertEquals(electionId, key)); + assertEquals(1, s.getDatasetCount()); + }); } @Test @@ -649,12 +673,13 @@ void testGetDarCollectionSummaryForAdmin_NoPresentElections() { DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId(), datasetTwo.getDatasetId()); List targetDatasetDacNames = List.of(dacOneName, dacTwoName); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); assertNotNull(summaries); assertEquals(2, summaries.size()); summaries.forEach( @@ -684,19 +709,20 @@ void testGetDarCollectionSummaryForAdmin_ArchivedCollection() { dataAccessRequestDAO.archiveByReferenceIds(List.of(archivedDar.getReferenceId())); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(archivedDar.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + archivedDar.getReferenceId(), dataset.getDatasetId()); - List summaries = darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); + List summaries = + darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); - //test that only the non-archived collection was pulled by the query + // test that only the non-archived collection was pulled by the query assertNotNull(summaries); assertEquals(1, summaries.size()); assertEquals(collectionOneId, summaries.get(0).getDarCollectionId()); } @ParameterizedTest - @ValueSource(strings= {"admin", "researcher", "SO", "DAC", "dacCollectionId", "collectionId"}) + @ValueSource(strings = {"admin", "researcher", "SO", "DAC", "dacCollectionId", "collectionId"}) void testGetDarCollectionSummaryArchivedNotIncluded(String type) { User user = createUserWithInstitution(); Integer userId = user.getUserId(); @@ -710,8 +736,10 @@ void testGetDarCollectionSummaryArchivedNotIncluded(String type) { DataAccessRequest archivedDar = createProgressReportFromDAR(olderDar); // Insert dataset relations for all DARs - dataAccessRequestDAO.insertDARDatasetRelation(olderDar.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(archivedDar.getReferenceId(), dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + olderDar.getReferenceId(), dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + archivedDar.getReferenceId(), dataset.getDatasetId()); // archived DAR dataAccessRequestDAO.archiveByReferenceIds(List.of(archivedDar.getReferenceId())); @@ -721,15 +749,24 @@ void testGetDarCollectionSummaryArchivedNotIncluded(String type) { User chair = createUserWithRoleInDac(UserRoles.CHAIRPERSON.getRoleId(), dac.getDacId()); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); - List summaries = switch (type) { - case "admin" -> darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); - case "researcher" -> darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); - case "SO" -> darCollectionSummaryDAO.getDarCollectionSummariesForSO(user.getInstitutionId()); - case "DAC" -> darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(chair.getUserId(), UserRoles.CHAIRPERSON.getRoleId()); - case "dacCollectionId" -> List.of(darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(userId, List.of(dataset.getDatasetId()), collectionId)); - case "collectionId" -> List.of(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)); - default -> throw new IllegalArgumentException("Invalid type: " + type); - }; + List summaries = + switch (type) { + case "admin" -> darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); + case "researcher" -> + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); + case "SO" -> + darCollectionSummaryDAO.getDarCollectionSummariesForSO(user.getInstitutionId()); + case "DAC" -> + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + chair.getUserId(), UserRoles.CHAIRPERSON.getRoleId()); + case "dacCollectionId" -> + List.of( + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userId, List.of(dataset.getDatasetId()), collectionId)); + case "collectionId" -> + List.of(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)); + default -> throw new IllegalArgumentException("Invalid type: " + type); + }; assertNotNull(summaries); assertEquals(1, summaries.size()); @@ -747,7 +784,7 @@ void testGetDarCollectionSummaryArchivedNotIncluded(String type) { } @ParameterizedTest - @ValueSource(strings= {"admin", "researcher", "SO", "DAC", "dacCollectionId", "collectionId"}) + @ValueSource(strings = {"admin", "researcher", "SO", "DAC", "dacCollectionId", "collectionId"}) void testGetDarCollectionSummaryTwoDataAccessRequests(String type) { User user = createUserWithInstitution(); Integer userId = user.getUserId(); @@ -763,9 +800,12 @@ void testGetDarCollectionSummaryTwoDataAccessRequests(String type) { // Insert dataset relations for both DARs // the older DAR has two datasets and the newer DAR has one - dataAccessRequestDAO.insertDARDatasetRelation(olderDar.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(olderDar.getReferenceId(), dataset1.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(newerDar.getReferenceId(), dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + olderDar.getReferenceId(), dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + olderDar.getReferenceId(), dataset1.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + newerDar.getReferenceId(), dataset.getDatasetId()); // Create an election for the older DAR createElection( @@ -777,16 +817,26 @@ void testGetDarCollectionSummaryTwoDataAccessRequests(String type) { datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); datasetDAO.updateDatasetDacId(dataset1.getDatasetId(), dac.getDacId()); - List summaries = switch (type) { - case "admin" -> darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); - case "researcher" -> - darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); - case "SO" -> darCollectionSummaryDAO.getDarCollectionSummariesForSO(user.getInstitutionId()); - case "DAC" -> darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(chair.getUserId(), UserRoles.CHAIRPERSON.getRoleId()); - case "dacCollectionId" -> List.of(darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(userId, List.of(dataset.getDatasetId(), dataset1.getDatasetId()), collectionId)); - case "collectionId" -> List.of(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)); - default -> throw new IllegalArgumentException("Invalid type: " + type); - }; + List summaries = + switch (type) { + case "admin" -> darCollectionSummaryDAO.getDarCollectionSummariesForAdmin(); + case "researcher" -> + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); + case "SO" -> + darCollectionSummaryDAO.getDarCollectionSummariesForSO(user.getInstitutionId()); + case "DAC" -> + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + chair.getUserId(), UserRoles.CHAIRPERSON.getRoleId()); + case "dacCollectionId" -> + List.of( + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userId, + List.of(dataset.getDatasetId(), dataset1.getDatasetId()), + collectionId)); + case "collectionId" -> + List.of(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)); + default -> throw new IllegalArgumentException("Invalid type: " + type); + }; assertNotNull(summaries); assertEquals(1, summaries.size()); DarCollectionSummary summary = summaries.get(0); @@ -795,7 +845,10 @@ void testGetDarCollectionSummaryTwoDataAccessRequests(String type) { // Ensure the reference IDs include both DARs and latest represents the newer DAR assertNotNull(summary.getReferenceIds()); assertEquals(2, summary.getReferenceIds().size()); - assertTrue(summary.getReferenceIds().containsAll(List.of(olderDar.getReferenceId(), newerDar.getReferenceId()))); + assertTrue( + summary + .getReferenceIds() + .containsAll(List.of(olderDar.getReferenceId(), newerDar.getReferenceId()))); assertEquals(newerDar.getReferenceId(), summary.getLatestReferenceId()); // Ensure the election from the older DAR is not included @@ -814,7 +867,7 @@ void testGetDarCollectionSummaryTwoDataAccessRequests(String type) { } @ParameterizedTest - @ValueSource(strings= {"DAC", "CollectionId"}) + @ValueSource(strings = {"DAC", "CollectionId"}) void testGetDarCollectionSummaryTwoDataAccessRequestsForDACsWithVotes(String type) { // create a DAC and chairperson for the dataset for the DAC Chair test Dac dac = createDac(); @@ -831,22 +884,29 @@ void testGetDarCollectionSummaryTwoDataAccessRequestsForDACsWithVotes(String typ DataAccessRequest newerDar = createProgressReportFromDAR(olderDar); // Insert dataset relations for both DARs - dataAccessRequestDAO.insertDARDatasetRelation(olderDar.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(newerDar.getReferenceId(), dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + olderDar.getReferenceId(), dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + newerDar.getReferenceId(), dataset.getDatasetId()); // Create an election for the new DAR - Election expectedElection = createElectionWithVotes(chair, userId, - newerDar.getReferenceId(), dataset.getDatasetId()); + Election expectedElection = + createElectionWithVotes(chair, userId, newerDar.getReferenceId(), dataset.getDatasetId()); // Create an election for the older DAR with old votes and make sure they are not included - createElectionWithVotes(chair, userId, - olderDar.getReferenceId(), dataset.getDatasetId()); - - List summaries = switch (type) { - case "DAC" -> darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(chair.getUserId(), UserRoles.CHAIRPERSON.getRoleId()); - case "CollectionId" -> List.of(darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(userId, List.of(dataset.getDatasetId()), collectionId)); - default -> throw new IllegalArgumentException("Invalid type: " + type); - }; + createElectionWithVotes(chair, userId, olderDar.getReferenceId(), dataset.getDatasetId()); + + List summaries = + switch (type) { + case "DAC" -> + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + chair.getUserId(), UserRoles.CHAIRPERSON.getRoleId()); + case "CollectionId" -> + List.of( + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userId, List.of(dataset.getDatasetId()), collectionId)); + default -> throw new IllegalArgumentException("Invalid type: " + type); + }; assertNotNull(summaries); assertEquals(1, summaries.size()); @@ -865,11 +925,15 @@ void testGetDarCollectionSummaryTwoDataAccessRequestsForDACsWithVotes(String typ // In the DAC case, we expect votes from the chair // In the CollectionId case, we expect votes from the user Integer voteUserId = type.equals("DAC") ? chair.getUserId() : userId; - List expectedVotes = expectedElection.getVotes().values().stream() - .filter(v -> v.getUserId().equals(voteUserId) || v.getType().equals(VoteType.FINAL.getValue())) - .map(Vote::getVoteId) - .toList(); - summary.getVotes().forEach(v -> assertTrue(expectedVotes.contains(v.getVoteId()))); + List expectedVotes = + expectedElection.getVotes().values().stream() + .filter( + v -> + v.getUserId().equals(voteUserId) + || v.getType().equals(VoteType.FINAL.getValue())) + .map(Vote::getVoteId) + .toList(); + summary.getVotes().forEach(v -> assertTrue(expectedVotes.contains(v.getVoteId()))); } @Test @@ -891,8 +955,8 @@ void testGetDarCollectionSummaryByCollectionId() { DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); createElection( ElectionStatus.CLOSED.getValue(), darOne.getReferenceId(), dataset.getDatasetId()); @@ -903,14 +967,13 @@ void testGetDarCollectionSummaryByCollectionId() { ElectionStatus.OPEN.getValue(), darTwo.getReferenceId(), datasetTwo.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId()); - DarCollectionSummary summary = darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collectionOneId); + DarCollectionSummary summary = + darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionOneId); assertNotNull(summary); assertEquals(collectionOneId, summary.getDarCollectionId()); assertEquals(1, summary.getDatasetIds().size()); - summary.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); + summary.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); assertNotNull(summary.getDacNames()); assertEquals(1, summary.getDacNames().size()); @@ -942,21 +1005,20 @@ void testGetDarCollectionSummaryByCollectionId_NoElectionsPresent() { DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); createElection( ElectionStatus.OPEN.getValue(), darTwo.getReferenceId(), datasetTwo.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId()); - DarCollectionSummary summary = darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collectionOneId); + DarCollectionSummary summary = + darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionOneId); assertNotNull(summary); assertEquals(collectionOneId, summary.getDarCollectionId()); assertEquals(1, summary.getDatasetIds().size()); - summary.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); + summary.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); assertEquals(0, summary.getElections().size()); assertEquals(1, summary.getDatasetCount()); @@ -991,17 +1053,17 @@ void testGetDarCollectionSummaryForDACByCollectionId() { DataAccessRequest excludedDar = createDataAccessRequest(excludedCollectionId, userTwoId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), datasetTwo.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(excludedDar.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darOne.getReferenceId(), datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + excludedDar.getReferenceId(), datasetTwo.getDatasetId()); Election collectionOnePrevElection = createElection( ElectionStatus.CLOSED.getValue(), darOne.getReferenceId(), - dataset - .getDatasetId()); // non-latest dataset, need to make sure this isn't pulled into - // query results + dataset.getDatasetId()); // non-latest dataset, need to make sure this isn't pulled into + // query results Election collectionOneElection = createElection( ElectionStatus.OPEN.getValue(), darOne.getReferenceId(), dataset.getDatasetId()); @@ -1014,7 +1076,7 @@ void testGetDarCollectionSummaryForDACByCollectionId() { datasetTwo.getDatasetId()); Integer excludedCollectionElectionId = excludedCollectionElection.getElectionId(); - //create old votes to ensure that they don't get pulled in by the query + // create old votes to ensure that they don't get pulled in by the query createVote(userOneId, collectionOnePrevElectionId, VoteType.DAC.getValue()); createVote(userTwoId, collectionOnePrevElectionId, VoteType.RADAR_APPROVE.getValue()); createVote(userChairId, collectionOnePrevElectionId, VoteType.FINAL.getValue()); @@ -1033,14 +1095,14 @@ void testGetDarCollectionSummaryForDACByCollectionId() { createVote(userChairId, excludedCollectionElectionId, VoteType.CHAIRPERSON.getValue()); List targetDatasets = List.of(dataset.getDatasetId(), datasetTwo.getDatasetId()); - DarCollectionSummary summary = darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( - userChairId, targetDatasets, collectionOneId); + DarCollectionSummary summary = + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userChairId, targetDatasets, collectionOneId); assertNotNull(summary); assertEquals(collectionOneId, summary.getDarCollectionId()); assertEquals(2, summary.getDatasetIds().size()); - summary.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); + summary.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); // Ensure that only the DACs associated with datasets in the specified collection are included assertNotNull(summary.getDacNames()); @@ -1048,13 +1110,12 @@ void testGetDarCollectionSummaryForDACByCollectionId() { assertTrue(summary.getDacNames().contains(dacOneName)); assertTrue(summary.getDacNames().contains(dacTwoName)); - List targetVotes = List.of(collectionOneVoteChair.getVoteId(), - collectionOneVoteThree.getVoteId()); + List targetVotes = + List.of(collectionOneVoteChair.getVoteId(), collectionOneVoteThree.getVoteId()); Integer electionId = collectionOneElection.getElectionId(); summary.getElections().forEach((key, value) -> assertEquals(electionId, key)); - summary.getVotes().forEach(v -> assertTrue( - targetVotes.contains(v.getVoteId()))); + summary.getVotes().forEach(v -> assertTrue(targetVotes.contains(v.getVoteId()))); assertEquals(2, summary.getDatasetCount()); } @@ -1077,8 +1138,8 @@ void testGetDarCollectionSummaryForDACByCollectionId_NoElectionsPresent() { DataAccessRequest darOne = createDataAccessRequest(collectionOneId, userOneId); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(excludedDar.getReferenceId(), - excludedDataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + excludedDar.getReferenceId(), excludedDataset.getDatasetId()); Election excludedElection = createElection( @@ -1091,14 +1152,14 @@ void testGetDarCollectionSummaryForDACByCollectionId_NoElectionsPresent() { createVote(userOneId, excludedElectionId, VoteType.DAC.getValue()); List targetDatasets = List.of(dataset.getDatasetId()); - DarCollectionSummary summary = darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( - userChairId, targetDatasets, collectionOneId); + DarCollectionSummary summary = + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userChairId, targetDatasets, collectionOneId); assertNotNull(summary); assertEquals(collectionOneId, summary.getDarCollectionId()); assertEquals(1, summary.getDatasetIds().size()); - summary.getDatasetIds() - .forEach(id -> assertTrue(targetDatasets.contains(id))); + summary.getDatasetIds().forEach(id -> assertTrue(targetDatasets.contains(id))); assertNotNull(summary.getDacNames()); assertEquals(1, summary.getDacNames().size()); @@ -1124,12 +1185,13 @@ void testGetDarCollectionSummaryForDACByCollectionId_ArchivedCollection() { Integer archivedCollectionId = createDarCollection(userOneId); DataAccessRequest archivedDar = createDataAccessRequest(archivedCollectionId, userOneId); dataAccessRequestDAO.archiveByReferenceIds(List.of(archivedDar.getReferenceId())); - dataAccessRequestDAO.insertDARDatasetRelation(archivedDar.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + archivedDar.getReferenceId(), dataset.getDatasetId()); List targetDatasets = List.of(dataset.getDatasetId()); - DarCollectionSummary summary = darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( - userChairId, targetDatasets, archivedCollectionId); + DarCollectionSummary summary = + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + userChairId, targetDatasets, archivedCollectionId); assertNull(summary); } @@ -1143,11 +1205,11 @@ void testGetDarCollectionSummaryByCollectionId_ArchivedCollection() { Integer archivedCollectionId = createDarCollection(userOneId); DataAccessRequest archivedDar = createDataAccessRequest(archivedCollectionId, userOneId); dataAccessRequestDAO.archiveByReferenceIds(List.of(archivedDar.getReferenceId())); - dataAccessRequestDAO.insertDARDatasetRelation(archivedDar.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + archivedDar.getReferenceId(), dataset.getDatasetId()); - DarCollectionSummary summary = darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - archivedCollectionId); + DarCollectionSummary summary = + darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(archivedCollectionId); assertNull(summary); } @@ -1158,19 +1220,22 @@ void testGetDarCollectionSummaryForResearcherWithProgressReports(String voteType Integer userId = setup.userId(); DarCollectionSummary summary = setup.summary(); - List summariesForResearcher = darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); + List summariesForResearcher = + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); assertEquals(1, summariesForResearcher.size()); Optional firstId = summariesForResearcher.get(0).getReferenceIds().stream().findFirst(); assertTrue(firstId.isPresent()); DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId(firstId.get()); assertEquals(summary.getDarCollectionId(), dar.getCollectionId()); - //create child progress report + // create child progress report String progressReportReferenceId = createProgressReportFromDAR(dar).getReferenceId(); validateSummaryObjectForResearcherWithParent(userId, progressReportReferenceId); - //create grandchild progress report - DataAccessRequest progressReportDar = dataAccessRequestDAO.findByReferenceId(progressReportReferenceId); - String progressReportReferenceId2 = createProgressReportFromDAR(progressReportDar).getReferenceId(); + // create grandchild progress report + DataAccessRequest progressReportDar = + dataAccessRequestDAO.findByReferenceId(progressReportReferenceId); + String progressReportReferenceId2 = + createProgressReportFromDAR(progressReportDar).getReferenceId(); validateSummaryObjectForResearcherWithParent(userId, progressReportReferenceId2); } @@ -1182,10 +1247,12 @@ void testGetDarCollectionSummaryForResearcherWithCloseout(String voteType) { DarCollectionSummary summary = setup.summary(); // Create a child progress report with closeout supplement - DataAccessRequest parent = dataAccessRequestDAO.findByReferenceId(summary.getLatestReferenceId()); + DataAccessRequest parent = + dataAccessRequestDAO.findByReferenceId(summary.getLatestReferenceId()); String referenceId = UUID.randomUUID().toString(); DataAccessRequestData data = parent.getData(); - data.setCloseoutSupplement(new CloseoutSupplement(List.of("Closeout data"), "Closeout notes", 1)); + data.setCloseoutSupplement( + new CloseoutSupplement(List.of("Closeout data"), "Closeout notes", 1)); dataAccessRequestDAO.insertProgressReport( parent.getId(), parent.getCollectionId(), @@ -1199,7 +1266,8 @@ void testGetDarCollectionSummaryForResearcherWithCloseout(String voteType) { .forEach( datasetId -> dataAccessRequestDAO.insertDARDatasetRelation(referenceId, datasetId)); - List summariesForResearcher = darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); + List summariesForResearcher = + darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); assertEquals(1, summariesForResearcher.size()); assertTrue(summariesForResearcher.get(0).getProgressReport()); assertNotNull(summariesForResearcher.get(0).getCloseoutSupplement()); @@ -1218,7 +1286,8 @@ void testGetDarCollectionSummaryForDACWithProgressReports(String voteType) { createProgressReportFromDAR(dar); List summariesForDAC = - darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(chairId, UserRoles.CHAIRPERSON.getRoleId()); + darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + chairId, UserRoles.CHAIRPERSON.getRoleId()); assertTrue(summariesForDAC.get(0).getProgressReport()); } @@ -1273,7 +1342,8 @@ void testGetDarCollectionSummaryForDACByCollectionIdWithProgressReports(String v createProgressReportFromDAR(dar); DarCollectionSummary summaryForDAC = - darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(chairId, dar.getDatasetIds(), dar.getCollectionId()); + darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + chairId, dar.getDatasetIds(), dar.getCollectionId()); assertTrue(summaryForDAC.getProgressReport()); } @@ -1286,22 +1356,23 @@ private Setup createDarCollectionSummaryForUser(VoteType voteType) { Integer dacId = dac.getDacId(); Dataset dataset = createDatasetWithDac(userId, dacId); - DarCollectionSummary summary = createDarWithVotes(userId, chairId, dataset.getDatasetId(), voteType); + DarCollectionSummary summary = + createDarWithVotes(userId, chairId, dataset.getDatasetId(), voteType); return new Setup(userId, chairId, summary); } public record Setup(Integer userId, Integer chairId, DarCollectionSummary summary) {} private void validateSummaryObjectForResearcherWithParent(Integer userId, String referenceId) { - DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId( - referenceId); + DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId(referenceId); List summariesForResearcher = darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(userId); assertTrue(summariesForResearcher.get(0).getProgressReport()); assertTrue(dar.getProgressReport()); } - private DarCollectionSummary createDarWithVotes(Integer userId, Integer chairId, Integer datasetId, VoteType voteType) { + private DarCollectionSummary createDarWithVotes( + Integer userId, Integer chairId, Integer datasetId, VoteType voteType) { Integer collectionOneId = createDarCollection(userId); DataAccessRequest darOne = createDataAccessRequest(collectionOneId, userId); @@ -1310,10 +1381,8 @@ private DarCollectionSummary createDarWithVotes(Integer userId, Integer chairId, Election collectionOneElection = createElection(ElectionStatus.CLOSED.getValue(), darOne.getReferenceId(), datasetId); - createVote(chairId, collectionOneElection.getElectionId(), - voteType.getValue()); + createVote(chairId, collectionOneElection.getElectionId(), voteType.getValue()); - return darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collectionOneId); + return darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionOneId); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DataAccessRequestDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DataAccessRequestDAOTest.java index 6ea09cbc72..bbd2a52147 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DataAccessRequestDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DataAccessRequestDAOTest.java @@ -59,8 +59,8 @@ void testFindAll() { assertTrue(dars.isEmpty()); DataAccessRequest collectionDar = createDataAccessRequestV3(); - DarCollection collection = darCollectionDAO.findDARCollectionByCollectionId( - collectionDar.getCollectionId()); + DarCollection collection = + darCollectionDAO.findDARCollectionByCollectionId(collectionDar.getCollectionId()); createDraftDataAccessRequest(); List newDars = dataAccessRequestDAO.findAllDataAccessRequests(); assertFalse(newDars.isEmpty()); @@ -111,8 +111,8 @@ void updateDraftToNonDraft() { assertFalse(draftDars1.isEmpty()); assertEquals(1, draftDars1.size()); DataAccessRequestData darData = draftDars1.get(0).getData(); - dataAccessRequestDAO.updateDataByReferenceId(dar.referenceId, dar.userId, new Date(), - new Date(), darData, randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.referenceId, dar.userId, new Date(), new Date(), darData, randomAlphabetic(10)); List draftDars2 = dataAccessRequestDAO.findAllDraftDataAccessRequests(); assertTrue(draftDars2.isEmpty()); } @@ -124,8 +124,8 @@ void updateNonDraftToDraft() { List draftDars1 = dataAccessRequestDAO.findAllDraftDataAccessRequests(); assertTrue(draftDars1.isEmpty()); - dataAccessRequestDAO.updateDataByReferenceId(dar.getReferenceId(), dar.userId, null, - new Date(), dar.getData(), randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.getReferenceId(), dar.userId, null, new Date(), dar.getData(), randomAlphabetic(10)); List draftDars2 = dataAccessRequestDAO.findAllDraftDataAccessRequests(); assertFalse(draftDars2.isEmpty()); assertEquals(1, draftDars2.size()); @@ -137,16 +137,17 @@ void updateDraftToNonDraftByCollectionId() { DarCollection darColl = createDarCollection(); DataAccessRequest dar = new ArrayList<>(darColl.getDars().values()).get(0); - dataAccessRequestDAO.updateDataByReferenceId(dar.referenceId, dar.userId, null, - new Date(), dar.getData(), randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.referenceId, dar.userId, null, new Date(), dar.getData(), randomAlphabetic(10)); dar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); DataAccessRequestData darData = dar.getData(); - dataAccessRequestDAO.updateDataByReferenceId(dar.referenceId, dar.userId, new Date(), - new Date(), darData, randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.referenceId, dar.userId, new Date(), new Date(), darData, randomAlphabetic(10)); dar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertFalse(dar.getDraft()); - Timestamp expectedTimestamp = new Timestamp( - dar.getSubmissionDate().getTime() + DataAccessRequest.EXPIRATION_DURATION_MILLIS); + Timestamp expectedTimestamp = + new Timestamp( + dar.getSubmissionDate().getTime() + DataAccessRequest.EXPIRATION_DURATION_MILLIS); assertEquals(expectedTimestamp, dar.getExpiresAt()); assertNotNull(dar.getDarCode()); } @@ -156,8 +157,8 @@ void testDataAccessRequestSubmissionDateAbsent() { DarCollection darColl = createDarCollection(); DataAccessRequest dar = new ArrayList<>(darColl.getDars().values()).get(0); - dataAccessRequestDAO.updateDataByReferenceId(dar.referenceId, dar.userId, null, - new Date(), dar.getData(), randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.referenceId, dar.userId, null, new Date(), dar.getData(), randomAlphabetic(10)); dar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertNull(dar.getSubmissionDate()); assertTrue(dar.getDraft()); @@ -170,13 +171,14 @@ void testDataAccessRequestSubmissionDatePresent() { DarCollection darColl = createDarCollection(); DataAccessRequest dar = new ArrayList<>(darColl.getDars().values()).get(0); - dataAccessRequestDAO.updateDataByReferenceId(dar.referenceId, dar.userId, new Date(), - new Date(), dar.getData(), randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.referenceId, dar.userId, new Date(), new Date(), dar.getData(), randomAlphabetic(10)); dar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertFalse(dar.getDraft()); assertFalse(dar.getExpired()); - Timestamp expectedTimestamp = new Timestamp( - dar.getSubmissionDate().getTime() + DataAccessRequest.EXPIRATION_DURATION_MILLIS); + Timestamp expectedTimestamp = + new Timestamp( + dar.getSubmissionDate().getTime() + DataAccessRequest.EXPIRATION_DURATION_MILLIS); assertEquals(expectedTimestamp, dar.getExpiresAt()); } @@ -187,8 +189,8 @@ void updateNonDraftToDraftByCollectionId() { dar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertFalse(dar.getDraft()); - dataAccessRequestDAO.updateDataByReferenceId(dar.referenceId, dar.userId, null, - new Date(), dar.getData(), randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.referenceId, dar.userId, null, new Date(), dar.getData(), randomAlphabetic(10)); dar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertTrue(dar.getDraft()); assertNull(dar.getSubmissionDate()); @@ -200,8 +202,8 @@ void updateNonDraftToDraftByCollectionId() { void testCreate() { User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 999999999); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d1 = createDARDAOTestDataset(); Dataset d2 = createDARDAOTestDataset(); @@ -219,8 +221,8 @@ void testFindByReferenceIds() { DataAccessRequest dar1 = createDataAccessRequestV3(); DataAccessRequest dar2 = createDataAccessRequestV3(); DataAccessRequest dar3 = createDataAccessRequestV3(); - List referenceIds = Arrays.asList(dar1.getReferenceId(), dar2.getReferenceId(), - dar3.getReferenceId()); + List referenceIds = + Arrays.asList(dar1.getReferenceId(), dar2.getReferenceId(), dar3.getReferenceId()); List dars = dataAccessRequestDAO.findByReferenceIds(referenceIds); assertNotNull(dars); @@ -238,8 +240,8 @@ void testUpdateByReferenceId() { String rus = randomAlphabetic(10); dar.getData().setRus(rus); dar.getData().setValidRestriction(false); - dataAccessRequestDAO.updateDataByReferenceId(dar.getReferenceId(), user.getUserId(), now, - now, dar.getData(), randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.getReferenceId(), user.getUserId(), now, now, dar.getData(), randomAlphabetic(10)); DataAccessRequest updatedDar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertEquals(rus, updatedDar.getData().getRus()); assertFalse(updatedDar.getData().getValidRestriction()); @@ -257,7 +259,9 @@ void testUnsupportedUnicodeDarInsert() { collection.getDarCollectionId(), referenceId, collection.getCreateUserId(), - now, now, now, + now, + now, + now, data, randomAlphabetic(10)); DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId(referenceId); @@ -275,8 +279,13 @@ void testUnsupportedUnicodeDarUpdate() { String rus = randomAlphabetic(10); dar.getData().setRus(rus + String.format(" %s ", unsupportedUnicode)); - dataAccessRequestDAO.updateDataByReferenceId(dar.getReferenceId(), collection.getCreateUserId(), - now, now, dar.getData(), randomAlphabetic(10)); + dataAccessRequestDAO.updateDataByReferenceId( + dar.getReferenceId(), + collection.getCreateUserId(), + now, + now, + dar.getData(), + randomAlphabetic(10)); DataAccessRequest updatedDar = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertNotNull(updatedDar); @@ -292,12 +301,7 @@ void testUnsupportedUnicodeDraftDar() { String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDraftDataAccessRequest( - referenceId, - user.getUserId(), - now, - now, - data - ); + referenceId, user.getUserId(), now, now, data); DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId(referenceId); assertNotNull(dar); assertFalse(dar.getData().getRus().contains(unsupportedUnicode)); @@ -317,7 +321,7 @@ void testInsertVersion3() { @Test void testDeleteByCollectionId() { - //creates a dar with a collection ID (also creates a DarCollection) + // creates a dar with a collection ID (also creates a DarCollection) DataAccessRequest dar = createDataAccessRequestV3(); DataAccessRequest returned = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertNotNull(returned); @@ -325,7 +329,6 @@ void testDeleteByCollectionId() { dataAccessRequestDAO.deleteByCollectionId(dar.getCollectionId()); DataAccessRequest returnedAfter = dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); assertNull(returnedAfter); - } @Test @@ -397,11 +400,10 @@ protected DataAccessRequest createExpiredDAR(User user, Dataset dataset, String } // local method to create a DAR - protected DataAccessRequest createDAR(User user, Dataset dataset, String darCode, - Timestamp submissionDate) { + protected DataAccessRequest createDAR( + User user, Dataset dataset, String darCode, Timestamp submissionDate) { var now = new Timestamp(new Date().getTime()); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - now); + Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), now); DataAccessRequest testDar = new DataAccessRequest(); testDar.setCollectionId(collectionId); testDar.setReferenceId(UUID.randomUUID().toString()); @@ -419,8 +421,7 @@ protected DataAccessRequest createDAR(User user, Dataset dataset, String darCode testDar.getSubmissionDate(), testDar.getUpdateDate(), testDar.getData(), - randomAlphabetic(10) - ); + randomAlphabetic(10)); dataAccessRequestDAO.insertDARDatasetRelation(testDar.getReferenceId(), dataset.getDatasetId()); return dataAccessRequestDAO.findByReferenceId(testDar.getReferenceId()); } @@ -431,12 +432,7 @@ protected DataAccessRequest createDraftDAR(User user) { DataAccessRequestData contents = new DataAccessRequestData(); String referenceId = UUID.randomUUID().toString(); dataAccessRequestDAO.insertDraftDataAccessRequest( - referenceId, - user.getUserId(), - now, - now, - contents - ); + referenceId, user.getUserId(), now, now, contents); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -489,35 +485,21 @@ void testEnsureOnlyDataAccessRequestsByDatasetIdReturnsJustForSpecificDatasetId( Election e1 = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v1 = createFinalVote(dataset1.getCreateUserId(), e1.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - v1.getVoteId(), - false, - e1.getElectionId(), - now, - false); + updateVote(true, "", now, v1.getVoteId(), false, e1.getElectionId(), now, false); Election e2 = createDataAccessElection(testDar2.getReferenceId(), dataset2.getDatasetId()); Vote v2 = createVote(dataset2.getCreateUserId(), e2.getElectionId(), VoteType.RADAR_APPROVE); now = new Date(); - updateVote(true, - "", - now, - v2.getVoteId(), - false, - e2.getElectionId(), - now, - false); + updateVote(true, "", now, v2.getVoteId(), false, e2.getElectionId(), now, false); - List dars = dataAccessRequestDAO.findApprovedDARsByDatasetId( - dataset1.getDatasetId()); + List dars = + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()); assertEquals(1, dars.size()); assertTrue(dars.get(0).getDatasetIds().contains(dataset1.getDatasetId())); assertEquals(darCode1, dars.get(0).getDarCode()); - List returnedDARs = dataAccessRequestDAO.findApprovedDARsByDatasetId( - dataset2.getDatasetId()); + List returnedDARs = + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()); assertEquals(1, returnedDARs.size()); assertTrue(returnedDARs.get(0).getDatasetIds().contains(dataset2.getDatasetId())); assertEquals(darCode2, returnedDARs.get(0).getDarCode()); @@ -531,12 +513,8 @@ void testFindAllApprovedDataAccessRequestsByDatasetId() { Dataset dataset1 = createDARDAOTestDataset(); Dataset dataset2 = createDARDAOTestDataset(); - assertTrue( - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .isEmpty()); - assertTrue( - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()) - .isEmpty()); + assertTrue(dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()).isEmpty()); + assertTrue(dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()).isEmpty()); User user1 = createUserWithInstitution(); User user2 = createUserWithInstitution(); @@ -544,68 +522,46 @@ void testFindAllApprovedDataAccessRequestsByDatasetId() { DataAccessRequest testDar1 = createDAR(user1, dataset1, darCode1); DataAccessRequest testDar2 = createDAR(user2, dataset2, darCode2); DataAccessRequest testDar3 = createDAR(user3, dataset2, darCode3); - assertTrue( - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .isEmpty()); - assertTrue( - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()) - .isEmpty()); + assertTrue(dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()).isEmpty()); + assertTrue(dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()).isEmpty()); - assertEquals(0, - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()) - .size()); + assertEquals( + 0, dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()).size()); Election e1 = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v1 = createFinalVote(dataset1.getCreateUserId(), e1.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - v1.getVoteId(), - false, - e1.getElectionId(), - now, - false); + updateVote(true, "", now, v1.getVoteId(), false, e1.getElectionId(), now, false); Election e2 = createDataAccessElection(testDar2.getReferenceId(), dataset2.getDatasetId()); Vote v2 = createFinalVote(dataset2.getCreateUserId(), e2.getElectionId()); now = new Date(); - updateVote(true, - "", - now, - v2.getVoteId(), - false, - e2.getElectionId(), - now, - false); - - assertEquals(1, - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .size()); - assertEquals(testDar1.getUserId(), - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .get(0).getUserId()); - assertEquals(1, - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()) - .size()); - assertEquals(testDar2.getUserId(), - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()) - .get(0).getUserId()); + updateVote(true, "", now, v2.getVoteId(), false, e2.getElectionId(), now, false); + + assertEquals( + 1, dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()).size()); + assertEquals( + testDar1.getUserId(), + dataAccessRequestDAO + .findApprovedDARsByDatasetId(dataset1.getDatasetId()) + .get(0) + .getUserId()); + assertEquals( + 1, dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()).size()); + assertEquals( + testDar2.getUserId(), + dataAccessRequestDAO + .findApprovedDARsByDatasetId(dataset2.getDatasetId()) + .get(0) + .getUserId()); Election e3 = createDataAccessElection(testDar3.getReferenceId(), dataset2.getDatasetId()); Vote v3 = createFinalVote(dataset2.getCreateUserId(), e3.getElectionId()); now = new Date(); - updateVote(true, - "", - now, - v3.getVoteId(), - false, - e3.getElectionId(), - now, - false); + updateVote(true, "", now, v3.getVoteId(), false, e3.getElectionId(), now, false); - List approvedDars = dataAccessRequestDAO.findApprovedDARsByDatasetId( - dataset2.getDatasetId()); + List approvedDars = + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset2.getDatasetId()); List approvedDarIds = approvedDars.stream().map(DataAccessRequest::getId).toList(); assertEquals(2, approvedDarIds.size()); assertTrue(approvedDarIds.contains(testDar3.getId())); @@ -622,8 +578,10 @@ void testFindAllDatasetApprovalsByDar() { User user1 = createUserWithInstitution(); DataAccessRequest testDar1 = createDAR(user1, dataset1, darCode1); - dataAccessRequestDAO.insertDARDatasetRelation(testDar1.getReferenceId(), dataset2.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(testDar1.getReferenceId(), dataset3.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + testDar1.getReferenceId(), dataset2.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + testDar1.getReferenceId(), dataset3.getDatasetId()); Election e1 = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v1 = createVote(dataset1.getCreateUserId(), e1.getElectionId(), VoteType.RADAR_APPROVE); @@ -636,32 +594,16 @@ void testFindAllDatasetApprovalsByDar() { Date now = new Date(); - assertTrue( - dataAccessRequestDAO.findDatasetApprovalsByDar(testDar1.getReferenceId()) - .isEmpty()); + assertTrue(dataAccessRequestDAO.findDatasetApprovalsByDar(testDar1.getReferenceId()).isEmpty()); - updateVote(true, - "", - now, - v1.getVoteId(), - false, - e1.getElectionId(), - now, - false); + updateVote(true, "", now, v1.getVoteId(), false, e1.getElectionId(), now, false); - Set approvedDatasetIds = dataAccessRequestDAO.findDatasetApprovalsByDar( - testDar1.getReferenceId()); + Set approvedDatasetIds = + dataAccessRequestDAO.findDatasetApprovalsByDar(testDar1.getReferenceId()); assertEquals(1, approvedDatasetIds.size()); assertTrue(approvedDatasetIds.contains(dataset1.getDatasetId())); - updateVote(true, - "", - now, - v2.getVoteId(), - false, - e2.getElectionId(), - now, - false); + updateVote(true, "", now, v2.getVoteId(), false, e2.getElectionId(), now, false); approvedDatasetIds = dataAccessRequestDAO.findDatasetApprovalsByDar(testDar1.getReferenceId()); @@ -669,15 +611,7 @@ void testFindAllDatasetApprovalsByDar() { assertTrue(approvedDatasetIds.contains(dataset1.getDatasetId())); assertTrue(approvedDatasetIds.contains(dataset2.getDatasetId())); - - updateVote(false, - "", - now, - v3.getVoteId(), - false, - e3.getElectionId(), - now, - false); + updateVote(false, "", now, v3.getVoteId(), false, e3.getElectionId(), now, false); approvedDatasetIds = dataAccessRequestDAO.findDatasetApprovalsByDar(testDar1.getReferenceId()); @@ -693,24 +627,19 @@ void testFindAllDatasetApprovalsByDars_IncludesExpired() { User user1 = createUserWithInstitution(); DataAccessRequest testDar1 = createExpiredDAR(user1, dataset1, darCode1); - dataAccessRequestDAO.insertDARDatasetRelation(testDar1.getReferenceId(), dataset1.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + testDar1.getReferenceId(), dataset1.getDatasetId()); - Election election = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); + Election election = + createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v1 = createFinalVote(dataset1.getCreateUserId(), election.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - v1.getVoteId(), - false, - election.getElectionId(), - now, - false); + updateVote(true, "", now, v1.getVoteId(), false, election.getElectionId(), now, false); - Set approvedDatasetIds = dataAccessRequestDAO.findDatasetApprovalsByDar( - testDar1.getReferenceId()); + Set approvedDatasetIds = + dataAccessRequestDAO.findDatasetApprovalsByDar(testDar1.getReferenceId()); assertEquals(1, approvedDatasetIds.size()); assertTrue(approvedDatasetIds.contains(dataset1.getDatasetId())); } @@ -720,36 +649,30 @@ void testFindDatasetApprovalsByDAR_ExcludeCloseouts() { // Create a dar collection User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 10000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); // Create an approved DAR on a dataset Dataset dataset = createDataset(); DataAccessRequest parentDAR = createDataAccessRequest(user.getUserId(), collectionId); - dataAccessRequestDAO.insertDARDatasetRelation(parentDAR.getReferenceId(), - dataset.getDatasetId()); - Election election = createDataAccessElection(parentDAR.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + parentDAR.getReferenceId(), dataset.getDatasetId()); + Election election = + createDataAccessElection(parentDAR.getReferenceId(), dataset.getDatasetId()); Vote vote = createFinalVote(dataset.getCreateUserId(), election.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - vote.getVoteId(), - false, - election.getElectionId(), - now, - false); + updateVote(true, "", now, vote.getVoteId(), false, election.getElectionId(), now, false); // Ensure we can find the approved dataset for the parent DAR - Set approvedDatasetIds = dataAccessRequestDAO.findDatasetApprovalsByDar( - parentDAR.getReferenceId()); + Set approvedDatasetIds = + dataAccessRequestDAO.findDatasetApprovalsByDar(parentDAR.getReferenceId()); assertTrue(approvedDatasetIds.contains(dataset.getDatasetId())); // Create a closeout DAR for the parent DAR - DataAccessRequest closeoutDAR = createProgressReport(user.getEraCommonsId(), user.getUserId(), collectionId, - parentDAR.getId()); - CloseoutSupplement closeout = new CloseoutSupplement(List.of("Reason"), "Other Reason", - user.getUserId()); + DataAccessRequest closeoutDAR = + createProgressReport( + user.getEraCommonsId(), user.getUserId(), collectionId, parentDAR.getId()); + CloseoutSupplement closeout = + new CloseoutSupplement(List.of("Reason"), "Other Reason", user.getUserId()); closeoutDAR.getData().setCloseoutSupplement(closeout); dataAccessRequestDAO.updateDataByReferenceId( closeoutDAR.getReferenceId(), @@ -757,19 +680,19 @@ void testFindDatasetApprovalsByDAR_ExcludeCloseouts() { now, now, closeoutDAR.getData(), - randomAlphabetic(10) - ); + randomAlphabetic(10)); // Ensure that we do NOT get the dataset from the parent DAR - Set noApprovedDatasetIds1 = dataAccessRequestDAO.findDatasetApprovalsByDar( - parentDAR.getReferenceId()); - assertTrue(noApprovedDatasetIds1.isEmpty(), - "Parent DAR should not be included in dataset approvals"); + Set noApprovedDatasetIds1 = + dataAccessRequestDAO.findDatasetApprovalsByDar(parentDAR.getReferenceId()); + assertTrue( + noApprovedDatasetIds1.isEmpty(), "Parent DAR should not be included in dataset approvals"); // Ensure that we do NOT get the dataset from the closeout DAR - Set noApprovedDatasetIds2 = dataAccessRequestDAO.findDatasetApprovalsByDar( - closeoutDAR.getReferenceId()); - assertTrue(noApprovedDatasetIds2.isEmpty(), + Set noApprovedDatasetIds2 = + dataAccessRequestDAO.findDatasetApprovalsByDar(closeoutDAR.getReferenceId()); + assertTrue( + noApprovedDatasetIds2.isEmpty(), "Closeout DAR should not be included in dataset approvals"); } @@ -787,34 +710,18 @@ void testFindAllApprovedDataAccessRequestsByDatasetId_ApprovedThenDeniedCase() { Election e1 = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v1 = createFinalVote(dataset1.getCreateUserId(), e1.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - v1.getVoteId(), - false, - e1.getElectionId(), - now, - false); + updateVote(true, "", now, v1.getVoteId(), false, e1.getElectionId(), now, false); - assertEquals(1, - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .size()); + assertEquals( + 1, dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()).size()); Election e2 = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v2 = createFinalVote(dataset1.getCreateUserId(), e2.getElectionId()); now = new Date(); - updateVote(false, - "", - now, - v2.getVoteId(), - false, - e2.getElectionId(), - now, - false); + updateVote(false, "", now, v2.getVoteId(), false, e2.getElectionId(), now, false); - assertEquals(0, - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .size()); + assertEquals( + 0, dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()).size()); } @ParameterizedTest @@ -823,31 +730,25 @@ void testFindAllApprovedDataAccessRequestsByDatasetId_ExpiredDARCase(long submis String darCode1 = "DAR-" + randomInt(100, 1000000); Dataset dataset1 = createDARDAOTestDataset(); User user1 = createUserWithInstitution(); - var submissionDate = new Timestamp( - new Date().getTime() - TimeUnit.DAYS.toMillis(submissionDaysAgo)); + var submissionDate = + new Timestamp(new Date().getTime() - TimeUnit.DAYS.toMillis(submissionDaysAgo)); DataAccessRequest testDar1 = createDAR(user1, dataset1, darCode1, submissionDate); Election e1 = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v1 = createFinalVote(dataset1.getCreateUserId(), e1.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - v1.getVoteId(), - false, - e1.getElectionId(), - now, - false); + updateVote(true, "", now, v1.getVoteId(), false, e1.getElectionId(), now, false); var expectedDARS = 1; - // If submission date is more than a year ago, then the DAR should not be returned from findApprovedDARsByDatasetId + // If submission date is more than a year ago, then the DAR should not be returned from + // findApprovedDARsByDatasetId if (submissionDaysAgo >= 365) { expectedDARS = 0; } - assertEquals(expectedDARS, - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .size()); + assertEquals( + expectedDARS, + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()).size()); } @Test @@ -860,19 +761,12 @@ void testFindAllApprovedDataAccessRequestsByDatasetId_NullSubmissionDate() { Election e1 = createDataAccessElection(testDar1.getReferenceId(), dataset1.getDatasetId()); Vote v1 = createFinalVote(dataset1.getCreateUserId(), e1.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - v1.getVoteId(), - false, - e1.getElectionId(), - now, - false); + updateVote(true, "", now, v1.getVoteId(), false, e1.getElectionId(), now, false); - // If submission date is null, then the DAR should not be returned from findApprovedDARsByDatasetId - assertEquals(0, - dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()) - .size()); + // If submission date is null, then the DAR should not be returned from + // findApprovedDARsByDatasetId + assertEquals( + 0, dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset1.getDatasetId()).size()); } @Test @@ -880,37 +774,31 @@ void testFindApprovedDARsByDatasetId_ExcludeCloseouts() { // Create a dar collection User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 10000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); // Create an approved DAR on a dataset Dataset dataset = createDataset(); DataAccessRequest parentDAR = createDataAccessRequest(user.getUserId(), collectionId); - dataAccessRequestDAO.insertDARDatasetRelation(parentDAR.getReferenceId(), - dataset.getDatasetId()); - Election election = createDataAccessElection(parentDAR.getReferenceId(), - dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + parentDAR.getReferenceId(), dataset.getDatasetId()); + Election election = + createDataAccessElection(parentDAR.getReferenceId(), dataset.getDatasetId()); Vote vote = createFinalVote(dataset.getCreateUserId(), election.getElectionId()); Date now = new Date(); - updateVote(true, - "", - now, - vote.getVoteId(), - false, - election.getElectionId(), - now, - false); + updateVote(true, "", now, vote.getVoteId(), false, election.getElectionId(), now, false); // Ensure we can find the parent DAR for the approved dataset - List approvedDARs = dataAccessRequestDAO.findApprovedDARsByDatasetId( - dataset.getDatasetId()); + List approvedDARs = + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset.getDatasetId()); assertEquals(1, approvedDARs.size()); assertEquals(parentDAR.getReferenceId(), approvedDARs.get(0).getReferenceId()); // Create a closeout DAR from the parent DAR - DataAccessRequest closeoutDAR = createProgressReport(user.getEraCommonsId(), user.getUserId(), collectionId, - parentDAR.getId()); - CloseoutSupplement closeout = new CloseoutSupplement(List.of("Reason"), "Other Reason", - user.getUserId()); + DataAccessRequest closeoutDAR = + createProgressReport( + user.getEraCommonsId(), user.getUserId(), collectionId, parentDAR.getId()); + CloseoutSupplement closeout = + new CloseoutSupplement(List.of("Reason"), "Other Reason", user.getUserId()); closeoutDAR.getData().setCloseoutSupplement(closeout); dataAccessRequestDAO.updateDataByReferenceId( closeoutDAR.getReferenceId(), @@ -918,12 +806,11 @@ void testFindApprovedDARsByDatasetId_ExcludeCloseouts() { now, now, closeoutDAR.getData(), - randomAlphabetic(10) - ); + randomAlphabetic(10)); // Ensure we CANNOT find any DARs for the approved dataset - List noApprovedDARs = dataAccessRequestDAO.findApprovedDARsByDatasetId( - dataset.getDatasetId()); + List noApprovedDARs = + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset.getDatasetId()); assertTrue(noApprovedDARs.isEmpty()); } @@ -950,8 +837,8 @@ void testFindAllDraftsByUserIdArchived() { DataAccessRequest testDar = createDraftDAR(user); dataAccessRequestDAO.archiveByReferenceIds(List.of(testDar.getReferenceId())); - List returnedDARs = dataAccessRequestDAO.findAllDraftsByUserId( - user.getUserId()); + List returnedDARs = + dataAccessRequestDAO.findAllDraftsByUserId(user.getUserId()); assertTrue(returnedDARs.isEmpty()); } @@ -963,8 +850,8 @@ void testFindByReferenceIdArchived() { User user = createUserWithInstitution(); DataAccessRequest testDar = createDAR(user, dataset, darCode); dataAccessRequestDAO.archiveByReferenceIds(List.of(testDar.getReferenceId())); - DataAccessRequest returnedDAR = dataAccessRequestDAO.findByReferenceId( - testDar.getReferenceId()); + DataAccessRequest returnedDAR = + dataAccessRequestDAO.findByReferenceId(testDar.getReferenceId()); assertNull(returnedDAR); } @@ -981,8 +868,9 @@ void testFindByReferenceIdsArchived() { dataAccessRequestDAO.archiveByReferenceIds(List.of(testDar1.getReferenceId())); dataAccessRequestDAO.archiveByReferenceIds(List.of(testDar2.getReferenceId())); - List returnedDAR = dataAccessRequestDAO.findByReferenceIds( - List.of(testDar1.getReferenceId(), testDar2.getReferenceId())); + List returnedDAR = + dataAccessRequestDAO.findByReferenceIds( + List.of(testDar1.getReferenceId(), testDar2.getReferenceId())); assertTrue(returnedDAR.isEmpty()); } @@ -990,9 +878,12 @@ void testFindByReferenceIdsArchived() { void createProgressReport() { DarCollection darCollection = createDarCollection(); DataAccessRequest dar = new ArrayList<>(darCollection.getDars().values()).get(0); - DataAccessRequest progressReport = createProgressReport(createUser().getEraCommonsId(), dar.getUserId(), - darCollection.getDarCollectionId(), - dar.getId()); + DataAccessRequest progressReport = + createProgressReport( + createUser().getEraCommonsId(), + dar.getUserId(), + darCollection.getDarCollectionId(), + dar.getId()); assertNotNull(progressReport); assertEquals(dar.getId(), progressReport.getParentId()); @@ -1014,14 +905,17 @@ void insertProgressReport_WithExistingProgressReport() { Integer userId = dar.getUserId(); Integer darCollectionId = darCollection.getDarCollectionId(); Integer id = dar.getId(); - DataAccessRequest progressReport = createProgressReport(dar.getEraCommonsId(), userId, darCollectionId, id); + DataAccessRequest progressReport = + createProgressReport(dar.getEraCommonsId(), userId, darCollectionId, id); assertNotNull(progressReport); // Insert of second progress report should fail. - assertThrows(JdbiException.class, () -> createProgressReport(eraCommonsId, userId, darCollectionId, id)); + assertThrows( + JdbiException.class, () -> createProgressReport(eraCommonsId, userId, darCollectionId, id)); // Check that the first progress report is not updated. - DataAccessRequest firstProgressReport = dataAccessRequestDAO.findByReferenceId(progressReport.getReferenceId()); + DataAccessRequest firstProgressReport = + dataAccessRequestDAO.findByReferenceId(progressReport.getReferenceId()); assertEquals(progressReport.id, firstProgressReport.id); } @@ -1031,16 +925,20 @@ void testFindAgedDARsByEmailTypeOlderThanInterval() { Integer userOneId = userOne.getUserId(); Integer collectionOneId = createDarCollection(userOneId); Integer collectionTwoId = createDarCollection(userOneId); - createDataAccessRequest(collectionOneId, userOneId, - new Date(Instant.now().minus(360, - ChronoUnit.DAYS).toEpochMilli())); - createDataAccessRequest(collectionTwoId, userOneId, - new Date(Instant.now().minus(15, - ChronoUnit.DAYS).toEpochMilli())); - - List dars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), - EXPIRE_WARN_INTERVAL, Timestamp.from(Instant.now().minus(365, ChronoUnit.DAYS))); + createDataAccessRequest( + collectionOneId, + userOneId, + new Date(Instant.now().minus(360, ChronoUnit.DAYS).toEpochMilli())); + createDataAccessRequest( + collectionTwoId, + userOneId, + new Date(Instant.now().minus(15, ChronoUnit.DAYS).toEpochMilli())); + + List dars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + EXPIRE_WARN_INTERVAL, + Timestamp.from(Instant.now().minus(365, ChronoUnit.DAYS))); assertFalse(dars.isEmpty()); assertEquals(1, dars.size()); } @@ -1051,30 +949,35 @@ void testFindAgedDARsByEmailTypeOlderThanIntervalSkipsEntriesBeforeNotBefore() { Integer userOneId = userOne.getUserId(); Integer collectionOneId = createDarCollection(userOneId); Integer collectionTwoId = createDarCollection(userOneId); - createDataAccessRequest(collectionOneId, userOneId, - Date.from(Instant.now().minus(360, - ChronoUnit.DAYS))); - createDataAccessRequest(collectionTwoId, userOneId, - Date.from(Instant.now().minus(15, - ChronoUnit.DAYS))); - - List dars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), - EXPIRE_WARN_INTERVAL, Timestamp.from(Instant.now().minus(2, ChronoUnit.DAYS))); + createDataAccessRequest( + collectionOneId, userOneId, Date.from(Instant.now().minus(360, ChronoUnit.DAYS))); + createDataAccessRequest( + collectionTwoId, userOneId, Date.from(Instant.now().minus(15, ChronoUnit.DAYS))); + + List dars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + EXPIRE_WARN_INTERVAL, + Timestamp.from(Instant.now().minus(2, ChronoUnit.DAYS))); assertTrue(dars.isEmpty()); } @Test void testFindAgedDARsByEmailTypeOlderThanIntervalNoneInRange() { DarCollection darCollection = createDarCollection(); - darCollection.getDars().keySet().forEach(referenceId -> - dataAccessRequestDAO.updateDraftToSubmittedForCollection(darCollection.getDarCollectionId(), - referenceId) - ); + darCollection + .getDars() + .keySet() + .forEach( + referenceId -> + dataAccessRequestDAO.updateDraftToSubmittedForCollection( + darCollection.getDarCollectionId(), referenceId)); // query far enough into the past so slight clock variations do not matter for this test - List dars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), EXPIRE_WARN_INTERVAL, - Timestamp.from(Instant.now().minus(365, ChronoUnit.DAYS))); + List dars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + EXPIRE_WARN_INTERVAL, + Timestamp.from(Instant.now().minus(365, ChronoUnit.DAYS))); assertTrue(dars.isEmpty()); } @@ -1088,26 +991,29 @@ void testFindAgedDARsByEmailTypeOlderThanIntervalWithExpiringEntries() { Dataset datasetTwo = createDataset(userTwoId); Integer collectionOneId = createDarCollection(userOneId); Integer collectionTwoId = createDarCollection(userTwoId); - DataAccessRequest darOne = createDataAccessRequest(collectionOneId, userOneId, - Date.from(Instant.now().minus(365, - ChronoUnit.DAYS))); + DataAccessRequest darOne = + createDataAccessRequest( + collectionOneId, userOneId, Date.from(Instant.now().minus(365, ChronoUnit.DAYS))); DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId, new Date()); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); - List dars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), EXPIRE_WARN_INTERVAL, - Timestamp.from(Instant.now().minus(366, ChronoUnit.DAYS))); + List dars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + EXPIRE_WARN_INTERVAL, + Timestamp.from(Instant.now().minus(366, ChronoUnit.DAYS))); assertNotNull(dars); assertEquals(1, dars.size()); - dars.forEach(dar -> { - assertEquals(userOne.getUserId(), dar.getUserId()); - assertEquals(darOne.getReferenceId(), dar.getReferenceId()); - assertNotNull(dar.getDarCode()); - }); + dars.forEach( + dar -> { + assertEquals(userOne.getUserId(), dar.getUserId()); + assertEquals(darOne.getReferenceId(), dar.getReferenceId()); + assertNotNull(dar.getDarCode()); + }); } @Test @@ -1120,31 +1026,34 @@ void testFindAgedDARsByEmailTypeOlderThanIntervalWithExpiringEntriesFromMultiple Dataset datasetThree = createDataset(userTwoId); Integer collectionOneId = createDarCollection(userOneId); Integer collectionTwoId = createDarCollection(userTwoId); - DataAccessRequest darOne = createDataAccessRequest(collectionOneId, userOneId, - Date.from(Instant.now().minus(365, - ChronoUnit.DAYS))); - DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId, - Date.from(Instant.now().minus(350, - ChronoUnit.DAYS))); + DataAccessRequest darOne = + createDataAccessRequest( + collectionOneId, userOneId, Date.from(Instant.now().minus(365, ChronoUnit.DAYS))); + DataAccessRequest darTwo = + createDataAccessRequest( + collectionTwoId, userTwoId, Date.from(Instant.now().minus(350, ChronoUnit.DAYS))); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetThree.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetThree.getDatasetId()); - List dars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), EXPIRE_WARN_INTERVAL, - Timestamp.from(Instant.now().minus(366, ChronoUnit.DAYS))); + List dars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + EXPIRE_WARN_INTERVAL, + Timestamp.from(Instant.now().minus(366, ChronoUnit.DAYS))); assertNotNull(dars); assertEquals(2, dars.size()); - dars.forEach(dar -> { - assertNotNull(dar.getUserId()); - assertNotNull(dar.getReferenceId()); - assertNotNull(dar.getExpiresAt()); - assertNotNull(dar.getDarCode()); - }); + dars.forEach( + dar -> { + assertNotNull(dar.getUserId()); + assertNotNull(dar.getReferenceId()); + assertNotNull(dar.getExpiresAt()); + assertNotNull(dar.getDarCode()); + }); } @Test @@ -1157,20 +1066,22 @@ void testFindAgedDARsByEmailTypeOlderThanIntervalWithNoExpiringEntries() { Dataset datasetTwo = createDataset(userTwoId); Integer collectionOneId = createDarCollection(userOneId); Integer collectionTwoId = createDarCollection(userTwoId); - DataAccessRequest darOne = createDataAccessRequest(collectionOneId, userOneId, - Date.from(Instant.now().minus(30, - ChronoUnit.DAYS))); - DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId, - Date.from(Instant.now().minus(30, - ChronoUnit.DAYS))); + DataAccessRequest darOne = + createDataAccessRequest( + collectionOneId, userOneId, Date.from(Instant.now().minus(30, ChronoUnit.DAYS))); + DataAccessRequest darTwo = + createDataAccessRequest( + collectionTwoId, userTwoId, Date.from(Instant.now().minus(30, ChronoUnit.DAYS))); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); - List dars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), EXPIRE_WARN_INTERVAL, - Timestamp.from(Instant.now().minus(366, ChronoUnit.DAYS))); + List dars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + EXPIRE_WARN_INTERVAL, + Timestamp.from(Instant.now().minus(366, ChronoUnit.DAYS))); assertNotNull(dars); assertEquals(0, dars.size()); @@ -1188,36 +1099,48 @@ void testFindAgedDARsByEmailTypeOlderThanIntervalExpiringEntriesDoesNotRepeatIfE Dataset datasetThree = createDataset(userTwoId); Integer collectionOneId = createDarCollection(userOneId); Integer collectionTwoId = createDarCollection(userTwoId); - DataAccessRequest darOne = createDataAccessRequest(collectionOneId, userOneId, - Date.from(Instant.now().minus(365, - ChronoUnit.DAYS))); - DataAccessRequest darTwo = createDataAccessRequest(collectionTwoId, userTwoId, - Date.from(Instant.now().minus(366, - ChronoUnit.DAYS))); + DataAccessRequest darOne = + createDataAccessRequest( + collectionOneId, userOneId, Date.from(Instant.now().minus(365, ChronoUnit.DAYS))); + DataAccessRequest darTwo = + createDataAccessRequest( + collectionTwoId, userTwoId, Date.from(Instant.now().minus(366, ChronoUnit.DAYS))); dataAccessRequestDAO.insertDARDatasetRelation(darOne.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetTwo.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(darTwo.getReferenceId(), - datasetThree.getDatasetId()); - mailMessageDAO.insert(darOne.getReferenceId(), null, userOneId, - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), Instant.now(), "hello world!", - "success", 200, Instant.now()); - List dars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), EXPIRE_WARN_INTERVAL, - Timestamp.from(Instant.now().minus(367, ChronoUnit.DAYS))); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetTwo.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + darTwo.getReferenceId(), datasetThree.getDatasetId()); + mailMessageDAO.insert( + darOne.getReferenceId(), + null, + userOneId, + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + Instant.now(), + "hello world!", + "success", + 200, + Instant.now()); + List dars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRATION_REMINDER.getTypeInt(), + EXPIRE_WARN_INTERVAL, + Timestamp.from(Instant.now().minus(367, ChronoUnit.DAYS))); assertNotNull(dars); assertEquals(1, dars.size()); - dars.forEach(dar -> { - assertEquals(userTwo.getUserId(), dar.getUserId()); - assertEquals(darTwo.getReferenceId(), dar.getReferenceId()); - assertNotNull(dar.getDarCode()); - }); - - List expiredDars = dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( - EmailType.DAR_EXPIRED.getTypeInt(), EXPIRE_NOTICE_INTERVAL, - Timestamp.from(Instant.now().minus(367, ChronoUnit.DAYS))); + dars.forEach( + dar -> { + assertEquals(userTwo.getUserId(), dar.getUserId()); + assertEquals(darTwo.getReferenceId(), dar.getReferenceId()); + assertNotNull(dar.getDarCode()); + }); + + List expiredDars = + dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval( + EmailType.DAR_EXPIRED.getTypeInt(), + EXPIRE_NOTICE_INTERVAL, + Timestamp.from(Instant.now().minus(367, ChronoUnit.DAYS))); assertNotNull(expiredDars); assertEquals(2, expiredDars.size()); } @@ -1228,10 +1151,12 @@ void testMarkSOApprovalOfCloseout() { User signingOfficial = createUserWithInstitution(); Dataset dataset = createDataset(user.getUserId()); Integer collection = createDarCollection(user.getUserId()); - DataAccessRequest darToStore = createDataAccessRequest(collection, user.getUserId(), - Date.from(Instant.now())); - dataAccessRequestDAO.insertDARDatasetRelation(darToStore.getReferenceId(), dataset.getDatasetId()); - dataAccessRequestDAO.updateDarCloseoutSO(signingOfficial.getUserId(), darToStore.getReferenceId()); + DataAccessRequest darToStore = + createDataAccessRequest(collection, user.getUserId(), Date.from(Instant.now())); + dataAccessRequestDAO.insertDARDatasetRelation( + darToStore.getReferenceId(), dataset.getDatasetId()); + dataAccessRequestDAO.updateDarCloseoutSO( + signingOfficial.getUserId(), darToStore.getReferenceId()); DataAccessRequest dar = dataAccessRequestDAO.findByReferenceId(darToStore.getReferenceId()); @@ -1250,8 +1175,8 @@ private Dataset createDARDAOTestDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); List list = new ArrayList<>(); DatasetProperty dsp = new DatasetProperty(); dsp.setDatasetId(id); @@ -1273,39 +1198,35 @@ private DataAccessRequest createDataAccessRequest(Integer userId, Integer collec String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDataAccessRequest( - collectionId, - referenceId, - userId, - now, now, now, - data, - randomAlphabetic(10)); + collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } - private DataAccessRequest createProgressReport(String eraCommonsId, Integer userId, Integer collectionId, - Integer parentId) { - DataAccessRequestData data = createDataAccessRequestData( - ); + private DataAccessRequest createProgressReport( + String eraCommonsId, Integer userId, Integer collectionId, Integer parentId) { + DataAccessRequestData data = createDataAccessRequestData(); String referenceId = UUID.randomUUID().toString(); dataAccessRequestDAO.insertProgressReport( - parentId, - collectionId, - referenceId, - userId, - data, - eraCommonsId); + parentId, collectionId, referenceId, userId, data, eraCommonsId); return dataAccessRequestDAO.findByReferenceId(referenceId); } - private static DataAccessRequest createDataAccessRequest(Integer collectionId, Integer userId, - Date submissionDate) { + private static DataAccessRequest createDataAccessRequest( + Integer collectionId, Integer userId, Date submissionDate) { String referenceId = UUID.randomUUID().toString(); Date createDate = new Date(); DataAccessRequestData data = new DataAccessRequestData(); data.setProjectTitle("Project Title: " + randomAlphabetic(50)); data.setStatus("test"); - dataAccessRequestDAO.insertDataAccessRequest(collectionId, referenceId, userId, createDate, - submissionDate, new Date(), data, randomAlphabetic(10)); + dataAccessRequestDAO.insertDataAccessRequest( + collectionId, + referenceId, + userId, + createDate, + submissionDate, + new Date(), + data, + randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -1317,13 +1238,13 @@ private Integer createDarCollection(Integer createUserId) { private DarCollection createDarCollection() { User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 10000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); Dataset dataset = createDataset(); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset.getDatasetId()); - Election cancelled = createCancelledAccessElection(dar.getReferenceId(), - dataset.getDatasetId()); + Election cancelled = + createCancelledAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Election access = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); createFinalVote(user.getUserId(), cancelled.getElectionId()); createFinalVote(user.getUserId(), access.getElectionId()); @@ -1333,13 +1254,13 @@ private DarCollection createDarCollection() { } private Election createCancelledAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.CANCELED.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.CANCELED.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } @@ -1349,16 +1270,21 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } private Dataset createDataset(Integer userId) { - Integer datasetId = datasetDAO.insertDataset(randomAlphabetic(20), - new Timestamp(System.currentTimeMillis()), userId, null, - new DataUseBuilder().setGeneralUse(true).build().toString(), null); + Integer datasetId = + datasetDAO.insertDataset( + randomAlphabetic(20), + new Timestamp(System.currentTimeMillis()), + userId, + null, + new DataUseBuilder().setGeneralUse(true).build().toString(), + null); return datasetDAO.findDatasetById(datasetId); } @@ -1380,12 +1306,7 @@ private DataAccessRequest createDraftDataAccessRequest() { String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDraftDataAccessRequest( - referenceId, - user.getUserId(), - now, - now, - data - ); + referenceId, user.getUserId(), now, now, data); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -1399,13 +1320,13 @@ private Vote createVote(Integer userId, Integer electionId, VoteType voteType) { } private Election createDataAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DataUseParserTest.java b/src/test/java/org/broadinstitute/consent/http/db/DataUseParserTest.java index 6265994997..401d1b4650 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DataUseParserTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DataUseParserTest.java @@ -43,5 +43,4 @@ void testParseEmptyDataUse() { DataUse dataUse = dataUseParser.parseDataUse(""); assertNull(dataUse); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DatasetAuthorizationReaderDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DatasetAuthorizationReaderDAOTest.java index 2f68328c59..6f34840c9d 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DatasetAuthorizationReaderDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DatasetAuthorizationReaderDAOTest.java @@ -1,8 +1,8 @@ package org.broadinstitute.consent.http.db; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.Timestamp; import java.util.ArrayList; @@ -22,9 +22,12 @@ void testInsertDatasetAuthorizationRecord() { User testUser = createUserWithInstitution(); User operator = createUserWithInstitution(); int datasetId = createDataset(testUser); - long authRecordId = datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId, testUser.getUserId(), operator.getUserId()); + long authRecordId = + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId, testUser.getUserId(), operator.getUserId()); assertTrue(authRecordId > 0); - List authorizationReaderList = datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId); + List authorizationReaderList = + datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId); assertNotNull(authorizationReaderList); assertEquals(1, authorizationReaderList.size()); DatasetAuthorizationReader authorizationReader = authorizationReaderList.get(0); @@ -32,7 +35,8 @@ void testInsertDatasetAuthorizationRecord() { assertEquals(testUser.getUserId().intValue(), authorizationReader.userId()); assertEquals(operator.getUserId().intValue(), authorizationReader.createdBy()); datasetAuthorizationReaderDAO.deleteByDatasetId(datasetId); - List authorizationReaderList2 = datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId); + List authorizationReaderList2 = + datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId); assertNotNull(authorizationReaderList2); assertEquals(0, authorizationReaderList2.size()); } @@ -43,18 +47,26 @@ void testDeleteByDatasetAndUserId() { User operator = createUserWithInstitution(); int datasetId1 = createDataset(testUser); int datasetId2 = createDataset(testUser); - datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId1, testUser.getUserId(), operator.getUserId()); - datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId2, testUser.getUserId(), operator.getUserId()); - assertEquals(1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); - assertEquals(1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId1, testUser.getUserId(), operator.getUserId()); + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId2, testUser.getUserId(), operator.getUserId()); + assertEquals( + 1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); + assertEquals( + 1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); datasetAuthorizationReaderDAO.deleteByDatasetAndUserId(datasetId1, testUser.getUserId()); - assertEquals(0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); - assertEquals(1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); + assertEquals( + 0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); + assertEquals( + 1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); datasetAuthorizationReaderDAO.deleteByDatasetAndUserId(datasetId2, testUser.getUserId()); - assertEquals(0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); - assertEquals(0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); + assertEquals( + 0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); + assertEquals( + 0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); } @Test @@ -64,27 +76,37 @@ void testDeleteByDatasetId() { User operator = createUserWithInstitution(); int datasetId1 = createDataset(testUser); int datasetId2 = createDataset(testUser); - long record1 = datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId1, testUser.getUserId(), operator.getUserId()); - datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId2, testUser.getUserId(), operator.getUserId()); - datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId1, testUser2.getUserId(), operator.getUserId()); - - DatasetAuthorizationReader authReader = datasetAuthorizationReaderDAO.findAuthorizedReaderByRecordId(record1); + long record1 = + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId1, testUser.getUserId(), operator.getUserId()); + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId2, testUser.getUserId(), operator.getUserId()); + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId1, testUser2.getUserId(), operator.getUserId()); + + DatasetAuthorizationReader authReader = + datasetAuthorizationReaderDAO.findAuthorizedReaderByRecordId(record1); assertNotNull(authReader); assertEquals(record1, authReader.id()); assertEquals(datasetId1, authReader.datasetId()); assertEquals(testUser.getUserId().intValue(), authReader.userId()); assertEquals(operator.getUserId().intValue(), authReader.createdBy()); - assertEquals(2, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); - DatasetAuthorizationReader reader = datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetIdAndUserId(datasetId1, testUser.getUserId()); + assertEquals( + 2, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); + DatasetAuthorizationReader reader = + datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetIdAndUserId( + datasetId1, testUser.getUserId()); assertNotNull(reader); assertEquals(record1, reader.id()); assertEquals(datasetId1, reader.datasetId()); assertEquals(testUser.getUserId().intValue(), reader.userId()); assertEquals(operator.getUserId().intValue(), reader.createdBy()); datasetAuthorizationReaderDAO.deleteByDatasetId(datasetId1); - assertEquals(0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); + assertEquals( + 0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); - assertEquals(1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); + assertEquals( + 1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); } @Test @@ -95,16 +117,22 @@ void testDeleteByUserId() { int datasetId1 = createDataset(testUser1); int datasetId2 = createDataset(testUser2); - datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId1, testUser1.getUserId(), operator.getUserId()); - datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId2, testUser1.getUserId(), operator.getUserId()); - datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(datasetId2, testUser2.getUserId(), operator.getUserId()); - - assertEquals(1,datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); - assertEquals(2,datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId1, testUser1.getUserId(), operator.getUserId()); + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId2, testUser1.getUserId(), operator.getUserId()); + datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + datasetId2, testUser2.getUserId(), operator.getUserId()); + + assertEquals( + 1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); + assertEquals( + 2, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); datasetAuthorizationReaderDAO.deleteByUserId(testUser1.getUserId()); - assertEquals(0,datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); - assertEquals(1,datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); - + assertEquals( + 0, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId1).size()); + assertEquals( + 1, datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetId(datasetId2).size()); } private int createDataset(User user) { @@ -112,8 +140,8 @@ private int createDataset(User user) { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return id; } @@ -128,4 +156,4 @@ private void createDatasetProperties(Integer datasetId) { list.add(dsp); datasetDAO.insertDatasetProperties(list); } -} \ No newline at end of file +} diff --git a/src/test/java/org/broadinstitute/consent/http/db/DatasetDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DatasetDAOTest.java index b8bc82b7f5..3f95ee0ff1 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DatasetDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DatasetDAOTest.java @@ -62,12 +62,9 @@ void testFindDatasetWithoutFSOInformation() { Dataset dataset = insertDataset(); Study study = insertStudyWithProperties(); datasetDAO.updateStudyId(dataset.getDatasetId(), study.getStudyId()); - createFileStorageObject(study.getUuid().toString(), - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); + createFileStorageObject(study.getUuid().toString(), FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); createFileStorageObject( - dataset.getDatasetId().toString(), - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION - ); + dataset.getDatasetId().toString(), FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); Dataset foundDataset = datasetDAO.findDatasetWithoutFSOInformation(dataset.getDatasetId()); // Explicitly check queried entities assertNotNull(foundDataset.getProperties()); @@ -86,12 +83,9 @@ void testFindMinimalDatasetByAlias() { Dataset dataset = insertDataset(); Study study = insertStudyWithProperties(); datasetDAO.updateStudyId(dataset.getDatasetId(), study.getStudyId()); - createFileStorageObject(study.getUuid().toString(), - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); + createFileStorageObject(study.getUuid().toString(), FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); createFileStorageObject( - dataset.getDatasetId().toString(), - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION - ); + dataset.getDatasetId().toString(), FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); Dataset foundDataset = datasetDAO.findMinimalDatasetByAlias(dataset.getAlias()); // Explicitly check queried entities assertNotNull(foundDataset.getProperties()); @@ -201,8 +195,8 @@ void testFindDatasetsByAlias() { Dataset dataset1 = insertDataset(); Dataset dataset2 = insertDataset(); - List foundDatasets = datasetDAO.findDatasetsByAlias( - List.of(dataset1.getAlias(), dataset2.getAlias())); + List foundDatasets = + datasetDAO.findDatasetsByAlias(List.of(dataset1.getAlias(), dataset2.getAlias())); List foundDatasetIds = foundDatasets.stream().map(Dataset::getDatasetId).toList(); assertNotNull(foundDatasets); assertTrue( @@ -215,28 +209,21 @@ void testGetNIHInstitutionalFile() { // create unrelated file with the same id as dataset id but different category, timestamp before createFileStorageObject( - dataset.getDatasetId().toString(), - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN - ); + dataset.getDatasetId().toString(), FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - FileStorageObject nihFile = createFileStorageObject( - dataset.getDatasetId().toString(), - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION - ); + FileStorageObject nihFile = + createFileStorageObject( + dataset.getDatasetId().toString(), FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); // create unrelated files with timestamp later than the NIH file: one attached to dataset, one // completely separate from the dataset. ensures that the Mapper is selecting only the NIH file. createFileStorageObject(); - createFileStorageObject( - dataset.getDatasetId().toString(), - FileCategory.DATA_USE_LETTER - ); + createFileStorageObject(dataset.getDatasetId().toString(), FileCategory.DATA_USE_LETTER); Dataset found = datasetDAO.findDatasetById(dataset.getDatasetId()); assertEquals(nihFile, found.getNihInstitutionalCertificationFile()); - assertEquals(nihFile.getBlobId(), - found.getNihInstitutionalCertificationFile().getBlobId()); + assertEquals(nihFile.getBlobId(), found.getNihInstitutionalCertificationFile().getBlobId()); } @Test @@ -248,25 +235,25 @@ void testGetNIHInstitutionalFile_AlwaysLatestUpdated() { String gcsFileUri = randomAlphabetic(10); User createUser = createUser(); - Integer nihFileIdCreatedFirstUpdatedSecond = fileStorageObjectDAO.insertNewFile( - fileName, - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), - bucketName, - gcsFileUri, - dataset.getDatasetId().toString(), - createUser.getUserId(), - Instant.ofEpochMilli(100) - ); - - Integer nihFileIdCreatedSecondUpdatedFirst = fileStorageObjectDAO.insertNewFile( - fileName, - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), - bucketName, - gcsFileUri, - dataset.getDatasetId().toString(), - createUser.getUserId(), - Instant.ofEpochMilli(110) - ); + Integer nihFileIdCreatedFirstUpdatedSecond = + fileStorageObjectDAO.insertNewFile( + fileName, + FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), + bucketName, + gcsFileUri, + dataset.getDatasetId().toString(), + createUser.getUserId(), + Instant.ofEpochMilli(100)); + + Integer nihFileIdCreatedSecondUpdatedFirst = + fileStorageObjectDAO.insertNewFile( + fileName, + FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), + bucketName, + gcsFileUri, + dataset.getDatasetId().toString(), + createUser.getUserId(), + Instant.ofEpochMilli(110)); User updateUser = createUser(); @@ -287,7 +274,8 @@ void testGetNIHInstitutionalFile_AlwaysLatestUpdated() { Dataset found = datasetDAO.findDatasetById(dataset.getDatasetId()); // returns last updated file - assertEquals(nihFileIdCreatedFirstUpdatedSecond, + assertEquals( + nihFileIdCreatedFirstUpdatedSecond, found.getNihInstitutionalCertificationFile().getFileStorageObjectId()); } @@ -300,15 +288,15 @@ void testGetNIHInstitutionalFile_AlwaysLatestCreated() { String gcsFileUri = randomAlphabetic(10); User createUser = createUser(); - Integer nihFileIdCreatedFirst = fileStorageObjectDAO.insertNewFile( - fileName, - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), - bucketName, - gcsFileUri, - dataset.getDatasetId().toString(), - createUser.getUserId(), - Instant.ofEpochMilli(100) - ); + Integer nihFileIdCreatedFirst = + fileStorageObjectDAO.insertNewFile( + fileName, + FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), + bucketName, + gcsFileUri, + dataset.getDatasetId().toString(), + createUser.getUserId(), + Instant.ofEpochMilli(100)); User updateUser = createUser(); @@ -319,20 +307,21 @@ void testGetNIHInstitutionalFile_AlwaysLatestCreated() { updateUser.getUserId(), Instant.ofEpochMilli(120)); - Integer nihFileIdCreatedSecond = fileStorageObjectDAO.insertNewFile( - fileName, - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), - bucketName, - gcsFileUri, - dataset.getDatasetId().toString(), - createUser.getUserId(), - Instant.ofEpochMilli(130) - ); + Integer nihFileIdCreatedSecond = + fileStorageObjectDAO.insertNewFile( + fileName, + FileCategory.NIH_INSTITUTIONAL_CERTIFICATION.getValue(), + bucketName, + gcsFileUri, + dataset.getDatasetId().toString(), + createUser.getUserId(), + Instant.ofEpochMilli(130)); Dataset found = datasetDAO.findDatasetById(dataset.getDatasetId()); // returns last updated file - assertEquals(nihFileIdCreatedSecond, + assertEquals( + nihFileIdCreatedSecond, found.getNihInstitutionalCertificationFile().getFileStorageObjectId()); } @@ -340,18 +329,14 @@ void testGetNIHInstitutionalFile_AlwaysLatestCreated() { void testGetNIHInstitutionalFile_NotDeleted() { Dataset dataset = insertDataset(); - FileStorageObject nihFile = createFileStorageObject( - dataset.getDatasetId().toString(), - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION - ); + FileStorageObject nihFile = + createFileStorageObject( + dataset.getDatasetId().toString(), FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); User deleteUser = createUser(); fileStorageObjectDAO.deleteFileById( - nihFile.getFileStorageObjectId(), - deleteUser.getUserId(), - Instant.now() - ); + nihFile.getFileStorageObjectId(), deleteUser.getUserId(), Instant.now()); Dataset found = datasetDAO.findDatasetById(dataset.getDatasetId()); @@ -362,10 +347,11 @@ void testGetNIHInstitutionalFile_NotDeleted() { void testGetDictionaryTerms() { List terms = datasetDAO.getDictionaryTerms(); assertFalse(terms.isEmpty()); - terms.forEach(t -> { - assertNotNull(t.getKeyId()); - assertNotNull(t.getKey()); - }); + terms.forEach( + t -> { + assertNotNull(t.getKeyId()); + assertNotNull(t.getKey()); + }); } @Test @@ -439,45 +425,46 @@ void testUpdateDatasetProperty() { Dataset d = insertDataset(); Set properties = datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty originalProperty = properties.stream().toList().get(0); - DatasetProperty newProperty = new DatasetProperty( - d.getDatasetId(), - 1, - "dataAccessCommitteeId", - "Updated Value", - PropertyType.String, new Date() - ); + DatasetProperty newProperty = + new DatasetProperty( + d.getDatasetId(), + 1, + "dataAccessCommitteeId", + "Updated Value", + PropertyType.String, + new Date()); List updatedProperties = new ArrayList<>(); updatedProperties.add(newProperty); - datasetDAO.updateDatasetProperty(d.getDatasetId(), updatedProperties.get(0).getPropertyKey(), + datasetDAO.updateDatasetProperty( + d.getDatasetId(), + updatedProperties.get(0).getPropertyKey(), updatedProperties.get(0).getPropertyValue().toString()); - Set returnedProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set returnedProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty returnedProperty = returnedProperties.stream().toList().get(0); - assertEquals(originalProperty.getPropertyKey(), - returnedProperty.getPropertyKey()); + assertEquals(originalProperty.getPropertyKey(), returnedProperty.getPropertyKey()); assertEquals(originalProperty.getPropertyId(), returnedProperty.getPropertyId()); - assertNotEquals(originalProperty.getPropertyValue(), - returnedProperty.getPropertyValue()); + assertNotEquals(originalProperty.getPropertyValue(), returnedProperty.getPropertyValue()); } @Test void testCreateNumberTypedDatasetProperty() { Dataset d = insertDataset(); - Set oldProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set oldProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty propertyToDelete = new ArrayList<>(oldProperties).get(0); datasetDAO.deleteDatasetPropertyByKey(d.getDatasetId(), propertyToDelete.getPropertyKey()); - List newProps = List.of( - new DatasetProperty( - d.getDatasetId(), - 1, - "dataAccessCommitteeId", - "10", - PropertyType.Number, - new Date()) - ); + List newProps = + List.of( + new DatasetProperty( + d.getDatasetId(), + 1, + "dataAccessCommitteeId", + "10", + PropertyType.Number, + new Date())); datasetDAO.insertDatasetProperties(newProps); Dataset dWithProps = datasetDAO.findDatasetById(d.getDatasetId()); @@ -494,23 +481,22 @@ void testCreateDateTypedDatasetProperty() { Dataset d = insertDataset(); Instant date = Instant.now(); - Set oldProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set oldProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty propertyToDelete = new ArrayList<>(oldProperties).get(0); datasetDAO.deleteDatasetPropertyByKey(d.getDatasetId(), propertyToDelete.getPropertyKey()); - DatasetProperty propToAdd = new DatasetProperty( - d.getDatasetId(), - 1, - "dataAccessCommitteeId", - date.toString(), - PropertyType.Date, - new Date()); + DatasetProperty propToAdd = + new DatasetProperty( + d.getDatasetId(), + 1, + "dataAccessCommitteeId", + date.toString(), + PropertyType.Date, + new Date()); propToAdd.setSchemaProperty("date"); - List newProps = List.of( - propToAdd - ); + List newProps = List.of(propToAdd); datasetDAO.insertDatasetProperties(newProps); Set props = datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); @@ -526,20 +512,20 @@ void testCreateBooleanTypedDatasetProperty() { Dataset d = insertDataset(); Boolean bool = Boolean.FALSE; - Set oldProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set oldProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty propertyToDelete = new ArrayList<>(oldProperties).get(0); datasetDAO.deleteDatasetPropertyByKey(d.getDatasetId(), propertyToDelete.getPropertyKey()); - List newProps = List.of( - new DatasetProperty( - d.getDatasetId(), - 1, - "dataAccessCommitteeId", - bool.toString(), - PropertyType.Boolean, - new Date()) - ); + List newProps = + List.of( + new DatasetProperty( + d.getDatasetId(), + 1, + "dataAccessCommitteeId", + bool.toString(), + PropertyType.Boolean, + new Date())); datasetDAO.insertDatasetProperties(newProps); Dataset dWithProps = datasetDAO.findDatasetById(d.getDatasetId()); @@ -557,20 +543,20 @@ void testCreateJsonTypedDatasetProperty() { JsonObject jsonObject = new JsonObject(); jsonObject.add("test", new JsonObject()); - Set oldProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set oldProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty propertyToDelete = new ArrayList<>(oldProperties).get(0); datasetDAO.deleteDatasetPropertyByKey(d.getDatasetId(), propertyToDelete.getPropertyKey()); - List newProps = List.of( - new DatasetProperty( - d.getDatasetId(), - 1, - "dataAccessCommitteeId", - jsonObject.toString(), - PropertyType.Json, - new Date()) - ); + List newProps = + List.of( + new DatasetProperty( + d.getDatasetId(), + 1, + "dataAccessCommitteeId", + jsonObject.toString(), + PropertyType.Json, + new Date())); datasetDAO.insertDatasetProperties(newProps); Dataset dWithProps = datasetDAO.findDatasetById(d.getDatasetId()); @@ -587,20 +573,20 @@ void testCreateStringTypedDatasetProperty() { Dataset d = insertDataset(); String value = "hi"; - Set oldProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set oldProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty propertyToDelete = new ArrayList<>(oldProperties).get(0); datasetDAO.deleteDatasetPropertyByKey(d.getDatasetId(), propertyToDelete.getPropertyKey()); - List newProps = List.of( - new DatasetProperty( - d.getDatasetId(), - 1, - "dataAccessCommitteeId", - value, - PropertyType.String, - new Date()) - ); + List newProps = + List.of( + new DatasetProperty( + d.getDatasetId(), + 1, + "dataAccessCommitteeId", + value, + PropertyType.String, + new Date())); datasetDAO.insertDatasetProperties(newProps); Dataset dWithProps = datasetDAO.findDatasetById(d.getDatasetId()); @@ -617,20 +603,15 @@ void testCreateTypedDatasetPropertyWithSchema() { Dataset d = insertDataset(); String schemaValue = "test test test test"; - Set oldProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set oldProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty propertyToDelete = new ArrayList<>(oldProperties).get(0); datasetDAO.deleteDatasetPropertyByKey(d.getDatasetId(), propertyToDelete.getPropertyKey()); - List newProps = List.of( - new DatasetProperty( - d.getDatasetId(), - 1, - schemaValue, - "asdf", - PropertyType.String, - new Date()) - ); + List newProps = + List.of( + new DatasetProperty( + d.getDatasetId(), 1, schemaValue, "asdf", PropertyType.String, new Date())); datasetDAO.insertDatasetProperties(newProps); Dataset dWithProps = datasetDAO.findDatasetById(d.getDatasetId()); @@ -647,17 +628,21 @@ void testDeleteDatasetPropertyByKey() { Set properties = datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); DatasetProperty propertyToDelete = properties.stream().toList().get(0); datasetDAO.deleteDatasetPropertyByKey(d.getDatasetId(), propertyToDelete.getPropertyKey()); - Set returnedProperties = datasetDAO.findDatasetPropertiesByDatasetId( - d.getDatasetId()); + Set returnedProperties = + datasetDAO.findDatasetPropertiesByDatasetId(d.getDatasetId()); assertNotEquals(properties.size(), returnedProperties.size()); } @Test void testFindAllDatasetIds() { - List insertedDatasetIds = IntStream.range(1, 5).mapToObj(i -> { - Dataset dataset = insertDataset(); - return dataset.getDatasetId(); - }).toList(); + List insertedDatasetIds = + IntStream.range(1, 5) + .mapToObj( + i -> { + Dataset dataset = insertDataset(); + return dataset.getDatasetId(); + }) + .toList(); List datasetIds = datasetDAO.findAllDatasetIds(); assertThat(datasetIds, contains(insertedDatasetIds.toArray())); } @@ -665,12 +650,14 @@ void testFindAllDatasetIds() { @Test void testZeroAliasValuesValid() { Dataset dataset = insertDataset(); - jdbi.useHandle(handle -> { - Update update = handle.createUpdate(" UPDATE dataset SET alias = 0 WHERE dataset_id = :dataset_id "); - update.bind("dataset_id", dataset.getDatasetId()); - update.execute(); - handle.commit(); - }); + jdbi.useHandle( + handle -> { + Update update = + handle.createUpdate(" UPDATE dataset SET alias = 0 WHERE dataset_id = :dataset_id "); + update.bind("dataset_id", dataset.getDatasetId()); + update.execute(); + handle.commit(); + }); Dataset updatedDataset = datasetDAO.findDatasetById(dataset.getDatasetId()); assertEquals(0, updatedDataset.getAlias()); updatedDataset.setDatasetIdentifier(); @@ -681,7 +668,7 @@ void testZeroAliasValuesValid() { void testFindAllStudyNames() { Dataset ds1 = insertDataset(); String ds1Name = randomAlphabetic(20); - createStringDatasetProperty(ds1.getDatasetId(), ds1Name); + createStringDatasetProperty(ds1.getDatasetId(), ds1Name); Dataset ds2 = insertDataset(); String ds2Name = randomAlphabetic(25); @@ -722,8 +709,8 @@ void testFindDatasetListByDacIds() { datasetDAO.updateDatasetDacId(datasetTwo.getDatasetId(), dacTwo.getDacId()); List datasetIds = List.of(dataset.getDatasetId(), datasetTwo.getDatasetId()); - List datasets = datasetDAO.findDatasetListByDacIds( - List.of(dac.getDacId(), dacTwo.getDacId())); + List datasets = + datasetDAO.findDatasetListByDacIds(List.of(dac.getDacId(), dacTwo.getDacId())); datasets.forEach(d -> assertTrue(datasetIds.contains(d.getDatasetId()))); } @@ -741,8 +728,8 @@ void testFindDatasetIdsByDacIds() { datasetDAO.updateDatasetDacId(datasetTwo.getDatasetId(), dacTwo.getDacId()); List datasetIds = List.of(dataset.getDatasetId(), datasetTwo.getDatasetId()); - List foundDatasetIds = datasetDAO.findDatasetIdsByDacIds( - List.of(dac.getDacId(), dacTwo.getDacId())); + List foundDatasetIds = + datasetDAO.findDatasetIdsByDacIds(List.of(dac.getDacId(), dacTwo.getDacId())); assertTrue(datasetIds.containsAll(foundDatasetIds)); assertFalse(foundDatasetIds.contains(datasetThree.getDatasetId())); } @@ -751,12 +738,13 @@ void testFindDatasetIdsByDacIds() { void testUpdateDatasetDataUse() { Dataset dataset = insertDataset(); DataUse oldDataUse = dataset.getDataUse(); - DataUse newDataUse = new DataUseBuilder() - .setGeneralUse(false) - .setNonProfitUse(true) - .setHmbResearch(true) - .setDiseaseRestrictions(List.of("DOID_1")) - .build(); + DataUse newDataUse = + new DataUseBuilder() + .setGeneralUse(false) + .setNonProfitUse(true) + .setHmbResearch(true) + .setDiseaseRestrictions(List.of("DOID_1")) + .build(); datasetDAO.updateDatasetDataUse(dataset.getDatasetId(), newDataUse.toString()); Dataset updated = datasetDAO.findDatasetById(dataset.getDatasetId()); @@ -792,9 +780,7 @@ void testUpdateDatasetUpdateUser() { Dataset dataset = insertDataset(); User user = createUser(); datasetDAO.updateDatasetUpdateUser( - dataset.getDatasetId(), - new Timestamp(new Date().getTime()), - user.getUserId()); + dataset.getDatasetId(), new Timestamp(new Date().getTime()), user.getUserId()); Dataset foundDataset = datasetDAO.findDatasetById(dataset.getDatasetId()); assertNotNull(foundDataset); assertEquals(user.getUserId(), foundDataset.getUpdateUserId()); @@ -805,34 +791,28 @@ void testUpdateDatasetUpdateUser() { void testUpdateDatasetApproval() { User updateUser = createUser(); Dataset dataset = insertDataset(); - datasetDAO.updateDatasetApproval(true, Instant.now(), updateUser.getUserId(), - dataset.getDatasetId()); + datasetDAO.updateDatasetApproval( + true, Instant.now(), updateUser.getUserId(), dataset.getDatasetId()); Dataset updatedDataset = datasetDAO.findDatasetById(dataset.getDatasetId()); assertNotNull(updatedDataset); assertTrue(updatedDataset.getDacApproval()); - datasetDAO.updateDatasetApproval(false, Instant.now(), updateUser.getUserId(), - dataset.getDatasetId()); + datasetDAO.updateDatasetApproval( + false, Instant.now(), updateUser.getUserId(), dataset.getDatasetId()); Dataset updatedDatasetAfterApprovalFalse = datasetDAO.findDatasetById(dataset.getDatasetId()); assertNotNull(updatedDatasetAfterApprovalFalse); - assertEquals(dataset.getDatasetId(), - updatedDatasetAfterApprovalFalse.getDatasetId()); + assertEquals(dataset.getDatasetId(), updatedDatasetAfterApprovalFalse.getDatasetId()); assertFalse(updatedDatasetAfterApprovalFalse.getDacApproval()); - } @Test void testInsertDatasetAudit() { Dataset d = insertDataset(); - DatasetAudit audit = new DatasetAudit( - d.getDatasetId(), - "objectid", - "name", - new Date(), - d.getCreateUserId(), - "action"); + DatasetAudit audit = + new DatasetAudit( + d.getDatasetId(), "objectid", "name", new Date(), d.getCreateUserId(), "action"); Integer auditId = datasetDAO.insertDatasetAudit(audit); - Optional auditResponse = Optional.ofNullable( - datasetDAO.findAuditsByDatasetId(d.getDatasetId()).get(0)); + Optional auditResponse = + Optional.ofNullable(datasetDAO.findAuditsByDatasetId(d.getDatasetId()).get(0)); assertTrue(auditResponse.isPresent()); assertEquals(auditId, auditResponse.get().getDataSetAuditId()); } @@ -861,8 +841,9 @@ void testDatasetWithStudy() { insertDataset(); // create unrelated datasets (for testing study's dataset ids) - FileStorageObject fso = createFileStorageObject(study.getUuid().toString(), - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); + FileStorageObject fso = + createFileStorageObject( + study.getUuid().toString(), FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); ds = datasetDAO.findDatasetById(ds.getDatasetId()); @@ -874,12 +855,12 @@ void testDatasetWithStudy() { assertEquals(study.getProperties().size(), ds.getStudy().getProperties().size()); // reducer caught FSO assertNotNull(fso); - assertEquals(fso.getFileStorageObjectId(), + assertEquals( + fso.getFileStorageObjectId(), ds.getStudy().getAlternativeDataSharingPlan().getFileStorageObjectId()); assertEquals(2, ds.getStudy().getDatasetIds().size()); assertTrue(ds.getStudy().getDatasetIds().contains(ds.getDatasetId())); - assertTrue( - ds.getStudy().getDatasetIds().contains(otherDsOnStudy.getDatasetId())); + assertTrue(ds.getStudy().getDatasetIds().contains(otherDsOnStudy.getDatasetId())); } @ParameterizedTest @@ -895,32 +876,59 @@ void testGetApprovedDatasets_user_without_library_card(String voteType) { Timestamp timestamp = new Timestamp(new Date().getTime()); Dac dac1 = insertDac(); - datasetDAO.updateDataset(dataset1.getDatasetId(), dataset1.getDatasetName(), timestamp, - user.getUserId(), dac1.getDacId()); - datasetDAO.updateDataset(dataset2.getDatasetId(), dataset2.getDatasetName(), timestamp, - user.getUserId(), dac1.getDacId()); + datasetDAO.updateDataset( + dataset1.getDatasetId(), + dataset1.getDatasetName(), + timestamp, + user.getUserId(), + dac1.getDacId()); + datasetDAO.updateDataset( + dataset2.getDatasetId(), + dataset2.getDatasetName(), + timestamp, + user.getUserId(), + dac1.getDacId()); Dac dac2 = insertDac(); - datasetDAO.updateDataset(dataset3.getDatasetId(), dataset3.getDatasetName(), timestamp, - user.getUserId(), dac2.getDacId()); - datasetDAO.updateDataset(dataset4.getDatasetId(), dataset4.getDatasetName(), timestamp, - user.getUserId(), dac2.getDacId()); + datasetDAO.updateDataset( + dataset3.getDatasetId(), + dataset3.getDatasetName(), + timestamp, + user.getUserId(), + dac2.getDacId()); + datasetDAO.updateDataset( + dataset4.getDatasetId(), + dataset4.getDatasetName(), + timestamp, + user.getUserId(), + dac2.getDacId()); DarCollection dar1 = createDarCollectionWithDatasets(dac1.getDacId(), user, List.of(dataset1)); - DarCollection dar2 = createDarCollectionWithDatasets(dac2.getDacId(), user, - List.of(dataset2, dataset3)); + DarCollection dar2 = + createDarCollectionWithDatasets(dac2.getDacId(), user, List.of(dataset2, dataset3)); DarCollection dar3 = createDarCollectionWithDatasets(dac2.getDacId(), user, List.of(dataset4)); List allDarCollections = List.of(dar1, dar2, dar3); - Map expectedFinalVotesForDatasets = Map.of(dataset1.getDatasetId(), false, - dataset2.getDatasetId(), false, dataset3.getDatasetId(), true, dataset4.getDatasetId(), - true); + Map expectedFinalVotesForDatasets = + Map.of( + dataset1.getDatasetId(), + false, + dataset2.getDatasetId(), + false, + dataset3.getDatasetId(), + true, + dataset4.getDatasetId(), + true); for (DarCollection dar : allDarCollections) { for (Map.Entry e : dar.getDars().entrySet()) { for (Integer id : e.getValue().getDatasetIds()) { - createDataAccessElectionWithVotes(e.getKey(), id, user.getUserId(), - expectedFinalVotesForDatasets.get(id), VoteType.valueOf(voteType)); + createDataAccessElectionWithVotes( + e.getKey(), + id, + user.getUserId(), + expectedFinalVotesForDatasets.get(id), + VoteType.valueOf(voteType)); } } } @@ -936,7 +944,8 @@ void testGetApprovedDatasets(String voteType) { // user with a mix of approved and unapproved datasets User user = createUser(); - libraryCardDAO.insertLibraryCard(user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); Dataset dataset1 = createDataset(false); Dataset dataset2 = createDataset(true); @@ -946,33 +955,59 @@ void testGetApprovedDatasets(String voteType) { Timestamp timestamp = new Timestamp(new Date().getTime()); Dac dac1 = insertDac(); - datasetDAO.updateDataset(dataset1.getDatasetId(), dataset1.getDatasetName(), timestamp, - user.getUserId(), dac1.getDacId()); - datasetDAO.updateDataset(dataset2.getDatasetId(), dataset2.getDatasetName(), timestamp, - user.getUserId(), dac1.getDacId()); + datasetDAO.updateDataset( + dataset1.getDatasetId(), + dataset1.getDatasetName(), + timestamp, + user.getUserId(), + dac1.getDacId()); + datasetDAO.updateDataset( + dataset2.getDatasetId(), + dataset2.getDatasetName(), + timestamp, + user.getUserId(), + dac1.getDacId()); Dac dac2 = insertDac(); - datasetDAO.updateDataset(dataset3.getDatasetId(), dataset3.getDatasetName(), timestamp, - user.getUserId(), dac2.getDacId()); - datasetDAO.updateDataset(dataset4.getDatasetId(), dataset4.getDatasetName(), timestamp, - user.getUserId(), dac2.getDacId()); + datasetDAO.updateDataset( + dataset3.getDatasetId(), + dataset3.getDatasetName(), + timestamp, + user.getUserId(), + dac2.getDacId()); + datasetDAO.updateDataset( + dataset4.getDatasetId(), + dataset4.getDatasetName(), + timestamp, + user.getUserId(), + dac2.getDacId()); DarCollection dar1 = createDarCollectionWithDatasets(dac1.getDacId(), user, List.of(dataset1)); - DarCollection dar2 = createDarCollectionWithDatasets(dac2.getDacId(), user, - List.of(dataset2, dataset3)); + DarCollection dar2 = + createDarCollectionWithDatasets(dac2.getDacId(), user, List.of(dataset2, dataset3)); DarCollection dar3 = createDarCollectionWithDatasets(dac2.getDacId(), user, List.of(dataset4)); List allDarCollections = List.of(dar1, dar2, dar3); - Map expectedFinalVotesForDatasets = Map.of(dataset1.getDatasetId(), false, - dataset2.getDatasetId(), false, dataset3.getDatasetId(), true, dataset4.getDatasetId(), - true); - + Map expectedFinalVotesForDatasets = + Map.of( + dataset1.getDatasetId(), + false, + dataset2.getDatasetId(), + false, + dataset3.getDatasetId(), + true, + dataset4.getDatasetId(), + true); for (DarCollection dar : allDarCollections) { for (Map.Entry e : dar.getDars().entrySet()) { for (Integer id : e.getValue().getDatasetIds()) { - createDataAccessElectionWithVotes(e.getKey(), id, user.getUserId(), - expectedFinalVotesForDatasets.get(id), VoteType.valueOf(voteType)); + createDataAccessElectionWithVotes( + e.getKey(), + id, + user.getUserId(), + expectedFinalVotesForDatasets.get(id), + VoteType.valueOf(voteType)); } } } @@ -981,25 +1016,40 @@ void testGetApprovedDatasets(String voteType) { assertNotNull(approvedDatasets); // checks that all datasets in the result are approved - approvedDatasets.forEach(approvedDataset -> assertTrue( - datasetDAO.findDatasetByAlias(approvedDataset.getAlias()).getDacApproval())); - - ApprovedDataset expectedApprovedDataset1 = new ApprovedDataset(dataset3.getAlias(), - dar2.getDarCode(), dataset3.getDatasetName(), dac2.getName(), dar2.getMostRecentDar().getExpiresAt()); - ApprovedDataset expectedApprovedDataset2 = new ApprovedDataset(dataset4.getAlias(), - dar3.getDarCode(), dataset4.getDatasetName(), dac2.getName(), dar3.getMostRecentDar().getExpiresAt()); - Map expectedDatasets = Map.of(dataset3.getAlias(), - expectedApprovedDataset1, dataset4.getAlias(), expectedApprovedDataset2); + approvedDatasets.forEach( + approvedDataset -> + assertTrue(datasetDAO.findDatasetByAlias(approvedDataset.getAlias()).getDacApproval())); + + ApprovedDataset expectedApprovedDataset1 = + new ApprovedDataset( + dataset3.getAlias(), + dar2.getDarCode(), + dataset3.getDatasetName(), + dac2.getName(), + dar2.getMostRecentDar().getExpiresAt()); + ApprovedDataset expectedApprovedDataset2 = + new ApprovedDataset( + dataset4.getAlias(), + dar3.getDarCode(), + dataset4.getDatasetName(), + dac2.getName(), + dar3.getMostRecentDar().getExpiresAt()); + Map expectedDatasets = + Map.of( + dataset3.getAlias(), + expectedApprovedDataset1, + dataset4.getAlias(), + expectedApprovedDataset2); // checks that the expected result list size and contents match the observed result assertEquals(expectedDatasets.size(), approvedDatasets.size()); - IntStream.range(0, approvedDatasets.size()).forEach(index -> { - ApprovedDataset dataset = approvedDatasets.get(index); - ApprovedDataset expectedDataset = expectedDatasets.get(dataset.getAlias()); - assertTrue(dataset.isApprovedDatasetEqual(expectedDataset)); - }); - - + IntStream.range(0, approvedDatasets.size()) + .forEach( + index -> { + ApprovedDataset dataset = approvedDatasets.get(index); + ApprovedDataset expectedDataset = expectedDatasets.get(dataset.getAlias()); + assertTrue(dataset.isApprovedDatasetEqual(expectedDataset)); + }); } @ParameterizedTest @@ -1015,13 +1065,21 @@ void testGetApprovedDatasetsWhenNone(String voteType) { Timestamp timestamp = new Timestamp(new Date().getTime()); Dac dac1 = insertDac(); - datasetDAO.updateDataset(dataset1.getDatasetId(), dataset1.getDatasetName(), timestamp, - user.getUserId(), dac1.getDacId()); - datasetDAO.updateDataset(dataset2.getDatasetId(), dataset2.getDatasetName(), timestamp, - user.getUserId(), dac1.getDacId()); + datasetDAO.updateDataset( + dataset1.getDatasetId(), + dataset1.getDatasetName(), + timestamp, + user.getUserId(), + dac1.getDacId()); + datasetDAO.updateDataset( + dataset2.getDatasetId(), + dataset2.getDatasetName(), + timestamp, + user.getUserId(), + dac1.getDacId()); - DarCollection dar1 = createDarCollectionWithDatasets(dac1.getDacId(), user, - List.of(dataset1, dataset2)); + DarCollection dar1 = + createDarCollectionWithDatasets(dac1.getDacId(), user, List.of(dataset1, dataset2)); for (Map.Entry e : dar1.getDars().entrySet()) { for (Integer id : e.getValue().getDatasetIds()) { @@ -1041,7 +1099,6 @@ void testGetApprovedDatasetsWhenEmpty() { User user = createUser(); List approvedDatasets = datasetDAO.getApprovedDatasets(user.getUserId()); assertEquals(0, approvedDatasets.size()); - } @Test @@ -1051,7 +1108,8 @@ void testGetApprovedDatasetsForMultiDACElections() { User user = createUser(); User chairperson1 = createUser(); User chairperson2 = createUser(); - libraryCardDAO.insertLibraryCard(user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), now); + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), now); Dataset dataset1 = createDataset(true); Dataset dataset2 = createDataset(true); @@ -1061,72 +1119,102 @@ void testGetApprovedDatasetsForMultiDACElections() { Timestamp timestamp = new Timestamp(now.getTime()); Dac dac1 = insertDac(); - datasetDAO.updateDataset(dataset1.getDatasetId(), dataset1.getDatasetName(), timestamp, chairperson1.getUserId(), dac1.getDacId()); - datasetDAO.updateDataset(dataset2.getDatasetId(), dataset2.getDatasetName(), timestamp, chairperson1.getUserId(), dac1.getDacId()); - datasetDAO.updateDatasetApproval(true, Instant.now(), chairperson1.getUserId(), dataset1.getDatasetId()); - datasetDAO.updateDatasetApproval(true, Instant.now(), chairperson1.getUserId(), dataset2.getDatasetId()); - + datasetDAO.updateDataset( + dataset1.getDatasetId(), + dataset1.getDatasetName(), + timestamp, + chairperson1.getUserId(), + dac1.getDacId()); + datasetDAO.updateDataset( + dataset2.getDatasetId(), + dataset2.getDatasetName(), + timestamp, + chairperson1.getUserId(), + dac1.getDacId()); + datasetDAO.updateDatasetApproval( + true, Instant.now(), chairperson1.getUserId(), dataset1.getDatasetId()); + datasetDAO.updateDatasetApproval( + true, Instant.now(), chairperson1.getUserId(), dataset2.getDatasetId()); Dac dac2 = insertDac(); - datasetDAO.updateDataset(dataset3.getDatasetId(), dataset3.getDatasetName(), timestamp, chairperson2.getUserId(), dac2.getDacId()); - datasetDAO.updateDataset(dataset4.getDatasetId(), dataset4.getDatasetName(), timestamp, chairperson2.getUserId(), dac2.getDacId()); - datasetDAO.updateDatasetApproval(true, Instant.now(), chairperson2.getUserId(), dataset3.getDatasetId()); - datasetDAO.updateDatasetApproval(true, Instant.now(), chairperson2.getUserId(), dataset4.getDatasetId()); - - DarCollection darCollection = createDarCollectionWithDatasetsNewModel(user, List.of(dataset1, dataset2, dataset3, dataset4)); + datasetDAO.updateDataset( + dataset3.getDatasetId(), + dataset3.getDatasetName(), + timestamp, + chairperson2.getUserId(), + dac2.getDacId()); + datasetDAO.updateDataset( + dataset4.getDatasetId(), + dataset4.getDatasetName(), + timestamp, + chairperson2.getUserId(), + dac2.getDacId()); + datasetDAO.updateDatasetApproval( + true, Instant.now(), chairperson2.getUserId(), dataset3.getDatasetId()); + datasetDAO.updateDatasetApproval( + true, Instant.now(), chairperson2.getUserId(), dataset4.getDatasetId()); + + DarCollection darCollection = + createDarCollectionWithDatasetsNewModel( + user, List.of(dataset1, dataset2, dataset3, dataset4)); assertEquals(0, datasetDAO.getApprovedDatasets(user.getUserId()).size()); // Simulate 2 DAC 1 elections for yesterday Date yesterday = Date.from(Instant.now().minus(1, ChronoUnit.DAYS)); - Integer electionId1 = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - yesterday, - darCollection.getMostRecentDar().getReferenceId(), - dataset1.getDatasetId() - ); - Integer voteId1 = voteDAO.insertVote(chairperson1.getUserId(), electionId1, VoteType.FINAL.getValue()); + Integer electionId1 = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + yesterday, + darCollection.getMostRecentDar().getReferenceId(), + dataset1.getDatasetId()); + Integer voteId1 = + voteDAO.insertVote(chairperson1.getUserId(), electionId1, VoteType.FINAL.getValue()); updateVote(true, "rationale", yesterday, voteId1, false, electionId1, yesterday, false); electionDAO.updateElectionById(electionId1, ElectionStatus.CLOSED.getValue(), yesterday); List approvedDatasets = datasetDAO.getApprovedDatasets(user.getUserId()); assertEquals(1, approvedDatasets.size()); - assertEquals(darCollection.getMostRecentDar().getExpiresAt(), approvedDatasets.get(0).getExpirationDate()); - - - Integer electionId2 = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - yesterday, - darCollection.getMostRecentDar().getReferenceId(), - dataset2.getDatasetId() - ); - Integer voteId2 = voteDAO.insertVote(chairperson1.getUserId(), electionId2, VoteType.FINAL.getValue()); + assertEquals( + darCollection.getMostRecentDar().getExpiresAt(), + approvedDatasets.get(0).getExpirationDate()); + + Integer electionId2 = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + yesterday, + darCollection.getMostRecentDar().getReferenceId(), + dataset2.getDatasetId()); + Integer voteId2 = + voteDAO.insertVote(chairperson1.getUserId(), electionId2, VoteType.FINAL.getValue()); updateVote(true, "rationale", yesterday, voteId2, false, electionId1, yesterday, false); electionDAO.updateElectionById(electionId2, ElectionStatus.CLOSED.getValue(), yesterday); assertEquals(2, datasetDAO.getApprovedDatasets(user.getUserId()).size()); // Simulate 2 DAC 2 elections for today Date today = new Date(); - Integer electionId3 = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - today, - darCollection.getMostRecentDar().getReferenceId(), - dataset3.getDatasetId() - ); - Integer voteId3 = voteDAO.insertVote(chairperson2.getUserId(), electionId3, VoteType.FINAL.getValue()); + Integer electionId3 = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + today, + darCollection.getMostRecentDar().getReferenceId(), + dataset3.getDatasetId()); + Integer voteId3 = + voteDAO.insertVote(chairperson2.getUserId(), electionId3, VoteType.FINAL.getValue()); updateVote(true, "rationale", today, voteId3, false, electionId3, today, false); electionDAO.updateElectionById(electionId3, ElectionStatus.CLOSED.getValue(), today); assertEquals(3, datasetDAO.getApprovedDatasets(user.getUserId()).size()); - Integer electionId4 = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - today, - darCollection.getMostRecentDar().getReferenceId(), - dataset4.getDatasetId() - ); - Integer voteId4 = voteDAO.insertVote(chairperson2.getUserId(), electionId4, VoteType.FINAL.getValue()); + Integer electionId4 = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + today, + darCollection.getMostRecentDar().getReferenceId(), + dataset4.getDatasetId()); + Integer voteId4 = + voteDAO.insertVote(chairperson2.getUserId(), electionId4, VoteType.FINAL.getValue()); updateVote(true, "rationale", today, voteId4, false, electionId4, today, false); electionDAO.updateElectionById(electionId4, ElectionStatus.CLOSED.getValue(), today); @@ -1150,7 +1238,14 @@ void testGetApprovedDatasetsForMultiDACElections() { DataAccessRequest recentDar = darCollection.getMostRecentDar(); // submit a progress report. - DataAccessRequest progressReport = createProgressReport(recentDar.getData(), recentDar.getEraCommonsId(), recentDar.getUserId(), recentDar.getCollectionId(), recentDar.getId(), recentDar.getDatasetIds()); + DataAccessRequest progressReport = + createProgressReport( + recentDar.getData(), + recentDar.getEraCommonsId(), + recentDar.getUserId(), + recentDar.getCollectionId(), + recentDar.getId(), + recentDar.getDatasetIds()); // ensure we still have no approved datasets. List approvedDatasets4 = datasetDAO.getApprovedDatasets(user.getUserId()); @@ -1158,28 +1253,30 @@ void testGetApprovedDatasetsForMultiDACElections() { // Simulate 2 DAC 2 elections for today // vote yes on dataset 3 - Integer electionId5 = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - today, - progressReport.getReferenceId(), - dataset3.getDatasetId() - ); - Integer voteId5 = voteDAO.insertVote(chairperson2.getUserId(), electionId5, VoteType.FINAL.getValue()); + Integer electionId5 = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + today, + progressReport.getReferenceId(), + dataset3.getDatasetId()); + Integer voteId5 = + voteDAO.insertVote(chairperson2.getUserId(), electionId5, VoteType.FINAL.getValue()); updateVote(true, "rationale", today, voteId5, false, electionId5, today, false); electionDAO.updateElectionById(electionId5, ElectionStatus.CLOSED.getValue(), today); List approvedDatasets5 = datasetDAO.getApprovedDatasets(user.getUserId()); assertEquals(1, approvedDatasets5.size()); assertEquals(progressReport.getExpiresAt(), approvedDatasets5.get(0).getExpirationDate()); - Integer electionId6 = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - today, - progressReport.getReferenceId(), - dataset4.getDatasetId() - ); - Integer voteId6 = voteDAO.insertVote(chairperson2.getUserId(), electionId6, VoteType.FINAL.getValue()); + Integer electionId6 = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + today, + progressReport.getReferenceId(), + dataset4.getDatasetId()); + Integer voteId6 = + voteDAO.insertVote(chairperson2.getUserId(), electionId6, VoteType.FINAL.getValue()); // vote no on dataset 4 updateVote(false, "rationale", today, voteId6, false, electionId6, today, false); electionDAO.updateElectionById(electionId6, ElectionStatus.CLOSED.getValue(), today); @@ -1188,29 +1285,31 @@ void testGetApprovedDatasetsForMultiDACElections() { assertNotNull(approvedDatasets6); assertEquals(1, approvedDatasets6.size()); - List dataset3Dars = dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset3.getDatasetId()); + List dataset3Dars = + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset3.getDatasetId()); assertEquals(1, dataset3Dars.size()); - List dataset4Dars = dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset4.getDatasetId()); + List dataset4Dars = + dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset4.getDatasetId()); assertEquals(0, dataset4Dars.size()); - today = new Date(); //adjust the date into the future or the LAST_VALUE won't work correctly. + today = new Date(); // adjust the date into the future or the LAST_VALUE won't work correctly. // make a new election for dataset 3 and now vote no - Integer electionId7 = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - today, - progressReport.getReferenceId(), - dataset3.getDatasetId() - ); - Integer voteId7 = voteDAO.insertVote(chairperson2.getUserId(), electionId7, VoteType.FINAL.getValue()); + Integer electionId7 = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + today, + progressReport.getReferenceId(), + dataset3.getDatasetId()); + Integer voteId7 = + voteDAO.insertVote(chairperson2.getUserId(), electionId7, VoteType.FINAL.getValue()); updateVote(false, "rationale", today, voteId7, false, electionId7, today, false); electionDAO.updateElectionById(electionId7, ElectionStatus.CLOSED.getValue(), today); assertEquals(0, datasetDAO.getApprovedDatasets(user.getUserId()).size()); dataset3Dars = dataAccessRequestDAO.findApprovedDARsByDatasetId(dataset3.getDatasetId()); assertEquals(0, dataset3Dars.size()); - } @Test @@ -1224,25 +1323,26 @@ void testUpdateDatasetIndexedDate() { assertNull(updatedDataset2.getIndexedDate()); } - private DarCollection createDarCollectionWithDatasets(int dacId, User user, - List datasets) { + private DarCollection createDarCollectionWithDatasets( + int dacId, User user, List datasets) { String darCode = "DAR-" + randomInt(1, 999999); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - IntStream.range(0, datasets.size()).forEach(index -> { - Dataset dataset = datasets.get(index); - datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dacId); - createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, dataset.getDatasetId(), - user.getUserId()); - }); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + IntStream.range(0, datasets.size()) + .forEach( + index -> { + Dataset dataset = datasets.get(index); + datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dacId); + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); + }); return darCollectionDAO.findDARCollectionByCollectionId(collectionId); } private DarCollection createDarCollectionWithDatasetsNewModel(User user, List datasets) { String darCode = "DAR-" + randomInt(1, 999999); Date now = new Date(); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - now); + Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), now); List datasetIds = datasets.stream().map(Dataset::getDatasetId).toList(); createDataAccessRequestNewModel(collectionId, datasetIds, user.getUserId()); return darCollectionDAO.findDARCollectionByCollectionId(collectionId); @@ -1253,8 +1353,8 @@ private void createUserRole(Integer roleId, Integer userId, Integer dacId) { } private void createFileStorageObject() { - FileCategory category = List.of(FileCategory.values()) - .get(new Random().nextInt(FileCategory.values().length)); + FileCategory category = + List.of(FileCategory.values()).get(new Random().nextInt(FileCategory.values().length)); String entityId = randomAlphabetic(10); createFileStorageObject(entityId, category); } @@ -1266,15 +1366,15 @@ private FileStorageObject createFileStorageObject(String entityId, FileCategory User createUser = createUser(); Instant createDate = Instant.now(); - Integer newFileStorageObjectId = fileStorageObjectDAO.insertNewFile( - fileName, - category.getValue(), - bucketName, - gcsFileUri, - entityId, - createUser.getUserId(), - createDate - ); + Integer newFileStorageObjectId = + fileStorageObjectDAO.insertNewFile( + fileName, + category.getValue(), + bucketName, + gcsFileUri, + entityId, + createUser.getUserId(), + createDate); return fileStorageObjectDAO.findFileById(newFileStorageObjectId); } @@ -1293,10 +1393,9 @@ protected void createStringDatasetProperty(Integer datasetId, String value) { } private Dac insertDac() { - Integer id = dacDAO.createDac( - "Test_" + randomAlphanumeric(20), - "Test_" + randomAlphanumeric(20), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphanumeric(20), "Test_" + randomAlphanumeric(20), new Date()); return dacDAO.findById(id); } @@ -1310,72 +1409,67 @@ private Study insertStudyWithProperties(User user) { String name = randomAlphabetic(20); String description = randomAlphabetic(20); - List dataTypes = List.of( - randomAlphabetic(20), - randomAlphabetic(20) - ); + List dataTypes = List.of(randomAlphabetic(20), randomAlphabetic(20)); String piName = randomAlphabetic(20); Boolean publicVisibility = true; - Integer id = studyDAO.insertStudy( - name, - description, - piName, - dataTypes, - publicVisibility, - user.getUserId(), - Instant.now(), - UUID.randomUUID() - ); - - studyDAO.insertStudyProperty( - id, - "prop1", - PropertyType.String.toString(), - "asdf" - ); - - studyDAO.insertStudyProperty( - id, - "prop2", - PropertyType.Number.toString(), - "1" - ); + Integer id = + studyDAO.insertStudy( + name, + description, + piName, + dataTypes, + publicVisibility, + user.getUserId(), + Instant.now(), + UUID.randomUUID()); + + studyDAO.insertStudyProperty(id, "prop1", PropertyType.String.toString(), "asdf"); + + studyDAO.insertStudyProperty(id, "prop2", PropertyType.Number.toString(), "1"); return studyDAO.findStudyById(id); } - - private void createDataAccessRequestWithDatasetAndCollectionInfo(int collectionId, - int datasetId, int userId) { + private void createDataAccessRequestWithDatasetAndCollectionInfo( + int collectionId, int datasetId, int userId) { DataAccessRequestData data = new DataAccessRequestData(); data.setProjectTitle(randomAlphabetic(10)); String referenceId = randomAlphanumeric(20); - dataAccessRequestDAO.insertDataAccessRequest(collectionId, referenceId, userId, new Date(), - new Date(), new Date(), data, randomAlphabetic(10)); + dataAccessRequestDAO.insertDataAccessRequest( + collectionId, + referenceId, + userId, + new Date(), + new Date(), + new Date(), + data, + randomAlphabetic(10)); dataAccessRequestDAO.insertDARDatasetRelation(referenceId, datasetId); } - private void createDataAccessRequestNewModel(int collectionId, List datasetIds, int userId) { + private void createDataAccessRequestNewModel( + int collectionId, List datasetIds, int userId) { DataAccessRequestData data = new DataAccessRequestData(); data.setProjectTitle(randomAlphabetic(10)); String referenceId = randomAlphabetic(20); Date now = new Date(); - dataAccessRequestDAO.insertDataAccessRequest(collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); + dataAccessRequestDAO.insertDataAccessRequest( + collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); datasetIds.forEach( datasetId -> dataAccessRequestDAO.insertDARDatasetRelation(referenceId, datasetId)); } - private DataAccessRequest createProgressReport(DataAccessRequestData data, String eraCommonsId, Integer userId, Integer collectionId, - Integer parentId, List datasetIds) { + private DataAccessRequest createProgressReport( + DataAccessRequestData data, + String eraCommonsId, + Integer userId, + Integer collectionId, + Integer parentId, + List datasetIds) { String referenceId = UUID.randomUUID().toString(); dataAccessRequestDAO.insertProgressReport( - parentId, - collectionId, - referenceId, - userId, - data, - eraCommonsId); + parentId, collectionId, referenceId, userId, data, eraCommonsId); datasetIds.forEach( datasetId -> dataAccessRequestDAO.insertDARDatasetRelation(referenceId, datasetId)); return dataAccessRequestDAO.findByReferenceId(referenceId); @@ -1398,13 +1492,12 @@ private Dataset insertDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } - private Dataset createDataset(boolean dacApproval) { User user = createUser(); String name = "Name_" + randomAlphanumeric(20); @@ -1412,8 +1505,8 @@ private Dataset createDataset(boolean dacApproval) { Instant instant = Instant.now(); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); datasetDAO.updateDatasetApproval(dacApproval, instant, user.getUserId(), id); createDatasetProperties(id); return datasetDAO.findDatasetById(id); @@ -1425,25 +1518,28 @@ private void createStaticDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); } - private void createDataAccessElectionWithVotes(String referenceId, Integer datasetId, - Integer userId, boolean finalVoteApproval, VoteType voteType) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + private void createDataAccessElectionWithVotes( + String referenceId, + Integer datasetId, + Integer userId, + boolean finalVoteApproval, + VoteType voteType) { + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); Integer voteId = voteDAO.insertVote(userId, electionId, voteType.getValue()); - updateVote(finalVoteApproval, "rationale", new Date(), voteId, false, electionId, - new Date(), false); + updateVote( + finalVoteApproval, "rationale", new Date(), voteId, false, electionId, new Date(), false); electionDAO.updateElectionById(electionId, ElectionStatus.CLOSED.getValue(), new Date()); datasetDAO.updateDatasetApproval(finalVoteApproval, Instant.now(), userId, datasetId); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/DraftDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/DraftDAOTest.java index 58bcb44026..55b4c157be 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/DraftDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/DraftDAOTest.java @@ -30,7 +30,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; - @ExtendWith(MockitoExtension.class) class DraftDAOTest extends DAOTestHelper { @@ -44,10 +43,14 @@ void testInsertOperation() { Date createDate = draft.getCreateDate(); Date updateDate = draft.getUpdateDate(); String name = draft.getName(); - draftDAO.insert(draft.getName(), createDate.toInstant(), user1.getUserId(), - draft.getJson(), draft.getUUID(), draft.getType().getValue()); - Collection user1submissions = draftDAO.findDraftsByUserId( - user1.getUserId()); + draftDAO.insert( + draft.getName(), + createDate.toInstant(), + user1.getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); + Collection user1submissions = draftDAO.findDraftsByUserId(user1.getUserId()); assertThat(user1submissions, hasSize(1)); DraftInterface returnedDraft = user1submissions.iterator().next(); assertEquals(jsonText, returnedDraft.getJson()); @@ -63,8 +66,7 @@ void testInsertOperation() { assertEquals(returnedDraft.getUpdateUser().getEmail(), user1.getEmail()); assertEquals(returnedDraft.getUpdateUser().getInstitutionId(), user1.getInstitutionId()); assertEquals(returnedDraft.getUpdateUser().getEraCommonsId(), user1.getEraCommonsId()); - Collection user2submissions = draftDAO.findDraftsByUserId( - user2.getUserId()); + Collection user2submissions = draftDAO.findDraftsByUserId(user2.getUserId()); assertThat(user2submissions, hasSize(0)); } @@ -73,12 +75,23 @@ void testUniqueUUIDConstraint() { String jsonText = "{\"Name\": \"Greg\"}"; User user1 = createUser(); DraftStudyDataset draft = new DraftStudyDataset(jsonText, user1); - draftDAO.insert(draft.getName(), draft.getCreateDate().toInstant(), user1.getUserId(), - draft.getJson(), draft.getUUID(), draft.getType().getValue()); - assertThrows(UnableToExecuteStatementException.class, - () -> draftDAO.insert(draft.getName(), draft.getCreateDate().toInstant(), - user1.getUserId(), draft.getJson(), draft.getUUID(), - draft.getType().getValue())); + draftDAO.insert( + draft.getName(), + draft.getCreateDate().toInstant(), + user1.getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); + assertThrows( + UnableToExecuteStatementException.class, + () -> + draftDAO.insert( + draft.getName(), + draft.getCreateDate().toInstant(), + user1.getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue())); } @Test @@ -88,8 +101,13 @@ void testUpdateOperation() { DraftStudyDataset draft = new DraftStudyDataset(jsonText, user1); UUID uuid = draft.getUUID(); Date createDate = draft.getCreateDate(); - draftDAO.insert(draft.getName(), createDate.toInstant(), user1.getUserId(), - draft.getJson(), draft.getUUID(), draft.getType().getValue()); + draftDAO.insert( + draft.getName(), + createDate.toInstant(), + user1.getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); DraftInterface returnedDraft = draftDAO.findDraftById(uuid); assertFalse(Objects.isNull(returnedDraft)); assertEquals(jsonText, returnedDraft.getJson()); @@ -97,9 +115,13 @@ void testUpdateOperation() { String revisedJson = "{\"Name\": \"Bob\"}"; returnedDraft.setJson(revisedJson); returnedDraft.setUpdateDate(new Date()); - draftDAO.updateDraftByDraftUUID(returnedDraft.getName(), - returnedDraft.getUpdateDate().toInstant(), user1.getUserId(), returnedDraft.getJson(), - returnedDraft.getUUID(), returnedDraft.getType().getValue()); + draftDAO.updateDraftByDraftUUID( + returnedDraft.getName(), + returnedDraft.getUpdateDate().toInstant(), + user1.getUserId(), + returnedDraft.getJson(), + returnedDraft.getUUID(), + returnedDraft.getType().getValue()); returnedDraft = draftDAO.findDraftById(uuid); assertFalse(Objects.isNull(returnedDraft)); assertEquals(revisedJson, returnedDraft.getJson()); @@ -114,8 +136,13 @@ void testUpdateDraftByUUID() { DraftStudyDataset draft = new DraftStudyDataset(jsonText, user1); UUID uuid = draft.getUUID(); Date createDate = draft.getCreateDate(); - draftDAO.insert(draft.getName(), createDate.toInstant(), user1.getUserId(), - draft.getJson(), draft.getUUID(), draft.getType().getValue()); + draftDAO.insert( + draft.getName(), + createDate.toInstant(), + user1.getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); DraftInterface returnedDraft = draftDAO.findDraftById(uuid); assertEquals(uuid, returnedDraft.getUUID()); assertEquals(user1.getUserId(), returnedDraft.getUpdateUser().getUserId()); @@ -125,7 +152,6 @@ void testUpdateDraftByUUID() { returnedDraft = draftDAO.findDraftById(uuid); assertEquals(user2.getUserId(), returnedDraft.getUpdateUser().getUserId()); - } @Test @@ -134,24 +160,31 @@ void testFindByUserOperations() { User user2 = createUser(); DraftStudyDataset draft = new DraftStudyDataset("{\"Name\": \"User1\"}", user1); DraftStudyDataset draft2 = new DraftStudyDataset("{\"Name\": \"User2\"}", user2); - draftDAO.insert(draft.getName(), draft.getCreateDate().toInstant(), user1.getUserId(), - draft.getJson(), draft.getUUID(), draft.getType().getValue()); - draftDAO.insert(draft2.getName(), draft2.getCreateDate().toInstant(), + draftDAO.insert( + draft.getName(), + draft.getCreateDate().toInstant(), + user1.getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); + draftDAO.insert( + draft2.getName(), + draft2.getCreateDate().toInstant(), user2.getUserId(), - draft2.getJson(), draft2.getUUID(), draft2.getType().getValue()); - Collection user1submissions = draftDAO.findDraftsByUserId( - user1.getUserId()); - Collection user1summaries = draftDAO.findDraftSummariesByUserId( - user1.getUserId()); + draft2.getJson(), + draft2.getUUID(), + draft2.getType().getValue()); + Collection user1submissions = draftDAO.findDraftsByUserId(user1.getUserId()); + Collection user1summaries = + draftDAO.findDraftSummariesByUserId(user1.getUserId()); assertThat(user1submissions, hasSize(1)); assertThat(user1summaries, hasSize(1)); DraftSummary user1DraftSummary = user1summaries.iterator().next(); DraftInterface user1Draft = user1submissions.iterator().next(); summaryMatchesDetails(user1DraftSummary, user1Draft); - Collection user2Drafts = draftDAO.findDraftsByUserId( - user2.getUserId()); - Collection user2summaries = draftDAO.findDraftSummariesByUserId( - user2.getUserId()); + Collection user2Drafts = draftDAO.findDraftsByUserId(user2.getUserId()); + Collection user2summaries = + draftDAO.findDraftSummariesByUserId(user2.getUserId()); DraftSummary user2DraftSummary = user2summaries.iterator().next(); DraftInterface user2Draft = user2Drafts.iterator().next(); assertThat(user2Drafts, hasSize(1)); @@ -171,14 +204,22 @@ void testDraftsWithFiles() { fso.setUpdateDate(draft.getUpdateDate().toInstant()); fso.setCreateUserId(user1.getUserId()); fso.setEntityId(draft.getUUID().toString()); - draftDAO.insert(draft.getName(), draft.getCreateDate().toInstant(), - draft.getCreateUser().getUserId(), draft.getJson(), draft.getUUID(), + draftDAO.insert( + draft.getName(), + draft.getCreateDate().toInstant(), + draft.getCreateUser().getUserId(), + draft.getJson(), + draft.getUUID(), draft.getType().getValue()); - fileStorageObjectDAO.insertNewFile(fso.getFileName(), fso.getCategory().getValue(), - fso.getBlobId().toGsUtilUri(), fso.getMediaType(), draft.getUUID().toString(), - user1.getUserId(), fso.getCreateDate()); - Collection drafts = draftDAO.findDraftsByUserId( - user1.getUserId()); + fileStorageObjectDAO.insertNewFile( + fso.getFileName(), + fso.getCategory().getValue(), + fso.getBlobId().toGsUtilUri(), + fso.getMediaType(), + draft.getUUID().toString(), + user1.getUserId(), + fso.getCreateDate()); + Collection drafts = draftDAO.findDraftsByUserId(user1.getUserId()); assertThat(drafts, hasSize(1)); Set storedFiles = drafts.iterator().next().getStoredFiles(); assertThat(storedFiles, hasSize(1)); @@ -194,13 +235,21 @@ void testDeleteOperation() { User user1 = createUser(); DraftStudyDataset draft = new DraftStudyDataset("{\"Name\": \"First\"}", user1); DraftStudyDataset draft2 = new DraftStudyDataset("{\"Name\": \"Second\"}", user1); - draftDAO.insert(draft.getName(), draft.getCreateDate().toInstant(), user1.getUserId(), - draft.getJson(), draft.getUUID(), draft.getType().getValue()); - draftDAO.insert(draft2.getName(), draft2.getCreateDate().toInstant(), + draftDAO.insert( + draft.getName(), + draft.getCreateDate().toInstant(), + user1.getUserId(), + draft.getJson(), + draft.getUUID(), + draft.getType().getValue()); + draftDAO.insert( + draft2.getName(), + draft2.getCreateDate().toInstant(), user1.getUserId(), - draft2.getJson(), draft2.getUUID(), draft2.getType().getValue()); - Collection user1submissions = draftDAO.findDraftsByUserId( - user1.getUserId()); + draft2.getJson(), + draft2.getUUID(), + draft2.getType().getValue()); + Collection user1submissions = draftDAO.findDraftsByUserId(user1.getUserId()); assertThat(user1submissions, hasSize(2)); draftDAO.deleteDraftByUUIDList(List.of(draft2.getUUID())); user1submissions = draftDAO.findDraftsByUserId(user1.getUserId()); @@ -211,14 +260,13 @@ void testDeleteOperation() { void testUnknownDraftValue() throws SQLException { try (ResultSet resultSet = mock(ResultSet.class)) { try (StatementContext ctx = mock(StatementContext.class)) { - assertThrows(UnknownDraftTypeException.class, - () -> new DraftInterfaceMapper().map(resultSet, ctx)); + assertThrows( + UnknownDraftTypeException.class, () -> new DraftInterfaceMapper().map(resultSet, ctx)); } } } - private void summaryMatchesDetails(DraftSummary draftSummary, - DraftInterface draftInterface) { + private void summaryMatchesDetails(DraftSummary draftSummary, DraftInterface draftInterface) { assertEquals(draftSummary.getId(), draftInterface.getUUID()); assertEquals(draftSummary.getName(), draftInterface.getName()); assertEquals(draftSummary.getCreateDate(), draftInterface.getCreateDate()); diff --git a/src/test/java/org/broadinstitute/consent/http/db/ElectionDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/ElectionDAOTest.java index 8d7983522b..b31775a13f 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/ElectionDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/ElectionDAOTest.java @@ -40,18 +40,18 @@ void testGetElectionIdsByReferenceIds() { String accessReferenceId2 = UUID.randomUUID().toString(); Dataset dataset1 = createDataset(); Dataset dataset2 = createDataset(); - Election accessElection1 = createDataAccessElection(accessReferenceId1, - dataset1.getDatasetId()); - Election accessElection2 = createDataAccessElection(accessReferenceId2, - dataset2.getDatasetId()); + Election accessElection1 = + createDataAccessElection(accessReferenceId1, dataset1.getDatasetId()); + Election accessElection2 = + createDataAccessElection(accessReferenceId2, dataset2.getDatasetId()); - List electionIds = electionDAO.getElectionIdsByReferenceIds( - List.of(accessReferenceId1, accessReferenceId2)); + List electionIds = + electionDAO.getElectionIdsByReferenceIds(List.of(accessReferenceId1, accessReferenceId2)); assertEquals(2, electionIds.size()); assertTrue(electionIds.contains(accessElection1.getElectionId())); assertTrue(electionIds.contains(accessElection2.getElectionId())); - List missingElectionIds = electionDAO.getElectionIdsByReferenceIds( - List.of("1", "2", "3")); + List missingElectionIds = + electionDAO.getElectionIdsByReferenceIds(List.of("1", "2", "3")); assertTrue(missingElectionIds.isEmpty()); } @@ -60,8 +60,8 @@ void testFindElectionByDacId() { Dac dac = createDac(); User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset dataset = createDataset(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); @@ -128,46 +128,53 @@ void testFindLastElectionByReferenceIdDatasetIdAndType() { // We should find ONLY the most recent elections with this method User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d1 = createDataset(); Dataset d2 = createDataset(); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), d1.getDatasetId()); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), d2.getDatasetId()); // Create OPEN elections - List firstElectionIds = Stream - .of(createElectionsForDarDataset(dar, d1), createElectionsForDarDataset(dar, d2)) - .flatMap(List::stream).toList(); + List firstElectionIds = + Stream.of(createElectionsForDarDataset(dar, d1), createElectionsForDarDataset(dar, d2)) + .flatMap(List::stream) + .toList(); // Cancel those elections firstElectionIds.forEach( - id -> electionDAO.updateElectionById(id, ElectionStatus.CANCELED.getValue(), new Date(), - true)); + id -> + electionDAO.updateElectionById( + id, ElectionStatus.CANCELED.getValue(), new Date(), true)); // Create a new set of elections - List latestElectionIds = Stream - .of(createElectionsForDarDataset(dar, d1), createElectionsForDarDataset(dar, d2)) - .flatMap(List::stream).toList(); - - Election latestAccessForD1 = electionDAO.findLastElectionByReferenceIdDatasetIdAndType( - dar.getReferenceId(), d1.getDatasetId(), ElectionType.DATA_ACCESS.getValue()); + List latestElectionIds = + Stream.of(createElectionsForDarDataset(dar, d1), createElectionsForDarDataset(dar, d2)) + .flatMap(List::stream) + .toList(); + + Election latestAccessForD1 = + electionDAO.findLastElectionByReferenceIdDatasetIdAndType( + dar.getReferenceId(), d1.getDatasetId(), ElectionType.DATA_ACCESS.getValue()); assertNotNull(latestAccessForD1); assertFalse(firstElectionIds.contains(latestAccessForD1.getElectionId())); assertTrue(latestElectionIds.contains(latestAccessForD1.getElectionId())); - Election latestRPForD1 = electionDAO.findLastElectionByReferenceIdDatasetIdAndType( - dar.getReferenceId(), d1.getDatasetId(), ElectionType.RP.getValue()); + Election latestRPForD1 = + electionDAO.findLastElectionByReferenceIdDatasetIdAndType( + dar.getReferenceId(), d1.getDatasetId(), ElectionType.RP.getValue()); assertNotNull(latestRPForD1); assertFalse(firstElectionIds.contains(latestRPForD1.getElectionId())); assertTrue(latestElectionIds.contains(latestRPForD1.getElectionId())); - Election latestAccessForD2 = electionDAO.findLastElectionByReferenceIdDatasetIdAndType( - dar.getReferenceId(), d2.getDatasetId(), ElectionType.DATA_ACCESS.getValue()); + Election latestAccessForD2 = + electionDAO.findLastElectionByReferenceIdDatasetIdAndType( + dar.getReferenceId(), d2.getDatasetId(), ElectionType.DATA_ACCESS.getValue()); assertNotNull(latestAccessForD2); assertFalse(firstElectionIds.contains(latestAccessForD2.getElectionId())); assertTrue(latestElectionIds.contains(latestAccessForD2.getElectionId())); - Election latestRPForD2 = electionDAO.findLastElectionByReferenceIdDatasetIdAndType( - dar.getReferenceId(), d2.getDatasetId(), ElectionType.RP.getValue()); + Election latestRPForD2 = + electionDAO.findLastElectionByReferenceIdDatasetIdAndType( + dar.getReferenceId(), d2.getDatasetId(), ElectionType.RP.getValue()); assertNotNull(latestRPForD2); assertFalse(firstElectionIds.contains(latestRPForD2.getElectionId())); assertTrue(latestElectionIds.contains(latestRPForD2.getElectionId())); @@ -178,7 +185,7 @@ void testFindLastElectionByReferenceIdDatasetIdAndType() { * Access and RP elections for dar/dataset combination * * @param dar DataAccessRequest - * @param d Dataset + * @param d Dataset * @return List of created electionIds */ private List createElectionsForDarDataset(DataAccessRequest dar, Dataset d) { @@ -191,16 +198,16 @@ private List createElectionsForDarDataset(DataAccessRequest dar, Datase void testFindElectionsByReferenceIdAndDatasetId() { User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d1 = createDataset(); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), d1.getDatasetId()); createRPElection(dar.getReferenceId(), d1.getDatasetId()); createDataAccessElection(dar.getReferenceId(), d1.getDatasetId()); - List elections = electionDAO.findElectionsByReferenceIdAndDatasetId( - dar.getReferenceId(), d1.getDatasetId()); + List elections = + electionDAO.findElectionsByReferenceIdAndDatasetId(dar.getReferenceId(), d1.getDatasetId()); assertEquals(2, elections.size()); } @@ -209,8 +216,8 @@ void testFindElectionByDacIdWithNoAssociation() { Dac dac = createDac(); User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset dataset = createDataset(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); @@ -228,8 +235,8 @@ void testFindElectionByDacIdNotFound() { Dataset dataset = createDataset(); User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); @@ -243,17 +250,16 @@ void testFindAccessElectionWithFinalVoteById() { Dac dac = createDac(); User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d = createDataset(); datasetDAO.updateDatasetDacId(d.getDatasetId(), dac.getDacId()); Election e = createDataAccessElection(dar.getReferenceId(), d.getDatasetId()); - Integer voteId = voteDAO.insertVote(u.getUserId(), e.getElectionId(), - VoteType.FINAL.getValue()); - updateVote(true, "rationale", new Date(), voteId, false, e.getElectionId(), new Date(), - false); + Integer voteId = + voteDAO.insertVote(u.getUserId(), e.getElectionId(), VoteType.FINAL.getValue()); + updateVote(true, "rationale", new Date(), voteId, false, e.getElectionId(), new Date(), false); Vote v = voteDAO.findVoteById(voteId); Election election = electionDAO.findElectionWithFinalVoteById(e.getElectionId()); @@ -268,8 +274,8 @@ void testRPFindElectionWithFinalVoteById() { Dac dac = createDac(); User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d = createDataset(); datasetDAO.updateDatasetDacId(d.getDatasetId(), dac.getDacId()); @@ -289,18 +295,19 @@ void testDULFindElectionWithFinalVoteById() { Dac dac = createDac(); User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d = createDataset(); datasetDAO.updateDatasetDacId(d.getDatasetId(), dac.getDacId()); - Integer electionId = electionDAO.insertElection( - ElectionType.TRANSLATE_DUL.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - dar.getReferenceId(), - d.getDatasetId()); + Integer electionId = + electionDAO.insertElection( + ElectionType.TRANSLATE_DUL.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + dar.getReferenceId(), + d.getDatasetId()); Election e = electionDAO.findElectionById(electionId); Vote v = createPopulatedChairpersonVote(u.getUserId(), e.getElectionId()); @@ -327,19 +334,20 @@ void testInsertExtendedElection() { Dac dac = createDac(); User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d = createDataset(); User u = createUserWithRoleInDac(UserRoles.CHAIRPERSON.getRoleId(), dac.getDacId()); datasetDAO.updateDatasetDacId(d.getDatasetId(), dac.getDacId()); - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - dar.getReferenceId(), - d.getDatasetId()); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + dar.getReferenceId(), + d.getDatasetId()); Election e = electionDAO.findElectionById(electionId); createFinalVote(u.getUserId(), e.getElectionId()); Election election = electionDAO.findElectionWithFinalVoteById(e.getElectionId()); @@ -377,8 +385,8 @@ void testFindLastElectionsByReferenceIds() { Integer datasetId = dataset.getDatasetId(); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), datasetId); - Election recentClosedAccessElection = createDataAccessElection(darReferenceId, - dataset.getDatasetId()); + Election recentClosedAccessElection = + createDataAccessElection(darReferenceId, dataset.getDatasetId()); Election recentClosedRPElection = createRPElection(darReferenceId, datasetId); List elections = electionDAO.findLastElectionsByReferenceIds(Collections.singletonList(dar.referenceId)); @@ -442,13 +450,15 @@ void testFindElectionsWithCardHoldingUsersByElectionIds() { Dataset dataset = createDataset(); int datasetId = dataset.getDatasetId(); createLibraryCard(lcUser); - DataAccessRequest lcDAR = createDataAccessRequestWithUserIdV3(lcUser.getUserId(),"DAR-0001000"); - DataAccessRequest nonLCDAR = createDataAccessRequestWithUserIdV3(nonLCUser.getUserId(),"DAR-0002000"); + DataAccessRequest lcDAR = + createDataAccessRequestWithUserIdV3(lcUser.getUserId(), "DAR-0001000"); + DataAccessRequest nonLCDAR = + createDataAccessRequestWithUserIdV3(nonLCUser.getUserId(), "DAR-0002000"); Election lcElection = createDataAccessElection(lcDAR.getReferenceId(), datasetId); Election nonLCElection = createDataAccessElection(nonLCDAR.getReferenceId(), datasetId); List electionIds = List.of(lcElection.getElectionId(), nonLCElection.getElectionId()); - List elections = electionDAO.findElectionsWithCardHoldingUsersByElectionIds( - electionIds); + List elections = + electionDAO.findElectionsWithCardHoldingUsersByElectionIds(electionIds); assertEquals(1, elections.size()); assertEquals(elections.get(0).getElectionId(), lcElection.getElectionId()); @@ -465,12 +475,13 @@ void testInsertAndFindElection() { Date d = new Date(); - Integer id = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - d, - referenceId, - datasetId); + Integer id = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + d, + referenceId, + datasetId); Election e = electionDAO.findElectionById(id); @@ -479,7 +490,6 @@ void testInsertAndFindElection() { assertNotNull(e.getCreateDate()); assertEquals(referenceId, e.getReferenceId()); assertEquals(datasetId, e.getDatasetId()); - } @Test @@ -496,9 +506,7 @@ void testUpdateElectionById() { assertNull(before.getLastUpdate()); electionDAO.updateElectionById( - before.getElectionId(), - ElectionStatus.FINAL.getValue(), - new Date()); + before.getElectionId(), ElectionStatus.FINAL.getValue(), new Date()); Election after = electionDAO.findElectionById(before.getElectionId()); @@ -521,10 +529,7 @@ void testUpdateElectionById_FinalAccessVote() { assertNull(before.getFinalAccessVote()); electionDAO.updateElectionById( - before.getElectionId(), - ElectionStatus.FINAL.getValue(), - new Date(), - true); + before.getElectionId(), ElectionStatus.FINAL.getValue(), new Date(), true); Election after = electionDAO.findElectionById(before.getElectionId()); @@ -543,9 +548,7 @@ void testFindElectionWithFinalVoteById_NotFinal() { Election e = createDataAccessElection(referenceId, datasetId); - Election returned = - electionDAO.findElectionWithFinalVoteById( - e.getElectionId()); + Election returned = electionDAO.findElectionWithFinalVoteById(e.getElectionId()); assertNull(returned); } @@ -562,9 +565,7 @@ void testFindElectionWithFinalVoteById_Success() { Election e = createDataAccessElection(referenceId, datasetId); createFinalVote(user.getUserId(), e.getElectionId()); - Election returned = - electionDAO.findElectionWithFinalVoteById( - e.getElectionId()); + Election returned = electionDAO.findElectionWithFinalVoteById(e.getElectionId()); assertEquals(e.getElectionId(), returned.getElectionId()); } @@ -581,8 +582,9 @@ void testFindElectionsByIds() { Election datasetAccessElection = createDataAccessElection(referenceId, datasetId); Election rpElection = createRPElection(referenceId, datasetId); - List found = electionDAO.findElectionsByIds( - List.of(datasetAccessElection.getElectionId(), rpElection.getElectionId())); + List found = + electionDAO.findElectionsByIds( + List.of(datasetAccessElection.getElectionId(), rpElection.getElectionId())); assertEquals(2, found.size()); @@ -610,15 +612,15 @@ void testFindElectionById() { void testArchiveElectionByIds() { User user = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); Dataset d1 = createDataset(); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), d1.getDatasetId()); createRPElection(dar.getReferenceId(), d1.getDatasetId()); createDataAccessElection(dar.getReferenceId(), d1.getDatasetId()); - List elections = electionDAO.findElectionsByReferenceIdAndDatasetId( - dar.getReferenceId(), d1.getDatasetId()); + List elections = + electionDAO.findElectionsByReferenceIdAndDatasetId(dar.getReferenceId(), d1.getDatasetId()); List electionIds = elections.stream().map(Election::getElectionId).toList(); electionDAO.archiveElectionByIds(electionIds, new Date()); @@ -637,8 +639,7 @@ void testFindDacForElection() { Election e = createDataAccessElection(referenceId, datasetId); - assertEquals(dac.getDacId(), - electionDAO.findDacForElection(e.getElectionId()).getDacId()); + assertEquals(dac.getDacId(), electionDAO.findDacForElection(e.getElectionId()).getDacId()); } @Test @@ -655,10 +656,7 @@ void testFindOpenElectionsByDacId() { Election e3 = createDataAccessElection(referenceId, datasetId); Election closed = createDataAccessElection(referenceId, datasetId); electionDAO.updateElectionById( - closed.getElectionId(), - ElectionStatus.CLOSED.getValue(), - new Date() - ); + closed.getElectionId(), ElectionStatus.CLOSED.getValue(), new Date()); List found = electionDAO.findOpenElectionsByDacId(dac.getDacId()); @@ -700,20 +698,14 @@ private DataAccessRequest createDataAccessRequest(Integer userId, Integer collec String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDataAccessRequest( - collectionId, - referenceId, - userId, - now, now, now, - data, - randomAlphabetic(10)); + collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } private Dac createDac() { - Integer id = dacDAO.createDac( - "Test_" + randomAlphabetic(20), - "Test_" + randomAlphabetic(20), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphabetic(20), "Test_" + randomAlphabetic(20), new Date()); return dacDAO.findById(id); } @@ -723,8 +715,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphabetic(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -741,8 +733,9 @@ private void createDatasetProperties(Integer datasetId) { } private void createLibraryCard(User user) { - Integer id = libraryCardDAO.insertLibraryCard(user.getUserId(), - user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); + Integer id = + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); libraryCardDAO.findLibraryCardById(id); } @@ -757,31 +750,31 @@ private Dataset createDatasetWithDac(Integer dacId) { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphabetic(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), dacId); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), dacId); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } private Election createRPElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.RP.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.RP.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } private Election createDataAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/FileStorageObjectDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/FileStorageObjectDAOTest.java index de6ba9b0d6..7518ad50b2 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/FileStorageObjectDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/FileStorageObjectDAOTest.java @@ -28,30 +28,30 @@ void testInsertFile() { createFileStorageObject(); String fileName = RandomStringUtils.randomAlphabetic(10); - String category = FileCategory.getValues() - .get(new Random().nextInt(FileCategory.getValues().size())); - String gcsFileUri = BlobId.of( - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10)).toGsUtilUri(); + String category = + FileCategory.getValues().get(new Random().nextInt(FileCategory.getValues().size())); + String gcsFileUri = + BlobId.of(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10)) + .toGsUtilUri(); String mediaType = RandomStringUtils.randomAlphabetic(10); String entityId = RandomStringUtils.randomAlphabetic(10); User createUser = createUser(); Instant createDate = Instant.now(); - Integer newFileStorageObjectId = fileStorageObjectDAO.insertNewFile( - fileName, - category, - gcsFileUri, - mediaType, - entityId, - createUser.getUserId(), - createDate - ); + Integer newFileStorageObjectId = + fileStorageObjectDAO.insertNewFile( + fileName, + category, + gcsFileUri, + mediaType, + entityId, + createUser.getUserId(), + createDate); createFileStorageObject(); - FileStorageObject newFileStorageObject = fileStorageObjectDAO.findFileById( - newFileStorageObjectId); + FileStorageObject newFileStorageObject = + fileStorageObjectDAO.findFileById(newFileStorageObjectId); assertNotNull(newFileStorageObject); assertNotNull(newFileStorageObject.getFileStorageObjectId()); @@ -61,8 +61,8 @@ void testInsertFile() { assertEquals(mediaType, newFileStorageObject.getMediaType()); assertEquals(entityId, newFileStorageObject.getEntityId()); assertEquals(createUser.getUserId(), newFileStorageObject.getCreateUserId()); - assertEquals(createDate.getEpochSecond(), - newFileStorageObject.getCreateDate().getEpochSecond()); + assertEquals( + createDate.getEpochSecond(), newFileStorageObject.getCreateDate().getEpochSecond()); assertFalse(newFileStorageObject.getDeleted()); assertNull(newFileStorageObject.getUploadedFile()); } @@ -78,16 +78,15 @@ void testDeleteFileById() { assertNull(origFile.getDeleteUserId()); assertNull(origFile.getDeleteDate()); - fileStorageObjectDAO.deleteFileById(origFile.getFileStorageObjectId(), deleteUser.getUserId(), - deleteDate); + fileStorageObjectDAO.deleteFileById( + origFile.getFileStorageObjectId(), deleteUser.getUserId(), deleteDate); - FileStorageObject deletedFile = fileStorageObjectDAO.findFileById( - origFile.getFileStorageObjectId()); + FileStorageObject deletedFile = + fileStorageObjectDAO.findFileById(origFile.getFileStorageObjectId()); assertTrue(deletedFile.getDeleted()); assertEquals(deleteUser.getUserId(), deletedFile.getDeleteUserId()); - assertEquals(deleteDate.getEpochSecond(), - deletedFile.getDeleteDate().getEpochSecond()); + assertEquals(deleteDate.getEpochSecond(), deletedFile.getDeleteDate().getEpochSecond()); } @Test @@ -98,13 +97,13 @@ void testDeleteFileByEntityId() { User deleteUser = createUser(); Instant deleteDate = Instant.now(); - FileStorageObject file1 = createFileStorageObject(entityId, - FileCategory.IRB_COLLABORATION_LETTER); + FileStorageObject file1 = + createFileStorageObject(entityId, FileCategory.IRB_COLLABORATION_LETTER); FileStorageObject file2 = createFileStorageObject(entityId, FileCategory.DATA_USE_LETTER); - FileStorageObject file3 = createFileStorageObject(entityId, - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - FileStorageObject file4 = createFileStorageObject(otherEntityId, - FileCategory.IRB_COLLABORATION_LETTER); + FileStorageObject file3 = + createFileStorageObject(entityId, FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); + FileStorageObject file4 = + createFileStorageObject(otherEntityId, FileCategory.IRB_COLLABORATION_LETTER); assertFalse(file1.getDeleted()); assertNull(file1.getDeleteUserId()); @@ -128,16 +127,13 @@ void testDeleteFileByEntityId() { assertTrue(file1.getDeleted()); assertEquals(deleteUser.getUserId(), file1.getDeleteUserId()); - assertEquals(deleteDate.getEpochSecond(), - file1.getDeleteDate().getEpochSecond()); + assertEquals(deleteDate.getEpochSecond(), file1.getDeleteDate().getEpochSecond()); assertTrue(file2.getDeleted()); assertEquals(deleteUser.getUserId(), file2.getDeleteUserId()); - assertEquals(deleteDate.getEpochSecond(), - file2.getDeleteDate().getEpochSecond()); + assertEquals(deleteDate.getEpochSecond(), file2.getDeleteDate().getEpochSecond()); assertTrue(file3.getDeleted()); assertEquals(deleteUser.getUserId(), file3.getDeleteUserId()); - assertEquals(deleteDate.getEpochSecond(), - file3.getDeleteDate().getEpochSecond()); + assertEquals(deleteDate.getEpochSecond(), file3.getDeleteDate().getEpochSecond()); assertFalse(file4.getDeleted()); // should not be effected assertNull(file4.getDeleteUserId()); assertNull(file4.getDeleteDate()); @@ -149,15 +145,15 @@ void testFindFilesByEntityId() { createFileStorageObject(); createFileStorageObject(); // random other files - FileStorageObject file1 = createFileStorageObject(entityId, - FileCategory.IRB_COLLABORATION_LETTER); + FileStorageObject file1 = + createFileStorageObject(entityId, FileCategory.IRB_COLLABORATION_LETTER); FileStorageObject file2 = createFileStorageObject(entityId, FileCategory.DATA_USE_LETTER); - FileStorageObject file3 = createFileStorageObject(entityId, - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); + FileStorageObject file3 = + createFileStorageObject(entityId, FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); List filesFound = fileStorageObjectDAO.findFilesByEntityId(entityId); - List fileIdsfound = filesFound.stream().map(FileStorageObject::getFileStorageObjectId) - .toList(); + List fileIdsfound = + filesFound.stream().map(FileStorageObject::getFileStorageObjectId).toList(); assertEquals(3, filesFound.size()); assertTrue(fileIdsfound.contains(file1.getFileStorageObjectId())); @@ -172,17 +168,19 @@ void testFindFilesByEntityIdAndCategory() { // different entity id, same category, shouldn't be returned. createFileStorageObject("asdf", FileCategory.IRB_COLLABORATION_LETTER); createFileStorageObject(); - FileStorageObject file1 = createFileStorageObject(entityId, - FileCategory.IRB_COLLABORATION_LETTER); - FileStorageObject file2 = createFileStorageObject(entityId, - FileCategory.IRB_COLLABORATION_LETTER); - FileStorageObject file3 = createFileStorageObject(entityId, - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - - List irbFiles = fileStorageObjectDAO.findFilesByEntityIdAndCategory(entityId, - FileCategory.IRB_COLLABORATION_LETTER.getValue()); - List altDataSharingFiles = fileStorageObjectDAO.findFilesByEntityIdAndCategory( - entityId, FileCategory.ALTERNATIVE_DATA_SHARING_PLAN.getValue()); + FileStorageObject file1 = + createFileStorageObject(entityId, FileCategory.IRB_COLLABORATION_LETTER); + FileStorageObject file2 = + createFileStorageObject(entityId, FileCategory.IRB_COLLABORATION_LETTER); + FileStorageObject file3 = + createFileStorageObject(entityId, FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); + + List irbFiles = + fileStorageObjectDAO.findFilesByEntityIdAndCategory( + entityId, FileCategory.IRB_COLLABORATION_LETTER.getValue()); + List altDataSharingFiles = + fileStorageObjectDAO.findFilesByEntityIdAndCategory( + entityId, FileCategory.ALTERNATIVE_DATA_SHARING_PLAN.getValue()); assertEquals(2, irbFiles.size()); assertTrue(irbFiles.contains(file1)); @@ -208,8 +206,8 @@ void testDeleteFileStorageObjectByUserId() { } private FileStorageObject createFileStorageObject() { - FileCategory category = List.of(FileCategory.values()) - .get(new Random().nextInt(FileCategory.values().length)); + FileCategory category = + List.of(FileCategory.values()).get(new Random().nextInt(FileCategory.values().length)); String entityId = RandomStringUtils.randomAlphabetic(10); return createFileStorageObject(entityId, category); @@ -222,16 +220,15 @@ private FileStorageObject createFileStorageObject(String entityId, FileCategory User createUser = createUser(); Instant createDate = Instant.now(); - Integer newFileStorageObjectId = fileStorageObjectDAO.insertNewFile( - fileName, - category.getValue(), - bucketName, - gcsFileUri, - entityId, - createUser.getUserId(), - createDate - ); + Integer newFileStorageObjectId = + fileStorageObjectDAO.insertNewFile( + fileName, + category.getValue(), + bucketName, + gcsFileUri, + entityId, + createUser.getUserId(), + createDate); return fileStorageObjectDAO.findFileById(newFileStorageObjectId); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/InstitutionDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/InstitutionDAOTest.java index 4489681ba9..0c63934a96 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/InstitutionDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/InstitutionDAOTest.java @@ -47,11 +47,11 @@ void testInsertInstitutionDuplicateName() { null, null, userId, - institution.getCreateDate() - ); + institution.getCreateDate()); fail("CREATE should fail due to UNIQUE constraint violation (name)"); - //JBDI wraps ALL SQL exceptions under the generic class UnableToExecuteStatementException - //Test is specifically looking for UNIQUE constraint violations, so I need to catch and unwrap the error to confirm + // JBDI wraps ALL SQL exceptions under the generic class UnableToExecuteStatementException + // Test is specifically looking for UNIQUE constraint violations, so I need to catch and + // unwrap the error to confirm } catch (Exception e) { assertEquals("23505", ((PSQLException) e.getCause()).getSQLState()); } @@ -62,8 +62,18 @@ void testUpdateInstitutionById() { Integer userId = createUser().getUserId(); String newValue = "New Value"; Institution institution = createInstitution(); - institutionDAO.updateInstitutionById(institution.getId(), newValue, newValue, newValue, - newValue, 100, newValue, newValue, newValue, OrganizationType.FOR_PROFIT.getValue(), userId, + institutionDAO.updateInstitutionById( + institution.getId(), + newValue, + newValue, + newValue, + newValue, + 100, + newValue, + newValue, + newValue, + OrganizationType.FOR_PROFIT.getValue(), + userId, new Date()); Institution updated = institutionDAO.findInstitutionById(institution.getId()); assertEquals(newValue, updated.getName()); @@ -74,8 +84,7 @@ void testUpdateInstitutionById() { assertEquals(newValue, updated.getOrgChartUrl()); assertEquals(newValue, updated.getVerificationUrl()); assertEquals(newValue, updated.getVerificationFilename()); - assertEquals(OrganizationType.FOR_PROFIT.getValue(), - updated.getOrganizationType().getValue()); + assertEquals(OrganizationType.FOR_PROFIT.getValue(), updated.getOrganizationType().getValue()); } @Test @@ -83,7 +92,8 @@ void testUpdateInstitutionByIdDuplicateName() { Institution institution = createInstitution(); Institution secondInstitution = createInstitution(); try { - institutionDAO.updateInstitutionById(secondInstitution.getId(), + institutionDAO.updateInstitutionById( + secondInstitution.getId(), institution.getName(), secondInstitution.getItDirectorName(), secondInstitution.getItDirectorEmail(), @@ -128,12 +138,9 @@ void testFindInstitutionById() { Institution institutionFromDAO = institutionDAO.findInstitutionById(id); assertEquals(institutionFromDAO.getId(), institution.getId()); assertEquals(institutionFromDAO.getName(), institution.getName()); - assertEquals(institutionFromDAO.getItDirectorName(), - institution.getItDirectorName()); - assertEquals(institutionFromDAO.getItDirectorEmail(), - institution.getItDirectorEmail()); - assertEquals(institutionFromDAO.getCreateUserId(), - institution.getCreateUserId()); + assertEquals(institutionFromDAO.getItDirectorName(), institution.getItDirectorName()); + assertEquals(institutionFromDAO.getItDirectorEmail(), institution.getItDirectorEmail()); + assertEquals(institutionFromDAO.getCreateUserId(), institution.getCreateUserId()); assertEquals(institutionFromDAO.getCreateDate(), institution.getCreateDate()); } @@ -151,7 +158,7 @@ void testFindAllInstitutions_InstitutionWithSOs() { List instituteList = institutionDAO.findAllInstitutions(); assertEquals(0, instituteList.size()); - //inserts institution, inserts user with that institution id and SO role + // inserts institution, inserts user with that institution id and SO role User user = createUserWithInstitution(); List instituteListUpdated = institutionDAO.findAllInstitutions(); @@ -160,8 +167,7 @@ void testFindAllInstitutions_InstitutionWithSOs() { Institution institution = instituteListUpdated.get(0); assertEquals(1, institution.getSigningOfficials().size()); assertEquals(user.getInstitutionId(), institution.getId()); - assertEquals(user.getDisplayName(), - institution.getSigningOfficials().get(0).getDisplayName()); + assertEquals(user.getDisplayName(), institution.getSigningOfficials().get(0).getDisplayName()); } @Test @@ -178,8 +184,8 @@ void testFindInstitutionsByName() { void testFindInstitutionsByNameTrimsInput() { Institution institution = createInstitution(); - List found = institutionDAO.findInstitutionsByName( - " " + institution.getName() + " "); + List found = + institutionDAO.findInstitutionsByName(" " + institution.getName() + " "); assertFalse(found.isEmpty()); assertEquals(1, found.size()); assertEquals(institution.getId(), found.get(0).getId()); @@ -201,19 +207,16 @@ void testFindInstitutionsByNameTrimsDb() { institution.getVerificationFilename(), institution.getOrganizationType().getValue(), user.getUserId(), - new Date() - ); + new Date()); List found = institutionDAO.findInstitutionsByName(institution.getName()); assertFalse(found.isEmpty()); assertEquals(1, found.size()); assertEquals(institution.getId(), found.get(0).getId()); } - @Test void testFindInstitutionsByName_Missing() { - List found = institutionDAO.findInstitutionsByName( - randomAlphabetic(10)); + List found = institutionDAO.findInstitutionsByName(randomAlphabetic(10)); assertTrue(found.isEmpty()); } @@ -233,39 +236,43 @@ void testDeleteInstitutionWithDomainsByUserId() throws SQLException { Integer userId = institution.getCreateUserId(); institutionDAO.deleteAllInstitutionsByUser(userId); assertNull(institutionDAO.findInstitutionById(institution.getId())); - jdbi.useHandle(handle -> { - List domains = handle.createQuery( - "SELECT domain FROM institution_domains WHERE institution_id = :id") - .bind("id", institution.getId()) - .mapTo(String.class) - .list(); - assertTrue(domains.isEmpty(), "Domains should be deleted when institution is deleted"); - }); + jdbi.useHandle( + handle -> { + List domains = + handle + .createQuery("SELECT domain FROM institution_domains WHERE institution_id = :id") + .bind("id", institution.getId()) + .mapTo(String.class) + .list(); + assertTrue(domains.isEmpty(), "Domains should be deleted when institution is deleted"); + }); } @Test void testFindInstitutionWithSOById() { User user = createUserWithInstitution(); - Institution institutionWithSO = institutionDAO.findInstitutionWithSOById( - user.getInstitutionId()); + Institution institutionWithSO = + institutionDAO.findInstitutionWithSOById(user.getInstitutionId()); assertEquals(1, institutionWithSO.getSigningOfficials().size()); - assertEquals(user.getDisplayName(), - institutionWithSO.getSigningOfficials().get(0).getDisplayName()); + assertEquals( + user.getDisplayName(), institutionWithSO.getSigningOfficials().get(0).getDisplayName()); } private Institution createInstitution() { User createUser = createUser(); - Integer id = institutionDAO.insertInstitution(randomAlphabetic(20), - "itDirectorName", - "itDirectorEmail", - randomAlphabetic(10), - new Random().nextInt(), - randomAlphabetic(10), - randomAlphabetic(10), - randomAlphabetic(10), - OrganizationType.NON_PROFIT.getValue(), - createUser.getUserId(), - createUser.getCreateDate()); + Integer id = + institutionDAO.insertInstitution( + randomAlphabetic(20), + "itDirectorName", + "itDirectorEmail", + randomAlphabetic(10), + new Random().nextInt(), + randomAlphabetic(10), + randomAlphabetic(10), + randomAlphabetic(10), + OrganizationType.NON_PROFIT.getValue(), + createUser.getUserId(), + createUser.getCreateDate()); Institution institution = institutionDAO.findInstitutionById(id); User updateUser = createUser(); institutionDAO.updateInstitutionById( @@ -280,8 +287,7 @@ private Institution createInstitution() { institution.getVerificationFilename(), institution.getOrganizationType().getValue(), updateUser.getUserId(), - new Date() - ); + new Date()); return institutionDAO.findInstitutionById(id); } @@ -299,8 +305,8 @@ void testInsertFullInstitution() throws Exception { institution.setVerificationFilename("verification.pdf"); institution.setOrganizationType(OrganizationType.NON_PROFIT); institution.setDomains(List.of("domain1.com", "domain2.com")); - Institution insertedInstitution = institutionDAO.insertFullInstitution(institution, - user.getUserId()); + Institution insertedInstitution = + institutionDAO.insertFullInstitution(institution, user.getUserId()); assertEquals(institution.getName(), insertedInstitution.getName()); assertEquals(institution.getItDirectorName(), insertedInstitution.getItDirectorName()); @@ -309,10 +315,11 @@ void testInsertFullInstitution() throws Exception { assertEquals(institution.getDunsNumber(), insertedInstitution.getDunsNumber()); assertEquals(institution.getOrgChartUrl(), insertedInstitution.getOrgChartUrl()); assertEquals(institution.getVerificationUrl(), insertedInstitution.getVerificationUrl()); - assertEquals(institution.getVerificationFilename(), - insertedInstitution.getVerificationFilename()); + assertEquals( + institution.getVerificationFilename(), insertedInstitution.getVerificationFilename()); assertEquals(institution.getDomains().size(), insertedInstitution.getDomains().size()); - institution.getDomains() + institution + .getDomains() .forEach(domain -> assertTrue(insertedInstitution.getDomains().contains(domain))); } @@ -333,8 +340,8 @@ void testInsertFullInstitutionUniqueDomainException_Case1() { try { institutionDAO.insertFullInstitution(institution, user.getUserId()); } catch (Exception e) { - assertEquals(PSQLState.UNIQUE_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.UNIQUE_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } } @@ -353,8 +360,8 @@ void testUpdateFullInstitution() throws Exception { institution.setOrganizationType(OrganizationType.NON_PROFIT); institution.setDomains(List.of("domain1.com", "domain2.com")); - Institution insertedInstitution = institutionDAO.insertFullInstitution(institution, - user.getUserId()); + Institution insertedInstitution = + institutionDAO.insertFullInstitution(institution, user.getUserId()); insertedInstitution.setName("Updated Institution"); insertedInstitution.setItDirectorName("Updated Director"); @@ -368,8 +375,8 @@ void testUpdateFullInstitution() throws Exception { insertedInstitution.setDomains( List.of("new.domain1.com", "new.domain2.com", "new.domain3.com")); - Institution updatedInstitution = institutionDAO.updateFullInstitution(insertedInstitution, - user.getUserId()); + Institution updatedInstitution = + institutionDAO.updateFullInstitution(insertedInstitution, user.getUserId()); assertEquals(updatedInstitution.getName(), insertedInstitution.getName()); assertEquals(updatedInstitution.getItDirectorName(), insertedInstitution.getItDirectorName()); @@ -378,15 +385,17 @@ void testUpdateFullInstitution() throws Exception { assertEquals(updatedInstitution.getDunsNumber(), insertedInstitution.getDunsNumber()); assertEquals(updatedInstitution.getOrgChartUrl(), insertedInstitution.getOrgChartUrl()); assertEquals(updatedInstitution.getVerificationUrl(), insertedInstitution.getVerificationUrl()); - assertEquals(updatedInstitution.getVerificationFilename(), + assertEquals( + updatedInstitution.getVerificationFilename(), insertedInstitution.getVerificationFilename()); assertEquals(updatedInstitution.getDomains().size(), insertedInstitution.getDomains().size()); - updatedInstitution.getDomains() + updatedInstitution + .getDomains() .forEach(domain -> assertTrue(insertedInstitution.getDomains().contains(domain))); updatedInstitution.setDomains(null); // Reset domains to test deletion - Institution reloadedInstitution = institutionDAO.updateFullInstitution(updatedInstitution, - user.getUserId()); + Institution reloadedInstitution = + institutionDAO.updateFullInstitution(updatedInstitution, user.getUserId()); assertNull(reloadedInstitution.getDomains(), "Domains should be empty after update"); } @@ -395,15 +404,21 @@ void testUpdateFullInstitution() throws Exception { void testFindInstitutionByDomain(String domain) throws Exception { Institution institution = createMockInstitution(domain); User user = createUser(); - Institution fullInstitution = institutionDAO.insertFullInstitution(institution, user.getUserId()); + Institution fullInstitution = + institutionDAO.insertFullInstitution(institution, user.getUserId()); Institution foundInstitution1 = institutionDAO.findInstitutionByDomain(domain.toUpperCase()); assertEquals(fullInstitution.getId(), foundInstitution1.getId()); - assertTrue(foundInstitution1.getDomains().contains(domain), "Domain should be found in institution's domains"); + assertTrue( + foundInstitution1.getDomains().contains(domain), + "Domain should be found in institution's domains"); Institution foundInstitution2 = institutionDAO.findInstitutionByDomain(domain.toLowerCase()); assertEquals(fullInstitution.getId(), foundInstitution2.getId()); - assertTrue(foundInstitution2.getDomains().contains(domain), "Domain should be found in institution's domains"); - Institution notFoundInstitution = institutionDAO.findInstitutionByDomain("nonexistentdomain.org"); + assertTrue( + foundInstitution2.getDomains().contains(domain), + "Domain should be found in institution's domains"); + Institution notFoundInstitution = + institutionDAO.findInstitutionByDomain("nonexistentdomain.org"); assertNull(notFoundInstitution, "Should return null for non-existent domain"); } @@ -412,7 +427,8 @@ void testFindInstitutionByDomain(String domain) throws Exception { void testFindInstitutionIdByDomain(String domain) throws Exception { Institution institution = createMockInstitution(domain); User user = createUser(); - Institution fullInstitution = institutionDAO.insertFullInstitution(institution, user.getUserId()); + Institution fullInstitution = + institutionDAO.insertFullInstitution(institution, user.getUserId()); Integer foundId1 = institutionDAO.findInstitutionIdByDomain(domain.toUpperCase()); assertEquals(fullInstitution.getId(), foundId1); diff --git a/src/test/java/org/broadinstitute/consent/http/db/LibraryCardDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/LibraryCardDAOTest.java index 77651e37eb..0aae4ea9c3 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/LibraryCardDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/LibraryCardDAOTest.java @@ -38,21 +38,21 @@ void testInsertLibraryCardFKConstraintErrors() { User user = createUser(); // Test FK on library_card.user_id try { - libraryCardDAO.insertLibraryCard(0, user.getDisplayName(), user.getEmail(), - user.getUserId(), new Date()); + libraryCardDAO.insertLibraryCard( + 0, user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); fail("Should have thrown a FOREIGN_KEY_VIOLATION exception"); } catch (Exception e) { - assertEquals(PSQLState.FOREIGN_KEY_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.FOREIGN_KEY_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } // Test FK on library_card.create_user_id try { - libraryCardDAO.insertLibraryCard(user.getUserId(), user.getDisplayName(), user.getEmail(), 0, - new Date()); + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), 0, new Date()); fail("Should have thrown a FOREIGN_KEY_VIOLATION exception"); } catch (Exception e) { - assertEquals(PSQLState.FOREIGN_KEY_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.FOREIGN_KEY_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } } @@ -60,26 +60,34 @@ void testInsertLibraryCardFKConstraintErrors() { void testInsertLibraryCardUniqueConstraintErrors() { User user1 = createUser(); // Set up LC that will trigger the unique constraints on subsequent inserts - libraryCardDAO.insertLibraryCard(user1.getUserId(), user1.getDisplayName(), user1.getEmail(), - user1.getUserId(), new Date()); + libraryCardDAO.insertLibraryCard( + user1.getUserId(), user1.getDisplayName(), user1.getEmail(), user1.getUserId(), new Date()); // Test Unique on library_card.user_id try { - libraryCardDAO.insertLibraryCard(user1.getUserId(), user1.getDisplayName(), user1.getEmail(), - user1.getUserId(), new Date()); + libraryCardDAO.insertLibraryCard( + user1.getUserId(), + user1.getDisplayName(), + user1.getEmail(), + user1.getUserId(), + new Date()); fail("Should have thrown a UNIQUE_VIOLATION exception"); } catch (Exception e) { - assertEquals(PSQLState.UNIQUE_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.UNIQUE_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } User user2 = createUser(); // Test Unique on library_card.user_email - note that we're using the same email as user1 try { - libraryCardDAO.insertLibraryCard(user2.getUserId(), user2.getDisplayName(), user1.getEmail(), - user2.getUserId(), new Date()); + libraryCardDAO.insertLibraryCard( + user2.getUserId(), + user2.getDisplayName(), + user1.getEmail(), + user2.getUserId(), + new Date()); fail("Should have thrown a UNIQUE_VIOLATION exception"); } catch (Exception e) { - assertEquals(PSQLState.UNIQUE_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.UNIQUE_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } } @@ -96,8 +104,8 @@ void testDeleteLibraryCardByIdNegative() { try { libraryCardDAO.deleteLibraryCardById(randomInt(1, 1000)); } catch (Exception e) { - assertEquals(PSQLState.UNIQUE_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.UNIQUE_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } } @@ -107,11 +115,13 @@ void testDeleteLibraryCardWithDaaRelationships() { // 1. Library Card for a user as a top level object that will be deleted // 2. Dac so we can create a DAA // 3. DAA so we can link it to a user's Library Card - // 4. Library Card <-> DAA relationship that represents a Signing Official's acceptance of a DAA for the user + // 4. Library Card <-> DAA relationship that represents a Signing Official's acceptance of a DAA + // for the user LibraryCard card = createLibraryCard(); int dacId = dacDAO.createDac(randomAlphabetic(10), randomAlphabetic(10), new Date()); - int daaId = daaDAO.createDaa(card.getCreateUserId(), Instant.now(), card.getCreateUserId(), - Instant.now(), dacId); + int daaId = + daaDAO.createDaa( + card.getCreateUserId(), Instant.now(), card.getCreateUserId(), Instant.now(), dacId); daaDAO.createDacDaaRelation(dacId, daaId); libraryCardDAO.createLibraryCardDaaRelation(card.getId(), daaId); @@ -142,10 +152,10 @@ void testFindLibraryCardDaaByIdMultipleDaas() { LibraryCard card = createLibraryCard(); Integer userId = createUser().getUserId(); Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, - new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, - new Date().toInstant(), dacId); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); DataAccessAgreement daa1 = daaDAO.findById(daaId1); DataAccessAgreement daa2 = daaDAO.findById(daaId2); card.addDaa(daa1.getDaaId()); @@ -207,11 +217,11 @@ void testFindLibraryCardByInstitutionId() { Institution institution = createInstitution(); int userId = institution.getCreateUserId(); String stringValue = "value"; - Integer lcId = libraryCardDAO.insertLibraryCard(userId, stringValue, - stringValue, userId, new Date()); + Integer lcId = + libraryCardDAO.insertLibraryCard(userId, stringValue, stringValue, userId, new Date()); userDAO.updateInstitutionId(userId, institution.getId()); - List cardsFromDAO = libraryCardDAO.findLibraryCardsByInstitutionId( - institution.getId()); + List cardsFromDAO = + libraryCardDAO.findLibraryCardsByInstitutionId(institution.getId()); assertNotNull(cardsFromDAO); assertEquals(1, cardsFromDAO.size()); @@ -222,8 +232,8 @@ void testFindLibraryCardByInstitutionId() { @Test void testFindLibraryCardByUserIdInstitutionId() { LibraryCard libraryCard = createLibraryCard(); - int dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), randomAlphabetic(5), - new Date()); + int dacId = + dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), randomAlphabetic(5), new Date()); Instant now = Instant.now(); int daaId = daaDAO.createDaa(libraryCard.getUserId(), now, libraryCard.getUserId(), now, dacId); daaDAO.createDacDaaRelation(dacId, daaId); @@ -279,10 +289,10 @@ void testCreateLibraryCardDaaAssociation() { Integer userId = user.getUserId(); Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, - new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, - new Date().toInstant(), dacId2); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); libraryCardDAO.createLibraryCardDaaRelation(card.getId(), daaId1); libraryCardDAO.createLibraryCardDaaRelation(card.getId(), daaId2); libraryCardDAO.createLibraryCardDaaRelation(card2.getId(), daaId1); @@ -302,21 +312,21 @@ void testCreateLibraryCardDaaAssociationInvalid() { LibraryCard card = createLibraryCard(user); Integer userId = user.getUserId(); Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, - new Date().toInstant(), dacId); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); try { libraryCardDAO.createLibraryCardDaaRelation(card.getId(), 2); } catch (Exception e) { - assertEquals(PSQLState.FOREIGN_KEY_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.FOREIGN_KEY_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } try { libraryCardDAO.createLibraryCardDaaRelation(2, daaId1); } catch (Exception e) { - assertEquals(PSQLState.FOREIGN_KEY_VIOLATION.getState(), - ((PSQLException) e.getCause()).getSQLState()); + assertEquals( + PSQLState.FOREIGN_KEY_VIOLATION.getState(), ((PSQLException) e.getCause()).getSQLState()); } List lcs = libraryCardDAO.findAllLibraryCards(); @@ -333,10 +343,10 @@ void testDeleteLibraryCardDaaAssociation() { Integer userId = user.getUserId(); Integer dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); Integer dacId2 = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), "", new Date()); - Integer daaId1 = daaDAO.createDaa(userId, new Date().toInstant(), userId, - new Date().toInstant(), dacId); - Integer daaId2 = daaDAO.createDaa(userId, new Date().toInstant(), userId, - new Date().toInstant(), dacId2); + Integer daaId1 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId); + Integer daaId2 = + daaDAO.createDaa(userId, new Date().toInstant(), userId, new Date().toInstant(), dacId2); libraryCardDAO.createLibraryCardDaaRelation(card.getId(), daaId1); libraryCardDAO.createLibraryCardDaaRelation(card.getId(), daaId2); @@ -366,8 +376,10 @@ void testFindByUserEmails() { // This card will not be returned since its email is not in the list LibraryCard card4 = createLibraryCard(createUser()); - List cardsFromDAO = libraryCardDAO.findByUserEmails( - List.of(user1.getEmail().toLowerCase(), user2.getEmail().toUpperCase(), user3.getEmail())); + List cardsFromDAO = + libraryCardDAO.findByUserEmails( + List.of( + user1.getEmail().toLowerCase(), user2.getEmail().toUpperCase(), user3.getEmail())); assertEquals(3, cardsFromDAO.size()); assertTrue(cardsFromDAO.contains(card1)); @@ -377,9 +389,21 @@ void testFindByUserEmails() { } @ParameterizedTest - @ValueSource(strings = {"", " ", "invalid-email", "user@domain", "user@domain.", "@domain.com", - "user@.com", "user_@domain.com", "user%@domain.com", "user*@domain.com", "user.@domain.com", - "user-@domain.com"}) + @ValueSource( + strings = { + "", + " ", + "invalid-email", + "user@domain", + "user@domain.", + "@domain.com", + "user@.com", + "user_@domain.com", + "user%@domain.com", + "user*@domain.com", + "user.@domain.com", + "user-@domain.com" + }) void testFindByUserEmailsWithSpecialCharacters(String email) { Integer userId = userDAO.insertUser(email, "display name", null, new Date()); userRoleDAO.insertSingleUserRole(UserRoles.RESEARCHER.getRoleId(), userId); @@ -391,22 +415,30 @@ void testFindByUserEmailsWithSpecialCharacters(String email) { @Test void testFindByUserEmailsWithConflictingSpecialCharacters() { - List emails = List.of("user_@domain.com", "user%@domain.com", "user*@domain.com", - "user.@domain.com", "user-@domain.com"); + List emails = + List.of( + "user_@domain.com", + "user%@domain.com", + "user*@domain.com", + "user.@domain.com", + "user-@domain.com"); // Create users with emails that have special characters that could conflict with SQL queries - emails.forEach(email -> { - Integer userId = userDAO.insertUser(email, "display name " + randomAlphabetic(25), null, - new Date()); - userRoleDAO.insertSingleUserRole(UserRoles.RESEARCHER.getRoleId(), userId); - User user = userDAO.findUserById(userId); - createLibraryCard(user); - }); - - // Fetch library cards by emails and ensure that multiples (due to regexes in emails) are not returned - emails.forEach(email -> { - List cards = libraryCardDAO.findByUserEmails(List.of(email)); - assertEquals(1, cards.size(), "Should return exactly one card for email: " + email); - }); + emails.forEach( + email -> { + Integer userId = + userDAO.insertUser(email, "display name " + randomAlphabetic(25), null, new Date()); + userRoleDAO.insertSingleUserRole(UserRoles.RESEARCHER.getRoleId(), userId); + User user = userDAO.findUserById(userId); + createLibraryCard(user); + }); + + // Fetch library cards by emails and ensure that multiples (due to regexes in emails) are not + // returned + emails.forEach( + email -> { + List cards = libraryCardDAO.findByUserEmails(List.of(email)); + assertEquals(1, cards.size(), "Should return exactly one card for email: " + email); + }); } @Test @@ -420,8 +452,9 @@ void testFindByUserIds() { // This card will not be returned since its email is not in the list LibraryCard card4 = createLibraryCard(createUser()); - List cardsFromDAO = libraryCardDAO.findLibraryCardsByUserIds( - List.of(user1.getUserId(), user2.getUserId(), user3.getUserId())); + List cardsFromDAO = + libraryCardDAO.findLibraryCardsByUserIds( + List.of(user1.getUserId(), user2.getUserId(), user3.getUserId())); assertEquals(3, cardsFromDAO.size()); assertTrue(cardsFromDAO.contains(card1)); @@ -433,9 +466,8 @@ void testFindByUserIds() { private LibraryCard createLibraryCardForIndex() { Integer userId = createUser().getUserId(); String stringValue = "value"; - Integer id = libraryCardDAO.insertLibraryCard(userId, stringValue, - stringValue, - userId, new Date()); + Integer id = + libraryCardDAO.insertLibraryCard(userId, stringValue, stringValue, userId, new Date()); return libraryCardDAO.findLibraryCardById(id); } @@ -448,15 +480,15 @@ private LibraryCard createLibraryCard() { int userId = institution.getCreateUserId(); String stringValue = "value"; - Integer id = libraryCardDAO.insertLibraryCard(userId, stringValue, - stringValue, userId, new Date()); + Integer id = + libraryCardDAO.insertLibraryCard(userId, stringValue, stringValue, userId, new Date()); return libraryCardDAO.findLibraryCardById(id); } private LibraryCard createLibraryCard(User user) { - Integer id = libraryCardDAO.insertLibraryCard(user.getUserId(), - user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); + Integer id = + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); return libraryCardDAO.findLibraryCardById(id); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/MailMessageDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/MailMessageDAOTest.java index 908ffd235f..2a9770e24c 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/MailMessageDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/MailMessageDAOTest.java @@ -25,121 +25,123 @@ class MailMessageDAOTest extends DAOTestHelper { @Test void testInsert_AllFields() { Instant now = Instant.now(); - Integer mailId = mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - now, - randomAlphanumeric(10), - randomAlphanumeric(10), - randomInt(200, 399), - now - ); + Integer mailId = + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + now, + randomAlphanumeric(10), + randomAlphanumeric(10), + randomInt(200, 399), + now); assertNotNull(mailId); } @Test void testInsert_AllEmailTypes() { - EnumSet.allOf(EmailType.class).forEach(t -> { - Instant now = Instant.now(); - Integer mailId = mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - t.getTypeInt(), - now, - randomAlphanumeric(10), - randomAlphanumeric(10), - randomInt(200, 399), - now - ); - assertNotNull(mailId); - }); + EnumSet.allOf(EmailType.class) + .forEach( + t -> { + Instant now = Instant.now(); + Integer mailId = + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + t.getTypeInt(), + now, + randomAlphanumeric(10), + randomAlphanumeric(10), + randomInt(200, 399), + now); + assertNotNull(mailId); + }); } @Test void testInsert_NullEntityReferenceId() { Instant now = Instant.now(); - Integer mailId = mailMessageDAO.insert( - null, - randomInt(1, 1000), - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - now, - randomAlphanumeric(10), - randomAlphanumeric(10), - randomInt(200, 399), - now - ); + Integer mailId = + mailMessageDAO.insert( + null, + randomInt(1, 1000), + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + now, + randomAlphanumeric(10), + randomAlphanumeric(10), + randomInt(200, 399), + now); assertNotNull(mailId); } @Test void testInsert_NullVoteId() { Instant now = Instant.now(); - Integer mailId = mailMessageDAO.insert( - randomAlphanumeric(10), - null, - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - now, - randomAlphanumeric(10), - randomAlphanumeric(10), - randomInt(200, 399), - now - ); + Integer mailId = + mailMessageDAO.insert( + randomAlphanumeric(10), + null, + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + now, + randomAlphanumeric(10), + randomAlphanumeric(10), + randomInt(200, 399), + now); assertNotNull(mailId); } @Test void testInsert_NullDateSent() { Instant now = Instant.now(); - Integer mailId = mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - null, - randomAlphanumeric(10), - randomAlphanumeric(10), - randomInt(200, 399), - now - ); + Integer mailId = + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + null, + randomAlphanumeric(10), + randomAlphanumeric(10), + randomInt(200, 399), + now); assertNotNull(mailId); } @Test void testInsert_NullSendGridResponse() { Instant now = Instant.now(); - Integer mailId = mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - now, - randomAlphanumeric(10), - null, - randomInt(200, 399), - now - ); + Integer mailId = + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + now, + randomAlphanumeric(10), + null, + randomInt(200, 399), + now); assertNotNull(mailId); } @Test void testInsert_NullSendGridStatus() { Instant now = Instant.now(); - Integer mailId = mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - now, - randomAlphanumeric(10), - randomAlphanumeric(10), - null, - now - ); + Integer mailId = + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + now, + randomAlphanumeric(10), + randomAlphanumeric(10), + null, + now); assertNotNull(mailId); } @@ -150,17 +152,19 @@ void testInsert_MissingUserId() { Integer voteId = randomInt(1, 1000); String sendGridResponse = randomAlphanumeric(10); Integer sendGridStatus = randomInt(200, 399); - assertThrows(UnableToExecuteStatementException.class, () -> mailMessageDAO.insert( - entityReferenceId, - voteId, - null, - null, - now, - null, - sendGridResponse, - sendGridStatus, - null - )); + assertThrows( + UnableToExecuteStatementException.class, + () -> + mailMessageDAO.insert( + entityReferenceId, + voteId, + null, + null, + now, + null, + sendGridResponse, + sendGridStatus, + null)); } @Test @@ -171,17 +175,19 @@ void testInsert_MissingEmailType() { Integer userId = randomInt(1, 1000); String sendGridResponse = randomAlphanumeric(10); Integer sendGridStatus = randomInt(200, 399); - assertThrows(UnableToExecuteStatementException.class, () -> mailMessageDAO.insert( - entityReferenceId, - voteId, - userId, - null, - now, - null, - sendGridResponse, - sendGridStatus, - null - )); + assertThrows( + UnableToExecuteStatementException.class, + () -> + mailMessageDAO.insert( + entityReferenceId, + voteId, + userId, + null, + now, + null, + sendGridResponse, + sendGridStatus, + null)); } @Test @@ -193,17 +199,19 @@ void testInsert_MissingEmailText() { Integer emailType = EmailType.COLLECT.getTypeInt(); String sendGridResponse = randomAlphanumeric(10); Integer sendGridStatus = randomInt(200, 399); - assertThrows(UnableToExecuteStatementException.class, () -> mailMessageDAO.insert( - entityReferenceId, - voteId, - userId, - emailType, - now, - null, - sendGridResponse, - sendGridStatus, - null - )); + assertThrows( + UnableToExecuteStatementException.class, + () -> + mailMessageDAO.insert( + entityReferenceId, + voteId, + userId, + emailType, + now, + null, + sendGridResponse, + sendGridStatus, + null)); } @Test @@ -216,39 +224,42 @@ void testInsert_MissingCreateDate() { String emailText = randomAlphanumeric(10); String sendGridResponse = randomAlphanumeric(10); Integer sendGridStatus = randomInt(200, 399); - assertThrows(UnableToExecuteStatementException.class, () -> mailMessageDAO.insert( - entityReferenceId, - voteId, - userId, - emailType, - now, - emailText, - sendGridResponse, - sendGridStatus, - null - )); + assertThrows( + UnableToExecuteStatementException.class, + () -> + mailMessageDAO.insert( + entityReferenceId, + voteId, + userId, + emailType, + now, + emailText, + sendGridResponse, + sendGridStatus, + null)); } @Test void testFetch() { - EnumSet.allOf(EmailType.class).forEach(t -> { - Instant now = Instant.now(); - mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - t.getTypeInt(), - now, - randomAlphanumeric(10), - randomAlphanumeric(10), - randomInt(200, 399), - now - ); - }); - - EnumSet.allOf(EmailType.class).forEach(t -> - assertEquals(1, - mailMessageDAO.fetchMessagesByType(t.getTypeInt(), 1, 0).size())); + EnumSet.allOf(EmailType.class) + .forEach( + t -> { + Instant now = Instant.now(); + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + t.getTypeInt(), + now, + randomAlphanumeric(10), + randomAlphanumeric(10), + randomInt(200, 399), + now); + }); + + EnumSet.allOf(EmailType.class) + .forEach( + t -> assertEquals(1, mailMessageDAO.fetchMessagesByType(t.getTypeInt(), 1, 0).size())); } @Test @@ -263,36 +274,35 @@ void testFetchLimitAndOffset() { randomAlphanumeric(10), randomAlphanumeric(10), randomInt(200, 399), - now - ); + now); - List mailMessageList = mailMessageDAO.fetchMessagesByType( - EmailType.COLLECT.getTypeInt(), 1, 0); + List mailMessageList = + mailMessageDAO.fetchMessagesByType(EmailType.COLLECT.getTypeInt(), 1, 0); assertEquals(1, mailMessageList.size()); - List mailMessageList2 = mailMessageDAO.fetchMessagesByType( - EmailType.COLLECT.getTypeInt(), 1, 1); + List mailMessageList2 = + mailMessageDAO.fetchMessagesByType(EmailType.COLLECT.getTypeInt(), 1, 1); assertEquals(0, mailMessageList2.size()); - Integer mailId2 = mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - now, - randomAlphanumeric(10), - randomAlphanumeric(10), - null, - now - ); - - List mailMessageList3 = mailMessageDAO.fetchMessagesByType( - EmailType.COLLECT.getTypeInt(), 1, 1); + Integer mailId2 = + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + now, + randomAlphanumeric(10), + randomAlphanumeric(10), + null, + now); + + List mailMessageList3 = + mailMessageDAO.fetchMessagesByType(EmailType.COLLECT.getTypeInt(), 1, 1); assertEquals(1, mailMessageList3.size()); assertEquals(mailId2, mailMessageList3.get(0).getEmailId()); - List mailMessageList4 = mailMessageDAO.fetchMessagesByType( - EmailType.COLLECT.getTypeInt(), 20, 0); + List mailMessageList4 = + mailMessageDAO.fetchMessagesByType(EmailType.COLLECT.getTypeInt(), 20, 0); assertEquals(2, mailMessageList4.size()); } @@ -309,11 +319,10 @@ void testFetchByUserId() { randomAlphanumeric(10), randomAlphanumeric(10), randomInt(200, 399), - now - ); + now); - List mailMessageList = mailMessageDAO.fetchMessagesByUserId( - user.getUserId(), 10, 0); + List mailMessageList = + mailMessageDAO.fetchMessagesByUserId(user.getUserId(), 10, 0); assertEquals(1, mailMessageList.size()); assertEquals(user.getUserId(), mailMessageList.get(0).getUserId()); @@ -326,16 +335,15 @@ void testFetchByUserId() { randomAlphanumeric(10), randomAlphanumeric(10), randomInt(200, 399), - now - ); - List mailMessageList2 = mailMessageDAO.fetchMessagesByUserId( - user.getUserId(), 10, 0); + now); + List mailMessageList2 = + mailMessageDAO.fetchMessagesByUserId(user.getUserId(), 10, 0); assertEquals(2, mailMessageList2.size()); assertEquals(user.getUserId(), mailMessageList2.get(0).getUserId()); User user2 = createUser(); - List mailMessageList3 = mailMessageDAO.fetchMessagesByUserId( - user2.getUserId(), 10, 0); + List mailMessageList3 = + mailMessageDAO.fetchMessagesByUserId(user2.getUserId(), 10, 0); assertEquals(0, mailMessageList3.size()); } @@ -352,16 +360,19 @@ void testFetchByCreateDate_with_limit_and_offset() { Instant todayStart = LocalDate.now().atStartOfDay().toInstant(ZoneOffset.UTC); Instant tomorrowStart = LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.UTC); - // Find messages from beginning of today to the beginning of tomorrow. Should return `messageToday` - List messages = mailMessageDAO - .fetchMessagesByCreateDate(Date.from(todayStart), Date.from(tomorrowStart), 1, 0); + // Find messages from beginning of today to the beginning of tomorrow. Should return + // `messageToday` + List messages = + mailMessageDAO.fetchMessagesByCreateDate( + Date.from(todayStart), Date.from(tomorrowStart), 1, 0); assertEquals(1, messages.size()); assertEquals(messageToday.getEmailId(), messages.get(0).getEmailId()); // Find messages from beginning of yesterday to tomorrow. Should return both messages. // Order is create date descending, so today is first, yesterday second. - List messages2 = mailMessageDAO - .fetchMessagesByCreateDate(Date.from(yesterdayStart), Date.from(tomorrowStart), 2, 0); + List messages2 = + mailMessageDAO.fetchMessagesByCreateDate( + Date.from(yesterdayStart), Date.from(tomorrowStart), 2, 0); assertEquals(2, messages2.size()); assertEquals(messageToday.getEmailId(), messages2.get(0).getEmailId()); assertEquals(messageYesterday.getEmailId(), messages2.get(1).getEmailId()); @@ -369,30 +380,33 @@ void testFetchByCreateDate_with_limit_and_offset() { // Find messages from beginning of yesterday to tomorrow, offset by 1. Since messages are // ordered by create date descending, offset should trim today's message and only return // yesterday's message. - List messages3 = mailMessageDAO - .fetchMessagesByCreateDate(Date.from(yesterdayStart), Date.from(tomorrowStart), 2, 1); + List messages3 = + mailMessageDAO.fetchMessagesByCreateDate( + Date.from(yesterdayStart), Date.from(tomorrowStart), 2, 1); assertEquals(1, messages3.size()); assertEquals(messageYesterday.getEmailId(), messages3.get(0).getEmailId()); - // Find messages from beginning of yesterday to beginning today. Should return yesterday's message. - List messages4 = mailMessageDAO - .fetchMessagesByCreateDate(Date.from(yesterdayStart), Date.from(todayStart), 2, 0); + // Find messages from beginning of yesterday to beginning today. Should return yesterday's + // message. + List messages4 = + mailMessageDAO.fetchMessagesByCreateDate( + Date.from(yesterdayStart), Date.from(todayStart), 2, 0); assertEquals(1, messages4.size()); assertEquals(messageYesterday.getEmailId(), messages4.get(0).getEmailId()); } private MailMessage generateMessage(Instant instant) { - Integer messageId = mailMessageDAO.insert( - randomAlphanumeric(10), - randomInt(1, 1000), - randomInt(1, 1000), - EmailType.COLLECT.getTypeInt(), - instant, - randomAlphanumeric(10), - randomAlphanumeric(10), - randomInt(200, 399), - instant - ); + Integer messageId = + mailMessageDAO.insert( + randomAlphanumeric(10), + randomInt(1, 1000), + randomInt(1, 1000), + EmailType.COLLECT.getTypeInt(), + instant, + randomAlphanumeric(10), + randomAlphanumeric(10), + randomInt(200, 399), + instant); return mailMessageDAO.fetchMessageById(messageId); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/MatchDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/MatchDAOTest.java index 942c94d83b..7874f583fb 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/MatchDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/MatchDAOTest.java @@ -80,33 +80,50 @@ void testCountMatchesByResult() { @Test void testFindMatchesForLatestDataAccessElectionsByPurposeIds() { Dataset dataset = createDataset(); - //query should pull the latest election for a given reference id - //creating two access elections with the same reference id and datasetid to test that condition + // query should pull the latest election for a given reference id + // creating two access elections with the same reference id and datasetid to test that condition String darReferenceId = UUID.randomUUID().toString(); - Election targetElection = createDataAccessElection( - darReferenceId, dataset.getDatasetId() - ); - Election ignoredAccessElection = createDataAccessElection( - UUID.randomUUID().toString(), dataset.getDatasetId() - ); + Election targetElection = createDataAccessElection(darReferenceId, dataset.getDatasetId()); + Election ignoredAccessElection = + createDataAccessElection(UUID.randomUUID().toString(), dataset.getDatasetId()); - //Generate RP election to test that the query only references DataAccess elections + // Generate RP election to test that the query only references DataAccess elections Election rpElection = createRPElection(UUID.randomUUID().toString(), dataset.getDatasetId()); String datasetIdentifier = dataset.getDatasetIdentifier(); - //This match represents the match record generated for the target election - matchDAO.insertMatch(datasetIdentifier, darReferenceId, true, false, new Date(), MatchAlgorithm.V4.getVersion(), false); + // This match represents the match record generated for the target election + matchDAO.insertMatch( + datasetIdentifier, + darReferenceId, + true, + false, + new Date(), + MatchAlgorithm.V4.getVersion(), + false); // This match represents the match record generated for the ignored access election - matchDAO.insertMatch(datasetIdentifier, ignoredAccessElection.getReferenceId(), false, false, - new Date(), MatchAlgorithm.V4.getVersion(), false); + matchDAO.insertMatch( + datasetIdentifier, + ignoredAccessElection.getReferenceId(), + false, + false, + new Date(), + MatchAlgorithm.V4.getVersion(), + false); // This match is never created under consent's workflow (unless the cause is a bug) // This is included simply to test the DataAccess conditional on the INNER JOIN statement - matchDAO.insertMatch(datasetIdentifier, rpElection.getReferenceId(), false, false, new Date(), MatchAlgorithm.V4.getVersion(), true); + matchDAO.insertMatch( + datasetIdentifier, + rpElection.getReferenceId(), + false, + false, + new Date(), + MatchAlgorithm.V4.getVersion(), + true); - List matchResults = matchDAO.findMatchesForLatestDataAccessElectionsByPurposeIds( - List.of(darReferenceId)); + List matchResults = + matchDAO.findMatchesForLatestDataAccessElectionsByPurposeIds(List.of(darReferenceId)); assertEquals(1, matchResults.size()); Match result = matchResults.get(0); assertEquals(targetElection.getReferenceId(), result.getPurpose()); @@ -117,39 +134,56 @@ void testFindMatchesForLatestDataAccessElectionsByPurposeIds_NegativeTest() { Dataset dataset = createDataset(); String darReferenceId = UUID.randomUUID().toString(); - //Generate access election for test - Election accessElection = createDataAccessElection( - UUID.randomUUID().toString(), dataset.getDatasetId()); + // Generate access election for test + Election accessElection = + createDataAccessElection(UUID.randomUUID().toString(), dataset.getDatasetId()); - //Generate RP election for test + // Generate RP election for test Election rpElection = createRPElection(darReferenceId, dataset.getDatasetId()); String datasetIdentifier = dataset.getDatasetIdentifier(); // This match represents the match record generated for the access election - matchDAO.insertMatch(datasetIdentifier, accessElection.getReferenceId(), true, false, new Date(), MatchAlgorithm.V4.getVersion(), false); + matchDAO.insertMatch( + datasetIdentifier, + accessElection.getReferenceId(), + true, + false, + new Date(), + MatchAlgorithm.V4.getVersion(), + false); // This match is never created under consent's workflow (unless the cause is a bug) // This is included simply to test the DataAccess conditional on the INNER JOIN statement - matchDAO.insertMatch(datasetIdentifier, rpElection.getReferenceId(), false, false, new Date(), MatchAlgorithm.V4.getVersion(), false); - - //Negative testing means we'll feed the query a reference id that isn't tied to a DataAccess election - //Again, a match like this usually isn't generated in a normal workflow unless bug occurs, but having the 'DataAccess' condition is a nice safety net - List matchResults = matchDAO.findMatchesForLatestDataAccessElectionsByPurposeIds( - List.of(darReferenceId)); + matchDAO.insertMatch( + datasetIdentifier, + rpElection.getReferenceId(), + false, + false, + new Date(), + MatchAlgorithm.V4.getVersion(), + false); + + // Negative testing means we'll feed the query a reference id that isn't tied to a DataAccess + // election + // Again, a match like this usually isn't generated in a normal workflow unless bug occurs, but + // having the 'DataAccess' condition is a nice safety net + List matchResults = + matchDAO.findMatchesForLatestDataAccessElectionsByPurposeIds(List.of(darReferenceId)); assertTrue(matchResults.isEmpty()); } @Test void testFindMatchById() { Match match = makeMockMatch(UUID.randomUUID().toString()); - Integer matchId = matchDAO.insertMatch( - match.getConsent(), - match.getPurpose(), - match.getMatch(), - match.getFailed(), - match.getCreateDate(), - match.getAlgorithmVersion(), - match.getAbstain()); + Integer matchId = + matchDAO.insertMatch( + match.getConsent(), + match.getPurpose(), + match.getMatch(), + match.getFailed(), + match.getCreateDate(), + match.getAlgorithmVersion(), + match.getAbstain()); Match foundMatch = matchDAO.findMatchById(matchId); assertNotNull(foundMatch); } @@ -161,19 +195,19 @@ void testInsertFailureReason() { match.setAlgorithmVersion(MatchAlgorithm.V4.getVersion()); match.addRationale(RandomStringUtils.randomAlphabetic(100)); match.addRationale(RandomStringUtils.randomAlphabetic(100)); - Integer matchId = matchDAO.insertMatch( - match.getConsent(), - match.getPurpose(), - match.getMatch(), - match.getFailed(), - match.getCreateDate(), - match.getAlgorithmVersion(), - match.getAbstain()); + Integer matchId = + matchDAO.insertMatch( + match.getConsent(), + match.getPurpose(), + match.getMatch(), + match.getFailed(), + match.getCreateDate(), + match.getAlgorithmVersion(), + match.getAbstain()); match.getRationales().forEach(f -> matchDAO.insertRationale(matchId, f)); Match foundMatch = matchDAO.findMatchById(matchId); assertNotNull(foundMatch); - assertEquals(match.getRationales().size(), - foundMatch.getRationales().size()); + assertEquals(match.getRationales().size(), foundMatch.getRationales().size()); } @Test @@ -183,14 +217,15 @@ void testDeleteFailureReasonsByPurposeIds() { match.setAlgorithmVersion(MatchAlgorithm.V4.getVersion()); match.addRationale(RandomStringUtils.randomAlphabetic(100)); match.addRationale(RandomStringUtils.randomAlphabetic(100)); - Integer matchId = matchDAO.insertMatch( - match.getConsent(), - match.getPurpose(), - match.getMatch(), - match.getFailed(), - match.getCreateDate(), - match.getAlgorithmVersion(), - match.getAbstain()); + Integer matchId = + matchDAO.insertMatch( + match.getConsent(), + match.getPurpose(), + match.getMatch(), + match.getFailed(), + match.getCreateDate(), + match.getAlgorithmVersion(), + match.getAbstain()); match.getRationales().forEach(f -> matchDAO.insertRationale(matchId, f)); matchDAO.deleteRationalesByPurposeIds(List.of(match.getPurpose())); Match foundMatch = matchDAO.findMatchById(matchId); @@ -215,10 +250,11 @@ private Match createMatch() { } private Dac createDac() { - Integer id = dacDAO.createDac( - "Test_" + RandomStringUtils.random(20, true, true), - "Test_" + RandomStringUtils.random(20, true, true), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + RandomStringUtils.random(20, true, true), + "Test_" + RandomStringUtils.random(20, true, true), + new Date()); return dacDAO.findById(id); } @@ -228,8 +264,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + RandomStringUtils.random(20, true, true); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -246,25 +282,24 @@ private void createDatasetProperties(Integer datasetId) { } private Election createRPElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.RP.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.RP.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } private Election createDataAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/db/OidcAuthorityDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/OidcAuthorityDAOTest.java index 7108048786..a22b3d906f 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/OidcAuthorityDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/OidcAuthorityDAOTest.java @@ -21,7 +21,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; - @ExtendWith(MockitoExtension.class) class OidcAuthorityDAOTest extends MockServerTestHelper { @@ -44,9 +43,11 @@ void testGetOidcAuthorityConfiguration() { final String expectedIssuer = "https://example.com"; final String expectedAuthorizationEndpoint = expectedIssuer + "/oauth2/authorize"; final String expectedTokenEndpoint = expectedIssuer + "/oauth2/token"; - // the only things that matter in this body are the issuer, authorization_endpoint, and token_endpoint + // the only things that matter in this body are the issuer, authorization_endpoint, and + // token_endpoint // the rest of the fields are just to simulate a real response - final String bodyFormat = """ + final String bodyFormat = + """ { "issuer":"%s", "authorization_endpoint":"%s", @@ -65,16 +66,17 @@ void testGetOidcAuthorityConfiguration() { """; mockServerClient - .when( - request() - .withMethod("GET") - .withPath("/.well-known/openid-configuration")) + .when(request().withMethod("GET").withPath("/.well-known/openid-configuration")) .respond( response() .withStatusCode(200) .withHeader("Content-Type", "application/json") - .withBody(bodyFormat.formatted(expectedIssuer, expectedAuthorizationEndpoint, - expectedTokenEndpoint, expectedIssuer))); + .withBody( + bodyFormat.formatted( + expectedIssuer, + expectedAuthorizationEndpoint, + expectedTokenEndpoint, + expectedIssuer))); var actual = dao.getOidcAuthorityConfiguration(); assertEquals(expectedTokenEndpoint, actual.token_endpoint()); assertEquals(expectedAuthorizationEndpoint, actual.authorization_endpoint()); @@ -84,7 +86,8 @@ void testGetOidcAuthorityConfiguration() { @Test void testOauthTokenPost() { // the content of this response doesn't matter, it's just to simulate a real response - var expectedResponse = """ + var expectedResponse = + """ { "access_token":"1234567890", "token_type":"Bearer", @@ -103,19 +106,24 @@ void testOauthTokenPost() { request() .withMethod("POST") .withPath(tokenPath) - .withQueryStringParameters(queryParameters.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))) - .withBody(URLEncodedUtils.format(formParameters.entrySet().stream().flatMap( - entry -> entry.getValue().stream() - .map(value -> new BasicNameValuePair(entry.getKey(), value))).toList(), - StandardCharsets.UTF_8)) - ) + .withQueryStringParameters( + queryParameters.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))) + .withBody( + URLEncodedUtils.format( + formParameters.entrySet().stream() + .flatMap( + entry -> + entry.getValue().stream() + .map( + value -> new BasicNameValuePair(entry.getKey(), value))) + .toList(), + StandardCharsets.UTF_8))) .respond( response() .withStatusCode(200) .withHeader("Content-Type", "application/json") - .withBody( - expectedResponse)); + .withBody(expectedResponse)); var actual = dao.oauthTokenPost(formParameters, queryParameters); assertEquals(expectedResponse, actual); } diff --git a/src/test/java/org/broadinstitute/consent/http/db/StudyDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/StudyDAOTest.java index 3ac92759d4..6602959589 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/StudyDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/StudyDAOTest.java @@ -36,25 +36,25 @@ void testCreateAndFindStudy() { String name = RandomStringUtils.randomAlphabetic(20); String description = RandomStringUtils.randomAlphabetic(20); - List dataTypes = List.of( - RandomStringUtils.randomAlphabetic(20), - RandomStringUtils.randomAlphabetic(20), - RandomStringUtils.randomAlphabetic(20) - ); + List dataTypes = + List.of( + RandomStringUtils.randomAlphabetic(20), + RandomStringUtils.randomAlphabetic(20), + RandomStringUtils.randomAlphabetic(20)); String piName = RandomStringUtils.randomAlphabetic(20); Boolean publicVisibility = true; UUID uuid = UUID.randomUUID(); - Integer id = studyDAO.insertStudy( - name, - description, - piName, - dataTypes, - publicVisibility, - u.getUserId(), - Instant.now(), - uuid - ); + Integer id = + studyDAO.insertStudy( + name, + description, + piName, + dataTypes, + publicVisibility, + u.getUserId(), + Instant.now(), + uuid); studyDAO.insertStudy( RandomStringUtils.randomAlphabetic(20), @@ -64,8 +64,7 @@ void testCreateAndFindStudy() { publicVisibility, u.getUserId(), Instant.now(), - UUID.randomUUID() - ); + UUID.randomUUID()); Study study = studyDAO.findStudyById(id); @@ -86,103 +85,85 @@ void testStudyProps() { String name = RandomStringUtils.randomAlphabetic(20); String description = RandomStringUtils.randomAlphabetic(20); - List dataTypes = List.of( - RandomStringUtils.randomAlphabetic(20), - RandomStringUtils.randomAlphabetic(20), - RandomStringUtils.randomAlphabetic(20) - ); + List dataTypes = + List.of( + RandomStringUtils.randomAlphabetic(20), + RandomStringUtils.randomAlphabetic(20), + RandomStringUtils.randomAlphabetic(20)); String piName = RandomStringUtils.randomAlphabetic(20); Boolean publicVisibility = true; - Integer id = studyDAO.insertStudy( - name, - description, - piName, - dataTypes, - publicVisibility, - u.getUserId(), - Instant.now(), - UUID.randomUUID() - ); - - Integer id2 = studyDAO.insertStudy( - RandomStringUtils.randomAlphabetic(20), - description, - piName, - dataTypes, - publicVisibility, - u.getUserId(), - Instant.now(), - UUID.randomUUID() - ); - - Integer prop1Id = studyDAO.insertStudyProperty( - id, - "prop1", - PropertyType.String.toString(), - "asdf" - ); - - Integer prop2Id = studyDAO.insertStudyProperty( - id, - "prop2", - PropertyType.Number.toString(), - "1" - ); + Integer id = + studyDAO.insertStudy( + name, + description, + piName, + dataTypes, + publicVisibility, + u.getUserId(), + Instant.now(), + UUID.randomUUID()); + + Integer id2 = + studyDAO.insertStudy( + RandomStringUtils.randomAlphabetic(20), + description, + piName, + dataTypes, + publicVisibility, + u.getUserId(), + Instant.now(), + UUID.randomUUID()); + + Integer prop1Id = + studyDAO.insertStudyProperty(id, "prop1", PropertyType.String.toString(), "asdf"); + + Integer prop2Id = + studyDAO.insertStudyProperty(id, "prop2", PropertyType.Number.toString(), "1"); // create some random, other property - studyDAO.insertStudyProperty( - id2, - "unrelated", - PropertyType.String.toString(), - "asdfasdfasdf" - ); + studyDAO.insertStudyProperty(id2, "unrelated", PropertyType.String.toString(), "asdfasdfasdf"); Study study = studyDAO.findStudyById(id); assertEquals(study.getProperties().size(), 2); - study.getProperties().forEach((prop) -> { - if (prop.getStudyPropertyId().equals(prop1Id)) { - assertEquals("prop1", prop.getKey()); - assertEquals(PropertyType.String, prop.getType()); - assertEquals("asdf", prop.getValue()); - } else if (prop.getStudyPropertyId().equals(prop2Id)) { - assertEquals("prop2", prop.getKey()); - assertEquals(PropertyType.Number, prop.getType()); - assertEquals(1, prop.getValue()); - } else { - fail("Unexpected property"); - } - }); + study + .getProperties() + .forEach( + (prop) -> { + if (prop.getStudyPropertyId().equals(prop1Id)) { + assertEquals("prop1", prop.getKey()); + assertEquals(PropertyType.String, prop.getType()); + assertEquals("asdf", prop.getValue()); + } else if (prop.getStudyPropertyId().equals(prop2Id)) { + assertEquals("prop2", prop.getKey()); + assertEquals(PropertyType.Number, prop.getType()); + assertEquals(1, prop.getValue()); + } else { + fail("Unexpected property"); + } + }); } - @Test void testAlternativeDataSharingPlan() { User u = createUser(); UUID uuid = UUID.randomUUID(); - Integer id = studyDAO.insertStudy( - "name", - "description", - "asdf", - List.of(), - true, - u.getUserId(), - Instant.now(), - uuid - ); + Integer id = + studyDAO.insertStudy( + "name", "description", "asdf", List.of(), true, u.getUserId(), Instant.now(), uuid); - FileStorageObject fso = createFileStorageObject(uuid.toString(), - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); + FileStorageObject fso = + createFileStorageObject(uuid.toString(), FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); Study study = studyDAO.findStudyById(id); - assertEquals(fso.getFileStorageObjectId(), + assertEquals( + fso.getFileStorageObjectId(), study.getAlternativeDataSharingPlan().getFileStorageObjectId()); assertEquals(fso.getBlobId(), study.getAlternativeDataSharingPlan().getBlobId()); - } @Test @@ -191,28 +172,22 @@ void testGetAlternativeDataSharingFile() { // create unrelated file with the same id as dataset id but different category, timestamp before createFileStorageObject( - study.getUuid().toString(), - FileCategory.NIH_INSTITUTIONAL_CERTIFICATION - ); + study.getUuid().toString(), FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); - FileStorageObject altFile = createFileStorageObject( - study.getUuid().toString(), - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN - ); + FileStorageObject altFile = + createFileStorageObject( + study.getUuid().toString(), FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); // create unrelated files with timestamp later than the ADSP file: one attached to dataset, one - // completely separate from the dataset. ensures that the Mapper is selecting only the right file. + // completely separate from the dataset. ensures that the Mapper is selecting only the right + // file. createFileStorageObject("asdfasdf", FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - createFileStorageObject( - study.getUuid().toString(), - FileCategory.DATA_USE_LETTER - ); + createFileStorageObject(study.getUuid().toString(), FileCategory.DATA_USE_LETTER); Study found = studyDAO.findStudyById(study.getStudyId()); assertEquals(altFile, found.getAlternativeDataSharingPlan()); - assertEquals(altFile.getBlobId(), - found.getAlternativeDataSharingPlan().getBlobId()); + assertEquals(altFile.getBlobId(), found.getAlternativeDataSharingPlan().getBlobId()); } @Test @@ -224,15 +199,15 @@ void testGetAlternativeDataSharingPlanFile_AlwaysLatestCreated() { String gcsFileUri = org.apache.commons.lang3.RandomStringUtils.randomAlphabetic(10); User createUser = createUser(); - Integer altFileIdCreatedFirst = fileStorageObjectDAO.insertNewFile( - fileName, - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN.getValue(), - bucketName, - gcsFileUri, - study.getUuid().toString(), - createUser.getUserId(), - Instant.ofEpochMilli(100) - ); + Integer altFileIdCreatedFirst = + fileStorageObjectDAO.insertNewFile( + fileName, + FileCategory.ALTERNATIVE_DATA_SHARING_PLAN.getValue(), + bucketName, + gcsFileUri, + study.getUuid().toString(), + createUser.getUserId(), + Instant.ofEpochMilli(100)); User updateUser = createUser(); @@ -243,39 +218,35 @@ void testGetAlternativeDataSharingPlanFile_AlwaysLatestCreated() { updateUser.getUserId(), Instant.ofEpochMilli(120)); - Integer altFileIdCreatedSecond = fileStorageObjectDAO.insertNewFile( - fileName, - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN.getValue(), - bucketName, - gcsFileUri, - study.getUuid().toString(), - createUser.getUserId(), - Instant.ofEpochMilli(130) - ); + Integer altFileIdCreatedSecond = + fileStorageObjectDAO.insertNewFile( + fileName, + FileCategory.ALTERNATIVE_DATA_SHARING_PLAN.getValue(), + bucketName, + gcsFileUri, + study.getUuid().toString(), + createUser.getUserId(), + Instant.ofEpochMilli(130)); Study found = studyDAO.findStudyById(study.getStudyId()); // returns last updated file - assertEquals(altFileIdCreatedSecond, - found.getAlternativeDataSharingPlan().getFileStorageObjectId()); + assertEquals( + altFileIdCreatedSecond, found.getAlternativeDataSharingPlan().getFileStorageObjectId()); } @Test void testGetAlternativeDataSharingPlanFile_NotDeleted() { Study study = insertStudyWithProperties(); - FileStorageObject altFile = createFileStorageObject( - study.getUuid().toString(), - FileCategory.ALTERNATIVE_DATA_SHARING_PLAN - ); + FileStorageObject altFile = + createFileStorageObject( + study.getUuid().toString(), FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); User deleteUser = createUser(); fileStorageObjectDAO.deleteFileById( - altFile.getFileStorageObjectId(), - deleteUser.getUserId(), - Instant.now() - ); + altFile.getFileStorageObjectId(), deleteUser.getUserId(), Instant.now()); Study found = studyDAO.findStudyById(study.getStudyId()); @@ -332,26 +303,32 @@ void testUpdateStudyProperty() { Study study = insertStudyWithProperties(); String newPropStringVal = RandomStringUtils.randomAlphabetic(15); Integer newPropNumberVal = RandomUtils.nextInt(100, 1000); - study.getProperties().forEach(p -> { - if (p.getType().equals(PropertyType.String)) { - studyDAO.updateStudyProperty( - study.getStudyId(), - p.getKey(), - p.getType().toString(), - newPropStringVal); - } - if (p.getType().equals(PropertyType.Number)) { - studyDAO.updateStudyProperty( - study.getStudyId(), - p.getKey(), - p.getType().toString(), - newPropNumberVal.toString()); - } - }); + study + .getProperties() + .forEach( + p -> { + if (p.getType().equals(PropertyType.String)) { + studyDAO.updateStudyProperty( + study.getStudyId(), p.getKey(), p.getType().toString(), newPropStringVal); + } + if (p.getType().equals(PropertyType.Number)) { + studyDAO.updateStudyProperty( + study.getStudyId(), + p.getKey(), + p.getType().toString(), + newPropNumberVal.toString()); + } + }); Study updatedStudy = studyDAO.findStudyById(study.getStudyId()); - Optional stringProp = updatedStudy.getProperties().stream().filter(p -> p.getValue().equals(newPropStringVal)).findFirst(); - Optional numberProp = updatedStudy.getProperties().stream().filter(p -> p.getValue().equals(newPropNumberVal)).findFirst(); + Optional stringProp = + updatedStudy.getProperties().stream() + .filter(p -> p.getValue().equals(newPropStringVal)) + .findFirst(); + Optional numberProp = + updatedStudy.getProperties().stream() + .filter(p -> p.getValue().equals(newPropNumberVal)) + .findFirst(); assertTrue(stringProp.isPresent()); assertTrue(numberProp.isPresent()); } @@ -381,15 +358,15 @@ private FileStorageObject createFileStorageObject(String entityId, FileCategory User createUser = createUser(); Instant createDate = Instant.now(); - Integer newFileStorageObjectId = fileStorageObjectDAO.insertNewFile( - fileName, - category.getValue(), - bucketName, - gcsFileUri, - entityId, - createUser.getUserId(), - createDate - ); + Integer newFileStorageObjectId = + fileStorageObjectDAO.insertNewFile( + fileName, + category.getValue(), + bucketName, + gcsFileUri, + entityId, + createUser.getUserId(), + createDate); return fileStorageObjectDAO.findFileById(newFileStorageObjectId); } @@ -398,37 +375,25 @@ private Study insertStudyWithProperties() { String name = RandomStringUtils.randomAlphabetic(20); String description = RandomStringUtils.randomAlphabetic(20); - List dataTypes = List.of( - RandomStringUtils.randomAlphabetic(20), - RandomStringUtils.randomAlphabetic(20) - ); + List dataTypes = + List.of(RandomStringUtils.randomAlphabetic(20), RandomStringUtils.randomAlphabetic(20)); String piName = RandomStringUtils.randomAlphabetic(20); Boolean publicVisibility = true; - Integer id = studyDAO.insertStudy( - name, - description, - piName, - dataTypes, - publicVisibility, - u.getUserId(), - Instant.now(), - UUID.randomUUID() - ); - - studyDAO.insertStudyProperty( - id, - "prop1", - PropertyType.String.toString(), - "asdf" - ); - - studyDAO.insertStudyProperty( - id, - "prop2", - PropertyType.Number.toString(), - "1" - ); + Integer id = + studyDAO.insertStudy( + name, + description, + piName, + dataTypes, + publicVisibility, + u.getUserId(), + Instant.now(), + UUID.randomUUID()); + + studyDAO.insertStudyProperty(id, "prop1", PropertyType.String.toString(), "asdf"); + + studyDAO.insertStudyProperty(id, "prop2", PropertyType.Number.toString(), "1"); return studyDAO.findStudyById(id); } @@ -439,8 +404,8 @@ private Dataset insertDatasetForStudy(Integer studyId) { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + RandomStringUtils.random(20, true, true); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); datasetDAO.updateStudyId(id, studyId); @@ -453,9 +418,8 @@ private Dataset insertDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + RandomStringUtils.random(20, true, true); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); return datasetDAO.findDatasetById(id); } - -} \ No newline at end of file +} diff --git a/src/test/java/org/broadinstitute/consent/http/db/TestingDAO.java b/src/test/java/org/broadinstitute/consent/http/db/TestingDAO.java index 7277b75cff..fefbf6478a 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/TestingDAO.java +++ b/src/test/java/org/broadinstitute/consent/http/db/TestingDAO.java @@ -5,7 +5,8 @@ public interface TestingDAO extends Transactional { - @SqlUpdate(""" + @SqlUpdate( + """ DO $$ DECLARE table_name text; BEGIN diff --git a/src/test/java/org/broadinstitute/consent/http/db/UserDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/UserDAOTest.java index b81903358a..97b3beec75 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/UserDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/UserDAOTest.java @@ -50,14 +50,16 @@ void testFindUserById() { assertEquals(user.getEmail(), user2.getEmail()); // Assert roles are fetched correctly - assertTrue(user2.getRoles().stream() - .anyMatch(r -> r.getRoleId().equals(UserRoles.ALUMNI.getRoleId()))); - assertTrue(user2.getRoles().stream() - .anyMatch(r -> r.getRoleId().equals(UserRoles.ADMIN.getRoleId()))); - assertTrue(user2.getRoles().stream() - .anyMatch(r -> r.getRoleId().equals(UserRoles.RESEARCHER.getRoleId()))); - - //assert institution base data is present if available + assertTrue( + user2.getRoles().stream() + .anyMatch(r -> r.getRoleId().equals(UserRoles.ALUMNI.getRoleId()))); + assertTrue( + user2.getRoles().stream().anyMatch(r -> r.getRoleId().equals(UserRoles.ADMIN.getRoleId()))); + assertTrue( + user2.getRoles().stream() + .anyMatch(r -> r.getRoleId().equals(UserRoles.RESEARCHER.getRoleId()))); + + // assert institution base data is present if available User user3 = createUserWithInstitution(); User queriedUser3 = userDAO.findUserById(user3.getUserId()); assert (queriedUser3.getUserId()).equals(user3.getUserId()); @@ -68,8 +70,9 @@ void testFindUserById() { @Test void testFindUserWithPropertiesById() { User user = createUserWithInstitution(); - int lcId = libraryCardDAO.insertLibraryCard(user.getUserId(), user.getDisplayName(), - user.getEmail(), user.getUserId(), new Date()); + int lcId = + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); UserProperty eraExpProp = new UserProperty(); eraExpProp.setPropertyKey(UserFields.ERA_EXPIRATION_DATE.getValue()); eraExpProp.setPropertyValue(Instant.now().toString()); @@ -80,22 +83,26 @@ void testFindUserWithPropertiesById() { eraAuthProp.setUserId(user.getUserId()); userPropertyDAO.insertAll(List.of(eraExpProp, eraAuthProp)); - User foundUser = userDAO.findUserWithPropertiesById(user.getUserId(), - UserFields.getValues()); + User foundUser = userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues()); assertNotNull(foundUser); assertFalse(foundUser.getRoles().isEmpty()); assertEquals(lcId, foundUser.getLibraryCard().getId()); assertEquals(user.getInstitutionId(), foundUser.getInstitutionId()); assertFalse(foundUser.getProperties().isEmpty()); - assertTrue(foundUser.getProperties().stream() - .anyMatch(p -> p.getPropertyKey().equals(UserFields.ERA_EXPIRATION_DATE.getValue()) - && p.getPropertyValue().equals(eraExpProp.getPropertyValue()))); - assertTrue(foundUser.getProperties().stream() - .anyMatch(p -> p.getPropertyKey().equals(UserFields.ERA_STATUS.getValue()) - && p.getPropertyValue().equals(eraAuthProp.getPropertyValue()))); + assertTrue( + foundUser.getProperties().stream() + .anyMatch( + p -> + p.getPropertyKey().equals(UserFields.ERA_EXPIRATION_DATE.getValue()) + && p.getPropertyValue().equals(eraExpProp.getPropertyValue()))); + assertTrue( + foundUser.getProperties().stream() + .anyMatch( + p -> + p.getPropertyKey().equals(UserFields.ERA_STATUS.getValue()) + && p.getPropertyValue().equals(eraAuthProp.getPropertyValue()))); } - @Test void testFindUserByIdWithLibraryCard() { LibraryCard libraryCard = createLibraryCard(); @@ -181,8 +188,8 @@ void testFindUsersWithRoles() { userRoleDAO.insertSingleUserRole(UserRoles.MEMBER.getRoleId(), chair.getUserId()); Collection userIds = Collections.singletonList(chair.getUserId()); Collection users = userDAO.findUsersWithRoles(userIds); - users.forEach(u -> assertFalse(u.getRoles().isEmpty(), - "User: " + u.getUserId() + " has no roles")); + users.forEach( + u -> assertFalse(u.getRoles().isEmpty(), "User: " + u.getUserId() + " has no roles")); assertEquals(1, users.size()); User user = users.stream().findFirst().orElse(null); assertNotNull(user); @@ -199,12 +206,14 @@ void testFindUserByEmail() { assertNotNull(user1); // Assert roles are fetched correctly - assertTrue(user1.getRoles().stream() - .anyMatch(r -> r.getRoleId().equals(UserRoles.ALUMNI.getRoleId()))); - assertTrue(user1.getRoles().stream() - .anyMatch(r -> r.getRoleId().equals(UserRoles.ADMIN.getRoleId()))); - assertTrue(user1.getRoles().stream() - .anyMatch(r -> r.getRoleId().equals(UserRoles.RESEARCHER.getRoleId()))); + assertTrue( + user1.getRoles().stream() + .anyMatch(r -> r.getRoleId().equals(UserRoles.ALUMNI.getRoleId()))); + assertTrue( + user1.getRoles().stream().anyMatch(r -> r.getRoleId().equals(UserRoles.ADMIN.getRoleId()))); + assertTrue( + user1.getRoles().stream() + .anyMatch(r -> r.getRoleId().equals(UserRoles.RESEARCHER.getRoleId()))); User user2 = userDAO.findUserByEmail("no.one@nowhere.com"); assertNull(user2); @@ -229,26 +238,29 @@ void testFindUserByEmails() { @Test void testFindUsersWithLCsAndInstitution() { User user = createUserWithInstitution(); - int dacId = dacDAO.createDac(randomAlphabetic(5), - randomAlphabetic(5), new Date()); + int dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), new Date()); Instant now = Instant.now(); int daaId = daaDAO.createDaa(user.getUserId(), now, user.getUserId(), now, dacId); - int lcId1 = libraryCardDAO.insertLibraryCard(user.getUserId(), - user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); + int lcId1 = + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); libraryCardDAO.createLibraryCardDaaRelation(lcId1, daaId); User user2 = createUserWithInstitution(); - int lcId2 = libraryCardDAO.insertLibraryCard(user2.getUserId(), - user2.getDisplayName(), user2.getEmail(), user2.getUserId(), new Date()); + int lcId2 = + libraryCardDAO.insertLibraryCard( + user2.getUserId(), + user2.getDisplayName(), + user2.getEmail(), + user2.getUserId(), + new Date()); libraryCardDAO.createLibraryCardDaaRelation(lcId2, daaId); List users = userDAO.findUsersWithLCsAndInstitution(); // Four users: two admin users, two signing official users with library cards. assertEquals(4, users.size()); // Filter out admin users, which don't have institutions. - users = users.stream() - .filter(u -> u.getInstitution() != null) - .toList(); + users = users.stream().filter(u -> u.getInstitution() != null).toList(); assertEquals(2, users.size()); assertNotNull(users.get(0).getInstitution()); assertNotNull(users.get(0).getLibraryCard()); @@ -278,9 +290,19 @@ void testUpdateEmailPreference() { @Test void testUpdateInstitutionId() { User researcher = createUser(); - Integer institutionId = institutionDAO.insertInstitution("Institution", "it director", - "it director email", null, null, null, null, null, null, researcher.getUserId(), - new Date()); + Integer institutionId = + institutionDAO.insertInstitution( + "Institution", + "it director", + "it director email", + null, + null, + null, + null, + null, + null, + researcher.getUserId(), + new Date()); userDAO.updateInstitutionId(researcher.getUserId(), institutionId); User u1 = userDAO.findUserById(researcher.getUserId()); assertEquals(institutionId, u1.getInstitutionId()); @@ -299,7 +321,8 @@ void testUpdateDisplayName() { void testUpdateDisplayNameInvalidChars() { User researcher = createUser(); String newName = "invalid\0name"; - assertThrows(UnableToExecuteStatementException.class, + assertThrows( + UnableToExecuteStatementException.class, () -> userDAO.updateDisplayName(researcher.getUserId(), newName)); } @@ -310,9 +333,10 @@ void testFindUsersForDatasetsByRole() { User user = createUserWithRoleInDac(UserRoles.CHAIRPERSON.getRoleId(), dac.getDacId()); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); - Set users = userDAO.findUsersForDatasetsByRole( - Collections.singletonList(dataset.getDatasetId()), - Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId())); + Set users = + userDAO.findUsersForDatasetsByRole( + Collections.singletonList(dataset.getDatasetId()), + Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId())); Optional foundUser = users.stream().findFirst(); assertNotNull(users); assertFalse(users.isEmpty()); @@ -327,9 +351,10 @@ void testFindUsersForDatasetsByRoleNotFound() { createUserWithRoleInDac(UserRoles.MEMBER.getRoleId(), dac.getDacId()); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); - Set users = userDAO.findUsersForDatasetsByRole( - Collections.singletonList(dataset.getDatasetId()), - Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId())); + Set users = + userDAO.findUsersForDatasetsByRole( + Collections.singletonList(dataset.getDatasetId()), + Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId())); assertNotNull(users); assertTrue(users.isEmpty()); } @@ -338,7 +363,7 @@ void testFindUsersForDatasetsByRoleNotFound() { void testFindUsersByInstitution() { Integer institutionId = createUserWithInstitution().getInstitutionId(); List beforeList = userDAO.findUsersByInstitution(institutionId); - //should not change results since they are not in the institution + // should not change results since they are not in the institution createUser(); createUser(); List afterList = userDAO.findUsersByInstitution(institutionId); @@ -348,7 +373,7 @@ void testFindUsersByInstitution() { @Test void testGetSOsByInstitution() { - //user with institutionId and SO role + // user with institutionId and SO role User user = createUserWithInstitution(); Integer institutionId = user.getInstitutionId(); String displayName = user.getDisplayName(); @@ -364,8 +389,7 @@ void testGetSOsByInstitution() { @Test void testGetUsersFromInstitutionWithCards() { - int dacId = dacDAO.createDac(randomAlphabetic(5), - randomAlphabetic(5), new Date()); + int dacId = dacDAO.createDac(randomAlphabetic(5), randomAlphabetic(5), new Date()); Instant now = Instant.now(); LibraryCard card = createLibraryCard(); int daaId = daaDAO.createDaa(card.getUserId(), now, card.getUserId(), now, dacId); @@ -416,8 +440,7 @@ void testGetUsersWithNoInstitution() { List users = userDAO.getUsersWithNoInstitution(); // One user we created just now, one is the admin user for the institution. assertEquals(2, users.size()); - assertTrue(users.stream() - .anyMatch(u -> u.getUserId().equals(user.getUserId()))); + assertTrue(users.stream().anyMatch(u -> u.getUserId().equals(user.getUserId()))); } @Test @@ -446,10 +469,12 @@ void testCanAddAllRoles() { for (UserRoles role : roles) { // ensure that each role exists on user - assertTrue(found.getRoles().stream().anyMatch( - existingRole -> ( - role.getRoleId().equals(existingRole.getRoleId()) - && role.getRoleName().equals(existingRole.getName())))); + assertTrue( + found.getRoles().stream() + .anyMatch( + existingRole -> + (role.getRoleId().equals(existingRole.getRoleId()) + && role.getRoleName().equals(existingRole.getName())))); } } @@ -484,10 +509,9 @@ void testCanBeChairOfTwoDACs() { } private Dac createDac() { - Integer id = dacDAO.createDac( - "Test_" + randomAlphanumeric(20), - "Test_" + randomAlphanumeric(20), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphanumeric(20), "Test_" + randomAlphanumeric(20), new Date()); return dacDAO.findById(id); } @@ -497,8 +521,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -516,8 +540,9 @@ private void createDatasetProperties(Integer datasetId) { private LibraryCard createLibraryCard() { User user = createUserWithInstitution(); - Integer id = libraryCardDAO.insertLibraryCard(user.getUserId(), user.getDisplayName(), - user.getEmail(), user.getUserId(), new Date()); + Integer id = + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); return libraryCardDAO.findLibraryCardById(id); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/UserPropertyDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/UserPropertyDAOTest.java index 0c0ed63258..a137eba2de 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/UserPropertyDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/UserPropertyDAOTest.java @@ -29,25 +29,25 @@ void testFindUserProperties() { notPresent.setPropertyValue(randomAlphabetic(10)); notPresent.setUserId(user.getUserId()); - List props = userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( - user.getUserId(), - List.of(UserFields.ERA_EXPIRATION_DATE.getValue())); + List props = + userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + user.getUserId(), List.of(UserFields.ERA_EXPIRATION_DATE.getValue())); assertEquals(0, props.size()); - userPropertyDAO.insertAll(List.of( - eraExpProp, - notPresent - )); + userPropertyDAO.insertAll(List.of(eraExpProp, notPresent)); - props = userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( - user.getUserId(), - List.of(UserFields.ERA_EXPIRATION_DATE.getValue())); + props = + userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + user.getUserId(), List.of(UserFields.ERA_EXPIRATION_DATE.getValue())); assertEquals(1, props.size()); - assertTrue(props.stream().anyMatch((p) -> - (p.getPropertyKey().equals(UserFields.ERA_EXPIRATION_DATE.getValue()) - && p.getPropertyValue().equals(eraExpProp.getPropertyValue())))); + assertTrue( + props.stream() + .anyMatch( + (p) -> + (p.getPropertyKey().equals(UserFields.ERA_EXPIRATION_DATE.getValue()) + && p.getPropertyValue().equals(eraExpProp.getPropertyValue())))); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/UserRoleDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/UserRoleDAOTest.java index d6507056de..fd91d85568 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/UserRoleDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/UserRoleDAOTest.java @@ -51,8 +51,7 @@ void testFindRolesByUserMixedCaseEmail() { private String randomizeCase(String string) { Random random = new Random(); - return Arrays - .stream(string.split("")) + return Arrays.stream(string.split("")) .map(l -> random.nextBoolean() ? l.toUpperCase(Locale.ROOT) : l.toLowerCase(Locale.ROOT)) .collect(Collectors.joining("")); } @@ -65,11 +64,7 @@ void testFindRoles() { @Test void testFindRoleIdByName() { - List roleNames = userRoleDAO. - findRoles(). - stream(). - map(Role::getName). - toList(); + List roleNames = userRoleDAO.findRoles().stream().map(Role::getName).toList(); roleNames.forEach(r -> assertNotNull(userRoleDAO.findRoleIdByName(r))); assertNull(userRoleDAO.findRoleIdByName("Not a real role")); } @@ -80,8 +75,9 @@ void testInsertUserRoles() { UserRole r = new UserRole(); r.setRoleId(UserRoles.MEMBER.getRoleId()); userRoleDAO.insertUserRoles(Collections.singletonList(r), user.getUserId()); - Optional updatedUser = userDAO.findUsersWithRoles( - Collections.singletonList(user.getUserId())).stream().findFirst(); + Optional updatedUser = + userDAO.findUsersWithRoles(Collections.singletonList(user.getUserId())).stream() + .findFirst(); assertTrue(updatedUser.isPresent()); assertEquals(2, updatedUser.get().getRoles().size()); } @@ -90,8 +86,8 @@ void testInsertUserRoles() { void testUpdateUserRoles() { User user = createUserWithRole(UserRoles.MEMBER.getRoleId()); List currentRoles = userRoleDAO.findRolesByUserId(user.getUserId()); - userRoleDAO.updateUserRoles(UserRoles.CHAIRPERSON.getRoleId(), user.getUserId(), - UserRoles.MEMBER.getRoleId()); + userRoleDAO.updateUserRoles( + UserRoles.CHAIRPERSON.getRoleId(), user.getUserId(), UserRoles.MEMBER.getRoleId()); List newRoles = userRoleDAO.findRolesByUserId(user.getUserId()); assertNotEquals(currentRoles.get(0).getRoleId(), newRoles.get(0).getRoleId()); } @@ -101,8 +97,8 @@ void testRemoveUserRoles() { User user = createUser(); List currentRoles = userRoleDAO.findRolesByUserId(user.getUserId()); assertFalse(currentRoles.isEmpty()); - List roleIds = userRoleDAO.findRoles().stream().map(Role::getRoleId) - .collect(Collectors.toList()); + List roleIds = + userRoleDAO.findRoles().stream().map(Role::getRoleId).collect(Collectors.toList()); userRoleDAO.removeUserRoles(user.getUserId(), roleIds); List newRoles = userRoleDAO.findRolesByUserId(user.getUserId()); assertTrue(newRoles.isEmpty()); @@ -119,9 +115,7 @@ void testRemoveSingleUserRole() { List userRoles = userRoleDAO.findRolesByUserId(user.getUserId()); assertFalse(userRoles.isEmpty()); List roles = userRoleDAO.findRoles(); - roles.forEach(r -> - userRoleDAO.removeSingleUserRole(user.getUserId(), r.getRoleId()) - ); + roles.forEach(r -> userRoleDAO.removeSingleUserRole(user.getUserId(), r.getRoleId())); List newUserRoles = userRoleDAO.findRolesByUserId(user.getUserId()); assertTrue(newUserRoles.isEmpty()); @@ -130,20 +124,20 @@ void testRemoveSingleUserRole() { @Test void testFindRoleByNameAndUser() { User user = createUserWithRole(UserRoles.CHAIRPERSON.getRoleId()); - Integer roleId = userRoleDAO.findRoleByNameAndUser(UserRoles.CHAIRPERSON.getRoleName(), - user.getUserId()); + Integer roleId = + userRoleDAO.findRoleByNameAndUser(UserRoles.CHAIRPERSON.getRoleName(), user.getUserId()); assertNotNull(roleId); - Integer invalidRoleId = userRoleDAO.findRoleByNameAndUser(UserRoles.MEMBER.getRoleName(), - user.getUserId()); + Integer invalidRoleId = + userRoleDAO.findRoleByNameAndUser(UserRoles.MEMBER.getRoleName(), user.getUserId()); assertNull(invalidRoleId); } @Test void testFindRoleByUserIdAndRoleId() { User user = createUserWithRole(UserRoles.CHAIRPERSON.getRoleId()); - UserRole userRole = userRoleDAO.findRoleByUserIdAndRoleId(user.getUserId(), - UserRoles.CHAIRPERSON.getRoleId()); + UserRole userRole = + userRoleDAO.findRoleByUserIdAndRoleId(user.getUserId(), UserRoles.CHAIRPERSON.getRoleId()); assertNotNull(userRole); } } diff --git a/src/test/java/org/broadinstitute/consent/http/db/VoteDAOTest.java b/src/test/java/org/broadinstitute/consent/http/db/VoteDAOTest.java index 74d7e4ea0f..d55c96901b 100644 --- a/src/test/java/org/broadinstitute/consent/http/db/VoteDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/db/VoteDAOTest.java @@ -41,10 +41,11 @@ void testFindVoteById() { User user = createUserWithRole(UserRoles.CHAIRPERSON.getRoleId()); Dataset dataset = createDataset(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote vote = createDacVote(user.getUserId(), election.getElectionId()); @@ -64,23 +65,23 @@ void testFindVotesByIds() { User user4 = createUserWithRole(UserRoles.MEMBER.getRoleId()); Dataset dataset = createDataset(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote vote = createDacVote(user.getUserId(), election.getElectionId()); Vote vote2 = createDacVote(user2.getUserId(), election.getElectionId()); Vote vote3 = createDacVote(user3.getUserId(), election.getElectionId()); Vote vote4 = createDacVote(user4.getUserId(), election.getElectionId()); - List voteIds = List.of(vote.getVoteId(), vote2.getVoteId(), vote3.getVoteId(), - vote4.getVoteId()); + List voteIds = + List.of(vote.getVoteId(), vote2.getVoteId(), vote3.getVoteId(), vote4.getVoteId()); List foundVotes = voteDAO.findVotesByIds(voteIds); assertNotNull(foundVotes); assertFalse(foundVotes.isEmpty()); - assertTrue( - foundVotes.stream().map(Vote::getVoteId).toList().containsAll(voteIds)); + assertTrue(foundVotes.stream().map(Vote::getVoteId).toList().containsAll(voteIds)); } @Test @@ -88,19 +89,21 @@ void testFindVotesByElectionIds() { User user = createUserWithRole(UserRoles.CHAIRPERSON.getRoleId()); Dataset dataset = createDataset(); String darCode = "DAR-12345"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); createDacVote(user.getUserId(), election.getElectionId()); Dataset dataset2 = createDataset(); String darCode2 = "DAR-67890"; - Integer collectionId2 = darCollectionDAO.insertDarCollection(darCode2, user.getUserId(), - new Date()); - DataAccessRequest dar2 = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId2, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId2 = + darCollectionDAO.insertDarCollection(darCode2, user.getUserId(), new Date()); + DataAccessRequest dar2 = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId2, dataset.getDatasetId(), user.getUserId()); Election election2 = createDataAccessElection(dar2.getReferenceId(), dataset2.getDatasetId()); createDacVote(user.getUserId(), election2.getElectionId()); List electionIds = Arrays.asList(election.getElectionId(), election2.getElectionId()); @@ -116,27 +119,30 @@ void testFindVotesByElectionIdAndType() { User user = createUserWithRole(UserRoles.CHAIRPERSON.getRoleId()); Dataset dataset = createDataset(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote vote = createDacVote(user.getUserId(), election.getElectionId()); - List foundVotes = voteDAO.findVotesByElectionIdAndType(election.getElectionId(), - vote.getType()); + List foundVotes = + voteDAO.findVotesByElectionIdAndType(election.getElectionId(), vote.getType()); assertNotNull(foundVotes); assertFalse(foundVotes.isEmpty()); assertEquals(1, foundVotes.size()); - List foundVotes2 = voteDAO.findVotesByElectionIdAndType(election.getElectionId(), - vote.getType().toLowerCase()); + List foundVotes2 = + voteDAO.findVotesByElectionIdAndType( + election.getElectionId(), vote.getType().toLowerCase()); assertNotNull(foundVotes2); assertFalse(foundVotes2.isEmpty()); assertEquals(1, foundVotes2.size()); - List foundVotes3 = voteDAO.findVotesByElectionIdAndType(election.getElectionId(), - vote.getType().toUpperCase()); + List foundVotes3 = + voteDAO.findVotesByElectionIdAndType( + election.getElectionId(), vote.getType().toUpperCase()); assertNotNull(foundVotes3); assertFalse(foundVotes3.isEmpty()); assertEquals(1, foundVotes3.size()); @@ -147,15 +153,16 @@ void testFindVoteByElectionIdAndDACUserId() { User user = createUserWithRole(UserRoles.CHAIRPERSON.getRoleId()); Dataset dataset = createDataset(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote vote = createDacVote(user.getUserId(), election.getElectionId()); - Vote foundVote = voteDAO.findVoteByElectionIdAndUserId(election.getElectionId(), - user.getUserId()); + Vote foundVote = + voteDAO.findVoteByElectionIdAndUserId(election.getElectionId(), user.getUserId()); assertNotNull(foundVote); assertEquals(vote.getVoteId(), foundVote.getVoteId()); } @@ -165,10 +172,11 @@ void testCheckVoteById() { User user = createUserWithRole(UserRoles.CHAIRPERSON.getRoleId()); Dataset dataset = createDataset(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote vote = createDacVote(user.getUserId(), election.getElectionId()); @@ -184,10 +192,11 @@ void testCreateVote() { Dac dac = createDac(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote v = createDacVote(user.getUserId(), election.getElectionId()); @@ -203,17 +212,17 @@ void testUpdateVote() { Dac dac = createDac(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote v = createDacVote(user.getUserId(), election.getElectionId()); String rationale = "rationale"; Date now = new Date(); - updateVote(true, rationale, now, v.getVoteId(), true, - election.getElectionId(), now, true); + updateVote(true, rationale, now, v.getVoteId(), true, election.getElectionId(), now, true); Vote vote = voteDAO.findVoteById(v.getVoteId()); assertTrue(vote.getVote()); assertTrue(vote.getHasConcerns()); @@ -231,10 +240,11 @@ void testUpdateVoteReminderFlag() { Dac dac = createDac(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote v = createDacVote(user.getUserId(), election.getElectionId()); @@ -253,15 +263,14 @@ void testFindTotalFinalVoteByElectionTypeAndVote() { Dac dac = createDac(); Dataset dataset = createDatasetWithDac(dac.getDacId()); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); electionDAO.updateElectionById( - election.getElectionId(), - ElectionStatus.CLOSED.getValue(), - new Date()); + election.getElectionId(), ElectionStatus.CLOSED.getValue(), new Date()); Vote v = createFinalVote(user.getUserId(), election.getElectionId()); boolean voteValue = true; updateVote( @@ -272,19 +281,20 @@ void testFindTotalFinalVoteByElectionTypeAndVote() { false, election.getElectionId(), v.getCreateDate(), - false - ); + false); - int count = voteDAO.findTotalFinalVoteByElectionTypeAndVote(election.getElectionType(), - voteValue); + int count = + voteDAO.findTotalFinalVoteByElectionTypeAndVote(election.getElectionType(), voteValue); assertEquals(1, count); - int count2 = voteDAO.findTotalFinalVoteByElectionTypeAndVote( - election.getElectionType().toLowerCase(), voteValue); + int count2 = + voteDAO.findTotalFinalVoteByElectionTypeAndVote( + election.getElectionType().toLowerCase(), voteValue); assertEquals(1, count2); - int count3 = voteDAO.findTotalFinalVoteByElectionTypeAndVote( - election.getElectionType().toUpperCase(), voteValue); + int count3 = + voteDAO.findTotalFinalVoteByElectionTypeAndVote( + election.getElectionType().toUpperCase(), voteValue); assertEquals(1, count3); } @@ -295,15 +305,14 @@ void testFindMaxNumberOfDACMembers() { Dac dac = createDac(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); electionDAO.updateElectionById( - election.getElectionId(), - ElectionStatus.CLOSED.getValue(), - new Date()); + election.getElectionId(), ElectionStatus.CLOSED.getValue(), new Date()); Vote v = createDacVote(user.getUserId(), election.getElectionId()); boolean voteValue = true; updateVote( @@ -314,11 +323,10 @@ void testFindMaxNumberOfDACMembers() { false, election.getElectionId(), v.getCreateDate(), - false - ); + false); - int count = voteDAO.findMaxNumberOfDACMembers( - Collections.singletonList(election.getElectionId())); + int count = + voteDAO.findMaxNumberOfDACMembers(Collections.singletonList(election.getElectionId())); assertEquals(1, count); } @@ -332,16 +340,17 @@ void testInsertVotes() { datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); User user4 = createUser(); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user4.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user4.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user4.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user4.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); List userIds = Arrays.asList(user1.getUserId(), user2.getUserId(), user3.getUserId()); voteDAO.insertVotes(userIds, election.getElectionId(), VoteType.DAC.getValue()); - List votes = voteDAO.findVotesByElectionIds( - Collections.singletonList(election.getElectionId())); + List votes = + voteDAO.findVotesByElectionIds(Collections.singletonList(election.getElectionId())); assertNotNull(votes); assertFalse(votes.isEmpty()); assertEquals(3, votes.size()); @@ -354,10 +363,11 @@ void testRemoveVotesByIds() { Dac dac = createDac(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Vote vote = createDacVote(user.getUserId(), election.getElectionId()); @@ -373,10 +383,11 @@ void testFindVotesByUserId() { Dac dac = createDac(); datasetDAO.updateDatasetDacId(dataset.getDatasetId(), dac.getDacId()); String darCode = "DAR-1234567890"; - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); Election election = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); createChairpersonVote(user.getUserId(), election.getElectionId()); @@ -405,8 +416,8 @@ void testUpdateRationaleByVoteIds() { @Test void testFindVoteUsersByElectionReferenceIdList_Invalid() { // Empty case - List voteUsers = voteDAO.findVoteUsersByElectionReferenceIdList( - List.of("invalid reference id")); + List voteUsers = + voteDAO.findVoteUsersByElectionReferenceIdList(List.of("invalid reference id")); assertTrue(voteUsers.isEmpty()); } @@ -434,13 +445,12 @@ void testFindVoteUsersByElectionReferenceIdList() { User chair = createUserWithRoleInDac(UserRoles.CHAIRPERSON.getRoleId(), dac.getDacId()); Dataset dataset = createDatasetWithDac(dac.getDacId()); // This creates an election and votes for the user passed in as the creator - DarCollection collection = createDarCollectionWithDatasets(chair, - List.of(dataset)); + DarCollection collection = createDarCollectionWithDatasets(chair, List.of(dataset)); Optional dar = collection.getDars().values().stream().findFirst(); assertTrue(dar.isPresent()); - List voteUsers = voteDAO.findVoteUsersByElectionReferenceIdList( - List.of(dar.get().getReferenceId())); + List voteUsers = + voteDAO.findVoteUsersByElectionReferenceIdList(List.of(dar.get().getReferenceId())); assertFalse(voteUsers.isEmpty()); assertEquals(1, voteUsers.size()); assertEquals(chair.getUserId(), voteUsers.get(0).getUserId()); @@ -451,17 +461,17 @@ private void createChairpersonVote(Integer userId, Integer electionId) { voteDAO.findVoteById(voteId); } - private DarCollection createDarCollectionWithDatasets(User user, - List datasets) { + private DarCollection createDarCollectionWithDatasets(User user, List datasets) { String darCode = "DAR-" + randomInt(100, 1000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); - datasets - .forEach(dataset -> { - DataAccessRequest dar = createDataAccessRequestWithDatasetAndCollectionInfo(collectionId, - dataset.getDatasetId(), user.getUserId()); - Election cancelled = createCanceledAccessElection(dar.getReferenceId(), - dataset.getDatasetId()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); + datasets.forEach( + dataset -> { + DataAccessRequest dar = + createDataAccessRequestWithDatasetAndCollectionInfo( + collectionId, dataset.getDatasetId(), user.getUserId()); + Election cancelled = + createCanceledAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Election access = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); createFinalVote(user.getUserId(), cancelled.getElectionId()); createFinalVote(user.getUserId(), access.getElectionId()); @@ -469,33 +479,39 @@ private DarCollection createDarCollectionWithDatasets(User user, return darCollectionDAO.findDARCollectionByCollectionId(collectionId); } - private DataAccessRequest createDataAccessRequestWithDatasetAndCollectionInfo(int collectionId, - int datasetId, int userId) { + private DataAccessRequest createDataAccessRequestWithDatasetAndCollectionInfo( + int collectionId, int datasetId, int userId) { DataAccessRequestData data = new DataAccessRequestData(); data.setProjectTitle(randomAlphabetic(10)); String referenceId = randomAlphanumeric(20); - dataAccessRequestDAO.insertDataAccessRequest(collectionId, referenceId, userId, new Date(), - new Date(), new Date(), data, randomAlphabetic(10)); + dataAccessRequestDAO.insertDataAccessRequest( + collectionId, + referenceId, + userId, + new Date(), + new Date(), + new Date(), + data, + randomAlphabetic(10)); dataAccessRequestDAO.insertDARDatasetRelation(referenceId, datasetId); return dataAccessRequestDAO.findByReferenceId(referenceId); } private Election createCanceledAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.CANCELED.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.CANCELED.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } private Dac createDac() { - Integer id = dacDAO.createDac( - "Test_" + randomAlphanumeric(20), - "Test_" + randomAlphanumeric(20), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphanumeric(20), "Test_" + randomAlphanumeric(20), new Date()); return dacDAO.findById(id); } @@ -505,8 +521,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -538,20 +554,20 @@ private Dataset createDatasetWithDac(Integer dacId) { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), dacId); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), dacId); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } private Election createDataAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } } diff --git a/src/test/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheckTest.java b/src/test/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheckTest.java index 0edc1a2c0b..6701d19be2 100644 --- a/src/test/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheckTest.java +++ b/src/test/java/org/broadinstitute/consent/http/health/ElasticSearchHealthCheckTest.java @@ -22,7 +22,6 @@ class ElasticSearchHealthCheckTest extends MockServerTestHelper { private ElasticSearchHealthCheck healthCheck; private ElasticSearchConfiguration config; - @BeforeEach void init() { config = new ElasticSearchConfiguration(); @@ -33,9 +32,9 @@ void init() { private void initHealthCheck(String status, Integer statusCode) { try { String stringResponse = "{ \"status\": \"" + status + "\" }"; - mockServerClient.when(request()).respond(response() - .withStatusCode(statusCode) - .withBody(stringResponse)); + mockServerClient + .when(request()) + .respond(response().withStatusCode(statusCode).withBody(stringResponse)); healthCheck = new ElasticSearchHealthCheck(config); } catch (Exception e) { diff --git a/src/test/java/org/broadinstitute/consent/http/health/GCSHealthCheckTest.java b/src/test/java/org/broadinstitute/consent/http/health/GCSHealthCheckTest.java index 3821b5f5eb..0c5be0e372 100644 --- a/src/test/java/org/broadinstitute/consent/http/health/GCSHealthCheckTest.java +++ b/src/test/java/org/broadinstitute/consent/http/health/GCSHealthCheckTest.java @@ -19,11 +19,9 @@ class GCSHealthCheckTest { private GCSHealthCheck healthCheck; - @Mock - private GCSService store; + @Mock private GCSService store; - @Mock - private Bucket bucket; + @Mock private Bucket bucket; @BeforeEach void setUpClass() { diff --git a/src/test/java/org/broadinstitute/consent/http/health/OntologyHealthCheckTest.java b/src/test/java/org/broadinstitute/consent/http/health/OntologyHealthCheckTest.java index b0ddb17b35..d9c053a19f 100644 --- a/src/test/java/org/broadinstitute/consent/http/health/OntologyHealthCheckTest.java +++ b/src/test/java/org/broadinstitute/consent/http/health/OntologyHealthCheckTest.java @@ -20,14 +20,11 @@ @ExtendWith(MockitoExtension.class) class OntologyHealthCheckTest { - @Mock - private HttpClientUtil clientUtil; + @Mock private HttpClientUtil clientUtil; - @Mock - private SimpleResponse response; + @Mock private SimpleResponse response; - @Mock - private ServicesConfiguration servicesConfiguration; + @Mock private ServicesConfiguration servicesConfiguration; private OntologyHealthCheck healthCheck; diff --git a/src/test/java/org/broadinstitute/consent/http/health/SamHealthCheckTest.java b/src/test/java/org/broadinstitute/consent/http/health/SamHealthCheckTest.java index 483c5cec89..60caa3a0f8 100644 --- a/src/test/java/org/broadinstitute/consent/http/health/SamHealthCheckTest.java +++ b/src/test/java/org/broadinstitute/consent/http/health/SamHealthCheckTest.java @@ -20,18 +20,16 @@ @ExtendWith(MockitoExtension.class) class SamHealthCheckTest { - @Mock - private HttpClientUtil clientUtil; + @Mock private HttpClientUtil clientUtil; - @Mock - private SimpleResponse response; + @Mock private SimpleResponse response; - @Mock - private ServicesConfiguration servicesConfiguration; + @Mock private ServicesConfiguration servicesConfiguration; private SamHealthCheck healthCheck; - private static final String okResponse = """ + private static final String okResponse = + """ { "ok": true, "systems": { @@ -48,8 +46,7 @@ class SamHealthCheckTest { void testCheckSuccess() throws Exception { when(response.code()).thenReturn(HttpStatusCodes.STATUS_CODE_OK); try { - when(response.entity()) - .thenReturn(okResponse); + when(response.entity()).thenReturn(okResponse); when(clientUtil.getCachedResponse(any())).thenReturn(response); when(servicesConfiguration.getSamUrl()).thenReturn("http://localhost:8000/"); healthCheck = new SamHealthCheck(clientUtil, servicesConfiguration); diff --git a/src/test/java/org/broadinstitute/consent/http/health/SendGridHealthCheckTest.java b/src/test/java/org/broadinstitute/consent/http/health/SendGridHealthCheckTest.java index 8aae14ad3e..56301cad98 100644 --- a/src/test/java/org/broadinstitute/consent/http/health/SendGridHealthCheckTest.java +++ b/src/test/java/org/broadinstitute/consent/http/health/SendGridHealthCheckTest.java @@ -22,14 +22,11 @@ @ExtendWith(MockitoExtension.class) class SendGridHealthCheckTest { - @Mock - private HttpClientUtil clientUtil; + @Mock private HttpClientUtil clientUtil; - @Mock - private SimpleResponse response; + @Mock private SimpleResponse response; - @Mock - private MailConfiguration mailConfiguration; + @Mock private MailConfiguration mailConfiguration; private SendGridHealthCheck healthCheck; private SendGridStatus goodStatus, badStatus; @@ -121,4 +118,4 @@ void testConfigException() throws Exception { HealthCheck.Result result = healthCheck.check(); assertFalse(result.isHealthy()); } -} \ No newline at end of file +} diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessageTest.java index 4547ca0256..2f7067797d 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/DACMembersDARRADARApprovedMessageTest.java @@ -43,9 +43,13 @@ void testGetDACMembersDARRADARApprovedTemplate() throws Exception { String darCode = "DAR-0001"; String referenceId = "abcd-12345"; - var message = new DACMembersDARRADARApprovedMessage(toUser, darCode, researcherUser, referenceId, datasetMailDTOs); + var message = + new DACMembersDARRADARApprovedMessage( + toUser, darCode, researcherUser, referenceId, datasetMailDTOs); assertEquals(referenceId, message.getEntityReferenceId()); - assertEquals("Broad Data Use Oversight System - Data Access Committee - Data Access Request DAR-0001 is Rule Automated DAR (RADAR) Approved", message.createSubject()); + assertEquals( + "Broad Data Use Oversight System - Data Access Committee - Data Access Request DAR-0001 is Rule Automated DAR (RADAR) Approved", + message.createSubject()); Template template = helper.getTemplate(message.getTemplateName()); Writer out = new StringWriter(); @@ -53,7 +57,9 @@ void testGetDACMembersDARRADARApprovedTemplate() throws Exception { String templateContent = out.toString(); Document parsedTemplate = Jsoup.parse(templateContent); - assertEquals("Broad Data Use Oversight System - Data Access Committee - Access to a dataset was Rule Automated DAR (RADAR) approved", parsedTemplate.title()); + assertEquals( + "Broad Data Use Oversight System - Data Access Committee - Access to a dataset was Rule Automated DAR (RADAR) approved", + parsedTemplate.title()); assertTrue(templateContent.contains(researcherUser.getDisplayName())); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessageTest.java index b2ba159127..95a8f50c90 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/DaaRequestMessageTest.java @@ -54,7 +54,6 @@ void testGetDaaRequestTemplate() throws Exception { String templateString = out.toString(); Document parsedTemplate = Jsoup.parse(templateString); - assertEquals( "Broad Data Use Oversight System - New Data Access Agreement-Library Card Relationship Request for your Institution", parsedTemplate.title()); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessageTest.java index d317991141..39ed7cf654 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/DarExpirationReminderMessageTest.java @@ -48,13 +48,14 @@ void testGetDarExpiredTemplate() throws Exception { Document parsedTemplate = Jsoup.parse(templateString); assertEquals( - "Broad Data Use Oversight System - Your DAR is about to expire", - parsedTemplate.title()); + "Broad Data Use Oversight System - Your DAR is about to expire", parsedTemplate.title()); assertEquals("Hello %s,".formatted(userName), getElementTextById(parsedTemplate, "userName")); assertEquals( - "Your Data Access Request %s is expiring in 30 days. Please complete a progress report to preserve your access to this data.".formatted( - darCode), getElementTextById(parsedTemplate, "expirationWarning")); - assertEquals("Login to DUOS to submit a progress report.", + "Your Data Access Request %s is expiring in 30 days. Please complete a progress report to preserve your access to this data." + .formatted(darCode), + getElementTextById(parsedTemplate, "expirationWarning")); + assertEquals( + "Login to DUOS to submit a progress report.", getElementTextById(parsedTemplate, "loginLink")); } } diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/DataCustodianApprovalMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/DataCustodianApprovalMessageTest.java index c43c8fbf4c..0502f32279 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/DataCustodianApprovalMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/DataCustodianApprovalMessageTest.java @@ -79,7 +79,9 @@ void testGetDataCustodianRADARApprovalTemplate() throws Exception { var message = new DataCustodianApprovalMessage( toUser, darCode, datasetMailDTOs, "Depositor", "researcher@email.com", true); - assertEquals("Dar Code has been Rule Automated DAR (RADAR) approved by the DAC", message.createSubject()); + assertEquals( + "Dar Code has been Rule Automated DAR (RADAR) approved by the DAC", + message.createSubject()); Template template = helper.getTemplate(message.getTemplateName()); Writer out = new StringWriter(); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessageTest.java index 05562d8c0b..b697eea336 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/DatasetSubmittedMessageTest.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.mail.message; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessageTest.java index 5a1493e408..612cd72eed 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadResearcherMessageTest.java @@ -43,7 +43,8 @@ void testGetNewDaaUploadSOTemplate() throws Exception { User researcher = new User(); researcher.setDisplayName(researcherUserName); - var message = new NewDAAUploadResearcherMessage(researcher, dacName, previousDaaName, newDaaName); + var message = + new NewDAAUploadResearcherMessage(researcher, dacName, previousDaaName, newDaaName); assertEquals(dacName, message.getEntityReferenceId()); Template template = helper.getTemplate(message.getTemplateName()); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessageTest.java index c9875c5925..81e0ad9738 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/NewDAAUploadSOMessageTest.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.mail.message; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -68,13 +67,12 @@ void testGetNewDaaUploadSOTemplate() throws Exception { + dacName + ".")); assertTrue( - content - .contains( - "The " - + dacName - + " has recently transitioned to using the " - + newDaaName - + " which will apply for all future requests to this DAC.")); + content.contains( + "The " + + dacName + + " has recently transitioned to using the " + + newDaaName + + " which will apply for all future requests to this DAC.")); // no unspecified values assertFalse(templateString.contains("${")); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessageTest.java index 6cc15c86a4..d201db596a 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/NewDARRequestMessageTest.java @@ -51,8 +51,7 @@ void testGetNewDARRequestTemplate() throws Exception { String darCode = "DAR-01"; var message = new NewDARRequestMessage(toUser, darCode, dacDatasetGroups, "ResearcherName"); assertEquals(darCode, message.getEntityReferenceId()); - assertEquals( - "Create an election for Data Access Request id: DAR-01.", message.createSubject()); + assertEquals("Create an election for Data Access Request id: DAR-01.", message.createSubject()); Template template = helper.getTemplate(message.getTemplateName()); Writer out = new StringWriter(); @@ -61,11 +60,10 @@ void testGetNewDARRequestTemplate() throws Exception { String templateString = out.toString(); Document parsedTemplate = Jsoup.parse(templateString); - assertEquals("Broad Data Use Oversight System - New DAR submitted to your DAC", - parsedTemplate.title()); assertEquals( - "Hello Admin,", - Objects.requireNonNull(parsedTemplate.getElementById("userName")).text()); + "Broad Data Use Oversight System - New DAR submitted to your DAC", parsedTemplate.title()); + assertEquals( + "Hello Admin,", Objects.requireNonNull(parsedTemplate.getElementById("userName")).text()); assertTrue(templateString.contains(darCode)); assertTrue(templateString.contains(serverUrl)); assertTrue(templateString.contains(dac.getName())); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessageTest.java index 67a56d35b8..67833e8296 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/NewLibraryCardIssuedMessageTest.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.mail.message; - import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessageTest.java index b0076c9b47..fa012b152d 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportCaseMessageTest.java @@ -54,7 +54,8 @@ void testGetNewCaseTemplate() throws Exception { Document parsedTemplate = Jsoup.parse(templateString); assertEquals( - "Broad Data Use Oversight System - New Progress Report ready for your vote", parsedTemplate.title()); + "Broad Data Use Oversight System - New Progress Report ready for your vote", + parsedTemplate.title()); assertEquals("Hello " + userName + ",", getElementTextById(parsedTemplate, "userName")); assertTrue( templateString.contains( diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessageTest.java index 5c30677f92..ee9621358f 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/NewProgressReportRequestMessageTest.java @@ -49,10 +49,11 @@ void testGetNewDARRequestTemplate() throws Exception { var dacDatasetGroups = Map.of(dac.getName(), List.of(d1.getDatasetIdentifier())); String darCode = "DAR-01"; - var message = new NewProgressReportRequestMessage(toUser, darCode, "myReferenceId", dacDatasetGroups, "ResearcherName"); + var message = + new NewProgressReportRequestMessage( + toUser, darCode, "myReferenceId", dacDatasetGroups, "ResearcherName"); assertEquals("myReferenceId", message.getEntityReferenceId()); - assertEquals( - "Create an election for Progress Report id: DAR-01.", message.createSubject()); + assertEquals("Create an election for Progress Report id: DAR-01.", message.createSubject()); Template template = helper.getTemplate(message.getTemplateName()); Writer out = new StringWriter(); @@ -61,11 +62,11 @@ void testGetNewDARRequestTemplate() throws Exception { String templateString = out.toString(); Document parsedTemplate = Jsoup.parse(templateString); - assertEquals("Broad Data Use Oversight System - New Progress Report submitted to your DAC", + assertEquals( + "Broad Data Use Oversight System - New Progress Report submitted to your DAC", parsedTemplate.title()); assertEquals( - "Hello Admin,", - Objects.requireNonNull(parsedTemplate.getElementById("userName")).text()); + "Hello Admin,", Objects.requireNonNull(parsedTemplate.getElementById("userName")).text()); assertTrue(templateString.contains(darCode)); assertTrue(templateString.contains(serverUrl)); assertTrue(templateString.contains(dac.getName())); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/NewResearcherLibraryRequestMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/NewResearcherLibraryRequestMessageTest.java index ffb55b0b0f..02964812da 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/NewResearcherLibraryRequestMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/NewResearcherLibraryRequestMessageTest.java @@ -56,8 +56,7 @@ void testGetNewResearcherLibraryRequestTemplate() throws Exception { .contains("A researcher from your institution, John Doe, has registered in DUOS")); assertEquals( - serverUrl, - Objects.requireNonNull(parsedTemplate.getElementById("serverUrl")).attr("href")); + serverUrl, Objects.requireNonNull(parsedTemplate.getElementById("serverUrl")).attr("href")); // no unspecified values assertFalse(templateString.contains("${")); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/ReminderMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/ReminderMessageTest.java index 8d65ee0082..2d7a95f228 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/ReminderMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/ReminderMessageTest.java @@ -30,12 +30,17 @@ void setUp() { @Test void testMessageSubject() { - var message = new ReminderMessage(new User(), new Vote(), "DUL-123", "Data Use Limitations", ""); - assertEquals("Urgent: Log vote on Data Use Limitations case id: DUL-123.", message.createSubject()); - var message2 = new ReminderMessage(new User(), new Vote(), "DAR-123", "Data Access Request", ""); - assertEquals("Urgent: Log votes on Data Access Request case id: DAR-123.", message2.createSubject()); + var message = + new ReminderMessage(new User(), new Vote(), "DUL-123", "Data Use Limitations", ""); + assertEquals( + "Urgent: Log vote on Data Use Limitations case id: DUL-123.", message.createSubject()); + var message2 = + new ReminderMessage(new User(), new Vote(), "DAR-123", "Data Access Request", ""); + assertEquals( + "Urgent: Log votes on Data Access Request case id: DAR-123.", message2.createSubject()); var message3 = new ReminderMessage(new User(), new Vote(), "RP-123", "Research Purpose", ""); - assertEquals("Urgent: Log votes on Research Purpose Review case id: RP-123.", message3.createSubject()); + assertEquals( + "Urgent: Log votes on Research Purpose Review case id: RP-123.", message3.createSubject()); } @Test @@ -57,7 +62,8 @@ void testGetReminderTemplate() throws Exception { String templateString = out.toString(); Document parsedTemplate = Jsoup.parse(templateString); - assertEquals("Broad Data Use Oversight System - Your vote was requested for a Data Access Request", + assertEquals( + "Broad Data Use Oversight System - Your vote was requested for a Data Access Request", parsedTemplate.title()); assertEquals( "Hello Reminder User,", diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessageTest.java index 6288b815e3..0744de0e8d 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherCloseoutCompletedMessageTest.java @@ -49,14 +49,16 @@ void testGetResearcherCloseoutCompletedTemplate() throws Exception { var templateString = out.toString(); Document parsedTemplate = Jsoup.parse(templateString); - assertEquals("Broad Data Use Oversight System - Researcher - Closeout Complete", - parsedTemplate.title()); + assertEquals( + "Broad Data Use Oversight System - Researcher - Closeout Complete", parsedTemplate.title()); assertEquals("Dear %s,".formatted(userName), getElementTextById(parsedTemplate, "userName")); assertEquals( - "The closeout on Data Access Request (DAR) %s has been approved and your access to all datasets in this DAR will be revoked unless you have permission to use that data under another DAR.".formatted( - darCode), getElementTextById(parsedTemplate, "content")); - assertTrue(getElementTextById(parsedTemplate, "warning").contains( - "you have agreed to destroy all copies")); + "The closeout on Data Access Request (DAR) %s has been approved and your access to all datasets in this DAR will be revoked unless you have permission to use that data under another DAR." + .formatted(darCode), + getElementTextById(parsedTemplate, "content")); + assertTrue( + getElementTextById(parsedTemplate, "warning") + .contains("you have agreed to destroy all copies")); // no unspecified values assertFalse(templateString.contains("${")); } diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherDarApprovedMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherDarApprovedMessageTest.java index e3297c11f9..4ecb336f83 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherDarApprovedMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherDarApprovedMessageTest.java @@ -104,7 +104,9 @@ void testGetResearcherRADARApprovedTemplate() throws Exception { "Hello " + researcherUserName + ",", getElementTextById(parsedTemplate, "userName")); assertTrue( templateString.contains( - "Your data access request application " + darCode + " was Rule Automated DAR (RADAR) approved")); + "Your data access request application " + + darCode + + " was Rule Automated DAR (RADAR) approved")); assertTrue(templateString.contains(datasetId)); assertTrue(templateString.contains(datasetName)); assertTrue(templateString.contains(researcherEmail)); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherProgressReportApprovedMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherProgressReportApprovedMessageTest.java index b48804f9d9..dc2682a26c 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherProgressReportApprovedMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/ResearcherProgressReportApprovedMessageTest.java @@ -36,7 +36,8 @@ String getElementTextById(Document document, String id) { @Test void testMessageSubject() { - var message = new ResearcherApprovedProgressReportMessage(new User(), "DAR-123", List.of(), "", false); + var message = + new ResearcherApprovedProgressReportMessage(new User(), "DAR-123", List.of(), "", false); assertEquals("Your DUOS Progress Report Results", message.createSubject()); } @@ -67,7 +68,8 @@ void testGetResearcherApprovedTemplate() throws Exception { parsedTemplate.title()); assertEquals( "Hello " + researcherUserName + ",", getElementTextById(parsedTemplate, "userName")); - assertTrue(templateString.contains("Your progress report application " + darCode + " was approved")); + assertTrue( + templateString.contains("Your progress report application " + darCode + " was approved")); assertTrue(templateString.contains(datasetId)); assertTrue(templateString.contains(datasetName)); assertTrue(templateString.contains(researcherEmail)); @@ -100,7 +102,11 @@ void testGetResearcherRADARApprovedTemplate() throws Exception { parsedTemplate.title()); assertEquals( "Hello " + researcherUserName + ",", getElementTextById(parsedTemplate, "userName")); - assertTrue(templateString.contains("Your progress report application " + darCode + " was Rule Automated DAR (RADAR) approved")); + assertTrue( + templateString.contains( + "Your progress report application " + + darCode + + " was Rule Automated DAR (RADAR) approved")); assertTrue(templateString.contains(datasetId)); assertTrue(templateString.contains(datasetName)); assertTrue(templateString.contains(researcherEmail)); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/SigningOfficialMessagesTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/SigningOfficialMessagesTest.java index eb902ef636..665ad27ce5 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/SigningOfficialMessagesTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/SigningOfficialMessagesTest.java @@ -26,8 +26,8 @@ class SigningOfficialMessagesTest extends AbstractTestHelper { private static final String DAR_CODE = "DAR-123"; private static final String REFERENCE_ID = UUID.randomUUID().toString(); - private static final String TRANSLATION = new DataUseBuilder().setGeneralUse(true).build() - .toString(); + private static final String TRANSLATION = + new DataUseBuilder().setGeneralUse(true).build().toString(); private static User toUser; private static User researcher; private static List datasets; @@ -35,17 +35,20 @@ class SigningOfficialMessagesTest extends AbstractTestHelper { private static Stream messageProvider() { return Stream.of( - Arguments.of(new SoDARApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, - TRANSLATION, false)), - Arguments.of(new SoDARApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, - TRANSLATION, true)), - Arguments.of(new SoPRApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, - TRANSLATION, false)), - Arguments.of(new SoPRApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, - TRANSLATION, true)), + Arguments.of( + new SoDARApproved( + toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, TRANSLATION, false)), + Arguments.of( + new SoDARApproved( + toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, TRANSLATION, true)), + Arguments.of( + new SoPRApproved( + toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, TRANSLATION, false)), + Arguments.of( + new SoPRApproved( + toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, TRANSLATION, true)), Arguments.of(new SoDARSubmitted(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets)), - Arguments.of(new SoPRSubmitted(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets)) - ); + Arguments.of(new SoPRSubmitted(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets))); } @BeforeEach @@ -85,10 +88,11 @@ void testMessageTemplate(MailMessage message) throws Exception { assertTrue(templateString.contains(toUser.getDisplayName())); assertTrue(templateString.contains(DAR_CODE)); assertTrue(templateString.contains(researcher.getDisplayName())); - datasets.forEach(dataset -> { - assertTrue(templateString.contains(dataset.getName())); - assertTrue(templateString.contains(dataset.getDatasetIdentifier())); - }); + datasets.forEach( + dataset -> { + assertTrue(templateString.contains(dataset.getName())); + assertTrue(templateString.contains(dataset.getDatasetIdentifier())); + }); } @ParameterizedTest @@ -99,22 +103,22 @@ void testMessageEntityReferenceId(MailMessage message) { @Test void testDARApprovedRADARReferences() throws Exception { - MailMessage message = new SoDARApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, - TRANSLATION, true); + MailMessage message = + new SoDARApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, TRANSLATION, true); var linkUrl = "http://testServerUrl"; var template = helper.getTemplate(message.getTemplateName()); var out = new StringWriter(); template.process(message.createModel(linkUrl), out); String templateString = out.toString(); - assertEquals(2, StringUtils.countMatches(templateString," Rule Automated DAR (RADAR) ")); + assertEquals(2, StringUtils.countMatches(templateString, " Rule Automated DAR (RADAR) ")); assertFalse(templateString.contains("radarText")); } @Test void testDARNORADARReferences() throws Exception { - MailMessage message = new SoDARApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, - TRANSLATION, false); + MailMessage message = + new SoDARApproved(toUser, DAR_CODE, researcher, REFERENCE_ID, datasets, TRANSLATION, false); var linkUrl = "http://testServerUrl"; var template = helper.getTemplate(message.getTemplateName()); var out = new StringWriter(); @@ -134,7 +138,7 @@ void testPRApprovedRADARReferences() throws Exception { template.process(message.createModel(linkUrl), out); String templateString = out.toString(); - assertEquals(2, StringUtils.countMatches(templateString," Rule Automated DAR (RADAR) ")); + assertEquals(2, StringUtils.countMatches(templateString, " Rule Automated DAR (RADAR) ")); assertFalse(templateString.contains("radarText")); String subject = message.createSubject(); diff --git a/src/test/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessageTest.java b/src/test/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessageTest.java index 696339aa3f..91cbcaba4b 100644 --- a/src/test/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessageTest.java +++ b/src/test/java/org/broadinstitute/consent/http/mail/message/SubmittedCloseoutMessageTest.java @@ -31,7 +31,8 @@ void setUp() { @Test void testMessageSubject() { - var message = new SubmittedCloseoutMessage(toUser, "DAR-123", "ref-456", "http://testServerUrl"); + var message = + new SubmittedCloseoutMessage(toUser, "DAR-123", "ref-456", "http://testServerUrl"); assertEquals("DAR DAR-123 Closeout Available for Review", message.createSubject()); } diff --git a/src/test/java/org/broadinstitute/consent/http/models/DarManualReviewTest.java b/src/test/java/org/broadinstitute/consent/http/models/DarManualReviewTest.java index b7c4d53486..0c74a5e0d4 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DarManualReviewTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DarManualReviewTest.java @@ -104,5 +104,4 @@ void testManualReviewNotHealth() { dar.getData().setNotHealth(true); assertTrue(dar.requiresManualReview()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestDataTest.java b/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestDataTest.java index 2b0e345111..8f3de68fbc 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestDataTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestDataTest.java @@ -14,7 +14,8 @@ class DataAccessRequestDataTest { @Test void serialization() { - String exampleDarData = """ + String exampleDarData = + """ { "institution": "The Broad Institute of MIT and Harvard", "projectTitle": "title", @@ -22,7 +23,8 @@ void serialization() { "checkNihDataOnly": false }"""; DataAccessRequestData resultingDarData = DataAccessRequestData.fromString(exampleDarData); - String expectedDarData = """ + String expectedDarData = + """ {"projectTitle":"title","checkNihDataOnly":false}"""; // does not include fields removed from the object (ex. checkCollaborator, institution) assertEquals(expectedDarData, resultingDarData.toString()); @@ -67,7 +69,8 @@ void testGetSetSigningOfficialEmail() { @Test void testPopulateDARDataWithValidJson() { - String validJson = """ + String validJson = + """ { "projectTitle": "Test Project", "checkNihDataOnly": true @@ -81,12 +84,14 @@ void testPopulateDARDataWithValidJson() { @Test void testPopulateDARDataWithInvalidJson() { - String invalidJson = """ + String invalidJson = + """ { "projectTitle": "Test Project", "checkNihDataOnly": true, """; - assertThrows(BadRequestException.class, () -> DataAccessRequestData.populateDARData(invalidJson)); + assertThrows( + BadRequestException.class, () -> DataAccessRequestData.populateDARData(invalidJson)); } @Test diff --git a/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestTest.java b/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestTest.java index 41ec2cee64..28bbda941b 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DataAccessRequestTest.java @@ -35,7 +35,8 @@ void populateProgressReportFromJsonString() { parentData.setPubAcknowledgement(false); parentDar.setData(parentData); - String json = """ + String json = + """ { "projectTitle": "New Project Title", "internalCollaborators": [], @@ -52,7 +53,8 @@ void populateProgressReportFromJsonString() { } """; - DataAccessRequest newDar = DataAccessRequest.populateProgressReportFromJsonString(json, parentDar); + DataAccessRequest newDar = + DataAccessRequest.populateProgressReportFromJsonString(json, parentDar); DataAccessRequestData newData = newDar.getData(); assertNotNull(newDar); @@ -69,7 +71,8 @@ void populateProgressReportFromJsonString() { assertNull(newData.getIrbDocumentName()); assertNull(newData.getCollaborationLetterLocation()); assertNull(newData.getIrbDocumentLocation()); - assertEquals(List.of(collaborator), + assertEquals( + List.of(collaborator), parentDar.getData().getInternalCollaborators()); // Ensure parent is unchanged assertEquals("collaboration_letter.txt", parentDar.getData().getCollaborationLetterName()); assertTrue(newData.getDSAcknowledgement()); @@ -165,34 +168,54 @@ void testValidateCloseoutSupplement_Unset() { DataAccessRequestData darData = new DataAccessRequestData(); darData.setCloseoutSupplement(null); dar.setData(darData); - assertDoesNotThrow(() -> DataAccessRequest.validateCloseoutSupplement(dar.getData().getCloseoutSupplement())); + assertDoesNotThrow( + () -> DataAccessRequest.validateCloseoutSupplement(dar.getData().getCloseoutSupplement())); } @Test void testValidateCloseoutApprovalThrowsExceptionWithEmptyReasonsOtherTextSigningOfficial() { CloseoutSupplement supplement = new CloseoutSupplement(List.of(), "", null); - BadRequestException exception = assertThrows(BadRequestException.class, () -> DataAccessRequest.validateCloseoutSupplement(supplement)); - assertThat(exception.getMessage(), containsString("A closeout supplement must have values provided.")); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> DataAccessRequest.validateCloseoutSupplement(supplement)); + assertThat( + exception.getMessage(), containsString("A closeout supplement must have values provided.")); } @Test void testValidateCloseoutApprovalThrowsExceptionWithEmptyReasons() { CloseoutSupplement supplement = new CloseoutSupplement(List.of(), "", 1); - BadRequestException exception = assertThrows(BadRequestException.class, () -> DataAccessRequest.validateCloseoutSupplement(supplement)); - assertThat(exception.getMessage(), containsString("A closeout supplement must have reasons provided.")); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> DataAccessRequest.validateCloseoutSupplement(supplement)); + assertThat( + exception.getMessage(), + containsString("A closeout supplement must have reasons provided.")); } @Test void testValidateCloseoutApprovalThrowsExceptionWithNullReasons() { CloseoutSupplement supplement = new CloseoutSupplement(null, "", 1); - BadRequestException exception = assertThrows(BadRequestException.class, () -> DataAccessRequest.validateCloseoutSupplement(supplement)); - assertThat(exception.getMessage(), containsString("A closeout supplement must have reasons provided.")); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> DataAccessRequest.validateCloseoutSupplement(supplement)); + assertThat( + exception.getMessage(), + containsString("A closeout supplement must have reasons provided.")); } @Test void testValidateCloseoutApprovalThrowsExceptionWithEmptySigningOfficial() { CloseoutSupplement supplement = new CloseoutSupplement(List.of("test"), "", null); - BadRequestException exception = assertThrows(BadRequestException.class, () -> DataAccessRequest.validateCloseoutSupplement(supplement)); - assertThat(exception.getMessage(), containsString("A closeout supplement must have a signing official id provided.")); - } -} \ No newline at end of file + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> DataAccessRequest.validateCloseoutSupplement(supplement)); + assertThat( + exception.getMessage(), + containsString("A closeout supplement must have a signing official id provided.")); + } +} diff --git a/src/test/java/org/broadinstitute/consent/http/models/DatasetPatchTest.java b/src/test/java/org/broadinstitute/consent/http/models/DatasetPatchTest.java index ea3f0efac4..f928bd2a8b 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DatasetPatchTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DatasetPatchTest.java @@ -119,5 +119,4 @@ void testValidateDataLocationFailure() { DatasetPatch patch = new DatasetPatch(null, List.of(dataLocationProp)); assertFalse(patch.validateProperties()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1AssetsTest.java b/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1AssetsTest.java index 437da4ac9b..84c3a8f6a4 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1AssetsTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1AssetsTest.java @@ -15,15 +15,25 @@ class DatasetRegistrationSchemaV1AssetsTest { void testAssetsFieldCanBeSetAndRetrieved() { // Create a DatasetRegistrationSchemaV1 instance DatasetRegistrationSchemaV1 registration = new DatasetRegistrationSchemaV1(); - + // Create a sample assets object Map assets = new HashMap<>(); - assets.put("workspaces", Map.of("workspace_id", "c7b96ac5-5568-441c-a3f4-2e82e45e3e6d", "name", "Cardiometabolic GWAS Analysis Workspace", "platform", "Terra")); - assets.put("funding", Map.of("funding_id", "fund-0001", "funder_name", "NIH", "grant_number", "R01HG012345")); - + assets.put( + "workspaces", + Map.of( + "workspace_id", + "c7b96ac5-5568-441c-a3f4-2e82e45e3e6d", + "name", + "Cardiometabolic GWAS Analysis Workspace", + "platform", + "Terra")); + assets.put( + "funding", + Map.of("funding_id", "fund-0001", "funder_name", "NIH", "grant_number", "R01HG012345")); + // Set the assets registration.setAssets(assets); - + // Verify the assets can be retrieved Map retrievedAssets = registration.getAssets(); assertNotNull(retrievedAssets); @@ -36,23 +46,24 @@ void testAssetsFieldSerializationWithGson() { // Create a DatasetRegistrationSchemaV1 instance with assets DatasetRegistrationSchemaV1 registration = new DatasetRegistrationSchemaV1(); registration.setStudyName("Test Study"); - + Map assets = new HashMap<>(); assets.put("customField", "customValue"); assets.put("nestedObject", Map.of("key1", "value1", "key2", 123)); registration.setAssets(assets); - + // Serialize to JSON Gson gson = new Gson(); String json = gson.toJson(registration); - + // Verify JSON contains assets assertTrue(json.contains("\"assets\"")); assertTrue(json.contains("\"customField\"")); assertTrue(json.contains("\"customValue\"")); - + // Deserialize back - DatasetRegistrationSchemaV1 deserialized = gson.fromJson(json, DatasetRegistrationSchemaV1.class); + DatasetRegistrationSchemaV1 deserialized = + gson.fromJson(json, DatasetRegistrationSchemaV1.class); assertNotNull(deserialized.getAssets()); assertEquals("customValue", deserialized.getAssets().get("customField")); } @@ -62,7 +73,7 @@ void testAssetsFieldIsOptional() { // Create a DatasetRegistrationSchemaV1 instance without setting assets DatasetRegistrationSchemaV1 registration = new DatasetRegistrationSchemaV1(); registration.setStudyName("Test Study"); - + // Verify assets is initialized as empty map Map assets = registration.getAssets(); assertNotNull(assets); @@ -72,9 +83,10 @@ void testAssetsFieldIsOptional() { @Test void testJsonSchemaValidationAcceptsAssets() { JsonSchemaUtil jsonSchemaUtil = new JsonSchemaUtil(); - + // Create a minimal valid JSON with assets - String json = """ + String json = + """ { "studyName": "Test Study", "studyDescription": "Test Description", @@ -99,21 +111,22 @@ void testJsonSchemaValidationAcceptsAssets() { } } """; - + // Validate the schema var errors = jsonSchemaUtil.validateSchema_v1(json); - + // Verify no validation errors - assertTrue(errors.isEmpty(), - "Schema validation should pass with assets field. Errors: " + errors); + assertTrue( + errors.isEmpty(), "Schema validation should pass with assets field. Errors: " + errors); } @Test void testEmptyAssetsObjectIsValid() { JsonSchemaUtil jsonSchemaUtil = new JsonSchemaUtil(); - + // Create a minimal valid JSON with empty assets - String json = """ + String json = + """ { "studyName": "Test Study", "studyDescription": "Test Description", @@ -132,21 +145,23 @@ void testEmptyAssetsObjectIsValid() { "assets": {} } """; - + // Validate the schema var errors = jsonSchemaUtil.validateSchema_v1(json); - + // Verify no validation errors - assertTrue(errors.isEmpty(), + assertTrue( + errors.isEmpty(), "Schema validation should pass with empty assets field. Errors: " + errors); } @Test void testMissingAssetsFieldIsValid() { JsonSchemaUtil jsonSchemaUtil = new JsonSchemaUtil(); - + // Create a minimal valid JSON without assets field - String json = """ + String json = + """ { "studyName": "Test Study", "studyDescription": "Test Description", @@ -164,12 +179,12 @@ void testMissingAssetsFieldIsValid() { ] } """; - + // Validate the schema var errors = jsonSchemaUtil.validateSchema_v1(json); - + // Verify no validation errors - assertTrue(errors.isEmpty(), - "Schema validation should pass without assets field. Errors: " + errors); + assertTrue( + errors.isEmpty(), "Schema validation should pass without assets field. Errors: " + errors); } } diff --git a/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1BuilderTest.java b/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1BuilderTest.java index eb31ea14da..1a50d38682 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1BuilderTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DatasetRegistrationSchemaV1BuilderTest.java @@ -147,22 +147,23 @@ void testBuildSchemaWithDataUse() { DatasetRegistrationSchemaV1Builder builder = new DatasetRegistrationSchemaV1Builder(); Study study = createMockStudy(); Dataset dataset = createMockDataset(); - DataUse dataUse = new DataUseBuilder() - .setGeneralUse(RandomUtils.nextBoolean()) - .setHmbResearch(RandomUtils.nextBoolean()) - .setDiseaseRestrictions(List.of(RandomStringUtils.randomAlphabetic(10))) - .setPopulationOriginsAncestry(RandomUtils.nextBoolean()) - .setOther(RandomStringUtils.randomAlphabetic(10)) - .setMethodsResearch(RandomUtils.nextBoolean()) - .setGeneticStudiesOnly(RandomUtils.nextBoolean()) - .setPublicationResults(RandomUtils.nextBoolean()) - .setCollaboratorRequired(RandomUtils.nextBoolean()) - .setEthicsApprovalRequired(RandomUtils.nextBoolean()) - .setGeographicalRestrictions(RandomStringUtils.randomAlphabetic(10)) - .setPublicationMoratorium(new Date().toString()) - .setNonProfitUse(RandomUtils.nextBoolean()) - .setSecondaryOther(RandomStringUtils.randomAlphabetic(10)) - .build(); + DataUse dataUse = + new DataUseBuilder() + .setGeneralUse(RandomUtils.nextBoolean()) + .setHmbResearch(RandomUtils.nextBoolean()) + .setDiseaseRestrictions(List.of(RandomStringUtils.randomAlphabetic(10))) + .setPopulationOriginsAncestry(RandomUtils.nextBoolean()) + .setOther(RandomStringUtils.randomAlphabetic(10)) + .setMethodsResearch(RandomUtils.nextBoolean()) + .setGeneticStudiesOnly(RandomUtils.nextBoolean()) + .setPublicationResults(RandomUtils.nextBoolean()) + .setCollaboratorRequired(RandomUtils.nextBoolean()) + .setEthicsApprovalRequired(RandomUtils.nextBoolean()) + .setGeographicalRestrictions(RandomStringUtils.randomAlphabetic(10)) + .setPublicationMoratorium(new Date().toString()) + .setNonProfitUse(RandomUtils.nextBoolean()) + .setSecondaryOther(RandomStringUtils.randomAlphabetic(10)) + .build(); dataset.setDataUse(dataUse); DatasetRegistrationSchemaV1 schemaV1 = builder.build(study, List.of(dataset)); ConsentGroup consentGroup = schemaV1.getConsentGroups().get(0); @@ -219,77 +220,136 @@ private Study createMockStudy() { private void addAllStudyProperties(Study study) { study.addProperty( - createStudyProperty(studyType, study.getStudyId(), StudyType.OBSERVATIONAL.value(), - PropertyType.String)); - study.addProperty(createStudyProperty(phenotypeIndication, study.getStudyId(), randomString(), - PropertyType.String)); + createStudyProperty( + studyType, study.getStudyId(), StudyType.OBSERVATIONAL.value(), PropertyType.String)); + study.addProperty( + createStudyProperty( + phenotypeIndication, study.getStudyId(), randomString(), PropertyType.String)); study.addProperty( createStudyProperty(species, study.getStudyId(), randomString(), PropertyType.String)); - study.addProperty(createStudyProperty(dataCustodianEmail, study.getStudyId(), - GsonUtil.getInstance().toJson(List.of(randomString())), PropertyType.Json)); - study.addProperty(createStudyProperty(nihAnvilUse, study.getStudyId(), - NihAnvilUse.I_AM_NHGRI_FUNDED_AND_I_HAVE_A_DB_GA_P_PHS_ID_ALREADY.value(), - PropertyType.String)); - study.addProperty(createStudyProperty(submittingToAnvil, study.getStudyId(), Boolean.TRUE, - PropertyType.Boolean)); study.addProperty( - createStudyProperty(dbGaPPhsID, study.getStudyId(), randomString(), PropertyType.String)); + createStudyProperty( + dataCustodianEmail, + study.getStudyId(), + GsonUtil.getInstance().toJson(List.of(randomString())), + PropertyType.Json)); study.addProperty( - createStudyProperty(dbGaPStudyRegistrationName, study.getStudyId(), randomString(), + createStudyProperty( + nihAnvilUse, + study.getStudyId(), + NihAnvilUse.I_AM_NHGRI_FUNDED_AND_I_HAVE_A_DB_GA_P_PHS_ID_ALREADY.value(), PropertyType.String)); - study.addProperty(createStudyProperty(embargoReleaseDate, study.getStudyId(), randomString(), - PropertyType.String)); - study.addProperty(createStudyProperty(sequencingCenter, study.getStudyId(), randomString(), - PropertyType.String)); + study.addProperty( + createStudyProperty( + submittingToAnvil, study.getStudyId(), Boolean.TRUE, PropertyType.Boolean)); + study.addProperty( + createStudyProperty(dbGaPPhsID, study.getStudyId(), randomString(), PropertyType.String)); + study.addProperty( + createStudyProperty( + dbGaPStudyRegistrationName, study.getStudyId(), randomString(), PropertyType.String)); + study.addProperty( + createStudyProperty( + embargoReleaseDate, study.getStudyId(), randomString(), PropertyType.String)); + study.addProperty( + createStudyProperty( + sequencingCenter, study.getStudyId(), randomString(), PropertyType.String)); study.addProperty( createStudyProperty(piInstitution, study.getStudyId(), randomInt(), PropertyType.Number)); study.addProperty( - createStudyProperty(nihGrantContractNumber, study.getStudyId(), randomString(), + createStudyProperty( + nihGrantContractNumber, study.getStudyId(), randomString(), PropertyType.String)); + study.addProperty( + createStudyProperty( + nihICsSupportingStudy, + study.getStudyId(), + GsonUtil.getInstance().toJson(List.of(NihICsSupportingStudy.CC.value())), + PropertyType.Json)); + study.addProperty( + createStudyProperty( + nihProgramOfficerName, study.getStudyId(), randomString(), PropertyType.String)); + study.addProperty( + createStudyProperty( + nihInstitutionCenterSubmission, + study.getStudyId(), + NihInstitutionCenterSubmission.CC.value(), PropertyType.String)); - study.addProperty(createStudyProperty(nihICsSupportingStudy, study.getStudyId(), - GsonUtil.getInstance().toJson(List.of(NihICsSupportingStudy.CC.value())), - PropertyType.Json)); - study.addProperty(createStudyProperty(nihProgramOfficerName, study.getStudyId(), randomString(), - PropertyType.String)); - study.addProperty(createStudyProperty(nihInstitutionCenterSubmission, study.getStudyId(), - NihInstitutionCenterSubmission.CC.value(), PropertyType.String)); study.addProperty( - createStudyProperty(nihGenomicProgramAdministratorName, study.getStudyId(), randomString(), + createStudyProperty( + nihGenomicProgramAdministratorName, + study.getStudyId(), + randomString(), PropertyType.String)); - study.addProperty(createStudyProperty(multiCenterStudy, study.getStudyId(), Boolean.TRUE, - PropertyType.Boolean)); - study.addProperty(createStudyProperty(collaboratingSites, study.getStudyId(), - GsonUtil.getInstance().toJson(List.of(randomString())), PropertyType.Json)); study.addProperty( - createStudyProperty(controlledAccessRequiredForGenomicSummaryResultsGSR, study.getStudyId(), - Boolean.TRUE, PropertyType.Boolean)); + createStudyProperty( + multiCenterStudy, study.getStudyId(), Boolean.TRUE, PropertyType.Boolean)); study.addProperty( - createStudyProperty(controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation, - study.getStudyId(), randomString(), PropertyType.String)); - study.addProperty(createStudyProperty(alternativeDataSharingPlanReasons, study.getStudyId(), - GsonUtil.getInstance().toJson(List.of(AlternativeDataSharingPlanReason.OTHER.value())), - PropertyType.Json)); - study.addProperty(createStudyProperty(alternativeDataSharingPlanExplanation, study.getStudyId(), - randomString(), PropertyType.String)); + createStudyProperty( + collaboratingSites, + study.getStudyId(), + GsonUtil.getInstance().toJson(List.of(randomString())), + PropertyType.Json)); study.addProperty( - createStudyProperty(alternativeDataSharingPlanFileName, study.getStudyId(), randomString(), + createStudyProperty( + controlledAccessRequiredForGenomicSummaryResultsGSR, + study.getStudyId(), + Boolean.TRUE, + PropertyType.Boolean)); + study.addProperty( + createStudyProperty( + controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation, + study.getStudyId(), + randomString(), + PropertyType.String)); + study.addProperty( + createStudyProperty( + alternativeDataSharingPlanReasons, + study.getStudyId(), + GsonUtil.getInstance().toJson(List.of(AlternativeDataSharingPlanReason.OTHER.value())), + PropertyType.Json)); + study.addProperty( + createStudyProperty( + alternativeDataSharingPlanExplanation, + study.getStudyId(), + randomString(), PropertyType.String)); study.addProperty( - createStudyProperty(alternativeDataSharingPlanDataSubmitted, study.getStudyId(), - AlternativeDataSharingPlanDataSubmitted.BY_BATCHES_OVER_STUDY_TIMELINE_E_G_BASED_ON_CLINICAL_TRIAL_ENROLLMENT_BENCHMARKS.value(), + createStudyProperty( + alternativeDataSharingPlanFileName, + study.getStudyId(), + randomString(), PropertyType.String)); study.addProperty( - createStudyProperty(alternativeDataSharingPlanDataReleased, study.getStudyId(), - Boolean.TRUE, PropertyType.Boolean)); + createStudyProperty( + alternativeDataSharingPlanDataSubmitted, + study.getStudyId(), + AlternativeDataSharingPlanDataSubmitted + .BY_BATCHES_OVER_STUDY_TIMELINE_E_G_BASED_ON_CLINICAL_TRIAL_ENROLLMENT_BENCHMARKS + .value(), + PropertyType.String)); study.addProperty( - createStudyProperty(alternativeDataSharingPlanTargetDeliveryDate, study.getStudyId(), - randomString(), PropertyType.String)); + createStudyProperty( + alternativeDataSharingPlanDataReleased, + study.getStudyId(), + Boolean.TRUE, + PropertyType.Boolean)); study.addProperty( - createStudyProperty(alternativeDataSharingPlanTargetPublicReleaseDate, study.getStudyId(), - randomString(), PropertyType.String)); + createStudyProperty( + alternativeDataSharingPlanTargetDeliveryDate, + study.getStudyId(), + randomString(), + PropertyType.String)); study.addProperty( - createStudyProperty(alternativeDataSharingPlanAccessManagement, study.getStudyId(), - AlternativeDataSharingPlanAccessManagement.OPEN_ACCESS.value(), PropertyType.String)); + createStudyProperty( + alternativeDataSharingPlanTargetPublicReleaseDate, + study.getStudyId(), + randomString(), + PropertyType.String)); + study.addProperty( + createStudyProperty( + alternativeDataSharingPlanAccessManagement, + study.getStudyId(), + AlternativeDataSharingPlanAccessManagement.OPEN_ACCESS.value(), + PropertyType.String)); } private String randomString() { @@ -300,8 +360,8 @@ private Integer randomInt() { return RandomUtils.nextInt(1, 100); } - private StudyProperty createStudyProperty(String key, Integer studyId, Object value, - PropertyType type) { + private StudyProperty createStudyProperty( + String key, Integer studyId, Object value, PropertyType type) { StudyProperty property = new StudyProperty(); property.setKey(key); property.setStudyId(studyId); @@ -336,12 +396,13 @@ private Dataset createMockDataset() { private void addAllDatasetProperties(Dataset dataset) { dataset.addProperty( - createDatasetProperty(dataset, accessManagement, PropertyType.String, - AccessManagement.CONTROLLED.value())); + createDatasetProperty( + dataset, accessManagement, PropertyType.String, AccessManagement.CONTROLLED.value())); // Controlled access datasets require a DAC ID dataset.setDacId(RandomUtils.nextInt(10, 100)); - dataset.addProperty(createDatasetProperty(dataset, dataLocation, PropertyType.String, - DataLocation.NOT_DETERMINED.value())); + dataset.addProperty( + createDatasetProperty( + dataset, dataLocation, PropertyType.String, DataLocation.NOT_DETERMINED.value())); dataset.addProperty( createDatasetProperty(dataset, url, PropertyType.String, "http://www.abc.com")); dataset.addProperty( @@ -350,8 +411,8 @@ private void addAllDatasetProperties(Dataset dataset) { createDatasetProperty(dataset, fileTypes, PropertyType.Json, new FileTypeObject())); } - private DatasetProperty createDatasetProperty(Dataset dataset, String schemaProp, - PropertyType type, Object propValue) { + private DatasetProperty createDatasetProperty( + Dataset dataset, String schemaProp, PropertyType type, Object propValue) { DatasetProperty prop = new DatasetProperty(); prop.setDatasetId(dataset.getDatasetId()); prop.setSchemaProperty(schemaProp); @@ -374,5 +435,4 @@ private DatasetProperty createDatasetProperty(Dataset dataset, String schemaProp } return prop; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/DatasetTests.java b/src/test/java/org/broadinstitute/consent/http/models/DatasetTests.java index 12fe879366..f4e9c93f6f 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DatasetTests.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DatasetTests.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.models; - import static org.junit.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -91,12 +90,12 @@ void testParseIdentifierToAlias() { assertEquals(3, (int) Dataset.parseIdentifierToAlias("DUOS-000003")); assertEquals(123456, (int) Dataset.parseIdentifierToAlias("DUOS-123456")); - assertThrows(IllegalArgumentException.class, - () -> Dataset.parseIdentifierToAlias("asdf-123456")); - assertThrows(IllegalArgumentException.class, - () -> Dataset.parseIdentifierToAlias("DUOS-1234 56")); - assertThrows(IllegalArgumentException.class, - () -> Dataset.parseIdentifierToAlias("DUOS-1234as56")); + assertThrows( + IllegalArgumentException.class, () -> Dataset.parseIdentifierToAlias("asdf-123456")); + assertThrows( + IllegalArgumentException.class, () -> Dataset.parseIdentifierToAlias("DUOS-1234 56")); + assertThrows( + IllegalArgumentException.class, () -> Dataset.parseIdentifierToAlias("DUOS-1234as56")); } @Test @@ -210,7 +209,6 @@ void testIsDatasetMatchMultipleTerms() { assertFalse(ds.isDatasetMatch("asf DUOS-001234", AccessManagement.CONTROLLED)); assertFalse(ds.isDatasetMatch("asd 122", AccessManagement.CONTROLLED)); - } @Test @@ -246,5 +244,4 @@ void testIsDatasetMatchControlledAccess() { assertTrue(ds.isDatasetMatch(value, AccessManagement.CONTROLLED)); assertFalse(ds.isDatasetMatch(RandomStringUtils.randomAlphanumeric(25), AccessManagement.OPEN)); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/DatasetUpdateTest.java b/src/test/java/org/broadinstitute/consent/http/models/DatasetUpdateTest.java index 636a4fb0f1..d6614ea85f 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/DatasetUpdateTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/DatasetUpdateTest.java @@ -16,7 +16,8 @@ public class DatasetUpdateTest { @Test void testDatasetUpdate() { - String json = """ + String json = + """ { "name": "Test Dataset Update", "dacId": 1, @@ -53,21 +54,24 @@ void testDatasetUpdate() { // Parsing the object value of this prop is a little complicated due to JSON serialization DatasetProperty fileTypeProp = getPropByName("File Types", props); - java.lang.reflect.Type listOfFileTypes = new TypeToken>() {}.getType(); + java.lang.reflect.Type listOfFileTypes = + new TypeToken>() {}.getType(); Gson gson = new Gson(); - List fileTypes = gson.fromJson(fileTypeProp.getPropertyValueAsString(), listOfFileTypes); + List fileTypes = + gson.fromJson(fileTypeProp.getPropertyValueAsString(), listOfFileTypes); assertFalse(fileTypes.isEmpty()); FileTypeObject type = fileTypes.get(0); assertEquals(FileType.ARRAYS, type.getFileType()); } - private DatasetProperty getPropByName(String name, List props ) { + private DatasetProperty getPropByName(String name, List props) { return props.stream().filter(p -> p.getPropertyName().equals(name)).findFirst().orElse(null); } @Test void testDatasetUpdateNullValues() { - String json = """ + String json = + """ { "not_a_name": "Test Dataset Update", "not_a_dac_id": 1, @@ -83,5 +87,4 @@ void testDatasetUpdateNullValues() { assertNull(update.getDacId()); assertNull(update.getDatasetProperties()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/FileStorageObjectTest.java b/src/test/java/org/broadinstitute/consent/http/models/FileStorageObjectTest.java index 226fb3e728..2f14c2e22c 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/FileStorageObjectTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/FileStorageObjectTest.java @@ -28,25 +28,22 @@ void testFileStorageObjectGsonSerialization() { fso.setBlobId(BlobId.of("sensitive", "information")); // should not be serialized fso.setCreateDate(Instant.now()); fso.setCategory(FileCategory.IRB_COLLABORATION_LETTER); - fso.setUploadedFile(new ByteArrayInputStream(new byte[]{})); // should not be serialized + fso.setUploadedFile(new ByteArrayInputStream(new byte[] {})); // should not be serialized Gson gson = GsonUtil.buildGson(); JsonObject fsoJsonObject = gson.fromJson(gson.toJson(fso), JsonObject.class); assertEquals(3, fsoJsonObject.size()); assertTrue(fsoJsonObject.has("createDate")); - assertEquals(fso.getCreateDate().toEpochMilli(), - fsoJsonObject.get("createDate").getAsLong()); + assertEquals(fso.getCreateDate().toEpochMilli(), fsoJsonObject.get("createDate").getAsLong()); assertTrue(fsoJsonObject.has("fileName")); assertEquals(fso.getFileName(), fsoJsonObject.get("fileName").getAsString()); assertTrue(fsoJsonObject.has("category")); - assertEquals(fso.getCategory().getValue(), - fsoJsonObject.get("category").getAsString()); + assertEquals(fso.getCategory().getValue(), fsoJsonObject.get("category").getAsString()); // should not have these fields ever assertFalse(fsoJsonObject.has("blobId")); assertFalse(fsoJsonObject.has("uploadedFile")); - } @Test diff --git a/src/test/java/org/broadinstitute/consent/http/models/InstitutionDomainMapTest.java b/src/test/java/org/broadinstitute/consent/http/models/InstitutionDomainMapTest.java index b7a2ca5979..b832c579b8 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/InstitutionDomainMapTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/InstitutionDomainMapTest.java @@ -19,10 +19,10 @@ void testInstitutionDomainMapGetAndSet() { assertNull(map.getInstitutionDomainMap()); // set a test map - Map> testMap = Map.of( - "Broad Institute", Set.of("broadinstitute.org", "broad.mit.edu"), - "Harvard", Set.of("harvard.edu", "hms.harvard.edu") - ); + Map> testMap = + Map.of( + "Broad Institute", Set.of("broadinstitute.org", "broad.mit.edu"), + "Harvard", Set.of("harvard.edu", "hms.harvard.edu")); map.setInstitutionDomainMap(testMap); assertEquals(testMap, map.getInstitutionDomainMap()); @@ -35,7 +35,8 @@ void testInstitutionDomainMapSerDeser() { Gson gson = new Gson(); // json string representation - String domainMapJson = """ + String domainMapJson = + """ { "institutionDomainMap": { "Broad Institute": ["broadinstitute.org", "broad.mit.edu"], @@ -43,15 +44,14 @@ void testInstitutionDomainMapSerDeser() { } } """; - InstitutionDomainMap map1 = gson.fromJson(domainMapJson, - InstitutionDomainMap.class); + InstitutionDomainMap map1 = gson.fromJson(domainMapJson, InstitutionDomainMap.class); // object representation InstitutionDomainMap map2 = new InstitutionDomainMap(); - Map> domainMap = Map.of( - "Broad Institute", Set.of("broadinstitute.org", "broad.mit.edu"), - "Harvard", Set.of("harvard.edu", "hms.harvard.edu") - ); + Map> domainMap = + Map.of( + "Broad Institute", Set.of("broadinstitute.org", "broad.mit.edu"), + "Harvard", Set.of("harvard.edu", "hms.harvard.edu")); map2.setInstitutionDomainMap(domainMap); String json = gson.toJson(map2); @@ -65,10 +65,10 @@ void testInstitutionDomainMapSerDeser() { @Test void testGetDomainsForInstitution() { InstitutionDomainMap map = new InstitutionDomainMap(); - Map> testMap = Map.of( - "Broad Institute", Set.of("broadinstitute.org", "broad.mit.edu"), - "Harvard", Set.of("harvard.edu", "hms.harvard.edu") - ); + Map> testMap = + Map.of( + "Broad Institute", Set.of("broadinstitute.org", "broad.mit.edu"), + "Harvard", Set.of("harvard.edu", "hms.harvard.edu")); map.setInstitutionDomainMap(testMap); diff --git a/src/test/java/org/broadinstitute/consent/http/models/UserCheckRoleInDacTest.java b/src/test/java/org/broadinstitute/consent/http/models/UserCheckRoleInDacTest.java index c5c81d36c8..9883d19bb5 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/UserCheckRoleInDacTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/UserCheckRoleInDacTest.java @@ -53,5 +53,4 @@ void testVerifyDACRole_NullDacId() { assertFalse(isUserChair); assertTrue(isUserAdmin); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/UserTest.java b/src/test/java/org/broadinstitute/consent/http/models/UserTest.java index bd612ae2cb..36f93b4cfa 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/UserTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/UserTest.java @@ -34,7 +34,10 @@ void testHasRoleEmptyUserNoRoles(UserRoles roleToTest) { @ParameterizedTest @EnumSource(UserRoles.class) void testHasUserRole(UserRoles roleToTest) { - Set otherRoles = EnumSet.allOf(UserRoles.class).stream().filter(u -> u != roleToTest).collect(Collectors.toSet()); + Set otherRoles = + EnumSet.allOf(UserRoles.class).stream() + .filter(u -> u != roleToTest) + .collect(Collectors.toSet()); User user = new User(); user.addRole(new UserRole(roleToTest.getRoleId(), roleToTest.getRoleName())); assertTrue(user.hasUserRole(roleToTest)); @@ -66,7 +69,8 @@ void testHasAnyRoleEmptyUserNoRoles(UserRoles roleToTest) { void testHasAnyRole() { User user = new User(); user.addRole(new UserRole(UserRoles.ADMIN.getRoleId(), UserRoles.ADMIN.getRoleName())); - user.addRole(new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName())); + user.addRole( + new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName())); // User has ADMIN and RESEARCHER roles, test cases where at least one matches assertTrue(user.hasAnyUserRole(List.of(UserRoles.ADMIN, UserRoles.RESEARCHER))); assertTrue(user.hasAnyUserRole(List.of(UserRoles.ADMIN, UserRoles.CHAIRPERSON))); diff --git a/src/test/java/org/broadinstitute/consent/http/models/UserUpdateFieldsTest.java b/src/test/java/org/broadinstitute/consent/http/models/UserUpdateFieldsTest.java index 8b19f2153b..3533a12a21 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/UserUpdateFieldsTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/UserUpdateFieldsTest.java @@ -15,10 +15,12 @@ @ExtendWith(MockitoExtension.class) class UserUpdateFieldsTest { - private static final List ALL_ROLE_IDS = Stream.of(UserRoles.values()) - .map(UserRoles::getRoleId).collect(Collectors.toList()); - private static final List NON_IGNORABLE_ROLES = ALL_ROLE_IDS.stream() - .filter(id -> !UserUpdateFields.IGNORE_ROLE_IDS.contains(id)).collect(Collectors.toList()); + private static final List ALL_ROLE_IDS = + Stream.of(UserRoles.values()).map(UserRoles::getRoleId).collect(Collectors.toList()); + private static final List NON_IGNORABLE_ROLES = + ALL_ROLE_IDS.stream() + .filter(id -> !UserUpdateFields.IGNORE_ROLE_IDS.contains(id)) + .collect(Collectors.toList()); @Test void testGetRoleIdsToAdd_Case_1() { @@ -67,9 +69,10 @@ void testGetRoleIdsToRemove_Case_2() { List roleIdsToRemove = fields.getRoleIdsToRemove(ALL_ROLE_IDS); assertFalse(roleIdsToRemove.isEmpty()); // We can never remove the ignorable roles, so they should not be in the list - roleIdsToRemove.forEach(id -> { - assertFalse(UserUpdateFields.IGNORE_ROLE_IDS.contains(id)); - }); + roleIdsToRemove.forEach( + id -> { + assertFalse(UserUpdateFields.IGNORE_ROLE_IDS.contains(id)); + }); // We can also never remove the Researcher role from a user assertFalse(roleIdsToRemove.contains(UserRoles.RESEARCHER.getRoleId())); } @@ -84,5 +87,4 @@ void testGetRoleIdsToRemove_Case_3() { List roleIdsToRemove = fields.getRoleIdsToRemove(ALL_ROLE_IDS); assertTrue(roleIdsToRemove.isEmpty()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidatorTest.java b/src/test/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidatorTest.java index 882d0f0a6d..889cecb248 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidatorTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/dataset_registration_v1/DatasetRegistrationSchemaV1UpdateValidatorTest.java @@ -28,8 +28,7 @@ @ExtendWith(MockitoExtension.class) class DatasetRegistrationSchemaV1UpdateValidatorTest { - @Mock - private DatasetService datasetService; + @Mock private DatasetService datasetService; private DatasetRegistrationSchemaV1UpdateValidator validator; @BeforeEach @@ -39,7 +38,8 @@ void setUp() { @Test void testValidation_knownFieldsExcluded() { - String json = """ + String json = + """ { "studyId": 6077, "studyName": "All of Us (Controlled+ Tier)", @@ -218,9 +218,11 @@ void testValidation_invalid_study_name_change() { DatasetRegistrationSchemaV1 registration = createMockRegistration(study); registration.setStudyName(existingStudyName); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -229,9 +231,11 @@ void testValidation_empty_consent_groups() { DatasetRegistrationSchemaV1 registration = createMockRegistration(study); registration.setConsentGroups(List.of()); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -241,18 +245,23 @@ void testValidation_non_study_dataset() { // mock data is limited to 10->100 registration.getConsentGroups().get(0).setDatasetId(10000); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test void testValidation_consent_group_name_change_allowed() { Study study = createMockStudy(); DatasetRegistrationSchemaV1 registration = createMockRegistration(study); - study.getDatasets().forEach(d -> { - d.setName(""); - }); + study + .getDatasets() + .forEach( + d -> { + d.setName(""); + }); boolean valid = validator.validate(study, registration); assertTrue(valid); @@ -262,26 +271,36 @@ void testValidation_consent_group_name_change_allowed() { void testValidation_consent_group_name_change_not_allowed() { Study study = createMockStudy(); DatasetRegistrationSchemaV1 registration = createMockRegistration(study); - study.getDatasets().forEach(d -> { - d.setName("Existing Name"); - }); - - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + study + .getDatasets() + .forEach( + d -> { + d.setName("Existing Name"); + }); + + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test void testValidation_consent_group_data_location_required() { Study study = createMockStudy(); DatasetRegistrationSchemaV1 registration = createMockRegistration(study); - registration.getConsentGroups().forEach(cg -> { - cg.setDataLocation(null); - }); - - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + registration + .getConsentGroups() + .forEach( + cg -> { + cg.setDataLocation(null); + }); + + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -298,9 +317,11 @@ void testValidation_invalid_delete_consent_groups() { datasetIds.add(dataset.getDatasetId()); study.addDatasetIds(new HashSet<>(datasetIds)); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -309,9 +330,11 @@ void testValidation_study_description() { DatasetRegistrationSchemaV1 registration = createMockRegistration(study); registration.setStudyDescription(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -320,9 +343,11 @@ void testValidation_data_types() { DatasetRegistrationSchemaV1 registration = createMockRegistration(study); registration.setDataTypes(List.of()); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -331,9 +356,11 @@ void testValidation_public_visibility() { DatasetRegistrationSchemaV1 registration = createMockRegistration(study); registration.setPublicVisibility(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -342,9 +369,11 @@ void testValidation_nih_anvil_use() { DatasetRegistrationSchemaV1 registration = createMockRegistration(study); registration.setNihAnvilUse(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -354,9 +383,11 @@ void testValidation_dbgap_phsid() { registration.setNihAnvilUse(NihAnvilUse.I_AM_NHGRI_FUNDED_AND_I_HAVE_A_DB_GA_P_PHS_ID_ALREADY); registration.setDbGaPPhsID(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -367,9 +398,11 @@ void testValidation_dbgap_pi_institution() { registration.setDbGaPPhsID(RandomStringUtils.randomAlphabetic(10)); registration.setPiInstitution(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -381,9 +414,11 @@ void testValidation_nih_grant_contract_number() { registration.setPiInstitution(RandomUtils.nextInt(10, 100)); registration.setNihGrantContractNumber(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -394,9 +429,11 @@ void testValidation_pi_institution() { NihAnvilUse.I_AM_NOT_NHGRI_FUNDED_BUT_I_AM_SEEKING_TO_SUBMIT_DATA_TO_AN_VIL); registration.setPiInstitution(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -408,9 +445,11 @@ void testValidation_pi_institution_nih_grant_contract_number() { registration.setPiInstitution(RandomUtils.nextInt(10, 100)); registration.setNihGrantContractNumber(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } @Test @@ -419,9 +458,11 @@ void testValidation_pi_name() { DatasetRegistrationSchemaV1 registration = createMockRegistration(study); registration.setPiName(null); - assertThrows(BadRequestException.class, () -> { - validator.validate(study, registration); - }); + assertThrows( + BadRequestException.class, + () -> { + validator.validate(study, registration); + }); } private Study createMockStudy() { @@ -449,17 +490,20 @@ private DatasetRegistrationSchemaV1 createMockRegistration(Study study) { registration.setPhenotypeIndication(RandomStringUtils.randomAlphabetic(10)); registration.setPiName(RandomStringUtils.randomAlphabetic(10)); registration.setDataCustodianEmail(List.of(RandomStringUtils.randomAlphabetic(10))); - List cgs = study.getDatasets().stream().map(d -> { - ConsentGroup cg = new ConsentGroup(); - cg.setDataLocation(DataLocation.NOT_DETERMINED); - cg.setNumberOfParticipants(RandomUtils.nextInt(10, 100)); - cg.setConsentGroupName(RandomStringUtils.randomAlphabetic(10)); - cg.setDatasetId(d.getDatasetId()); - cg.setDataAccessCommitteeId(d.getDacId()); - return cg; - }).toList(); + List cgs = + study.getDatasets().stream() + .map( + d -> { + ConsentGroup cg = new ConsentGroup(); + cg.setDataLocation(DataLocation.NOT_DETERMINED); + cg.setNumberOfParticipants(RandomUtils.nextInt(10, 100)); + cg.setConsentGroupName(RandomStringUtils.randomAlphabetic(10)); + cg.setDatasetId(d.getDatasetId()); + cg.setDataAccessCommitteeId(d.getDacId()); + return cg; + }) + .toList(); registration.setConsentGroups(cgs); return registration; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/models/support/DuosTicketTest.java b/src/test/java/org/broadinstitute/consent/http/models/support/DuosTicketTest.java index 9cee3f9aed..8d64e42049 100644 --- a/src/test/java/org/broadinstitute/consent/http/models/support/DuosTicketTest.java +++ b/src/test/java/org/broadinstitute/consent/http/models/support/DuosTicketTest.java @@ -10,18 +10,19 @@ class DuosTicketTest { @Test void toStringSerialization() { - TicketFields ticketFields = new TicketFields( - "Test User", - SupportRequestType.QUESTION, - "test.user@example.com", - "Test Subject", - "Test Description", - "https://example.com", - List.of("token1", "token2")); + TicketFields ticketFields = + new TicketFields( + "Test User", + SupportRequestType.QUESTION, + "test.user@example.com", + "Test Subject", + "Test Description", + "https://example.com", + List.of("token1", "token2")); DuosTicket ticket = TicketFactory.createTicket(ticketFields); - assertEquals(""" + assertEquals( + """ {"request":{"subject":"Test Subject","requester":{"name":"Test User","email":"test.user@example.com"},"comment":{"type":"Comment","body":"Test Description\\n\\n------------------\\nSubmitted from: https://example.com","uploads":["token1","token2"]},"custom_fields":[{"id":360012744452,"value":"QUESTION"},{"id":360007369412,"value":"Test Description"},{"id":360012744292,"value":"Test User"},{"id":360012782111,"value":"test.user@example.com"},{"id":360018545031,"value":"test.user@example.com"}],"has_incidents":false,"ticket_form_id":360000669472}}""", ticket.toString()); - } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java index eb156f8b07..6098f710d2 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DACAutomationRuleResourceTest.java @@ -26,15 +26,11 @@ @ExtendWith(MockitoExtension.class) class DACAutomationRuleResourceTest extends AbstractTestHelper { - @Mock - private DACAutomationRuleService ruleService; - @Mock - private DacService dacService; - @Mock - private UserService userService; + @Mock private DACAutomationRuleService ruleService; + @Mock private DacService dacService; + @Mock private UserService userService; - @Mock - private AuthUser authUser; + @Mock private AuthUser authUser; private DACAutomationRuleResource resource; @@ -54,8 +50,8 @@ void testGetAllRules() { @Test void testGetAvailableRulesAsAdmin() { - when(userService.findUserByEmail(authUser.getEmail())).thenReturn( - createUserWithRole(UserRoles.Admin())); + when(userService.findUserByEmail(authUser.getEmail())) + .thenReturn(createUserWithRole(UserRoles.Admin())); when(dacService.findById(1)).thenReturn(new Dac()); try (var response = resource.getAvailableRules(authUser, 1)) { @@ -103,10 +99,14 @@ void testToggleRuleAsChair() { User chairperson = createUserWithRole(role); when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chairperson); when(dacService.findById(1)).thenReturn(new Dac()); - when(ruleService.toggleRule(1, 1, chairperson)).thenReturn( - new AutomationRuleToggleResponse(1, true, Instant.now().toEpochMilli(), - chairperson.getDisplayName(), - chairperson.getEmail())); + when(ruleService.toggleRule(1, 1, chairperson)) + .thenReturn( + new AutomationRuleToggleResponse( + 1, + true, + Instant.now().toEpochMilli(), + chairperson.getDisplayName(), + chairperson.getEmail())); try (var response = resource.toggleRule(authUser, 1, 1)) { Assertions.assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -125,7 +125,6 @@ void testToggleRuleAsChairForbidden() { } } - private User createUserWithRole(UserRole role) { User user = new User(); user.setUserId(randomInt(1, 100)); @@ -134,5 +133,4 @@ private User createUserWithRole(UserRole role) { user.addRole(role); return user; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DACUserResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DACUserResourceTest.java index c1bd8b8ba7..f90db7cc75 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DACUserResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DACUserResourceTest.java @@ -15,10 +15,12 @@ class DACUserResourceTest { @Test void testConvertJsonToDACUserDateIgnoredCase() { - String jsonRole = "[{\"roleId\": 1, \"name\":\"name\", \"what\": \"Huh?\", \"rationale\": \"rationale\", \"status\": \"pending\"}]"; + String jsonRole = + "[{\"roleId\": 1, \"name\":\"name\", \"what\": \"Huh?\", \"rationale\": \"rationale\", \"status\": \"pending\"}]"; String json = "{\"userId\": 1, \"email\":\"email\", \"what\": \"Huh?\", \"createDate\": \"Oct 28, 2020\", \"emailPreference\": false, \"roles\": " - + jsonRole + "}"; + + jsonRole + + "}"; User user = new User(json); assertNotNull(user); assertNull(user.getCreateDate()); @@ -31,10 +33,12 @@ void testConvertJsonToDACUserDateIgnoredCase() { @Test void testConvertJsonToDACUserNoCreateDate() { - String jsonRole = "[{\"roleId\": 1, \"name\":\"name\", \"what\": \"Huh?\", \"rationale\": \"rationale\", \"status\": \"pending\"}]"; + String jsonRole = + "[{\"roleId\": 1, \"name\":\"name\", \"what\": \"Huh?\", \"rationale\": \"rationale\", \"status\": \"pending\"}]"; String json = "{\"userId\": 1, \"email\":\"email\", \"what\": \"Huh?\", \"emailPreference\": false, \"roles\": " - + jsonRole + "}"; + + jsonRole + + "}"; User user = new User(json); assertNotNull(user); assertNull(user.getCreateDate()); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DaaResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DaaResourceTest.java index 2644c23438..7b8fe96b17 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DaaResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DaaResourceTest.java @@ -45,14 +45,10 @@ @ExtendWith(MockitoExtension.class) class DaaResourceTest extends AbstractTestHelper { - @Mock - private DaaService daaService; - @Mock - private DacService dacService; - @Mock - private UserService userService; - @Mock - private LibraryCardService libraryCardService; + @Mock private DaaService daaService; + @Mock private DacService dacService; + @Mock private UserService userService; + @Mock private LibraryCardService libraryCardService; private final AuthUser authUser = new AuthUser("test@test.com"); private final DuosUser duosUser = new DuosUser(authUser, new User()); @@ -78,7 +74,9 @@ void testCreateDaaForDac_AdminCase() { when(userService.findUserByEmail(any())).thenReturn(admin); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createDaaForDac(info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); + Response response = + resource.createDaaForDac( + info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); assertEquals(HttpStatus.SC_CREATED, response.getStatus()); } @@ -96,10 +94,13 @@ void testCreateDaaForDac_ChairCase() { when(dacService.findById(any())).thenReturn(dac); when(userService.findUserByEmail(any())).thenReturn(admin); - when(daaService.createDaaWithFso(any(), any(), any(), any())).thenReturn(new DataAccessAgreement()); + when(daaService.createDaaWithFso(any(), any(), any(), any())) + .thenReturn(new DataAccessAgreement()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createDaaForDac(info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); + Response response = + resource.createDaaForDac( + info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); assertEquals(HttpStatus.SC_CREATED, response.getStatus()); } @@ -116,7 +117,9 @@ void testCreateDaaForDac_InvalidChairCase() { when(userService.findUserByEmail(any())).thenReturn(admin); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createDaaForDac(info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); + Response response = + resource.createDaaForDac( + info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatus()); } @@ -130,10 +133,13 @@ void testCreateDaaForDac_InvalidFile() { FormDataContentDisposition fileDetail = mock(FormDataContentDisposition.class); when(userService.findUserByEmail(any())).thenReturn(admin); - when(daaService.createDaaWithFso(any(), any(), any(), any())).thenThrow(new IllegalArgumentException()); + when(daaService.createDaaWithFso(any(), any(), any(), any())) + .thenThrow(new IllegalArgumentException()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createDaaForDac(info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); + Response response = + resource.createDaaForDac( + info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatus()); } @@ -147,10 +153,13 @@ void testCreateDaaForDac_UserWithoutInstitution() { FormDataContentDisposition fileDetail = mock(FormDataContentDisposition.class); when(userService.findUserByEmail(any())).thenReturn(admin); - when(daaService.createDaaWithFso(any(), any(), any(), any())).thenThrow(new IllegalArgumentException()); + when(daaService.createDaaWithFso(any(), any(), any(), any())) + .thenThrow(new IllegalArgumentException()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createDaaForDac(info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); + Response response = + resource.createDaaForDac( + info, authUser, dac.getDacId(), IOUtils.toInputStream("test", "UTF-8"), fileDetail); assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatus()); } @@ -161,7 +170,8 @@ void testFindAllNoDaas() { resource = new DaaResource(daaService, dacService, userService, libraryCardService); Response response = resource.findAll(duosUser); assert response.getStatus() == HttpStatus.SC_OK; - JsonArray daas = GsonUtil.buildGson().fromJson((response.getEntity().toString()), JsonArray.class); + JsonArray daas = + GsonUtil.buildGson().fromJson((response.getEntity().toString()), JsonArray.class); assertEquals(0, daas.size()); } @@ -173,7 +183,8 @@ void testFindAll() { resource = new DaaResource(daaService, dacService, userService, libraryCardService); Response response = resource.findAll(duosUser); assert response.getStatus() == HttpStatus.SC_OK; - JsonArray daas = GsonUtil.buildGson().fromJson((response.getEntity().toString()), JsonArray.class); + JsonArray daas = + GsonUtil.buildGson().fromJson((response.getEntity().toString()), JsonArray.class); assertEquals(1, daas.size()); } @@ -186,12 +197,12 @@ void testFindAllMultipleDaas() { resource = new DaaResource(daaService, dacService, userService, libraryCardService); Response response = resource.findAll(duosUser); assert response.getStatus() == HttpStatus.SC_OK; - JsonArray daas = GsonUtil.buildGson() - .fromJson((response.getEntity().toString()), JsonArray.class); + JsonArray daas = + GsonUtil.buildGson().fromJson((response.getEntity().toString()), JsonArray.class); assertEquals(2, daas.size()); } - @Test + @Test void testFindDaaByDaaId() { int expectedDaaId = randomInt(10, 100); DataAccessAgreement expectedDaa = new DataAccessAgreement(); @@ -226,7 +237,8 @@ void testFindDaaFileByDaaId() throws IOException { expectedDaa.setFile(fso); String fileContent = RandomStringUtils.randomAlphanumeric(10); - when(daaService.findFileById(expectedDaaId)).thenReturn(new ByteArrayInputStream(fileContent.getBytes())); + when(daaService.findFileById(expectedDaaId)) + .thenReturn(new ByteArrayInputStream(fileContent.getBytes())); when(daaService.findById(expectedDaaId)).thenReturn(expectedDaa); resource = new DaaResource(daaService, dacService, userService, libraryCardService); @@ -274,7 +286,6 @@ void testCreateLibraryCardDaaRelation_AdminCase() { researcher.setResearcherRole(); researcher.setInstitutionId(1); - DataAccessAgreement daa = new DataAccessAgreement(); daa.setDaaId(1); LibraryCard lc = new LibraryCard(); @@ -285,7 +296,8 @@ void testCreateLibraryCardDaaRelation_AdminCase() { when(userService.findUserById(any())).thenReturn(researcher); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); + Response response = + resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); assertEquals(HttpStatus.SC_OK, response.getStatus()); } @@ -315,7 +327,8 @@ void testCreateLibraryCardDaaRelation_SigningOfficialCase() { when(userService.findUserById(any())).thenReturn(researcher); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); + Response response = + resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); assertEquals(HttpStatus.SC_OK, response.getStatus()); } @@ -339,8 +352,9 @@ void testCreateLibraryCardDaaRelation_InvalidInstitutionIdCase() { when(userService.findUserById(any())).thenReturn(researcher); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); - assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatus()); + Response response = + resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); + assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatus()); } @Test @@ -363,7 +377,8 @@ void testCreateLibraryCardDaaRelation_InvalidUserCase() { when(userService.findUserById(any())).thenReturn(researcher); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); + Response response = + resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatus()); } @@ -388,7 +403,7 @@ void testCreateLibraryCardDaaRelation_InvalidDaaIdCase() { when(userService.findUserById(any())).thenReturn(researcher); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), 4); + Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), 4); assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus()); } @@ -412,12 +427,12 @@ void testCreateLibraryCardDaaRelation_NoMatchingLibraryCardsCase() { lc.setId(1); researcher.setLibraryCard(lc); - when(userService.findUserByEmail(any())).thenReturn(admin); when(userService.findUserById(any())).thenReturn(researcher); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); + Response response = + resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); assertEquals(HttpStatus.SC_OK, response.getStatus()); } @@ -445,7 +460,8 @@ void testCreateLibraryCardDaaRelation_NoLibraryCardsCase() { when(libraryCardService.createLibraryCardForSigningOfficial(any(), any())).thenReturn(newLc); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); + Response response = + resource.createLibraryCardDaaRelation(info, authUser, daa.getDaaId(), admin.getUserId()); assertEquals(HttpStatus.SC_OK, response.getStatus()); } @@ -482,12 +498,13 @@ void testSendDaaRequestMessage() throws Exception { User user = new User(); LibraryCard lc = new LibraryCard(); user.setResearcherRole(); - user.setInstitutionId(randomInt(0,10)); + user.setInstitutionId(randomInt(0, 10)); user.setLibraryCard(lc); doNothing().when(daaService).sendDaaRequestEmails(any(), any()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendDaaRequestMessage(new DuosUser(authUser, user), randomInt(10, 100)); + Response response = + resource.sendDaaRequestMessage(new DuosUser(authUser, user), randomInt(10, 100)); assertEquals(HttpStatus.SC_OK, response.getStatus()); } @@ -496,12 +513,13 @@ void testSendDaaRequestMessageDaaNotFound() throws Exception { User user = new User(); LibraryCard lc = new LibraryCard(); user.setResearcherRole(); - user.setInstitutionId(randomInt(0,10)); + user.setInstitutionId(randomInt(0, 10)); user.setLibraryCard(lc); doThrow(new NotFoundException()).when(daaService).sendDaaRequestEmails(any(), any()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendDaaRequestMessage(new DuosUser(authUser, user), randomInt(10, 100)); + Response response = + resource.sendDaaRequestMessage(new DuosUser(authUser, user), randomInt(10, 100)); assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus()); } @@ -510,12 +528,13 @@ void testSendDaaRequestMessageEmailError() throws Exception { User user = new User(); LibraryCard lc = new LibraryCard(); user.setResearcherRole(); - user.setInstitutionId(randomInt(0,10)); + user.setInstitutionId(randomInt(0, 10)); user.setLibraryCard(lc); doThrow(new Exception()).when(daaService).sendDaaRequestEmails(any(), any()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendDaaRequestMessage(new DuosUser(authUser, user), randomInt(10, 100)); + Response response = + resource.sendDaaRequestMessage(new DuosUser(authUser, user), randomInt(10, 100)); assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus()); } @@ -530,13 +549,13 @@ void testSendDaaRequestMessageAssociationAlreadyExists() { resource = new DaaResource(daaService, dacService, userService, libraryCardService); Response response = resource.sendDaaRequestMessage(new DuosUser(authUser, user), daaId); - assertEquals( HttpStatus.SC_BAD_REQUEST, response.getStatus()); + assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatus()); } @Test void testSendNewDAAMessage() throws Exception { User user = new User(); - int dacId = randomInt(10,20); + int dacId = randomInt(10, 20); Dac dac = new Dac(); dac.setDacId(dacId); dac.setName(randomAlphabetic(10)); @@ -546,39 +565,42 @@ void testSendNewDAAMessage() throws Exception { doNothing().when(daaService).sendNewDaaEmails(any(), any(), any(), any()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); + Response response = + resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); assertEquals(HttpStatus.SC_OK, response.getStatus()); } @Test void testSendNewDAAMessageUserNotFound() { User user = new User(); - int dacId = randomInt(10,20); + int dacId = randomInt(10, 20); user.setChairpersonRoleWithDAC(dacId); when(userService.findUserByEmail(any())).thenThrow(new NotFoundException()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); + Response response = + resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus()); } @Test void testSendNewDAAMessageDacNotFound() { User user = new User(); - int dacId = randomInt(10,20); + int dacId = randomInt(10, 20); user.setChairpersonRoleWithDAC(dacId); when(userService.findUserByEmail(any())).thenReturn(user); when(dacService.findById(dacId)).thenThrow(new NotFoundException()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); + Response response = + resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus()); } @Test void testSendNewDAAMessageDaaNotFound() throws Exception { User user = new User(); - int dacId = randomInt(10,20); + int dacId = randomInt(10, 20); Dac dac = new Dac(); dac.setDacId(dacId); dac.setName(randomAlphabetic(10)); @@ -588,14 +610,15 @@ void testSendNewDAAMessageDaaNotFound() throws Exception { doThrow(new NotFoundException()).when(daaService).sendNewDaaEmails(any(), any(), any(), any()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); + Response response = + resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus()); } @Test void testSendNewDAAMessageEmailError() throws Exception { User user = new User(); - int dacId = randomInt(10,20); + int dacId = randomInt(10, 20); Dac dac = new Dac(); dac.setDacId(dacId); dac.setName(randomAlphabetic(10)); @@ -605,7 +628,8 @@ void testSendNewDAAMessageEmailError() throws Exception { doThrow(new Exception()).when(daaService).sendNewDaaEmails(any(), any(), any(), any()); resource = new DaaResource(daaService, dacService, userService, libraryCardService); - Response response = resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); + Response response = + resource.sendNewDaaMessage(authUser, dacId, randomInt(10, 100), randomAlphabetic(10)); assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatus()); } @@ -626,11 +650,11 @@ void testBulkAddUsersToDaa() { authedUser.setAdminRole(); authedUser.setInstitutionId(institutionId); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -652,11 +676,11 @@ void testBulkAddUsersWithAdminAndSO() { authedUser.setRoles(List.of(UserRoles.Admin(), UserRoles.SigningOfficial())); authedUser.setInstitutionId(5); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -676,11 +700,11 @@ void testBulkAddUsersToDaaForbidden() { authedUser.setSigningOfficialRole(); authedUser.setInstitutionId(4); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -700,11 +724,11 @@ void testBulkAddUsersToDaaDaaNotFound() { authedUser.setSigningOfficialRole(); authedUser.setInstitutionId(institutionId); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -725,11 +749,11 @@ void testBulkRemoveUsersFromDaa() { authedUser.setAdminRole(); authedUser.setInstitutionId(institutionId); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -751,11 +775,11 @@ void testBulkRemoveUsersWithAdminAndSO() { authedUser.setRoles(List.of(UserRoles.Admin(), UserRoles.SigningOfficial())); authedUser.setInstitutionId(5); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -777,11 +801,11 @@ void testBulkRemoveUsersFromDaaForbidden() { authedUser.setSigningOfficialRole(); authedUser.setInstitutionId(4); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -801,11 +825,11 @@ void testBulkRemoveUsersFromDaaDaaNotFound() { authedUser.setSigningOfficialRole(); authedUser.setInstitutionId(institutionId); - List users = List.of( - researcherWithInstitution(1, institutionId), - researcherWithInstitution(2, institutionId), - researcherWithInstitution(3, institutionId) - ); + List users = + List.of( + researcherWithInstitution(1, institutionId), + researcherWithInstitution(2, institutionId), + researcherWithInstitution(3, institutionId)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUsersInJsonArray(any(), any())).thenReturn(users); @@ -833,11 +857,7 @@ void testBulkAddDAAsToUserAsSigningOfficial() { authedUser.setInstitutionId(institutionId); User researcher = researcherWithInstitution(userId, institutionId); - List agreements = List.of( - createDAA(1), - createDAA(2), - createDAA(3) - ); + List agreements = List.of(createDAA(1), createDAA(2), createDAA(3)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUserById(userId)).thenReturn(researcher); @@ -860,11 +880,7 @@ void testBulkAddDAAsToUserAsAdmin() { authedUser.setInstitutionId(institutionId); User researcher = researcherWithInstitution(userId, institutionId); - List agreements = List.of( - createDAA(1), - createDAA(2), - createDAA(3) - ); + List agreements = List.of(createDAA(1), createDAA(2), createDAA(3)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUserById(userId)).thenReturn(researcher); @@ -925,11 +941,7 @@ void testBulkRemoveDAAsFromUserAsSigningOfficial() { authedUser.setInstitutionId(institutionId); User researcher = researcherWithInstitution(userId, institutionId); - List agreements = List.of( - createDAA(1), - createDAA(2), - createDAA(3) - ); + List agreements = List.of(createDAA(1), createDAA(2), createDAA(3)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUserById(userId)).thenReturn(researcher); @@ -952,11 +964,7 @@ void testBulkRemoveDAAsFromUserAsAdmin() { authedUser.setInstitutionId(institutionId); User researcher = researcherWithInstitution(userId, institutionId); - List agreements = List.of( - createDAA(1), - createDAA(2), - createDAA(3) - ); + List agreements = List.of(createDAA(1), createDAA(2), createDAA(3)); when(userService.findUserByEmail(any())).thenReturn(authedUser); when(userService.findUserById(userId)).thenReturn(researcher); @@ -1054,7 +1062,7 @@ void testAddDacToDaaChairpersonNoMatchingDac() { dac.setDacId(randomInt(10, 100)); User chairperson = new User(); - chairperson.setChairpersonRoleWithDAC(randomInt(100,200)); + chairperson.setChairpersonRoleWithDAC(randomInt(100, 200)); when(userService.findUserByEmail(any())).thenReturn(chairperson); @@ -1214,7 +1222,7 @@ void testRemoveDacFromDaaChairpersonNoMatchingDac() { daa.addDac(dac); User chairperson = new User(); - chairperson.setChairpersonRoleWithDAC(randomInt(100,200)); + chairperson.setChairpersonRoleWithDAC(randomInt(100, 200)); when(userService.findUserByEmail(any())).thenReturn(chairperson); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java index 11862a0f8e..afe578557d 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DacResourceTest.java @@ -39,14 +39,11 @@ @ExtendWith(MockitoExtension.class) class DacResourceTest extends AbstractTestHelper { - @Mock - private DacService dacService; + @Mock private DacService dacService; - @Mock - private DatasetService datasetService; + @Mock private DatasetService datasetService; - @Mock - private UserService userService; + @Mock private UserService userService; private DacResource dacResource; @@ -72,10 +69,7 @@ void testFindAll_success_1() { @Test void testFindAll_success_2() { - Dac dac = new DacBuilder() - .setName("name") - .setDescription("description") - .build(); + Dac dac = new DacBuilder().setName("name").setDescription("description").build(); when(dacService.findDacsWithMembersOption(true)).thenReturn(Collections.singletonList(dac)); try (Response response = dacResource.findAll(authUser, Optional.of(true))) { @@ -121,7 +115,7 @@ void testFindDatasetsAssociatedWithDac_NoDac() { when(dacService.findById(1)).thenReturn(null); - try(Response response = dacResource.findAllDacDatasets(authUser, 1)) { + try (Response response = dacResource.findAllDacDatasets(authUser, 1)) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -165,13 +159,9 @@ void testFindDatasetsAssociatedWithDac_NotAuthorized() { } } - @Test void testCreateDac_success() { - Dac dac = new DacBuilder() - .setName("name") - .setDescription("description") - .build(); + Dac dac = new DacBuilder().setName("name").setDescription("description").build(); when(dacService.createDac(any(), any())).thenReturn(1); when(dacService.findById(1)).thenReturn(dac); @@ -182,11 +172,12 @@ void testCreateDac_success() { @Test void testCreateDacWithEmail_success() { - Dac dac = new DacBuilder() - .setName("name") - .setDescription("description") - .setEmail("test@email.com") - .build(); + Dac dac = + new DacBuilder() + .setName("name") + .setDescription("description") + .setEmail("test@email.com") + .build(); when(dacService.createDac(any(), any(), any())).thenReturn(1); when(dacService.findById(1)).thenReturn(dac); @@ -204,23 +195,17 @@ void testCreateDac_badRequest_1() { @Test void testCreateDac_badRequest_2() { - Dac dac = new DacBuilder() - .setName(null) - .setDescription("description") - .build(); + Dac dac = new DacBuilder().setName(null).setDescription("description").build(); - try(Response response = dacResource.createDac(authUser, gson.toJson(dac))) { + try (Response response = dacResource.createDac(authUser, gson.toJson(dac))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @Test void testCreateDac_badRequest_3() { - Dac dac = new DacBuilder() - .setName("name") - .setDescription(null) - .build(); - try(Response response = dacResource.createDac(authUser, gson.toJson(dac))) { + Dac dac = new DacBuilder().setName("name").setDescription(null).build(); + try (Response response = dacResource.createDac(authUser, gson.toJson(dac))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -230,12 +215,9 @@ void testUpdateDac_success() { User user = new User(); user.setAdminRole(); when(userService.findUserByEmail(anyString())).thenReturn(user); - Dac dac = new DacBuilder() - .setDacId(1) - .setName("name") - .setDescription("description") - .build(); - doNothing().when(dacService) + Dac dac = new DacBuilder().setDacId(1).setName("name").setDescription("description").build(); + doNothing() + .when(dacService) .updateDac(isA(String.class), isA(String.class), isA(Integer.class)); when(dacService.findById(1)).thenReturn(dac); @@ -249,13 +231,15 @@ void testUpdateDacWithEmail_success() { User user = new User(); user.setAdminRole(); when(userService.findUserByEmail(anyString())).thenReturn(user); - Dac dac = new DacBuilder() - .setDacId(1) - .setName("name") - .setEmail("test@email.com") - .setDescription("description") - .build(); - doNothing().when(dacService) + Dac dac = + new DacBuilder() + .setDacId(1) + .setName("name") + .setEmail("test@email.com") + .setDescription("description") + .build(); + doNothing() + .when(dacService) .updateDac(isA(String.class), isA(String.class), isA(String.class), isA(Integer.class)); when(dacService.findById(1)).thenReturn(dac); @@ -276,11 +260,7 @@ void testUpdateDac_badRequest_2() { User user = new User(); user.setAdminRole(); when(userService.findUserByEmail(anyString())).thenReturn(user); - Dac dac = new DacBuilder() - .setDacId(null) - .setName("name") - .setDescription("description") - .build(); + Dac dac = new DacBuilder().setDacId(null).setName("name").setDescription("description").build(); try (Response response = dacResource.updateDac(authUser, gson.toJson(dac))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -291,11 +271,7 @@ void testUpdateDac_badRequest_3() { User user = new User(); user.setAdminRole(); when(userService.findUserByEmail(anyString())).thenReturn(user); - Dac dac = new DacBuilder() - .setDacId(1) - .setName(null) - .setDescription("description") - .build(); + Dac dac = new DacBuilder().setDacId(1).setName(null).setDescription("description").build(); try (Response response = dacResource.updateDac(authUser, gson.toJson(dac))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -306,11 +282,7 @@ void testUpdateDac_badRequest_4() { User user = new User(); user.setAdminRole(); when(userService.findUserByEmail(anyString())).thenReturn(user); - Dac dac = new DacBuilder() - .setDacId(1) - .setName("name") - .setDescription(null) - .build(); + Dac dac = new DacBuilder().setDacId(1).setName("name").setDescription(null).build(); try (Response response = dacResource.updateDac(authUser, gson.toJson(dac))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -318,11 +290,7 @@ void testUpdateDac_badRequest_4() { @Test void testUpdateDac_notAuthorized() { - Dac dac = new DacBuilder() - .setDacId(1) - .setName("name") - .setDescription("description") - .build(); + Dac dac = new DacBuilder().setDacId(1).setName("name").setDescription("description").build(); User user = new User(); user.setChairpersonRoleWithDAC(dac.getDacId() + 1); when(userService.findUserByEmail(anyString())).thenReturn(user); @@ -334,12 +302,13 @@ void testUpdateDac_notAuthorized() { @Test void testFindById_success() { - Dac dac = new DacBuilder() - .setDacId(1) - .setName("name") - .setDescription("description") - .setAssociatedDaa(new DataAccessAgreement()) - .build(); + Dac dac = + new DacBuilder() + .setDacId(1) + .setName("name") + .setDescription("description") + .setAssociatedDaa(new DataAccessAgreement()) + .build(); when(dacService.findById(1)).thenReturn(dac); try (Response response = dacResource.findDacById(authUser, dac.getDacId())) { @@ -358,17 +327,12 @@ void testFindById_failure() { @Test void testDeleteDac_success() { - Dac dac = new DacBuilder() - .setDacId(1) - .setName("name") - .setDescription("description") - .build(); + Dac dac = new DacBuilder().setDacId(1).setName("name").setDescription("description").build(); when(dacService.findById(1)).thenReturn(dac); try (Response response = dacResource.deleteDac(authUser, dac.getDacId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } - } @Test @@ -389,8 +353,8 @@ void testAddDacMemberAsAdmin() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(admin); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.addDacMember(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.addDacMember(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -404,8 +368,8 @@ void testAddDacMemberAsChairSuccess() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chair); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.addDacMember(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.addDacMember(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -419,7 +383,8 @@ void testAddDacMemberAsChairFailure() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chair); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try(Response response = dacResource.addDacMember(authUser, dac.getDacId(), member.getUserId())) { + try (Response response = + dacResource.addDacMember(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } } @@ -433,8 +398,8 @@ void testRemoveDacMemberAsAdmin() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(admin); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.removeDacMember(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.removeDacMember(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -448,8 +413,8 @@ void testRemoveDacMemberAsChairSuccess() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chair); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.removeDacMember(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.removeDacMember(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -463,7 +428,8 @@ void testRemoveDacMemberAsChairFailure() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chair); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.removeDacMember(authUser, dac.getDacId(), member.getUserId())) { + try (Response response = + dacResource.removeDacMember(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } } @@ -477,8 +443,8 @@ void testAddDacChairAsAdmin() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(admin); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.addDacChair(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.addDacChair(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -492,8 +458,8 @@ void testAddDacChairAsChairSuccess() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chair); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.addDacChair(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.addDacChair(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -507,8 +473,8 @@ void testAddDacChairAsChairFailure() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chair); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.addDacChair(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.addDacChair(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } } @@ -522,8 +488,8 @@ void testRemoveDacChairAsAdmin() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(admin); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.removeDacChair(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.removeDacChair(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -537,8 +503,8 @@ void testRemoveDacChairAsChairSuccess() { when(userService.findUserByEmail(authUser.getEmail())).thenReturn(chair); when(dacService.findUserById(member.getUserId())).thenReturn(member); - try (Response response = dacResource.removeDacChair(authUser, dac.getDacId(), - member.getUserId())) { + try (Response response = + dacResource.removeDacChair(authUser, dac.getDacId(), member.getUserId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -664,11 +630,8 @@ private JsonArray getListFromEntityString(String str) { } private Dac buildDac(User chair) { - Dac dac = new DacBuilder() - .setDacId(nextInt()) - .setName("name") - .setDescription("description") - .build(); + Dac dac = + new DacBuilder().setDacId(nextInt()).setName("name").setDescription("description").build(); if (Objects.nonNull(chair)) { dac.setChairpersons(Collections.singletonList(chair)); } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DarCollectionResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DarCollectionResourceTest.java index 232744674e..a8e39d2b73 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DarCollectionResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DarCollectionResourceTest.java @@ -41,34 +41,33 @@ class DarCollectionResourceTest extends AbstractTestHelper { private final AuthUser authUser = new AuthUser("test@test.com"); private final List researcherRole = List.of(UserRoles.Researcher()); - private final User researcher = new User(1, authUser.getEmail(), "Display Name", new Date(), - researcherRole); + private final User researcher = + new User(1, authUser.getEmail(), "Display Name", new Date(), researcherRole); private final DuosUser duosResearcher = new DuosUser(authUser, researcher); private final List signingOfficialRole = List.of(UserRoles.SigningOfficial()); - private final User signingOfficial = new User(4, authUser.getEmail(), "Display Name", new Date(), - signingOfficialRole); + private final User signingOfficial = + new User(4, authUser.getEmail(), "Display Name", new Date(), signingOfficialRole); private final DuosUser duosSigningOfficial = new DuosUser(authUser, signingOfficial); private final List adminRole = List.of(UserRoles.Admin()); - private final User admin = new User(5, authUser.getEmail(), "Display Name", new Date(), - adminRole); + private final User admin = + new User(5, authUser.getEmail(), "Display Name", new Date(), adminRole); private final DuosUser duosAdmin = new DuosUser(authUser, admin); private final List chairpersonRole = List.of(UserRoles.Chairperson()); - private final User chairperson = new User (6, authUser.getEmail(), "Display Name", new Date(), - chairpersonRole); + private final User chairperson = + new User(6, authUser.getEmail(), "Display Name", new Date(), chairpersonRole); private final DuosUser duosChairperson = new DuosUser(authUser, chairperson); private final List memberRole = List.of(UserRoles.Member()); - private final User member = new User(7, authUser.getEmail(), "Display Name", new Date(), memberRole); + private final User member = + new User(7, authUser.getEmail(), "Display Name", new Date(), memberRole); private final DuosUser duosMember = new DuosUser(authUser, member); private DarCollectionResource resource; - @Mock - private DarCollectionService darCollectionService; - @Mock - private ContainerRequest request; + @Mock private DarCollectionService darCollectionService; + @Mock private ContainerRequest request; @BeforeEach void initResource() { @@ -99,7 +98,8 @@ void testGetCollectionByIdResearcher() { DarCollection collection = mockDarCollection(); collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())) + .thenReturn(collection); Response response = resource.getCollectionById(duosUser, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -110,7 +110,8 @@ void testGetCollectionByIdResearcherNotFound() { DarCollection collection = mockDarCollection(); collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId() + 1); - when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())) + .thenReturn(collection); Response response = resource.getCollectionById(duosResearcher, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -122,7 +123,8 @@ void testGetCollectionByIdAdmin() { collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(admin, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(admin, collection.getDarCollectionId())) + .thenReturn(collection); Response response = resource.getCollectionById(duosAdmin, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -136,9 +138,11 @@ void testGetCollectionByIdSO() { collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())) + .thenReturn(collection); - Response response = resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); + Response response = + resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -150,9 +154,11 @@ void testGetCollectionByIdSOWrongInstitution() { collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())) + .thenReturn(collection); - Response response = resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); + Response response = + resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -163,9 +169,11 @@ void testGetCollectionByIdNoInstitution() { collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())) + .thenReturn(collection); - Response response = resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); + Response response = + resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -176,9 +184,11 @@ void testGetCollectionByIdSONoInstitution() { collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(signingOfficial, collection.getDarCollectionId())) + .thenReturn(collection); - Response response = resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); + Response response = + resource.getCollectionById(duosSigningOfficial, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -194,10 +204,12 @@ void testGetCollectionByIdChair() { dataSet.setDatasetId(2); collection.addDataset(dataSet); - when(darCollectionService.getByCollectionId(chair, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(chair, collection.getDarCollectionId())) + .thenReturn(collection); when(darCollectionService.findDatasetIdsByDACUser(chair)).thenReturn(Arrays.asList(1, 2)); - Response response = resource.getCollectionById(new DuosUser(authUser, chair), collection.getDarCollectionId()); + Response response = + resource.getCollectionById(new DuosUser(authUser, chair), collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -211,7 +223,8 @@ void testGetCollectionByIdDacMember() { dataSet.setDatasetId(2); collection.addDataset(dataSet); - when(darCollectionService.getByCollectionId(member, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(member, collection.getDarCollectionId())) + .thenReturn(collection); when(darCollectionService.findDatasetIdsByDACUser(member)).thenReturn(Arrays.asList(1, 2)); Response response = resource.getCollectionById(duosMember, collection.getDarCollectionId()); @@ -230,10 +243,12 @@ void testGetCollectionByIdDacMemberNoDatasetIdMatch() { dataSet.setDatasetId(3); collection.addDataset(dataSet); - when(darCollectionService.getByCollectionId(chair, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(chair, collection.getDarCollectionId())) + .thenReturn(collection); when(darCollectionService.findDatasetIdsByDACUser(chair)).thenReturn(Arrays.asList(1, 2)); - Response response = resource.getCollectionById(new DuosUser(authUser, chair), collection.getDarCollectionId()); + Response response = + resource.getCollectionById(new DuosUser(authUser, chair), collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -241,8 +256,13 @@ void testGetCollectionByIdDacMemberNoDatasetIdMatch() { void testGetCollectionByIdMultipleRoles() { UserRole chairRole = UserRoles.Chairperson(); UserRole localResearcherRole = UserRoles.Researcher(); - User user = new User(1, authUser.getEmail(), "Display Name", new Date(), - List.of(chairRole, localResearcherRole)); + User user = + new User( + 1, + authUser.getEmail(), + "Display Name", + new Date(), + List.of(chairRole, localResearcherRole)); DarCollection collection = mockDarCollection(); collection.setCreateUser(user); collection.setCreateUserId(user.getUserId()); @@ -251,7 +271,8 @@ void testGetCollectionByIdMultipleRoles() { dataSet.setDatasetId(3); collection.addDataset(dataSet); - when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())) + .thenReturn(collection); when(darCollectionService.findDatasetIdsByDACUser(researcher)).thenReturn(Arrays.asList(1, 2)); Response response = resource.getCollectionById(duosResearcher, collection.getDarCollectionId()); @@ -264,9 +285,13 @@ void testGetCollectionWithAllElectionsByCollectionIdAdmin() { collection.setCreateUser(researcher); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getCollectionWithAllElectionsByCollectionId(admin, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getCollectionWithAllElectionsByCollectionId( + admin, collection.getDarCollectionId())) + .thenReturn(collection); - Response response = resource.getCollectionWithAllElectionsByCollectionId(duosAdmin, collection.getDarCollectionId()); + Response response = + resource.getCollectionWithAllElectionsByCollectionId( + duosAdmin, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -281,16 +306,21 @@ void testGetCollectionWithAllElectionsByCollectionIdDacMember() { collection.setDatasets(Set.of(dataset1)); when(darCollectionService.findDatasetIdsByDACUser(member)).thenReturn(userDatasetIds); - when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds(member, userDatasetIds, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds( + member, userDatasetIds, collection.getDarCollectionId())) + .thenReturn(collection); - Response response = resource.getCollectionWithAllElectionsByCollectionId(duosMember, collection.getDarCollectionId()); + Response response = + resource.getCollectionWithAllElectionsByCollectionId( + duosMember, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @Test void testGetCollectionWithAllElectionsById_CollectionNotFoundCollection() { when(darCollectionService.findDatasetIdsByDACUser(researcher)).thenReturn(List.of()); - when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds(researcher, List.of(), 1)) + when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds( + researcher, List.of(), 1)) .thenThrow(new NotFoundException("Collection not found")); Response response = resource.getCollectionWithAllElectionsByCollectionId(duosResearcher, 1); @@ -300,7 +330,8 @@ void testGetCollectionWithAllElectionsById_CollectionNotFoundCollection() { @Test void testGetCollectionWithAllElectionsByCollectionId_ServiceException() { when(darCollectionService.findDatasetIdsByDACUser(researcher)).thenReturn(List.of()); - when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds(researcher, List.of(), 1)) + when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds( + researcher, List.of(), 1)) .thenThrow(new RuntimeException("Service error")); Response response = resource.getCollectionWithAllElectionsByCollectionId(duosResearcher, 1); @@ -314,19 +345,21 @@ void testGetCollectionWithAllElectionsByCollectionId_UserNotAuthorized() { collection.setCreateUserId(researcher.getUserId()); when(darCollectionService.findDatasetIdsByDACUser(researcher)).thenReturn(List.of()); - when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds(researcher, List.of(), - collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getCollectionWithElectionsByCollectionIdAndDatasetIds( + researcher, List.of(), collection.getDarCollectionId())) + .thenReturn(collection); - Response response = resource.getCollectionWithAllElectionsByCollectionId(duosResearcher, - collection.getDarCollectionId()); + Response response = + resource.getCollectionWithAllElectionsByCollectionId( + duosResearcher, collection.getDarCollectionId()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @Test void testGetCollectionByReferenceId() { DarCollection collection = mockDarCollection(); - String referenceId = collection.getDars().values().stream().findFirst().orElseThrow() - .getReferenceId(); + String referenceId = + collection.getDars().values().stream().findFirst().orElseThrow().getReferenceId(); assertNotNull(referenceId); collection.setCreateUserId(researcher.getUserId()); when(darCollectionService.getByReferenceId(researcher, referenceId)).thenReturn(collection); @@ -338,8 +371,8 @@ void testGetCollectionByReferenceId() { @Test void testGetCollectionByReferenceIdNotFound() { DarCollection collection = mockDarCollection(); - String referenceId = collection.getDars().values().stream().findFirst().orElseThrow() - .getReferenceId(); + String referenceId = + collection.getDars().values().stream().findFirst().orElseThrow().getReferenceId(); assertNotNull(referenceId); collection.setCreateUserId(researcher.getUserId() + 1); when(darCollectionService.getByReferenceId(researcher, referenceId)).thenReturn(collection); @@ -352,9 +385,12 @@ void testGetCollectionByReferenceIdNotFound() { void testCancelDarCollection_NotFoundStatus() { DarCollection collection = mockDarCollection(); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())).thenReturn(null); + when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())) + .thenReturn(null); - try (var response = resource.cancelDarCollectionByCollectionId(duosResearcher, request, collection.getDarCollectionId(), null)) { + try (var response = + resource.cancelDarCollectionByCollectionId( + duosResearcher, request, collection.getDarCollectionId(), null)) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -365,10 +401,12 @@ void testCancelDarCollection_BadRequestStatus() { collection.setCreateUserId(researcher.getUserId()); int collectionId = collection.getDarCollectionId(); when(darCollectionService.getByCollectionId(researcher, collectionId)).thenReturn(collection); - when(darCollectionService.cancelDarCollectionByRole(researcher, collection, UserRoles.RESEARCHER)) + when(darCollectionService.cancelDarCollectionByRole( + researcher, collection, UserRoles.RESEARCHER)) .thenThrow(new BadRequestException()); - try (var response = resource.cancelDarCollectionByCollectionId(duosResearcher, request, collectionId, null)) { + try (var response = + resource.cancelDarCollectionByCollectionId(duosResearcher, request, collectionId, null)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -379,10 +417,12 @@ void testCancelDarCollection_InternalErrorStatus() { collection.setCreateUserId(researcher.getUserId()); int collectionId = collection.getDarCollectionId(); when(darCollectionService.getByCollectionId(researcher, collectionId)).thenReturn(collection); - when(darCollectionService.cancelDarCollectionByRole(researcher, collection, UserRoles.RESEARCHER)) + when(darCollectionService.cancelDarCollectionByRole( + researcher, collection, UserRoles.RESEARCHER)) .thenThrow(new InternalServerErrorException()); - try (var response = resource.cancelDarCollectionByCollectionId(duosResearcher, request, collectionId, null)) { + try (var response = + resource.cancelDarCollectionByCollectionId(duosResearcher, request, collectionId, null)) { assertEquals(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, response.getStatus()); } } @@ -396,7 +436,9 @@ void testCancelDarCollection_asAdmin() { when(darCollectionService.cancelDarCollectionByRole(admin, collection, UserRoles.ADMIN)) .thenReturn(collection); - try (var response = resource.cancelDarCollectionByCollectionId(duosAdmin, request, collectionId, Resource.ADMIN)) { + try (var response = + resource.cancelDarCollectionByCollectionId( + duosAdmin, request, collectionId, Resource.ADMIN)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -407,10 +449,13 @@ void testCancelDarCollection_asChair() { collection.setCreateUserId(chairperson.getUserId()); int collectionId = collection.getDarCollectionId(); when(darCollectionService.getByCollectionId(chairperson, collectionId)).thenReturn(collection); - when(darCollectionService.cancelDarCollectionByRole(chairperson, collection, UserRoles.CHAIRPERSON)) + when(darCollectionService.cancelDarCollectionByRole( + chairperson, collection, UserRoles.CHAIRPERSON)) .thenReturn(collection); - try (var response = resource.cancelDarCollectionByCollectionId(duosChairperson, request, collectionId, Resource.CHAIRPERSON)) { + try (var response = + resource.cancelDarCollectionByCollectionId( + duosChairperson, request, collectionId, Resource.CHAIRPERSON)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -419,9 +464,12 @@ void testCancelDarCollection_asChair() { void testCancelDarCollection_asChairAsAdmin() { DarCollection collection = mockDarCollection(); collection.setCreateUserId(chairperson.getUserId()); - when(darCollectionService.getByCollectionId(chairperson, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(chairperson, collection.getDarCollectionId())) + .thenReturn(collection); - try (var response = resource.cancelDarCollectionByCollectionId(duosChairperson, request, collection.getDarCollectionId(), Resource.ADMIN)) { + try (var response = + resource.cancelDarCollectionByCollectionId( + duosChairperson, request, collection.getDarCollectionId(), Resource.ADMIN)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -432,10 +480,13 @@ void testCancelDarCollection_asResearcher() { int collectionId = collection.getDarCollectionId(); collection.setCreateUserId(researcher.getUserId()); when(darCollectionService.getByCollectionId(researcher, collectionId)).thenReturn(collection); - when(darCollectionService.cancelDarCollectionByRole(researcher, collection, UserRoles.RESEARCHER)) + when(darCollectionService.cancelDarCollectionByRole( + researcher, collection, UserRoles.RESEARCHER)) .thenReturn(collection); - try (var response = resource.cancelDarCollectionByCollectionId(duosResearcher, request, collectionId, Resource.RESEARCHER)) { + try (var response = + resource.cancelDarCollectionByCollectionId( + duosResearcher, request, collectionId, Resource.RESEARCHER)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -444,14 +495,16 @@ void testCancelDarCollection_asResearcher() { void testCancelDarCollection_asResearcherAsAdmin() { DarCollection collection = mockDarCollection(); collection.setCreateUserId(researcher.getUserId()); - when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())) + .thenReturn(collection); - try (var response = resource.cancelDarCollectionByCollectionId(duosResearcher, request, collection.getDarCollectionId(), Resource.ADMIN)) { + try (var response = + resource.cancelDarCollectionByCollectionId( + duosResearcher, request, collection.getDarCollectionId(), Resource.ADMIN)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } - @Test void testResubmitDarCollection_CollectionNotFound() { when(darCollectionService.getByCollectionId(researcher, 1)).thenReturn(null); @@ -482,9 +535,11 @@ void testResubmitDarCollection_CollectionNotCanceled() { when(dar.getReferenceId()).thenReturn(referenceId); Map darMap = Map.of(dar.getReferenceId(), dar); when(collection.getDars()).thenReturn(darMap); - when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())) + .thenReturn(collection); - try (var response = resource.resubmitDarCollection(duosResearcher, collection.getDarCollectionId())) { + try (var response = + resource.resubmitDarCollection(duosResearcher, collection.getDarCollectionId())) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -501,9 +556,11 @@ void testResubmitDarCollection_Success() { when(dar.getReferenceId()).thenReturn(referenceId); Map darMap = Map.of(dar.getReferenceId(), dar); when(collection.getDars()).thenReturn(darMap); - when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionService.getByCollectionId(researcher, collection.getDarCollectionId())) + .thenReturn(collection); - try (var response = resource.resubmitDarCollection(duosResearcher, collection.getDarCollectionId())) { + try (var response = + resource.resubmitDarCollection(duosResearcher, collection.getDarCollectionId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -533,8 +590,8 @@ void getCollectionSummariesForUserByRole_Member() { when(darCollectionService.getSummariesForRole(member, UserRoles.MEMBER)) .thenReturn(List.of(mockSummary)); - Response response = resource.getCollectionSummariesForUserByRole(duosMember, - UserRoles.MEMBER.getRoleName()); + Response response = + resource.getCollectionSummariesForUserByRole(duosMember, UserRoles.MEMBER.getRoleName()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -544,8 +601,9 @@ void getCollectionSummariesForUserByRole_Chair() { when(darCollectionService.getSummariesForRole(chairperson, UserRoles.CHAIRPERSON)) .thenReturn(List.of(mockSummary)); - Response response = resource.getCollectionSummariesForUserByRole(duosChairperson, - UserRoles.CHAIRPERSON.getRoleName()); + Response response = + resource.getCollectionSummariesForUserByRole( + duosChairperson, UserRoles.CHAIRPERSON.getRoleName()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -555,8 +613,9 @@ void getCollectionSummariesForUserByRole_SO() { when(darCollectionService.getSummariesForRole(signingOfficial, UserRoles.SIGNINGOFFICIAL)) .thenReturn(List.of(mockSummary)); - Response response = resource.getCollectionSummariesForUserByRole(duosSigningOfficial, - UserRoles.SIGNINGOFFICIAL.getRoleName()); + Response response = + resource.getCollectionSummariesForUserByRole( + duosSigningOfficial, UserRoles.SIGNINGOFFICIAL.getRoleName()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -566,8 +625,9 @@ void getCollectionSummariesForUserByRole_Researcher() { when(darCollectionService.getSummariesForRole(researcher, UserRoles.RESEARCHER)) .thenReturn(List.of(mockSummary)); - Response response = resource.getCollectionSummariesForUserByRole(duosResearcher, - UserRoles.RESEARCHER.getRoleName()); + Response response = + resource.getCollectionSummariesForUserByRole( + duosResearcher, UserRoles.RESEARCHER.getRoleName()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -577,15 +637,16 @@ void getCollectionSummariesForUserByRole_Admin() { when(darCollectionService.getSummariesForRole(admin, UserRoles.ADMIN)) .thenReturn(List.of(mockSummary)); - Response response = resource.getCollectionSummariesForUserByRole(duosAdmin, - UserRoles.ADMIN.getRoleName()); + Response response = + resource.getCollectionSummariesForUserByRole(duosAdmin, UserRoles.ADMIN.getRoleName()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @Test void getCollectionSummariesForUserByRole_NoRoleFound() { - Response response = resource.getCollectionSummariesForUserByRole(duosResearcher, - UserRoles.SIGNINGOFFICIAL.getRoleName()); + Response response = + resource.getCollectionSummariesForUserByRole( + duosResearcher, UserRoles.SIGNINGOFFICIAL.getRoleName()); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -595,7 +656,6 @@ void getCollectionSummariesForUserByRole_InvalidRoleString() { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } - @Test void getCollectionSummaryForRoleById_Member() { DarCollectionSummary mockSummary = new DarCollectionSummary(); @@ -603,11 +663,13 @@ void getCollectionSummaryForRoleById_Member() { Integer collectionId = randomInt(1, 100); when(darCollectionService.findDatasetIdsByDACUser(member)).thenReturn(List.of(1, 2)); - when(darCollectionService.getSummaryForRoleByCollectionId(member, UserRoles.MEMBER, collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + member, UserRoles.MEMBER, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosMember, - UserRoles.MEMBER.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosMember, UserRoles.MEMBER.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -618,11 +680,13 @@ void getCollectionSummaryForRoleById_MemberNoDatasetsInCollection() { Integer collectionId = randomInt(1, 100); when(darCollectionService.findDatasetIdsByDACUser(member)).thenReturn(List.of(2)); - when(darCollectionService.getSummaryForRoleByCollectionId(member, UserRoles.MEMBER, collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + member, UserRoles.MEMBER, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosMember, - UserRoles.MEMBER.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosMember, UserRoles.MEMBER.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -633,11 +697,13 @@ void getCollectionSummaryForRoleById_Chair() { Integer collectionId = randomInt(1, 100); when(darCollectionService.findDatasetIdsByDACUser(chairperson)).thenReturn(List.of(1, 2)); - when(darCollectionService.getSummaryForRoleByCollectionId(chairperson, UserRoles.CHAIRPERSON, collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + chairperson, UserRoles.CHAIRPERSON, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosChairperson, - UserRoles.CHAIRPERSON.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosChairperson, UserRoles.CHAIRPERSON.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -648,11 +714,13 @@ void getCollectionSummaryForRoleById_ChairNoDatasetsInCollection() { Integer collectionId = randomInt(1, 100); when(darCollectionService.findDatasetIdsByDACUser(chairperson)).thenReturn(List.of(2)); - when(darCollectionService.getSummaryForRoleByCollectionId(chairperson, UserRoles.CHAIRPERSON, collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + chairperson, UserRoles.CHAIRPERSON, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosChairperson, - UserRoles.CHAIRPERSON.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosChairperson, UserRoles.CHAIRPERSON.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -663,12 +731,13 @@ void getCollectionSummaryForRoleById_SO() { mockSummary.setInstitutionId(signingOfficial.getInstitutionId()); Integer collectionId = randomInt(1, 100); - when(darCollectionService.getSummaryForRoleByCollectionId(signingOfficial, UserRoles.SIGNINGOFFICIAL, - collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + signingOfficial, UserRoles.SIGNINGOFFICIAL, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosSigningOfficial, - UserRoles.SIGNINGOFFICIAL.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosSigningOfficial, UserRoles.SIGNINGOFFICIAL.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -678,12 +747,13 @@ void getCollectionSummaryForRoleById_SODifferentInstitution() { mockSummary.setInstitutionId(2); Integer collectionId = randomInt(1, 100); - when(darCollectionService.getSummaryForRoleByCollectionId(signingOfficial, UserRoles.SIGNINGOFFICIAL, - collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + signingOfficial, UserRoles.SIGNINGOFFICIAL, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosSigningOfficial, - UserRoles.SIGNINGOFFICIAL.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosSigningOfficial, UserRoles.SIGNINGOFFICIAL.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -693,12 +763,13 @@ void getCollectionSummaryForRoleById_Researcher() { mockSummary.setResearcherId(researcher.getUserId()); Integer collectionId = randomInt(1, 100); - when(darCollectionService.getSummaryForRoleByCollectionId(researcher, UserRoles.RESEARCHER, - collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + researcher, UserRoles.RESEARCHER, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosResearcher, - UserRoles.RESEARCHER.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosResearcher, UserRoles.RESEARCHER.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -708,12 +779,13 @@ void getCollectionSummaryForRoleById_ResearcherNotCreateUser() { mockSummary.setResearcherId(2); Integer collectionId = randomInt(1, 100); - when(darCollectionService.getSummaryForRoleByCollectionId(researcher, UserRoles.RESEARCHER, - collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + researcher, UserRoles.RESEARCHER, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosResearcher, - UserRoles.RESEARCHER.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosResearcher, UserRoles.RESEARCHER.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -722,13 +794,12 @@ void getCollectionSummaryForRoleById_Admin() { DarCollectionSummary mockSummary = new DarCollectionSummary(); Integer collectionId = randomInt(1, 100); - - when(darCollectionService.getSummaryForRoleByCollectionId(admin, UserRoles.ADMIN, - collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId(admin, UserRoles.ADMIN, collectionId)) .thenReturn(mockSummary); - Response response = resource.getCollectionSummaryForRoleById(duosAdmin, - UserRoles.ADMIN.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosAdmin, UserRoles.ADMIN.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -739,7 +810,9 @@ void getCollectionSummaryForRoleById_NoRoleFound() { Response response = resource.getCollectionSummaryForRoleById( - new DuosUser(authUser, noRoleUser), UserRoles.SIGNINGOFFICIAL.getRoleName(), collectionId); + new DuosUser(authUser, noRoleUser), + UserRoles.SIGNINGOFFICIAL.getRoleName(), + collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -747,7 +820,8 @@ void getCollectionSummaryForRoleById_NoRoleFound() { void getCollectionSummaryForRoleById_InvalidRoleString() { Integer collectionId = randomInt(1, 100); - Response response = resource.getCollectionSummaryForRoleById(duosResearcher, "invalid", collectionId); + Response response = + resource.getCollectionSummaryForRoleById(duosResearcher, "invalid", collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -755,12 +829,13 @@ void getCollectionSummaryForRoleById_InvalidRoleString() { void getCollectionSummaryForRoleById_CollectionNotFound() { Integer collectionId = randomInt(1, 100); - when(darCollectionService.getSummaryForRoleByCollectionId(duosResearcher.getUser(), UserRoles.RESEARCHER, - collectionId)) + when(darCollectionService.getSummaryForRoleByCollectionId( + duosResearcher.getUser(), UserRoles.RESEARCHER, collectionId)) .thenThrow(new NotFoundException()); - Response response = resource.getCollectionSummaryForRoleById(duosResearcher, - UserRoles.RESEARCHER.getRoleName(), collectionId); + Response response = + resource.getCollectionSummaryForRoleById( + duosResearcher, UserRoles.RESEARCHER.getRoleName(), collectionId); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java index 1821861dd7..4f41abc114 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DataAccessRequestResourceTest.java @@ -86,42 +86,30 @@ class DataAccessRequestResourceTest extends AbstractTestHelper { private final AuthUser anotherUser = new AuthUser("bob@test.com"); private final List roles = Collections.singletonList(UserRoles.Researcher()); private final List adminRoles = Collections.singletonList(UserRoles.Admin()); - private final List chairpersonRoles = Collections.singletonList( - UserRoles.Chairperson()); + private final List chairpersonRoles = + Collections.singletonList(UserRoles.Chairperson()); private final List memberRoles = Collections.singletonList(UserRoles.Member()); private final User user = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); private final DuosUser duosUser = new DuosUser(authUser, user); - private final User admin = new User(2, adminUser.getEmail(), "Admin user", new Date(), - adminRoles); - private final User chairperson = new User(3, chairpersonUser.getEmail(), "Chairperson user", - new Date(), chairpersonRoles); - private final User member = new User(4, memberUser.getEmail(), "Member user", new Date(), - memberRoles); + private final User admin = + new User(2, adminUser.getEmail(), "Admin user", new Date(), adminRoles); + private final User chairperson = + new User(3, chairpersonUser.getEmail(), "Chairperson user", new Date(), chairpersonRoles); + private final User member = + new User(4, memberUser.getEmail(), "Member user", new Date(), memberRoles); private final User bob = new User(5, anotherUser.getEmail(), "Bob", new Date(), roles); - @Mock - private DaaService daaService; - @Mock - private DataAccessRequestService dataAccessRequestService; - @Mock - private MatchService matchService; - @Mock - private GCSService gcsService; - @Mock - private UserService userService; - @Mock - private DatasetService datasetService; - @Mock - private DarCollectionService darCollectionService; - @Mock - private ContainerRequest request; - @Mock - private UriInfo info; - @Mock - private UriBuilder builder; - @Mock - private User mockUser; - @Mock - private ContainerRequest containerRequest; + @Mock private DaaService daaService; + @Mock private DataAccessRequestService dataAccessRequestService; + @Mock private MatchService matchService; + @Mock private GCSService gcsService; + @Mock private UserService userService; + @Mock private DatasetService datasetService; + @Mock private DarCollectionService darCollectionService; + @Mock private ContainerRequest request; + @Mock private UriInfo info; + @Mock private UriBuilder builder; + @Mock private User mockUser; + @Mock private ContainerRequest containerRequest; private DataAccessRequestResource resource; @BeforeEach @@ -129,9 +117,14 @@ void initResource() { user.setLibraryCard(new LibraryCard()); try { resource = - new DataAccessRequestResource(daaService, - dataAccessRequestService, gcsService, userService, datasetService, - matchService, darCollectionService); + new DataAccessRequestResource( + daaService, + dataAccessRequestService, + gcsService, + userService, + datasetService, + matchService, + darCollectionService); } catch (Exception e) { fail("Initialization Exception: " + e.getMessage()); } @@ -149,8 +142,7 @@ void testCreateDataAccessRequest() { DataAccessRequestData data = new DataAccessRequestData(); data.setReferenceId(dar.getReferenceId()); dar.setData(data); - when(dataAccessRequestService.createDataAccessRequest(any(), any(), any())) - .thenReturn(dar); + when(dataAccessRequestService.createDataAccessRequest(any(), any(), any())).thenReturn(dar); doNothing().when(matchService).reprocessMatchesForPurpose(any()); doNothing().when(darCollectionService).sendNewDARCollectionMessage(any()); when(builder.build()).thenReturn(URI.create("https://test.domain.org/some/path")); @@ -176,12 +168,14 @@ void testCreateDataAccessRequestWithSubmittedDAR() { data.setReferenceId(dar.getReferenceId()); dar.setData(data); dar.setSubmissionDate(Timestamp.from(Instant.now())); - doThrow(new SubmittedDARCannotBeEditedException()).when(dataAccessRequestService) + doThrow(new SubmittedDARCannotBeEditedException()) + .when(dataAccessRequestService) .createDataAccessRequest(any(), any(), any()); try (var response = resource.createDataAccessRequest(authUser, request, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY, response.getStatus()); - org.broadinstitute.consent.http.models.Error error = (org.broadinstitute.consent.http.models.Error) response.getEntity(); + org.broadinstitute.consent.http.models.Error error = + (org.broadinstitute.consent.http.models.Error) response.getEntity(); assertEquals(SubmittedDARCannotBeEditedException.MESSAGE, error.message()); } } @@ -191,7 +185,8 @@ void testCreateDataAccessRequestWithoutValidERACommons() { User userWithCards = new User(1, authUser.getEmail(), "Display Name", new Date(), roles); userWithCards.setLibraryCard(new LibraryCard()); when(userService.findUserByEmail(any())).thenReturn(userWithCards); - doThrow(new BadRequestException()).when(dataAccessRequestService) + doThrow(new BadRequestException()) + .when(dataAccessRequestService) .createDataAccessRequest(eq(user), any(), any()); try (var response = resource.createDataAccessRequest(authUser, request, info, "")) { @@ -217,7 +212,9 @@ void testGetByReferenceIdForbidden() { } @ParameterizedTest - @EnumSource(value = UserRoles.class, names = {"ADMIN", "CHAIRPERSON", "MEMBER", "SIGNINGOFFICIAL"}) + @EnumSource( + value = UserRoles.class, + names = {"ADMIN", "CHAIRPERSON", "MEMBER", "SIGNINGOFFICIAL"}) void testGetByReferenceIdAllowedRoles(UserRoles role) { UserRole userRole = new UserRole(role.getRoleId(), role.getRoleName()); User roleUser = new User(1, authUser.getEmail(), "Display Name", new Date(), List.of(userRole)); @@ -231,7 +228,9 @@ void testGetByReferenceIdAllowedRoles(UserRoles role) { } @ParameterizedTest - @EnumSource(value = UserRoles.class, names = {"ALUMNI", "DATASUBMITTER", "ITDIRECTOR", "SERVICE_ACCOUNT", "RESEARCHER"}) + @EnumSource( + value = UserRoles.class, + names = {"ALUMNI", "DATASUBMITTER", "ITDIRECTOR", "SERVICE_ACCOUNT", "RESEARCHER"}) void testGetByReferenceIdDisallowedRoles(UserRoles role) { UserRole userRole = new UserRole(role.getRoleId(), role.getRoleName()); User roleUser = new User(1, authUser.getEmail(), "Display Name", new Date(), List.of(userRole)); @@ -326,7 +325,8 @@ void testGetIrbDocument() { dar.getData().setIrbDocumentName(randomAlphabetic(10) + ".txt"); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); - assertEquals(200, resource.getIrbDocument(new DuosUser(chairpersonUser, chairperson), "").getStatus()); + assertEquals( + 200, resource.getIrbDocument(new DuosUser(chairpersonUser, chairperson), "").getStatus()); assertEquals(200, resource.getIrbDocument(new DuosUser(adminUser, admin), "").getStatus()); assertEquals(200, resource.getIrbDocument(new DuosUser(memberUser, member), "").getStatus()); assertEquals(200, resource.getIrbDocument(new DuosUser(authUser, user), "").getStatus()); @@ -416,15 +416,23 @@ void testPostProgressReportCollabAndEthicsFiles() { DataAccessRequest parentDar = generateDataAccessRequest(); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(parentDar); DataAccessRequest childDar = generateDataAccessRequest(); - when(dataAccessRequestService.createProgressReport(eq(user), any(), eq(parentDar), eq(request))).thenReturn( - childDar); + when(dataAccessRequestService.createProgressReport(eq(user), any(), eq(parentDar), eq(request))) + .thenReturn(childDar); // datasets retrieved for the compliance logger when(datasetService.findDatasetsByIds(user, childDar.getDatasetIds())).thenReturn(List.of()); Pair collabFile = mockFormDataMultiPart("collab.txt"); Pair ethicsFile = mockFormDataMultiPart("ethics.txt"); - try (var response = resource.postProgressReport(authUser, request, "", "", collabFile.getLeft(), - collabFile.getRight(), ethicsFile.getLeft(), ethicsFile.getRight())) { + try (var response = + resource.postProgressReport( + authUser, + request, + "", + "", + collabFile.getLeft(), + collabFile.getRight(), + ethicsFile.getLeft(), + ethicsFile.getRight())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -438,8 +446,16 @@ void testPostProgressReportDifferentUser() { Pair collabFile = mockFormDataMultiPart("collab.txt"); Pair ethicsFile = mockFormDataMultiPart("ethics.txt"); - Response response = resource.postProgressReport(authUser, request,"", "", collabFile.getLeft(), - collabFile.getRight(), ethicsFile.getLeft(), ethicsFile.getRight()); + Response response = + resource.postProgressReport( + authUser, + request, + "", + "", + collabFile.getLeft(), + collabFile.getRight(), + ethicsFile.getLeft(), + ethicsFile.getRight()); assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } @@ -450,8 +466,16 @@ void testPostProgressReportMissingParentDar() { Pair collabFile = mockFormDataMultiPart("collab.txt"); Pair ethicsFile = mockFormDataMultiPart("ethics.txt"); - try (var response = resource.postProgressReport(authUser, request,"", "", collabFile.getLeft(), - collabFile.getRight(), ethicsFile.getLeft(), ethicsFile.getRight())) { + try (var response = + resource.postProgressReport( + authUser, + request, + "", + "", + collabFile.getLeft(), + collabFile.getRight(), + ethicsFile.getLeft(), + ethicsFile.getRight())) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -465,8 +489,16 @@ void testPostProgressReportInvalidJson() { var collabFile = mockFormDataMultiPart("collab.txt"); var ethicsFile = mockFormDataMultiPart("ethics.txt"); - try (var response = resource.postProgressReport(authUser, request,"", invalidDar, - collabFile.getLeft(), collabFile.getRight(), ethicsFile.getLeft(), ethicsFile.getRight())) { + try (var response = + resource.postProgressReport( + authUser, + request, + "", + invalidDar, + collabFile.getLeft(), + collabFile.getRight(), + ethicsFile.getLeft(), + ethicsFile.getRight())) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); assertTrue(response.getEntity().toString().contains("Unable to parse DAR from JSON string")); } @@ -477,8 +509,8 @@ void testPostProgressReportThrowsWhenNoERACommonsID() { when(userService.findUserByEmail(user.getEmail())).thenReturn(user); doThrow(BadRequestException.class).when(userService).validateActiveERACredentials(user); - try (var response = resource.postProgressReport(authUser, request,"", "", - null, null, null, null)) { + try (var response = + resource.postProgressReport(authUser, request, "", "", null, null, null, null)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -492,14 +524,27 @@ void testPostProgressReportWithOpenElections() { election.setStatus(ElectionStatus.OPEN.getValue()); election.setElectionType(ElectionType.DATA_ACCESS.getValue()); election.setReferenceId(parentDar.getReferenceId()); - when(dataAccessRequestService.findOpenElectionsByReferenceId(parentDar.getReferenceId())).thenReturn(List.of(election)); + when(dataAccessRequestService.findOpenElectionsByReferenceId(parentDar.getReferenceId())) + .thenReturn(List.of(election)); var collabFile = mockFormDataMultiPart("collab.txt"); var ethicsFile = mockFormDataMultiPart("ethics.txt"); - try (var response = resource.postProgressReport(authUser, request,"", "", - collabFile.getLeft(), collabFile.getRight(), ethicsFile.getLeft(), ethicsFile.getRight())) { + try (var response = + resource.postProgressReport( + authUser, + request, + "", + "", + collabFile.getLeft(), + collabFile.getRight(), + ethicsFile.getLeft(), + ethicsFile.getRight())) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); - assertTrue(response.getEntity().toString().contains("Cannot create a progress report for a DAR with an open election")); + assertTrue( + response + .getEntity() + .toString() + .contains("Cannot create a progress report for a DAR with an open election")); } } @@ -512,28 +557,29 @@ void populateProgressReportWithDocuments() throws Exception { childDar.setDatasetIds(List.of(1, 2)); Dataset dataset1 = new Dataset(); - DataUse dataUse1 = new DataUseBuilder() - .setCollaboratorRequired(true) - .setEthicsApprovalRequired(true).build(); + DataUse dataUse1 = + new DataUseBuilder().setCollaboratorRequired(true).setEthicsApprovalRequired(true).build(); dataset1.setDataUse(dataUse1); // Both documents required Dataset dataset2 = new Dataset(); - DataUse dataUse2 = new DataUseBuilder() - .setCollaboratorRequired(false) - .setEthicsApprovalRequired(false).build(); + DataUse dataUse2 = + new DataUseBuilder() + .setCollaboratorRequired(false) + .setEthicsApprovalRequired(false) + .build(); dataset2.setDataUse(dataUse2); // No documents required when(datasetService.findDatasetById(mockUser, 1)).thenReturn(dataset1); when(datasetService.findDatasetById(mockUser, 2)).thenReturn(dataset2); String fileType = "text/plain"; - InputStream collabInputStream = IOUtils.toInputStream("collab content", - Charset.defaultCharset()); + InputStream collabInputStream = + IOUtils.toInputStream("collab content", Charset.defaultCharset()); FormDataContentDisposition collabFileDetails = mock(FormDataContentDisposition.class); when(collabFileDetails.getFileName()).thenReturn("collab_document.txt"); when(collabFileDetails.getType()).thenReturn(fileType); - InputStream ethicsInputStream = IOUtils.toInputStream("ethics content", - Charset.defaultCharset()); + InputStream ethicsInputStream = + IOUtils.toInputStream("ethics content", Charset.defaultCharset()); FormDataContentDisposition ethicsFileDetails = mock(FormDataContentDisposition.class); when(ethicsFileDetails.getFileName()).thenReturn("ethics_document.txt"); when(ethicsFileDetails.getType()).thenReturn(fileType); @@ -541,11 +587,15 @@ void populateProgressReportWithDocuments() throws Exception { BlobId blobId = BlobId.of("bucket", "location"); when(gcsService.storeDocument(eq(collabInputStream), eq(fileType), any())).thenReturn(blobId); when(gcsService.storeDocument(eq(ethicsInputStream), eq(fileType), any())).thenReturn(blobId); - resource.populateProgressReportWithDocuments(mockUser, - collabInputStream, collabFileDetails, ethicsInputStream, ethicsFileDetails, childDar, + resource.populateProgressReportWithDocuments( + mockUser, + collabInputStream, + collabFileDetails, + ethicsInputStream, + ethicsFileDetails, + childDar, parentDar); verify(gcsService, times(2)).storeDocument(any(), any(), any()); - } @Test @@ -557,14 +607,17 @@ void populateProgressReportWithDocumentsMissingCollaboration() { childDar.setDatasetIds(List.of(1)); Dataset dataset = new Dataset(); - DataUse dataUse = new DataUseBuilder() - .setCollaboratorRequired(true) - .setEthicsApprovalRequired(false).build(); + DataUse dataUse = + new DataUseBuilder().setCollaboratorRequired(true).setEthicsApprovalRequired(false).build(); dataset.setDataUse(dataUse); // Collaboration document required when(datasetService.findDatasetById(mockUser, 1)).thenReturn(dataset); - BadRequestException exception = assertThrows(BadRequestException.class, () -> resource.populateProgressReportWithDocuments( - mockUser, null, null, null, null, childDar, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> + resource.populateProgressReportWithDocuments( + mockUser, null, null, null, null, childDar, parentDar)); assertEquals("Collaboration document is required", exception.getMessage()); } @@ -579,14 +632,17 @@ void populateProgressReportWithDocumentsMissingEthics() { // Mock dataset Dataset dataset = new Dataset(); - DataUse dataUse = new DataUseBuilder() - .setCollaboratorRequired(false) - .setEthicsApprovalRequired(true).build(); + DataUse dataUse = + new DataUseBuilder().setCollaboratorRequired(false).setEthicsApprovalRequired(true).build(); dataset.setDataUse(dataUse); // Ethics approval document required when(datasetService.findDatasetById(mockUser, 1)).thenReturn(dataset); - BadRequestException exception = assertThrows(BadRequestException.class, () -> resource.populateProgressReportWithDocuments( - mockUser, null, null, null, null, childDar, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> + resource.populateProgressReportWithDocuments( + mockUser, null, null, null, null, childDar, parentDar)); assertEquals("Ethics approval document is required", exception.getMessage()); } @@ -602,8 +658,12 @@ void populateProgressReportWithDocumentsMissingDataUse() { dataset.setDataUse(null); // Ethics approval document required when(datasetService.findDatasetById(mockUser, 1)).thenReturn(dataset); - BadRequestException exception = assertThrows(BadRequestException.class, () -> resource.populateProgressReportWithDocuments( - mockUser, null, null, null, null, childDar, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> + resource.populateProgressReportWithDocuments( + mockUser, null, null, null, null, childDar, parentDar)); assertEquals("Dataset 1 is missing data use(s)", exception.getMessage()); } @@ -615,8 +675,12 @@ void populateProgressReportWithDocumentsDatasetNotFound() { childDar.setDatasetIds(List.of(1)); when(datasetService.findDatasetById(mockUser, 1)).thenReturn(null); - NotFoundException exception = assertThrows(NotFoundException.class, () -> resource.populateProgressReportWithDocuments( - mockUser, null, null, null, null, childDar, parentDar)); + NotFoundException exception = + assertThrows( + NotFoundException.class, + () -> + resource.populateProgressReportWithDocuments( + mockUser, null, null, null, null, childDar, parentDar)); assertEquals("Dataset 1 not found", exception.getMessage()); } @@ -651,8 +715,7 @@ private static Stream dataUseProvider() { Arguments.of(new DataUseBuilder().setStigmatizeDiseases(true).build()), Arguments.of(new DataUseBuilder().setVulnerablePopulations(true).build()), Arguments.of(new DataUseBuilder().setPsychologicalTraits(true).build()), - Arguments.of(new DataUseBuilder().setNotHealth(true).build()) - ); + Arguments.of(new DataUseBuilder().setNotHealth(true).build())); } @ParameterizedTest @@ -668,8 +731,10 @@ void testPopulateProgressReportWithDocumentsAndValidDataUse(DataUse dataUse) { DataAccessRequest childDar = generateDataAccessRequest(); childDar.setDatasetIds(List.of(dataset.getDatasetId())); - assertDoesNotThrow(() -> resource.populateProgressReportWithDocuments( - mockUser, null, null, null, null, childDar, parentDar)); + assertDoesNotThrow( + () -> + resource.populateProgressReportWithDocuments( + mockUser, null, null, null, null, childDar, parentDar)); } @ParameterizedTest @@ -694,8 +759,8 @@ void uploadDocumentContents(DarDocumentType documentType) throws Exception { String newLocation = "new_location"; BlobId mockBlobId = BlobId.of("bucket", newLocation); - when(gcsService.storeDocument(eq(uploadInputStream), eq(fileType), any())).thenReturn( - mockBlobId); + when(gcsService.storeDocument(eq(uploadInputStream), eq(fileType), any())) + .thenReturn(mockBlobId); when(gcsService.deleteDocument(existingLocation)).thenReturn(true); resource.uploadDocumentContents(documentType, dar, uploadInputStream, fileDetail); @@ -716,13 +781,19 @@ void testGetCollaborationDocument() { dar.getData().setCollaborationLetterName(randomAlphabetic(10) + ".txt"); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); - assertEquals(200, - resource.getCollaborationDocument(new DuosUser(chairpersonUser, chairperson), "").getStatus()); - assertEquals(200, resource.getCollaborationDocument(new DuosUser(adminUser, admin), "").getStatus()); - assertEquals(200, resource.getCollaborationDocument(new DuosUser(memberUser, member), "").getStatus()); - assertEquals(200, resource.getCollaborationDocument(new DuosUser(authUser, user), "").getStatus()); - assertEquals(403, - resource.getCollaborationDocument(new DuosUser(anotherUser, bob), "").getStatus()); + assertEquals( + 200, + resource + .getCollaborationDocument(new DuosUser(chairpersonUser, chairperson), "") + .getStatus()); + assertEquals( + 200, resource.getCollaborationDocument(new DuosUser(adminUser, admin), "").getStatus()); + assertEquals( + 200, resource.getCollaborationDocument(new DuosUser(memberUser, member), "").getStatus()); + assertEquals( + 200, resource.getCollaborationDocument(new DuosUser(authUser, user), "").getStatus()); + assertEquals( + 403, resource.getCollaborationDocument(new DuosUser(anotherUser, bob), "").getStatus()); } @Test @@ -761,8 +832,8 @@ void testUploadCollaborationDocument() throws Exception { when(formData.getSize()).thenReturn(1L); when(gcsService.storeDocument(any(), any(), any())).thenReturn(BlobId.of("buket", "name")); - Response response = resource.uploadCollaborationDocument(authUser, "", uploadInputStream, - formData); + Response response = + resource.uploadCollaborationDocument(authUser, "", uploadInputStream, formData); assertEquals(200, response.getStatus()); } @@ -773,8 +844,8 @@ void testUploadCollaborationDocumentDARNotFound() { InputStream uploadInputStream = IOUtils.toInputStream("test", Charset.defaultCharset()); FormDataContentDisposition formData = mock(FormDataContentDisposition.class); - Response response = resource.uploadCollaborationDocument(authUser, "", uploadInputStream, - formData); + Response response = + resource.uploadCollaborationDocument(authUser, "", uploadInputStream, formData); assertEquals(404, response.getStatus()); } @@ -794,8 +865,8 @@ void testUploadCollaborationDocumentWithPreviousDocument() throws Exception { when(gcsService.storeDocument(any(), any(), any())).thenReturn(BlobId.of("bucket", "name")); when(gcsService.deleteDocument(any())).thenReturn(true); - Response response = resource.uploadCollaborationDocument(authUser, "", uploadInputStream, - formData); + Response response = + resource.uploadCollaborationDocument(authUser, "", uploadInputStream, formData); assertEquals(200, response.getStatus()); } @@ -897,8 +968,7 @@ void testCreateDataAccessRequestWithDAARestrictions() { DataAccessRequestData data = new DataAccessRequestData(); data.setReferenceId(dar.getReferenceId()); dar.setData(data); - when(dataAccessRequestService.createDataAccessRequest(any(), any(), any())) - .thenReturn(dar); + when(dataAccessRequestService.createDataAccessRequest(any(), any(), any())).thenReturn(dar); doNothing().when(matchService).reprocessMatchesForPurpose(any()); doNothing().when(darCollectionService).sendNewDARCollectionMessage(any()); when(builder.build()).thenReturn(URI.create("https://test.domain.org/some/path")); @@ -907,9 +977,8 @@ void testCreateDataAccessRequestWithDAARestrictions() { fail("Initialization Exception: " + e.getMessage()); } - try (Response response = resource.createDataAccessRequestWithDAARestrictions(authUser, containerRequest, - info, - "")) { + try (Response response = + resource.createDataAccessRequestWithDAARestrictions(authUser, containerRequest, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); } } @@ -931,8 +1000,8 @@ void testCreateDataAccessRequestWithDAARestrictionsFailure() { fail("Initialization Exception: " + e.getMessage()); } - try (Response response = resource.createDataAccessRequestWithDAARestrictions(authUser, - containerRequest, info, "")) { + try (Response response = + resource.createDataAccessRequestWithDAARestrictions(authUser, containerRequest, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -950,8 +1019,8 @@ void testCreateDraftDataAccessRequestWithDAARestrictions() { fail("Initialization Exception: " + e.getMessage()); } - try (Response response = resource.createDraftDataAccessRequestWithDAARestrictions(authUser, - info, "")) { + try (Response response = + resource.createDraftDataAccessRequestWithDAARestrictions(authUser, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); } } @@ -965,8 +1034,8 @@ void testCreateDraftDataAccessRequestWithDAARestrictionsFailure() { fail("Initialization Exception: " + e.getMessage()); } - try (Response response = resource.createDraftDataAccessRequestWithDAARestrictions(authUser, - info, "")) { + try (Response response = + resource.createDraftDataAccessRequestWithDAARestrictions(authUser, info, "")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -978,8 +1047,8 @@ void testUpdatePartialDataAccessRequestWithDAARestrictions() { when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); when(dataAccessRequestService.updateByReferenceId(any(), any())).thenReturn(dar); - try (Response response = resource.updatePartialDataAccessRequestWithDAARestrictions(authUser, - "", "{}")) { + try (Response response = + resource.updatePartialDataAccessRequestWithDAARestrictions(authUser, "", "{}")) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -991,8 +1060,8 @@ void testUpdatePartialDataAccessRequestWithDAARestrictionsFailure() { when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); doThrow(BadRequestException.class).when(datasetService).enforceDAARestrictions(any(), any()); - try (Response response = resource.updatePartialDataAccessRequestWithDAARestrictions(authUser, - "", "{}")) { + try (Response response = + resource.updatePartialDataAccessRequestWithDAARestrictions(authUser, "", "{}")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -1003,7 +1072,8 @@ void testGetDAAsByReferenceId() { when(dataAccessRequestService.findByReferenceId(any())).thenReturn(dar); when(daaService.findByDarReferenceId(any())).thenReturn(List.of()); - try (Response response = resource.getDAAsByReferenceId(new DuosUser(authUser, user), dar.getReferenceId())) { + try (Response response = + resource.getDAAsByReferenceId(new DuosUser(authUser, user), dar.getReferenceId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -1013,7 +1083,8 @@ void testGetDAAsByReferenceIdNotFound() { DataAccessRequest dar = generateDataAccessRequest(); when(dataAccessRequestService.findByReferenceId(any())).thenReturn(null); - try (Response response = resource.getDAAsByReferenceId(new DuosUser(authUser, user), dar.getReferenceId())) { + try (Response response = + resource.getDAAsByReferenceId(new DuosUser(authUser, user), dar.getReferenceId())) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -1022,7 +1093,8 @@ void testGetDAAsByReferenceIdNotFound() { void testApproveCloseout() { String referenceId = UUID.randomUUID().toString(); doNothing().when(dataAccessRequestService).approveDataAccessRequestCloseout(user, referenceId); - when(dataAccessRequestService.findByReferenceId(referenceId)).thenReturn(new DataAccessRequest()); + when(dataAccessRequestService.findByReferenceId(referenceId)) + .thenReturn(new DataAccessRequest()); when(datasetService.findDatasetsByIds(user, List.of())).thenReturn(List.of()); try (Response response = resource.approveCloseout(duosUser, request, referenceId)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -1032,7 +1104,9 @@ void testApproveCloseout() { @Test void testApproveCloseoutThrows() { String referenceId = UUID.randomUUID().toString(); - doThrow(BadRequestException.class).when(dataAccessRequestService).approveDataAccessRequestCloseout(user,referenceId); + doThrow(BadRequestException.class) + .when(dataAccessRequestService) + .approveDataAccessRequestCloseout(user, referenceId); try (Response response = resource.approveCloseout(duosUser, request, referenceId)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -1046,7 +1120,8 @@ void testDeleteDraftDataAccessRequestForDraft() { assertTrue(dar.getDraft()); when(dataAccessRequestService.findByReferenceId(dar.getReferenceId())).thenReturn(dar); doNothing().when(dataAccessRequestService).deleteDataAccessRequest(dar); - try (Response response = resource.deleteDar(new DuosUser(authUser, user), dar.getReferenceId())) { + try (Response response = + resource.deleteDar(new DuosUser(authUser, user), dar.getReferenceId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -1060,7 +1135,8 @@ void testDeleteDraftDataAccessRequestThrowsForSubmittedDar() { assertFalse(dar.getDraft()); when(dataAccessRequestService.findByReferenceId(dar.getReferenceId())).thenReturn(dar); doThrow(BadRequestException.class).when(dataAccessRequestService).deleteDataAccessRequest(dar); - try (Response response = resource.deleteDar(new DuosUser(authUser, user), dar.getReferenceId())) { + try (Response response = + resource.deleteDar(new DuosUser(authUser, user), dar.getReferenceId())) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DataResourceTestData.java b/src/test/java/org/broadinstitute/consent/http/resources/DataResourceTestData.java index cb3523768c..cf1ba134c0 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DataResourceTestData.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DataResourceTestData.java @@ -2,13 +2,15 @@ public class DataResourceTestData { - public static final String registrationWithMalformedJson = """ + public static final String registrationWithMalformedJson = + """ { "studyType" - "Observational" } """; - public static final String registrationWithStudyName = """ + public static final String registrationWithStudyName = + """ { "studyType": "Observational", "studyName": "name", @@ -20,7 +22,8 @@ public class DataResourceTestData { } """; - public static final String registrationWithDataSubmitterUserId = """ + public static final String registrationWithDataSubmitterUserId = + """ { "studyType": "Observational", "studyDescription": "description", @@ -32,7 +35,8 @@ public class DataResourceTestData { } """; - public static final String registrationWithExistingCGDataUse = """ + public static final String registrationWithExistingCGDataUse = + """ { "studyType": "Observational", "studyDescription": "description", @@ -69,7 +73,8 @@ public class DataResourceTestData { } """; - public static final String registrationWithExistingCG = """ + public static final String registrationWithExistingCG = + """ { "studyType": "Observational", "studyDescription": "description", @@ -93,7 +98,8 @@ public class DataResourceTestData { } """; - public static final String validRegistration = """ + public static final String validRegistration = + """ { "studyType": "Observational", "studyDescription": "description", @@ -155,5 +161,4 @@ public class DataResourceTestData { ] } """; - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java index daedcda5dc..ead7921c13 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DatasetResourceTest.java @@ -1,6 +1,5 @@ package org.broadinstitute.consent.http.resources; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -80,25 +79,18 @@ @ExtendWith(MockitoExtension.class) class DatasetResourceTest extends AbstractTestHelper { - @Mock - private DatasetService datasetService; - @Mock - private DatasetRegistrationService datasetRegistrationService; + @Mock private DatasetService datasetService; + @Mock private DatasetRegistrationService datasetRegistrationService; - @Mock - private ElasticSearchService elasticSearchService; + @Mock private ElasticSearchService elasticSearchService; - @Mock - private TDRService tdrService; + @Mock private TDRService tdrService; - @Mock - private UserService userService; + @Mock private UserService userService; - @Mock - private GCSService gcsService; + @Mock private GCSService gcsService; - @Mock - private Response mockResponse; + @Mock private Response mockResponse; private final AuthUser authUser = new AuthUser().setEmail("test@test.com"); private final User user = new User(); @@ -107,8 +99,14 @@ class DatasetResourceTest extends AbstractTestHelper { @BeforeEach void initResource() { - resource = new DatasetResource(datasetService, userService, - datasetRegistrationService, elasticSearchService, tdrService, gcsService); + resource = + new DatasetResource( + datasetService, + userService, + datasetRegistrationService, + elasticSearchService, + tdrService, + gcsService); } @Test @@ -182,14 +180,14 @@ void testPatchByDatasetUpdate_notModified() { dataset.setProperties(Set.of(dataLocationProp)); when(datasetService.findDatasetById(any(), any())).thenReturn(dataset); - DatasetPatch patch = new DatasetPatch(dataset.getDatasetName(), - dataset.getProperties().stream().toList()); + DatasetPatch patch = + new DatasetPatch(dataset.getDatasetName(), dataset.getProperties().stream().toList()); user.setUserId(randomInt(1, 100)); dataset.setCreateUserId(user.getUserId()); - try (Response response = resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), - gson.toJson(patch))) { + try (Response response = + resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), gson.toJson(patch))) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_MODIFIED, response.getStatus()); } } @@ -220,8 +218,8 @@ void testPatchByDatasetUpdate_nonUniqueName() { dataset.setCreateUserId(user.getUserId()); when(datasetService.findAllDatasetNames()).thenReturn(List.of(dataset.getName(), patch.name())); - try (Response response = resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), - gson.toJson(patch))) { + try (Response response = + resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), gson.toJson(patch))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -255,8 +253,8 @@ void testPatchByDatasetUpdate_patchable() throws Exception { user.setUserId(randomInt(1, 100)); dataset.setCreateUserId(user.getUserId()); - try (Response response = resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), - gson.toJson(patch))) { + try (Response response = + resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), gson.toJson(patch))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); verify(elasticSearchService, never()).indexDataset(dataset.getDatasetId(), user); } @@ -291,8 +289,8 @@ void testPatchByDatasetUpdate_patchableNoName() { when(datasetRegistrationService.patchDataset(any(), any(), any())).thenReturn(dataset); dataset.setCreateUserId(user.getUserId()); - try (Response response = resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), - gson.toJson(patch))) { + try (Response response = + resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), gson.toJson(patch))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -312,8 +310,8 @@ void testPatchByDatasetUpdate_invokeIndexUpdate() { when(datasetRegistrationService.patchDataset(any(), any(), any())).thenReturn(dataset); dataset.setCreateUserId(user.getUserId()); - try (Response response = resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), - gson.toJson(patch))) { + try (Response response = + resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), gson.toJson(patch))) { verify(elasticSearchService).synchronizeDatasetInESIndex(dataset, user, false); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -345,8 +343,8 @@ void testPatchByDatasetUpdate_invalidPatchProperties() { DatasetPatch patch = new DatasetPatch(randomAlphabetic(20), List.of(patchProp)); dataset.setCreateUserId(user.getUserId()); - try (Response response = resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), - gson.toJson(patch))) { + try (Response response = + resource.patchByDatasetUpdate(duosUser, dataset.getDatasetId(), gson.toJson(patch))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -356,18 +354,20 @@ void testValidateDatasetNameSuccess() { Dataset testDataset = new Dataset(); when(datasetService.getDatasetByName("test")).thenReturn(testDataset); - try (var response = resource.validateDatasetName(duosUser,"test")) { + try (var response = resource.validateDatasetName(duosUser, "test")) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @Test void testValidateDatasetNameNotFound() { - assertThrows(NotFoundException.class, () -> { - try (var response = resource.validateDatasetName(duosUser, "test")) { - fail("Should not get to this point"); - } - }); + assertThrows( + NotFoundException.class, + () -> { + try (var response = resource.validateDatasetName(duosUser, "test")) { + fail("Should not get to this point"); + } + }); } @Test @@ -440,7 +440,8 @@ void testDeleteErrorNullConsent() { role.setDacId(1); user.addRole(role); - when(datasetService.findDatasetById(duosUser.getUser(), dataset.getDatasetId())).thenReturn(dataset); + when(datasetService.findDatasetById(duosUser.getUser(), dataset.getDatasetId())) + .thenReturn(dataset); try (var response = resource.delete(duosUser, 1)) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -469,7 +470,8 @@ void testIndexAllDatasets() throws Exception { Dataset dataset = new Dataset(); dataset.setDatasetId(randomInt(10, 100)); Gson gson = GsonUtil.buildGson(); - String esResponseArray = """ + String esResponseArray = + """ [ { "took": 2, @@ -495,11 +497,11 @@ void testIndexAllDatasets() throws Exception { } ] """; - StreamingOutput output = out -> out.write( - esResponseArray.formatted(dataset.getDatasetId()).getBytes()); + StreamingOutput output = + out -> out.write(esResponseArray.formatted(dataset.getDatasetId()).getBytes()); when(datasetService.findAllDatasetIds()).thenReturn(List.of(dataset.getDatasetId())); - when(elasticSearchService.indexDatasetIds(List.of(dataset.getDatasetId()), user)).thenReturn( - output); + when(elasticSearchService.indexDatasetIds(List.of(dataset.getDatasetId()), user)) + .thenReturn(output); when(userService.findUserByEmail(duosUser.getEmail())).thenReturn(user); try (Response response = resource.indexDatasets(duosUser)) { @@ -513,11 +515,7 @@ void testIndexAllDatasets() throws Exception { assertEquals(1, items.size()); assertEquals( dataset.getDatasetId(), - items.get(0) - .getAsJsonObject() - .getAsJsonObject("index") - .get("_id") - .getAsInt()); + items.get(0).getAsJsonObject().getAsJsonObject("index").get("_id").getAsInt()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -589,7 +587,8 @@ void testGetDatasets() { ds3.setDatasetId(3); List datasets = List.of(ds1, ds2, ds3); - when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 2, 3))).thenReturn(datasets); + when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 2, 3))) + .thenReturn(datasets); Response response = resource.getDatasets(duosUser, List.of(1, 2, 3)); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -606,7 +605,8 @@ void testGetDatasetsDuplicates() { ds3.setDatasetId(3); List datasets = List.of(ds1, ds2, ds3); - when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 1, 2, 2, 3, 3))).thenReturn(datasets); + when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 1, 2, 2, 3, 3))) + .thenReturn(datasets); Response response = resource.getDatasets(duosUser, List.of(1, 1, 2, 2, 3, 3)); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -620,17 +620,14 @@ void testGetDatasetsDuplicatesNotFound() { Dataset ds2 = new Dataset(); ds2.setDatasetId(2); - when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 1, 2, 2, 3, 3))).thenReturn(List.of( - ds1, - ds2 - )); + when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 1, 2, 2, 3, 3))) + .thenReturn(List.of(ds1, ds2)); Response response = resource.getDatasets(duosUser, List.of(1, 1, 2, 2, 3, 3)); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); assertTrue(((Error) response.getEntity()).message().contains("3")); assertFalse(((Error) response.getEntity()).message().contains("2")); assertFalse(((Error) response.getEntity()).message().contains("1")); - } @Test @@ -640,10 +637,8 @@ void testGetDatasetsNotFound() { Dataset ds3 = new Dataset(); ds3.setDatasetId(3); - when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 2, 3, 4))).thenReturn(List.of( - ds1, - ds3 - )); + when(datasetService.findDatasetsByIds(duosUser.getUser(), List.of(1, 2, 3, 4))) + .thenReturn(List.of(ds1, ds3)); Response response = resource.getDatasets(duosUser, List.of(1, 2, 3, 4)); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -662,10 +657,7 @@ void testGetDatasetsNotFoundNullValues() { List input = new ArrayList<>(List.of(1, 2, 3, 4)); input.add(null); - when(datasetService.findDatasetsByIds(duosUser.getUser(), input)).thenReturn(List.of( - ds1, - ds3 - )); + when(datasetService.findDatasetsByIds(duosUser.getUser(), input)).thenReturn(List.of(ds1, ds3)); Response response = resource.getDatasets(duosUser, input); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -675,7 +667,6 @@ void testGetDatasetsNotFoundNullValues() { assertFalse(((Error) response.getEntity()).message().contains("1")); } - @Test void testUpdateDatasetDataUse_OK() { Dataset d = new Dataset(); @@ -699,8 +690,8 @@ void testUpdateDatasetDataUse_BadRequestJson() { void testUpdateDatasetDataUse_BadRequestService() { Dataset d = new Dataset(); when(datasetService.findDatasetById(any(), any())).thenReturn(d); - when(datasetService.updateDatasetDataUse(any(), any(), any())).thenThrow( - new IllegalArgumentException()); + when(datasetService.updateDatasetDataUse(any(), any(), any())) + .thenThrow(new IllegalArgumentException()); String duString = new DataUseBuilder().setGeneralUse(true).build().toString(); try (var response = resource.updateDatasetDataUse(new AuthUser(), 1, duString)) { @@ -772,8 +763,8 @@ void testCreateDatasetRegistration_validSchema() throws SQLException, IOExceptio study.setStudyId(1); dataset.setStudy(study); dataset.setStudyId(study.getStudyId()); - when(datasetRegistrationService.createDatasetsFromRegistration(any(), any(), any())).thenReturn( - List.of(dataset)); + when(datasetRegistrationService.createDatasetsFromRegistration(any(), any(), any())) + .thenReturn(List.of(dataset)); when(datasetService.findStudy(anyInt())).thenReturn(study); String schemaV1 = createDatasetRegistrationMock(user); @@ -801,10 +792,8 @@ void testCreateDatasetRegistration_NoStudyFound() throws SQLException, IOExcepti @Test void testCreateDatasetRegistration_withFile() throws SQLException, IOException { - FormDataContentDisposition content = FormDataContentDisposition - .name("file") - .fileName("sharing_plan.txt") - .build(); + FormDataContentDisposition content = + FormDataContentDisposition.name("file").fileName("sharing_plan.txt").build(); FormDataBodyPart formDataBodyPart = mock(FormDataBodyPart.class); when(formDataBodyPart.getContentDisposition()).thenReturn(content); @@ -818,8 +807,8 @@ void testCreateDatasetRegistration_withFile() throws SQLException, IOException { study.setStudyId(1); dataset.setStudy(study); dataset.setStudyId(study.getStudyId()); - when(datasetRegistrationService.createDatasetsFromRegistration(any(), any(), any())).thenReturn( - List.of(dataset)); + when(datasetRegistrationService.createDatasetsFromRegistration(any(), any(), any())) + .thenReturn(List.of(dataset)); String schemaV1 = createDatasetRegistrationMock(user); when(datasetService.findStudy(anyInt())).thenReturn(study); Response response = resource.createDatasetRegistration(authUser, formDataMultiPart, schemaV1); @@ -828,34 +817,29 @@ void testCreateDatasetRegistration_withFile() throws SQLException, IOException { @Test void testCreateDatasetRegistration_multipleFiles() throws SQLException, IOException { - FormDataContentDisposition contentFile = FormDataContentDisposition - .name("file") - .fileName("sharing_plan.txt") - .build(); + FormDataContentDisposition contentFile = + FormDataContentDisposition.name("file").fileName("sharing_plan.txt").build(); FormDataBodyPart formDataBodyPartFile = mock(FormDataBodyPart.class); when(formDataBodyPartFile.getName()).thenReturn("file"); when(formDataBodyPartFile.getContentDisposition()).thenReturn(contentFile); - FormDataContentDisposition contentOther = FormDataContentDisposition - .name("other") - .fileName("other.txt") - .build(); + FormDataContentDisposition contentOther = + FormDataContentDisposition.name("other").fileName("other.txt").build(); FormDataBodyPart formDataBodyPartOther = mock(FormDataBodyPart.class); when(formDataBodyPartOther.getName()).thenReturn("other"); when(formDataBodyPartOther.getContentDisposition()).thenReturn(contentOther); - FormDataContentDisposition contentNotFile = FormDataContentDisposition - .name("notFile") - .build(); + FormDataContentDisposition contentNotFile = FormDataContentDisposition.name("notFile").build(); FormDataBodyPart formDataBodyPartNotFile = mock(FormDataBodyPart.class); when(formDataBodyPartNotFile.getContentDisposition()).thenReturn(contentNotFile); FormDataMultiPart formDataMultiPart = mock(FormDataMultiPart.class); - when(formDataMultiPart.getFields()).thenReturn( - Map.of( - "file", List.of(formDataBodyPartFile), - "other", List.of(formDataBodyPartOther), - "notFile", List.of(formDataBodyPartNotFile))); + when(formDataMultiPart.getFields()) + .thenReturn( + Map.of( + "file", List.of(formDataBodyPartFile), + "other", List.of(formDataBodyPartOther), + "notFile", List.of(formDataBodyPartNotFile))); when(userService.findUserByEmail(any())).thenReturn(user); user.setUserId(1); @@ -864,19 +848,19 @@ void testCreateDatasetRegistration_multipleFiles() throws SQLException, IOExcept study.setStudyId(1); dataset.setStudy(study); dataset.setStudyId(study.getStudyId()); - when(datasetRegistrationService.createDatasetsFromRegistration(any(), any(), any())).thenReturn( - List.of(dataset)); + when(datasetRegistrationService.createDatasetsFromRegistration(any(), any(), any())) + .thenReturn(List.of(dataset)); when(datasetService.findStudy(anyInt())).thenReturn(study); String schemaV1 = createDatasetRegistrationMock(user); Response response = resource.createDatasetRegistration(authUser, formDataMultiPart, schemaV1); assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); - verify(datasetRegistrationService, times(1)).createDatasetsFromRegistration( - any(), - eq(user), - eq(Map.of("file", formDataBodyPartFile, "other", formDataBodyPartOther))); - + verify(datasetRegistrationService, times(1)) + .createDatasetsFromRegistration( + any(), + eq(user), + eq(Map.of("file", formDataBodyPartFile, "other", formDataBodyPartOther))); } @Test @@ -895,8 +879,8 @@ void testGetRegistrationFromDatasetIdentifier() { assertNotNull(dataset); when(datasetService.findDatasetByIdentifier(any(), any())).thenReturn(dataset); - Response response = resource.getRegistrationFromDatasetIdentifier(duosUser, - dataset.getDatasetIdentifier()); + Response response = + resource.getRegistrationFromDatasetIdentifier(duosUser, dataset.getDatasetIdentifier()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -906,8 +890,8 @@ void testGetRegistrationFromDatasetIdentifierStudyNotFound() { assertNotNull(dataset); when(datasetService.findDatasetByIdentifier(any(), any())).thenReturn(dataset); - Response response = resource.getRegistrationFromDatasetIdentifier(duosUser, - dataset.getDatasetIdentifier()); + Response response = + resource.getRegistrationFromDatasetIdentifier(duosUser, dataset.getDatasetIdentifier()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -918,8 +902,8 @@ void testGetRegistrationFromDatasetIdentifierDatasetNotFound() { assertNotNull(dataset); when(datasetService.findDatasetByIdentifier(any(), any())).thenReturn(null); - Response response = resource.getRegistrationFromDatasetIdentifier(duosUser, - dataset.getDatasetIdentifier()); + Response response = + resource.getRegistrationFromDatasetIdentifier(duosUser, dataset.getDatasetIdentifier()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -927,14 +911,12 @@ void testGetRegistrationFromDatasetIdentifierDatasetNotFound() { void testUpdateDatasetByDatasetIntakeSuccess() throws SQLException, IOException { Dataset preexistingDataset = new Dataset(); when(datasetService.findDatasetById(any(), anyInt())).thenReturn(preexistingDataset); - when(datasetRegistrationService.updateDataset(any(), any(), any(), any())).thenReturn( - preexistingDataset); + when(datasetRegistrationService.updateDataset(any(), any(), any(), any())) + .thenReturn(preexistingDataset); String json = createDataset(user); - FormDataContentDisposition content = FormDataContentDisposition - .name("file") - .fileName("validFile.txt") - .build(); + FormDataContentDisposition content = + FormDataContentDisposition.name("file").fileName("validFile.txt").build(); FormDataBodyPart formDataBodyPart = mock(FormDataBodyPart.class); when(formDataBodyPart.getContentDisposition()).thenReturn(content); @@ -973,10 +955,8 @@ void testUpdateDatasetWithInvalidJson() { @Test void testUpdateDatasetWithNoProperties() throws Exception { Dataset dataset = new Dataset(); - FormDataContentDisposition content = FormDataContentDisposition - .name("file") - .fileName("validFile.txt") - .build(); + FormDataContentDisposition content = + FormDataContentDisposition.name("file").fileName("validFile.txt").build(); FormDataBodyPart formDataBodyPart = mock(FormDataBodyPart.class); when(formDataBodyPart.getContentDisposition()).thenReturn(content); @@ -986,8 +966,8 @@ void testUpdateDatasetWithNoProperties() throws Exception { when(datasetService.findDatasetById(any(), any())).thenReturn(dataset); when(datasetRegistrationService.updateDataset(any(), any(), any(), any())).thenReturn(dataset); - try (var response = resource.updateByDatasetUpdate(duosUser, 1, formDataMultiPart, - "{\"properties\":[]}")) { + try (var response = + resource.updateByDatasetUpdate(duosUser, 1, formDataMultiPart, "{\"properties\":[]}")) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -1009,10 +989,10 @@ void testUpdateDatasetInvalidFileName() { when(datasetService.findDatasetById(any(), anyInt())).thenReturn(preexistingDataset); String json = createDatasetRegistrationMock(user); - FormDataContentDisposition content = FormDataContentDisposition - .name("file") - .fileName("\"file/with&$invalid*^chars\\\\.txt\"") - .build(); + FormDataContentDisposition content = + FormDataContentDisposition.name("file") + .fileName("\"file/with&$invalid*^chars\\\\.txt\"") + .build(); FormDataBodyPart formDataBodyPart = mock(FormDataBodyPart.class); when(formDataBodyPart.getContentDisposition()).thenReturn(content); @@ -1036,8 +1016,8 @@ void testSyncDataUseTranslation() { @Test void testSyncDataUseTranslationNotFound() { - when(datasetService.syncDatasetDataUseTranslation(any(), any())).thenThrow( - new NotFoundException()); + when(datasetService.syncDatasetDataUseTranslation(any(), any())) + .thenThrow(new NotFoundException()); try (var response = resource.syncDataUseTranslation(authUser, 1)) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -1047,22 +1027,21 @@ void testSyncDataUseTranslationNotFound() { @Test void testGetAuthorizedReadersOK() { when(datasetService.getAuthorizationReaders(anyLong())).thenReturn(new ArrayList<>()); - Response response = resource.getAuthorizedReaders(duosUser,1L); + Response response = resource.getAuthorizedReaders(duosUser, 1L); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } - @Test void testGetAuthorizedReadersError() { doThrow(new RuntimeException("Some Exception")) .when(datasetService) .getAuthorizationReaders(anyLong()); - Response response = resource.getAuthorizedReaders(duosUser,1L); + Response response = resource.getAuthorizedReaders(duosUser, 1L); assertEquals(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, response.getStatus()); } @Test - void testAddAuthorizedReadersNotServiceAccount(){ + void testAddAuthorizedReadersNotServiceAccount() { User readerUser = new User(); readerUser.setUserId(1); readerUser.addRole( @@ -1073,14 +1052,14 @@ void testAddAuthorizedReadersNotServiceAccount(){ } @Test - void testAddAuthorizedReaders(){ + void testAddAuthorizedReaders() { User readerUser = new User(); readerUser.setUserId(1); readerUser.addRole( new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName())); user.setUserId(1); - DatasetAuthorizationReader reader = new DatasetAuthorizationReader(1,1,1, 1, Timestamp.from( - Instant.now())); + DatasetAuthorizationReader reader = + new DatasetAuthorizationReader(1, 1, 1, 1, Timestamp.from(Instant.now())); when(userService.findUserById(any())).thenReturn(readerUser); when(datasetService.addAuthorizedReader(anyLong(), anyLong(), anyLong())).thenReturn(reader); Response response = resource.addAuthorizedReaders(duosUser, 1, 1); @@ -1088,7 +1067,7 @@ void testAddAuthorizedReaders(){ } @Test - void testAddAuthorizedReadersThrows(){ + void testAddAuthorizedReadersThrows() { User readerUser = new User(); readerUser.setUserId(1); readerUser.addRole( @@ -1100,15 +1079,17 @@ void testAddAuthorizedReadersThrows(){ } @Test - void testRemoveAuthorizedReaders(){ + void testRemoveAuthorizedReaders() { doNothing().when(datasetService).removeAuthorizedAccessReader(anyLong(), anyLong()); Response response = resource.removeAuthorizedReaders(duosUser, 1, 1); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @Test - void testRemoveAuthorizedReadersThrows(){ - doThrow(new RuntimeException("Some Exception")).when(datasetService).removeAuthorizedAccessReader(anyLong(), anyLong()); + void testRemoveAuthorizedReadersThrows() { + doThrow(new RuntimeException("Some Exception")) + .when(datasetService) + .removeAuthorizedAccessReader(anyLong(), anyLong()); Response response = resource.removeAuthorizedReaders(duosUser, 1, 1); assertEquals(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, response.getStatus()); } @@ -1117,17 +1098,19 @@ void testRemoveAuthorizedReadersThrows(){ void testGetApprovedUsers() { Dataset dataset = new Dataset(); dataset.setDatasetId(1); - when(datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false)).thenReturn(dataset); + when(datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false)) + .thenReturn(dataset); when(datasetService.isAuthorizedToListUsers(any(), any())).thenReturn(true); - when(tdrService.getApprovedUsersForDataset(any(), any())).thenReturn(new ApprovedUsers(List.of())); + when(tdrService.getApprovedUsersForDataset(any(), any())) + .thenReturn(new ApprovedUsers(List.of())); Response response = resource.getApprovedUsers(duosUser, "ABC"); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } - @Test void testGetApprovedUsersDatasetNotFound() { - when(datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false)).thenReturn(null); + when(datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false)) + .thenReturn(null); Response response = resource.getApprovedUsers(duosUser, "ABC"); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -1136,7 +1119,8 @@ void testGetApprovedUsersDatasetNotFound() { void testGetAuthorizedUsersNotApproved() { Dataset dataset = new Dataset(); dataset.setDatasetId(1); - when(datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false)).thenReturn(dataset); + when(datasetService.findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false)) + .thenReturn(dataset); when(datasetService.isAuthorizedToListUsers(any(), any())).thenReturn(false); Response response = resource.getApprovedUsers(duosUser, "ABC"); assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); @@ -1145,7 +1129,8 @@ void testGetAuthorizedUsersNotApproved() { @Test void testGetApprovedUsersDatasetThrows() { doThrow(new RuntimeException("Some exception")) - .when(datasetService).findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false); + .when(datasetService) + .findMinimalDatasetByIdentifier(duosUser.getUser(), "ABC", false); Response response = resource.getApprovedUsers(duosUser, "ABC"); assertEquals(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, response.getStatus()); } @@ -1159,7 +1144,6 @@ void testGetNihInstitutionalCertification_Submitter() { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } - @Test void testGetNihInstitutionalCertification_Document_No_Authorized_User() { Dataset dataset = getDatasetWithStudyUserAndFile(); @@ -1212,7 +1196,7 @@ void testGetNihInstitutionalCertification_Document_DacMember_Wrong_Dac() { Dataset dataset = getDatasetWithStudyUserAndFile(); User requestingUser = new User(); requestingUser.setUserId(2); - requestingUser.setMemberRoleWithDAC(dataset.getDacId()+1); + requestingUser.setMemberRoleWithDAC(dataset.getDacId() + 1); DuosUser requestingDuosUser = new DuosUser(authUser, requestingUser); when(datasetService.findDatasetById(any(), any())).thenReturn(dataset); Response response = resource.getNihInstitutionalCertification(requestingDuosUser, 1); @@ -1224,7 +1208,7 @@ void testGetNihInstitutionalCertification_Document_DacChair_Wrong_Dac() { Dataset dataset = getDatasetWithStudyUserAndFile(); User requestingUser = new User(); requestingUser.setUserId(2); - requestingUser.setChairpersonRoleWithDAC(dataset.getDacId()+1); + requestingUser.setChairpersonRoleWithDAC(dataset.getDacId() + 1); DuosUser requestingDuosUser = new DuosUser(authUser, requestingUser); when(datasetService.findDatasetById(any(), any())).thenReturn(dataset); Response response = resource.getNihInstitutionalCertification(requestingDuosUser, 1); @@ -1249,7 +1233,7 @@ void testGetNihInstitutionalCertification_Throws() { void testGetNihInstitutionalCertification_file_deleted() { Dataset dataset = getDatasetWithStudyUserAndFile(); FileStorageObject fso = new FileStorageObject(); - fso.setBlobId(BlobId.of("bucket","name")); + fso.setBlobId(BlobId.of("bucket", "name")); fso.setFileName("my file.pdf"); fso.setDeleted(true); fso.setMediaType("application/pdf"); @@ -1264,7 +1248,7 @@ void testGetNihInstitutionalCertification_file_deleted() { void testGetNihInstitutionalCertification_no_file_name() { Dataset dataset = getDatasetWithStudyUserAndFile(); FileStorageObject fso = new FileStorageObject(); - fso.setBlobId(BlobId.of("bucket","name")); + fso.setBlobId(BlobId.of("bucket", "name")); fso.setDeleted(false); fso.setMediaType("application/pdf"); dataset.setNihInstitutionalCertificationFile(fso); @@ -1301,7 +1285,7 @@ private Dataset getDatasetWithStudyUserAndFile() { dataset.setStudy(study); dataset.setStudyId(study.getStudyId()); FileStorageObject fso = new FileStorageObject(); - fso.setBlobId(BlobId.of("bucket","name")); + fso.setBlobId(BlobId.of("bucket", "name")); fso.setFileName("my file.pdf"); fso.setDeleted(false); fso.setMediaType("application/pdf"); @@ -1316,7 +1300,8 @@ private Dataset getDatasetWithStudyUserAndFile() { * @return The DatasetRegistrationSchemaV1.yaml instance */ private String createDatasetRegistrationMock(User user) { - String format = """ + String format = + """ { "studyType": "Observational", "studyName": "name", @@ -1354,7 +1339,8 @@ private String createDatasetRegistrationMock(User user) { * @return The Dataset instance */ private String createDataset(User user) { - String format = """ + String format = + """ { "datasetId": 2, "objectId": "SC-10985", @@ -1405,7 +1391,8 @@ private String createDataset(User user) { * @return The Dataset instance */ private String createInvalidDataset(User user) { - String format = """ + String format = + """ { "datasetId": 2, } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java index b2ad58270f..6f15d7423f 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/DraftResourceTest.java @@ -42,20 +42,15 @@ @ExtendWith(MockitoExtension.class) class DraftResourceTest { - @Mock - private DraftService draftService; + @Mock private DraftService draftService; - @Mock - private AuthUser authUser; + @Mock private AuthUser authUser; - @Mock - private User user; + @Mock private User user; - @Mock - private User user2; + @Mock private User user2; - @Mock - private UserService userService; + @Mock private UserService userService; private DraftResource resource; @@ -66,8 +61,7 @@ private void initResource() { @Test void testGetDraftWhenNoneExistForUser() { when(userService.findUserByEmail(any())).thenReturn(user); - when(draftService.findDraftSummariesForUser(any())).thenReturn( - Collections.emptySet()); + when(draftService.findDraftSummariesForUser(any())).thenReturn(Collections.emptySet()); initResource(); Response response = resource.getDrafts(authUser); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -78,7 +72,11 @@ void testGetDraftWhenNoneExistForUser() { void testGetDraftsWhenOneExistForUser() { Set draftSummaries = new HashSet<>(); draftSummaries.add( - new DraftSummary(UUID.randomUUID(), "test", new Date(), new Date(), + new DraftSummary( + UUID.randomUUID(), + "test", + new Date(), + new Date(), DraftType.STUDY_DATASET_SUBMISSION_V1)); when(userService.findUserByEmail(any())).thenReturn(user); when(draftService.findDraftSummariesForUser(any())).thenReturn(draftSummaries); @@ -99,7 +97,8 @@ void tesCreateDraftRegistration() { @Test void tesCreateDraftRegistrationWithoutJSON() throws SQLException { - doThrow(new BadRequestException("Error submitting draft")).when(draftService) + doThrow(new BadRequestException("Error submitting draft")) + .when(draftService) .insertDraft(any()); String draft = ""; initResource(); @@ -109,8 +108,8 @@ void tesCreateDraftRegistrationWithoutJSON() throws SQLException { @Test void testGetDraftDocumentNotFound() { - when(draftService.getAuthorizedDraft(any(), any())).thenThrow( - new NotFoundException("Not found exception.")); + when(draftService.getAuthorizedDraft(any(), any())) + .thenThrow(new NotFoundException("Not found exception.")); initResource(); Response response = resource.getDraftDocument(authUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -133,8 +132,8 @@ void testGetDraftDocumentSuccess() throws IOException { @Test void testGetDraftDocumentNotAuthorized() { - when(draftService.getAuthorizedDraft(any(), any())).thenThrow( - new NotAuthorizedException("Not authorized.")); + when(draftService.getAuthorizedDraft(any(), any())) + .thenThrow(new NotAuthorizedException("Not authorized.")); initResource(); Response response = resource.getDraftDocument(authUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); @@ -142,8 +141,8 @@ void testGetDraftDocumentNotAuthorized() { @Test void testPutDraftDocumentUnauthorized() { - when(draftService.getAuthorizedDraft(any(), any())).thenThrow( - new NotAuthorizedException("Not authorized.")); + when(draftService.getAuthorizedDraft(any(), any())) + .thenThrow(new NotAuthorizedException("Not authorized.")); initResource(); Response response = resource.updateDraft(authUser, UUID.randomUUID().toString(), "{}"); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); @@ -151,8 +150,8 @@ void testPutDraftDocumentUnauthorized() { @Test void testPutDraftDocumentNotFound() { - when(draftService.getAuthorizedDraft(any(), any())).thenThrow( - new NotFoundException("Not found exception.")); + when(draftService.getAuthorizedDraft(any(), any())) + .thenThrow(new NotFoundException("Not found exception.")); initResource(); Response response = resource.updateDraft(authUser, UUID.randomUUID().toString(), "{}"); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -176,8 +175,7 @@ void testPutDraftDocumentSuccess() throws IOException { @Test void testDeleteDraftDocumentNotFound() { - when(draftService.getAuthorizedDraft(any(), any())).thenThrow( - NotFoundException.class); + when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotFoundException.class); initResource(); Response response = resource.deleteDraft(authUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -185,8 +183,7 @@ void testDeleteDraftDocumentNotFound() { @Test void testDeleteDraftDocumentNotAuthorized() { - when(draftService.getAuthorizedDraft(any(), any())).thenThrow( - NotAuthorizedException.class); + when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotAuthorizedException.class); initResource(); Response response = resource.deleteDraft(authUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); @@ -194,8 +191,8 @@ void testDeleteDraftDocumentNotAuthorized() { @Test void testDeleteDraftDocumentSuccess() { - when(draftService.getAuthorizedDraft(any(), any())).thenReturn( - new DraftStudyDataset("{}", user)); + when(draftService.getAuthorizedDraft(any(), any())) + .thenReturn(new DraftStudyDataset("{}", user)); initResource(); Response response = resource.deleteDraft(authUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -245,8 +242,9 @@ void testGetDraftAttachmentsSuccessWithAttachments() { void testUploadAttachmentNotFound() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotFoundException.class); initResource(); - Response response = resource.addAttachments(authUser, UUID.randomUUID().toString(), mock( - FormDataMultiPart.class)); + Response response = + resource.addAttachments( + authUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } @@ -254,23 +252,24 @@ void testUploadAttachmentNotFound() { void testUploadAttachmentNotAuthorized() { when(draftService.getAuthorizedDraft(any(), any())).thenThrow(NotAuthorizedException.class); initResource(); - Response response = resource.addAttachments(authUser, UUID.randomUUID().toString(), mock( - FormDataMultiPart.class)); + Response response = + resource.addAttachments( + authUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatus()); } - @Test void testUploadAttachmentSuccess() throws SQLException { - when(draftService.getAuthorizedDraft(any(), any())).thenReturn( - new DraftStudyDataset("{}", user)); + when(draftService.getAuthorizedDraft(any(), any())) + .thenReturn(new DraftStudyDataset("{}", user)); DraftInterface draftWithAttachment = new DraftStudyDataset("{}", user); draftWithAttachment.addStoredFile(mock(FileStorageObject.class)); - when(draftService.addAttachments(any(), any(), any())).thenReturn( - List.copyOf(draftWithAttachment.getStoredFiles())); + when(draftService.addAttachments(any(), any(), any())) + .thenReturn(List.copyOf(draftWithAttachment.getStoredFiles())); initResource(); - Response response = resource.addAttachments(authUser, UUID.randomUUID().toString(), mock( - FormDataMultiPart.class)); + Response response = + resource.addAttachments( + authUser, UUID.randomUUID().toString(), mock(FormDataMultiPart.class)); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertEquals(List.copyOf(draftWithAttachment.getStoredFiles()), response.getEntity()); } @@ -299,13 +298,15 @@ void testGetAttachmentSuccess() throws SQLException { when(fileStorageObject1.getFileStorageObjectId()).thenReturn(1); draftWithAttachment.addStoredFile(fileStorageObject1); when(draftService.getAuthorizedDraft(any(), any())).thenReturn(draftWithAttachment); - when(draftService.getDraftAttachmentStream(fileStorageObject1)).thenReturn(mock( - InputStream.class)); + when(draftService.getDraftAttachmentStream(fileStorageObject1)) + .thenReturn(mock(InputStream.class)); initResource(); Response response = resource.getAttachment(authUser, UUID.randomUUID().toString(), 1); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); - assertTrue(response.getHeaderString("Content-Disposition") - .contains("attachment; filename=\"fileName1.txt\"")); + assertTrue( + response + .getHeaderString("Content-Disposition") + .contains("attachment; filename=\"fileName1.txt\"")); } @Test @@ -341,8 +342,8 @@ void testDeleteFileAttachmentNotAuthorized() { @Test void testDeleteFileAttachmentSuccess() throws SQLException { - when(draftService.getAuthorizedDraft(any(), any())).thenReturn( - new DraftStudyDataset("{}", user)); + when(draftService.getAuthorizedDraft(any(), any())) + .thenReturn(new DraftStudyDataset("{}", user)); doNothing().when(draftService).deleteDraftAttachment(any(), any(), any()); initResource(); Response response = resource.deleteDraftAttachment(authUser, UUID.randomUUID().toString(), 1); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java index 8f3fd7b2bc..f16f311781 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/EmailNotifierResourceTest.java @@ -8,7 +8,6 @@ import org.apache.commons.lang3.RandomUtils; import org.broadinstitute.consent.http.models.AuthUser; import org.broadinstitute.consent.http.service.DataAccessRequestService; -import org.broadinstitute.consent.http.service.EmailService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -18,10 +17,8 @@ @ExtendWith(MockitoExtension.class) class EmailNotifierResourceTest { - @Mock - private DataAccessRequestService dataAccessRequestService; - @Mock - private AuthUser authUser; + @Mock private DataAccessRequestService dataAccessRequestService; + @Mock private AuthUser authUser; private EmailNotifierResource resource; @@ -33,8 +30,8 @@ void setUp() { @Test void testResourceSuccess() throws Exception { doNothing().when(dataAccessRequestService).sendReminderMessage(any()); - try (Response response = resource.sendReminderMessage(authUser, - String.valueOf(RandomUtils.nextInt(100, 1000)))) { + try (Response response = + resource.sendReminderMessage(authUser, String.valueOf(RandomUtils.nextInt(100, 1000)))) { assertEquals(200, response.getStatus()); } } @@ -52,5 +49,4 @@ void testSendDarExpirationNotices() { assertEquals(200, response.getStatus()); } } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/ErrorResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/ErrorResourceTest.java index 17ac076292..d542fef678 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/ErrorResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/ErrorResourceTest.java @@ -18,12 +18,9 @@ @ExtendWith(MockitoExtension.class) class ErrorResourceTest { - @Mock - private HttpServletRequestWrapper request; - @Mock - private ServletApiRequest servletRequest; - @Mock - private ServletRequestInfo servletRequestInfo; + @Mock private HttpServletRequestWrapper request; + @Mock private ServletApiRequest servletRequest; + @Mock private ServletRequestInfo servletRequestInfo; @ParameterizedTest @ValueSource(strings = {"/not_found", "/context/¥"}) diff --git a/src/test/java/org/broadinstitute/consent/http/resources/InstitutionResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/InstitutionResourceTest.java index 8c5ec5f83b..e321aa02e5 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/InstitutionResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/InstitutionResourceTest.java @@ -35,12 +35,11 @@ class InstitutionResourceTest { private final AuthUser authUser = new AuthUser("test@test.com"); - private final User user = new User(1, "test@test.com", "Display Name", new Date(), - Collections.emptyList()); + private final User user = + new User(1, "test@test.com", "Display Name", new Date(), Collections.emptyList()); private final DuosUser duosUser = new DuosUser(authUser, user); - @Mock - private InstitutionService institutionService; + @Mock private InstitutionService institutionService; private InstitutionResource resource; @@ -118,7 +117,6 @@ void testGetInstitutionFail() { } } - @Test void testCreateInstitution() { Institution mockInstitution = mockInstitutionSetup(); @@ -138,8 +136,8 @@ void testCreateInstitutionNullName() { Institution mockInstitution = mockInstitutionSetup(); when(institutionService.createInstitution(any(), anyInt())).thenThrow(error); - try (var response = resource.createInstitution(duosUser, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.createInstitution(duosUser, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(400, response.getStatus()); } } @@ -150,8 +148,8 @@ void testCreateInstitutionBlankName() { Institution mockInstitution = mockInstitutionSetup(); when(institutionService.createInstitution(any(), anyInt())).thenThrow(error); - try (var response = resource.createInstitution(duosUser, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.createInstitution(duosUser, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(400, response.getStatus()); } } @@ -159,12 +157,13 @@ void testCreateInstitutionBlankName() { @Test void testCreateInstitutionDuplicate() { Institution mockInstitution = mockInstitutionSetup(); - ConsentConflictException conflictException = new ConsentConflictException( - "An institution exists with the name of '" + mockInstitution.getName() + "'"); + ConsentConflictException conflictException = + new ConsentConflictException( + "An institution exists with the name of '" + mockInstitution.getName() + "'"); when(institutionService.createInstitution(any(), anyInt())).thenThrow(conflictException); - try (var response = resource.createInstitution(duosUser, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.createInstitution(duosUser, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(409, response.getStatus()); } } @@ -173,14 +172,14 @@ void testCreateInstitutionDuplicate() { void testPatchInstitution() throws Exception { Institution mockInstitution = mockInstitutionSetup(); mockInstitution.setId(1); - when(institutionService.findInstitutionById(mockInstitution.getId())).thenReturn( - mockInstitution); - when(institutionService.updateInstitutionById(mockInstitution, mockInstitution.getId(), - duosUser.getUserId())).thenReturn( - mockInstitution); + when(institutionService.findInstitutionById(mockInstitution.getId())) + .thenReturn(mockInstitution); + when(institutionService.updateInstitutionById( + mockInstitution, mockInstitution.getId(), duosUser.getUserId())) + .thenReturn(mockInstitution); initResource(); - try (var response = resource.patchInstitution(duosUser, 1, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.patchInstitution(duosUser, 1, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertNotNull(response.getEntity().toString()); } @@ -190,11 +189,11 @@ void testPatchInstitution() throws Exception { void testPatchInstitutionNotFound() { Institution mockInstitution = mockInstitutionSetup(); mockInstitution.setId(1); - when(institutionService.findInstitutionById(mockInstitution.getId())).thenThrow( - new NotFoundException("Institution not found")); + when(institutionService.findInstitutionById(mockInstitution.getId())) + .thenThrow(new NotFoundException("Institution not found")); initResource(); - try (var response = resource.patchInstitution(duosUser, 1, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.patchInstitution(duosUser, 1, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); assertNotNull(response.getEntity().toString()); } @@ -204,8 +203,8 @@ void testPatchInstitutionNotFound() { void testPatchInstitutionBadRequest() { Institution mockInstitution = mockInstitutionSetup(); mockInstitution.setId(1); - when(institutionService.findInstitutionById(mockInstitution.getId())).thenReturn( - mockInstitution); + when(institutionService.findInstitutionById(mockInstitution.getId())) + .thenReturn(mockInstitution); initResource(); try (var response = resource.patchInstitution(duosUser, 1, "bad json")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); @@ -217,14 +216,14 @@ void testPatchInstitutionBadRequest() { void testPatchInstitutionServerError() throws Exception { Institution mockInstitution = mockInstitutionSetup(); mockInstitution.setId(1); - when(institutionService.findInstitutionById(mockInstitution.getId())).thenReturn( - mockInstitution); - when(institutionService.updateInstitutionById(mockInstitution, mockInstitution.getId(), - duosUser.getUserId())).thenThrow( - new ServerErrorException(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)); + when(institutionService.findInstitutionById(mockInstitution.getId())) + .thenReturn(mockInstitution); + when(institutionService.updateInstitutionById( + mockInstitution, mockInstitution.getId(), duosUser.getUserId())) + .thenThrow(new ServerErrorException(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)); initResource(); - try (var response = resource.patchInstitution(duosUser, 1, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.patchInstitution(duosUser, 1, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, response.getStatus()); assertNotNull(response.getEntity().toString()); } @@ -233,11 +232,11 @@ void testPatchInstitutionServerError() throws Exception { @Test void testUpdateInstitution() throws Exception { Institution mockInstitution = mockInstitutionSetup(); - when(institutionService.updateInstitutionById(any(), anyInt(), anyInt())).thenReturn( - mockInstitution); + when(institutionService.updateInstitutionById(any(), anyInt(), anyInt())) + .thenReturn(mockInstitution); - try (var response = resource.updateInstitution(duosUser, 1, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.updateInstitution(duosUser, 1, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(200, response.getStatus()); assertNotNull(response.getEntity().toString()); } @@ -249,8 +248,8 @@ void testUpdateInstitutionNotFound() throws Exception { Institution mockInstitution = mockInstitutionSetup(); when(institutionService.updateInstitutionById(any(), anyInt(), anyInt())).thenThrow(error); - try (var response = resource.updateInstitution(duosUser, 1, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.updateInstitution(duosUser, 1, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(404, response.getStatus()); } } @@ -262,8 +261,8 @@ void testUpdateInstiutionNullName() throws Exception { mockInstitution.setName(null); when(institutionService.updateInstitutionById(any(), anyInt(), anyInt())).thenThrow(error); - try (var response = resource.updateInstitution(duosUser, 1, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.updateInstitution(duosUser, 1, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(400, response.getStatus()); } } @@ -275,8 +274,8 @@ void testUpdateInstiutionBlankName() throws Exception { mockInstitution.setName(""); when(institutionService.updateInstitutionById(any(), anyInt(), anyInt())).thenThrow(error); - try (var response = resource.updateInstitution(duosUser, 1, - GsonUtil.getInstance().toJson(mockInstitution))) { + try (var response = + resource.updateInstitution(duosUser, 1, GsonUtil.getInstance().toJson(mockInstitution))) { assertEquals(400, response.getStatus()); } } @@ -302,42 +301,46 @@ void testDeleteInstitutionNotFound() { @Test void testUpdateInstitutionDomains() throws Exception { Institution mockInstitution = mockInstitutionSetup(); - String institutionDomainMapJson = """ + String institutionDomainMapJson = + """ { "institutionDomainMap": { "%s": ["test.edu"] } } - """.formatted(mockInstitution.getName()); - when(institutionService.findAllInstitutionsByName(mockInstitution.getName())).thenReturn( - List.of(mockInstitution)); + """ + .formatted(mockInstitution.getName()); + when(institutionService.findAllInstitutionsByName(mockInstitution.getName())) + .thenReturn(List.of(mockInstitution)); try (var response = resource.updateInstitutionDomains(duosUser, institutionDomainMapJson)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertTrue(mockInstitution.getDomains().contains("test.edu")); - verify(institutionService, times(1)).updateInstitutionById(mockInstitution, - mockInstitution.getId(), duosUser.getUserId()); + verify(institutionService, times(1)) + .updateInstitutionById(mockInstitution, mockInstitution.getId(), duosUser.getUserId()); } } @Test void testUpdateInstitutionDomainsMissingInstitution() throws Exception { Institution mockInstitution = mockInstitutionSetup(); - String institutionDomainMapJson = """ + String institutionDomainMapJson = + """ { "institutionDomainMap": { "%s": ["test.edu"] } } - """.formatted(mockInstitution.getName()); - when(institutionService.findAllInstitutionsByName(mockInstitution.getName())).thenReturn( - List.of()); + """ + .formatted(mockInstitution.getName()); + when(institutionService.findAllInstitutionsByName(mockInstitution.getName())) + .thenReturn(List.of()); try (var response = resource.updateInstitutionDomains(duosUser, institutionDomainMapJson)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); assertNull(mockInstitution.getDomains()); - verify(institutionService, never()).updateInstitutionById(mockInstitution, - mockInstitution.getId(), duosUser.getUserId()); + verify(institutionService, never()) + .updateInstitutionById(mockInstitution, mockInstitution.getId(), duosUser.getUserId()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/LibraryCardResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/LibraryCardResourceTest.java index 0c1cf198ce..29117dbcf1 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/LibraryCardResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/LibraryCardResourceTest.java @@ -38,17 +38,20 @@ class LibraryCardResourceTest { private final AuthUser authUser = new AuthUser("test@test.com"); private final List adminRoles = Collections.singletonList(UserRoles.Admin()); - private final User user = new User(1, authUser.getEmail(), "Display Name", new Date(), - adminRoles); - private final User lcUser = new User(2, "testuser@gmail.com", "Test User", new Date(), - Collections.singletonList(UserRoles.Researcher())); + private final User user = + new User(1, authUser.getEmail(), "Display Name", new Date(), adminRoles); + private final User lcUser = + new User( + 2, + "testuser@gmail.com", + "Test User", + new Date(), + Collections.singletonList(UserRoles.Researcher())); private LibraryCardResource resource; - @Mock - private UserService userService; - @Mock - private LibraryCardService libraryCardService; + @Mock private UserService userService; + @Mock private LibraryCardService libraryCardService; private LibraryCard mockLibraryCardSetup() { LibraryCard mockCard = new LibraryCard(); @@ -59,8 +62,13 @@ private LibraryCard mockLibraryCardSetup() { } private User mockSOUser() { - User mockUser = new User(2, "testuser@gmail.com", "Test User", new Date(), - Collections.singletonList(UserRoles.SigningOfficial())); + User mockUser = + new User( + 2, + "testuser@gmail.com", + "Test User", + new Date(), + Collections.singletonList(UserRoles.SigningOfficial())); return mockUser; } @@ -70,9 +78,7 @@ private void initResource() { private UnableToExecuteStatementException generateUniqueViolationException() { PSQLState uniqueViolationEnum = PSQLState.UNIQUE_VIOLATION; - PSQLException uniqueViolationException = new PSQLException( - "Error", uniqueViolationEnum - ); + PSQLException uniqueViolationException = new PSQLException("Error", uniqueViolationEnum); return new UnableToExecuteStatementException(uniqueViolationException, null); } @@ -117,8 +123,8 @@ void testGetLibraryCardByInstitutionId() { @Test void testGetLibraryCardByInstitutionIdThrowsNotFoundException() { - when(libraryCardService.findLibraryCardsByInstitutionId(anyInt())).thenThrow( - new NotFoundException()); + when(libraryCardService.findLibraryCardsByInstitutionId(anyInt())) + .thenThrow(new NotFoundException()); initResource(); Response response = resource.getLibraryCardsByInstitutionId(authUser, 1); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -129,8 +135,8 @@ void testCreateLibraryCard() throws Exception { LibraryCard mockCard = mockLibraryCardSetup(); String payload = GsonUtil.getInstance().toJson(mockCard); when(userService.findUserByEmail(authUser.getEmail())).thenReturn(user); - when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))).thenReturn( - mockCard); + when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))) + .thenReturn(mockCard); initResource(); Response response = resource.createLibraryCard(authUser, payload); String json = response.getEntity().toString(); @@ -143,8 +149,8 @@ void testCreateLibraryCardThrowsIllegalArgumentException() throws Exception { LibraryCard mockCard = mockLibraryCardSetup(); String payload = GsonUtil.getInstance().toJson(mockCard); when(userService.findUserByEmail(anyString())).thenReturn(user); - when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))).thenThrow( - new IllegalArgumentException()); + when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))) + .thenThrow(new IllegalArgumentException()); initResource(); Response response = resource.createLibraryCard(authUser, payload); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); @@ -155,8 +161,8 @@ void testCreateLibraryCardThrowsConflictException() throws Exception { UnableToExecuteStatementException exception = generateUniqueViolationException(); String json = GsonUtil.getInstance().toJson(mockLibraryCardSetup()); when(userService.findUserByEmail(anyString())).thenReturn(user); - when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))).thenThrow( - exception); + when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))) + .thenThrow(exception); initResource(); Response response = resource.createLibraryCard(authUser, json); assertEquals(HttpStatusCodes.STATUS_CODE_CONFLICT, response.getStatus()); @@ -167,8 +173,8 @@ void testCreateLibraryCardThrowsBadRequestException() throws Exception { BadRequestException exception = new BadRequestException(); String json = GsonUtil.getInstance().toJson(mockLibraryCardSetup()); when(userService.findUserByEmail(anyString())).thenReturn(user); - when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))).thenThrow( - exception); + when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))) + .thenThrow(exception); initResource(); Response response = resource.createLibraryCard(authUser, json); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); @@ -179,8 +185,8 @@ void testCreateLibraruCardThrowsNotFoundException() throws Exception { NotFoundException exception = new NotFoundException(); String json = GsonUtil.getInstance().toJson(mockLibraryCardSetup()); when(userService.findUserByEmail(anyString())).thenReturn(user); - when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))).thenThrow( - exception); + when(libraryCardService.createLibraryCard(any(LibraryCard.class), any(User.class))) + .thenThrow(exception); initResource(); Response response = resource.createLibraryCard(authUser, json); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java index bc380b189b..cc30deafec 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/MailResourceTest.java @@ -24,8 +24,7 @@ @ExtendWith(MockitoExtension.class) class MailResourceTest extends AbstractTestHelper { - @Mock - private EmailService emailService; + @Mock private EmailService emailService; private final AuthUser authUser = new AuthUser("test@test.com"); private MailResource mailResource; @@ -37,8 +36,8 @@ private void initResource() { @Test void test_MailResource() { initResource(); - when(emailService.fetchEmailMessagesByType(any(), any(), any())).thenReturn( - generateMailMessageList()); + when(emailService.fetchEmailMessagesByType(any(), any(), any())) + .thenReturn(generateMailMessageList()); Response response = mailResource.getEmailByType(authUser, EmailType.COLLECT, null, null); assertEquals(200, response.getStatus()); } @@ -54,8 +53,8 @@ void test_MailResourceEmptyListResponse() { @Test void test_MailResourceByUser() { initResource(); - when(emailService.fetchEmailMessagesByUserId(any(), any(), any())).thenReturn( - generateMailMessageList()); + when(emailService.fetchEmailMessagesByUserId(any(), any(), any())) + .thenReturn(generateMailMessageList()); Response response = mailResource.getEmailByUser(authUser, 1, null, null); assertEquals(200, response.getStatus()); } @@ -63,7 +62,8 @@ void test_MailResourceByUser() { @Test void test_MailResourceByUserEmptyListResponse() { initResource(); - when(emailService.fetchEmailMessagesByUserId(any(), any(), any())).thenReturn(new ArrayList<>()); + when(emailService.fetchEmailMessagesByUserId(any(), any(), any())) + .thenReturn(new ArrayList<>()); Response response = mailResource.getEmailByUser(authUser, 1, null, null); assertEquals(200, response.getStatus()); } @@ -71,59 +71,62 @@ void test_MailResourceByUserEmptyListResponse() { @Test void test_MailResource_date_range_EmptyListResponse() { initResource(); - when(emailService.fetchEmailMessagesByCreateDate(any(), any(), any(), any())).thenReturn( - new ArrayList<>()); - Response response = mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, - null); + when(emailService.fetchEmailMessagesByCreateDate(any(), any(), any(), any())) + .thenReturn(new ArrayList<>()); + Response response = + mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, null); assertEquals(200, response.getStatus()); } @Test void test_MailResource_date_range_ListResponse() { initResource(); - when(emailService.fetchEmailMessagesByCreateDate(any(), any(), any(), any())).thenReturn( - generateMailMessageList()); - Response response = mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, - null); + when(emailService.fetchEmailMessagesByCreateDate(any(), any(), any(), any())) + .thenReturn(generateMailMessageList()); + Response response = + mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, null); assertEquals(200, response.getStatus()); } @Test void test_MailResource_date_range_invalid_limit() { initResource(); - assertThrows(BadRequestException.class, () -> { - mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", -5, null); - }); + assertThrows( + BadRequestException.class, + () -> { + mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", -5, null); + }); } @Test void test_MailResource_date_range_invalid_offset() { initResource(); - assertThrows(BadRequestException.class, () -> { - mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, -1); - }); + assertThrows( + BadRequestException.class, + () -> { + mailResource.getEmailByDateRange(authUser, "05/11/2021", "05/11/2022", null, -1); + }); } @Test void test_MailResource_invalid_start_date() { initResource(); - Response response = mailResource.getEmailByDateRange(authUser, "55/11/2021", "05/11/2022", null, - null); + Response response = + mailResource.getEmailByDateRange(authUser, "55/11/2021", "05/11/2022", null, null); assertEquals(400, response.getStatus()); } @Test void test_MailResource_invalid_end_date() { initResource(); - Response response = mailResource.getEmailByDateRange(authUser, "05/11/2021", "65/98/20229", - null, null); + Response response = + mailResource.getEmailByDateRange(authUser, "05/11/2021", "65/98/20229", null, null); assertEquals(400, response.getStatus()); } private List generateMailMessageList() { List messageList = new ArrayList<>(); - EnumSet.allOf(EmailType.class).forEach(t -> - messageList.add(generateMailMessage(t.toString()))); + EnumSet.allOf(EmailType.class).forEach(t -> messageList.add(generateMailMessage(t.toString()))); return messageList; } @@ -137,7 +140,6 @@ private MailMessage generateMailMessage(String emailType) { randomAlphanumeric(10), randomAlphanumeric(10), nextInt(), - new Date() - ); + new Date()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java index e32af5f0f6..35c50312e1 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/MatchResourceTest.java @@ -27,8 +27,7 @@ @ExtendWith(MockitoExtension.class) class MatchResourceTest { - @Mock - private MatchService service; + @Mock private MatchService service; private final AuthUser authUser = new AuthUser("test"); private final List roles = List.of(UserRoles.Researcher()); @@ -46,8 +45,9 @@ private void initResource() { void testGetMatchesForPurpose() { initResource(); - Response response = resource.getMatchesForLatestDataAccessElectionsByPurposeIds(duosUser, - UUID.randomUUID().toString()); + Response response = + resource.getMatchesForLatestDataAccessElectionsByPurposeIds( + duosUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -61,8 +61,8 @@ void testGetMatchesForPurpose_EmptyParam() { @Test void testGetMatchesForPurpose_CommaSeparatedBlanks() { initResource(); - Response response = resource.getMatchesForLatestDataAccessElectionsByPurposeIds(duosUser, - " , , ,"); + Response response = + resource.getMatchesForLatestDataAccessElectionsByPurposeIds(duosUser, " , , ,"); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } @@ -70,12 +70,12 @@ void testGetMatchesForPurpose_CommaSeparatedBlanks() { void testGetMatchesForPurpose_PartialValidIds() { Match match = new Match(); match.setId(2); - when(service.findMatchesForLatestDataAccessElectionsByPurposeIds(anyList())).thenReturn( - List.of(match)); + when(service.findMatchesForLatestDataAccessElectionsByPurposeIds(anyList())) + .thenReturn(List.of(match)); initResource(); - Response response = resource.getMatchesForLatestDataAccessElectionsByPurposeIds(duosUser, - "3, , 5, "); + Response response = + resource.getMatchesForLatestDataAccessElectionsByPurposeIds(duosUser, "3, , 5, "); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } @@ -85,9 +85,7 @@ void testReprocessPurposeMatches() { when(service.findMatchesByPurposeId(any())).thenReturn(Collections.singletonList(new Match())); initResource(); - Response response = resource.reprocessPurposeMatches(authUser, - UUID.randomUUID().toString()); + Response response = resource.reprocessPurposeMatches(authUser, UUID.randomUUID().toString()); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/MetricsResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/MetricsResourceTest.java index fe0d232061..2ed7af8a62 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/MetricsResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/MetricsResourceTest.java @@ -18,8 +18,7 @@ @ExtendWith(MockitoExtension.class) class MetricsResourceTest { - @Mock - private MetricsService service; + @Mock private MetricsService service; private MetricsResource resource; @@ -33,7 +32,7 @@ void testGetDatasetMetricsData() { DatasetMetrics metrics = new DatasetMetrics(); when(service.generateDatasetMetrics(any())).thenReturn(metrics); - Response response = resource.getDatasetMetricsData( 1); + Response response = resource.getDatasetMetricsData(1); assertEquals(200, response.getStatus()); assertFalse(response.getEntity().toString().isEmpty()); } @@ -42,7 +41,7 @@ void testGetDatasetMetricsData() { void testGetDatasetMetricsDataNotFound() { when(service.generateDatasetMetrics(any())).thenThrow(new NotFoundException()); - Response response = resource.getDatasetMetricsData( 1); + Response response = resource.getDatasetMetricsData(1); assertEquals(404, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/NihAccountResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/NihAccountResourceTest.java index 1653e3b339..05bd3c4b1c 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/NihAccountResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/NihAccountResourceTest.java @@ -22,12 +22,9 @@ @ExtendWith(MockitoExtension.class) class NihAccountResourceTest { - @Mock - private NihService nihService; - - @Mock - private NIHUserAccount nihAccount; + @Mock private NihService nihService; + @Mock private NIHUserAccount nihAccount; private final AuthUser authUser = new AuthUser("test"); private final List roles = List.of(UserRoles.Researcher()); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/OAuth2ResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/OAuth2ResourceTest.java index a0c2a73dd6..d606e63308 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/OAuth2ResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/OAuth2ResourceTest.java @@ -23,7 +23,8 @@ class OAuth2ResourceTest { void testGetOAuth2Redirect() throws URISyntaxException { var queryParameters = new MultivaluedHashMap(); when(mockUriInfo.getQueryParameters()).thenReturn(queryParameters); - when(mockOidcService.getAuthorizationURI(queryParameters)).thenReturn(new URI("http://example.com")); + when(mockOidcService.getAuthorizationURI(queryParameters)) + .thenReturn(new URI("http://example.com")); OAuth2Resource resource = new OAuth2Resource(mockOidcService); var response = resource.getAuthorizationEndpoint(mockUriInfo); assertEquals(302, response.getStatus()); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/ResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/ResourceTest.java index fd344eb25e..880360aff9 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/ResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/ResourceTest.java @@ -34,13 +34,14 @@ void testUnableToExecuteExceptionGeneric() { @Test void testUnableToExecuteExceptionDatabaseConflict() { - PSQLException psqlException = new PSQLException( - "duplicate key value violates unique constraint", PSQLState.UNIQUE_VIOLATION); + PSQLException psqlException = + new PSQLException( + "duplicate key value violates unique constraint", PSQLState.UNIQUE_VIOLATION); StatementContext ctx = mock(StatementContext.class); StatementExceptions exceptions = mock(StatementExceptions.class); when(ctx.getConfig(StatementExceptions.class)).thenReturn(exceptions); - UnableToExecuteStatementException exception = new UnableToExecuteStatementException( - "Failed to execute statement", psqlException, ctx); + UnableToExecuteStatementException exception = + new UnableToExecuteStatementException("Failed to execute statement", psqlException, ctx); var result = Resource.unableToExecuteExceptionHandler(exception); var entity = (Error) result.getEntity(); @@ -51,15 +52,16 @@ void testUnableToExecuteExceptionDatabaseConflict() { @Test void testUnableToExecuteExceptionInvalidByteSequence() { PSQLState psqlState = mock(PSQLState.class); - // PSQLState is missing the enum constant 22021 for invalid byte sequence but returns it so we mock it + // PSQLState is missing the enum constant 22021 for invalid byte sequence but returns it so we + // mock it when(psqlState.getState()).thenReturn("22021"); - PSQLException psqlException = new PSQLException( - "invalid byte sequence for encoding \"UTF8\": 0x00", psqlState); + PSQLException psqlException = + new PSQLException("invalid byte sequence for encoding \"UTF8\": 0x00", psqlState); StatementContext ctx = mock(StatementContext.class); StatementExceptions exceptions = mock(StatementExceptions.class); when(ctx.getConfig(StatementExceptions.class)).thenReturn(exceptions); - UnableToExecuteStatementException exception = new UnableToExecuteStatementException( - "Failed to execute statement", psqlException, ctx); + UnableToExecuteStatementException exception = + new UnableToExecuteStatementException("Failed to execute statement", psqlException, ctx); var result = Resource.unableToExecuteExceptionHandler(exception); var entity = (Error) result.getEntity(); @@ -86,9 +88,11 @@ void testValidateFileDetailsFileName() { Resource abstractResource = mock(Resource.class, Mockito.CALLS_REAL_METHODS); FormDataContentDisposition fileDetail = mock(FormDataContentDisposition.class); when(fileDetail.getFileName()).thenReturn("C:\\temp\\virus.exe"); - assertThrows(IllegalArgumentException.class, () -> { - abstractResource.validateFileDetails(fileDetail); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + abstractResource.validateFileDetails(fileDetail); + }); } @Test @@ -98,9 +102,10 @@ void testValidateFileDetailsFileSize() { FormDataContentDisposition fileDetail = mock(FormDataContentDisposition.class); when(fileDetail.getFileName()).thenReturn("temp.txt"); when(fileDetail.getSize()).thenReturn(maxSize + 1); - assertThrows(IllegalArgumentException.class, () -> { - abstractResource.validateFileDetails(fileDetail); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + abstractResource.validateFileDetails(fileDetail); + }); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/SamResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/SamResourceTest.java index a06f8c6cad..8ed32cb1ec 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/SamResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/SamResourceTest.java @@ -32,17 +32,13 @@ @ExtendWith(MockitoExtension.class) class SamResourceTest { - @Mock - private DuosUser duosUser; + @Mock private DuosUser duosUser; - @Mock - private SamService samService; + @Mock private SamService samService; - @Mock - private UserService userService; + @Mock private UserService userService; - @Mock - private UriInfo uriInfo; + @Mock private UriInfo uriInfo; private SamResource resource; @@ -52,22 +48,25 @@ private void initResource() { @Test void testGetResourceTypes() throws Exception { - ActionPattern pattern = new ActionPattern() - .setAuthDomainConstrainable(true) - .setDescription("description") - .setValue("value"); - ResourceTypeRole role = new ResourceTypeRole() - .setRoleName("roleName") - .setActions(Collections.singletonList("action")) - .setDescendantRoles(Collections.emptyMap()) - .setIncludedRoles(Collections.emptyList()) - .setIncludedRoles(Collections.emptyList()); - ResourceType type = new ResourceType() - .setName("name") - .setReuseIds(true) - .setOwnerRoleName("ownerRoleName") - .setActionPatterns(Collections.singletonList(pattern)) - .setRoles(Collections.singletonList(role)); + ActionPattern pattern = + new ActionPattern() + .setAuthDomainConstrainable(true) + .setDescription("description") + .setValue("value"); + ResourceTypeRole role = + new ResourceTypeRole() + .setRoleName("roleName") + .setActions(Collections.singletonList("action")) + .setDescendantRoles(Collections.emptyMap()) + .setIncludedRoles(Collections.emptyList()) + .setIncludedRoles(Collections.emptyList()); + ResourceType type = + new ResourceType() + .setName("name") + .setReuseIds(true) + .setOwnerRoleName("ownerRoleName") + .setActionPatterns(Collections.singletonList(pattern)) + .setRoles(Collections.singletonList(role)); when(samService.getResourceTypes(any())).thenReturn(Collections.singletonList(type)); initResource(); Response response = resource.getResourceTypes(duosUser); @@ -76,10 +75,10 @@ void testGetResourceTypes() throws Exception { @Test void testPostRegistrationInfo() throws Exception { - UserStatus.UserInfo info = new UserStatus.UserInfo().setUserEmail("test@test.org") - .setUserSubjectId("subjectId"); - UserStatus.Enabled enabled = new UserStatus.Enabled().setAllUsersGroup(true).setGoogle(true) - .setLdap(true); + UserStatus.UserInfo info = + new UserStatus.UserInfo().setUserEmail("test@test.org").setUserSubjectId("subjectId"); + UserStatus.Enabled enabled = + new UserStatus.Enabled().setAllUsersGroup(true).setGoogle(true).setLdap(true); UserStatus status = new UserStatus().setUserInfo(info).setEnabled(enabled); when(samService.postRegistrationInfo(any())).thenReturn(status); initResource(); @@ -89,12 +88,13 @@ void testPostRegistrationInfo() throws Exception { @Test void testGetSelfDiagnostics() throws Exception { - UserStatusDiagnostics diagnostics = new UserStatusDiagnostics() - .setAdminEnabled(RandomUtils.nextBoolean()) - .setEnabled(RandomUtils.nextBoolean()) - .setInAllUsersGroup(RandomUtils.nextBoolean()) - .setInGoogleProxyGroup(RandomUtils.nextBoolean()) - .setTosAccepted(RandomUtils.nextBoolean()); + UserStatusDiagnostics diagnostics = + new UserStatusDiagnostics() + .setAdminEnabled(RandomUtils.nextBoolean()) + .setEnabled(RandomUtils.nextBoolean()) + .setInAllUsersGroup(RandomUtils.nextBoolean()) + .setInGoogleProxyGroup(RandomUtils.nextBoolean()) + .setTosAccepted(RandomUtils.nextBoolean()); when(samService.getSelfDiagnostics(any())).thenReturn(diagnostics); initResource(); Response response = resource.getSelfDiagnostics(duosUser); @@ -103,11 +103,12 @@ void testGetSelfDiagnostics() throws Exception { @Test void testGetRegistrationInfo() throws Exception { - UserStatusInfo userInfo = new UserStatusInfo() - .setAdminEnabled(RandomUtils.nextBoolean()) - .setUserEmail("test@test.org") - .setUserSubjectId(RandomStringUtils.random(10, false, true)) - .setEnabled(RandomUtils.nextBoolean()); + UserStatusInfo userInfo = + new UserStatusInfo() + .setAdminEnabled(RandomUtils.nextBoolean()) + .setUserEmail("test@test.org") + .setUserSubjectId(RandomStringUtils.random(10, false, true)) + .setEnabled(RandomUtils.nextBoolean()); when(samService.getRegistrationInfo(any())).thenReturn(userInfo); initResource(); Response response = resource.getRegistrationInfo(duosUser); @@ -153,5 +154,4 @@ void testRemoveSelfTos() throws Exception { Response response = resource.removeTos(duosUser); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/SchemaResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/SchemaResourceTest.java index 6e4c7b879d..7c3da0f2ad 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/SchemaResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/SchemaResourceTest.java @@ -12,7 +12,6 @@ @ExtendWith(MockitoExtension.class) class SchemaResourceTest { - private final JsonSchemaUtil jsonSchemaUtil = new JsonSchemaUtil(); @Test @@ -25,5 +24,4 @@ void testGetDatasetRegistrationSchemaV1() { Object body = response.getEntity(); assertEquals(jsonSchemaUtil.getDatasetRegistrationSchemaV1(), body.toString()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/StatusResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/StatusResourceTest.java index ec17bd2ad1..71f7a3ec42 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/StatusResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/StatusResourceTest.java @@ -19,8 +19,7 @@ @ExtendWith(MockitoExtension.class) class StatusResourceTest { - @Mock - private HealthCheckRegistry healthChecks; + @Mock private HealthCheckRegistry healthChecks; private StatusResource initStatusResource(SortedMap checks) { when(healthChecks.runHealthChecks()).thenReturn(checks); @@ -40,8 +39,8 @@ void testHealthy() { @Test void testUnhealthyDatabase() { - Result postgresql = Result.unhealthy( - new Exception("Cannot connect to the postgresql database")); + Result postgresql = + Result.unhealthy(new Exception("Cannot connect to the postgresql database")); SortedMap checks = new TreeMap<>(); checks.put(DB_ENV, postgresql); checks.put(ConsentApplication.ONTOLOGY_CHECK, Result.healthy()); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java index a214e217a0..3190245008 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/StudyResourceTest.java @@ -49,39 +49,33 @@ @ExtendWith(MockitoExtension.class) class StudyResourceTest extends AbstractTestHelper { - @Mock - private DatasetService datasetService; + @Mock private DatasetService datasetService; - @Mock - private DatasetRegistrationService datasetRegistrationService; + @Mock private DatasetRegistrationService datasetRegistrationService; - @Mock - private UserService userService; + @Mock private UserService userService; - @Mock - private ElasticSearchService elasticSearchService; + @Mock private ElasticSearchService elasticSearchService; - @Mock - private AuthUser authUser; + @Mock private AuthUser authUser; - @Mock - private User user; + @Mock private User user; - @Mock - private DuosUser duosUser; + @Mock private DuosUser duosUser; private StudyResource resource; @BeforeEach void setUp() { - resource = new StudyResource(datasetService, userService, datasetRegistrationService, - elasticSearchService); + resource = + new StudyResource( + datasetService, userService, datasetRegistrationService, elasticSearchService); } @Test void testUpdateCustodiansSuccess() { - try (var response = resource.updateCustodians(authUser, 1, - "[\"user_1@test.com\", \"user_2@test.com\"]")) { + try (var response = + resource.updateCustodians(authUser, 1, "[\"user_1@test.com\", \"user_2@test.com\"]")) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -95,11 +89,11 @@ void testUpdateCustodiansInvalidEmails() { @Test void testUpdateCustodiansNotFound() { - when(datasetService.updateStudyCustodians(any(), any(), any())).thenThrow( - new NotFoundException("Study not found")); + when(datasetService.updateStudyCustodians(any(), any(), any())) + .thenThrow(new NotFoundException("Study not found")); - try (var response = resource.updateCustodians(authUser, 1, - "[\"user_1@test.com\", \"user_2@test.com\"]")) { + try (var response = + resource.updateCustodians(authUser, 1, "[\"user_1@test.com\", \"user_2@test.com\"]")) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -149,7 +143,8 @@ void testGetStudyByIdWithDatasets() { @Test void testGetStudyByIdNotFound() { - when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), 1)).thenThrow(new NotFoundException()); + when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), 1)) + .thenThrow(new NotFoundException()); try (var response = resource.getStudyById(duosUser, 1)) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -163,7 +158,8 @@ void testGetStudyByIdNotPublicGeneralUser() { User generalUser = new User(); generalUser.setUserId(randomInt(1000, 1100)); when(duosUser.getUser()).thenReturn(generalUser); - when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(generalUser, study)).thenReturn(false); try (var response = resource.getStudyById(duosUser, study.getStudyId())) { @@ -178,7 +174,8 @@ void testGetStudyByIdNotPublicCreateUser() { User createUser = new User(); createUser.setUserId(study.getCreateUserId()); when(duosUser.getUser()).thenReturn(createUser); - when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = resource.getStudyById(duosUser, study.getStudyId())) { @@ -214,7 +211,8 @@ void testGetRegistrationFromStudyNoDatasets() { @Test void testGetRegistrationFromStudyNotFound() { Study study = createMockStudy(); - when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())).thenThrow(new NotFoundException()); + when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())) + .thenThrow(new NotFoundException()); try (var response = resource.getRegistrationFromStudy(duosUser, study.getStudyId())) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -228,7 +226,8 @@ void testGetRegistrationFromStudyNotPublicGeneralUser() { User generalUser = new User(); generalUser.setUserId(randomInt(1000, 1100)); when(duosUser.getUser()).thenReturn(generalUser); - when(datasetService.getStudyWithDatasetsById(generalUser, study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(generalUser, study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(generalUser, study)).thenReturn(false); try (var response = resource.getRegistrationFromStudy(duosUser, study.getStudyId())) { @@ -243,7 +242,8 @@ void testGetRegistrationFromStudyNotPublicCreateUser() { User createUser = new User(); createUser.setUserId(study.getCreateUserId()); when(duosUser.getUser()).thenReturn(createUser); - when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(duosUser.getUser(), study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); try (var response = resource.getRegistrationFromStudy(duosUser, study.getStudyId())) { @@ -252,23 +252,24 @@ void testGetRegistrationFromStudyNotPublicCreateUser() { } @ParameterizedTest - @ValueSource(strings = { - DataResourceTestData.registrationWithMalformedJson, - DataResourceTestData.registrationWithStudyName, - DataResourceTestData.registrationWithDataSubmitterUserId, - DataResourceTestData.registrationWithExistingCGDataUse, - DataResourceTestData.registrationWithExistingCG - }) + @ValueSource( + strings = { + DataResourceTestData.registrationWithMalformedJson, + DataResourceTestData.registrationWithStudyName, + DataResourceTestData.registrationWithDataSubmitterUserId, + DataResourceTestData.registrationWithExistingCGDataUse, + DataResourceTestData.registrationWithExistingCG + }) void testUpdateStudyByRegistrationInvalidInput(String input) { Study study = createMockStudy(); // for DataResourceTestData.registrationWithExistingCG, manipulate the dataset ids to simulate // a dataset deletion if (input.equals(DataResourceTestData.registrationWithExistingCG)) { Gson gson = GsonUtil.gsonBuilderWithAdapters().create(); - DatasetRegistrationSchemaV1 schemaV1 = gson.fromJson(input, - DatasetRegistrationSchemaV1.class); - List datasetIds = schemaV1.getConsentGroups().stream() - .map(ConsentGroup::getDatasetId).toList(); + DatasetRegistrationSchemaV1 schemaV1 = + gson.fromJson(input, DatasetRegistrationSchemaV1.class); + List datasetIds = + schemaV1.getConsentGroups().stream().map(ConsentGroup::getDatasetId).toList(); study.addDatasetIds(Set.of(datasetIds.get(0) + 1)); } when(userService.findUserByEmail(any())).thenReturn(user); @@ -280,7 +281,8 @@ void testUpdateStudyByRegistrationInvalidInput(String input) { when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); - try (var response = resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + try (var response = + resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -291,12 +293,11 @@ void testUpdateStudyByRegistrationCreatorOrCustodian() { Study study = createMockStudy(); Gson gson = GsonUtil.gsonBuilderWithAdapters().create(); DatasetRegistrationSchemaV1 schemaV1 = gson.fromJson(input, DatasetRegistrationSchemaV1.class); - Set datasetIds = schemaV1 - .getConsentGroups() - .stream() - .map(ConsentGroup::getDatasetId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + Set datasetIds = + schemaV1.getConsentGroups().stream() + .map(ConsentGroup::getDatasetId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); study.getDatasetIds().clear(); study.addDatasetIds(datasetIds); User createUser = new User(); @@ -307,7 +308,8 @@ void testUpdateStudyByRegistrationCreatorOrCustodian() { when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); - try (var response = resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + try (var response = + resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -318,12 +320,11 @@ void testUpdateStudyByRegistrationAdmin() { Study study = createMockStudy(); Gson gson = GsonUtil.gsonBuilderWithAdapters().create(); DatasetRegistrationSchemaV1 schemaV1 = gson.fromJson(input, DatasetRegistrationSchemaV1.class); - Set datasetIds = schemaV1 - .getConsentGroups() - .stream() - .map(ConsentGroup::getDatasetId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + Set datasetIds = + schemaV1.getConsentGroups().stream() + .map(ConsentGroup::getDatasetId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); study.getDatasetIds().clear(); study.addDatasetIds(datasetIds); User createUser = new User(); @@ -335,7 +336,8 @@ void testUpdateStudyByRegistrationAdmin() { when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(true); - try (var response = resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + try (var response = + resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -346,12 +348,11 @@ void testUpdateStudyByRegistrationNotCreatorOrAdmin() { Study study = createMockStudy(); Gson gson = GsonUtil.gsonBuilderWithAdapters().create(); DatasetRegistrationSchemaV1 schemaV1 = gson.fromJson(input, DatasetRegistrationSchemaV1.class); - Set datasetIds = schemaV1 - .getConsentGroups() - .stream() - .map(ConsentGroup::getDatasetId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + Set datasetIds = + schemaV1.getConsentGroups().stream() + .map(ConsentGroup::getDatasetId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); study.getDatasetIds().clear(); study.addDatasetIds(datasetIds); User createUser = new User(); @@ -363,7 +364,8 @@ void testUpdateStudyByRegistrationNotCreatorOrAdmin() { when(datasetRegistrationService.findStudyById(study.getStudyId())).thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(createUser, study)).thenReturn(false); - try (var response = resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { + try (var response = + resource.updateStudyByRegistration(authUser, null, study.getStudyId(), input)) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } } @@ -444,7 +446,6 @@ void testDeleteStudyByIdNullDatasets() throws Exception { } } - @Test void testDeleteStudyByIdNoDatasets() throws Exception { Study study = createMockStudy(); @@ -479,7 +480,6 @@ void testDeleteStudyByIdElasticSearchFailure() throws Exception { } } - /* * Study mock */ @@ -548,7 +548,8 @@ void testCheckPublicVisibilityForUser_PublicStudy_ApprovedRole() { study.setPublicVisibility(true); User approvedUser = new User(); approvedUser.setUserId(study.getCreateUserId()); - when(datasetService.getStudyWithDatasetsById(approvedUser, study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(approvedUser, study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(approvedUser, study)).thenReturn(true); when(duosUser.getUser()).thenReturn(approvedUser); @@ -563,7 +564,8 @@ void testCheckPublicVisibilityForUser_PublicStudy_NoApprovedRole() { study.setPublicVisibility(true); User generalUser = new User(); generalUser.setUserId(randomInt(1000, 1100)); - when(datasetService.getStudyWithDatasetsById(generalUser, study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(generalUser, study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(generalUser, study)).thenReturn(false); when(duosUser.getUser()).thenReturn(generalUser); @@ -624,7 +626,8 @@ void testCheckPublicVisibilityForUser_PrivateStudy_NoApprovedRole() { study.setPublicVisibility(false); User generalUser = new User(); generalUser.setUserId(randomInt(1000, 1100)); - when(datasetService.getStudyWithDatasetsById(generalUser, study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(generalUser, study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(generalUser, study)).thenReturn(false); when(duosUser.getUser()).thenReturn(generalUser); @@ -639,7 +642,8 @@ void testCheckPublicVisibilityForUser_PublicVisibilityNull_CausesError() { study.setPublicVisibility(null); User approvedUser = new User(); approvedUser.setUserId(study.getCreateUserId()); - when(datasetService.getStudyWithDatasetsById(approvedUser, study.getStudyId())).thenReturn(study); + when(datasetService.getStudyWithDatasetsById(approvedUser, study.getStudyId())) + .thenReturn(study); when(datasetService.isCreatorCustodianOrAdmin(approvedUser, study)).thenReturn(true); when(duosUser.getUser()).thenReturn(approvedUser); diff --git a/src/test/java/org/broadinstitute/consent/http/resources/SupportResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/SupportResourceTest.java index 99113938bc..abe4c432e9 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/SupportResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/SupportResourceTest.java @@ -27,8 +27,7 @@ @ExtendWith(MockitoExtension.class) public class SupportResourceTest extends ResourceTest { - @Mock - private SupportRequestService supportRequestService; + @Mock private SupportRequestService supportRequestService; private SupportResource supportResource; @@ -40,7 +39,8 @@ public void setUp() { @ParameterizedTest @EnumSource(SupportRequestType.class) void testPostRequestSuccess(SupportRequestType type) throws Exception { - String body = """ + String body = + """ { "name": "Test User", "email": "test.user@example.com", @@ -53,7 +53,8 @@ void testPostRequestSuccess(SupportRequestType type) throws Exception { "token2", ] } - """.formatted(type); + """ + .formatted(type); when(supportRequestService.postTicketToSupport(any())).thenReturn(new Request()); try (Response response = supportResource.postRequest(body)) { assertEquals(HttpStatusCodes.STATUS_CODE_CREATED, response.getStatus()); @@ -62,7 +63,8 @@ void testPostRequestSuccess(SupportRequestType type) throws Exception { private static Stream testPostRequestInvalidFields() { return Stream.of( - Arguments.of(""" + Arguments.of( + """ { "email": "test.user@example.com", "subject": "Test Subject", @@ -72,7 +74,8 @@ private static Stream testPostRequestInvalidFields() { "uploads": ["token1", "token2"] } """), - Arguments.of(""" + Arguments.of( + """ { "name": "Test User", "subject": "Test Subject", @@ -82,7 +85,8 @@ private static Stream testPostRequestInvalidFields() { "uploads": ["token1", "token2"] } """), - Arguments.of(""" + Arguments.of( + """ { "name": "Test User", "email": "test.user@example.com", @@ -92,7 +96,8 @@ private static Stream testPostRequestInvalidFields() { "uploads": ["token1", "token2"] } """), - Arguments.of(""" + Arguments.of( + """ { "name": "Test User", "email": "test.user@example.com", @@ -102,7 +107,8 @@ private static Stream testPostRequestInvalidFields() { "uploads": ["token1", "token2"] } """), - Arguments.of(""" + Arguments.of( + """ { "name": "Test User", "email": "test.user@example.com", @@ -112,7 +118,8 @@ private static Stream testPostRequestInvalidFields() { "uploads": ["token1", "token2"] } """), - Arguments.of(""" + Arguments.of( + """ { "name": "Test User", "email": "test.user@example.com", @@ -121,8 +128,7 @@ private static Stream testPostRequestInvalidFields() { "type": "QUESTION", "uploads": ["token1", "token2"] } - """) - ); + """)); } @ParameterizedTest @@ -135,9 +141,12 @@ void testPostRequestInvalidFields(String body) { @Test void testUnprocessableTicket() throws Exception { - doThrow(new UnprocessableEntityException("Unprocessable")).when(supportRequestService) + doThrow(new UnprocessableEntityException("Unprocessable")) + .when(supportRequestService) .postTicketToSupport(any()); - try (Response response = supportResource.postRequest(""" + try (Response response = + supportResource.postRequest( + """ { "name": "Test User", "email": "test.user@example.com", @@ -164,11 +173,11 @@ void testPostUpload() throws Exception { @Test void testUnprocessableUpload() throws Exception { - doThrow(new UnprocessableEntityException("Unprocessable")).when(supportRequestService) + doThrow(new UnprocessableEntityException("Unprocessable")) + .when(supportRequestService) .postAttachmentToSupport(any()); try (Response response = supportResource.postUpload("test".getBytes())) { assertEquals(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY, response.getStatus()); } } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/SwaggerResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/SwaggerResourceTest.java index a0c2723145..f2f4d31dcc 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/SwaggerResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/SwaggerResourceTest.java @@ -32,8 +32,7 @@ void setUp() { void testIndex() { Response response = swaggerResource.content("index.html"); assertTrue(checkStatusAndHeader(response, TEXT_HTML)); - String content = response.getEntity().toString() - .replaceFirst("", "").trim(); + String content = response.getEntity().toString().replaceFirst("", "").trim(); assertTrue(content.startsWith("")); assertTrue(content.endsWith("")); } @@ -72,5 +71,4 @@ private boolean checkStatusAndHeader(Response response, String header) { String headerObject = response.getHeaderString(HttpHeaders.CONTENT_TYPE); return headerObject.contains(header); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/TDRResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/TDRResourceTest.java index 121ec81b78..43124b896b 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/TDRResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/TDRResourceTest.java @@ -24,17 +24,13 @@ @ExtendWith(MockitoExtension.class) class TDRResourceTest { - @Mock - private TDRService tdrService; - @Mock - private DatasetService datasetService; + @Mock private TDRService tdrService; + @Mock private DatasetService datasetService; private TDRResource resource; - @Mock - private User user; + @Mock private User user; - @Mock - private DuosUser duosUser; + @Mock private DuosUser duosUser; private void initResource() { try { @@ -47,9 +43,8 @@ private void initResource() { @Test void testGetApprovedUsersForDataset() { String ds = "DUOS-00003"; - List users = List.of( - new ApprovedUser("asdf1@gmail.com"), - new ApprovedUser("asdf2@gmail.com")); + List users = + List.of(new ApprovedUser("asdf1@gmail.com"), new ApprovedUser("asdf2@gmail.com")); ApprovedUsers approvedUsers = new ApprovedUsers(users); Dataset d = new Dataset(); @@ -97,7 +92,6 @@ void testGetDatasetByIdentifier() { assertEquals(GsonUtil.buildGson().toJson(d), r.getEntity()); } - @Test void testGetDatasetByIdentifier404() { when(duosUser.getUser()).thenReturn(user); @@ -109,5 +103,4 @@ void testGetDatasetByIdentifier404() { assertEquals(404, r.getStatus()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/TosResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/TosResourceTest.java index b957289e10..17a55af5eb 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/TosResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/TosResourceTest.java @@ -15,8 +15,7 @@ @ExtendWith(MockitoExtension.class) class TosResourceTest { - @Mock - private SamService service; + @Mock private SamService service; private TosResource resource; diff --git a/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java index 764e1874e1..644372b0f5 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/UserResourceTest.java @@ -60,49 +60,44 @@ @ExtendWith(MockitoExtension.class) class UserResourceTest extends AbstractTestHelper { - @Mock - private UserService userService; + @Mock private UserService userService; - @Mock - private SamService samService; + @Mock private SamService samService; - @Mock - private DatasetService datasetService; + @Mock private DatasetService datasetService; private UserResource userResource; - @Mock - private UriInfo uriInfo; + @Mock private UriInfo uriInfo; - @Mock - private UriBuilder uriBuilder; + @Mock private UriBuilder uriBuilder; - @Mock - private UserStatusInfo userStatusInfo; + @Mock private UserStatusInfo userStatusInfo; - @Mock - private AcknowledgementService acknowledgementService; + @Mock private AcknowledgementService acknowledgementService; - @Mock - private NihService nihService; + @Mock private NihService nihService; private static final String TEST_EMAIL = "test@gmail.com"; private final Gson gson = GsonUtil.getInstance(); - private final AuthUser authUser = new AuthUser() - .setAuthToken("auth-token") - .setName("Test User") - .setEmail(TEST_EMAIL) - .setUserStatusInfo(userStatusInfo); + private final AuthUser authUser = + new AuthUser() + .setAuthToken("auth-token") + .setName("Test User") + .setEmail(TEST_EMAIL) + .setUserStatusInfo(userStatusInfo); - private final DuosUser duosUser = new DuosUser(authUser, - new User(1, TEST_EMAIL, "Test User", new Date(), Collections.emptyList())); + private final DuosUser duosUser = + new DuosUser( + authUser, new User(1, TEST_EMAIL, "Test User", new Date(), Collections.emptyList())); @BeforeEach void initResource() { - userResource = new UserResource(samService, userService, datasetService, acknowledgementService, - nihService); + userResource = + new UserResource( + samService, userService, datasetService, acknowledgementService, nihService); } @Test @@ -125,8 +120,8 @@ void testGetUserById() { @Test void testGetUserByIdNotFound() { - when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())).thenThrow( - new NotFoundException()); + when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())) + .thenThrow(new NotFoundException()); Response response = userResource.getUserById(duosUser, 1); assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus()); @@ -137,8 +132,8 @@ void testGetUsers_SO() { User user = createUserWithRole(); user.setSigningOfficialRole(); when(userService.findUserByEmail(any())).thenReturn(user); - when(userService.getUsersAsRole(user, "SigningOfficial")).thenReturn( - Arrays.asList(new User(), new User())); + when(userService.getUsersAsRole(user, "SigningOfficial")) + .thenReturn(Arrays.asList(new User(), new User())); Response response = userResource.getUsers(authUser, "SigningOfficial"); assertEquals(Status.OK.getStatusCode(), response.getStatus()); @@ -158,8 +153,8 @@ void testGetUsers_Admin() { User user = createUserWithRole(); user.setAdminRole(); when(userService.findUserByEmail(any())).thenReturn(user); - when(userService.getUsersAsRole(user, "Admin")).thenReturn( - Arrays.asList(new User(), new User())); + when(userService.getUsersAsRole(user, "Admin")) + .thenReturn(Arrays.asList(new User(), new User())); Response response = userResource.getUsers(authUser, "Admin"); assertEquals(Status.OK.getStatusCode(), response.getStatus()); @@ -245,7 +240,8 @@ void testAddRoleToUser() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ADMIN.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ADMIN.getRoleId())) { assertEquals(200, response.getStatus()); } } @@ -257,7 +253,8 @@ void testAddRoleToUserNotFound() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); doThrow(new NotFoundException()).when(userService).findUserById(any()); - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ADMIN.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ADMIN.getRoleId())) { assertEquals(404, response.getStatus()); } } @@ -270,8 +267,8 @@ void testAddRoleToUserNotModified() { User user = createUserWithRole(); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.RESEARCHER.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.RESEARCHER.getRoleId())) { assertEquals(304, response.getStatus()); } } @@ -295,8 +292,8 @@ void testAddRoleToUserBySoWithoutUserAndSoInstitution() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.DATASUBMITTER.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.DATASUBMITTER.getRoleId())) { assertEquals(400, response.getStatus()); } } @@ -310,8 +307,8 @@ void testAddRoleToUserBySoInstitutionWithoutUserInstitution() { User user = createUserWithRole(); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.DATASUBMITTER.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.DATASUBMITTER.getRoleId())) { assertEquals(200, response.getStatus()); } } @@ -325,8 +322,8 @@ void testAddRoleToUserBySoWithoutSoInstitution() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.DATASUBMITTER.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.DATASUBMITTER.getRoleId())) { assertEquals(400, response.getStatus()); } } @@ -341,24 +338,24 @@ void testAddRoleToUserBySoWithDeniedRoles() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), user); when(userService.findUserById(any())).thenReturn(user); - - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ADMIN.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ADMIN.getRoleId())) { assertEquals(400, response.getStatus()); } - try (Response response2 = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.RESEARCHER.getRoleId())) { + try (Response response2 = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.RESEARCHER.getRoleId())) { assertEquals(400, response2.getStatus()); } - try (Response response3 = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.MEMBER.getRoleId())) { + try (Response response3 = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.MEMBER.getRoleId())) { assertEquals(400, response3.getStatus()); } - try (Response response4 = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.CHAIRPERSON.getRoleId())) { + try (Response response4 = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.CHAIRPERSON.getRoleId())) { assertEquals(400, response4.getStatus()); } - try (Response response5 = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.ALUMNI.getRoleId())) { + try (Response response5 = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ALUMNI.getRoleId())) { assertEquals(400, response5.getStatus()); } } @@ -373,16 +370,16 @@ void testAddRoleToUserBySoWithPermittedRoles() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.DATASUBMITTER.getRoleId())) { + try (Response response = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.DATASUBMITTER.getRoleId())) { assertEquals(200, response.getStatus()); } - try (Response response2 = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.ITDIRECTOR.getRoleId())) { + try (Response response2 = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ITDIRECTOR.getRoleId())) { assertEquals(200, response2.getStatus()); } - try (Response response3 = userResource.addRoleToUser(activeDuosUser, 1, - UserRoles.ITDIRECTOR.getRoleId())) { + try (Response response3 = + userResource.addRoleToUser(activeDuosUser, 1, UserRoles.ITDIRECTOR.getRoleId())) { assertEquals(200, response3.getStatus()); } } @@ -393,8 +390,9 @@ void testGetSOsForInstitution() { User user = createUserWithInstitution(); User so = createUserWithRole(); when(userService.findUserByEmail(any())).thenReturn(user); - when(userService.findSOsByInstitutionId(any())).thenReturn( - Arrays.asList(new UserService.SimplifiedUser(so), new UserService.SimplifiedUser(so))); + when(userService.findSOsByInstitutionId(any())) + .thenReturn( + Arrays.asList(new UserService.SimplifiedUser(so), new UserService.SimplifiedUser(so))); Response response = userResource.getSOsForInstitution(authUser); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); @@ -443,8 +441,7 @@ void testGetUsersByInstitutionNoInstitution() { @Test void testGetUsersByInstitutionNullInstitution() { - doThrow(new IllegalArgumentException()).when(userService) - .findUsersByInstitutionId(null); + doThrow(new IllegalArgumentException()).when(userService).findUsersByInstitutionId(null); Response response = userResource.getUsersByInstitution(authUser, null); assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); @@ -467,8 +464,8 @@ void testUpdateSelf() { when(userService.findUserWithPropertiesByIdAsJsonObject(localDuosUser, user.getUserId())) .thenReturn(gson.toJsonTree(user).getAsJsonObject()); - try (Response response = userResource.updateSelf(localDuosUser, uriInfo, - gson.toJson(userUpdateFields))) { + try (Response response = + userResource.updateSelf(localDuosUser, uriInfo, gson.toJson(userUpdateFields))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -476,15 +473,16 @@ void testUpdateSelf() { @Test void testUpdateSelfInvalidName() { PSQLState psqlState = mock(PSQLState.class); - // PSQLState is missing the enum constant 22021 for invalid byte sequence but returns it so we mock it + // PSQLState is missing the enum constant 22021 for invalid byte sequence but returns it so we + // mock it when(psqlState.getState()).thenReturn("22021"); - PSQLException psqlException = new PSQLException( - "invalid byte sequence for encoding \"UTF8\": 0x00", psqlState); + PSQLException psqlException = + new PSQLException("invalid byte sequence for encoding \"UTF8\": 0x00", psqlState); StatementContext ctx = mock(StatementContext.class); StatementExceptions exceptions = mock(StatementExceptions.class); when(ctx.getConfig(StatementExceptions.class)).thenReturn(exceptions); - UnableToExecuteStatementException exception = new UnableToExecuteStatementException( - "Failed to execute statement", psqlException, ctx); + UnableToExecuteStatementException exception = + new UnableToExecuteStatementException("Failed to execute statement", psqlException, ctx); User user = createUserWithRole(); String invalidName = "invalid\0name"; @@ -492,7 +490,9 @@ void testUpdateSelfInvalidName() { userUpdateFields.setDisplayName(invalidName); when(userService.updateUserFieldsById(any(), any())).thenThrow(exception); - try (var response = userResource.updateSelf(new DuosUser(authUser, user), uriInfo, gson.toJson(userUpdateFields))) { + try (var response = + userResource.updateSelf( + new DuosUser(authUser, user), uriInfo, gson.toJson(userUpdateFields))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -503,7 +503,9 @@ void testUpdateSelfRolesNotAdmin() { UserUpdateFields userUpdateFields = new UserUpdateFields(); userUpdateFields.setUserRoleIds(List.of(1)); // any roles - try (var response = userResource.updateSelf(new DuosUser(authUser, user), uriInfo, gson.toJson(userUpdateFields))) { + try (var response = + userResource.updateSelf( + new DuosUser(authUser, user), uriInfo, gson.toJson(userUpdateFields))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -514,11 +516,11 @@ void testUpdate() { UserUpdateFields userUpdateFields = new UserUpdateFields(); when(userService.findUserById(any())).thenReturn(user); when(userService.updateUserFieldsById(any(), any())).thenReturn(user); - when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())).thenReturn( - gson.toJsonTree(user).getAsJsonObject()); + when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())) + .thenReturn(gson.toJsonTree(user).getAsJsonObject()); - try (Response response = userResource.update(duosUser, user.getUserId(), - gson.toJson(userUpdateFields))) { + try (Response response = + userResource.update(duosUser, user.getUserId(), gson.toJson(userUpdateFields))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } @@ -551,12 +553,13 @@ void testDeleteRoleFromUser() { activeUser.setAdminRole(); when(userService.findUserById(any())).thenReturn(user); JsonElement userJson = gson.toJsonTree(user); - when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())).thenReturn( - userJson.getAsJsonObject()); + when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())) + .thenReturn(userJson.getAsJsonObject()); DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); User returnedUser; - try (Response response = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.RESEARCHER.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.RESEARCHER.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); returnedUser = new User((String) response.getEntity()); } @@ -600,24 +603,26 @@ void testDeleteDeniedRoleBySoShouldFail() { activeUser.setInstitutionId(10); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.deleteRoleFromUser(duosUser, user.getUserId(), - UserRoles.ADMIN.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser(duosUser, user.getUserId(), UserRoles.ADMIN.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } - try (Response response2 = userResource.deleteRoleFromUser(duosUser, user.getUserId(), - UserRoles.RESEARCHER.getRoleId())) { + try (Response response2 = + userResource.deleteRoleFromUser( + duosUser, user.getUserId(), UserRoles.RESEARCHER.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response2.getStatus()); } - try (Response response3 = userResource.deleteRoleFromUser(duosUser, user.getUserId(), - UserRoles.CHAIRPERSON.getRoleId())) { + try (Response response3 = + userResource.deleteRoleFromUser( + duosUser, user.getUserId(), UserRoles.CHAIRPERSON.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response3.getStatus()); } - try (Response response4 = userResource.deleteRoleFromUser(duosUser, user.getUserId(), - UserRoles.MEMBER.getRoleId())) { + try (Response response4 = + userResource.deleteRoleFromUser(duosUser, user.getUserId(), UserRoles.MEMBER.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response4.getStatus()); } - try (Response response5 = userResource.deleteRoleFromUser(duosUser, user.getUserId(), - UserRoles.ALUMNI.getRoleId())) { + try (Response response5 = + userResource.deleteRoleFromUser(duosUser, user.getUserId(), UserRoles.ALUMNI.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response5.getStatus()); assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response5.getStatus()); } @@ -638,16 +643,19 @@ void testDeletePermittedRolesBySoShouldSucceedForUserWithSameInstitution() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.ITDIRECTOR.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.ITDIRECTOR.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } - try (Response response2 = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.DATASUBMITTER.getRoleId())) { + try (Response response2 = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.DATASUBMITTER.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response2.getStatus()); } - try (Response response3 = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.SIGNINGOFFICIAL.getRoleId())) { + try (Response response3 = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.SIGNINGOFFICIAL.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response3.getStatus()); } } @@ -666,19 +674,21 @@ void testDeletePermittedRolesBySoShouldFailForUserWitNullInstitution() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.ITDIRECTOR.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.ITDIRECTOR.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } - try (Response response2 = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.DATASUBMITTER.getRoleId())) { + try (Response response2 = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.DATASUBMITTER.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response2.getStatus()); } - try (Response response3 = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.SIGNINGOFFICIAL.getRoleId())) { + try (Response response3 = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.SIGNINGOFFICIAL.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response3.getStatus()); } - } @Test @@ -695,8 +705,9 @@ void testDeleteSORoleFromSOInOtherOrgSOShouldFail() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenReturn(user); - try (Response response = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.SIGNINGOFFICIAL.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.SIGNINGOFFICIAL.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, response.getStatus()); } } @@ -709,9 +720,9 @@ void testDeleteSORoleFromSelfShouldFail() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), user); when(userService.findUserById(any())).thenReturn(user); - - try (Response response = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.SIGNINGOFFICIAL.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.SIGNINGOFFICIAL.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -725,12 +736,13 @@ void testDeleteRoleFromUser_UserWithoutRole() { activeUser.setAdminRole(); when(userService.findUserById(any())).thenReturn(user); JsonElement userJson = gson.toJsonTree(user); - when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())).thenReturn( - userJson.getAsJsonObject()); + when(userService.findUserWithPropertiesByIdAsJsonObject(any(), any())) + .thenReturn(userJson.getAsJsonObject()); DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); User returnedUser; - try (Response response = userResource.deleteRoleFromUser(activeDuosUser, user.getUserId(), - UserRoles.ADMIN.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser( + activeDuosUser, user.getUserId(), UserRoles.ADMIN.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); returnedUser = new User((String) response.getEntity()); } @@ -744,8 +756,8 @@ void testDeleteRoleFromUser_UserNotFound() { DuosUser activeDuosUser = new DuosUser(new AuthUser(), activeUser); when(userService.findUserById(any())).thenThrow(new NotFoundException()); - try (Response response = userResource.deleteRoleFromUser(activeDuosUser, 1, - UserRoles.ADMIN.getRoleId())) { + try (Response response = + userResource.deleteRoleFromUser(activeDuosUser, 1, UserRoles.ADMIN.getRoleId())) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -774,8 +786,8 @@ void testGetDatasetsFromUserDacsV2DatasetsNotFound() { @Test void testGetDatasetsFromUserDacsV2UserNotFound() { - when(userService.findUserByEmail(anyString())).thenThrow( - new NotFoundException("User not found")); + when(userService.findUserByEmail(anyString())) + .thenThrow(new NotFoundException("User not found")); Response response = userResource.getDatasetsFromUserDacsV2(authUser); assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); @@ -785,10 +797,10 @@ void testGetDatasetsFromUserDacsV2UserNotFound() { void testPostAcknowledgement() { User user = createUserWithRole(); String acknowledgementKey = "key1"; - Map acknowledgementMap = getDefaultAcknowledgementForUser(user, - acknowledgementKey); - when(acknowledgementService.makeAcknowledgements(anyList(), any())).thenReturn( - acknowledgementMap); + Map acknowledgementMap = + getDefaultAcknowledgementForUser(user, acknowledgementKey); + when(acknowledgementService.makeAcknowledgements(anyList(), any())) + .thenReturn(acknowledgementMap); String jsonString = userResource.unmarshal(List.of(acknowledgementKey)); try (Response response = userResource.postAcknowledgements(duosUser, jsonString)) { @@ -799,7 +811,8 @@ void testPostAcknowledgement() { @Test void testPostAcknowledgementException() { String acknowledgementKey = "key1"; - doThrow(new RuntimeException("exception during post")).when(acknowledgementService) + doThrow(new RuntimeException("exception during post")) + .when(acknowledgementService) .makeAcknowledgements(anyList(), any()); String jsonString = userResource.unmarshal(List.of(acknowledgementKey)); @@ -824,10 +837,10 @@ void testPostCloseoutAcknowledgementSuccess() { user.addRole(UserRoles.Chairperson()); DuosUser chairUser = new DuosUser(authUser, user); String acknowledgementKey = AcknowledgementService.DAR_CLOSEOUT_CHAIR_REF + "12345"; - Map acknowledgementMap = getDefaultAcknowledgementForUser(user, - acknowledgementKey); - when(acknowledgementService.makeAcknowledgements(anyList(), any())).thenReturn( - acknowledgementMap); + Map acknowledgementMap = + getDefaultAcknowledgementForUser(user, acknowledgementKey); + when(acknowledgementService.makeAcknowledgements(anyList(), any())) + .thenReturn(acknowledgementMap); String jsonString = userResource.unmarshal(List.of(acknowledgementKey)); try (Response response = userResource.postAcknowledgements(chairUser, jsonString)) { @@ -871,7 +884,8 @@ void testMissingAcknowledgement() { @Test void testGetAcknowledgementException() { String acknowledgementKey = "key1"; - doThrow(new RuntimeException("some exception during get.")).when(acknowledgementService) + doThrow(new RuntimeException("some exception during get.")) + .when(acknowledgementService) .findAcknowledgementForUserByKey(any(), any()); Response response = userResource.getUserAcknowledgement(duosUser, acknowledgementKey); @@ -896,7 +910,8 @@ void testGetUnsetAcknowledgementsForUser() { @Test void testGetAcknowledgementsForUserException() { - doThrow(new RuntimeException("some get exception")).when(acknowledgementService) + doThrow(new RuntimeException("some get exception")) + .when(acknowledgementService) .findAcknowledgementsForUser(any()); Response response = userResource.getUserAcknowledgements(duosUser); @@ -907,12 +922,13 @@ void testGetAcknowledgementsForUserException() { void testGetSetAcknowledgementForUser() { String acknowledgementKey = "key1"; User user = createUserWithRole(); - Map acknowledgementMap = getDefaultAcknowledgementForUser(user, - acknowledgementKey); - when(acknowledgementService.findAcknowledgementForUserByKey(any(), any())).thenReturn( - acknowledgementMap.get(acknowledgementKey)); + Map acknowledgementMap = + getDefaultAcknowledgementForUser(user, acknowledgementKey); + when(acknowledgementService.findAcknowledgementForUserByKey(any(), any())) + .thenReturn(acknowledgementMap.get(acknowledgementKey)); - Response response = userResource.getUserAcknowledgement(new DuosUser(authUser, user), acknowledgementKey); + Response response = + userResource.getUserAcknowledgement(new DuosUser(authUser, user), acknowledgementKey); assertEquals(Status.OK.getStatusCode(), response.getStatus()); } @@ -920,10 +936,10 @@ void testGetSetAcknowledgementForUser() { void testDeleteAcknowledgementForUser() { String acknowledgementKey = "key1"; User user = createUserWithRole(); - Map acknowledgementMap = getDefaultAcknowledgementForUser(user, - acknowledgementKey); - when(acknowledgementService.findAcknowledgementForUserByKey(any(), any())).thenReturn( - acknowledgementMap.get(acknowledgementKey)); + Map acknowledgementMap = + getDefaultAcknowledgementForUser(user, acknowledgementKey); + when(acknowledgementService.findAcknowledgementForUserByKey(any(), any())) + .thenReturn(acknowledgementMap.get(acknowledgementKey)); try (Response response = userResource.deleteUserAcknowledgement(authUser, acknowledgementKey)) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); @@ -944,8 +960,8 @@ void testDeleteMissingAcknowledgementForUser() { void testGetAllAcknowledgements() { String acknowledgementKey = "key1"; User user = createUserWithRole(); - Map acknowledgementMap = getDefaultAcknowledgementForUser(user, - acknowledgementKey); + Map acknowledgementMap = + getDefaultAcknowledgementForUser(user, acknowledgementKey); when(acknowledgementService.findAcknowledgementsForUser(any())).thenReturn(acknowledgementMap); Response response = userResource.getUserAcknowledgements(new DuosUser(authUser, user)); assertEquals(Status.OK.getStatusCode(), response.getStatus()); @@ -968,8 +984,8 @@ void testGetApprovedDatasets() { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } - private Map getDefaultAcknowledgementForUser(User user, - String acknowledgementKey) { + private Map getDefaultAcknowledgementForUser( + User user, String acknowledgementKey) { Acknowledgement ack = new Acknowledgement(); Timestamp timestamp = new Timestamp(new Date().getTime()); ack.setAckKey(acknowledgementKey); @@ -981,7 +997,6 @@ private Map getDefaultAcknowledgementForUser(User user, return map; } - private User createUserWithRole() { User user = new User(); user.setUserId(randomInt(1, 100)); @@ -999,5 +1014,4 @@ private User createUserWithInstitution() { user.setInstitutionId(1); return user; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/VersionResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/VersionResourceTest.java index f5800868b5..89d82fc972 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/VersionResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/VersionResourceTest.java @@ -11,14 +11,12 @@ @ExtendWith(DropwizardExtensionsSupport.class) class VersionResourceTest { - private static final ResourceExtension RESOURCE_EXTENSION = ResourceExtension.builder() - .addResource(new VersionResource()) - .build(); + private static final ResourceExtension RESOURCE_EXTENSION = + ResourceExtension.builder().addResource(new VersionResource()).build(); @Test void testGetVersion() { Response response = RESOURCE_EXTENSION.target("/version").request().get(); assertEquals(200, response.getStatus()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java b/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java index 6a1095b61f..b064f12eb8 100644 --- a/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/resources/VoteResourceTest.java @@ -30,20 +30,15 @@ @ExtendWith(MockitoExtension.class) class VoteResourceTest { - @Mock - private ContainerRequest request; + @Mock private ContainerRequest request; - @Mock - private UserService userService; + @Mock private UserService userService; - @Mock - private VoteService voteService; + @Mock private VoteService voteService; - @Mock - private ElectionService electionService; + @Mock private ElectionService electionService; - @Mock - private AuthUser authUser; + @Mock private AuthUser authUser; private final User user = new User(); @@ -60,7 +55,7 @@ private void initResource() { @Test void testUpdateVotes_invalidJson() { initResource(); - try (var response = resource.updateVotes(authUser, request,"{\"vote\": true, \"ID\":12345}")) { + try (var response = resource.updateVotes(authUser, request, "{\"vote\": true, \"ID\":12345}")) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -72,8 +67,8 @@ void testUpdateVotes_nullIds() { voteUpdate.setVote(true); voteUpdate.setRationale("example"); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -82,21 +77,20 @@ void testUpdateVotes_nullIds() { void testUpdateVotes_noIds() { initResource(); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", new ArrayList<>()); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } - @Test void testUpdateVotes_noVotesForIds() { when(voteService.findVotesByIds(any())).thenReturn(Collections.emptyList()); initResource(); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1)); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -109,8 +103,8 @@ void testUpdateVotes_noVoteValue() { voteUpdate.setRationale("example"); voteUpdate.setVoteIds(List.of(1, 2, 3)); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -124,8 +118,8 @@ void testUpdateVotes_invalidUser() { initResource(); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); } } @@ -138,8 +132,8 @@ void testUpdateVotes_closedElection() { initResource(); Vote.VoteUpdate voteUpdate = new Vote.VoteUpdate(true, "example", List.of(1, 2, 3)); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_BAD_REQUEST, response.getStatus()); } } @@ -161,8 +155,8 @@ void testUpdateVotes_allMemberVotes() { .thenReturn(List.of(vote)); initResource(); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -185,8 +179,8 @@ void testUpdateVotes_allYes_allRP() { initResource(); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -208,8 +202,8 @@ void testUpdateVotes_allNo_allRP() { .thenReturn(List.of(vote)); initResource(); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -240,8 +234,8 @@ void testUpdateVotes_allYes_allDataAccess_AllCards() { initResource(); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -265,8 +259,8 @@ void testUpdateVotes_allNo_allDataAccess_AllCards() { .thenReturn(List.of(vote, voteTwo)); initResource(); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.OK.getStatusCode(), response.getStatus()); } } @@ -296,8 +290,8 @@ void testUpdateVotes_allYes_allDataAccess_NotAllCards() { .thenReturn(List.of(election)); initResource(); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } } @@ -314,8 +308,8 @@ void testUpdateVotes_noRationale() { voteUpdate.setVote(false); voteUpdate.setVoteIds(List.of(1, 2, 3)); - try (var response = resource.updateVotes(authUser, request, - gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { + try (var response = + resource.updateVotes(authUser, request, gson.toJson(voteUpdate, Vote.VoteUpdate.class))) { assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.getStatus()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1Test.java b/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1Test.java index e9ae401c70..d57ecd27c9 100644 --- a/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1Test.java +++ b/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseV1Test.java @@ -19,75 +19,193 @@ class GeneralResearchUseV1Test { private static Stream testCompare() { return Stream.of( - Arguments.of(new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions(List.of("setDiseaseRestrictions")), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions(null), new DataAccessRequestDataBuilder().setHmb(true), true), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions( - Collections.emptyList()), new DataAccessRequestDataBuilder().setHmb(true), true), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setNonProfitUse(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setMethodsResearch(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setCollaboratorRequired(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setEthicsApprovalRequired(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setGeneticStudiesOnly(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setGeographicalRestrictions("setGeographicalRestrictions"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setIllegalBehavior(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setOther("setOther"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPopulationOriginsAncestry(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPopulation(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPublicationMoratorium("setPublicationMoratorium"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setSecondaryOther("setSecondaryOther"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPublicationResults(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setAiLlmUse(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setControl(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setGender("Gender"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setStigmatizeDiseases(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setNotHealth(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPediatric(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPsychologicalTraits(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setSexualDiseases(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setVulnerablePopulations(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setHmb(true), true), - Arguments.of(new DataUseBuilder().setGeneralUse(false), - new DataAccessRequestDataBuilder().setHmb(true), false), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setDiseaseRestrictions(List.of("setDiseaseRestrictions")), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions(null), + new DataAccessRequestDataBuilder().setHmb(true), + true), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setDiseaseRestrictions(Collections.emptyList()), + new DataAccessRequestDataBuilder().setHmb(true), + true), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setNonProfitUse(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setMethodsResearch(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setCollaboratorRequired(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setEthicsApprovalRequired(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setGeneticStudiesOnly(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setGeographicalRestrictions("setGeographicalRestrictions"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setIllegalBehavior(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setOther("setOther"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPopulationOriginsAncestry(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPopulation(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setPublicationMoratorium("setPublicationMoratorium"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setSecondaryOther("setSecondaryOther"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPublicationResults(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setAiLlmUse(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setControl(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setGender("Gender"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setStigmatizeDiseases(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setNotHealth(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPediatric(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPsychologicalTraits(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setSexualDiseases(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setVulnerablePopulations(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setHmb(true), + true), + Arguments.of( + new DataUseBuilder().setGeneralUse(false), + new DataAccessRequestDataBuilder().setHmb(true), + false), Arguments.of(new DataUseBuilder(), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setOther(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setOtherText("Other Condition"), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setAiLlmUse(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setControls(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setPopulation(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setForProfit(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setGender("Gender"), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setPediatric(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setVulnerablePopulation(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setIllegalBehavior(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setSexualDiseases(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setPsychiatricTraits(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setNotHealth(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setStigmatizedDiseases(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setAddiction(true), false)); + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setOther(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setOtherText("Other Condition"), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setAiLlmUse(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setControls(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setPopulation(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setForProfit(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setGender("Gender"), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setPediatric(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setVulnerablePopulation(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setIllegalBehavior(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setSexualDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setPsychiatricTraits(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setNotHealth(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setStigmatizedDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setAddiction(true), + false)); } @ParameterizedTest @MethodSource - void testCompare(DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, - boolean expected) { + void testCompare( + DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, boolean expected) { Dataset dataset = new Dataset(); dataset.setDataUse(dataUseBuilder.build()); DataAccessRequest dataAccessRequest = new DataAccessRequest(); @@ -96,5 +214,4 @@ void testCompare(DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dat Assertions.assertEquals(expected, rule.compare(dataset, dataAccessRequest)); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseWithDiseaseSpecificV1Test.java b/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseWithDiseaseSpecificV1Test.java index e65ad680af..b789d850ae 100644 --- a/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseWithDiseaseSpecificV1Test.java +++ b/src/test/java/org/broadinstitute/consent/http/rules/GeneralResearchUseWithDiseaseSpecificV1Test.java @@ -20,122 +20,312 @@ public class GeneralResearchUseWithDiseaseSpecificV1Test { private static Stream testCompare() { return Stream.of( - Arguments.of(new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions(List.of("setDiseaseRestrictions")), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions(null), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), true), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions( - Collections.emptyList()), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), true), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setNonProfitUse(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setMethodsResearch(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setCollaboratorRequired(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setEthicsApprovalRequired(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setGeneticStudiesOnly(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setGeographicalRestrictions("setGeographicalRestrictions"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setIllegalBehavior(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setOther("setOther"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPopulationOriginsAncestry(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPopulation(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPublicationMoratorium("setPublicationMoratorium"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setSecondaryOther("setSecondaryOther"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPublicationResults(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setAiLlmUse(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setControl(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setGender("Gender"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setStigmatizeDiseases(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setNotHealth(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPediatric(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setPsychologicalTraits(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setSexualDiseases(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true).setVulnerablePopulations(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), true), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(false).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - Collections.emptyList()), false), - Arguments.of(new DataUseBuilder().setGeneralUse(false), - new DataAccessRequestDataBuilder().setHmb(true), false), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setDiseaseRestrictions(List.of("setDiseaseRestrictions")), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setDiseaseRestrictions(null), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + true), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setDiseaseRestrictions(Collections.emptyList()), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + true), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setNonProfitUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setMethodsResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setCollaboratorRequired(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setEthicsApprovalRequired(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setGeneticStudiesOnly(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setGeographicalRestrictions("setGeographicalRestrictions"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setIllegalBehavior(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setOther("setOther"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPopulationOriginsAncestry(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPopulation(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder() + .setGeneralUse(true) + .setPublicationMoratorium("setPublicationMoratorium"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setSecondaryOther("setSecondaryOther"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPublicationResults(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setAiLlmUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setControl(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setGender("Gender"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setStigmatizeDiseases(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setNotHealth(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPediatric(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setPsychologicalTraits(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setSexualDiseases(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true).setVulnerablePopulations(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + true), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(false) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(Collections.emptyList()), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(false), + new DataAccessRequestDataBuilder().setHmb(true), + false), Arguments.of(new DataUseBuilder(), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setOtherText("Other Condition"), - false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setAiLlmUse(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setControls(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setPopulation(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setForProfit(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setGender("Gender"), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setPediatric(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setVulnerablePopulation(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setIllegalBehavior(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setSexualDiseases(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setPsychiatricTraits(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setNotHealth(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setStigmatizedDiseases(true), false), - Arguments.of(new DataUseBuilder().setGeneralUse(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setAddiction(true), false)); + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setOtherText("Other Condition"), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setAiLlmUse(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setControls(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setPopulation(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setForProfit(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setGender("Gender"), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setPediatric(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setVulnerablePopulation(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setIllegalBehavior(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder().setSexualDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setPsychiatricTraits(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setNotHealth(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setStigmatizedDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setGeneralUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setAddiction(true), + false)); } @ParameterizedTest @MethodSource - void testCompare(DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, - boolean expected) { + void testCompare( + DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, boolean expected) { Dataset dataset = new Dataset(); dataset.setDataUse(dataUseBuilder.build()); DataAccessRequest dataAccessRequest = new DataAccessRequest(); diff --git a/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1Test.java b/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1Test.java index 0b4f489021..2b8885dc22 100644 --- a/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1Test.java +++ b/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalV1Test.java @@ -19,75 +19,193 @@ public class HealthMedicalBioMedicalV1Test { private static Stream testCompare() { return Stream.of( - Arguments.of(new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(List.of("setDiseaseRestrictions")), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(null), new DataAccessRequestDataBuilder().setHmb(true), true), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions( - Collections.emptyList()), new DataAccessRequestDataBuilder().setHmb(true), true), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setNonProfitUse(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setMethodsResearch(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setCollaboratorRequired(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setEthicsApprovalRequired(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setGeneticStudiesOnly(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setGeographicalRestrictions("setGeographicalRestrictions"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setIllegalBehavior(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setOther("setOther"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPopulationOriginsAncestry(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPopulation(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPublicationMoratorium("setPublicationMoratorium"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setSecondaryOther("setSecondaryOther"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPublicationResults(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setAiLlmUse(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setControl(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setGender("Gender"), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setStigmatizeDiseases(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setNotHealth(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPediatric(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPsychologicalTraits(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setSexualDiseases(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setVulnerablePopulations(true), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setHmb(true), true), - Arguments.of(new DataUseBuilder().setHmbResearch(false), - new DataAccessRequestDataBuilder().setHmb(true), false), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setDiseaseRestrictions(List.of("setDiseaseRestrictions")), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(null), + new DataAccessRequestDataBuilder().setHmb(true), + true), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setDiseaseRestrictions(Collections.emptyList()), + new DataAccessRequestDataBuilder().setHmb(true), + true), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setNonProfitUse(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setMethodsResearch(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setCollaboratorRequired(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setEthicsApprovalRequired(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setGeneticStudiesOnly(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setGeographicalRestrictions("setGeographicalRestrictions"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setIllegalBehavior(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setOther("setOther"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPopulationOriginsAncestry(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPopulation(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setPublicationMoratorium("setPublicationMoratorium"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setSecondaryOther("setSecondaryOther"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPublicationResults(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setAiLlmUse(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setControl(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setGender("Gender"), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setStigmatizeDiseases(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setNotHealth(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPediatric(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPsychologicalTraits(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setSexualDiseases(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setVulnerablePopulations(true), + new DataAccessRequestDataBuilder().setHmb(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setHmb(true), + true), + Arguments.of( + new DataUseBuilder().setHmbResearch(false), + new DataAccessRequestDataBuilder().setHmb(true), + false), Arguments.of(new DataUseBuilder(), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setOther(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setOtherText("Other Condition"), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setAiLlmUse(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setControls(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setPopulation(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setForProfit(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setGender("Gender"), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setPediatric(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setVulnerablePopulation(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setIllegalBehavior(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setSexualDiseases(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setPsychiatricTraits(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setNotHealth(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setStigmatizedDiseases(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setAddiction(true), false)); + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setOther(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setOtherText("Other Condition"), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setAiLlmUse(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setControls(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setPopulation(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setForProfit(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setGender("Gender"), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setPediatric(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setVulnerablePopulation(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setIllegalBehavior(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setSexualDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setPsychiatricTraits(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setNotHealth(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setStigmatizedDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setAddiction(true), + false)); } @ParameterizedTest @MethodSource - void testCompare(DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, - boolean expected) { + void testCompare( + DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, boolean expected) { Dataset dataset = new Dataset(); dataset.setDataUse(dataUseBuilder.build()); DataAccessRequest dataAccessRequest = new DataAccessRequest(); diff --git a/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1Test.java b/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1Test.java index 042975851b..35cfdafdc9 100644 --- a/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1Test.java +++ b/src/test/java/org/broadinstitute/consent/http/rules/HealthMedicalBioMedicalWithDiseaseSpecificV1Test.java @@ -20,127 +20,318 @@ public class HealthMedicalBioMedicalWithDiseaseSpecificV1Test { private static Stream testCompare() { return Stream.of( - Arguments.of(new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(List.of("setDiseaseRestrictions")), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(null), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), true), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions( - Collections.emptyList()), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), true), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setNonProfitUse(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setMethodsResearch(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setCollaboratorRequired(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setEthicsApprovalRequired(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setGeneticStudiesOnly(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setGeographicalRestrictions("setGeographicalRestrictions"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setIllegalBehavior(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setOther("setOther"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPopulationOriginsAncestry(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPopulation(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPublicationMoratorium("setPublicationMoratorium"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setSecondaryOther("setSecondaryOther"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPublicationResults(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setAiLlmUse(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setControl(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setGender("Gender"), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setStigmatizeDiseases(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setNotHealth(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPediatric(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setPsychologicalTraits(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setSexualDiseases(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true).setVulnerablePopulations(true), new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())), true), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(false).setOntologies( - List.of(new OntologyEntry())), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - Collections.emptyList()), false), - Arguments.of(new DataUseBuilder().setHmbResearch(false), - new DataAccessRequestDataBuilder().setHmb(true), false), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setDiseaseRestrictions(List.of("setDiseaseRestrictions")), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(null), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + true), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setDiseaseRestrictions(Collections.emptyList()), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + true), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setNonProfitUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setMethodsResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setCollaboratorRequired(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setEthicsApprovalRequired(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setGeneticStudiesOnly(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setGeographicalRestrictions("setGeographicalRestrictions"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setIllegalBehavior(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setOther("setOther"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPopulationOriginsAncestry(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPopulation(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder() + .setHmbResearch(true) + .setPublicationMoratorium("setPublicationMoratorium"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setSecondaryOther("setSecondaryOther"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPublicationResults(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setAiLlmUse(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setControl(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setGender("Gender"), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setStigmatizeDiseases(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setNotHealth(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPediatric(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setPsychologicalTraits(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setSexualDiseases(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true).setVulnerablePopulations(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())), + true), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(false) + .setOntologies(List.of(new OntologyEntry())), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(Collections.emptyList()), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(false), + new DataAccessRequestDataBuilder().setHmb(true), + false), Arguments.of(new DataUseBuilder(), new DataAccessRequestDataBuilder().setHmb(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setOtherText("Other Condition"), - false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setAiLlmUse(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setControls(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setPopulation(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setForProfit(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setGender("Gender"), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setPediatric(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setVulnerablePopulation(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setIllegalBehavior(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setSexualDiseases(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setPsychiatricTraits(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setNotHealth(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setStigmatizedDiseases(true), false), - Arguments.of(new DataUseBuilder().setHmbResearch(true), - new DataAccessRequestDataBuilder().setDiseases(true).setOntologies( - List.of(new OntologyEntry())).setOther(true).setAddiction(true), false)); + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setOtherText("Other Condition"), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setAiLlmUse(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setControls(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setPopulation(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setForProfit(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setGender("Gender"), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setPediatric(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setVulnerablePopulation(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setIllegalBehavior(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder().setSexualDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setPsychiatricTraits(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setNotHealth(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setStigmatizedDiseases(true), + false), + Arguments.of( + new DataUseBuilder().setHmbResearch(true), + new DataAccessRequestDataBuilder() + .setDiseases(true) + .setOntologies(List.of(new OntologyEntry())) + .setOther(true) + .setAddiction(true), + false)); } @ParameterizedTest @MethodSource - void testCompare(DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, - boolean expected) { + void testCompare( + DataUseBuilder dataUseBuilder, DataAccessRequestDataBuilder dataBuilder, boolean expected) { Dataset dataset = new Dataset(); dataset.setDataUse(dataUseBuilder.build()); DataAccessRequest dataAccessRequest = new DataAccessRequest(); dataAccessRequest.setData(dataBuilder.build()); - HealthMedicalBioMedicalWithDiseaseSpecificV1 rule = new HealthMedicalBioMedicalWithDiseaseSpecificV1(); + HealthMedicalBioMedicalWithDiseaseSpecificV1 rule = + new HealthMedicalBioMedicalWithDiseaseSpecificV1(); Assertions.assertEquals(expected, rule.compare(dataset, dataAccessRequest)); } diff --git a/src/test/java/org/broadinstitute/consent/http/rules/RuleImplementationInterfaceTest.java b/src/test/java/org/broadinstitute/consent/http/rules/RuleImplementationInterfaceTest.java index a41107ae08..28606b901b 100644 --- a/src/test/java/org/broadinstitute/consent/http/rules/RuleImplementationInterfaceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/rules/RuleImplementationInterfaceTest.java @@ -19,8 +19,9 @@ public DACAutomationRuleType getRuleType() { } @Override - public boolean compare(org.broadinstitute.consent.http.models.Dataset dataset, - org.broadinstitute.consent.http.models.DataAccessRequest dataAccessRequest) { + public boolean compare( + org.broadinstitute.consent.http.models.Dataset dataset, + org.broadinstitute.consent.http.models.DataAccessRequest dataAccessRequest) { return false; } } @@ -70,7 +71,8 @@ void testRequestHasDiseasesWithAiLlmUse() { TestRuleImplementation rule = new TestRuleImplementation(); DataAccessRequestData data = new DataAccessRequestData(); data.setDiseases(true); - data.setOntologies(java.util.List.of(new org.broadinstitute.consent.http.models.OntologyEntry())); + data.setOntologies( + java.util.List.of(new org.broadinstitute.consent.http.models.OntologyEntry())); assertTrue(rule.requestHasDiseases(data)); diff --git a/src/test/java/org/broadinstitute/consent/http/service/AcknowledgementServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/AcknowledgementServiceTest.java index 0bd4cd3f27..0aa3ffbd7f 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/AcknowledgementServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/AcknowledgementServiceTest.java @@ -38,28 +38,25 @@ @ExtendWith(MockitoExtension.class) class AcknowledgementServiceTest extends AbstractTestHelper { - @Mock - private static AcknowledgementDAO acknowledgementDAO; - @Mock - private static DataAccessRequestDAO dataAccessRequestDAO; - @Mock - private static EmailService emailService; + @Mock private static AcknowledgementDAO acknowledgementDAO; + @Mock private static DataAccessRequestDAO dataAccessRequestDAO; + @Mock private static EmailService emailService; private AcknowledgementService acknowledgementService; @BeforeEach void setUp() { - acknowledgementService = new AcknowledgementService(acknowledgementDAO, dataAccessRequestDAO, - emailService); + acknowledgementService = + new AcknowledgementService(acknowledgementDAO, dataAccessRequestDAO, emailService); } @Test void test_noAcknowledgementsForUser() { - User user = new User(1, "test@domain.com", "Test User", new Date(), - List.of(UserRoles.Researcher())); + User user = + new User(1, "test@domain.com", "Test User", new Date(), List.of(UserRoles.Researcher())); when(acknowledgementDAO.findAcknowledgementsForUser(anyInt())).thenReturn(new ArrayList<>()); - when(acknowledgementDAO.findAcknowledgementsByKeyForUser(anyString(), anyInt())).thenReturn( - null); + when(acknowledgementDAO.findAcknowledgementsByKeyForUser(anyString(), anyInt())) + .thenReturn(null); assertTrue(acknowledgementService.findAcknowledgementsForUser(user).isEmpty()); assertNull(acknowledgementService.findAcknowledgementForUserByKey(user, "key1")); @@ -67,8 +64,8 @@ void test_noAcknowledgementsForUser() { @Test void test_makeAndDeleteAcknowledgementForUser() { - User user = new User(2, "test@domain.com", "Test User", new Date(), - List.of(UserRoles.Researcher())); + User user = + new User(2, "test@domain.com", "Test User", new Date(), List.of(UserRoles.Researcher())); String key = "key2"; List keys = List.of(key); Timestamp timestamp = new Timestamp(new Date().getTime()); @@ -78,27 +75,27 @@ void test_makeAndDeleteAcknowledgementForUser() { key2Acknowledgement.setFirstAcknowledged(timestamp); key2Acknowledgement.setLastAcknowledged(timestamp); List acknowledgementList = List.of(key2Acknowledgement); - when(acknowledgementDAO.findAcknowledgementsForUser(any(), any())).thenReturn( - acknowledgementList); + when(acknowledgementDAO.findAcknowledgementsForUser(any(), any())) + .thenReturn(acknowledgementList); when(acknowledgementDAO.findAcknowledgementsForUser(anyInt())).thenReturn(acknowledgementList); - when(acknowledgementDAO.findAcknowledgementsByKeyForUser(anyString(), anyInt())).thenReturn( - key2Acknowledgement); + when(acknowledgementDAO.findAcknowledgementsByKeyForUser(anyString(), anyInt())) + .thenReturn(key2Acknowledgement); doNothing().when(acknowledgementDAO).deleteAcknowledgement(anyString(), anyInt()); - Map makeResponse = acknowledgementService.makeAcknowledgements(keys, - user); + Map makeResponse = + acknowledgementService.makeAcknowledgements(keys, user); assertEquals(1, makeResponse.size()); assertTrue(makeResponse.containsKey(key)); assertEquals(key2Acknowledgement, makeResponse.get(key)); - Map lookupResponse = acknowledgementService.findAcknowledgementsForUser( - user); + Map lookupResponse = + acknowledgementService.findAcknowledgementsForUser(user); assertEquals(1, lookupResponse.size()); assertTrue(lookupResponse.containsKey(key)); assertEquals(key2Acknowledgement, lookupResponse.get(key)); - Acknowledgement singleLookupResponse = acknowledgementService.findAcknowledgementForUserByKey( - user, key); + Acknowledgement singleLookupResponse = + acknowledgementService.findAcknowledgementForUserByKey(user, key); assertEquals(singleLookupResponse, key2Acknowledgement); acknowledgementService.deleteAcknowledgementForUserByKey(user, key); @@ -108,8 +105,8 @@ void test_makeAndDeleteAcknowledgementForUser() { void testMakeCloseoutAcknowledgement() throws Exception { DataAccessRequestData data = new DataAccessRequestData(); data.setCloseoutSupplement(new CloseoutSupplement(List.of("reason"), "details", 1)); - User user = new User(3, "test@domain.com", "Test User", new Date(), - List.of(UserRoles.Chairperson())); + User user = + new User(3, "test@domain.com", "Test User", new Date(), List.of(UserRoles.Chairperson())); DataAccessRequest dar1 = new DataAccessRequest(); dar1.setReferenceId(UUID.randomUUID().toString()); dar1.setDarCode("DAR-" + randomInt(100, 1000)); @@ -143,25 +140,27 @@ void testMakeCloseoutAcknowledgement() throws Exception { when(dataAccessRequestDAO.findByReferenceId(dar1.getReferenceId())).thenReturn(dar1); when(dataAccessRequestDAO.findByReferenceId(dar2.getReferenceId())).thenReturn(dar2); // Neither DAR has been acknowledged yet - when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ack1.getAckKey(), user.getUserId())).thenReturn(null); - when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ack3.getAckKey(), user.getUserId())).thenReturn(null); + when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ack1.getAckKey(), user.getUserId())) + .thenReturn(null); + when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ack3.getAckKey(), user.getUserId())) + .thenReturn(null); when(acknowledgementDAO.findAcknowledgementsForUser( - List.of(ack1.getAckKey(), ack2.getAckKey(), ack3.getAckKey()), - user.getUserId())).thenReturn(List.of(ack1, ack2, ack3)); + List.of(ack1.getAckKey(), ack2.getAckKey(), ack3.getAckKey()), user.getUserId())) + .thenReturn(List.of(ack1, ack2, ack3)); acknowledgementService.makeAcknowledgements( List.of(ack1.getAckKey(), ack2.getAckKey(), ack3.getAckKey()), user); // Only two acknowledgements are closeouts, so only two emails should be sent - verify(emailService).sendResearcherCloseoutCompletedMessage(user, dar1.getDarCode(), - dar1.getReferenceId()); - verify(emailService).sendResearcherCloseoutCompletedMessage(user, dar2.getDarCode(), - dar2.getReferenceId()); + verify(emailService) + .sendResearcherCloseoutCompletedMessage(user, dar1.getDarCode(), dar1.getReferenceId()); + verify(emailService) + .sendResearcherCloseoutCompletedMessage(user, dar2.getDarCode(), dar2.getReferenceId()); } @Test void testMakeCloseoutAcknowledgementPreviouslyAcknowledged() throws Exception { - User user = new User(3, "test@domain.com", "Test User", new Date(), - List.of(UserRoles.Chairperson())); + User user = + new User(3, "test@domain.com", "Test User", new Date(), List.of(UserRoles.Chairperson())); DataAccessRequest dar1 = new DataAccessRequest(); dar1.setReferenceId(UUID.randomUUID().toString()); dar1.setDarCode("DAR-" + randomInt(100, 1000)); @@ -173,12 +172,15 @@ void testMakeCloseoutAcknowledgementPreviouslyAcknowledged() throws Exception { ack1.setFirstAcknowledged(timestamp); // Ensures that this DAR closeout has already been acknowledged - when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ack1.getAckKey(), user.getUserId())).thenReturn(ack1); + when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ack1.getAckKey(), user.getUserId())) + .thenReturn(ack1); when(dataAccessRequestDAO.findByReferenceId(dar1.getReferenceId())).thenReturn(dar1); List keys = List.of(ack1.getAckKey()); - assertThrows(BadRequestException.class, () -> acknowledgementService.makeAcknowledgements(keys, user)); - verify(emailService, never()).sendResearcherCloseoutCompletedMessage(any(), anyString(), anyString()); + assertThrows( + BadRequestException.class, () -> acknowledgementService.makeAcknowledgements(keys, user)); + verify(emailService, never()) + .sendResearcherCloseoutCompletedMessage(any(), anyString(), anyString()); } @Test @@ -205,17 +207,19 @@ void testMakeCloseoutAcknowledgementPreviouslyAcknowledgedByDifferentChair() thr ack1.setFirstAcknowledged(timestamp); // This is technically a no-op, but we want to document a chair1 ack for test clarity acknowledgementDAO.upsertAcknowledgement(ack1.getAckKey(), chair1.getUserId()); - when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ackKey, chair2.getUserId())).thenReturn(null); + when(acknowledgementDAO.findAcknowledgementsByKeyForUser(ackKey, chair2.getUserId())) + .thenReturn(null); when(dataAccessRequestDAO.findByReferenceId(dar1.getReferenceId())).thenReturn(dar1); acknowledgementService.makeAcknowledgements(List.of(ackKey), chair2); - verify(emailService).sendResearcherCloseoutCompletedMessage(chair2, dar1.getDarCode(), dar1.getReferenceId()); + verify(emailService) + .sendResearcherCloseoutCompletedMessage(chair2, dar1.getDarCode(), dar1.getReferenceId()); } @Test void testMakeCloseoutAcknowledgementNotACloseout() throws Exception { - User user = new User(3, "test@domain.com", "Test User", new Date(), - List.of(UserRoles.Chairperson())); + User user = + new User(3, "test@domain.com", "Test User", new Date(), List.of(UserRoles.Chairperson())); // Note that this DAR does not have a closeout DataAccessRequest dar1 = new DataAccessRequest(); dar1.setReferenceId(UUID.randomUUID().toString()); @@ -223,11 +227,14 @@ void testMakeCloseoutAcknowledgementNotACloseout() throws Exception { String key = AcknowledgementService.DAR_CLOSEOUT_CHAIR_REF + dar1.getReferenceId(); // Ensures that this DAR closeout has NOT already been acknowledged - when(acknowledgementDAO.findAcknowledgementsByKeyForUser(key, user.getUserId())).thenReturn(null); + when(acknowledgementDAO.findAcknowledgementsByKeyForUser(key, user.getUserId())) + .thenReturn(null); when(dataAccessRequestDAO.findByReferenceId(dar1.getReferenceId())).thenReturn(dar1); List keys = List.of(key); - assertThrows(BadRequestException.class, () -> acknowledgementService.makeAcknowledgements(keys, user)); - verify(emailService, never()).sendResearcherCloseoutCompletedMessage(any(), anyString(), anyString()); + assertThrows( + BadRequestException.class, () -> acknowledgementService.makeAcknowledgements(keys, user)); + verify(emailService, never()) + .sendResearcherCloseoutCompletedMessage(any(), anyString(), anyString()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/service/CounterServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/CounterServiceTest.java index a3cc4431b1..edadc18029 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/CounterServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/CounterServiceTest.java @@ -10,12 +10,10 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; - @ExtendWith(MockitoExtension.class) class CounterServiceTest { - @Mock - private CounterDAO counterDAO; + @Mock private CounterDAO counterDAO; private CounterService service; diff --git a/src/test/java/org/broadinstitute/consent/http/service/DACAutomationRuleServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DACAutomationRuleServiceTest.java index 38205280dc..abc22e8b5e 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DACAutomationRuleServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DACAutomationRuleServiceTest.java @@ -63,36 +63,32 @@ @ExtendWith(MockitoExtension.class) class DACAutomationRuleServiceTest { - @Mock - private DataAccessRequestDAO dataAccessRequestDAO; - @Mock - private DatasetDAO datasetDAO; - @Mock - private ElectionDAO electionDAO; - @Mock - private VoteDAO voteDAO; - @Mock - private VoteServiceDAO voteServiceDAO; - @Mock - private User user; - - @Mock - private DACAutomationRuleDAO ruleDAO; - - @Mock - private UserDAO userDAO; - - @Mock - private VoteService voteService; - - @Mock - private ContainerRequest request; + @Mock private DataAccessRequestDAO dataAccessRequestDAO; + @Mock private DatasetDAO datasetDAO; + @Mock private ElectionDAO electionDAO; + @Mock private VoteDAO voteDAO; + @Mock private VoteServiceDAO voteServiceDAO; + @Mock private User user; + + @Mock private DACAutomationRuleDAO ruleDAO; + + @Mock private UserDAO userDAO; + + @Mock private VoteService voteService; + + @Mock private ContainerRequest request; private DACAutomationRuleService service; private static DACAutomationRule makeDacAutomationRuleGRU() { - return new DACAutomationRule(1, DACAutomationRuleType.GRU_V1, - "Test Rule", RuleState.AVAILABLE, Timestamp.from(Instant.now()), 1, "admin", + return new DACAutomationRule( + 1, + DACAutomationRuleType.GRU_V1, + "Test Rule", + RuleState.AVAILABLE, + Timestamp.from(Instant.now()), + 1, + "admin", "admin@example.com"); } @@ -142,15 +138,23 @@ void setUp() { userDAO, voteDAO, voteServiceDAO, - voteService - ); + voteService); } @Test void testFindAll() { - when(ruleDAO.findAll()).thenReturn(List.of( - new DACAutomationRule(1, DACAutomationRuleType.GRU_V1, "Test Rule", RuleState.AVAILABLE, - null, null, null, null))); + when(ruleDAO.findAll()) + .thenReturn( + List.of( + new DACAutomationRule( + 1, + DACAutomationRuleType.GRU_V1, + "Test Rule", + RuleState.AVAILABLE, + null, + null, + null, + null))); List rules = service.findAll(); Assertions.assertNotNull(rules); @@ -159,9 +163,18 @@ void testFindAll() { @Test void testFindById() { - when(ruleDAO.findAllDACAutomationRulesByDACId(1)).thenReturn(List.of( - new DACAutomationRule(1, DACAutomationRuleType.GRU_V1, "Test Rule", RuleState.AVAILABLE, - null, null, null, null))); + when(ruleDAO.findAllDACAutomationRulesByDACId(1)) + .thenReturn( + List.of( + new DACAutomationRule( + 1, + DACAutomationRuleType.GRU_V1, + "Test Rule", + RuleState.AVAILABLE, + null, + null, + null, + null))); List rules = service.findAllByDacId(1); Assertions.assertNotNull(rules); assertFalse(rules.isEmpty()); @@ -169,13 +182,20 @@ void testFindById() { @Test void testToggleRuleFromOffToOn() { - when(ruleDAO.findAllDACAutomationRulesByDACId(1)).thenReturn(List.of( - new DACAutomationRule(1, DACAutomationRuleType.GRU_V1, "Test Rule", RuleState.AVAILABLE, - null, null, null, null))); - when(ruleDAO.auditedInsertDACRuleSetting(anyInt(), anyInt(), anyInt(), any())).thenReturn( - 1); - AutomationRuleToggleResponse result = service.toggleRule( - 1, 1, user); + when(ruleDAO.findAllDACAutomationRulesByDACId(1)) + .thenReturn( + List.of( + new DACAutomationRule( + 1, + DACAutomationRuleType.GRU_V1, + "Test Rule", + RuleState.AVAILABLE, + null, + null, + null, + null))); + when(ruleDAO.auditedInsertDACRuleSetting(anyInt(), anyInt(), anyInt(), any())).thenReturn(1); + AutomationRuleToggleResponse result = service.toggleRule(1, 1, user); assertTrue(result.isRuleEnabled()); assertEquals(1, result.getRuleId()); Assertions.assertTrue(result.getEnabledTime() > 1); @@ -183,9 +203,18 @@ void testToggleRuleFromOffToOn() { @Test void testToggleRuleFromOnToOff() { - when(ruleDAO.findAllDACAutomationRulesByDACId(1)).thenReturn(List.of( - new DACAutomationRule(1, DACAutomationRuleType.GRU_V1, "Test Rule", RuleState.AVAILABLE, - Timestamp.from(Instant.now()), 1, "alice", "alice@fake.org"))); + when(ruleDAO.findAllDACAutomationRulesByDACId(1)) + .thenReturn( + List.of( + new DACAutomationRule( + 1, + DACAutomationRuleType.GRU_V1, + "Test Rule", + RuleState.AVAILABLE, + Timestamp.from(Instant.now()), + 1, + "alice", + "alice@fake.org"))); doNothing().when(ruleDAO).auditedDeleteDACRuleSetting(anyInt(), anyInt(), anyInt()); AutomationRuleToggleResponse result = service.toggleRule(1, 1, user); assertFalse(result.isRuleEnabled()); @@ -222,22 +251,20 @@ void testFindAuditRecords() { int offset = (page - 1) * pageSize; int totalCount = 25; - List mockAudits = List.of( - new DACAutomationRuleAudit( - RuleAuditAction.ADD, - Timestamp.from(Instant.now()), - DACAutomationRuleType.GRU_V1, - "user1@example.com", - "User One" - ), - new DACAutomationRuleAudit( - RuleAuditAction.REMOVE, - Timestamp.from(Instant.now()), - DACAutomationRuleType.HMB_DSV1, - "user2@example.com", - "User Two" - ) - ); + List mockAudits = + List.of( + new DACAutomationRuleAudit( + RuleAuditAction.ADD, + Timestamp.from(Instant.now()), + DACAutomationRuleType.GRU_V1, + "user1@example.com", + "User One"), + new DACAutomationRuleAudit( + RuleAuditAction.REMOVE, + Timestamp.from(Instant.now()), + DACAutomationRuleType.HMB_DSV1, + "user2@example.com", + "User Two")); when(ruleDAO.findAutomationAuditsForDac(dacId, pageSize, offset)).thenReturn(mockAudits); when(ruleDAO.findCountOfAutomationAuditsForDac(dacId)).thenReturn(totalCount); @@ -260,18 +287,30 @@ void testTriggerDACRuleSettings() { Dataset dataset1 = makeDataset(1, "Dataset One", 3); Dataset dataset2 = makeDataset(2, "Dataset Two", 4); DACAutomationRule activeRule = makeDacAutomationRuleGRU(); // This has enabledByUserId=1 - DACAutomationRule inactiveRule = new DACAutomationRule(2, DACAutomationRuleType.GRU_V1, - "Inactive Rule", RuleState.AVAILABLE, null, null, null, null); + DACAutomationRule inactiveRule = + new DACAutomationRule( + 2, + DACAutomationRuleType.GRU_V1, + "Inactive Rule", + RuleState.AVAILABLE, + null, + null, + null, + null); when(dataAccessRequestDAO.findByReferenceId(referenceId)).thenReturn(dar); when(datasetDAO.findDatasetById(1)).thenReturn(dataset1); when(datasetDAO.findDatasetById(2)).thenReturn(dataset2); - when(ruleDAO.findAllDACAutomationRulesByDACId(dataset1.getDacId())).thenReturn(List.of(activeRule)); - when(ruleDAO.findAllDACAutomationRulesByDACId(dataset2.getDacId())).thenReturn(List.of(inactiveRule)); + when(ruleDAO.findAllDACAutomationRulesByDACId(dataset1.getDacId())) + .thenReturn(List.of(activeRule)); + when(ruleDAO.findAllDACAutomationRulesByDACId(dataset2.getDacId())) + .thenReturn(List.of(inactiveRule)); DACAutomationRuleService serviceSpy = spy(service); // in order to test sending the email we need to add to the datasetsAuthorized list - doAnswer(inv -> Optional.of(new Vote())).when(serviceSpy).applyRule(activeRule, dataset1, dar, request); + doAnswer(inv -> Optional.of(new Vote())) + .when(serviceSpy) + .applyRule(activeRule, dataset1, dar, request); serviceSpy.triggerDACRuleSettings(researcher, datasetIds, referenceId, request); @@ -285,12 +324,21 @@ void testTriggerDACRuleSettingsNoAuthorizedDatasets() { String referenceId = dar.getReferenceId(); List datasetIds = List.of(1); Dataset dataset = makeDataset(); - DACAutomationRule inactiveRule = new DACAutomationRule(1, DACAutomationRuleType.GRU_V1, - "Inactive Rule", RuleState.AVAILABLE, null, null, null, null); + DACAutomationRule inactiveRule = + new DACAutomationRule( + 1, + DACAutomationRuleType.GRU_V1, + "Inactive Rule", + RuleState.AVAILABLE, + null, + null, + null, + null); when(dataAccessRequestDAO.findByReferenceId(referenceId)).thenReturn(dar); when(datasetDAO.findDatasetById(1)).thenReturn(dataset); - when(ruleDAO.findAllDACAutomationRulesByDACId(dataset.getDacId())).thenReturn(List.of(inactiveRule)); + when(ruleDAO.findAllDACAutomationRulesByDACId(dataset.getDacId())) + .thenReturn(List.of(inactiveRule)); DACAutomationRuleService serviceSpy = spy(service); @@ -300,7 +348,7 @@ void testTriggerDACRuleSettingsNoAuthorizedDatasets() { } @Test - void testTriggerDACRuleSettings_does_not_throw(){ + void testTriggerDACRuleSettings_does_not_throw() { User researcher = makeResearcher(); DataAccessRequest dar = makeDAR(); String referenceId = dar.getReferenceId(); @@ -310,7 +358,8 @@ void testTriggerDACRuleSettings_does_not_throw(){ .when(dataAccessRequestDAO) .findByReferenceId(referenceId); - assertDoesNotThrow(() -> service.triggerDACRuleSettings(researcher, datasetIds, referenceId, request)); + assertDoesNotThrow( + () -> service.triggerDACRuleSettings(researcher, datasetIds, referenceId, request)); } @Test @@ -331,13 +380,13 @@ void testOpenElectionAndApprove() { Vote vote = mockFindVoteById(voteId); when(voteServiceDAO.updateVotesWithValue(any(), anyBoolean(), any())).thenReturn(List.of(vote)); - Vote openedVote = service.openElectionAndApprove(rule, ruleImplementation, dar, dataset, request); + Vote openedVote = + service.openElectionAndApprove(rule, ruleImplementation, dar, dataset, request); assertEquals(vote, openedVote); - verify(voteServiceDAO).updateVotesWithValue( - List.of(vote), - true, - "Rule Automated DAR (RADAR) Approval using rule: GRU_V1"); + verify(voteServiceDAO) + .updateVotesWithValue( + List.of(vote), true, "Rule Automated DAR (RADAR) Approval using rule: GRU_V1"); } @Test @@ -377,11 +426,16 @@ void testApplyRuleApprove() { vote.setType(VoteType.RADAR_APPROVE.getValue()); vote.setVote(true); - when(electionDAO.insertElection(eq(ElectionType.DATA_ACCESS.getValue()), - eq(ElectionStatus.OPEN.getValue()), any(), eq(darHmb.getReferenceId()), eq(datasetGru.getDatasetId()))).thenReturn(1); - - when(voteDAO.insertVote(rule.enabledByUserId(), 1, - VoteType.RADAR_APPROVE.getValue())).thenReturn(1); + when(electionDAO.insertElection( + eq(ElectionType.DATA_ACCESS.getValue()), + eq(ElectionStatus.OPEN.getValue()), + any(), + eq(darHmb.getReferenceId()), + eq(datasetGru.getDatasetId()))) + .thenReturn(1); + + when(voteDAO.insertVote(rule.enabledByUserId(), 1, VoteType.RADAR_APPROVE.getValue())) + .thenReturn(1); when(voteDAO.findVoteById(1)).thenReturn(vote); when(userDAO.findUserById(rule.enabledByUserId())).thenReturn(user); when(voteServiceDAO.updateVotesWithValue(any(), anyBoolean(), any())).thenReturn(List.of(vote)); @@ -428,11 +482,16 @@ void testApplyRule_Error_In_Vote() { Vote vote = new Vote(); vote.setType(VoteType.RADAR_APPROVE.getValue()); - when(electionDAO.insertElection(eq(ElectionType.DATA_ACCESS.getValue()), - eq(ElectionStatus.OPEN.getValue()), any(), eq(darHmb.getReferenceId()), eq(datasetGru.getDatasetId()))).thenReturn(1); - - when(voteDAO.insertVote(rule.enabledByUserId(), 1, - VoteType.RADAR_APPROVE.getValue())).thenReturn(1); + when(electionDAO.insertElection( + eq(ElectionType.DATA_ACCESS.getValue()), + eq(ElectionStatus.OPEN.getValue()), + any(), + eq(darHmb.getReferenceId()), + eq(datasetGru.getDatasetId()))) + .thenReturn(1); + + when(voteDAO.insertVote(rule.enabledByUserId(), 1, VoteType.RADAR_APPROVE.getValue())) + .thenReturn(1); when(voteDAO.findVoteById(1)).thenReturn(vote); doThrow(new RuntimeException("Test error")) @@ -453,20 +512,21 @@ void testApplyRuleNotApprove() { DACAutomationRuleService serviceSpy = spy(service); serviceSpy.applyRule(rule, datasetGru, darNotHmb, request); - verify(serviceSpy, never()).openElectionAndApprove( - any(DACAutomationRule.class), - any(RuleImplementationInterface.class), - any(DataAccessRequest.class), - any(Dataset.class), - any(ContainerRequest.class) - ); + verify(serviceSpy, never()) + .openElectionAndApprove( + any(DACAutomationRule.class), + any(RuleImplementationInterface.class), + any(DataAccessRequest.class), + any(Dataset.class), + any(ContainerRequest.class)); } @Test void testGetRuleImplementation() { DACAutomationRule gruRule = makeDacAutomationRuleGRU(); - RuleImplementationInterface implementation = DACAutomationRuleService.getRuleImplementation(gruRule); + RuleImplementationInterface implementation = + DACAutomationRuleService.getRuleImplementation(gruRule); assertNotNull(implementation); assertEquals(DACAutomationRuleType.GRU_V1, implementation.getRuleType()); @@ -481,22 +541,21 @@ void testGetRuleImplementationException() { when(mockRule.ruleType()).thenReturn(mockType); when(mockType.toString()).thenReturn("MOCK_TYPE"); - IllegalArgumentException exception = assertThrows( - IllegalArgumentException.class, - () -> DACAutomationRuleService.getRuleImplementation(mockRule)); - assertEquals( - "No rule implementation found for type: MOCK_TYPE", - exception.getMessage()); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> DACAutomationRuleService.getRuleImplementation(mockRule)); + assertEquals("No rule implementation found for type: MOCK_TYPE", exception.getMessage()); } private void mockInsertElection(DataAccessRequest dar, Dataset dataset, Integer electionId) { when(electionDAO.insertElection( - eq(ElectionType.DATA_ACCESS.getValue()), - eq(ElectionStatus.OPEN.getValue()), - any(Date.class), - eq(dar.getReferenceId()), - eq(dataset.getDatasetId()) - )).thenReturn(electionId); + eq(ElectionType.DATA_ACCESS.getValue()), + eq(ElectionStatus.OPEN.getValue()), + any(Date.class), + eq(dar.getReferenceId()), + eq(dataset.getDatasetId()))) + .thenReturn(electionId); } private Vote mockFindVoteById(Integer voteId) { @@ -506,5 +565,4 @@ private Vote mockFindVoteById(Integer voteId) { when(voteDAO.findVoteById(voteId)).thenReturn(vote); return vote; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/DaaServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DaaServiceTest.java index 177fb778d3..d85554f9fa 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DaaServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DaaServiceTest.java @@ -46,37 +46,31 @@ @ExtendWith(MockitoExtension.class) class DaaServiceTest { - @Mock - private DaaServiceDAO daaServiceDAO; + @Mock private DaaServiceDAO daaServiceDAO; - @Mock - private DaaDAO daaDAO; + @Mock private DaaDAO daaDAO; - @Mock - private GCSService gcsService; + @Mock private GCSService gcsService; - @Mock - private EmailService emailService; + @Mock private EmailService emailService; - @Mock - private UserService userService; + @Mock private UserService userService; - @Mock - private InstitutionDAO institutionDAO; + @Mock private InstitutionDAO institutionDAO; - @Mock - private DacDAO dacDAO; + @Mock private DacDAO dacDAO; private final InputStream inputStream = mock(InputStream.class); - private final FormDataContentDisposition contentDisposition = mock( - FormDataContentDisposition.class); - + private final FormDataContentDisposition contentDisposition = + mock(FormDataContentDisposition.class); private DaaService service; private void initService() { - service = new DaaService(daaServiceDAO, daaDAO, gcsService, emailService, userService, institutionDAO, dacDAO); + service = + new DaaService( + daaServiceDAO, daaDAO, gcsService, emailService, userService, institutionDAO, dacDAO); } @Test @@ -99,8 +93,10 @@ void testCreateDaaWithFsoGCSError() throws Exception { doThrow(new IOException("gcs error")).when(gcsService).storeDocument(any(), any(), any()); initService(); - ServerErrorException e = assertThrows(ServerErrorException.class, - () -> service.createDaaWithFso(1, 1, inputStream, contentDisposition)); + ServerErrorException e = + assertThrows( + ServerErrorException.class, + () -> service.createDaaWithFso(1, 1, inputStream, contentDisposition)); assertNotNull(e); } @@ -110,8 +106,10 @@ void testCreateDaaWithFsoDBError() throws Exception { doThrow(new Exception("db error")).when(daaServiceDAO).createDaaWithFso(any(), any(), any()); initService(); - ServerErrorException e = assertThrows(ServerErrorException.class, - () -> service.createDaaWithFso(1, 1, inputStream, contentDisposition)); + ServerErrorException e = + assertThrows( + ServerErrorException.class, + () -> service.createDaaWithFso(1, 1, inputStream, contentDisposition)); assertNotNull(e); } @@ -167,16 +165,16 @@ void testFindAllWithBroadDaa() { initService(); List foundDaas = service.findAll(); - Optional foundBroadDAA = foundDaas.stream() - .filter(d -> d.getDaaId().equals(broadDAA.getDaaId())).findFirst(); + Optional foundBroadDAA = + foundDaas.stream().filter(d -> d.getDaaId().equals(broadDAA.getDaaId())).findFirst(); assertTrue(foundBroadDAA.isPresent() && foundBroadDAA.get().getBroadDaa()); - Optional foundNonBroadDAA1 = foundDaas.stream() - .filter(d -> d.getDaaId().equals(nonBroadDAA1.getDaaId())).findFirst(); + Optional foundNonBroadDAA1 = + foundDaas.stream().filter(d -> d.getDaaId().equals(nonBroadDAA1.getDaaId())).findFirst(); assertTrue(foundNonBroadDAA1.isPresent() && !foundNonBroadDAA1.get().getBroadDaa()); - Optional foundNonBroadDAA2 = foundDaas.stream() - .filter(d -> d.getDaaId().equals(nonBroadDAA2.getDaaId())).findFirst(); + Optional foundNonBroadDAA2 = + foundDaas.stream().filter(d -> d.getDaaId().equals(nonBroadDAA2.getDaaId())).findFirst(); assertTrue(foundNonBroadDAA2.isPresent() && !foundNonBroadDAA2.get().getBroadDaa()); } @@ -270,12 +268,12 @@ void testSendNewDaaEmails() throws Exception { SimplifiedUser researcher = mock(SimplifiedUser.class); researcher.setDisplayName("Official Name"); researcher.setEmail("official@example.com"); - researcher.setInstitutionId(RandomUtils.nextInt(0,50)); + researcher.setInstitutionId(RandomUtils.nextInt(0, 50)); SimplifiedUser researcher2 = mock(SimplifiedUser.class); researcher2.setDisplayName("Official Name2"); researcher2.setEmail("official2@example.com"); - researcher2.setInstitutionId(RandomUtils.nextInt(0,50)); + researcher2.setInstitutionId(RandomUtils.nextInt(0, 50)); SimplifiedUser signingOfficial = mock(SimplifiedUser.class); signingOfficial.setDisplayName("Official Name"); @@ -294,9 +292,11 @@ void testSendNewDaaEmails() throws Exception { initService(); when(userService.getUsersByDaaId(any())).thenReturn(List.of(researcher, researcher2)); - when(userService.findSOsByInstitutionId(any())).thenReturn(List.of(signingOfficial, signingOfficial2)); + when(userService.findSOsByInstitutionId(any())) + .thenReturn(List.of(signingOfficial, signingOfficial2)); assertDoesNotThrow(() -> service.sendNewDaaEmails(user, 1, "dacName", "newDaaName")); - verify(emailService, times(2)).sendNewDAAUploadResearcherMessage(any(), any(), any(), any(), any()); + verify(emailService, times(2)) + .sendNewDAAUploadResearcherMessage(any(), any(), any(), any(), any()); verify(emailService, times(2)).sendNewDAAUploadSOMessage(any(), any(), any(), any(), any()); } @@ -307,7 +307,7 @@ void testSendNewDaaEmailsOneResearcher() throws Exception { SimplifiedUser researcher = mock(SimplifiedUser.class); researcher.setDisplayName("Official Name"); researcher.setEmail("official@example.com"); - researcher.setInstitutionId(RandomUtils.nextInt(0,50)); + researcher.setInstitutionId(RandomUtils.nextInt(0, 50)); SimplifiedUser signingOfficial = mock(SimplifiedUser.class); signingOfficial.setDisplayName("Official Name"); @@ -326,9 +326,11 @@ void testSendNewDaaEmailsOneResearcher() throws Exception { initService(); when(userService.getUsersByDaaId(any())).thenReturn(List.of(researcher)); - when(userService.findSOsByInstitutionId(any())).thenReturn(List.of(signingOfficial, signingOfficial2)); + when(userService.findSOsByInstitutionId(any())) + .thenReturn(List.of(signingOfficial, signingOfficial2)); assertDoesNotThrow(() -> service.sendNewDaaEmails(user, 1, "dacName", "newDaaName")); - verify(emailService, times(1)).sendNewDAAUploadResearcherMessage(any(), any(), any(), any(), any()); + verify(emailService, times(1)) + .sendNewDAAUploadResearcherMessage(any(), any(), any(), any(), any()); verify(emailService, times(2)).sendNewDAAUploadSOMessage(any(), any(), any(), any(), any()); } @@ -337,7 +339,8 @@ void testSendNewDaaEmailsDAANotFound() throws Exception { User user = mock(User.class); initService(); - assertThrows(NotFoundException.class, () -> service.sendNewDaaEmails(user, 1, "dacName", "newDaaName")); + assertThrows( + NotFoundException.class, () -> service.sendNewDaaEmails(user, 1, "dacName", "newDaaName")); } @Test @@ -350,7 +353,6 @@ void testSendNewDaaEmailsDAANoResearchersAndSOs() throws Exception { when(daa.getFile()).thenReturn(file); when(daaDAO.findById(any())).thenReturn(daa); - initService(); when(userService.getUsersByDaaId(any())).thenReturn(List.of()); @@ -480,7 +482,7 @@ private DataAccessAgreement createDaa(int daaId) { @Test void testFindDAAsInJsonArray() { String json = "{daaList:[1,2,3]}"; - List daaList = List.of(createDaa(0), createDaa(1), createDaa(2)); + List daaList = List.of(createDaa(0), createDaa(1), createDaa(2)); when(daaDAO.findById(any())).thenReturn(daaList.get(0), daaList.get(1), daaList.get(2)); initService(); List result = service.findDAAsInJsonArray(json, "daaList"); @@ -490,7 +492,7 @@ void testFindDAAsInJsonArray() { @Test void testFindDAAsInJsonArrayRemoveDuplicates() { String json = "{daaList:[1,1,2,3]}"; - List daaList = List.of(createDaa(0), createDaa(1), createDaa(2)); + List daaList = List.of(createDaa(0), createDaa(1), createDaa(2)); when(daaDAO.findById(any())).thenReturn(daaList.get(0), daaList.get(1), daaList.get(2)); initService(); List result = service.findDAAsInJsonArray(json, "daaList"); @@ -537,7 +539,7 @@ void testDeleteDaaDaaNotFound() { @Test void testIsBroadDAANoDaasNoDacs() { initService(); - assertFalse(service.isBroadDAA(RandomUtils.nextInt(0,50), List.of(), List.of())); + assertFalse(service.isBroadDAA(RandomUtils.nextInt(0, 50), List.of(), List.of())); } @Test @@ -560,7 +562,7 @@ void testIsBroadDAANoBroadDacs() { Dac dac = new Dac(); dac.setName("dacName"); - Dac dac2= new Dac(); + Dac dac2 = new Dac(); dac2.setName("dacName2"); DataAccessAgreement daa1 = new DataAccessAgreement(); @@ -580,16 +582,16 @@ void testIsBroadDAANoMatchingDaa() { dac.setName("dacName"); dac.setDacId(1); - Dac dac2= new Dac(); + Dac dac2 = new Dac(); dac2.setName("broadDac"); dac2.setDacId(2); DataAccessAgreement daa1 = new DataAccessAgreement(); DataAccessAgreement daa2 = new DataAccessAgreement(); daa1.setDaaId(1); - daa1.setInitialDacId(RandomUtils.nextInt(3,50)); + daa1.setInitialDacId(RandomUtils.nextInt(3, 50)); daa2.setDaaId(2); - daa2.setInitialDacId(RandomUtils.nextInt(3,50)); + daa2.setInitialDacId(RandomUtils.nextInt(3, 50)); assertFalse(service.isBroadDAA(1, List.of(daa1, daa2), List.of(dac, dac2))); assertFalse(service.isBroadDAA(2, List.of(daa1, daa2), List.of(dac, dac2))); @@ -603,14 +605,14 @@ void testIsBroadDAAMatching() { dac.setName("dacName"); dac.setDacId(1); - Dac dac2= new Dac(); + Dac dac2 = new Dac(); dac2.setName("broadDac"); dac2.setDacId(2); DataAccessAgreement daa1 = new DataAccessAgreement(); DataAccessAgreement daa2 = new DataAccessAgreement(); daa1.setDaaId(1); - daa1.setInitialDacId(RandomUtils.nextInt(3,50)); + daa1.setInitialDacId(RandomUtils.nextInt(3, 50)); daa2.setDaaId(2); daa2.setInitialDacId(2); @@ -624,7 +626,8 @@ void testFindByDarReferenceId() { DataAccessAgreement daa1 = new DataAccessAgreement(); when(daaDAO.findByDarReferenceId(any())).thenReturn(List.of(daa1)); - List daas = service.findByDarReferenceId(RandomStringUtils.randomAlphabetic(5)); + List daas = + service.findByDarReferenceId(RandomStringUtils.randomAlphabetic(5)); assertFalse(daas.isEmpty()); assertTrue(daas.stream().map(DataAccessAgreement::getDaaId).toList().contains(daa1.getDaaId())); } @@ -634,8 +637,8 @@ void testFindByDarReferenceIdNoResults() { initService(); when(daaDAO.findByDarReferenceId(any())).thenReturn(List.of()); - List daas = service.findByDarReferenceId(RandomStringUtils.randomAlphabetic(5)); + List daas = + service.findByDarReferenceId(RandomStringUtils.randomAlphabetic(5)); assertTrue(daas.isEmpty()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/DacServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DacServiceTest.java index c212be791c..3022fe87b9 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DacServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DacServiceTest.java @@ -29,7 +29,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.broadinstitute.consent.http.AbstractTestHelper; -import org.apache.commons.lang3.RandomUtils; import org.broadinstitute.consent.http.db.DACAutomationRuleDAO; import org.broadinstitute.consent.http.db.DacDAO; import org.broadinstitute.consent.http.db.DataAccessRequestDAO; @@ -61,36 +60,36 @@ class DacServiceTest extends AbstractTestHelper { private DacService service; - @Mock - private DacDAO dacDAO; + @Mock private DacDAO dacDAO; - @Mock - private UserDAO userDAO; + @Mock private UserDAO userDAO; - @Mock - private DatasetDAO dataSetDAO; + @Mock private DatasetDAO dataSetDAO; - @Mock - private ElectionDAO electionDAO; + @Mock private ElectionDAO electionDAO; - @Mock - DataAccessRequestDAO dataAccessRequestDAO; + @Mock DataAccessRequestDAO dataAccessRequestDAO; - @Mock - private VoteService voteService; + @Mock private VoteService voteService; - @Mock - private DaaService daaService; + @Mock private DaaService daaService; - @Mock - private DacServiceDAO dacServiceDAO; + @Mock private DacServiceDAO dacServiceDAO; - @Mock - private DACAutomationRuleDAO ruleDAO; + @Mock private DACAutomationRuleDAO ruleDAO; private void initService() { - service = new DacService(dacDAO, userDAO, dataSetDAO, electionDAO, dataAccessRequestDAO, - voteService, daaService, dacServiceDAO, ruleDAO); + service = + new DacService( + dacDAO, + userDAO, + dataSetDAO, + electionDAO, + dataAccessRequestDAO, + voteService, + daaService, + dacServiceDAO, + ruleDAO); } @Test @@ -104,12 +103,12 @@ void testFindAll() { @Test void testFindAllWithDaas() { Dac broadDac = new Dac(); - int broadDacId = randomInt(3,50); + int broadDacId = randomInt(3, 50); broadDac.setName("broadDac"); broadDac.setDacId(broadDacId); Dac dac2 = new Dac(); - int dac2Id = randomInt(3,50); + int dac2Id = randomInt(3, 50); dac2.setName("dac2"); dac2.setDacId(dac2Id); @@ -138,10 +137,10 @@ void testFindAllWithDaas() { void testFindById() { int dacId = 1; when(dacDAO.findById(dacId)).thenReturn(getDacs().get(0)); - when(dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.CHAIRPERSON.getRoleId())).thenReturn( - Collections.singletonList(getDacUsers().get(0))); - when(dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.MEMBER.getRoleId())).thenReturn( - Collections.singletonList(getDacUsers().get(1))); + when(dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.CHAIRPERSON.getRoleId())) + .thenReturn(Collections.singletonList(getDacUsers().get(0))); + when(dacDAO.findMembersByDacIdAndRoleId(dacId, UserRoles.MEMBER.getRoleId())) + .thenReturn(Collections.singletonList(getDacUsers().get(1))); when(daaService.isBroadDAA(anyInt(), any(), any())).thenReturn(true); initService(); @@ -164,8 +163,8 @@ void testCreateDac() { @Test void testCreateDacWithEmail() { - when(dacDAO.createDac(anyString(), anyString(), anyString(), any())).thenReturn( - getDacs().get(0).getDacId()); + when(dacDAO.createDac(anyString(), anyString(), anyString(), any())) + .thenReturn(getDacs().get(0).getDacId()); initService(); Integer dacId = service.createDac("name", "description", "email@test.com"); @@ -212,13 +211,7 @@ void testDeleteDacServiceDAOException() throws SQLException { } @ParameterizedTest - @ValueSource(strings = { - "Broad DAC", - "Dac 2", - "Dac 3", - "Dac 4", - "Dac 5" - }) + @ValueSource(strings = {"Broad DAC", "Dac 2", "Dac 3", "Dac 4", "Dac 5"}) void testDeleteDac(String dacName) { DataAccessAgreement daa = new DataAccessAgreement(); daa.setDaaId(randomInt(1, 10)); @@ -251,8 +244,8 @@ void testFindDatasetsByDacId() { @Test void testFindMembersByDacId() { - when(dacDAO.findMembersByDacId(anyInt())).thenReturn( - Collections.singletonList(getDacUsers().get(0))); + when(dacDAO.findMembersByDacId(anyInt())) + .thenReturn(Collections.singletonList(getDacUsers().get(0))); when(dacDAO.findUserRolesForUsers(any())).thenReturn(getDacUsers().get(0).getRoles()); initService(); @@ -268,14 +261,16 @@ void testAddDacMember() { Dac dac = getDacs().get(0); when(userDAO.findUserById(any())).thenReturn(user); when(userDAO.findUserById(any())).thenReturn(user); - List elections = getElections().stream(). - map(e -> { - Election newE = gson.fromJson(gson.toJson(e), Election.class); - newE.setElectionType(ElectionType.DATA_ACCESS.getValue()); - newE.setReferenceId(UUID.randomUUID().toString()); - return newE; - }). - collect(Collectors.toList()); + List elections = + getElections().stream() + .map( + e -> { + Election newE = gson.fromJson(gson.toJson(e), Election.class); + newE.setElectionType(ElectionType.DATA_ACCESS.getValue()); + newE.setReferenceId(UUID.randomUUID().toString()); + return newE; + }) + .collect(Collectors.toList()); DataAccessRequest dar = new DataAccessRequest(); dar.setData(new DataAccessRequestData()); when(dataAccessRequestDAO.findByReferenceId(any())).thenReturn(dar); @@ -287,8 +282,8 @@ void testAddDacMember() { User user1 = service.addDacMember(role, user, dac); assertNotNull(user1); assertFalse(user1.getRoles().isEmpty()); - verify(voteService, times(elections.size())).createVotesForUser(any(), any(), any(), - anyBoolean()); + verify(voteService, times(elections.size())) + .createVotesForUser(any(), any(), any(), anyBoolean()); } @Test @@ -343,12 +338,14 @@ void testRemoveDacChairFailure() { dac.setMembers(Collections.singletonList(getDacUsers().get(1))); initService(); - assertThrows(BadRequestException.class, () -> { - service.removeDacMember(role, chair, dac, 1); - verify(dacDAO, times(0)).removeDacMember(anyInt()); - verify(voteService, times(0)).deleteOpenDacVotesForUser(any(), any()); - verify(ruleDAO, times(0)).auditedDeleteDACRuleSettingByUser(anyInt(), anyInt(), anyInt()); - }); + assertThrows( + BadRequestException.class, + () -> { + service.removeDacMember(role, chair, dac, 1); + verify(dacDAO, times(0)).removeDacMember(anyInt()); + verify(voteService, times(0)).deleteOpenDacVotesForUser(any(), any()); + verify(ruleDAO, times(0)).auditedDeleteDACRuleSettingByUser(anyInt(), anyInt(), anyInt()); + }); } @Test @@ -371,7 +368,8 @@ void testFilterDataAccessRequestsByDAC_adminCase() { void testFilterDataAccessRequestsByDAC_memberCase_1() { // Member has access to DataSet 1 List memberDataSets = Collections.singletonList(getDatasets().get(0)); - when(dataSetDAO.findDatasetIdsByDACUserId(getMember().getUserId())).thenReturn(List.of(memberDataSets.get(0).getDatasetId())); + when(dataSetDAO.findDatasetIdsByDACUserId(getMember().getUserId())) + .thenReturn(List.of(memberDataSets.get(0).getDatasetId())); initService(); @@ -387,7 +385,8 @@ void testFilterDataAccessRequestsByDAC_memberCase_1() { void testFilterDataAccessRequestsByDAC_memberCase_2() { // Member has access to datasets List memberDataSets = Collections.singletonList(getDatasets().get(0)); - when(dataSetDAO.findDatasetIdsByDACUserId(getMember().getUserId())).thenReturn(List.of(memberDataSets.get(0).getDatasetId())); + when(dataSetDAO.findDatasetIdsByDACUserId(getMember().getUserId())) + .thenReturn(List.of(memberDataSets.get(0).getDatasetId())); initService(); @@ -435,10 +434,8 @@ void testFindDacsByUserChairCase() { assertEquals(dacsForUser.size(), dacs.size()); } - /* Helper functions */ - private AuthUser getUser() { return new AuthUser("User"); } @@ -447,42 +444,48 @@ private AuthUser getUser() { * @return A list of 5 elections with DataSet ids */ private List getElections() { - return IntStream.range(1, 5). - mapToObj(i -> { - Election election = new Election(); - election.setDatasetId(i); - return election; - }).collect(Collectors.toList()); + return IntStream.range(1, 5) + .mapToObj( + i -> { + Election election = new Election(); + election.setDatasetId(i); + return election; + }) + .collect(Collectors.toList()); } /** * @return A list of 5 DataAccessRequest with DataSet ids and Reference ids */ private List getDataAccessRequests() { - return IntStream.range(1, 5). - mapToObj(i -> { - String referenceId = UUID.randomUUID().toString(); - List datasetIds = Collections.singletonList(i); - DataAccessRequest dar = new DataAccessRequest(); - dar.setReferenceId(referenceId); - DataAccessRequestData data = new DataAccessRequestData(); - dar.setDatasetIds(datasetIds); - data.setReferenceId(referenceId); - dar.setData(data); - return dar; - }).collect(Collectors.toList()); + return IntStream.range(1, 5) + .mapToObj( + i -> { + String referenceId = UUID.randomUUID().toString(); + List datasetIds = Collections.singletonList(i); + DataAccessRequest dar = new DataAccessRequest(); + dar.setReferenceId(referenceId); + DataAccessRequestData data = new DataAccessRequestData(); + dar.setDatasetIds(datasetIds); + data.setReferenceId(referenceId); + dar.setData(data); + return dar; + }) + .collect(Collectors.toList()); } /** * @return A list of 5 datasets with ids */ private List getDatasets() { - return IntStream.range(1, 5). - mapToObj(i -> { - Dataset dataSet = new Dataset(); - dataSet.setDatasetId(i); - return dataSet; - }).collect(Collectors.toList()); + return IntStream.range(1, 5) + .mapToObj( + i -> { + Dataset dataSet = new Dataset(); + dataSet.setDatasetId(i); + return dataSet; + }) + .collect(Collectors.toList()); } /** @@ -491,15 +494,17 @@ private List getDatasets() { private List getDacs() { DataAccessAgreement daa = new DataAccessAgreement(); daa.setDaaId(1); - return IntStream.range(1, 5). - mapToObj(i -> { - Dac dac = new Dac(); - dac.setDacId(i); - dac.setDescription("Dac " + i); - dac.setName("Dac " + i); - dac.setAssociatedDaa(daa); - return dac; - }).collect(Collectors.toList()); + return IntStream.range(1, 5) + .mapToObj( + i -> { + Dac dac = new Dac(); + dac.setDacId(i); + dac.setDescription("Dac " + i); + dac.setName("Dac " + i); + dac.setAssociatedDaa(daa); + return dac; + }) + .collect(Collectors.toList()); } /** @@ -515,8 +520,15 @@ private User getChair() { chair.setDisplayName("Chair"); chair.setEmail("chair@duos.org"); chair.setRoles(new ArrayList<>()); - chair.getRoles().add(new UserRole(1, chair.getUserId(), UserRoles.CHAIRPERSON.getRoleId(), - UserRoles.CHAIRPERSON.getRoleName(), 1)); + chair + .getRoles() + .add( + new UserRole( + 1, + chair.getUserId(), + UserRoles.CHAIRPERSON.getRoleId(), + UserRoles.CHAIRPERSON.getRoleName(), + 1)); return chair; } @@ -526,9 +538,15 @@ private User getMember() { member.setDisplayName("Member"); member.setEmail("member@duos.org"); member.setRoles(new ArrayList<>()); - member.getRoles().add(new UserRole(2, member.getUserId(), UserRoles.MEMBER.getRoleId(), - UserRoles.MEMBER.getRoleName(), 1)); + member + .getRoles() + .add( + new UserRole( + 2, + member.getUserId(), + UserRoles.MEMBER.getRoleId(), + UserRoles.MEMBER.getRoleName(), + 1)); return member; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/DarCollectionServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DarCollectionServiceTest.java index 7f393a6a37..73b12fe0ee 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DarCollectionServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DarCollectionServiceTest.java @@ -74,28 +74,17 @@ class DarCollectionServiceTest extends AbstractTestHelper { private DarCollectionService service; - @Mock - private DarCollectionDAO darCollectionDAO; - @Mock - private DarCollectionSummaryDAO darCollectionSummaryDAO; - @Mock - private DarCollectionServiceDAO darCollectionServiceDAO; - @Mock - private DatasetDAO datasetDAO; - @Mock - private ElectionDAO electionDAO; - @Mock - private DataAccessRequestDAO dataAccessRequestDAO; - @Mock - private EmailService emailService; - @Mock - private VoteDAO voteDAO; - @Mock - private UserDAO userDAO; - @Mock - private DacDAO dacDAO; - @Mock - private Jdbi jdbi; + @Mock private DarCollectionDAO darCollectionDAO; + @Mock private DarCollectionSummaryDAO darCollectionSummaryDAO; + @Mock private DarCollectionServiceDAO darCollectionServiceDAO; + @Mock private DatasetDAO datasetDAO; + @Mock private ElectionDAO electionDAO; + @Mock private DataAccessRequestDAO dataAccessRequestDAO; + @Mock private EmailService emailService; + @Mock private VoteDAO voteDAO; + @Mock private UserDAO userDAO; + @Mock private DacDAO dacDAO; + @Mock private Jdbi jdbi; @BeforeEach void setUp() { @@ -114,10 +103,7 @@ void setUp() { void testAddDatasetsToCollection() { Set datasets = new HashSet<>(); DarCollection collection = generateMockDarCollection(datasets); - List datasetIds = datasets.stream() - .map(Dataset::getDatasetId) - .sorted() - .toList(); + List datasetIds = datasets.stream().map(Dataset::getDatasetId).sorted().toList(); when(datasetDAO.findDatasetsByIdList(anyList())).thenReturn(List.copyOf(datasets)); when(dataAccessRequestDAO.findAllDARDatasetRelations(any())).thenReturn(datasetIds); @@ -128,10 +114,8 @@ void testAddDatasetsToCollection() { Set datasetsFromCollection = collection.getDatasets(); assertEquals(datasetIds.size(), datasetsFromCollection.size()); - List collectionDatasetIds = datasetsFromCollection.stream() - .map(Dataset::getDatasetId) - .sorted() - .toList(); + List collectionDatasetIds = + datasetsFromCollection.stream().map(Dataset::getDatasetId).sorted().toList(); assertEquals(datasetIds, collectionDatasetIds); } @@ -153,8 +137,7 @@ void testGetByCollectionId_NotFound() { Integer collectionId = 1; when(darCollectionDAO.findDARCollectionByCollectionId(collectionId)).thenReturn(null); - assertThrows(NotFoundException.class, () -> - service.getByCollectionId(user, collectionId)); + assertThrows(NotFoundException.class, () -> service.getByCollectionId(user, collectionId)); } @Test @@ -165,13 +148,15 @@ void testGetCollectionById_ServiceException() { when(darCollectionDAO.findDARCollectionByCollectionId(collectionId)) .thenThrow(expectedException); - RuntimeException exception = assertThrows(RuntimeException.class, () -> - service.getByCollectionId(user, collectionId)); + RuntimeException exception = + assertThrows(RuntimeException.class, () -> service.getByCollectionId(user, collectionId)); assertEquals(expectedException, exception); } @ParameterizedTest - @EnumSource(value = UserRoles.class, names = {"ADMIN", "MEMBER", "CHAIRPERSON"}) + @EnumSource( + value = UserRoles.class, + names = {"ADMIN", "MEMBER", "CHAIRPERSON"}) void testGetByCollectionIdWithVotes(UserRoles role) { User user = new User(); user.addRole(new UserRole(role.getRoleId(), role.getRoleName())); @@ -181,17 +166,26 @@ void testGetByCollectionIdWithVotes(UserRoles role) { DarCollection result = service.getByCollectionId(user, collectionId); assertNotNull(result); - List votes = result.getDars().values().stream() - .flatMap(d -> d.getElections().values().stream()) - .map(Election::getVotes) - .flatMap(v -> v.values().stream()) - .toList(); + List votes = + result.getDars().values().stream() + .flatMap(d -> d.getElections().values().stream()) + .map(Election::getVotes) + .flatMap(v -> v.values().stream()) + .toList(); assertFalse(votes.isEmpty()); } @ParameterizedTest - @EnumSource(value = UserRoles.class, names = {"RESEARCHER", "ALUMNI", "SIGNINGOFFICIAL", - "DATASUBMITTER", "ITDIRECTOR", "SERVICE_ACCOUNT"}) + @EnumSource( + value = UserRoles.class, + names = { + "RESEARCHER", + "ALUMNI", + "SIGNINGOFFICIAL", + "DATASUBMITTER", + "ITDIRECTOR", + "SERVICE_ACCOUNT" + }) void testGetByCollectionIdWithoutVotes(UserRoles role) { User user = new User(); user.addRole(new UserRole(role.getRoleId(), role.getRoleName())); @@ -201,11 +195,12 @@ void testGetByCollectionIdWithoutVotes(UserRoles role) { DarCollection result = service.getByCollectionId(user, collectionId); assertNotNull(result); - List votes = result.getDars().values().stream() - .flatMap(d -> d.getElections().values().stream()) - .map(Election::getVotes) - .flatMap(v -> v.values().stream()) - .toList(); + List votes = + result.getDars().values().stream() + .flatMap(d -> d.getElections().values().stream()) + .map(Election::getVotes) + .flatMap(v -> v.values().stream()) + .toList(); assertTrue(votes.isEmpty()); } @@ -216,8 +211,8 @@ void testGetCollectionWithAllElectionsByCollectionId() { Integer collectionId = 1; DarCollection collection = new DarCollection(); collection.setDarCollectionId(collectionId); - when(darCollectionDAO.findCollectionWithAllElectionsByCollectionId(collectionId)).thenReturn( - collection); + when(darCollectionDAO.findCollectionWithAllElectionsByCollectionId(collectionId)) + .thenReturn(collection); DarCollection result = service.getCollectionWithAllElectionsByCollectionId(user, collectionId); assertNotNull(result); @@ -229,11 +224,12 @@ void testGetCollectionWithAllElectionsByCollectionId_NotFound() { User user = new User(); user.setAdminRole(); Integer collectionId = 1; - when(darCollectionDAO.findCollectionWithAllElectionsByCollectionId(collectionId)).thenReturn( - null); + when(darCollectionDAO.findCollectionWithAllElectionsByCollectionId(collectionId)) + .thenReturn(null); - assertThrows(NotFoundException.class, () -> - service.getCollectionWithAllElectionsByCollectionId(user, collectionId)); + assertThrows( + NotFoundException.class, + () -> service.getCollectionWithAllElectionsByCollectionId(user, collectionId)); } @Test @@ -245,12 +241,13 @@ void testGetCollectionWithAllElectionsByCollectionId_ServiceException() { when(darCollectionDAO.findCollectionWithAllElectionsByCollectionId(collectionId)) .thenThrow(expectedException); - RuntimeException exception = assertThrows(RuntimeException.class, () -> - service.getCollectionWithAllElectionsByCollectionId(user, collectionId)); + RuntimeException exception = + assertThrows( + RuntimeException.class, + () -> service.getCollectionWithAllElectionsByCollectionId(user, collectionId)); assertEquals(expectedException, exception); } - @Test void testGetCollectionWithElectionsByCollectionIdAndDatasetIds() { User user = mock(User.class); @@ -258,11 +255,13 @@ void testGetCollectionWithElectionsByCollectionIdAndDatasetIds() { DarCollection collection = new DarCollection(); collection.setDarCollectionId(collectionId); List datasetIds = List.of(1, 2, 3); - when(darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds(datasetIds, - collectionId)).thenReturn(collection); + when(darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetIds, collectionId)) + .thenReturn(collection); - DarCollection result = service.getCollectionWithElectionsByCollectionIdAndDatasetIds(user, - datasetIds, collectionId); + DarCollection result = + service.getCollectionWithElectionsByCollectionIdAndDatasetIds( + user, datasetIds, collectionId); assertNotNull(result); assertEquals(collectionId, result.getDarCollectionId()); } @@ -272,12 +271,15 @@ void testGetCollectionWithElectionsByCollectionIdAndDatasetIds_NotFound() { User user = mock(User.class); Integer collectionId = 1; List datasetIds = List.of(1, 2, 3); - when(darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds(datasetIds, - collectionId)).thenReturn(null); + when(darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetIds, collectionId)) + .thenReturn(null); - assertThrows(NotFoundException.class, () -> - service.getCollectionWithElectionsByCollectionIdAndDatasetIds(user, datasetIds, - collectionId)); + assertThrows( + NotFoundException.class, + () -> + service.getCollectionWithElectionsByCollectionIdAndDatasetIds( + user, datasetIds, collectionId)); } @Test @@ -286,13 +288,16 @@ void testGetCollectionWithElectionsByCollectionIdAndDatasetIds_ServiceException( Integer collectionId = 1; List datasetIds = List.of(1, 2, 3); RuntimeException expectedException = new RuntimeException("Test exception"); - when(darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds(datasetIds, - collectionId)) + when(darCollectionDAO.findCollectionWithElectionsByCollectionIdAndDatasetIds( + datasetIds, collectionId)) .thenThrow(expectedException); - RuntimeException exception = assertThrows(RuntimeException.class, () -> - service.getCollectionWithElectionsByCollectionIdAndDatasetIds(user, datasetIds, - collectionId)); + RuntimeException exception = + assertThrows( + RuntimeException.class, + () -> + service.getCollectionWithElectionsByCollectionIdAndDatasetIds( + user, datasetIds, collectionId)); assertEquals(expectedException, exception); } @@ -303,15 +308,15 @@ void testCancelDarCollection_noElections() { collection.getDars().values().forEach(d -> d.getData().setStatus("Canceled")); when(darCollectionDAO.findDARCollectionByCollectionId(any())).thenReturn(collection); when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collection.getDarCollectionId())) + collection.getDarCollectionId())) .thenReturn(new DarCollectionSummary()); User user = new User(); user.setUserId(1); collection.setCreateUserId(user.getUserId()); when(electionDAO.findLastElectionsByReferenceIds(anyList())).thenReturn(List.of()); - DarCollection canceledCollection = service.cancelDarCollectionByRole(user, collection, - UserRoles.RESEARCHER); + DarCollection canceledCollection = + service.cancelDarCollectionByRole(user, collection, UserRoles.RESEARCHER); for (DataAccessRequest collectionDar : canceledCollection.getDars().values()) { assertEquals("canceled", collectionDar.getData().getStatus().toLowerCase()); } @@ -322,10 +327,10 @@ void testCancelDarCollection_electionPresent() { Set datasets = new HashSet<>(); DarCollection collection = generateMockDarCollection(datasets); - when(electionDAO.findLastElectionsByReferenceIds(anyList())).thenReturn( - List.of(new Election())); + when(electionDAO.findLastElectionsByReferenceIds(anyList())) + .thenReturn(List.of(new Election())); when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collection.getDarCollectionId())) + collection.getDarCollectionId())) .thenReturn(new DarCollectionSummary()); User user = new User(); @@ -347,7 +352,7 @@ void testCancelDarCollectionAsResearcher_NoElections() { when(electionDAO.findLastElectionsByReferenceIds(anyList())).thenReturn(List.of()); when(darCollectionDAO.findDARCollectionByCollectionId(any())).thenReturn(collection); when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collection.getDarCollectionId())) + collection.getDarCollectionId())) .thenReturn(new DarCollectionSummary()); User user = new User(); @@ -357,8 +362,8 @@ void testCancelDarCollectionAsResearcher_NoElections() { verify(electionDAO).findLastElectionsByReferenceIds(anyList()); verify(electionDAO, times(0)).updateElectionById(anyInt(), anyString(), any()); verify(dataAccessRequestDAO).cancelByReferenceIds(anyList()); - verify(darCollectionDAO, atLeastOnce()).findDARCollectionByCollectionId( - collection.getDarCollectionId()); + verify(darCollectionDAO, atLeastOnce()) + .findDARCollectionByCollectionId(collection.getDarCollectionId()); } @Test @@ -378,7 +383,7 @@ void testCancelDarCollectionAsResearcher_WithElections() { collection.setCreateUserId(user.getUserId()); when(electionDAO.findLastElectionsByReferenceIds(anyList())).thenReturn(List.of(election)); when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collection.getDarCollectionId())) + collection.getDarCollectionId())) .thenReturn(new DarCollectionSummary()); assertThrows( @@ -399,15 +404,15 @@ void testCancelDarCollectionAsAdmin() { election.setStatus(ElectionStatus.OPEN.getValue()); election.setElectionId(1); when(electionDAO.findOpenElectionsByReferenceIds(anyList())).thenReturn(List.of(election)); - when(darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId())) + .thenReturn(collection); service.cancelDarCollectionByRole(new User(), collection, UserRoles.ADMIN); verify(electionDAO).findOpenElectionsByReferenceIds(anyList()); verify(electionDAO).updateElectionById(anyInt(), anyString(), any()); verify(dataAccessRequestDAO, times(0)).cancelByReferenceIds(anyList()); - verify(darCollectionDAO, atLeastOnce()).findDARCollectionByCollectionId( - collection.getDarCollectionId()); + verify(darCollectionDAO, atLeastOnce()) + .findDARCollectionByCollectionId(collection.getDarCollectionId()); } @Test @@ -427,19 +432,19 @@ void testCancelDarCollectionAsChair_ChairHasDatasets() { election.setReferenceId(dar.getReferenceId()); election.setStatus(ElectionStatus.OPEN.getValue()); election.setElectionId(1); - when(datasetDAO.findDatasetIdsByDACUserId(anyInt())).thenReturn( - List.of(dataset.getDatasetId())); + when(datasetDAO.findDatasetIdsByDACUserId(anyInt())) + .thenReturn(List.of(dataset.getDatasetId())); when(electionDAO.findOpenElectionsByReferenceIds(anyList())).thenReturn(List.of(election)); - when(darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId())) + .thenReturn(collection); service.cancelDarCollectionByRole(user, collection, UserRoles.CHAIRPERSON); verify(datasetDAO).findDatasetIdsByDACUserId(anyInt()); verify(electionDAO).findOpenElectionsByReferenceIds(anyList()); verify(electionDAO).updateElectionById(anyInt(), anyString(), any()); verify(dataAccessRequestDAO, times(0)).cancelByReferenceIds(anyList()); - verify(darCollectionDAO, atLeastOnce()).findDARCollectionByCollectionId( - collection.getDarCollectionId()); + verify(darCollectionDAO, atLeastOnce()) + .findDARCollectionByCollectionId(collection.getDarCollectionId()); } @Test @@ -460,8 +465,8 @@ void testCancelDarCollectionAsChair_ChairHasNoDatasets() { election.setStatus(ElectionStatus.OPEN.getValue()); election.setElectionId(1); when(datasetDAO.findDatasetIdsByDACUserId(anyInt())).thenReturn(List.of()); - when(darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId())) + .thenReturn(collection); service.cancelDarCollectionByRole(user, collection, UserRoles.CHAIRPERSON); verify(datasetDAO).findDatasetIdsByDACUserId(anyInt()); @@ -476,7 +481,7 @@ void cancelDarCollectionByRole_ProgressReport() { summary.addParentChildRelationship(123, "456"); summary.setSubmissionDate(new Timestamp(0)); when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId( - collection.getDarCollectionId())) + collection.getDarCollectionId())) .thenReturn(summary); User user = new User(); user.setUserId(1); @@ -502,11 +507,11 @@ void testCreateElectionsForDarCollection() throws Exception { dar.setReferenceId(UUID.randomUUID().toString()); DarCollection collection = createMockCollections().get(0); collection.addDar(dar); - when(darCollectionServiceDAO.createElectionsForDarByUser(any(), any())).thenReturn( - List.of("electionId")); + when(darCollectionServiceDAO.createElectionsForDarByUser(any(), any())) + .thenReturn(List.of("electionId")); when(voteDAO.findVoteUsersByElectionReferenceIdList(any())).thenReturn(List.of(new User())); - when(darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId())) + .thenReturn(collection); service.createElectionsForDarCollection(user, collection); verify(darCollectionServiceDAO).createElectionsForDarByUser(any(), eq(dar)); @@ -537,8 +542,8 @@ void testCreateElectionsForProgressReport() throws Exception { .thenReturn(List.of(electionId)); when(voteDAO.findVoteUsersByElectionReferenceIdList(List.of(electionId))) .thenReturn(List.of(voteUser)); - when(darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId())) + .thenReturn(collection); service.createElectionsForDarCollection(user, collection); @@ -556,7 +561,8 @@ void testCreateElectionsForDarCollectionEmpty() { DarCollection collection = createMockCollections().get(0); collection.addDar(dar); - assertThrows(IllegalStateException.class, + assertThrows( + IllegalStateException.class, () -> service.createElectionsForDarCollection(user, collection)); } @@ -569,12 +575,11 @@ void testCreateElectionsForDarCollectionVoteUsersException() throws Exception { DarCollection collection = createMockCollections().get(0); collection.addDar(dar); List electionIds = List.of("electionId"); - when(darCollectionServiceDAO.createElectionsForDarByUser(user, dar)).thenReturn( - electionIds); - when(voteDAO.findVoteUsersByElectionReferenceIdList(electionIds)).thenThrow( - IllegalArgumentException.class); - when(darCollectionDAO.findDARCollectionByCollectionId( - collection.getDarCollectionId())).thenReturn(collection); + when(darCollectionServiceDAO.createElectionsForDarByUser(user, dar)).thenReturn(electionIds); + when(voteDAO.findVoteUsersByElectionReferenceIdList(electionIds)) + .thenThrow(IllegalArgumentException.class); + when(darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId())) + .thenReturn(collection); service.createElectionsForDarCollection(user, collection); verify(darCollectionServiceDAO).createElectionsForDarByUser(user, dar); @@ -595,16 +600,15 @@ void testProcessDarCollectionSummariesForDAC_SO_InProcess() { datasetOne.setDatasetId(1); summary.addElection(electionOne); summary.addDatasetId(datasetOne.getDatasetId()); - when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(any())).thenReturn( - List.of(summary)); + when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(any())) + .thenReturn(List.of(summary)); - List summaries = service.getSummariesForRole(user, - UserRoles.SIGNINGOFFICIAL); + List summaries = + service.getSummariesForRole(user, UserRoles.SIGNINGOFFICIAL); assertNotNull(summaries); assertEquals(1, summaries.size()); DarCollectionSummary s = summaries.get(0); - assertTrue( - s.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); + assertTrue(s.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); } @Test @@ -626,16 +630,15 @@ void testProcessDarCollectionSummariesForDAC_SO_Complete() { summary.addElection(electionTwo); summary.addDatasetId(datasetOne.getDatasetId()); summary.addDatasetId(datasetTwo.getDatasetId()); - when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(any())).thenReturn( - List.of(summary)); + when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(any())) + .thenReturn(List.of(summary)); - List summaries = service.getSummariesForRole(user, - UserRoles.SIGNINGOFFICIAL); + List summaries = + service.getSummariesForRole(user, UserRoles.SIGNINGOFFICIAL); assertNotNull(summaries); assertEquals(1, summaries.size()); DarCollectionSummary s = summaries.get(0); - assertTrue( - s.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); + assertTrue(s.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); } @Test @@ -649,16 +652,15 @@ void testProcessDarCollectionSummariesForDAC_SO_Unreviewed() { datasetTwo.setDatasetId(2); summary.addDatasetId(datasetOne.getDatasetId()); summary.addDatasetId(datasetTwo.getDatasetId()); - when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(any())).thenReturn( - List.of(summary)); + when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(any())) + .thenReturn(List.of(summary)); - List summaries = service.getSummariesForRole(user, - UserRoles.SIGNINGOFFICIAL); + List summaries = + service.getSummariesForRole(user, UserRoles.SIGNINGOFFICIAL); assertNotNull(summaries); assertEquals(1, summaries.size()); DarCollectionSummary s = summaries.get(0); - assertTrue( - s.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); + assertTrue(s.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); } @Test @@ -668,8 +670,7 @@ void testProcessDarCollectionSummariesForAdminWithCloseout() { DarCollectionSummary summary = new DarCollectionSummary(); summary.setLatestReferenceId(UUID.randomUUID().toString()); summary.setCloseoutSupplement(new CloseoutSupplement(List.of("Closeout"), "Closeout", 1)); - when(darCollectionSummaryDAO.getDarCollectionSummariesForAdmin()) - .thenReturn(List.of(summary)); + when(darCollectionSummaryDAO.getDarCollectionSummariesForAdmin()).thenReturn(List.of(summary)); List summaries = service.getSummariesForRole(user, UserRoles.ADMIN); @@ -685,8 +686,7 @@ void testProcessDarCollectionSummariesForAdminWithoutCloseout() { user.setUserId(1); DarCollectionSummary summary = new DarCollectionSummary(); summary.setLatestReferenceId(UUID.randomUUID().toString()); - when(darCollectionSummaryDAO.getDarCollectionSummariesForAdmin()) - .thenReturn(List.of(summary)); + when(darCollectionSummaryDAO.getDarCollectionSummariesForAdmin()).thenReturn(List.of(summary)); List summaries = service.getSummariesForRole(user, UserRoles.ADMIN); @@ -765,48 +765,39 @@ void testProcessDarCollectionSummariesForResearcher() { data.setProjectTitle(randomAlphabetic(10)); draft.setData(data); when(dataAccessRequestDAO.findAllDraftsByUserId(any())).thenReturn(List.of(draft)); - when(darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(any())).thenReturn( - List.of(summaryOne, summaryTwo, summaryThree, summaryFour, summaryFive)); + when(darCollectionSummaryDAO.getDarCollectionSummariesForResearcher(any())) + .thenReturn(List.of(summaryOne, summaryTwo, summaryThree, summaryFour, summaryFive)); when(dataAccessRequestDAO.findDatasetApprovalsByDar("ref1")).thenReturn(Set.of()); when(dataAccessRequestDAO.findDatasetApprovalsByDar("ref4")) .thenReturn(Set.of(datasetSix.getDatasetId())); - List summaries = service.getSummariesForRole(user, - UserRoles.RESEARCHER); + List summaries = service.getSummariesForRole(user, UserRoles.RESEARCHER); assertNotNull(summaries); assertEquals(6, summaries.size()); DarCollectionSummary testOne = summaries.get(0); - Set expectedOneActions = Set.of( - DarCollectionActions.REVIEW.getValue() - ); - assertTrue( - testOne.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); + Set expectedOneActions = Set.of(DarCollectionActions.REVIEW.getValue()); + assertTrue(testOne.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(expectedOneActions, testOne.getActions()); DarCollectionSummary testTwo = summaries.get(1); - Set expectedTwoActions = Set.of( - DarCollectionActions.REVIEW.getValue(), - DarCollectionActions.CANCEL.getValue() - ); - assertTrue( - testTwo.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); + Set expectedTwoActions = + Set.of(DarCollectionActions.REVIEW.getValue(), DarCollectionActions.CANCEL.getValue()); + assertTrue(testTwo.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); assertEquals(expectedTwoActions, testTwo.getActions()); DarCollectionSummary testThree = summaries.get(2); - Set expectedThreeActions = Set.of( - DarCollectionActions.REVIEW.getValue(), - DarCollectionActions.REVISE.getValue()); - assertTrue( - testThree.getStatus().equalsIgnoreCase(DarCollectionStatus.CANCELED.getValue())); + Set expectedThreeActions = + Set.of(DarCollectionActions.REVIEW.getValue(), DarCollectionActions.REVISE.getValue()); + assertTrue(testThree.getStatus().equalsIgnoreCase(DarCollectionStatus.CANCELED.getValue())); assertEquals(expectedThreeActions, testThree.getActions()); DarCollectionSummary testFour = summaries.get(3); - Set expectedFourActions = Set.of( - DarCollectionActions.REVIEW.getValue(), - DarCollectionActions.CREATE_PROGRESS_REPORT.getValue()); - assertTrue( - testFour.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); + Set expectedFourActions = + Set.of( + DarCollectionActions.REVIEW.getValue(), + DarCollectionActions.CREATE_PROGRESS_REPORT.getValue()); + assertTrue(testFour.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); assertEquals(testFour.getActions(), expectedFourActions); DarCollectionSummary testFive = summaries.get(4); @@ -814,9 +805,8 @@ void testProcessDarCollectionSummariesForResearcher() { assertEquals(Set.of(DarCollectionActions.REVIEW.getValue()), testFive.getActions()); DarCollectionSummary testDraft = summaries.get(5); - Set expectedDraftActions = Set.of( - DarCollectionActions.RESUME.getValue(), - DarCollectionActions.DELETE.getValue()); + Set expectedDraftActions = + Set.of(DarCollectionActions.RESUME.getValue(), DarCollectionActions.DELETE.getValue()); assertEquals(DarCollectionStatus.DRAFT.getValue(), testDraft.getStatus()); assertEquals(expectedDraftActions, testDraft.getActions()); } @@ -840,8 +830,11 @@ void testProcessDarCollectionSummariesForResearcherWithCloseout() { // All summaries should have the REVIEW action assertTrue(summaries.get(0).getActions().contains(DarCollectionActions.REVIEW.getValue())); // Summaries with closeout should not have the CREATE_PROGRESS_REPORT action - assertFalse(summaries.get(0).getActions() - .contains(DarCollectionActions.CREATE_PROGRESS_REPORT.getValue())); + assertFalse( + summaries + .get(0) + .getActions() + .contains(DarCollectionActions.CREATE_PROGRESS_REPORT.getValue())); } @Test @@ -862,8 +855,11 @@ void testProcessDarCollectionSummariesForResearcherWithoutCloseout() { // All summaries should have the REVIEW action assertTrue(summaries.get(0).getActions().contains(DarCollectionActions.REVIEW.getValue())); // Summaries without a closeout should have the CREATE_PROGRESS_REPORT action - assertTrue(summaries.get(0).getActions() - .contains(DarCollectionActions.CREATE_PROGRESS_REPORT.getValue())); + assertTrue( + summaries + .get(0) + .getActions() + .contains(DarCollectionActions.CREATE_PROGRESS_REPORT.getValue())); } @Test @@ -876,8 +872,8 @@ void testProcessDarCollectionSummariesForSOWithPendingCloseout() { DarCollectionSummary summary = new DarCollectionSummary(); summary.setLatestReferenceId(UUID.randomUUID().toString()); - CloseoutSupplement closeoutSupplement = new CloseoutSupplement( - List.of("Closeout"), "Closeout", 1); + CloseoutSupplement closeoutSupplement = + new CloseoutSupplement(List.of("Closeout"), "Closeout", 1); summary.setCloseoutSupplement(closeoutSupplement); summary.setCloseoutSigningOfficialApprovalDate(null); @@ -885,8 +881,8 @@ void testProcessDarCollectionSummariesForSOWithPendingCloseout() { when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(user.getInstitutionId())) .thenReturn(List.of(summary)); - List summaries = service.getSummariesForRole(user, - UserRoles.SIGNINGOFFICIAL); + List summaries = + service.getSummariesForRole(user, UserRoles.SIGNINGOFFICIAL); assertNotNull(summaries); assertEquals(1, summaries.size()); @@ -904,8 +900,8 @@ void testProcessDarCollectionSummariesForSOWithApprovedCloseout() { DarCollectionSummary summary = new DarCollectionSummary(); summary.setLatestReferenceId(UUID.randomUUID().toString()); - CloseoutSupplement closeoutSupplement = new CloseoutSupplement( - List.of("Closeout"), "Closeout", 1); + CloseoutSupplement closeoutSupplement = + new CloseoutSupplement(List.of("Closeout"), "Closeout", 1); summary.setCloseoutSupplement(closeoutSupplement); summary.setCloseoutSigningOfficialApprovalDate(new Timestamp(System.currentTimeMillis())); @@ -913,8 +909,8 @@ void testProcessDarCollectionSummariesForSOWithApprovedCloseout() { when(darCollectionSummaryDAO.getDarCollectionSummariesForSO(user.getInstitutionId())) .thenReturn(List.of(summary)); - List summaries = service.getSummariesForRole(user, - UserRoles.SIGNINGOFFICIAL); + List summaries = + service.getSummariesForRole(user, UserRoles.SIGNINGOFFICIAL); assertNotNull(summaries); assertEquals(1, summaries.size()); @@ -930,14 +926,14 @@ void testProcessDarCollectionSummariesForChairWithApprovedCloseout() { DarCollectionSummary summary = new DarCollectionSummary(); summary.setLatestReferenceId(UUID.randomUUID().toString()); - CloseoutSupplement closeoutSupplement = new CloseoutSupplement( - List.of("Closeout"), "Closeout", 1); + CloseoutSupplement closeoutSupplement = + new CloseoutSupplement(List.of("Closeout"), "Closeout", 1); summary.setCloseoutSupplement(closeoutSupplement); summary.setCloseoutSigningOfficialApprovalDate(new Timestamp(System.currentTimeMillis())); - when(darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(user.getUserId(), - UserRoles.CHAIRPERSON.getRoleId())) + when(darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + user.getUserId(), UserRoles.CHAIRPERSON.getRoleId())) .thenReturn(List.of(summary)); List summaries = service.getSummariesForRole(user, UserRoles.CHAIRPERSON); @@ -950,10 +946,10 @@ void testProcessDarCollectionSummariesForChairWithApprovedCloseout() { @Test void testProcessDarCollectionSummariesForAdmin() { - //summaryOne -> all elections present and open - //summaryTwo -> mix of open elections : absent/non-open elections (in process) - //summaryThree -> all canceled elections (Complete) - //summaryFour -> no elections (unreviewed) + // summaryOne -> all elections present and open + // summaryTwo -> mix of open elections : absent/non-open elections (in process) + // summaryThree -> all canceled elections (Complete) + // summaryFour -> no elections (unreviewed) User user = new User(); user.setUserId(1); @@ -1010,36 +1006,27 @@ void testProcessDarCollectionSummariesForAdmin() { when(darCollectionSummaryDAO.getDarCollectionSummariesForAdmin()) .thenReturn(List.of(summaryOne, summaryTwo, summaryThree, summaryFour)); - List summaries = service.getSummariesForRole(user, - UserRoles.ADMIN); + List summaries = service.getSummariesForRole(user, UserRoles.ADMIN); DarCollectionSummary testOne = summaries.get(0); - Set expectedOneActions = Set.of( - DarCollectionActions.CANCEL.getValue()); - assertTrue( - testOne.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); + Set expectedOneActions = Set.of(DarCollectionActions.CANCEL.getValue()); + assertTrue(testOne.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(testOne.getActions(), expectedOneActions); DarCollectionSummary testTwo = summaries.get(1); - Set expectedTwoActions = Set.of( - DarCollectionActions.CANCEL.getValue(), - DarCollectionActions.OPEN.getValue()); - assertTrue( - testTwo.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); + Set expectedTwoActions = + Set.of(DarCollectionActions.CANCEL.getValue(), DarCollectionActions.OPEN.getValue()); + assertTrue(testTwo.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(testTwo.getActions(), expectedTwoActions); DarCollectionSummary testThree = summaries.get(2); - Set expectedThreeActions = Set.of( - DarCollectionActions.OPEN.getValue()); - assertTrue( - testThree.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); + Set expectedThreeActions = Set.of(DarCollectionActions.OPEN.getValue()); + assertTrue(testThree.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); assertEquals(testThree.getActions(), expectedThreeActions); DarCollectionSummary testFour = summaries.get(3); - Set expectedFourActions = Set.of( - DarCollectionActions.OPEN.getValue()); - assertTrue( - testFour.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); + Set expectedFourActions = Set.of(DarCollectionActions.OPEN.getValue()); + assertTrue(testFour.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); assertEquals(testFour.getActions(), expectedFourActions); } @@ -1050,8 +1037,7 @@ void testProcessDarCollectionSummariesForDACMemberNoDatasets() { User user = new User(); user.setUserId(randomInt(1, 10)); user.setMemberRole(); - List summaries = service.getSummariesForRole(user, - UserRoles.MEMBER); + List summaries = service.getSummariesForRole(user, UserRoles.MEMBER); assertTrue(summaries.isEmpty()); } @@ -1062,8 +1048,7 @@ void testProcessDarCollectionSummariesForDACChairNoDatasets() { User user = new User(); user.setUserId(randomInt(1, 10)); user.setChairpersonRole(); - List summaries = service.getSummariesForRole(user, - UserRoles.CHAIRPERSON); + List summaries = service.getSummariesForRole(user, UserRoles.CHAIRPERSON); assertTrue(summaries.isEmpty()); } @@ -1075,10 +1060,10 @@ void testProcessDarCollectionSummariesForDACMember() { user.setUserId(1); user.setMemberRoleWithDAC(dac.getDacId()); - //summaryOne -> no open elections (no action) - //summaryTwo -> at least one open election, member has submitted all votes (Update button) - //summaryThree -> unreviewed scenario (no elections), - //summaryFour -> at least one open election, member has not submitted all votes (Vote button) + // summaryOne -> no open elections (no action) + // summaryTwo -> at least one open election, member has submitted all votes (Update button) + // summaryThree -> unreviewed scenario (no elections), + // summaryFour -> at least one open election, member has not submitted all votes (Vote button) DarCollectionSummary summary = new DarCollectionSummary(); summary.addDatasetId(1); @@ -1095,8 +1080,18 @@ void testProcessDarCollectionSummariesForDACMember() { DarCollectionSummary summaryTwo = new DarCollectionSummary(); summaryTwo.addDatasetId(3); Election electionThree = new Election(); - Vote vote = new Vote(1, true, user.getUserId(), null, null, electionThree.getElectionId(), null, - VoteType.DAC.getValue(), null, null); + Vote vote = + new Vote( + 1, + true, + user.getUserId(), + null, + null, + electionThree.getElectionId(), + null, + VoteType.DAC.getValue(), + null, + null); electionThree.setElectionId(3); electionThree.setStatus(ElectionStatus.OPEN.getValue()); summaryTwo.addElection(electionThree); @@ -1108,12 +1103,30 @@ void testProcessDarCollectionSummariesForDACMember() { DarCollectionSummary summaryFour = new DarCollectionSummary(); summaryFour.addDatasetId(5); Election electionFour = new Election(); - Vote voteTwo = new Vote(2, true, user.getUserId(), null, null, electionThree.getElectionId(), - null, - VoteType.DAC.getValue(), null, null); - Vote voteThree = new Vote(4, null, user.getUserId(), null, null, electionThree.getElectionId(), - null, - VoteType.DAC.getValue(), null, null); + Vote voteTwo = + new Vote( + 2, + true, + user.getUserId(), + null, + null, + electionThree.getElectionId(), + null, + VoteType.DAC.getValue(), + null, + null); + Vote voteThree = + new Vote( + 4, + null, + user.getUserId(), + null, + null, + electionThree.getElectionId(), + null, + VoteType.DAC.getValue(), + null, + null); electionFour.setElectionId(4); electionFour.setStatus(ElectionStatus.OPEN.getValue()); summaryFour.addElection(electionFour); @@ -1122,8 +1135,7 @@ void testProcessDarCollectionSummariesForDACMember() { when(darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(any(), any())) .thenReturn(List.of(summary, summaryTwo, summaryThree, summaryFour)); - List summaries = service.getSummariesForRole(user, - UserRoles.MEMBER); + List summaries = service.getSummariesForRole(user, UserRoles.MEMBER); assertNotNull(summaries); assertEquals(4, summaries.size()); @@ -1151,12 +1163,13 @@ void testProcessDarCollectionSummariesForDACMember() { @Test void testProcessDarCollectionSummariesForChair() { - //summaryOne -> all elections present and open - //summaryTwo -> mix of open elections : absent/canceled elections (in process) - //summaryThree -> all canceled elections (Complete) - //summaryFour -> no elections (unreviewed) - //summaryFive -> mix of open : absent/closed elections (in process, but cancel action does not appear) - //summarySix -> all closed elections (complete, only open available) + // summaryOne -> all elections present and open + // summaryTwo -> mix of open elections : absent/canceled elections (in process) + // summaryThree -> all canceled elections (Complete) + // summaryFour -> no elections (unreviewed) + // summaryFive -> mix of open : absent/closed elections (in process, but cancel action does not + // appear) + // summarySix -> all closed elections (complete, only open available) Dac dac = new Dac(); dac.setDacId(1); @@ -1242,58 +1255,44 @@ void testProcessDarCollectionSummariesForChair() { .thenReturn( List.of(summaryOne, summaryTwo, summaryThree, summaryFour, summaryFive, summarySix)); - List summaries = service.getSummariesForRole(user, - UserRoles.CHAIRPERSON); + List summaries = service.getSummariesForRole(user, UserRoles.CHAIRPERSON); assertEquals(6, summaries.size()); DarCollectionSummary testOne = summaries.get(0); - Set expectedOneActions = Set.of( - DarCollectionActions.VOTE.getValue(), - DarCollectionActions.CANCEL.getValue()); - assertTrue( - testOne.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); + Set expectedOneActions = + Set.of(DarCollectionActions.VOTE.getValue(), DarCollectionActions.CANCEL.getValue()); + assertTrue(testOne.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(testOne.getActions(), expectedOneActions); DarCollectionSummary testTwo = summaries.get(1); - Set expectedTwoActions = Set.of( - DarCollectionActions.VOTE.getValue(), - DarCollectionActions.CANCEL.getValue(), - DarCollectionActions.OPEN.getValue()); - assertTrue( - testTwo.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); + Set expectedTwoActions = + Set.of( + DarCollectionActions.VOTE.getValue(), + DarCollectionActions.CANCEL.getValue(), + DarCollectionActions.OPEN.getValue()); + assertTrue(testTwo.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(testTwo.getActions(), expectedTwoActions); DarCollectionSummary testThree = summaries.get(2); - Set expectedThreeActions = Set.of( - DarCollectionActions.OPEN.getValue()); - assertTrue( - testThree.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); + Set expectedThreeActions = Set.of(DarCollectionActions.OPEN.getValue()); + assertTrue(testThree.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); assertEquals(testThree.getActions(), expectedThreeActions); DarCollectionSummary testFour = summaries.get(3); - Set expectedFourActions = Set.of( - DarCollectionActions.OPEN.getValue()); - assertTrue( - testFour.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); + Set expectedFourActions = Set.of(DarCollectionActions.OPEN.getValue()); + assertTrue(testFour.getStatus().equalsIgnoreCase(DarCollectionStatus.SUBMITTED.getValue())); assertEquals(testFour.getActions(), expectedFourActions); DarCollectionSummary testFive = summaries.get(4); - Set expectedFiveActions = Set.of( - DarCollectionActions.OPEN.getValue(), - DarCollectionActions.VOTE.getValue() - ); - assertTrue( - testFive.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); + Set expectedFiveActions = + Set.of(DarCollectionActions.OPEN.getValue(), DarCollectionActions.VOTE.getValue()); + assertTrue(testFive.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(testFive.getActions(), expectedFiveActions); DarCollectionSummary testSix = summaries.get(5); - Set expectedSixActions = Set.of( - DarCollectionActions.OPEN.getValue() - ); - assertTrue( - testSix.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); + Set expectedSixActions = Set.of(DarCollectionActions.OPEN.getValue()); + assertTrue(testSix.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); assertEquals(testSix.getActions(), expectedSixActions); - } @Test @@ -1304,8 +1303,8 @@ void testProcessDarCollectionSummariesForChairWithCloseout() { DarCollectionSummary summary = new DarCollectionSummary(); summary.setLatestReferenceId(UUID.randomUUID().toString()); summary.setCloseoutSupplement(new CloseoutSupplement(List.of("Closeout"), "Closeout", 1)); - when(darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(user.getUserId(), - UserRoles.CHAIRPERSON.getRoleId())) + when(darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + user.getUserId(), UserRoles.CHAIRPERSON.getRoleId())) .thenReturn(List.of(summary)); List summaries = service.getSummariesForRole(user, UserRoles.CHAIRPERSON); @@ -1323,8 +1322,8 @@ void testProcessDarCollectionSummariesForChairWithoutCloseout() { user.addRole(UserRoles.Chairperson()); DarCollectionSummary summary = new DarCollectionSummary(); summary.setLatestReferenceId(UUID.randomUUID().toString()); - when(darCollectionSummaryDAO.getDarCollectionSummariesForDACRole(user.getUserId(), - UserRoles.CHAIRPERSON.getRoleId())) + when(darCollectionSummaryDAO.getDarCollectionSummariesForDACRole( + user.getUserId(), UserRoles.CHAIRPERSON.getRoleId())) .thenReturn(List.of(summary)); List summaries = service.getSummariesForRole(user, UserRoles.CHAIRPERSON); @@ -1346,8 +1345,8 @@ void testGetSummaryForRoleByCollectionId_SO() { when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)) .thenReturn(summary); - DarCollectionSummary summaryResult = service.getSummaryForRoleByCollectionId(user, - UserRoles.SIGNINGOFFICIAL, collectionId); + DarCollectionSummary summaryResult = + service.getSummaryForRoleByCollectionId(user, UserRoles.SIGNINGOFFICIAL, collectionId); assertNotNull(summaryResult); assertTrue( @@ -1368,12 +1367,11 @@ void testGetSummaryForRoleByCollectionId_Researcher() { .thenReturn(summary); when(dataAccessRequestDAO.findDatasetApprovalsByDar("ref1")).thenReturn(Set.of()); - DarCollectionSummary summaryResult = service.getSummaryForRoleByCollectionId(user, - UserRoles.RESEARCHER, collectionId); + DarCollectionSummary summaryResult = + service.getSummaryForRoleByCollectionId(user, UserRoles.RESEARCHER, collectionId); assertNotNull(summaryResult); - Set expectedActions = Set.of( - DarCollectionActions.REVIEW.getValue()); + Set expectedActions = Set.of(DarCollectionActions.REVIEW.getValue()); assertTrue( summaryResult.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(expectedActions, summaryResult.getActions()); @@ -1390,13 +1388,12 @@ void testGetSummaryForRoleByCollectionId_Admin() { when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)) .thenReturn(summary); - DarCollectionSummary summaryResult = service.getSummaryForRoleByCollectionId(user, - UserRoles.ADMIN, collectionId); + DarCollectionSummary summaryResult = + service.getSummaryForRoleByCollectionId(user, UserRoles.ADMIN, collectionId); assertNotNull(summaryResult); - Set expectedActions = Set.of( - DarCollectionActions.CANCEL.getValue(), - DarCollectionActions.OPEN.getValue()); + Set expectedActions = + Set.of(DarCollectionActions.CANCEL.getValue(), DarCollectionActions.OPEN.getValue()); assertTrue( summaryResult.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(expectedActions, summaryResult.getActions()); @@ -1408,30 +1405,33 @@ void testGetSummaryForRoleNameByCollectionIdForResearcher_PRWithClosedElections( user.setUserId(1); DarCollectionSummary summary = createDarCollectionSummaryWithElections(); - summary.getElections().values().forEach(election -> { - election.setStatus(ElectionStatus.CLOSED.getValue()); - }); + summary + .getElections() + .values() + .forEach( + election -> { + election.setStatus(ElectionStatus.CLOSED.getValue()); + }); summary.setLatestReferenceId("ref1"); Integer collectionId = summary.getDarCollectionId(); when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)) .thenReturn(summary); - when(dataAccessRequestDAO.findDatasetApprovalsByDar("ref1")) - .thenReturn(Set.of(1)); + when(dataAccessRequestDAO.findDatasetApprovalsByDar("ref1")).thenReturn(Set.of(1)); - DarCollectionSummary summaryResult = service.getSummaryForRoleByCollectionId(user, - UserRoles.RESEARCHER, collectionId); + DarCollectionSummary summaryResult = + service.getSummaryForRoleByCollectionId(user, UserRoles.RESEARCHER, collectionId); assertNotNull(summaryResult); - assertTrue( - summaryResult.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); + assertTrue(summaryResult.getStatus().equalsIgnoreCase(DarCollectionStatus.COMPLETE.getValue())); // Verify that the create_progress_report action is included - Set expectedActions = Set.of( - DarCollectionActions.REVIEW.getValue(), - DarCollectionActions.CREATE_PROGRESS_REPORT.getValue()); + Set expectedActions = + Set.of( + DarCollectionActions.REVIEW.getValue(), + DarCollectionActions.CREATE_PROGRESS_REPORT.getValue()); assertEquals(expectedActions, summaryResult.getActions()); } @@ -1441,20 +1441,23 @@ void testGetSummaryForRoleNameByCollectionIdForResearcher_PRWithOpenElections() user.setUserId(1); DarCollectionSummary summary = createDarCollectionSummaryWithElections(); - summary.getElections().values().forEach(election -> { - election.setStatus(ElectionStatus.OPEN.getValue()); - }); + summary + .getElections() + .values() + .forEach( + election -> { + election.setStatus(ElectionStatus.OPEN.getValue()); + }); summary.setLatestReferenceId("ref1"); Integer collectionId = summary.getDarCollectionId(); when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)) .thenReturn(summary); - when(dataAccessRequestDAO.findDatasetApprovalsByDar("ref1")) - .thenReturn(Set.of(1)); + when(dataAccessRequestDAO.findDatasetApprovalsByDar("ref1")).thenReturn(Set.of(1)); - DarCollectionSummary summaryResult = service.getSummaryForRoleByCollectionId(user, - UserRoles.RESEARCHER, collectionId); + DarCollectionSummary summaryResult = + service.getSummaryForRoleByCollectionId(user, UserRoles.RESEARCHER, collectionId); assertNotNull(summaryResult); @@ -1477,19 +1480,20 @@ void testGetSummaryForRoleByCollectionId_Chair() { DarCollectionSummary summary = createDarCollectionSummaryWithElections(); Integer collectionId = summary.getDarCollectionId(); - when(darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(user.getUserId(), - List.of(), collectionId)) + when(darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + user.getUserId(), List.of(), collectionId)) .thenReturn(summary); when(datasetDAO.findDatasetIdsByDacIds(any())).thenReturn(List.of()); - DarCollectionSummary summaryResult = service.getSummaryForRoleByCollectionId(user, - UserRoles.CHAIRPERSON, collectionId); + DarCollectionSummary summaryResult = + service.getSummaryForRoleByCollectionId(user, UserRoles.CHAIRPERSON, collectionId); assertNotNull(summaryResult); - Set expectedActions = Set.of( - DarCollectionActions.VOTE.getValue(), - DarCollectionActions.CANCEL.getValue(), - DarCollectionActions.OPEN.getValue()); + Set expectedActions = + Set.of( + DarCollectionActions.VOTE.getValue(), + DarCollectionActions.CANCEL.getValue(), + DarCollectionActions.OPEN.getValue()); assertTrue( summaryResult.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(expectedActions, summaryResult.getActions()); @@ -1516,24 +1520,24 @@ void testGetSummaryForRoleByCollectionId_DACMember() { Election electionTwo = new Election(); electionTwo.setElectionId(2); electionTwo.setStatus(ElectionStatus.CLOSED.getValue()); - Vote vote = new Vote(1, null, user.getUserId(), null, null, 1, null, VoteType.DAC.getValue(), - null, null); + Vote vote = + new Vote( + 1, null, user.getUserId(), null, null, 1, null, VoteType.DAC.getValue(), null, null); summary.addElection(electionOne); summary.addElection(electionTwo); summary.addDatasetId(datasetOne.getDatasetId()); summary.addDatasetId(datasetTwo.getDatasetId()); summary.setVotes(List.of(vote)); - when(darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId(user.getUserId(), - List.of(), collectionId)) + when(darCollectionSummaryDAO.getDarCollectionSummaryForDACByCollectionId( + user.getUserId(), List.of(), collectionId)) .thenReturn(summary); - DarCollectionSummary summaryResult = service.getSummaryForRoleByCollectionId(user, - UserRoles.MEMBER, collectionId); + DarCollectionSummary summaryResult = + service.getSummaryForRoleByCollectionId(user, UserRoles.MEMBER, collectionId); assertNotNull(summaryResult); - Set expectedActions = Set.of( - DarCollectionActions.VOTE.getValue()); + Set expectedActions = Set.of(DarCollectionActions.VOTE.getValue()); assertTrue( summaryResult.getStatus().equalsIgnoreCase(DarCollectionStatus.IN_PROCESS.getValue())); assertEquals(expectedActions, summaryResult.getActions()); @@ -1550,7 +1554,8 @@ void testGetSummaryForRoleNameByCollectionId_NoSummaryFound() { when(darCollectionSummaryDAO.getDarCollectionSummaryByCollectionId(collectionId)) .thenReturn(null); - assertThrows(NotFoundException.class, + assertThrows( + NotFoundException.class, () -> service.getSummaryForRoleByCollectionId(user, UserRoles.RESEARCHER, collectionId)); } @@ -1622,9 +1627,9 @@ void testSendNewDARCollectionMessage() throws Exception { when(darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId())) .thenReturn(collection); when(userDAO.findUserById(researcher.getUserId())).thenReturn(researcher); - when(userDAO.findUsersForDatasetsByRole(dar.getDatasetIds(), - Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId()))).thenReturn( - Set.of(chairperson)); + when(userDAO.findUsersForDatasetsByRole( + dar.getDatasetIds(), Collections.singletonList(UserRoles.CHAIRPERSON.getRoleId()))) + .thenReturn(Set.of(chairperson)); when(dacDAO.findDacsForDatasetIds(dar.getDatasetIds())).thenReturn(Set.of(dac)); when(datasetDAO.findDatasetsByIdList(dar.getDatasetIds())).thenReturn(List.of(d1, d2)); service.sendNewDARCollectionMessage(collection.getDarCollectionId()); @@ -1641,8 +1646,8 @@ void testNotifySigningOfficialsOfDARSubmission_DAR() throws TemplateException, I Dataset dataset = new Dataset(); dataset.setDatasetId(1); dataset.setDataUse(new DataUseBuilder().setGeneralUse(true).build()); - when(datasetDAO.findDatasetsByIdList(List.of(dataset.getDatasetId()))).thenReturn( - List.of(dataset)); + when(datasetDAO.findDatasetsByIdList(List.of(dataset.getDatasetId()))) + .thenReturn(List.of(dataset)); DarCollection collection = new DarCollection(); collection.setDarCode("DAR-000123"); @@ -1657,13 +1662,13 @@ void testNotifySigningOfficialsOfDARSubmission_DAR() throws TemplateException, I researcher.setInstitutionId(1); User signingOfficial = createUserWithRole(UserRoles.SIGNINGOFFICIAL, null); signingOfficial.setEmailPreference(true); - when(userDAO.getSOsByInstitution(researcher.getInstitutionId())).thenReturn( - List.of(signingOfficial)); + when(userDAO.getSOsByInstitution(researcher.getInstitutionId())) + .thenReturn(List.of(signingOfficial)); - service.notifySigningOfficialsOfDARSubmission(collection.getMostRecentDar(), researcher, - collection.getDarCode()); - verify(emailService, never()).sendNewSoProgressReportSubmittedEmail(any(), any(), any(), any(), - any()); + service.notifySigningOfficialsOfDARSubmission( + collection.getMostRecentDar(), researcher, collection.getDarCode()); + verify(emailService, never()) + .sendNewSoProgressReportSubmittedEmail(any(), any(), any(), any(), any()); verify(emailService, times(1)).sendNewSoDARSubmittedEmail(any(), any(), any(), any(), any()); } @@ -1672,8 +1677,8 @@ void testNotifySigningOfficialsOfDARSubmission_PR() throws TemplateException, IO Dataset dataset = new Dataset(); dataset.setDatasetId(1); dataset.setDataUse(new DataUseBuilder().setGeneralUse(true).build()); - when(datasetDAO.findDatasetsByIdList(List.of(dataset.getDatasetId()))).thenReturn( - List.of(dataset)); + when(datasetDAO.findDatasetsByIdList(List.of(dataset.getDatasetId()))) + .thenReturn(List.of(dataset)); DarCollection collection = new DarCollection(); collection.setDarCode("DAR-000123"); @@ -1699,13 +1704,13 @@ void testNotifySigningOfficialsOfDARSubmission_PR() throws TemplateException, IO researcher.setInstitutionId(1); User signingOfficial = createUserWithRole(UserRoles.SIGNINGOFFICIAL, null); signingOfficial.setEmailPreference(true); - when(userDAO.getSOsByInstitution(researcher.getInstitutionId())).thenReturn( - List.of(signingOfficial)); + when(userDAO.getSOsByInstitution(researcher.getInstitutionId())) + .thenReturn(List.of(signingOfficial)); - service.notifySigningOfficialsOfDARSubmission(collection.getMostRecentDar(), researcher, - collection.getDarCode()); - verify(emailService, times(1)).sendNewSoProgressReportSubmittedEmail(any(), any(), any(), any(), - any()); + service.notifySigningOfficialsOfDARSubmission( + collection.getMostRecentDar(), researcher, collection.getDarCode()); + verify(emailService, times(1)) + .sendNewSoProgressReportSubmittedEmail(any(), any(), any(), any(), any()); verify(emailService, never()).sendNewSoDARSubmittedEmail(any(), any(), any(), any(), any()); } @@ -1727,10 +1732,10 @@ void testNotifySigningOfficialsOfDARSubmission_NoInstitution() User researcher = createUserWithRole(UserRoles.RESEARCHER, null); collection.setCreateUserId(researcher.getUserId()); - service.notifySigningOfficialsOfDARSubmission(collection.getMostRecentDar(), researcher, - collection.getDarCode()); - verify(emailService, never()).sendNewSoProgressReportSubmittedEmail(any(), any(), any(), any(), - any()); + service.notifySigningOfficialsOfDARSubmission( + collection.getMostRecentDar(), researcher, collection.getDarCode()); + verify(emailService, never()) + .sendNewSoProgressReportSubmittedEmail(any(), any(), any(), any(), any()); verify(emailService, never()).sendNewSoDARSubmittedEmail(any(), any(), any(), any(), any()); } @@ -1780,8 +1785,7 @@ private Dataset createDataset(Integer dacId) { dataset.setAlias(dataset.getDatasetId()); dataset.setDatasetIdentifier(); dataset.setDacId(dacId); - dataset.setName(String.format("Dataset %s-%s", randomAlphabetic(10), - dataset.getDatasetId())); + dataset.setName(String.format("Dataset %s-%s", randomAlphabetic(10), dataset.getDatasetId())); return dataset; } @@ -1790,10 +1794,7 @@ private User createUserWithRole(UserRoles userRoles, Integer dacId) { user.setUserId(randomInt(1, 100000)); user.setDisplayName(String.format("%s - %s", userRoles.getRoleName(), user.getUserId())); user.setEmail(String.format("%s@test.com", userRoles.getRoleName())); - UserRole role = new UserRole( - userRoles.getRoleId(), - userRoles.getRoleName() - ); + UserRole role = new UserRole(userRoles.getRoleId(), userRoles.getRoleName()); if (dacId != null) { role.setDacId(dacId); } @@ -1801,5 +1802,4 @@ private User createUserWithRole(UserRoles userRoles, Integer dacId) { user.setEmailPreference(Boolean.TRUE); return user; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/DataAccessReportsParserTest.java b/src/test/java/org/broadinstitute/consent/http/service/DataAccessReportsParserTest.java index 81f96dc000..3fcdb2b8f2 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DataAccessReportsParserTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DataAccessReportsParserTest.java @@ -27,16 +27,15 @@ @ExtendWith(MockitoExtension.class) class DataAccessReportsParserTest { - @Mock - private DatasetDAO datasetDAO; - @Mock - private UseRestrictionConverter useRestrictionConverter; + @Mock private DatasetDAO datasetDAO; + @Mock private UseRestrictionConverter useRestrictionConverter; private DataAccessReportsParser parser; private final String CONSENT_NAME = "ORSP-1903"; private final String NAME = "Test"; private final String DS_IDENTIFIER = "DUOS-000001"; private final String RUS_SUMMARY = "Purpose"; - private final String sDUL = """ + private final String sDUL = + """ Samples Restricted for use with "cancer" [DOID_162(CC)] Future use by for-profit entities is prohibited [NPU] Future use of aggregate-level data for general research purposes is prohibited [NPNV] @@ -54,7 +53,8 @@ public void setUp() { d.setName(NAME); List datasets = List.of(d); when(datasetDAO.findDatasetsByIdList(List.of(1))).thenReturn(datasets); - String translation = """ + String translation = + """ Research is limited to samples restricted for use under the following conditions: Data is limited for health/medical/biomedical research. [HMB] """; @@ -72,8 +72,8 @@ void testDataAccessApprovedReport() throws IOException { parser.setApprovedDARHeader(darWriter); String REQUESTER = "Wesley"; String ORGANIZATION = "Broad"; - parser.addApprovedDARLine(darWriter, election, dar, DAR_CODE, REQUESTER, ORGANIZATION, - CONSENT_NAME, sDUL); + parser.addApprovedDARLine( + darWriter, election, dar, DAR_CODE, REQUESTER, ORGANIZATION, CONSENT_NAME, sDUL); darWriter.flush(); try (var stream = Files.lines(Paths.get(file.getPath()))) { Iterator iterator = stream.iterator(); @@ -94,8 +94,7 @@ void testDataAccessApprovedReport() throws IOException { assertEquals(columns[8], HeaderDAR.RESEARCH_PURPOSE.getValue()); assertEquals(columns[9], HeaderDAR.DATE_REQUEST_SUBMISSION.getValue()); assertEquals(columns[10], HeaderDAR.DATE_REQUEST_APPROVAL.getValue()); - assertEquals(columns[11], - HeaderDAR.DATE_REQUEST_RE_ATTESTATION.getValue()); + assertEquals(columns[11], HeaderDAR.DATE_REQUEST_RE_ATTESTATION.getValue()); } if (i == 1) { assertEquals(DAR_CODE, columns[0]); @@ -123,7 +122,7 @@ void testDataAccessReviewedReport() throws IOException { parser.setReviewedDARHeader(darWriter); parser.addReviewedDARLine(darWriter, election, dar, DAR_CODE, CONSENT_NAME, sDUL); darWriter.flush(); - try(var stream = Files.lines(Paths.get(file.getPath()))){ + try (var stream = Files.lines(Paths.get(file.getPath()))) { Iterator iterator = stream.iterator(); int i = 0; while (iterator.hasNext()) { @@ -137,8 +136,7 @@ void testDataAccessReviewedReport() throws IOException { assertEquals(columns[3], HeaderDAR.CONSENT_ID.getValue()); assertEquals(columns[4], HeaderDAR.CODED_VERSION_SDUL.getValue()); assertEquals(columns[5], HeaderDAR.CODED_VERSION_DAR.getValue()); - assertEquals(columns[6], - HeaderDAR.DATE_REQUEST_APPROVAL_DISAPROVAL.getValue()); + assertEquals(columns[6], HeaderDAR.DATE_REQUEST_APPROVAL_DISAPROVAL.getValue()); assertEquals(columns[7], HeaderDAR.APPROVED_DISAPPROVED.getValue()); } if (i == 1) { @@ -165,7 +163,7 @@ void testDataAccessReviewedReportNullElectionDate() throws IOException { parser.setReviewedDARHeader(darWriter); parser.addReviewedDARLine(darWriter, election, dar, DAR_CODE, CONSENT_NAME, sDUL); darWriter.flush(); - try(var stream = Files.lines(Paths.get(file.getPath()))){ + try (var stream = Files.lines(Paths.get(file.getPath()))) { Iterator iterator = stream.iterator(); int i = 0; while (iterator.hasNext()) { @@ -179,8 +177,7 @@ void testDataAccessReviewedReportNullElectionDate() throws IOException { assertEquals(columns[3], HeaderDAR.CONSENT_ID.getValue()); assertEquals(columns[4], HeaderDAR.CODED_VERSION_SDUL.getValue()); assertEquals(columns[5], HeaderDAR.CODED_VERSION_DAR.getValue()); - assertEquals(columns[6], - HeaderDAR.DATE_REQUEST_APPROVAL_DISAPROVAL.getValue()); + assertEquals(columns[6], HeaderDAR.DATE_REQUEST_APPROVAL_DISAPROVAL.getValue()); assertEquals(columns[7], HeaderDAR.APPROVED_DISAPPROVED.getValue()); } if (i == 1) { diff --git a/src/test/java/org/broadinstitute/consent/http/service/DataAccessRequestServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DataAccessRequestServiceTest.java index 89fdee97c7..d27ec9b349 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DataAccessRequestServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DataAccessRequestServiceTest.java @@ -68,8 +68,8 @@ import org.broadinstitute.consent.http.models.Vote; import org.broadinstitute.consent.http.service.dao.DataAccessRequestServiceDAO; import org.glassfish.jersey.server.ContainerRequest; -import org.jetbrains.annotations.NotNull; import org.jdbi.v3.core.statement.UnableToExecuteStatementException; +import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -87,40 +87,23 @@ class DataAccessRequestServiceTest extends AbstractTestHelper { private static final String USER_EMAIL = "email@test.org"; private static final String USER_NAME = "Display Name"; private final List roles = List.of(UserRoles.Researcher()); - @Mock - private CounterService counterService; - @Mock - private DataAccessRequestDAO dataAccessRequestDAO; - @Mock - private DarCollectionDAO darCollectionDAO; - @Mock - private DacDAO dacDAO; - @Mock - private UserDAO userDAO; - @Mock - private DatasetDAO dataSetDAO; - @Mock - private ElectionDAO electionDAO; - @Mock - private EmailService emailService; - @Mock - private DacService dacService; - @Mock - private VoteDAO voteDAO; - @Mock - private InstitutionDAO institutionDAO; - @Mock - private MatchDAO matchDAO; - @Mock - private DataAccessRequestServiceDAO dataAccessRequestServiceDAO; - @Mock - private UserService userService; - @Mock - private InstitutionService institutionService; - @Mock - private DACAutomationRuleService ruleService; - @Mock - private ContainerRequest request; + @Mock private CounterService counterService; + @Mock private DataAccessRequestDAO dataAccessRequestDAO; + @Mock private DarCollectionDAO darCollectionDAO; + @Mock private DacDAO dacDAO; + @Mock private UserDAO userDAO; + @Mock private DatasetDAO dataSetDAO; + @Mock private ElectionDAO electionDAO; + @Mock private EmailService emailService; + @Mock private DacService dacService; + @Mock private VoteDAO voteDAO; + @Mock private InstitutionDAO institutionDAO; + @Mock private MatchDAO matchDAO; + @Mock private DataAccessRequestServiceDAO dataAccessRequestServiceDAO; + @Mock private UserService userService; + @Mock private InstitutionService institutionService; + @Mock private DACAutomationRuleService ruleService; + @Mock private ContainerRequest request; private DataAccessRequestService service; private String serverUrl; @@ -155,8 +138,8 @@ private static DataAccessRequestData getDataAccessRequestData(String goodEmailAd } @NotNull - private static DataAccessRequestData getDataAccessRequestData(String goodEmailAddress, - String badEmailAddress) { + private static DataAccessRequestData getDataAccessRequestData( + String goodEmailAddress, String badEmailAddress) { DataAccessRequestData data = new DataAccessRequestData(); data.setPiEmail(goodEmailAddress); data.setSigningOfficialEmail(goodEmailAddress); @@ -165,7 +148,7 @@ private static DataAccessRequestData getDataAccessRequestData(String goodEmailAd Collaborator collaborator2 = createCollaborator(goodEmailAddress); data.setLabCollaborators(List.of(collaborator1, collaborator2)); Collaborator labStaffMember = createCollaborator(goodEmailAddress); - Collaborator labStaffMember2 =createCollaborator(badEmailAddress); + Collaborator labStaffMember2 = createCollaborator(badEmailAddress); data.setLabCollaborators(List.of(labStaffMember, labStaffMember2)); return data; } @@ -185,8 +168,17 @@ void initService() { container.setVoteDAO(voteDAO); container.setMatchDAO(matchDAO); serverUrl = config.getServicesConfiguration().getLocalURL(); - service = new DataAccessRequestService(counterService, container, dacService, - dataAccessRequestServiceDAO, userService, institutionService, emailService, ruleService, config); + service = + new DataAccessRequestService( + counterService, + container, + dacService, + dataAccessRequestServiceDAO, + userService, + institutionService, + emailService, + ruleService, + config); } @Test @@ -198,7 +190,8 @@ void testCreateDataAccessRequest_Update() { when(institutionService.findInstitutionForEmail(any())).thenReturn(user.getInstitution()); when(counterService.getNextDarSequence()).thenReturn(1); when(dataAccessRequestDAO.findByReferenceId(any())).thenReturn(dar); - doNothing().when(dataAccessRequestDAO) + doNothing() + .when(dataAccessRequestDAO) .updateDataByReferenceId(any(), any(), any(), any(), any(), any()); DataAccessRequest newDar = service.createDataAccessRequest(user, dar, request); assertNotNull(newDar); @@ -215,11 +208,19 @@ void testCreateDataAccessRequest_Create() { when(counterService.getNextDarSequence()).thenReturn(1); when(dataAccessRequestDAO.findByReferenceId("id")).thenReturn(null); when(dataAccessRequestDAO.findByReferenceId(argThat(new LongerThanTwo()))).thenReturn(dar); - when(darCollectionDAO.insertDarCollection(anyString(), anyInt(), any(Date.class))).thenReturn( - randomInt(1, 100)); - doNothing().when(dataAccessRequestDAO) - .insertDataAccessRequest(anyInt(), anyString(), anyInt(), any(Date.class), any(Date.class), - any(Date.class), any(DataAccessRequestData.class), anyString()); + when(darCollectionDAO.insertDarCollection(anyString(), anyInt(), any(Date.class))) + .thenReturn(randomInt(1, 100)); + doNothing() + .when(dataAccessRequestDAO) + .insertDataAccessRequest( + anyInt(), + anyString(), + anyInt(), + any(Date.class), + any(Date.class), + any(Date.class), + any(DataAccessRequestData.class), + anyString()); DataAccessRequest newDar = service.createDataAccessRequest(user, dar, request); assertNotNull(newDar); } @@ -234,7 +235,8 @@ void testCreateDataAccessRequest_CreateWithSubmittedDar() { User user = createUserWithPrerequisites(); when(institutionService.findInstitutionForEmail(any())).thenReturn(user.getInstitution()); when(dataAccessRequestDAO.findByReferenceId(any())).thenReturn(dar); - assertThrows(SubmittedDARCannotBeEditedException.class, + assertThrows( + SubmittedDARCannotBeEditedException.class, () -> service.createDataAccessRequest(user, dar, request)); } @@ -243,7 +245,8 @@ void testCreateDataAccessRequestCreateWithoutERACommons() { DataAccessRequest dar = generateDataAccessRequest(); User user = createUserWithPrerequisites(); doThrow(BadRequestException.class).when(userService).validateActiveERACredentials(user); - assertThrows(BadRequestException.class, () -> service.createDataAccessRequest(user, dar, request)); + assertThrows( + BadRequestException.class, () -> service.createDataAccessRequest(user, dar, request)); } @Test @@ -253,9 +256,8 @@ void testUpdateByReferenceIdThrowsOnDraft() { User user = new User(1, "email@test.org", "Display Name", new Date()); dar.addDatasetIds(List.of(1, 2, 3)); dar.setSubmissionDate(Timestamp.from(Instant.now())); - assertThrows(SubmittedDARCannotBeEditedException.class, () -> - service.updateByReferenceId(user, dar) - ); + assertThrows( + SubmittedDARCannotBeEditedException.class, () -> service.updateByReferenceId(user, dar)); } @Test @@ -265,7 +267,8 @@ void testCreateDataAccessRequest_FailsIfNoLibraryCard() { dar.setCreateDate(new Timestamp(1000)); dar.setReferenceId("id"); User user = new User(1, "email@test.org", "Display Name", new Date()); - assertThrows(NIHComplianceRuleException.class, + assertThrows( + NIHComplianceRuleException.class, () -> service.createDataAccessRequest(user, dar, request)); } @@ -278,18 +281,26 @@ void createProgressReport() { parentDar.setSubmissionDate(Timestamp.from(Instant.now())); User user = createUserWithPrerequisites(); parentDar.setUserId(user.getUserId()); - when(dataAccessRequestDAO.findByReferenceId(progressReport.getReferenceId())).thenReturn(progressReport); - when(dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId())).thenReturn( - Set.copyOf(progressReport.getDatasetIds())); - DataAccessRequest newDar = service.createProgressReport(user, progressReport, parentDar, request); + when(dataAccessRequestDAO.findByReferenceId(progressReport.getReferenceId())) + .thenReturn(progressReport); + when(dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId())) + .thenReturn(Set.copyOf(progressReport.getDatasetIds())); + DataAccessRequest newDar = + service.createProgressReport(user, progressReport, parentDar, request); assertNotNull(newDar); verify(dataAccessRequestDAO) - .insertProgressReport(parentDar.getId(), progressReport.getCollectionId(), - progressReport.getReferenceId(), user.getUserId(), - progressReport.getData(), user.getEraCommonsId()); - verify(ruleService).triggerDACRuleSettings(user, progressReport.getDatasetIds(), progressReport.getReferenceId(), request); - verify(dataAccessRequestDAO).insertAllDarDatasets( - argThat(new DarDatasetMatcher(progressReport))); + .insertProgressReport( + parentDar.getId(), + progressReport.getCollectionId(), + progressReport.getReferenceId(), + user.getUserId(), + progressReport.getData(), + user.getEraCommonsId()); + verify(ruleService) + .triggerDACRuleSettings( + user, progressReport.getDatasetIds(), progressReport.getReferenceId(), request); + verify(dataAccessRequestDAO) + .insertAllDarDatasets(argThat(new DarDatasetMatcher(progressReport))); } @Test @@ -315,7 +326,8 @@ void createCloseoutProgressReport() throws TemplateException, IOException { when(dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId())) .thenReturn(Set.copyOf(progressReport.getDatasetIds())); - DataAccessRequest newDar = service.createProgressReport(user, progressReport, parentDar, request); + DataAccessRequest newDar = + service.createProgressReport(user, progressReport, parentDar, request); assertNotNull(newDar); verify(emailService) @@ -346,8 +358,11 @@ void createProgressReportFailsIfNonApprovedDatasets() { parentDar.setSubmissionDate(Timestamp.from(Instant.now())); User user = createUserWithPrerequisites(); parentDar.setUserId(user.getUserId()); - when(dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId())).thenReturn(Set.of()); - assertThrows(BadRequestException.class, () -> service.createProgressReport(user, progressReport, parentDar, request)); + when(dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId())) + .thenReturn(Set.of()); + assertThrows( + BadRequestException.class, + () -> service.createProgressReport(user, progressReport, parentDar, request)); } @Test @@ -359,8 +374,8 @@ void createProgressReportFailsIfDAOOperationFails() { parentDar.setSubmissionDate(Timestamp.from(Instant.now())); User user = createUserWithPrerequisites(); parentDar.setUserId(user.getUserId()); - when(dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId())).thenReturn( - Set.copyOf(progressReport.getDatasetIds())); + when(dataAccessRequestDAO.findDatasetApprovalsByDar(parentDar.getReferenceId())) + .thenReturn(Set.copyOf(progressReport.getDatasetIds())); doThrow(new UnableToExecuteStatementException("Test exception")) .when(dataAccessRequestDAO) .insertProgressReport( @@ -370,7 +385,9 @@ void createProgressReportFailsIfDAOOperationFails() { user.getUserId(), progressReport.data, user.getEraCommonsId()); - assertThrows(BadRequestException.class, () -> service.createProgressReport(user, progressReport, parentDar, request)); + assertThrows( + BadRequestException.class, + () -> service.createProgressReport(user, progressReport, parentDar, request)); } private User createRequestingUser() { @@ -387,9 +404,13 @@ void validateProgressReportParentDarIsDraft() { User user = createUserWithPrerequisites(); DataAccessRequest progressReport = generateProgressReport(); DataAccessRequest parentDar = generateDataAccessRequest(); - BadRequestException exception = assertThrows(BadRequestException.class, - () -> service.validateProgressReport(user, progressReport, parentDar)); - assertThat(exception.getMessage(), containsString("Cannot create a progress report for a draft Data Access Request")); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); + assertThat( + exception.getMessage(), + containsString("Cannot create a progress report for a draft Data Access Request")); } @Test @@ -400,8 +421,10 @@ void validateProgressReportNoDatasetIds() { DataAccessRequest parentDar = generateDataAccessRequest(); parentDar.setSubmissionDate(Timestamp.from(Instant.now())); parentDar.setUserId(user.getUserId()); - BadRequestException exception = assertThrows(BadRequestException.class, - () -> service.validateProgressReport(user, progressReport, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); assertThat(exception.getMessage(), containsString("At least one dataset is required")); } @@ -413,8 +436,10 @@ void validateProgressReportNoSummary() { DataAccessRequest parentDar = generateDataAccessRequest(); parentDar.setSubmissionDate(Timestamp.from(Instant.now())); parentDar.setUserId(user.getUserId()); - BadRequestException exception = assertThrows(BadRequestException.class, - () -> service.validateProgressReport(user, progressReport, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); assertThat(exception.getMessage(), containsString("Progress report summary is required")); } @@ -427,13 +452,17 @@ void validateProgressReportInvalidDatasetIds() { parentDar.setSubmissionDate(Timestamp.from(Instant.now())); parentDar.setDatasetIds(List.of(1, 2, 3)); parentDar.setUserId(user.getUserId()); - BadRequestException exception = assertThrows(BadRequestException.class, - () -> service.validateProgressReport(user, progressReport, parentDar)); - assertThat(exception.getMessage(), containsString("Progress report can only be created for datasets in the parent DAR")); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); + assertThat( + exception.getMessage(), + containsString("Progress report can only be created for datasets in the parent DAR")); } @Test - void validateProgressReportCloseoutNotFoundSO(){ + void validateProgressReportCloseoutNotFoundSO() { User user = createUserWithPrerequisites(); DataAccessRequest progressReport = generateProgressReport(); DataAccessRequest parentDar = generateDataAccessRequest(); @@ -447,17 +476,19 @@ void validateProgressReportCloseoutNotFoundSO(){ doThrow(NotFoundException.class).when(userService).findUserById(2); - BadRequestException exception = assertThrows(BadRequestException.class, - () -> service.validateProgressReport(user, progressReport, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); assertThat( exception.getMessage(), containsString("The selected signing official in the closeout was not found.")); } @Test - void validateProgressReportCloseoutNotSameInstitutionSO(){ + void validateProgressReportCloseoutNotSameInstitutionSO() { User user = createUserWithPrerequisites(); - User signingOfficial = createUserWithPrerequisites(); + User signingOfficial = createUserWithPrerequisites(); signingOfficial.setInstitutionId(user.getInstitutionId() + 1); DataAccessRequest progressReport = generateProgressReport(); DataAccessRequest parentDar = generateDataAccessRequest(); @@ -471,17 +502,20 @@ void validateProgressReportCloseoutNotSameInstitutionSO(){ when(userService.findUserById(2)).thenReturn(signingOfficial); - BadRequestException exception = assertThrows(BadRequestException.class, - () -> service.validateProgressReport(user, progressReport, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); assertThat( exception.getMessage(), - containsString("The signing official selected in the closeout is not in the same institution as the submitter.")); + containsString( + "The signing official selected in the closeout is not in the same institution as the submitter.")); } @Test - void validateProgressReportCloseoutSameInstitutionNotAnSO(){ + void validateProgressReportCloseoutSameInstitutionNotAnSO() { User user = createUserWithPrerequisites(); - User signingOfficial = createUserWithPrerequisites(); + User signingOfficial = createUserWithPrerequisites(); signingOfficial.setInstitutionId(user.getInstitutionId()); DataAccessRequest progressReport = generateProgressReport(); DataAccessRequest parentDar = generateDataAccessRequest(); @@ -495,17 +529,19 @@ void validateProgressReportCloseoutSameInstitutionNotAnSO(){ when(userService.findUserById(2)).thenReturn(signingOfficial); - BadRequestException exception = assertThrows(BadRequestException.class, - () -> service.validateProgressReport(user, progressReport, parentDar)); + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); assertThat( exception.getMessage(), containsString("The selected signing official is not a signing official")); } @Test - void validateProgressReportCloseout(){ + void validateProgressReportCloseout() { User user = createUserWithPrerequisites(); - User signingOfficial = createUserWithPrerequisites(); + User signingOfficial = createUserWithPrerequisites(); signingOfficial.setInstitutionId(user.getInstitutionId()); signingOfficial.setSigningOfficialRole(); DataAccessRequest progressReport = generateProgressReport(); @@ -520,8 +556,7 @@ void validateProgressReportCloseout(){ when(userService.findUserById(2)).thenReturn(signingOfficial); - assertDoesNotThrow( - () -> service.validateProgressReport(user, progressReport, parentDar)); + assertDoesNotThrow(() -> service.validateProgressReport(user, progressReport, parentDar)); } @Test @@ -581,7 +616,10 @@ void validateProgressReportWithCollaboratorsAndStaffInInvalidInstitution() { parentDar.setUserId(user.getUserId()); when(userDAO.findUserByEmail(collaborator1.email())).thenReturn(user); when(institutionService.findInstitutionForEmail(any())).thenReturn(null); - BadRequestException badRequestException = assertThrows(BadRequestException.class, () -> service.validateProgressReport(user, progressReport, parentDar)); + BadRequestException badRequestException = + assertThrows( + BadRequestException.class, + () -> service.validateProgressReport(user, progressReport, parentDar)); assertThat( badRequestException.getMessage(), containsString( @@ -594,21 +632,20 @@ void validateProgressReportWithCollaboratorsAndStaffInInvalidInstitution() { """)); } - @Test void validateCommonNullUserThrows() { DataAccessRequest dar = generateDataAccessRequest(); - assertThrows(IllegalArgumentException.class, () -> - service.validateCommonDarAndProgressReportElements(null, dar) - ); + assertThrows( + IllegalArgumentException.class, + () -> service.validateCommonDarAndProgressReportElements(null, dar)); } @Test void validateCommonNullDarThrows() { User user = createUserWithPrerequisites(); - assertThrows(IllegalArgumentException.class, () -> - service.validateCommonDarAndProgressReportElements(user, null) - ); + assertThrows( + IllegalArgumentException.class, + () -> service.validateCommonDarAndProgressReportElements(user, null)); } @Test @@ -616,18 +653,17 @@ void validateCommonNullDarDataThrows() { User user = createUserWithPrerequisites(); DataAccessRequest dar = new DataAccessRequest(); dar.setData(null); - assertThrows(IllegalArgumentException.class, () -> - service.validateCommonDarAndProgressReportElements(user, dar) - ); + assertThrows( + IllegalArgumentException.class, + () -> service.validateCommonDarAndProgressReportElements(user, dar)); } @Test void validateCommonDoesNotThrow() { User validUser = createUserWithPrerequisites(); DataAccessRequest validDar = generateDataAccessRequest(); - assertDoesNotThrow(() -> - service.validateCommonDarAndProgressReportElements(validUser, validDar) - ); + assertDoesNotThrow( + () -> service.validateCommonDarAndProgressReportElements(validUser, validDar)); } @Test @@ -636,12 +672,11 @@ void validateCommonNoLibraryCard() { DataAccessRequest validDar = generateDataAccessRequest(); validDar.getData().setPiName(validUser.getDisplayName()); validDar.getData().setPiEmail(validUser.getEmail()); - assertThrows(NIHComplianceRuleException.class, () -> - service.validateCommonDarAndProgressReportElements(validUser, validDar) - ); + assertThrows( + NIHComplianceRuleException.class, + () -> service.validateCommonDarAndProgressReportElements(validUser, validDar)); } - @Test void validateDarNullUser() { DataAccessRequest dar = generateDataAccessRequest(); @@ -677,15 +712,12 @@ void validateDarNoLibraryCards() { assertThrows(NIHComplianceRuleException.class, () -> service.validateDar(user, dar)); } - @Test void validateDarDifferentPiEmail() { User validUser = createUserWithPrerequisites(); DataAccessRequest dar = generateDataAccessRequest(); dar.getData().setPiEmail("otheremail@example.com"); - assertThrows(BadRequestException.class, () -> - service.validateDar(validUser, dar) - ); + assertThrows(BadRequestException.class, () -> service.validateDar(validUser, dar)); } @Test @@ -693,9 +725,7 @@ void validateDarDifferentPiName() { User validUser = createUserWithPrerequisites(); DataAccessRequest dar = generateDataAccessRequest(); dar.getData().setPiName("Other Name"); - assertThrows(BadRequestException.class, () -> - service.validateDar(validUser, dar) - ); + assertThrows(BadRequestException.class, () -> service.validateDar(validUser, dar)); } @Test @@ -717,13 +747,14 @@ void testValidateInternalCollaboratorsNone() { void testValidateInternalCollaboratorsValid() { User requestingUser = createRequestingUser(); Collaborator validCollaborator = createCollaborator(); - User collaboratorUser = new User(2, validCollaborator.email(), "Collaborator", new Date(), - roles); + User collaboratorUser = + new User(2, validCollaborator.email(), "Collaborator", new Date(), roles); collaboratorUser.setInstitutionId(requestingUser.getInstitutionId()); LibraryCard libraryCard = new LibraryCard(); collaboratorUser.setLibraryCard(libraryCard); DataAccessRequest dar = createDataAccessRequest(List.of(validCollaborator)); - when(institutionService.findInstitutionForEmail(collaboratorUser.getEmail())).thenReturn(requestingUser.getInstitution()); + when(institutionService.findInstitutionForEmail(collaboratorUser.getEmail())) + .thenReturn(requestingUser.getInstitution()); when(userDAO.findUserByEmail(validCollaborator.email())).thenReturn(collaboratorUser); assertDoesNotThrow(() -> service.validateInternalCollaborators(requestingUser, dar)); @@ -733,20 +764,26 @@ void testValidateInternalCollaboratorsValid() { void testValidateInternalCollaboratorsLibraryCard_NoInstitution() { User requestingUser = createRequestingUser(); Collaborator validCollaborator = createCollaborator(); - User collaboratorUser = new User(2, validCollaborator.email(), "Collaborator", new Date(), - roles); + User collaboratorUser = + new User(2, validCollaborator.email(), "Collaborator", new Date(), roles); collaboratorUser.setInstitutionId(requestingUser.getInstitutionId()); LibraryCard libraryCard = new LibraryCard(); collaboratorUser.setLibraryCard(libraryCard); DataAccessRequest dar = createDataAccessRequest(List.of(validCollaborator)); when(userDAO.findUserByEmail(validCollaborator.email())).thenReturn(collaboratorUser); - BadRequestException exception = assertThrows(BadRequestException.class, () -> service.validateInternalCollaborators(requestingUser, dar)); - assertEquals(""" + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateInternalCollaborators(requestingUser, dar)); + assertEquals( + """ All listed personnel must share the same institutional affiliation and have a library card. \ The following list of roles and members must have email addresses associated with your \ institution or library cards issued: Internal Collaborator member: (missing institution) %s\ - """.formatted(collaboratorUser.getEmail()), exception.getMessage()); + """ + .formatted(collaboratorUser.getEmail()), + exception.getMessage()); } @Test @@ -775,22 +812,27 @@ void testValidateInternalCollaboratorsDoesNotExist() { void testValidateInternalCollaboratorsNoLibraryCard() { User requestingUser = createRequestingUser(); Collaborator invalidCollaborator = createCollaborator(); - User collaboratorUser = new User(2, invalidCollaborator.email(), "Collaborator", new Date(), - roles); + User collaboratorUser = + new User(2, invalidCollaborator.email(), "Collaborator", new Date(), roles); collaboratorUser.setInstitutionId(requestingUser.getInstitutionId()); DataAccessRequest dar = createDataAccessRequest(List.of(invalidCollaborator)); when(userDAO.findUserByEmail(invalidCollaborator.email())).thenReturn(collaboratorUser); - when(institutionService.findInstitutionForEmail(invalidCollaborator.email())).thenReturn(requestingUser.getInstitution()); + when(institutionService.findInstitutionForEmail(invalidCollaborator.email())) + .thenReturn(requestingUser.getInstitution()); - BadRequestException exception = assertThrows(BadRequestException.class, () -> - service.validateInternalCollaborators(requestingUser, dar) - ); - assertEquals(""" + BadRequestException exception = + assertThrows( + BadRequestException.class, + () -> service.validateInternalCollaborators(requestingUser, dar)); + assertEquals( +""" All listed personnel must share the same institutional affiliation and have a library card. \ The following list of roles and members must have email addresses associated with your \ institution or library cards issued: Internal Collaborator member: \ (missing library card) %s\ -""".formatted(collaboratorUser.getEmail()), exception.getMessage()); +""" + .formatted(collaboratorUser.getEmail()), + exception.getMessage()); } @Test @@ -828,8 +870,7 @@ void testGetUsersApprovedForDataset() { dar1.setUserId(user1.getUserId()); DataAccessRequest dar2 = new DataAccessRequest(); dar2.setUserId(user2.getUserId()); - when(dataAccessRequestDAO - .findApprovedDARsByDatasetId(d.getDatasetId())) + when(dataAccessRequestDAO.findApprovedDARsByDatasetId(d.getDatasetId())) .thenReturn(List.of(dar1, dar2)); assertEquals(List.of(dar1, dar2), service.getApprovedDARsForDataset(d)); @@ -851,30 +892,30 @@ void testInsertDraftDataAccessRequest() { @Test void testInsertDraftDataAccessRequestFailure() { - assertThrows(IllegalArgumentException.class, () -> service.insertDraftDataAccessRequest(null, null)); + assertThrows( + IllegalArgumentException.class, () -> service.insertDraftDataAccessRequest(null, null)); } private DataAccessRequest generateProgressReport() { DataAccessRequest progressReport = generateDataAccessRequest(); progressReport.getData().setProgressReportSummary("Progress Report Summary"); - progressReport.getData().setIntellectualProperties( - List.of( - new IntellectualProperty( - "Patent", - "Description of patent", - "2024-01-01", - "Test Assignee", - "US12345678", - true, - "Active", - "https://example.com", - "contact@example.com", - "ip-123", - "study-456", - List.of("tag1", "tag2") - ) - ) - ); + progressReport + .getData() + .setIntellectualProperties( + List.of( + new IntellectualProperty( + "Patent", + "Description of patent", + "2024-01-01", + "Test Assignee", + "US12345678", + true, + "Active", + "https://example.com", + "contact@example.com", + "ip-123", + "study-456", + List.of("tag1", "tag2")))); return progressReport; } @@ -922,16 +963,16 @@ private DataAccessRequest generateDataAccessRequest() { @Test void testFindAllDraftDataAccessRequests() { - when(dataAccessRequestDAO.findAllDraftDataAccessRequests()).thenReturn( - List.of(new DataAccessRequest())); + when(dataAccessRequestDAO.findAllDraftDataAccessRequests()) + .thenReturn(List.of(new DataAccessRequest())); List drafts = service.findAllDraftDataAccessRequests(); assertEquals(1, drafts.size()); } @Test void testFindAllDraftDataAccessRequestsByUser() { - when(dataAccessRequestDAO.findAllDraftsByUserId(any())).thenReturn( - List.of(new DataAccessRequest())); + when(dataAccessRequestDAO.findAllDraftsByUserId(any())) + .thenReturn(List.of(new DataAccessRequest())); List drafts = service.findAllDraftDataAccessRequestsByUser(1); assertEquals(1, drafts.size()); } @@ -971,7 +1012,8 @@ void testDeleteDataAccessRequestAdmin() { election.setReferenceId(referenceId); when(electionDAO.findElectionsByReferenceId(any())).thenReturn(List.of(election)); - assertThrows(NotAcceptableException.class, () -> service.deleteDataAccessRequest(dataAccessRequest)); + assertThrows( + NotAcceptableException.class, () -> service.deleteDataAccessRequest(dataAccessRequest)); } @Test @@ -1001,8 +1043,8 @@ void testDeleteDataAccessRequestResearcherFailure() { election.setReferenceId(referenceId); when(electionDAO.findElectionsByReferenceId(any())).thenReturn(List.of(election)); - assertThrows(NotAcceptableException.class, - () -> service.deleteDataAccessRequest(dataAccessRequest)); + assertThrows( + NotAcceptableException.class, () -> service.deleteDataAccessRequest(dataAccessRequest)); } @Test @@ -1012,8 +1054,8 @@ void testDeleteDataAccessRequestSubmittedDarFailure() { dataAccessRequest.setReferenceId(referenceId); dataAccessRequest.setSubmissionDate(Timestamp.from(Instant.now())); - assertThrows(BadRequestException.class, - () -> service.deleteDataAccessRequest(dataAccessRequest)); + assertThrows( + BadRequestException.class, () -> service.deleteDataAccessRequest(dataAccessRequest)); } @Test @@ -1035,8 +1077,8 @@ void testValidateNoKeyPersonnelDuplicatesBadPIEmail() { data.setPiEmail("invalid"); data.setItDirectorEmail(IT_EMAIL); data.setSigningOfficialEmail(SO_EMAIL); - assertThrows(IllegalArgumentException.class, - () -> service.validateNoKeyPersonnelDuplicates(data)); + assertThrows( + IllegalArgumentException.class, () -> service.validateNoKeyPersonnelDuplicates(data)); } @Test @@ -1045,8 +1087,8 @@ void testValidateNoKeyPersonnelDuplicatesBadITDirectorEmail() { data.setPiEmail(PI_EMAIL); data.setItDirectorEmail("invalid"); data.setSigningOfficialEmail(SO_EMAIL); - assertThrows(IllegalArgumentException.class, - () -> service.validateNoKeyPersonnelDuplicates(data)); + assertThrows( + IllegalArgumentException.class, () -> service.validateNoKeyPersonnelDuplicates(data)); } @Test @@ -1055,8 +1097,8 @@ void testValidateNoKeyPersonnelDuplicatesBadSO() { data.setPiEmail(PI_EMAIL); data.setItDirectorEmail(IT_EMAIL); data.setSigningOfficialEmail("invalid"); - assertThrows(IllegalArgumentException.class, - () -> service.validateNoKeyPersonnelDuplicates(data)); + assertThrows( + IllegalArgumentException.class, () -> service.validateNoKeyPersonnelDuplicates(data)); } @Test @@ -1065,8 +1107,8 @@ void testValidateNoKeyPersonnelDuplicatesItDirector() { data.setPiEmail(PI_EMAIL); data.setItDirectorEmail(PI_EMAIL); data.setSigningOfficialEmail(SO_EMAIL); - assertThrows(IllegalArgumentException.class, - () -> service.validateNoKeyPersonnelDuplicates(data)); + assertThrows( + IllegalArgumentException.class, () -> service.validateNoKeyPersonnelDuplicates(data)); } @Test @@ -1075,8 +1117,8 @@ void testValidateNoKeyPersonnelDuplicatesSO() { data.setPiEmail(PI_EMAIL); data.setItDirectorEmail(IT_EMAIL); data.setSigningOfficialEmail(PI_EMAIL); - assertThrows(IllegalArgumentException.class, - () -> service.validateNoKeyPersonnelDuplicates(data)); + assertThrows( + IllegalArgumentException.class, () -> service.validateNoKeyPersonnelDuplicates(data)); } @Test @@ -1120,7 +1162,8 @@ void testValidatePersonnelInstitutionAndLibraryCardRequirementsDoesNotThrowExcep when(institutionService.findInstitutionForEmail(goodEmailAddress)).thenReturn(goodInstitution); when(userDAO.findUserByEmail(goodEmailAddress)).thenReturn(user); initService(); - assertDoesNotThrow(() -> service.validatePersonnelInstitutionAndLibraryCardRequirements(user, data)); + assertDoesNotThrow( + () -> service.validatePersonnelInstitutionAndLibraryCardRequirements(user, data)); } @Test @@ -1252,8 +1295,7 @@ void testValidatePIAndCollaboratorCountryOfOperationThrowsForBadCountry() { BadRequestException exception = assertThrows( - BadRequestException.class, - () -> service.validateCountryOfOperation(data, false)); + BadRequestException.class, () -> service.validateCountryOfOperation(data, false)); assertThat(exception.getMessage(), containsString("Principal Investigator")); assertThat(exception.getMessage(), containsString("Atlantis")); @@ -1386,7 +1428,8 @@ void sendExpirationNoticesTest() { when(userDAO.findUserById(user1.getUserId())).thenReturn(user1); when(userDAO.findUserById(user2.getUserId())).thenReturn(user2); List dars = List.of(dar1, dar2); - when(dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval(any(), any(), any())).thenReturn(dars); + when(dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval(any(), any(), any())) + .thenReturn(dars); initService(); assertDoesNotThrow(() -> service.sendExpirationNotices()); } @@ -1394,7 +1437,8 @@ void sendExpirationNoticesTest() { @Test void sendExpirationNoticesTestMissingEmailForOneUser() { ListAppender listAppender = new ListAppender<>(); - ch.qos.logback.classic.Logger log = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(DataAccessRequestService.class); + ch.qos.logback.classic.Logger log = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(DataAccessRequestService.class); listAppender.start(); log.addAppender(listAppender); User user1 = new User(); @@ -1414,10 +1458,11 @@ void sendExpirationNoticesTestMissingEmailForOneUser() { List dars = List.of(dar2, dar1); - when(dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval(any(), any(), any())).thenReturn(dars); + when(dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval(any(), any(), any())) + .thenReturn(dars); initService(); - assertDoesNotThrow(()->service.sendExpirationNotices()); + assertDoesNotThrow(() -> service.sendExpirationNotices()); assertEquals(2, listAppender.list.size()); } @@ -1425,7 +1470,8 @@ void sendExpirationNoticesTestMissingEmailForOneUser() { @Test void sendExpirationNoticesTestUnderlyingExceptionThrownSendingOneTypeOfMessage() { ListAppender listAppender = new ListAppender<>(); - ch.qos.logback.classic.Logger log = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(DataAccessRequestService.class); + ch.qos.logback.classic.Logger log = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(DataAccessRequestService.class); listAppender.start(); log.addAppender(listAppender); User user1 = new User(); @@ -1446,25 +1492,28 @@ void sendExpirationNoticesTestUnderlyingExceptionThrownSendingOneTypeOfMessage() List dars = List.of(dar2, dar1); - when(dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval(any(), any(), any())).thenReturn(dars); + when(dataAccessRequestDAO.findAgedDARsByEmailTypeOlderThanInterval(any(), any(), any())) + .thenReturn(dars); initService(); - assertDoesNotThrow(()->service.sendExpirationNotices()); + assertDoesNotThrow(() -> service.sendExpirationNotices()); assertEquals(2, listAppender.list.size()); } @Test - void testValidateCloseoutApproval_NonCloseout(){ + void testValidateCloseoutApproval_NonCloseout() { User user = new User(); user.setUserId(123); DataAccessRequest dar = new DataAccessRequest(); - BadRequestException exception = assertThrows(BadRequestException.class, ()->service.validateCloseoutApproval(user, dar)); - assertThat(exception.getMessage(), containsString("Signing officials can only approve closeout progress reports.")); + BadRequestException exception = + assertThrows(BadRequestException.class, () -> service.validateCloseoutApproval(user, dar)); + assertThat( + exception.getMessage(), + containsString("Signing officials can only approve closeout progress reports.")); } - @Test - void testValidateCloseoutApproval_AlreadyApproved(){ + void testValidateCloseoutApproval_AlreadyApproved() { User user = new User(); user.setUserId(123); DataAccessRequest dar = new DataAccessRequest(); @@ -1472,35 +1521,40 @@ void testValidateCloseoutApproval_AlreadyApproved(){ dar.setParentId(1); dar.setCloseoutSigningOfficialApprovedDate(Timestamp.from(Instant.now())); dar.setCloseoutSigningOfficialApprovedUserId(1); - DataAccessRequestData data = new DataAccessRequestData(); + DataAccessRequestData data = new DataAccessRequestData(); data.setCloseoutSupplement(new CloseoutSupplement(List.of(""), "", 1)); dar.setData(data); - BadRequestException exception = assertThrows(BadRequestException.class, ()->service.validateCloseoutApproval(user, dar)); - assertThat(exception.getMessage(), containsString("This progress report closeout has already been approved by a signing official.")); + BadRequestException exception = + assertThrows(BadRequestException.class, () -> service.validateCloseoutApproval(user, dar)); + assertThat( + exception.getMessage(), + containsString( + "This progress report closeout has already been approved by a signing official.")); } @Test - void testValidateCloseoutApproval_NotTheSelectedSigningOfficial(){ + void testValidateCloseoutApproval_NotTheSelectedSigningOfficial() { User user = new User(); user.setUserId(123); DataAccessRequest dar = new DataAccessRequest(); dar.setSubmissionDate(Timestamp.from(Instant.now())); dar.setParentId(1); - DataAccessRequestData data = new DataAccessRequestData(); + DataAccessRequestData data = new DataAccessRequestData(); data.setCloseoutSupplement(new CloseoutSupplement(List.of(""), "", 1)); dar.setData(data); - BadRequestException exception = assertThrows(BadRequestException.class, ()->service.validateCloseoutApproval(user, dar)); + BadRequestException exception = + assertThrows(BadRequestException.class, () -> service.validateCloseoutApproval(user, dar)); assertThat( exception.getMessage(), containsString( - "This request can only be approved by the signing official selected in the closeout request.")); + "This request can only be approved by the signing official selected in the closeout request.")); } @Test - void testValidateCloseoutApproval_NotInSameInstitution(){ + void testValidateCloseoutApproval_NotInSameInstitution() { User actor = new User(); actor.setUserId(123); actor.setInstitutionId(1); @@ -1512,12 +1566,13 @@ void testValidateCloseoutApproval_NotInSameInstitution(){ dar.setSubmissionDate(Timestamp.from(Instant.now())); dar.setParentId(1); - DataAccessRequestData data = new DataAccessRequestData(); + DataAccessRequestData data = new DataAccessRequestData(); data.setCloseoutSupplement(new CloseoutSupplement(List.of(""), "", actor.getUserId())); dar.setData(data); when(userService.findUserById(darSubmitter.getUserId())).thenReturn(darSubmitter); - BadRequestException exception = assertThrows(BadRequestException.class, ()->service.validateCloseoutApproval(actor, dar)); + BadRequestException exception = + assertThrows(BadRequestException.class, () -> service.validateCloseoutApproval(actor, dar)); assertThat( exception.getMessage(), containsString( @@ -1525,11 +1580,12 @@ void testValidateCloseoutApproval_NotInSameInstitution(){ } @Test - void testValidateCloseoutApproval(){ - CloseoutWithUserAndSigningOfficialApproval closeout = new CloseoutWithUserAndSigningOfficialApproval(); + void testValidateCloseoutApproval() { + CloseoutWithUserAndSigningOfficialApproval closeout = + new CloseoutWithUserAndSigningOfficialApproval(); when(userService.findUserById(closeout.submitter.getUserId())).thenReturn(closeout.submitter); - assertDoesNotThrow(()->service.validateCloseoutApproval(closeout.actor, closeout.dar)); + assertDoesNotThrow(() -> service.validateCloseoutApproval(closeout.actor, closeout.dar)); } @Test @@ -1563,9 +1619,10 @@ private DataAccessRequest getMockedDar(String darCode, String referenceId, User return dar; } - record CloseoutWithUserAndSigningOfficialApproval(User actor, User submitter, DataAccessRequest dar) { + record CloseoutWithUserAndSigningOfficialApproval( + User actor, User submitter, DataAccessRequest dar) { public CloseoutWithUserAndSigningOfficialApproval() { - this(new User(), new User(), new DataAccessRequest()); + this(new User(), new User(), new DataAccessRequest()); actor.setUserId(123); actor.setInstitutionId(1); submitter.setUserId(124); @@ -1577,7 +1634,7 @@ public CloseoutWithUserAndSigningOfficialApproval() { dar.setDarCode("DAR-0001"); dar.setCollectionId(4); dar.setReferenceId(UUID.randomUUID().toString()); - DataAccessRequestData data = new DataAccessRequestData(); + DataAccessRequestData data = new DataAccessRequestData(); data.setCloseoutSupplement(new CloseoutSupplement(List.of(""), "", actor.getUserId())); dar.setData(data); } @@ -1594,8 +1651,8 @@ public DarDatasetMatcher(DataAccessRequest progressReport) { @Override public boolean matches(List darDatasets) { for (int i = 0; i < darDatasets.size(); i++) { - if (!darDatasets.get(i).getReferenceId().equals(progressReport.getReferenceId()) || - !darDatasets.get(i).getDatasetId().equals(progressReport.getDatasetIds().get(i))) { + if (!darDatasets.get(i).getReferenceId().equals(progressReport.getReferenceId()) + || !darDatasets.get(i).getDatasetId().equals(progressReport.getDatasetIds().get(i))) { return false; } } @@ -1610,5 +1667,4 @@ public boolean matches(String argument) { return argument.length() > 2; } } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/DatasetRegistrationServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DatasetRegistrationServiceTest.java index a06bd31fa2..72bdb7f458 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DatasetRegistrationServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DatasetRegistrationServiceTest.java @@ -70,38 +70,35 @@ class DatasetRegistrationServiceTest { private DatasetRegistrationService datasetRegistrationService; - @Mock - private DatasetDAO datasetDAO; + @Mock private DatasetDAO datasetDAO; - @Mock - private DacDAO dacDAO; + @Mock private DacDAO dacDAO; - @Mock - private DatasetServiceDAO datasetServiceDAO; + @Mock private DatasetServiceDAO datasetServiceDAO; - @Mock - private StudyDAO studyDAO; + @Mock private StudyDAO studyDAO; - @Mock - private GCSService gcsService; + @Mock private GCSService gcsService; - @Mock - private ElasticSearchService elasticSearchService; + @Mock private ElasticSearchService elasticSearchService; - @Mock - private EmailService emailService; + @Mock private EmailService emailService; private void initService() { - datasetRegistrationService = new DatasetRegistrationService(datasetDAO, dacDAO, - datasetServiceDAO, gcsService, elasticSearchService, studyDAO, emailService); + datasetRegistrationService = + new DatasetRegistrationService( + datasetDAO, + dacDAO, + datasetServiceDAO, + gcsService, + elasticSearchService, + studyDAO, + emailService); } - // captor: allows you to inspect the arguments sent to a function. - @Captor - ArgumentCaptor> datasetInsertCaptor; - @Captor - ArgumentCaptor studyInsert; + @Captor ArgumentCaptor> datasetInsertCaptor; + @Captor ArgumentCaptor studyInsert; // ------------------------ test multiple dataset insert ----------------------------------- // @Test @@ -109,10 +106,8 @@ void testInsertCompleteDatasetRegistration() throws Exception { User user = mock(); DatasetRegistrationSchemaV1 schema = createRandomCompleteDatasetRegistration(user); - FormDataContentDisposition content = FormDataContentDisposition - .name("file") - .fileName("sharing_plan.txt") - .build(); + FormDataContentDisposition content = + FormDataContentDisposition.name("file").fileName("sharing_plan.txt").build(); InputStream is = new ByteArrayInputStream("HelloWorld".getBytes(StandardCharsets.UTF_8)); FormDataBodyPart bodyPart = mock(); @@ -122,17 +117,22 @@ void testInsertCompleteDatasetRegistration() throws Exception { initService(); - Map files = Map.of("alternativeDataSharingPlan", - bodyPart, "consentGroups[0].nihInstitutionalCertificationFile", - bodyPart, "otherUnused", bodyPart); - when(gcsService.storeDocument(any(), any(), any())).thenReturn(BlobId.of("asdf", "hjkl"), - BlobId.of("qwer", "tyuio")); + Map files = + Map.of( + "alternativeDataSharingPlan", + bodyPart, + "consentGroups[0].nihInstitutionalCertificationFile", + bodyPart, + "otherUnused", + bodyPart); + when(gcsService.storeDocument(any(), any(), any())) + .thenReturn(BlobId.of("asdf", "hjkl"), BlobId.of("qwer", "tyuio")); when(dacDAO.findById(any())).thenReturn(new Dac()); datasetRegistrationService.createDatasetsFromRegistration(schema, user, files); - verify(datasetServiceDAO).insertDatasetRegistration(studyInsert.capture(), - datasetInsertCaptor.capture()); + verify(datasetServiceDAO) + .insertDatasetRegistration(studyInsert.capture(), datasetInsertCaptor.capture()); // only two files are stored; extra "unused" file not used verify(gcsService, times(2)).storeDocument(any(), any(), any()); @@ -142,32 +142,32 @@ void testInsertCompleteDatasetRegistration() throws Exception { assertEquals(1, inserts.size()); - assertEquals(schema.getConsentGroups().get(0).getConsentGroupName(), - inserts.get(0).name()); + assertEquals(schema.getConsentGroups().get(0).getConsentGroupName(), inserts.get(0).name()); assertDataUse(schema.getConsentGroups().get(0), inserts.get(0).dataUse()); assertEquals(user.getUserId(), inserts.get(0).userId()); assertEquals(1, inserts.get(0).files().size()); - assertEquals(FileCategory.NIH_INSTITUTIONAL_CERTIFICATION, - inserts.get(0).files().get(0).getCategory()); assertEquals( - files.get("consentGroups[0].nihInstitutionalCertificationFile").getContentDisposition() + FileCategory.NIH_INSTITUTIONAL_CERTIFICATION, inserts.get(0).files().get(0).getCategory()); + assertEquals( + files + .get("consentGroups[0].nihInstitutionalCertificationFile") + .getContentDisposition() .getFileName(), inserts.get(0).files().get(0).getFileName()); - assertEquals(BlobId.of("qwer", "tyuio"), - inserts.get(0).files().get(0).getBlobId()); + assertEquals(BlobId.of("qwer", "tyuio"), inserts.get(0).files().get(0).getBlobId()); assertEquals(schema.getStudyName(), capturedStudyInsert.name()); assertEquals(schema.getPiName(), capturedStudyInsert.piName()); assertEquals(schema.getStudyDescription(), capturedStudyInsert.description()); assertEquals(schema.getDataTypes(), capturedStudyInsert.dataTypes()); - assertEquals(schema.getPublicVisibility(), - capturedStudyInsert.publicVisibility()); + assertEquals(schema.getPublicVisibility(), capturedStudyInsert.publicVisibility()); assertEquals(user.getUserId(), capturedStudyInsert.userId()); assertEquals(1, capturedStudyInsert.files().size()); - assertEquals(FileCategory.ALTERNATIVE_DATA_SHARING_PLAN, + assertEquals( + FileCategory.ALTERNATIVE_DATA_SHARING_PLAN, capturedStudyInsert.files().get(0).getCategory()); // TODO: is there a way to ensure we don't miss anything? @@ -175,75 +175,119 @@ void testInsertCompleteDatasetRegistration() throws Exception { assertContainsStudyProperty(studyProps, "studyType", schema.getStudyType().value()); assertContainsStudyProperty(studyProps, "phenotypeIndication", schema.getPhenotypeIndication()); assertContainsStudyProperty(studyProps, "species", schema.getSpecies()); - assertContainsStudyProperty(studyProps, "dataCustodianEmail", + assertContainsStudyProperty( + studyProps, + "dataCustodianEmail", PropertyType.coerceToJson(GsonUtil.getInstance().toJson(schema.getDataCustodianEmail()))); assertContainsStudyProperty(studyProps, "nihAnvilUse", schema.getNihAnvilUse().value()); assertContainsStudyProperty(studyProps, "submittingToAnvil", schema.getSubmittingToAnvil()); assertContainsStudyProperty(studyProps, "dbGaPPhsID", schema.getDbGaPPhsID()); - assertContainsStudyProperty(studyProps, "dbGaPStudyRegistrationName", - schema.getDbGaPStudyRegistrationName()); - assertContainsStudyProperty(studyProps, "embargoReleaseDate", + assertContainsStudyProperty( + studyProps, "dbGaPStudyRegistrationName", schema.getDbGaPStudyRegistrationName()); + assertContainsStudyProperty( + studyProps, + "embargoReleaseDate", PropertyType.coerceToDate(schema.getEmbargoReleaseDate())); assertContainsStudyProperty(studyProps, "sequencingCenter", schema.getSequencingCenter()); assertContainsStudyProperty(studyProps, "piInstitution", schema.getPiInstitution()); - assertContainsStudyProperty(studyProps, "nihGrantContractNumber", - schema.getNihGrantContractNumber()); - assertContainsStudyProperty(studyProps, "nihICsSupportingStudy", PropertyType.coerceToJson( - GsonUtil.getInstance().toJson( - schema.getNihICsSupportingStudy().stream().map(NihICsSupportingStudy::value) - .toList()))); - assertContainsStudyProperty(studyProps, "nihProgramOfficerName", - schema.getNihProgramOfficerName()); - assertContainsStudyProperty(studyProps, "nihInstitutionCenterSubmission", + assertContainsStudyProperty( + studyProps, "nihGrantContractNumber", schema.getNihGrantContractNumber()); + assertContainsStudyProperty( + studyProps, + "nihICsSupportingStudy", + PropertyType.coerceToJson( + GsonUtil.getInstance() + .toJson( + schema.getNihICsSupportingStudy().stream() + .map(NihICsSupportingStudy::value) + .toList()))); + assertContainsStudyProperty( + studyProps, "nihProgramOfficerName", schema.getNihProgramOfficerName()); + assertContainsStudyProperty( + studyProps, + "nihInstitutionCenterSubmission", schema.getNihInstitutionCenterSubmission().value()); - assertContainsStudyProperty(studyProps, "nihGenomicProgramAdministratorName", + assertContainsStudyProperty( + studyProps, + "nihGenomicProgramAdministratorName", schema.getNihGenomicProgramAdministratorName()); assertContainsStudyProperty(studyProps, "multiCenterStudy", schema.getMultiCenterStudy()); - assertContainsStudyProperty(studyProps, "collaboratingSites", + assertContainsStudyProperty( + studyProps, + "collaboratingSites", PropertyType.coerceToJson(GsonUtil.getInstance().toJson(schema.getCollaboratingSites()))); - assertContainsStudyProperty(studyProps, "controlledAccessRequiredForGenomicSummaryResultsGSR", + assertContainsStudyProperty( + studyProps, + "controlledAccessRequiredForGenomicSummaryResultsGSR", schema.getControlledAccessRequiredForGenomicSummaryResultsGSR()); - assertContainsStudyProperty(studyProps, + assertContainsStudyProperty( + studyProps, "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation", schema.getControlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation()); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlan", - schema.getAlternativeDataSharingPlan()); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanReasons", - PropertyType.coerceToJson(GsonUtil.getInstance().toJson( - schema.getAlternativeDataSharingPlanReasons().stream() - .map(AlternativeDataSharingPlanReason::value).toList()))); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanExplanation", + assertContainsStudyProperty( + studyProps, "alternativeDataSharingPlan", schema.getAlternativeDataSharingPlan()); + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanReasons", + PropertyType.coerceToJson( + GsonUtil.getInstance() + .toJson( + schema.getAlternativeDataSharingPlanReasons().stream() + .map(AlternativeDataSharingPlanReason::value) + .toList()))); + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanExplanation", schema.getAlternativeDataSharingPlanExplanation()); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanFileName", + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanFileName", schema.getAlternativeDataSharingPlanFileName()); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanDataSubmitted", + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanDataSubmitted", schema.getAlternativeDataSharingPlanDataSubmitted().value()); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanDataReleased", + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanDataReleased", schema.getAlternativeDataSharingPlanDataReleased()); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanTargetDeliveryDate", + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanTargetDeliveryDate", PropertyType.Date.coerce(schema.getAlternativeDataSharingPlanTargetDeliveryDate())); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanTargetPublicReleaseDate", + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanTargetPublicReleaseDate", PropertyType.Date.coerce(schema.getAlternativeDataSharingPlanTargetPublicReleaseDate())); - assertContainsStudyProperty(studyProps, "alternativeDataSharingPlanAccessManagement", + assertContainsStudyProperty( + studyProps, + "alternativeDataSharingPlanAccessManagement", schema.getAlternativeDataSharingPlanAccessManagement().value()); - assertContainsStudyProperty(studyProps, "assets", + assertContainsStudyProperty( + studyProps, + "assets", PropertyType.coerceToJson(GsonUtil.getInstance().toJson(schema.getAssets()))); List datasetProps = inserts.get(0).props(); - assertContainsDatasetProperty(datasetProps, "dataLocation", - schema.getConsentGroups().get(0).getDataLocation().value()); - assertContainsDatasetProperty(datasetProps, "numberOfParticipants", + assertContainsDatasetProperty( + datasetProps, "dataLocation", schema.getConsentGroups().get(0).getDataLocation().value()); + assertContainsDatasetProperty( + datasetProps, + "numberOfParticipants", schema.getConsentGroups().get(0).getNumberOfParticipants()); - assertContainsDatasetProperty(datasetProps, "fileTypes", PropertyType.coerceToJson( - GsonUtil.getInstance().toJson(schema.getConsentGroups().get(0).getFileTypes()))); - assertContainsDatasetProperty(datasetProps, "url", - schema.getConsentGroups().get(0).getUrl().toString()); - assertContainsDatasetProperty(datasetProps, "accessManagement", + assertContainsDatasetProperty( + datasetProps, + "fileTypes", + PropertyType.coerceToJson( + GsonUtil.getInstance().toJson(schema.getConsentGroups().get(0).getFileTypes()))); + assertContainsDatasetProperty( + datasetProps, "url", schema.getConsentGroups().get(0).getUrl().toString()); + assertContainsDatasetProperty( + datasetProps, + "accessManagement", schema.getConsentGroups().get(0).getAccessManagement().value()); - } - // inserts only required fields to ensure that null fields are ok @Test void testInsertMinimumDatasetRegistration() throws Exception { @@ -255,8 +299,8 @@ void testInsertMinimumDatasetRegistration() throws Exception { datasetRegistrationService.createDatasetsFromRegistration(schema, user, Map.of()); - verify(datasetServiceDAO).insertDatasetRegistration(studyInsert.capture(), - datasetInsertCaptor.capture()); + verify(datasetServiceDAO) + .insertDatasetRegistration(studyInsert.capture(), datasetInsertCaptor.capture()); verify(gcsService, times(0)).storeDocument(any(), any(), any()); @@ -265,8 +309,7 @@ void testInsertMinimumDatasetRegistration() throws Exception { assertEquals(1, inserts.size()); - assertEquals(schema.getConsentGroups().get(0).getConsentGroupName(), - inserts.get(0).name()); + assertEquals(schema.getConsentGroups().get(0).getConsentGroupName(), inserts.get(0).name()); ConsentGroup consentGroup = schema.getConsentGroups().get(0); DataUse dataUse = inserts.get(0).dataUse(); @@ -277,8 +320,7 @@ void testInsertMinimumDatasetRegistration() throws Exception { assertEquals(schema.getPiName(), capturedStudyInsert.piName()); assertEquals(schema.getStudyDescription(), capturedStudyInsert.description()); assertEquals(schema.getDataTypes(), capturedStudyInsert.dataTypes()); - assertEquals(schema.getPublicVisibility(), - capturedStudyInsert.publicVisibility()); + assertEquals(schema.getPublicVisibility(), capturedStudyInsert.publicVisibility()); assertEquals(user.getUserId(), capturedStudyInsert.userId()); assertEquals(user.getUserId(), inserts.get(0).userId()); @@ -289,10 +331,15 @@ void testInsertMinimumDatasetRegistration() throws Exception { List studyProps = capturedStudyInsert.props(); assertContainsStudyProperty(studyProps, "phenotypeIndication", schema.getPhenotypeIndication()); assertContainsStudyProperty(studyProps, "species", schema.getSpecies()); - assertContainsDatasetProperty(datasetProps, "numberOfParticipants", + assertContainsDatasetProperty( + datasetProps, + "numberOfParticipants", schema.getConsentGroups().get(0).getNumberOfParticipants()); - assertContainsDatasetProperty(datasetProps, "fileTypes", PropertyType.coerceToJson( - GsonUtil.getInstance().toJson(schema.getConsentGroups().get(0).getFileTypes()))); + assertContainsDatasetProperty( + datasetProps, + "fileTypes", + PropertyType.coerceToJson( + GsonUtil.getInstance().toJson(schema.getConsentGroups().get(0).getFileTypes()))); } @Test @@ -368,19 +415,23 @@ void testSendDatasetSubmittedEmailsNoDAC() throws Exception { @Test void testCreatedDatasetsFromUpdatedStudy() { Study study = mock(); - Set allDatasets = Stream.of(1, 2, 3, 4, 5).map((i) -> { - Dataset dataset = new Dataset(); - dataset.setDatasetId(i); - return dataset; - }).collect(Collectors.toSet()); - List updatedDatasets = Stream.of(3, 4) - .map((i) -> new DatasetUpdate(i, "update", 1, 1, null, null)).toList(); + Set allDatasets = + Stream.of(1, 2, 3, 4, 5) + .map( + (i) -> { + Dataset dataset = new Dataset(); + dataset.setDatasetId(i); + return dataset; + }) + .collect(Collectors.toSet()); + List updatedDatasets = + Stream.of(3, 4).map((i) -> new DatasetUpdate(i, "update", 1, 1, null, null)).toList(); initService(); when(study.getDatasets()).thenReturn(allDatasets); - List datasets = datasetRegistrationService.createdDatasetsFromUpdatedStudy(study, - updatedDatasets); + List datasets = + datasetRegistrationService.createdDatasetsFromUpdatedStudy(study, updatedDatasets); assertEquals(3, datasets.size()); @@ -396,8 +447,8 @@ void testCreatedDatasetsFromUpdatedStudyNoDatasets() { List updatedDatasets = null; initService(); when(study.getDatasets()).thenReturn(null); - List datasets = datasetRegistrationService.createdDatasetsFromUpdatedStudy(study, - updatedDatasets); + List datasets = + datasetRegistrationService.createdDatasetsFromUpdatedStudy(study, updatedDatasets); assertTrue(datasets.isEmpty()); } @@ -410,8 +461,8 @@ void testInsertAccessManagement() throws Exception { datasetRegistrationService.createDatasetsFromRegistration(schema, user, Map.of()); - verify(datasetServiceDAO).insertDatasetRegistration(studyInsert.capture(), - datasetInsertCaptor.capture()); + verify(datasetServiceDAO) + .insertDatasetRegistration(studyInsert.capture(), datasetInsertCaptor.capture()); verify(gcsService, times(0)).storeDocument(any(), any(), any()); List inserts = datasetInsertCaptor.getValue(); @@ -421,17 +472,14 @@ void testInsertAccessManagement() throws Exception { verify(dacDAO, never()).findById(any()); } - // test inset multiple consent groups @Test void testInsertMultipleDatasetRegistration() throws Exception { User user = mock(); DatasetRegistrationSchemaV1 schema = createRandomMultipleDatasetRegistration(user); - FormDataContentDisposition content = FormDataContentDisposition - .name("file") - .fileName("sharing_plan.txt") - .build(); + FormDataContentDisposition content = + FormDataContentDisposition.name("file").fileName("sharing_plan.txt").build(); InputStream is = new ByteArrayInputStream("HelloWorld".getBytes(StandardCharsets.UTF_8)); FormDataBodyPart bodyPart = mock(); @@ -442,16 +490,21 @@ void testInsertMultipleDatasetRegistration() throws Exception { initService(); when(dacDAO.findById(any())).thenReturn(new Dac()); - Map files = Map.of("alternativeDataSharingPlan", - bodyPart, "consentGroups[0].nihInstitutionalCertificationFile", - bodyPart, "otherUnused", bodyPart); - when(gcsService.storeDocument(any(), any(), any())).thenReturn(BlobId.of("asdf", "hjkl"), - BlobId.of("qwer", "tyuio")); + Map files = + Map.of( + "alternativeDataSharingPlan", + bodyPart, + "consentGroups[0].nihInstitutionalCertificationFile", + bodyPart, + "otherUnused", + bodyPart); + when(gcsService.storeDocument(any(), any(), any())) + .thenReturn(BlobId.of("asdf", "hjkl"), BlobId.of("qwer", "tyuio")); datasetRegistrationService.createDatasetsFromRegistration(schema, user, files); - verify(datasetServiceDAO).insertDatasetRegistration(studyInsert.capture(), - datasetInsertCaptor.capture()); + verify(datasetServiceDAO) + .insertDatasetRegistration(studyInsert.capture(), datasetInsertCaptor.capture()); // only two files are stored; extra "unused" file not used verify(gcsService, times(2)).storeDocument(any(), any(), any()); @@ -463,8 +516,7 @@ void testInsertMultipleDatasetRegistration() throws Exception { // check first dataset insert is ok - assertEquals(schema.getConsentGroups().get(0).getConsentGroupName(), - inserts.get(0).name()); + assertEquals(schema.getConsentGroups().get(0).getConsentGroupName(), inserts.get(0).name()); ConsentGroup consentGroup = schema.getConsentGroups().get(0); DataUse dataUse = inserts.get(0).dataUse(); @@ -477,8 +529,7 @@ void testInsertMultipleDatasetRegistration() throws Exception { assertEquals(schema.getPiName(), capturedStudyInsert.piName()); assertEquals(schema.getStudyDescription(), capturedStudyInsert.description()); assertEquals(schema.getDataTypes(), capturedStudyInsert.dataTypes()); - assertEquals(schema.getPublicVisibility(), - capturedStudyInsert.publicVisibility()); + assertEquals(schema.getPublicVisibility(), capturedStudyInsert.publicVisibility()); assertEquals(user.getUserId(), capturedStudyInsert.userId()); assertEquals(1, inserts.get(0).files().size()); @@ -489,17 +540,19 @@ void testInsertMultipleDatasetRegistration() throws Exception { assertContainsStudyProperty(studyProps, "species", schema.getSpecies()); List props = inserts.get(0).props(); - assertContainsDatasetProperty(props, "fileTypes", PropertyType.coerceToJson( - GsonUtil.getInstance().toJson(schema.getConsentGroups().get(0).getFileTypes()))); - assertContainsDatasetProperty(props, "accessManagement", - schema.getConsentGroups().get(0).getAccessManagement().value()); - assertContainsDatasetProperty(props, "numberOfParticipants", - schema.getConsentGroups().get(0).getNumberOfParticipants()); + assertContainsDatasetProperty( + props, + "fileTypes", + PropertyType.coerceToJson( + GsonUtil.getInstance().toJson(schema.getConsentGroups().get(0).getFileTypes()))); + assertContainsDatasetProperty( + props, "accessManagement", schema.getConsentGroups().get(0).getAccessManagement().value()); + assertContainsDatasetProperty( + props, "numberOfParticipants", schema.getConsentGroups().get(0).getNumberOfParticipants()); // assert on all the same properties, but for the second dataset - assertEquals(schema.getConsentGroups().get(1).getConsentGroupName(), - inserts.get(1).name()); + assertEquals(schema.getConsentGroups().get(1).getConsentGroupName(), inserts.get(1).name()); ConsentGroup consentGroup2 = schema.getConsentGroups().get(1); DataUse dataUse2 = inserts.get(1).dataUse(); @@ -511,14 +564,15 @@ void testInsertMultipleDatasetRegistration() throws Exception { assertEquals(0, inserts.get(1).files().size()); List props2 = inserts.get(1).props(); - assertContainsDatasetProperty(props2, "fileTypes", PropertyType.coerceToJson( - GsonUtil.getInstance().toJson(schema.getConsentGroups().get(1).getFileTypes()))); - assertContainsDatasetProperty(props2, "accessManagement", - schema.getConsentGroups().get(1).getAccessManagement().value()); - assertContainsDatasetProperty(props2, "numberOfParticipants", - schema.getConsentGroups().get(1).getNumberOfParticipants()); - - + assertContainsDatasetProperty( + props2, + "fileTypes", + PropertyType.coerceToJson( + GsonUtil.getInstance().toJson(schema.getConsentGroups().get(1).getFileTypes()))); + assertContainsDatasetProperty( + props2, "accessManagement", schema.getConsentGroups().get(1).getAccessManagement().value()); + assertContainsDatasetProperty( + props2, "numberOfParticipants", schema.getConsentGroups().get(1).getNumberOfParticipants()); } @Test @@ -530,9 +584,11 @@ void testRegistrationErrorsOnInvalidDacId() throws Exception { when(dacDAO.findById(any())).thenReturn(null); initService(); - assertThrows(NotFoundException.class, () -> { - datasetRegistrationService.createDatasetsFromRegistration(schema, user, Map.of()); - }); + assertThrows( + NotFoundException.class, + () -> { + datasetRegistrationService.createDatasetsFromRegistration(schema, user, Map.of()); + }); } @Test @@ -540,12 +596,14 @@ void testRegistrationSucceedsWithESError() throws Exception { User user = mock(); DatasetRegistrationSchemaV1 schema = createRandomMinimumDatasetRegistration(user); when(dacDAO.findById(any())).thenReturn(new Dac()); - when(elasticSearchService.indexDatasets(any(), any())).thenThrow( - new ServerErrorException("Timeout connecting to [elasticsearch]", 500)); + when(elasticSearchService.indexDatasets(any(), any())) + .thenThrow(new ServerErrorException("Timeout connecting to [elasticsearch]", 500)); initService(); - assertDoesNotThrow(() -> { - datasetRegistrationService.createDatasetsFromRegistration(schema, user, Map.of()); - }, "Registration Error"); + assertDoesNotThrow( + () -> { + datasetRegistrationService.createDatasetsFromRegistration(schema, user, Map.of()); + }, + "Registration Error"); } @Test @@ -557,25 +615,25 @@ void testUpdateDatasetSucceedsWithESError() { dataset.setDatasetId(RandomUtils.nextInt(1, 100)); dataset.setDacId(dac.getDacId()); String name = RandomStringUtils.randomAlphabetic(10); - org.broadinstitute.consent.http.models.DatasetUpdate update = new org.broadinstitute.consent.http.models.DatasetUpdate( - name, - dac.getDacId(), - List.of()); + org.broadinstitute.consent.http.models.DatasetUpdate update = + new org.broadinstitute.consent.http.models.DatasetUpdate(name, dac.getDacId(), List.of()); when(datasetDAO.findDatasetById(any())).thenReturn(dataset); initService(); - assertDoesNotThrow(() -> { - datasetRegistrationService.updateDataset(dataset.getDatasetId(), user, update, Map.of()); - }, "Update Error"); + assertDoesNotThrow( + () -> { + datasetRegistrationService.updateDataset(dataset.getDatasetId(), user, update, Map.of()); + }, + "Update Error"); } @Test void testExtractStudyProperty() { - DatasetRegistrationService.StudyPropertyExtractor extractor = new DatasetRegistrationService.StudyPropertyExtractor( - RandomStringUtils.randomAlphabetic(10), - PropertyType.String, - DatasetRegistrationSchemaV1::getStudyName - ); + DatasetRegistrationService.StudyPropertyExtractor extractor = + new DatasetRegistrationService.StudyPropertyExtractor( + RandomStringUtils.randomAlphabetic(10), + PropertyType.String, + DatasetRegistrationSchemaV1::getStudyName); DatasetRegistrationSchemaV1 schemaV1 = new DatasetRegistrationSchemaV1(); @@ -596,12 +654,12 @@ void testExtractStudyProperty() { @Test void testExtractDatasetProperty() { - DatasetRegistrationService.DatasetPropertyExtractor extractor = new DatasetRegistrationService.DatasetPropertyExtractor( - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), - PropertyType.String, - ConsentGroup::getConsentGroupName - ); + DatasetRegistrationService.DatasetPropertyExtractor extractor = + new DatasetRegistrationService.DatasetPropertyExtractor( + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + PropertyType.String, + ConsentGroup::getConsentGroupName); ConsentGroup group = new ConsentGroup(); @@ -621,14 +679,13 @@ void testExtractDatasetProperty() { assertEquals(extractor.type(), prop.get().getPropertyType()); } - @Test void testExtractStudyPropertyTyped() { - DatasetRegistrationService.StudyPropertyExtractor extractor = new DatasetRegistrationService.StudyPropertyExtractor( - RandomStringUtils.randomAlphabetic(10), - PropertyType.Json, - (registration) -> GsonUtil.getInstance().toJson(registration.getDataTypes()) - ); + DatasetRegistrationService.StudyPropertyExtractor extractor = + new DatasetRegistrationService.StudyPropertyExtractor( + RandomStringUtils.randomAlphabetic(10), + PropertyType.Json, + (registration) -> GsonUtil.getInstance().toJson(registration.getDataTypes())); DatasetRegistrationSchemaV1 schemaV1 = new DatasetRegistrationSchemaV1(); @@ -638,20 +695,19 @@ void testExtractStudyPropertyTyped() { assertTrue(prop.isPresent()); - assertEquals(GsonUtil.getInstance().toJsonTree(schemaV1.getDataTypes()), - prop.get().getValue()); + assertEquals(GsonUtil.getInstance().toJsonTree(schemaV1.getDataTypes()), prop.get().getValue()); assertEquals(extractor.key(), prop.get().getKey()); assertEquals(extractor.type(), prop.get().getType()); } @Test void testExtractDatasetPropertyTyped() { - DatasetRegistrationService.DatasetPropertyExtractor extractor = new DatasetRegistrationService.DatasetPropertyExtractor( - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), - PropertyType.Json, - (consentGroup) -> GsonUtil.getInstance().toJson(consentGroup.getDiseaseSpecificUse()) - ); + DatasetRegistrationService.DatasetPropertyExtractor extractor = + new DatasetRegistrationService.DatasetPropertyExtractor( + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + PropertyType.Json, + (consentGroup) -> GsonUtil.getInstance().toJson(consentGroup.getDiseaseSpecificUse())); ConsentGroup group = new ConsentGroup(); @@ -661,7 +717,8 @@ void testExtractDatasetPropertyTyped() { assertTrue(prop.isPresent()); - assertEquals(GsonUtil.getInstance().toJsonTree(group.getDiseaseSpecificUse()), + assertEquals( + GsonUtil.getInstance().toJsonTree(group.getDiseaseSpecificUse()), prop.get().getPropertyValue()); assertEquals(extractor.name(), prop.get().getPropertyName()); assertEquals(extractor.schemaProp(), prop.get().getSchemaProperty()); @@ -670,8 +727,7 @@ void testExtractDatasetPropertyTyped() { private void assertDataUse(ConsentGroup consentGroup, DataUse dataUse) { assertEquals(consentGroup.getCol(), dataUse.getCollaboratorRequired()); - assertEquals(consentGroup.getDiseaseSpecificUse(), - dataUse.getDiseaseRestrictions()); + assertEquals(consentGroup.getDiseaseSpecificUse(), dataUse.getDiseaseRestrictions()); assertEquals(consentGroup.getIrb(), dataUse.getEthicsApprovalRequired()); assertEquals(consentGroup.getGeneralResearchUse(), dataUse.getGeneralUse()); assertEquals(consentGroup.getGs(), dataUse.getGeographicalRestrictions()); @@ -690,16 +746,16 @@ private void assertDataUse(ConsentGroup consentGroup, DataUse dataUse) { assertEquals(consentGroup.getPub(), dataUse.getPublicationResults()); } - private void assertContainsDatasetProperty(Collection props, String schema, - Object value) { - Optional prop = props.stream() - .filter((p) -> p.getSchemaProperty().equals(schema)).findFirst(); + private void assertContainsDatasetProperty( + Collection props, String schema, Object value) { + Optional prop = + props.stream().filter((p) -> p.getSchemaProperty().equals(schema)).findFirst(); assertTrue(prop.isPresent()); assertEquals(value, prop.get().getPropertyValue()); } - private void assertContainsStudyProperty(Collection props, String key, - Object value) { + private void assertContainsStudyProperty( + Collection props, String key, Object value) { Optional prop = props.stream().filter((p) -> p.getKey().equals(key)).findFirst(); assertTrue(prop.isPresent()); assertEquals(value, prop.get().getValue()); @@ -798,7 +854,6 @@ private DatasetRegistrationSchemaV1 createRandomMultipleDatasetRegistration(User return schemaV1; } - private DatasetRegistrationSchemaV1 createRandomCompleteDatasetRegistration(User user) { // TODO: find a better way to initialize this object DatasetRegistrationSchemaV1 schemaV1 = new DatasetRegistrationSchemaV1(); @@ -819,7 +874,8 @@ private DatasetRegistrationSchemaV1 createRandomCompleteDatasetRegistration(User schemaV1.setEmbargoReleaseDate("2007-12-03"); schemaV1.setSequencingCenter(RandomStringUtils.randomAlphabetic(10)); schemaV1.setNihAnvilUse( - DatasetRegistrationSchemaV1.NihAnvilUse.I_AM_NOT_NHGRI_FUNDED_BUT_I_AM_SEEKING_TO_SUBMIT_DATA_TO_AN_VIL); + DatasetRegistrationSchemaV1.NihAnvilUse + .I_AM_NOT_NHGRI_FUNDED_BUT_I_AM_SEEKING_TO_SUBMIT_DATA_TO_AN_VIL); schemaV1.setNihGrantContractNumber(RandomStringUtils.randomAlphabetic(10)); schemaV1.setNihICsSupportingStudy(List.of(NihICsSupportingStudy.CC, NihICsSupportingStudy.CIT)); schemaV1.setNihProgramOfficerName(RandomStringUtils.randomAlphabetic(10)); @@ -833,12 +889,15 @@ private DatasetRegistrationSchemaV1 createRandomCompleteDatasetRegistration(User schemaV1.setControlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation( RandomStringUtils.randomAlphabetic(10)); schemaV1.setAlternativeDataSharingPlan(true); - schemaV1.setAlternativeDataSharingPlanReasons(List.of( - AlternativeDataSharingPlanReason.INFORMED_CONSENT_PROCESSES_ARE_INADEQUATE_TO_SUPPORT_DATA_FOR_SHARING_FOR_THE_FOLLOWING_REASONS)); + schemaV1.setAlternativeDataSharingPlanReasons( + List.of( + AlternativeDataSharingPlanReason + .INFORMED_CONSENT_PROCESSES_ARE_INADEQUATE_TO_SUPPORT_DATA_FOR_SHARING_FOR_THE_FOLLOWING_REASONS)); schemaV1.setAlternativeDataSharingPlanExplanation(RandomStringUtils.randomAlphabetic(10)); schemaV1.setAlternativeDataSharingPlanFileName(RandomStringUtils.randomAlphabetic(10)); schemaV1.setAlternativeDataSharingPlanDataSubmitted( - DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted.WITHIN_3_MONTHS_OF_THE_LAST_DATA_GENERATED_OR_LAST_CLINICAL_VISIT); + DatasetRegistrationSchemaV1.AlternativeDataSharingPlanDataSubmitted + .WITHIN_3_MONTHS_OF_THE_LAST_DATA_GENERATED_OR_LAST_CLINICAL_VISIT); schemaV1.setAlternativeDataSharingPlanDataReleased(true); schemaV1.setAlternativeDataSharingPlanTargetDeliveryDate("2011-11-11"); schemaV1.setAlternativeDataSharingPlanTargetPublicReleaseDate("2012-10-08"); @@ -868,5 +927,4 @@ private DatasetRegistrationSchemaV1 createRandomCompleteDatasetRegistration(User schemaV1.setConsentGroups(List.of(consentGroup)); return schemaV1; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/DatasetServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DatasetServiceTest.java index 8fe9e2ed14..663e473cc1 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DatasetServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DatasetServiceTest.java @@ -829,13 +829,17 @@ void testIsCreatorOrCustodian_Custodian() { @Test void testIsAuthorizedToListUsers() { - when(datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetIdAndUserId(anyLong(), anyLong())).thenReturn(new DatasetAuthorizationReader(1, 1, 1, 1, Timestamp.from(Instant.now()))); + when(datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetIdAndUserId( + anyLong(), anyLong())) + .thenReturn(new DatasetAuthorizationReader(1, 1, 1, 1, Timestamp.from(Instant.now()))); assertTrue(datasetService.isAuthorizedToListUsers(1, 1)); } @Test void testIsAuthorizedToListUsersNotFound() { - when(datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetIdAndUserId(anyLong(), anyLong())).thenReturn(null); + when(datasetAuthorizationReaderDAO.findAuthorizedReadersByDatasetIdAndUserId( + anyLong(), anyLong())) + .thenReturn(null); assertFalse(datasetService.isAuthorizedToListUsers(1, 1)); } @@ -843,7 +847,8 @@ void testIsAuthorizedToListUsersNotFound() { void testAddAuthorizedReader() { DatasetAuthorizationReader dauthr = new DatasetAuthorizationReader(1, 1, 1, 1, Timestamp.from(Instant.now())); - when(datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset(anyLong(), anyLong(), anyLong())) + when(datasetAuthorizationReaderDAO.addAuthorizedReaderToDataset( + anyLong(), anyLong(), anyLong())) .thenReturn(dauthr.id()); when(datasetAuthorizationReaderDAO.findAuthorizedReaderByRecordId(anyLong())) .thenReturn(dauthr); diff --git a/src/test/java/org/broadinstitute/consent/http/service/DraftServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/DraftServiceTest.java index 0fab8b060a..b8ee8a0549 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/DraftServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/DraftServiceTest.java @@ -47,14 +47,11 @@ @ExtendWith(MockitoExtension.class) class DraftServiceTest { - @Mock - private DraftDAO draftDAO; + @Mock private DraftDAO draftDAO; - @Mock - private DraftServiceDAO draftServiceDAO; + @Mock private DraftServiceDAO draftServiceDAO; - @Mock - private GCSService gcsService; + @Mock private GCSService gcsService; private DraftService draftService; @@ -80,12 +77,13 @@ void testInsertDraftThrows() throws SQLException { @Test void testInsertDraft() throws SQLException { doNothing().when(draftServiceDAO).insertDraft(draft); - assertDoesNotThrow(()->draftService.insertDraft(draft)); + assertDoesNotThrow(() -> draftService.insertDraft(draft)); } @Test void testGetAuthorizedDraftNotFound() { - doThrow(new NotFoundException("Not Found")).when(draftServiceDAO) + doThrow(new NotFoundException("Not Found")) + .when(draftServiceDAO) .getAuthorizedDraft(any(), any()); assertThrows(NotFoundException.class, () -> draftService.getAuthorizedDraft(null, user)); } @@ -93,10 +91,11 @@ void testGetAuthorizedDraftNotFound() { @Test void testGetAuthorizedDraftsNotAuthorized() { UUID draftId = UUID.randomUUID(); - doThrow(new NotAuthorizedException("Not Authorized")).when(draftServiceDAO) + doThrow(new NotAuthorizedException("Not Authorized")) + .when(draftServiceDAO) .getAuthorizedDraft(draftId, user); - assertThrows(NotAuthorizedException.class, - () -> draftService.getAuthorizedDraft(draftId, user)); + assertThrows( + NotAuthorizedException.class, () -> draftService.getAuthorizedDraft(draftId, user)); } @Test @@ -112,8 +111,8 @@ void testaddAttachments() throws SQLException, RuntimeException { FileStorageObject fileStorageObject = new FileStorageObject(); fileStorageObject.setFileName("test"); when(draftServiceDAO.addAttachments(draft, user, files)).thenReturn(List.of(fileStorageObject)); - assertEquals(fileStorageObject, - draftService.addAttachments(draft, user, files).iterator().next()); + assertEquals( + fileStorageObject, draftService.addAttachments(draft, user, files).iterator().next()); } @Test @@ -124,15 +123,21 @@ void testDeleteAttachment() throws SQLException { @Test void testDeleteAttachmentThrows() throws SQLException { - doThrow(new SQLException("Couldn't delete document")).when(draftServiceDAO) + doThrow(new SQLException("Couldn't delete document")) + .when(draftServiceDAO) .deleteDraftAttachment(any(), any(), anyInt()); assertThrows(SQLException.class, () -> draftService.deleteDraftAttachment(null, null, 1)); } @Test void testFindDraftSummariesForUser() { - DraftSummary draftSummary = new DraftSummary(UUID.randomUUID(), "test", new Date(), new Date(), - DraftType.STUDY_DATASET_SUBMISSION_V1); + DraftSummary draftSummary = + new DraftSummary( + UUID.randomUUID(), + "test", + new Date(), + new Date(), + DraftType.STUDY_DATASET_SUBMISSION_V1); when(draftDAO.findDraftSummariesByUserId(user.getUserId())).thenReturn(List.of(draftSummary)); draftService.findDraftSummariesForUser(user); assertEquals(draftSummary, draftService.findDraftSummariesForUser(user).iterator().next()); @@ -166,10 +171,9 @@ void testStreamingOutput() throws Exception { output.write(byteArrayOutputStream); byteArrayOutputStream.close(); Gson gson = GsonUtil.buildGson(); - StreamingDeserializer streamedData = gson.fromJson(byteArrayOutputStream.toString(), - StreamingDeserializer.class); - assertEquals(draft.getCreateDate().getTime(), - streamedData.meta.getCreateDate().getTime()); + StreamingDeserializer streamedData = + gson.fromJson(byteArrayOutputStream.toString(), StreamingDeserializer.class); + assertEquals(draft.getCreateDate().getTime(), streamedData.meta.getCreateDate().getTime()); assertEquals("{}", streamedData.document.toString()); } @@ -177,9 +181,9 @@ void testStreamingOutput() throws Exception { void testGetDraftFileInputStream() throws IOException { FileStorageObject fileStorageObject = new FileStorageObject(); fileStorageObject.setBlobId(BlobId.of(UUID.randomUUID().toString(), "test")); - when(gcsService.getDocument(fileStorageObject.getBlobId())).thenAnswer( - inputStream -> new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8)) { - }); + when(gcsService.getDocument(fileStorageObject.getBlobId())) + .thenAnswer( + inputStream -> new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8)) {}); InputStream fileContents = draftService.getDraftAttachmentStream(fileStorageObject); assertEquals("{}", new String(fileContents.readAllBytes(), StandardCharsets.UTF_8)); } @@ -194,4 +198,4 @@ public StreamingDeserializer(String document, DraftStudyDataset meta) { this.meta = meta; } } -} \ No newline at end of file +} diff --git a/src/test/java/org/broadinstitute/consent/http/service/ElasticSearchServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/ElasticSearchServiceTest.java index a71dfa372e..5a38b93409 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/ElasticSearchServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/ElasticSearchServiceTest.java @@ -29,9 +29,9 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; @@ -82,45 +82,37 @@ class ElasticSearchServiceTest extends AbstractTestHelper { private ElasticSearchService service; - @Mock - private RestClient esClient; + @Mock private RestClient esClient; - @Mock - private OntologyService ontologyService; + @Mock private OntologyService ontologyService; - @Mock - private ElasticSearchConfiguration esConfig; + @Mock private ElasticSearchConfiguration esConfig; - @Mock - private DacDAO dacDAO; + @Mock private DacDAO dacDAO; - @Mock - private UserDAO userDao; + @Mock private UserDAO userDao; - @Mock - private InstitutionDAO institutionDAO; + @Mock private InstitutionDAO institutionDAO; - @Mock - private DatasetDAO datasetDAO; + @Mock private DatasetDAO datasetDAO; - @Mock - private DatasetServiceDAO datasetServiceDAO; + @Mock private DatasetServiceDAO datasetServiceDAO; - @Mock - private StudyDAO studyDAO; + @Mock private StudyDAO studyDAO; @BeforeEach void initService() { - service = new ElasticSearchService( - esClient, - esConfig, - dacDAO, - userDao, - ontologyService, - institutionDAO, - datasetDAO, - datasetServiceDAO, - studyDAO); + service = + new ElasticSearchService( + esClient, + esConfig, + dacDAO, + userDao, + ontologyService, + institutionDAO, + datasetDAO, + datasetServiceDAO, + studyDAO); } private void mockElasticSearchResponse(String body) throws IOException { @@ -207,8 +199,8 @@ private StudyProperty createStudyProperty(String key, PropertyType type) { return prop; } - private DatasetProperty createDatasetProperty(String schemaProp, PropertyType type, - String propertyName) { + private DatasetProperty createDatasetProperty( + String schemaProp, PropertyType type, String propertyName) { DatasetProperty prop = new DatasetProperty(); prop.setSchemaProperty(schemaProp); prop.setPropertyType(type); @@ -228,13 +220,9 @@ private DataUseSummary createDataUseSummary() { return dataUseSummary; } - /** - * Private container record to consolidate dataset and associated object creation - */ - private record DatasetRecord(User createUser, User updateUser, Dac dac, Dataset dataset, - Study study) { - - } + /** Private container record to consolidate dataset and associated object creation */ + private record DatasetRecord( + User createUser, User updateUser, Dac dac, Dataset dataset, Study study) {} private DatasetRecord createDatasetRecord() { User user = createUser(1, 100); @@ -245,47 +233,47 @@ private DatasetRecord createDatasetRecord() { createStudyProperty("dbGaPPhsID", PropertyType.String), createStudyProperty("phenotypeIndication", PropertyType.String), createStudyProperty("species", PropertyType.String), - createStudyProperty("dataCustodianEmail", PropertyType.Json) - ); + createStudyProperty("dataCustodianEmail", PropertyType.Json)); Dataset dataset = createDataset(user, updateUser, new DataUse(), dac); - dataset.setProperties(Set.of( - createDatasetProperty("accessManagement", PropertyType.Boolean, "accessManagement"), - createDatasetProperty("numberOfParticipants", PropertyType.Number, "# of participants"), - createDatasetProperty("url", PropertyType.String, "url"), - createDatasetProperty("dataLocation", PropertyType.String, "dataLocation") - )); + dataset.setProperties( + Set.of( + createDatasetProperty("accessManagement", PropertyType.Boolean, "accessManagement"), + createDatasetProperty("numberOfParticipants", PropertyType.Number, "# of participants"), + createDatasetProperty("url", PropertyType.String, "url"), + createDatasetProperty("dataLocation", PropertyType.String, "dataLocation"))); dataset.setStudy(study); return new DatasetRecord(user, updateUser, dac, dataset, study); } - @Test void testAsyncESIndexUpdate() { DatasetRecord datasetRecord = createDatasetRecord(); datasetRecord.dataset.setDataUse(new DataUseBuilder().setGeneralUse(true).build()); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); - when(datasetDAO.findDatasetById(datasetRecord.dataset.getDatasetId())).thenReturn(datasetRecord.dataset); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); + when(datasetDAO.findDatasetById(datasetRecord.dataset.getDatasetId())) + .thenReturn(datasetRecord.dataset); ElasticSearchService elasticSearchSpy = spy(service); // Call the async method ... - elasticSearchSpy.asyncDatasetInESIndex(datasetRecord.dataset.getDatasetId(), datasetRecord.createUser, true); + elasticSearchSpy.asyncDatasetInESIndex( + datasetRecord.dataset.getDatasetId(), datasetRecord.createUser, true); // Ensure that the synchronous method was called with the expected parameters - verify(elasticSearchSpy, timeout(1000)).synchronizeDatasetInESIndex(datasetRecord.dataset, datasetRecord.dataset.getCreateUser(), true); + verify(elasticSearchSpy, timeout(1000)) + .synchronizeDatasetInESIndex( + datasetRecord.dataset, datasetRecord.dataset.getCreateUser(), true); } @Test void testToDatasetTerm_UserInfo() { DatasetRecord datasetRecord = createDatasetRecord(); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); - when(userDao.findUserById(datasetRecord.updateUser.getUserId())).thenReturn( - datasetRecord.updateUser); - when( - institutionDAO.findInstitutionById(datasetRecord.createUser.getInstitutionId())).thenReturn( - datasetRecord.createUser.getInstitution()); - when( - institutionDAO.findInstitutionById(datasetRecord.updateUser.getInstitutionId())).thenReturn( - datasetRecord.updateUser.getInstitution()); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.updateUser.getUserId())) + .thenReturn(datasetRecord.updateUser); + when(institutionDAO.findInstitutionById(datasetRecord.createUser.getInstitutionId())) + .thenReturn(datasetRecord.createUser.getInstitution()); + when(institutionDAO.findInstitutionById(datasetRecord.updateUser.getInstitutionId())) + .thenReturn(datasetRecord.updateUser.getInstitution()); when(dacDAO.findById(any())).thenReturn(datasetRecord.dac); DatasetTerm term = service.toDatasetTerm(datasetRecord.dataset); @@ -293,51 +281,61 @@ void testToDatasetTerm_UserInfo() { assertEquals(datasetRecord.createUser.getDisplayName(), term.getCreateUserDisplayName()); assertEquals(datasetRecord.createUser.getUserId(), term.getSubmitter().userId()); assertEquals(datasetRecord.createUser.getDisplayName(), term.getSubmitter().displayName()); - assertEquals(datasetRecord.createUser.getInstitutionId(), - term.getSubmitter().institution().id()); - assertEquals(datasetRecord.createUser.getInstitution().getName(), + assertEquals( + datasetRecord.createUser.getInstitutionId(), term.getSubmitter().institution().id()); + assertEquals( + datasetRecord.createUser.getInstitution().getName(), term.getSubmitter().institution().name()); assertEquals(datasetRecord.updateUser.getUserId(), term.getUpdateUser().userId()); assertEquals(datasetRecord.updateUser.getDisplayName(), term.getUpdateUser().displayName()); - assertEquals(datasetRecord.updateUser.getInstitutionId(), - term.getUpdateUser().institution().id()); - assertEquals(datasetRecord.updateUser.getInstitution().getName(), + assertEquals( + datasetRecord.updateUser.getInstitutionId(), term.getUpdateUser().institution().id()); + assertEquals( + datasetRecord.updateUser.getInstitution().getName(), term.getUpdateUser().institution().name()); } @Test void testToDatasetTerm_StudyInfo() { DatasetRecord datasetRecord = createDatasetRecord(); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); - when(userDao.findUserById(datasetRecord.updateUser.getUserId())).thenReturn( - datasetRecord.updateUser); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.updateUser.getUserId())) + .thenReturn(datasetRecord.updateUser); when(dacDAO.findById(any())).thenReturn(datasetRecord.dac); DatasetTerm term = service.toDatasetTerm(datasetRecord.dataset); assertEquals(datasetRecord.study.getDescription(), term.getStudy().getDescription()); assertEquals(datasetRecord.study.getName(), term.getStudy().getStudyName()); assertEquals(datasetRecord.study.getStudyId(), term.getStudy().getStudyId()); - Optional phsIdProp = datasetRecord.study.getProperties().stream() - .filter(p -> p.getKey().equals("dbGaPPhsID")).findFirst(); + Optional phsIdProp = + datasetRecord.study.getProperties().stream() + .filter(p -> p.getKey().equals("dbGaPPhsID")) + .findFirst(); assertTrue(phsIdProp.isPresent()); assertEquals(phsIdProp.get().getValue().toString(), term.getStudy().getPhsId()); - Optional phenoProp = datasetRecord.study.getProperties().stream() - .filter(p -> p.getKey().equals("phenotypeIndication")).findFirst(); + Optional phenoProp = + datasetRecord.study.getProperties().stream() + .filter(p -> p.getKey().equals("phenotypeIndication")) + .findFirst(); assertTrue(phenoProp.isPresent()); assertEquals(phenoProp.get().getValue().toString(), term.getStudy().getPhenotype()); - Optional speciesProp = datasetRecord.study.getProperties().stream() - .filter(p -> p.getKey().equals("species")).findFirst(); + Optional speciesProp = + datasetRecord.study.getProperties().stream() + .filter(p -> p.getKey().equals("species")) + .findFirst(); assertTrue(speciesProp.isPresent()); assertEquals(speciesProp.get().getValue().toString(), term.getStudy().getSpecies()); assertEquals(datasetRecord.study.getPiName(), term.getStudy().getPiName()); assertEquals(datasetRecord.study.getCreateUserEmail(), term.getStudy().getDataSubmitterEmail()); assertEquals(datasetRecord.study.getCreateUserId(), term.getStudy().getDataSubmitterId()); - Optional custodianProp = datasetRecord.study.getProperties().stream() - .filter(p -> p.getKey().equals("dataCustodianEmail")).findFirst(); + Optional custodianProp = + datasetRecord.study.getProperties().stream() + .filter(p -> p.getKey().equals("dataCustodianEmail")) + .findFirst(); assertTrue(custodianProp.isPresent()); - String termCustodians = GsonUtil.getInstance() - .toJson(term.getStudy().getDataCustodianEmail(), ArrayList.class); + String termCustodians = + GsonUtil.getInstance().toJson(term.getStudy().getDataCustodianEmail(), ArrayList.class); assertEquals(custodianProp.get().getValue().toString(), termCustodians); assertEquals(datasetRecord.study.getPublicVisibility(), term.getStudy().getPublicVisibility()); assertEquals(datasetRecord.study.getDataTypes(), term.getStudy().getDataTypes()); @@ -354,15 +352,15 @@ void testToDatasetTerm_StudyAssets() { assetsProp.setType(PropertyType.Json); assetsProp.setValue(GsonUtil.getInstance().fromJson(assetsJson, Object.class)); datasetRecord.study.addProperty(assetsProp); - - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); - when(userDao.findUserById(datasetRecord.updateUser.getUserId())).thenReturn( - datasetRecord.updateUser); + + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.updateUser.getUserId())) + .thenReturn(datasetRecord.updateUser); when(dacDAO.findById(any())).thenReturn(datasetRecord.dac); DatasetTerm term = service.toDatasetTerm(datasetRecord.dataset); - + assertEquals(assetsMap, term.getStudy().getAssets()); } @@ -374,10 +372,10 @@ void testToDatasetTerm_DatasetInfo() { dar2.setUserId(2); DataUseSummary dataUseSummary = createDataUseSummary(); DatasetRecord datasetRecord = createDatasetRecord(); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); - when(userDao.findUserById(datasetRecord.updateUser.getUserId())).thenReturn( - datasetRecord.updateUser); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.updateUser.getUserId())) + .thenReturn(datasetRecord.updateUser); LibraryCard card1 = new LibraryCard(); card1.setUserId(dar1.getUserId()); LibraryCard card2 = new LibraryCard(); @@ -392,34 +390,42 @@ void testToDatasetTerm_DatasetInfo() { assertEquals(datasetRecord.dataset.getName(), term.getDatasetName()); assertEquals(datasetRecord.dataset.getDatasetName(), term.getDatasetName()); - Optional countProp = datasetRecord.dataset.getProperties().stream() - .filter(p -> p.getSchemaProperty().equals("numberOfParticipants")).findFirst(); + Optional countProp = + datasetRecord.dataset.getProperties().stream() + .filter(p -> p.getSchemaProperty().equals("numberOfParticipants")) + .findFirst(); assertTrue(countProp.isPresent()); - assertEquals(Integer.valueOf(countProp.get().getPropertyValue().toString()), - term.getParticipantCount()); + assertEquals( + Integer.valueOf(countProp.get().getPropertyValue().toString()), term.getParticipantCount()); assertEquals(dataUseSummary, term.getDataUse()); - Optional locationProp = datasetRecord.dataset.getProperties().stream() - .filter(p -> p.getSchemaProperty().equals("dataLocation")).findFirst(); + Optional locationProp = + datasetRecord.dataset.getProperties().stream() + .filter(p -> p.getSchemaProperty().equals("dataLocation")) + .findFirst(); assertTrue(locationProp.isPresent()); assertEquals(locationProp.get().getPropertyValue().toString(), term.getDataLocation()); - Optional urlProp = datasetRecord.dataset.getProperties().stream() - .filter(p -> p.getSchemaProperty().equals("url")).findFirst(); + Optional urlProp = + datasetRecord.dataset.getProperties().stream() + .filter(p -> p.getSchemaProperty().equals("url")) + .findFirst(); assertTrue(urlProp.isPresent()); assertEquals(urlProp.get().getPropertyValue().toString(), term.getUrl()); assertEquals(datasetRecord.dataset.getDacApproval(), term.getDacApproval()); - Optional accessManagementProp = datasetRecord.dataset.getProperties().stream() - .filter(p -> p.getSchemaProperty().equals("accessManagement")).findFirst(); + Optional accessManagementProp = + datasetRecord.dataset.getProperties().stream() + .filter(p -> p.getSchemaProperty().equals("accessManagement")) + .findFirst(); assertTrue(accessManagementProp.isPresent()); - assertEquals(accessManagementProp.get().getPropertyValue().toString(), - term.getAccessManagement()); + assertEquals( + accessManagementProp.get().getPropertyValue().toString(), term.getAccessManagement()); } @Test void testToDatasetTerm_DacInfo() { DatasetRecord datasetRecord = createDatasetRecord(); when(dacDAO.findById(any())).thenReturn(datasetRecord.dac); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); DatasetTerm term = service.toDatasetTerm(datasetRecord.dataset); assertEquals(datasetRecord.dataset.getDacApproval(), term.getDacApproval()); @@ -432,19 +438,20 @@ void testToDatasetTerm_DacInfo() { void testToDatasetTerm_NIHInstitutionalCertification() { DatasetRecord datasetRecord = createDatasetRecord(); when(dacDAO.findById(any())).thenReturn(datasetRecord.dac); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); DatasetTerm term = service.toDatasetTerm(datasetRecord.dataset); - assertEquals(datasetRecord.dataset.getNihInstitutionalCertificationFile() != null, term.getHasInstitutionCertification()); + assertEquals( + datasetRecord.dataset.getNihInstitutionalCertificationFile() != null, + term.getHasInstitutionCertification()); } - @Test void testToDatasetTerm_Missing_NIHInstitutionalCertification() { DatasetRecord datasetRecord = createDatasetRecord(); when(dacDAO.findById(any())).thenReturn(datasetRecord.dac); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); datasetRecord.dataset.setNihInstitutionalCertificationFile(null); DatasetTerm term = service.toDatasetTerm(datasetRecord.dataset); assertEquals(null, term.getHasInstitutionCertification()); @@ -459,20 +466,19 @@ void testToDatasetTerm_StringNumberOfParticipants() { study.addProperties( createStudyProperty("phenotypeIndication", PropertyType.String), createStudyProperty("species", PropertyType.String), - createStudyProperty("dataCustodianEmail", PropertyType.Json) - ); + createStudyProperty("dataCustodianEmail", PropertyType.Json)); Dataset dataset = createDataset(user, updateUser, new DataUse(), dac); - dataset.setProperties(Set.of( - createDatasetProperty("numberOfParticipants", PropertyType.String, "# of participants"), - createDatasetProperty("url", PropertyType.String, "url") - )); + dataset.setProperties( + Set.of( + createDatasetProperty("numberOfParticipants", PropertyType.String, "# of participants"), + createDatasetProperty("url", PropertyType.String, "url"))); dataset.setStudy(study); DatasetRecord datasetRecord = new DatasetRecord(user, updateUser, dac, dataset, study); when(dacDAO.findById(any())).thenReturn(dac); when(userDao.findUserById(user.getUserId())).thenReturn(user); when(dacDAO.findById(any())).thenReturn(datasetRecord.dac); - when(userDao.findUserById(datasetRecord.createUser.getUserId())).thenReturn( - datasetRecord.createUser); + when(userDao.findUserById(datasetRecord.createUser.getUserId())) + .thenReturn(datasetRecord.createUser); assertDoesNotThrow(() -> service.toDatasetTerm(dataset)); } @@ -507,8 +513,7 @@ void testToDatasetTermNullStudyProps() { assertDoesNotThrow(() -> service.toDatasetTerm(dataset)); } - @Captor - ArgumentCaptor request; + @Captor ArgumentCaptor request; @Test void testIndexDatasetTerms() throws IOException { @@ -527,15 +532,16 @@ void testIndexDatasetTerms() throws IOException { verify(esClient).performRequest(request.capture()); Request capturedRequest = request.getValue(); assertEquals("PUT", capturedRequest.getMethod()); - assertEquals(""" + assertEquals( + """ { "index": {"_type": "dataset", "_id": "1"} } {"datasetId":1} { "index": {"_type": "dataset", "_id": "2"} } {"datasetId":2} - + """, - new String(capturedRequest.getEntity().getContent().readAllBytes(), - StandardCharsets.UTF_8)); + new String( + capturedRequest.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8)); } } @@ -543,8 +549,12 @@ void testIndexDatasetTerms() throws IOException { void testIndexDatasets() throws Exception { DatasetRecord datasetRecord = createDatasetRecord(); Dataset dataset1 = datasetRecord.dataset; - Dataset dataset2 = createDataset(datasetRecord.createUser, datasetRecord.updateUser, - new DataUseBuilder().setGeneralUse(true).build(), datasetRecord.dac); + Dataset dataset2 = + createDataset( + datasetRecord.createUser, + datasetRecord.updateUser, + new DataUseBuilder().setGeneralUse(true).build(), + datasetRecord.dac); dataset2.setStudy(datasetRecord.study); when(datasetDAO.findDatasetById(dataset1.getDatasetId())).thenReturn(dataset1); when(datasetDAO.findDatasetById(dataset2.getDatasetId())).thenReturn(dataset2); @@ -557,9 +567,9 @@ void testIndexDatasets() throws Exception { when(mockResponse.getStatusLine()).thenReturn(statusLine); when(statusLine.getStatusCode()).thenReturn(200); - try (var ignored = service.indexDatasets( - List.of(dataset1.getDatasetId(), dataset2.getDatasetId()), - datasetRecord.createUser)) { + try (var ignored = + service.indexDatasets( + List.of(dataset1.getDatasetId(), dataset2.getDatasetId()), datasetRecord.createUser)) { // Each dataset should be looked up once when defining the term and a second time // when updating the indexed date. verify(datasetDAO, times(2)).findDatasetById(dataset1.getDatasetId()); @@ -586,12 +596,13 @@ void testSearchDatasets() throws IOException { } @ParameterizedTest - @ValueSource(strings = { - "{ \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", - "{ \"from\": 0, \"size\": 100, \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", - "{ \"sort\": [\"datasetIdentifier\"], \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", - "{ \"from\": 0, \"size\": 100, \"sort\": [\"datasetIdentifier\"], \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", - }) + @ValueSource( + strings = { + "{ \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", + "{ \"from\": 0, \"size\": 100, \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", + "{ \"sort\": [\"datasetIdentifier\"], \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", + "{ \"from\": 0, \"size\": 100, \"sort\": [\"datasetIdentifier\"], \"query\": { \"query_string\": { \"query\": \"(GRU) AND (HMB)\" } } }", + }) void testValidateQuerySuccess(String query) throws IOException { mockElasticSearchResponse("{\"valid\":true}"); assertTrue(service.validateQuery(query)); @@ -626,7 +637,8 @@ void testIndexDatasetIds() throws Exception { Gson gson = GsonUtil.buildGson(); Dataset dataset = new Dataset(); dataset.setDatasetId(randomInt(10, 100)); - String esResponseBody = """ + String esResponseBody = + """ { "took": 2, "errors": false, @@ -657,19 +669,14 @@ void testIndexDatasetIds() throws Exception { var baos = new ByteArrayOutputStream(); output.write(baos); var entityString = baos.toString(); - Type listOfEsResponses = new TypeToken>() { - }.getType(); + Type listOfEsResponses = new TypeToken>() {}.getType(); List responseList = gson.fromJson(entityString, listOfEsResponses); assertEquals(1, responseList.size()); JsonArray items = responseList.get(0).getAsJsonArray("items"); assertEquals(1, items.size()); assertEquals( dataset.getDatasetId(), - items.get(0) - .getAsJsonObject() - .getAsJsonObject("index") - .get("_id") - .getAsInt()); + items.get(0).getAsJsonObject().getAsJsonObject("index").get("_id").getAsInt()); } @Test @@ -704,7 +711,6 @@ private void mockESClientResponse(int status, String body) throws Exception { when(esClient.performRequest(any())).thenReturn(esClientResponse); } - @Test void testIndexStudyWithDatasets() { User user = new User(); @@ -727,11 +733,12 @@ void testIndexStudyWithNoDatasets() { study.setStudyId(1); when(studyDAO.findStudyById(any())).thenReturn(study); - assertDoesNotThrow(() -> { - try (var response = service.indexStudy(1, user)) { - assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); - } - }); + assertDoesNotThrow( + () -> { + try (var response = service.indexStudy(1, user)) { + assertEquals(HttpStatusCodes.STATUS_CODE_NOT_FOUND, response.getStatus()); + } + }); } @Test @@ -836,5 +843,4 @@ void testInvalidResultWindow_ExtraFieldsInQuery() { String query = "{\"size\": 100, \"from\": 50, \"query\": {\"match_all\": {}}}"; assertFalse(service.invalidResultWindow(query)); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/ElectionServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/ElectionServiceTest.java index d2fc166591..6cdbeaf57b 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/ElectionServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/ElectionServiceTest.java @@ -19,8 +19,7 @@ class ElectionServiceTest { private ElectionService service; - @Mock - private ElectionDAO electionDAO; + @Mock private ElectionDAO electionDAO; private void initService() { service = new ElectionService(electionDAO); @@ -47,5 +46,4 @@ void findElectionsWithCardHoldingUsersByElectionIds() { assertNotNull(elections); assertEquals(1, elections.size()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/EmailServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/EmailServiceTest.java index 43616a4371..d6a01a01e7 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/EmailServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/EmailServiceTest.java @@ -45,8 +45,8 @@ /** * This class can be used to functionally test email notifications as well as unit test. To enable * functional tests, configure MailService with correct values (i.e. is active, sendgrid key, etc.) - * Functional test emails will be directed to the private google group: - * duos-dev + * Functional test emails will be directed to the private google group: duos-dev */ @ExtendWith(MockitoExtension.class) class EmailServiceTest extends AbstractTestHelper { @@ -54,14 +54,10 @@ class EmailServiceTest extends AbstractTestHelper { private static final String SERVER_URL = "http://localhost:8000/#/"; private static final String FROM = "from@duos"; private EmailService service; - @Mock - private UserDAO userDAO; - @Mock - private MailMessageDAO emailDAO; - @Mock - private SendGridAPI sendGridAPI; - @Mock - private FreeMarkerTemplateHelper templateHelper; + @Mock private UserDAO userDAO; + @Mock private MailMessageDAO emailDAO; + @Mock private SendGridAPI sendGridAPI; + @Mock private FreeMarkerTemplateHelper templateHelper; @BeforeEach void initService() { @@ -71,12 +67,7 @@ void initService() { ServicesConfiguration servicesConfiguration = config.getServicesConfiguration(); servicesConfiguration.setLocalURL(SERVER_URL); - service = new EmailService( - userDAO, - emailDAO, - sendGridAPI, - templateHelper, - config); + service = new EmailService(userDAO, emailDAO, sendGridAPI, templateHelper, config); } @Test @@ -90,27 +81,28 @@ void sendMessage() throws Exception { Integer userId = 1234; Integer voteId = 4567; when(templateHelper.getTemplate(EmailType.COLLECT.templateName)).thenReturn(mock()); - var message = new org.broadinstitute.consent.http.mail.message.MailMessage(user, EmailType.COLLECT) { - @Override - public String createSubject() { - return subject; - } - - @Override - public Object createModel(String serverUrl) { - return model; - } - - @Override - public String getEntityReferenceId() { - return entityReferenceId; - } - - @Override - public Integer getVoteId() { - return voteId; - } - }; + var message = + new org.broadinstitute.consent.http.mail.message.MailMessage(user, EmailType.COLLECT) { + @Override + public String createSubject() { + return subject; + } + + @Override + public Object createModel(String serverUrl) { + return model; + } + + @Override + public String getEntityReferenceId() { + return entityReferenceId; + } + + @Override + public Integer getVoteId() { + return voteId; + } + }; Template template = mock(); when(templateHelper.getTemplate(EmailType.COLLECT.templateName)).thenReturn(template); Response response = new Response(); @@ -172,17 +164,17 @@ void testSendNewResearcherEmail() throws Exception { service.sendNewResearcherMessage(user, so); verify(sendGridAPI).sendMessage(any(), any()); - verify(emailDAO).insert( - eq("1234"), - eq(null), - eq(1234), - eq(EmailType.NEW_RESEARCHER.getTypeInt()), - any(), - any(), - any(), - any(), - any() - ); + verify(emailDAO) + .insert( + eq("1234"), + eq(null), + eq(1234), + eq(EmailType.NEW_RESEARCHER.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -198,17 +190,19 @@ void sendDarExpiredMessage() throws Exception { service.sendDarExpiredMessage(user, darCode, otherUserId, referenceId); verify(sendGridAPI).sendMessage(any(), eq(user.getEmail())); - verify(emailDAO).insert( - eq(referenceId), - isNull(), - eq(otherUserId), - eq(EmailType.DAR_EXPIRED.getTypeInt()), - any(), - any(), - any(), - any(), - any()); + verify(emailDAO) + .insert( + eq(referenceId), + isNull(), + eq(otherUserId), + eq(EmailType.DAR_EXPIRED.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } + @Test void sendDarExpirationReminderMessage() throws Exception { User user = new User(); @@ -218,21 +212,22 @@ void sendDarExpirationReminderMessage() throws Exception { String darCode = "DAR-12345"; String referenceId = UUID.randomUUID().toString(); Integer otherUserId = 456; - when(templateHelper.getTemplate(EmailType.DAR_EXPIRATION_REMINDER.templateName)).thenReturn( - mock()); + when(templateHelper.getTemplate(EmailType.DAR_EXPIRATION_REMINDER.templateName)) + .thenReturn(mock()); service.sendDarExpirationReminderMessage(user, darCode, otherUserId, referenceId); verify(sendGridAPI).sendMessage(any(), eq(user.getEmail())); - verify(emailDAO).insert( - eq(referenceId), - isNull(), - eq(otherUserId), - eq(EmailType.DAR_EXPIRATION_REMINDER.getTypeInt()), - any(), - any(), - any(), - any(), - any()); + verify(emailDAO) + .insert( + eq(referenceId), + isNull(), + eq(otherUserId), + eq(EmailType.DAR_EXPIRATION_REMINDER.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -254,17 +249,17 @@ void testSendDatasetSubmittedMessage() throws Exception { service.sendDatasetSubmittedMessage(dacChair, dataSubmitter, dacName, datasetName); verify(sendGridAPI).sendMessage(any(), any()); - verify(emailDAO).insert( - eq(datasetName), - eq(null), - eq(456), - eq(EmailType.NEW_DATASET.getTypeInt()), - any(), - any(), - any(), - any(), - any() - ); + verify(emailDAO) + .insert( + eq(datasetName), + eq(null), + eq(456), + eq(EmailType.NEW_DATASET.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -284,17 +279,17 @@ void testSendDaaRequestMessage() throws Exception { service.sendDaaRequestMessage(signingOfficial, user, daaName, daaId); verify(sendGridAPI).sendMessage(any(), any()); - verify(emailDAO).insert( - eq("456"), - eq(null), - eq(user.getUserId()), - eq(EmailType.NEW_DAA_REQUEST.getTypeInt()), - any(), - any(), - any(), - any(), - any() - ); + verify(emailDAO) + .insert( + eq("456"), + eq(null), + eq(user.getUserId()), + eq(EmailType.NEW_DAA_REQUEST.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -313,24 +308,24 @@ void testSendNewDAAUploadResearcherMessage() throws Exception { String previousDaaName = "DAA-123"; String newDaaName = "DAA-456"; - when(templateHelper.getTemplate(EmailType.NEW_DAA_UPLOAD_RESEARCHER.templateName)).thenReturn( - mock()); + when(templateHelper.getTemplate(EmailType.NEW_DAA_UPLOAD_RESEARCHER.templateName)) + .thenReturn(mock()); service.sendNewDAAUploadResearcherMessage( researcher, dac.getName(), previousDaaName, newDaaName, user.getUserId()); verify(sendGridAPI).sendMessage(any(), any()); - verify(emailDAO).insert( - eq("DAC-01"), - eq(null), - eq(user.getUserId()), - eq(EmailType.NEW_DAA_UPLOAD_RESEARCHER.getTypeInt()), - any(), - any(), - any(), - any(), - any() - ); + verify(emailDAO) + .insert( + eq("DAC-01"), + eq(null), + eq(user.getUserId()), + eq(EmailType.NEW_DAA_UPLOAD_RESEARCHER.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -351,21 +346,21 @@ void testSendNewDAAUploadSOMessage() throws Exception { String newDaaName = "DAA-456"; when(templateHelper.getTemplate(EmailType.NEW_DAA_UPLOAD_SO.templateName)).thenReturn(mock()); - service.sendNewDAAUploadSOMessage(signingOfficial, - dac.getName(), previousDaaName, newDaaName, user.getUserId()); + service.sendNewDAAUploadSOMessage( + signingOfficial, dac.getName(), previousDaaName, newDaaName, user.getUserId()); verify(sendGridAPI).sendMessage(any(), any()); - verify(emailDAO).insert( - eq("DAC-01"), - eq(null), - eq(user.getUserId()), - eq(EmailType.NEW_DAA_UPLOAD_SO.getTypeInt()), - any(), - any(), - any(), - any(), - any() - ); + verify(emailDAO) + .insert( + eq("DAC-01"), + eq(null), + eq(user.getUserId()), + eq(EmailType.NEW_DAA_UPLOAD_SO.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -376,30 +371,29 @@ void testSendResearcherCloseoutCompletedMessage() throws Exception { user.setEmail("jd@somewhere"); String darCode = "DAR-12345"; String referenceId = UUID.randomUUID().toString(); - when(templateHelper.getTemplate( - EmailType.RESEARCHER_CLOSEOUT_COMPLETED.templateName)).thenReturn( - mock()); + when(templateHelper.getTemplate(EmailType.RESEARCHER_CLOSEOUT_COMPLETED.templateName)) + .thenReturn(mock()); service.sendResearcherCloseoutCompletedMessage(user, darCode, referenceId); verify(sendGridAPI).sendMessage(any(), eq(user.getEmail())); - verify(emailDAO).insert( - eq(referenceId), - isNull(), - eq(user.getUserId()), - eq(EmailType.RESEARCHER_CLOSEOUT_COMPLETED.getTypeInt()), - any(), - any(), - any(), - any(), - any()); + verify(emailDAO) + .insert( + eq(referenceId), + isNull(), + eq(user.getUserId()), + eq(EmailType.RESEARCHER_CLOSEOUT_COMPLETED.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test void testFetchEmails() { List mailMessages = generateMailMessageList(); when(emailDAO.fetchMessagesByType(any(), anyInt(), anyInt())).thenReturn(mailMessages); - assertEquals(2, - service.fetchEmailMessagesByType(EmailType.COLLECT, 20, 0).size()); + assertEquals(2, service.fetchEmailMessagesByType(EmailType.COLLECT, 20, 0).size()); } @Test @@ -407,10 +401,9 @@ void testFetchEmailsByCreateDate() { List mailMessages = generateMailMessageList(); Date startDate = new Date(); Date endDate = new Date(); - when(emailDAO.fetchMessagesByCreateDate(any(), any(), anyInt(), anyInt())).thenReturn( - mailMessages); - assertEquals(2, - service.fetchEmailMessagesByCreateDate(startDate, endDate, 20, 0).size()); + when(emailDAO.fetchMessagesByCreateDate(any(), any(), anyInt(), anyInt())) + .thenReturn(mailMessages); + assertEquals(2, service.fetchEmailMessagesByCreateDate(startDate, endDate, 20, 0).size()); } @Test @@ -426,17 +419,17 @@ void testSendSubmittedCloseoutMessage() throws Exception { service.sendSubmittedCloseoutMessage(toUser, darId, referenceId, closeoutUrl); verify(sendGridAPI).sendMessage(any(Mail.class), eq(toUser.getEmail())); - verify(emailDAO).insert( - eq(referenceId), - eq(null), - eq(toUser.getUserId()), - eq(EmailType.SUBMITTED_CLOSEOUT.getTypeInt()), - any(), - any(), - any(), - any(), - any() - ); + verify(emailDAO) + .insert( + eq(referenceId), + eq(null), + eq(toUser.getUserId()), + eq(EmailType.SUBMITTED_CLOSEOUT.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -444,21 +437,22 @@ void testSendNewLibraryCardIssuedMessage() throws Exception { User toUser = new User(); toUser.setDisplayName("Test User"); toUser.setEmail("test.user@test.com"); - when(templateHelper.getTemplate(EmailType.NEW_LIBRARY_CARD_ISSUED.templateName)).thenReturn(mock()); + when(templateHelper.getTemplate(EmailType.NEW_LIBRARY_CARD_ISSUED.templateName)) + .thenReturn(mock()); service.sendNewLibraryCardIssuedMessage(toUser); verify(sendGridAPI).sendMessage(any(Mail.class), eq(toUser.getEmail())); - verify(emailDAO).insert( - eq(toUser.getEmail()), - eq(null), - eq(toUser.getUserId()), - eq(EmailType.NEW_LIBRARY_CARD_ISSUED.getTypeInt()), - any(), - any(), - any(), - any(), - any() - ); + verify(emailDAO) + .insert( + eq(toUser.getEmail()), + eq(null), + eq(toUser.getUserId()), + eq(EmailType.NEW_LIBRARY_CARD_ISSUED.getTypeInt()), + any(), + any(), + any(), + any(), + any()); } @Test @@ -508,8 +502,6 @@ private MailMessage generateMailMessage() { randomAlphanumeric(10), randomAlphanumeric(10), randomInt(31, 40), - new Date() - ); + new Date()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/FileStorageObjectServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/FileStorageObjectServiceTest.java index 2a621a299f..977814fa37 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/FileStorageObjectServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/FileStorageObjectServiceTest.java @@ -28,11 +28,9 @@ @ExtendWith(MockitoExtension.class) class FileStorageObjectServiceTest { - @Mock - private FileStorageObjectDAO fileStorageObjectDAO; + @Mock private FileStorageObjectDAO fileStorageObjectDAO; - @Mock - private GCSService gcsService; + @Mock private GCSService gcsService; private FileStorageObjectService service; @@ -45,8 +43,8 @@ void testUploadAndStoreFile() throws IOException { InputStream content = new ByteArrayInputStream(RandomStringUtils.random(20).getBytes()); String fileName = RandomStringUtils.randomAlphabetic(10); String mediaType = RandomStringUtils.randomAlphabetic(10); - FileCategory category = List.of(FileCategory.values()) - .get(new Random().nextInt(FileCategory.values().length)); + FileCategory category = + List.of(FileCategory.values()).get(new Random().nextInt(FileCategory.values().length)); String entityId = RandomStringUtils.randomAlphabetic(10); Integer createUserId = new Random().nextInt(); @@ -54,44 +52,40 @@ void testUploadAndStoreFile() throws IOException { String blob = RandomStringUtils.randomAlphabetic(10); when(fileStorageObjectDAO.insertNewFile( - eq(fileName), - eq(category.getValue()), - eq(BlobId.of(bucket, blob).toGsUtilUri()), - eq(mediaType), - eq(entityId), - eq(createUserId), - any())).thenReturn(10); + eq(fileName), + eq(category.getValue()), + eq(BlobId.of(bucket, blob).toGsUtilUri()), + eq(mediaType), + eq(entityId), + eq(createUserId), + any())) + .thenReturn(10); FileStorageObject newFileStorageObject = new FileStorageObject(); newFileStorageObject.setFileName(RandomStringUtils.randomAlphabetic(10)); when(fileStorageObjectDAO.findFileById(10)).thenReturn(newFileStorageObject); - when( - gcsService.storeDocument(eq(content), eq(mediaType), any()) - ).thenReturn(BlobId.of(bucket, blob)); + when(gcsService.storeDocument(eq(content), eq(mediaType), any())) + .thenReturn(BlobId.of(bucket, blob)); initService(); - FileStorageObject returned = service.uploadAndStoreFile(content, fileName, mediaType, category, - entityId, createUserId); + FileStorageObject returned = + service.uploadAndStoreFile(content, fileName, mediaType, category, entityId, createUserId); assertEquals(newFileStorageObject, returned); - verify( - gcsService, times(1) - ).storeDocument(eq(content), eq(mediaType), any()); - - verify( - fileStorageObjectDAO, times(1) - ).insertNewFile( - eq(fileName), - eq(category.getValue()), - eq(BlobId.of(bucket, blob).toGsUtilUri()), - eq(mediaType), - eq(entityId), - eq(createUserId), - any()); - + verify(gcsService, times(1)).storeDocument(eq(content), eq(mediaType), any()); + + verify(fileStorageObjectDAO, times(1)) + .insertNewFile( + eq(fileName), + eq(category.getValue()), + eq(BlobId.of(bucket, blob).toGsUtilUri()), + eq(mediaType), + eq(entityId), + eq(createUserId), + any()); } @Test @@ -104,13 +98,10 @@ void testFetchById() throws IOException { String content = RandomStringUtils.random(100); - when( - gcsService.getDocument(BlobId.of(bucket, blob)) - ).thenReturn(new ByteArrayInputStream(content.getBytes())); + when(gcsService.getDocument(BlobId.of(bucket, blob))) + .thenReturn(new ByteArrayInputStream(content.getBytes())); - when( - fileStorageObjectDAO.findFileById(10) - ).thenReturn(file); + when(fileStorageObjectDAO.findFileById(10)).thenReturn(file); initService(); @@ -143,19 +134,17 @@ void testFetchAllByEntityId() throws IOException { String content2 = RandomStringUtils.randomAlphabetic(10); String content3 = RandomStringUtils.randomAlphabetic(10); - when( - gcsService.getDocuments(List.of(file1.getBlobId(), file2.getBlobId(), file3.getBlobId())) - ).thenReturn(Map.of( - file1.getBlobId(), new ByteArrayInputStream(content1.getBytes()), - file2.getBlobId(), new ByteArrayInputStream(content2.getBytes()), - file3.getBlobId(), new ByteArrayInputStream(content3.getBytes()) - )); + when(gcsService.getDocuments(List.of(file1.getBlobId(), file2.getBlobId(), file3.getBlobId()))) + .thenReturn( + Map.of( + file1.getBlobId(), new ByteArrayInputStream(content1.getBytes()), + file2.getBlobId(), new ByteArrayInputStream(content2.getBytes()), + file3.getBlobId(), new ByteArrayInputStream(content3.getBytes()))); String entityId = RandomStringUtils.randomAlphabetic(10); - when( - fileStorageObjectDAO.findFilesByEntityId(entityId) - ).thenReturn(List.of(file1, file2, file3)); + when(fileStorageObjectDAO.findFilesByEntityId(entityId)) + .thenReturn(List.of(file1, file2, file3)); initService(); @@ -167,12 +156,9 @@ void testFetchAllByEntityId() throws IOException { assertEquals(file2, returned.get(1)); assertEquals(file3, returned.get(2)); - assertArrayEquals(content1.getBytes(), - returned.get(0).getUploadedFile().readAllBytes()); - assertArrayEquals(content2.getBytes(), - returned.get(1).getUploadedFile().readAllBytes()); - assertArrayEquals(content3.getBytes(), - returned.get(2).getUploadedFile().readAllBytes()); + assertArrayEquals(content1.getBytes(), returned.get(0).getUploadedFile().readAllBytes()); + assertArrayEquals(content2.getBytes(), returned.get(1).getUploadedFile().readAllBytes()); + assertArrayEquals(content3.getBytes(), returned.get(2).getUploadedFile().readAllBytes()); } @Test @@ -197,21 +183,19 @@ void testFetchAllByEntityIdAndCategory() throws IOException { String content2 = RandomStringUtils.randomAlphabetic(10); String content3 = RandomStringUtils.randomAlphabetic(10); - when( - gcsService.getDocuments(List.of(file1.getBlobId(), file2.getBlobId(), file3.getBlobId())) - ).thenReturn(Map.of( - file1.getBlobId(), new ByteArrayInputStream(content1.getBytes()), - file2.getBlobId(), new ByteArrayInputStream(content2.getBytes()), - file3.getBlobId(), new ByteArrayInputStream(content3.getBytes()) - )); + when(gcsService.getDocuments(List.of(file1.getBlobId(), file2.getBlobId(), file3.getBlobId()))) + .thenReturn( + Map.of( + file1.getBlobId(), new ByteArrayInputStream(content1.getBytes()), + file2.getBlobId(), new ByteArrayInputStream(content2.getBytes()), + file3.getBlobId(), new ByteArrayInputStream(content3.getBytes()))); String entityId = RandomStringUtils.randomAlphabetic(10); - FileCategory category = List.of(FileCategory.values()) - .get(new Random().nextInt(FileCategory.values().length)); + FileCategory category = + List.of(FileCategory.values()).get(new Random().nextInt(FileCategory.values().length)); - when( - fileStorageObjectDAO.findFilesByEntityIdAndCategory(entityId, category.getValue()) - ).thenReturn(List.of(file1, file2, file3)); + when(fileStorageObjectDAO.findFilesByEntityIdAndCategory(entityId, category.getValue())) + .thenReturn(List.of(file1, file2, file3)); initService(); @@ -223,12 +207,8 @@ void testFetchAllByEntityIdAndCategory() throws IOException { assertEquals(file2, returned.get(1)); assertEquals(file3, returned.get(2)); - assertArrayEquals(content1.getBytes(), - returned.get(0).getUploadedFile().readAllBytes()); - assertArrayEquals(content2.getBytes(), - returned.get(1).getUploadedFile().readAllBytes()); - assertArrayEquals(content3.getBytes(), - returned.get(2).getUploadedFile().readAllBytes()); + assertArrayEquals(content1.getBytes(), returned.get(0).getUploadedFile().readAllBytes()); + assertArrayEquals(content2.getBytes(), returned.get(1).getUploadedFile().readAllBytes()); + assertArrayEquals(content3.getBytes(), returned.get(2).getUploadedFile().readAllBytes()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/InstitutionServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/InstitutionServiceTest.java index 9c6512f43a..2e860f35f4 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/InstitutionServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/InstitutionServiceTest.java @@ -36,14 +36,11 @@ class InstitutionServiceTest extends AbstractTestHelper { private InstitutionService service; - @Mock - private InstitutionDAO institutionDAO; + @Mock private InstitutionDAO institutionDAO; - @Mock - private UserDAO userDAO; + @Mock private UserDAO userDAO; - @Mock - InstitutionAndLibraryCardEnforcement institutionAndLibraryCardEnforcement; + @Mock InstitutionAndLibraryCardEnforcement institutionAndLibraryCardEnforcement; @BeforeEach void setUp() { @@ -62,28 +59,28 @@ void testCreateInstitutionSuccess() throws Exception { when(institutionDAO.insertFullInstitution(mockInstitution, 1)).thenReturn(mockInstitution); Institution institution = service.createInstitution(mockInstitution, 1); assertNotNull(institution); - verify( - institutionAndLibraryCardEnforcement).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + verify(institutionAndLibraryCardEnforcement) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test void testCreateInstitutionBlankName() { Institution mockInstitution = initMockModel(); mockInstitution.setName(""); - assertThrows(IllegalArgumentException.class, - () -> service.createInstitution(mockInstitution, 1)); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + assertThrows( + IllegalArgumentException.class, () -> service.createInstitution(mockInstitution, 1)); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test void testCreateInstitutionNullName() { Institution mockInstitution = initMockModel(); mockInstitution.setName(null); - assertThrows(IllegalArgumentException.class, - () -> service.createInstitution(mockInstitution, 1)); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + assertThrows( + IllegalArgumentException.class, () -> service.createInstitution(mockInstitution, 1)); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -93,22 +90,22 @@ void testUpdateInstitutionById() throws Exception { when(institutionDAO.findInstitutionById(mockInstitution.getId())).thenReturn(mockInstitution); when(institutionDAO.updateFullInstitution(mockInstitution, 1)).thenReturn(mockInstitution); mockInstitution.setUpdateDate(new Date()); - //doNothing is default for void methods, no need to mock InstitutionDAO.updateInstitutionById - Institution updatedInstitution = service.updateInstitutionById(mockInstitution, - mockInstitution.getId(), 1); + // doNothing is default for void methods, no need to mock InstitutionDAO.updateInstitutionById + Institution updatedInstitution = + service.updateInstitutionById(mockInstitution, mockInstitution.getId(), 1); assertNotNull(updatedInstitution); - verify( - institutionAndLibraryCardEnforcement).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + verify(institutionAndLibraryCardEnforcement) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test void testUpdateInstitutionByIdNotFound() { Institution mockInstitution = initMockModel(); when(institutionDAO.findInstitutionById(anyInt())).thenThrow(new NotFoundException()); - assertThrows(NotFoundException.class, - () -> service.updateInstitutionById(mockInstitution, 1, 1)); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + assertThrows( + NotFoundException.class, () -> service.updateInstitutionById(mockInstitution, 1, 1)); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -116,10 +113,10 @@ void testUpdateInstitutionBlankNameFail() { Institution mockInstitution = initMockModel(); mockInstitution.setName(""); when(institutionDAO.findInstitutionById(anyInt())).thenReturn(mockInstitution); - assertThrows(IllegalArgumentException.class, - () -> service.updateInstitutionById(mockInstitution, 1, 1)); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + assertThrows( + IllegalArgumentException.class, () -> service.updateInstitutionById(mockInstitution, 1, 1)); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -127,10 +124,10 @@ void testUpdateInstitutionNullNameFail() { Institution mockInstitution = initMockModel(); when(institutionDAO.findInstitutionById(anyInt())).thenReturn(mockInstitution); mockInstitution.setName(null); - assertThrows(IllegalArgumentException.class, - () -> service.updateInstitutionById(mockInstitution, 1, 1)); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + assertThrows( + IllegalArgumentException.class, () -> service.updateInstitutionById(mockInstitution, 1, 1)); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -148,8 +145,8 @@ void testDeleteInstitutionById() { void testDeleteInstitutionByIdFail() { when(institutionDAO.findInstitutionById(anyInt())).thenThrow(new NotFoundException()); assertThrows(NotFoundException.class, () -> service.deleteInstitutionById(1)); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -199,11 +196,12 @@ void testCreateInstitutionDomainUniquenessAllUnique() { when(institutionDAO.findInstitutionIdByDomain("broadinstitute.org")).thenReturn(null); when(institutionDAO.findInstitutionIdByDomain("broad.mit.edu")).thenReturn(null); when(institutionDAO.findInstitutionIdByDomain("café.com")).thenReturn(null); - assertDoesNotThrow(() -> { - service.createInstitution(mockInstitution, 1); - }); - verify( - institutionAndLibraryCardEnforcement).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + assertDoesNotThrow( + () -> { + service.createInstitution(mockInstitution, 1); + }); + verify(institutionAndLibraryCardEnforcement) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -212,12 +210,13 @@ void testCreateInstitutionDomainUniquenessSomeUnique() { mockInstitution.setDomains(List.of("broadinstitute.org", "broad.mit.edu")); when(institutionDAO.findInstitutionIdByDomain("broadinstitute.org")).thenReturn(2); when(institutionDAO.findInstitutionIdByDomain("broad.mit.edu")).thenReturn(null); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, - () -> service.createInstitution(mockInstitution, 1)); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, () -> service.createInstitution(mockInstitution, 1)); assertTrue(exception.getMessage().contains("broadinstitute.org")); assertFalse(exception.getMessage().contains("broad.mit.edu")); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -226,12 +225,13 @@ void testCreateInstitutionDomainUniquenessNoneUnique() { mockInstitution.setDomains(List.of("broadinstitute.org", "broad.mit.edu")); when(institutionDAO.findInstitutionIdByDomain("broadinstitute.org")).thenReturn(2); when(institutionDAO.findInstitutionIdByDomain("broad.mit.edu")).thenReturn(2); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, - () -> service.createInstitution(mockInstitution, 1)); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, () -> service.createInstitution(mockInstitution, 1)); assertTrue(exception.getMessage().contains("broadinstitute.org")); assertTrue(exception.getMessage().contains("broad.mit.edu")); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -243,11 +243,12 @@ void testCheckDomainUniquenessUpdateSameInstitution() throws Exception { when(institutionDAO.findInstitutionIdByDomain("broadinstitute.org")).thenReturn(1); when(institutionDAO.findInstitutionById(1)).thenReturn(mockInstitution); when(institutionDAO.updateFullInstitution(mockInstitution, 1)).thenReturn(mockInstitution); - assertDoesNotThrow(() -> { - service.updateInstitutionById(mockInstitution, 1, 1); - }); - verify( - institutionAndLibraryCardEnforcement).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + assertDoesNotThrow( + () -> { + service.updateInstitutionById(mockInstitution, 1, 1); + }); + verify(institutionAndLibraryCardEnforcement) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -257,25 +258,29 @@ void testCheckDomainUniquenessUpdateDifferentInstitution() { mockInstitution.setDomains(List.of("broadinstitute.org")); when(institutionDAO.findInstitutionIdByDomain("broadinstitute.org")).thenReturn(2); when(institutionDAO.findInstitutionById(1)).thenReturn(mockInstitution); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, - () -> service.updateInstitutionById(mockInstitution, 1, 1)); - assertEquals("Domain(s) already associated with another institution: broadinstitute.org", + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> service.updateInstitutionById(mockInstitution, 1, 1)); + assertEquals( + "Domain(s) already associated with another institution: broadinstitute.org", exception.getMessage()); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test void testCreateInstitutionNameUniqueness() { Institution newInstitution = initMockModel(); newInstitution.setName("Broad Institute"); - when(institutionDAO.findInstitutionsByName("Broad Institute")).thenReturn( - Collections.emptyList()); - assertDoesNotThrow(() -> { - service.createInstitution(newInstitution, 1); - }); - verify( - institutionAndLibraryCardEnforcement).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + when(institutionDAO.findInstitutionsByName("Broad Institute")) + .thenReturn(Collections.emptyList()); + assertDoesNotThrow( + () -> { + service.createInstitution(newInstitution, 1); + }); + verify(institutionAndLibraryCardEnforcement) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -285,14 +290,17 @@ void testCreateInstitutionNameUniquenessConflict() { Institution existingConflictingInstitution = new Institution(); existingConflictingInstitution.setId(2); existingConflictingInstitution.setName("Broad Institute"); - when(institutionDAO.findInstitutionsByName("Broad Institute")).thenReturn( - List.of(existingConflictingInstitution)); - ConsentConflictException exception = assertThrows(ConsentConflictException.class, - () -> service.createInstitution(newInstitution, 1)); - assertTrue(exception.getMessage() - .contains("An institution exists with the name of 'Broad Institute'")); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + when(institutionDAO.findInstitutionsByName("Broad Institute")) + .thenReturn(List.of(existingConflictingInstitution)); + ConsentConflictException exception = + assertThrows( + ConsentConflictException.class, () -> service.createInstitution(newInstitution, 1)); + assertTrue( + exception + .getMessage() + .contains("An institution exists with the name of 'Broad Institute'")); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -301,15 +309,16 @@ void testUpdateInstitutionNameUniqueness() throws Exception { updatedInstitution.setId(1); updatedInstitution.setName("Broad Institute"); when(institutionDAO.findInstitutionById(1)).thenReturn(updatedInstitution); - when(institutionDAO.findInstitutionsByName("Broad Institute")).thenReturn( - Collections.emptyList()); - when(institutionDAO.updateFullInstitution(updatedInstitution, 1)).thenReturn( - updatedInstitution); - assertDoesNotThrow(() -> { - service.updateInstitutionById(updatedInstitution, 1, 1); - }); - verify( - institutionAndLibraryCardEnforcement).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + when(institutionDAO.findInstitutionsByName("Broad Institute")) + .thenReturn(Collections.emptyList()); + when(institutionDAO.updateFullInstitution(updatedInstitution, 1)) + .thenReturn(updatedInstitution); + assertDoesNotThrow( + () -> { + service.updateInstitutionById(updatedInstitution, 1, 1); + }); + verify(institutionAndLibraryCardEnforcement) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -321,14 +330,18 @@ void testUpdateInstitutionNameUniquenessConflict() { existingConflictingInstitution.setId(2); existingConflictingInstitution.setName("Broad Institute"); when(institutionDAO.findInstitutionById(1)).thenReturn(updatedInstitution); - when(institutionDAO.findInstitutionsByName("Broad Institute")).thenReturn( - List.of(existingConflictingInstitution)); - ConsentConflictException exception = assertThrows(ConsentConflictException.class, - () -> service.updateInstitutionById(updatedInstitution, 1, 1)); - assertTrue(exception.getMessage() - .contains("An institution exists with the name of 'Broad Institute'")); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + when(institutionDAO.findInstitutionsByName("Broad Institute")) + .thenReturn(List.of(existingConflictingInstitution)); + ConsentConflictException exception = + assertThrows( + ConsentConflictException.class, + () -> service.updateInstitutionById(updatedInstitution, 1, 1)); + assertTrue( + exception + .getMessage() + .contains("An institution exists with the name of 'Broad Institute'")); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } @Test @@ -336,24 +349,27 @@ void testCreateInstitutionDuplicateDomainsInPayload() { Institution newInstitution = initMockModel(); newInstitution.setName("Broad Institute"); newInstitution.setDomains(List.of("broadinstitute.org", "broadinstitute.org")); - when(institutionDAO.findInstitutionsByName("Broad Institute")).thenReturn( - Collections.emptyList()); - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, - () -> service.createInstitution(newInstitution, 1)); + when(institutionDAO.findInstitutionsByName("Broad Institute")) + .thenReturn(Collections.emptyList()); + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, () -> service.createInstitution(newInstitution, 1)); assertEquals("Institution domains must be unique", exception.getMessage()); - verify(institutionAndLibraryCardEnforcement, - never()).asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); + verify(institutionAndLibraryCardEnforcement, never()) + .asyncEnforceInstitutionAndLibraryCardRulesForAllUsers(); } /** * @return A list of 5 dacs */ private List getInstitutions() { - return IntStream.range(0, 4). - mapToObj(i -> { - Institution institute = new Institution(); - institute.setId(i); - return institute; - }).toList(); + return IntStream.range(0, 4) + .mapToObj( + i -> { + Institution institute = new Institution(); + institute.setId(i); + return institute; + }) + .toList(); } } diff --git a/src/test/java/org/broadinstitute/consent/http/service/LibraryCardServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/LibraryCardServiceTest.java index c2aed0be97..ea689c4136 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/LibraryCardServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/LibraryCardServiceTest.java @@ -12,7 +12,6 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -43,30 +42,29 @@ class LibraryCardServiceTest extends AbstractTestHelper { private LibraryCardService service; - @Mock - private InstitutionDAO institutionDAO; - @Mock - private LibraryCardDAO libraryCardDAO; - @Mock - private InstitutionService institutionService; - @Mock - private UserDAO userDAO; - @Mock - private EmailService emailService; + @Mock private InstitutionDAO institutionDAO; + @Mock private LibraryCardDAO libraryCardDAO; + @Mock private InstitutionService institutionService; + @Mock private UserDAO userDAO; + @Mock private EmailService emailService; @BeforeEach void initService() { - service = new LibraryCardService(libraryCardDAO, institutionDAO, institutionService, userDAO, emailService); + service = + new LibraryCardService( + libraryCardDAO, institutionDAO, institutionService, userDAO, emailService); } @Test - // Test SO LC create with userId and email success case + // Test SO LC create with userId and email success case void testCreateLibraryCardFullUserDetailsAsSOSameInstitution() throws TemplateException, IOException { Institution institution = testInstitution(); User user = testUser(institution.getId()); user.setEmail("testemail"); - User soUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User soUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); soUser.setInstitutionId(institution.getId()); when(userDAO.findUserById(user.getUserId())).thenReturn(user); when(userDAO.findUserByEmail(user.getEmail())).thenReturn(user); @@ -78,27 +76,34 @@ void testCreateLibraryCardFullUserDetailsAsSOSameInstitution() payload.setUserName("username"); payload.setCreateUserId(randomInt(1, 10)); - //last two calls in the function, no need to test within this service test file + // last two calls in the function, no need to test within this service test file LibraryCard createdCard = new LibraryCard(); when(libraryCardDAO.findLibraryCardById(anyInt())).thenReturn(createdCard); assertEquals(createdCard, service.createLibraryCard(payload, soUser)); - verify(libraryCardDAO).insertLibraryCard(eq(user.getUserId()), - eq(payload.getUserName()), eq(user.getEmail()), - eq(payload.getCreateUserId()), any()); + verify(libraryCardDAO) + .insertLibraryCard( + eq(user.getUserId()), + eq(payload.getUserName()), + eq(user.getEmail()), + eq(payload.getCreateUserId()), + any()); } @Test - // Test SO LC create with userId and email but in different institutions + // Test SO LC create with userId and email but in different institutions void testCreateLibraryCardFullUserDetailsAsSODifferentInstitution() { Institution institution = testInstitution(); User user = testUser(institution.getId()); user.setEmail("testemail"); - User soUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User soUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); // Signing officials should not create LCs for users outside their institution. - soUser.setInstitutionId(institution.getId()+1); + soUser.setInstitutionId(institution.getId() + 1); when(userDAO.findUserById(user.getUserId())).thenReturn(user); - when(institutionDAO.findInstitutionById(soUser.getInstitutionId())).thenReturn(new Institution()); + when(institutionDAO.findInstitutionById(soUser.getInstitutionId())) + .thenReturn(new Institution()); when(institutionService.findInstitutionForEmail(user.getEmail())).thenReturn(institution); LibraryCard payload = testLibraryCard(user.getUserId()); @@ -110,41 +115,46 @@ void testCreateLibraryCardFullUserDetailsAsSODifferentInstitution() { } @Test - //Test LC create with only user email (no userId) + // Test LC create with only user email (no userId) void testCreateLibraryCardPartialUserDetailsEmailThrowsBadRequest() { Institution institution = testInstitution(); User user = testUser(institution.getId()); user.setUserId(null); user.setEmail("testemail"); - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); LibraryCard payload = testLibraryCard(user.getUserId()); payload.setUserEmail(user.getEmail()); - assertThrows(BadRequestException.class, () -> - service.createLibraryCard(payload, signingOfficialUser)); + assertThrows( + BadRequestException.class, () -> service.createLibraryCard(payload, signingOfficialUser)); } @Test - //Test LC create with only user id (no email) + // Test LC create with only user id (no email) void testCreateLibraryCardPartialUserDetailsIdThrowsBadRequest() { Institution institution = testInstitution(); User user = testUser(institution.getId()); user.setEmail(null); user.setEmail("testemail"); - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); LibraryCard payload = testLibraryCard(user.getUserId()); - assertThrows(BadRequestException.class, () -> - service.createLibraryCard(payload, signingOfficialUser)); + assertThrows( + BadRequestException.class, () -> service.createLibraryCard(payload, signingOfficialUser)); } @Test void testCreateLibraryCardAsSO() { Institution institution = testInstitution(); - User soUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), - UserRoles.SIGNINGOFFICIAL.getRoleName()); + User soUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); soUser.setInstitutionId(institution.getId()); soUser.setEmail("testemail"); @@ -154,7 +164,8 @@ void testCreateLibraryCardAsSO() { when(libraryCardDAO.findLibraryCardByUserId(anyInt())).thenReturn(null); // last two calls in the function, no need to test within this service test file - when(libraryCardDAO.insertLibraryCard(anyInt(), eq(null), anyString(), eq(null), any())).thenReturn(1); + when(libraryCardDAO.insertLibraryCard(anyInt(), eq(null), anyString(), eq(null), any())) + .thenReturn(1); when(libraryCardDAO.findLibraryCardById(anyInt())).thenReturn(new LibraryCard()); LibraryCard payload = testLibraryCard(soUser.getUserId()); @@ -163,11 +174,14 @@ void testCreateLibraryCardAsSO() { } @Test - //Negative test, checks if error is thrown if payload email and userId don't match up to those on user record + // Negative test, checks if error is thrown if payload email and userId don't match up to those on + // user record void testCreateLibraryCardIncorrectUserIdAndEmail() { Institution institution = testInstitution(); User user = testUser(institution.getId()); - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); user.setUserId(1); user.setEmail("testemail"); @@ -176,28 +190,38 @@ void testCreateLibraryCardIncorrectUserIdAndEmail() { LibraryCard payload = testLibraryCard(user.getUserId()); payload.setUserEmail("differentemail"); - assertThrows(ConsentConflictException.class, () -> service.createLibraryCard(payload, signingOfficialUser)); + assertThrows( + ConsentConflictException.class, + () -> service.createLibraryCard(payload, signingOfficialUser)); } @Test - //Negative test, checks to see if error thrown if card already exists on user id and institution id + // Negative test, checks to see if error thrown if card already exists on user id and institution + // id void testCreateLibraryCardAlreadyExistsOnUserId() { Institution institution = testInstitution(); User user = testUser(institution.getId()); - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); LibraryCard savedCard = testLibraryCard(user.getUserId()); LibraryCard payload = savedCard; when(libraryCardDAO.findLibraryCardByUserId(anyInt())).thenReturn(savedCard); - assertThrows(ConsentConflictException.class, () -> service.createLibraryCard(payload, signingOfficialUser)); + assertThrows( + ConsentConflictException.class, + () -> service.createLibraryCard(payload, signingOfficialUser)); } @Test - // Negative test, checks to see if error thrown if card already exists on user email and institution id + // Negative test, checks to see if error thrown if card already exists on user email and + // institution id void testCreateLibraryCardAlreadyExistsOnUserEmail() { Institution institution = testInstitution(); User user = testUser(institution.getId()); - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); user.setEmail("testemail"); LibraryCard savedCard = testLibraryCard(null); savedCard.setUserEmail(user.getEmail()); @@ -205,43 +229,57 @@ void testCreateLibraryCardAlreadyExistsOnUserEmail() { LibraryCard payload = savedCard; when(libraryCardDAO.findLibraryCardByUserEmail(any())).thenReturn(savedCard); - assertThrows(ConsentConflictException.class, () -> { - service.createLibraryCard(payload, signingOfficialUser); - }); + assertThrows( + ConsentConflictException.class, + () -> { + service.createLibraryCard(payload, signingOfficialUser); + }); } @Test - //Negative test, checks to see if error is thrown if email and userId are not provided + // Negative test, checks to see if error is thrown if email and userId are not provided void testCreateLibraryCardNoUserDetails() { - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); LibraryCard payload = testLibraryCard(null); - assertThrows(BadRequestException.class, () -> { - service.createLibraryCard(payload, signingOfficialUser); - }); + assertThrows( + BadRequestException.class, + () -> { + service.createLibraryCard(payload, signingOfficialUser); + }); } @Test - //Negative test, checks if error is thrown on null institutionId + // Negative test, checks if error is thrown on null institutionId void testCreateLibraryCard_InvalidInstitution() { User user = testUser(1); - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); LibraryCard libraryCard = testLibraryCard(user.getUserId()); - assertThrows(BadRequestException.class, () -> service.createLibraryCard(libraryCard, signingOfficialUser)); + assertThrows( + BadRequestException.class, + () -> service.createLibraryCard(libraryCard, signingOfficialUser)); } @Test - //Negative test, checks to see if error is thrown on null payload + // Negative test, checks to see if error is thrown on null payload void testCreateLibraryCardNullPayload() { - User signingOfficialUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); - assertThrows(NotFoundException.class, () -> service.createLibraryCard(null, signingOfficialUser)); + User signingOfficialUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + assertThrows( + NotFoundException.class, () -> service.createLibraryCard(null, signingOfficialUser)); } @Test void testCreateLibraryCard_InvalidInstitutionId() { - User soUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), - UserRoles.SIGNINGOFFICIAL.getRoleName()); + User soUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); soUser.setInstitutionId(1); LibraryCard card = testLibraryCard(2); assertThrows(BadRequestException.class, () -> service.createLibraryCard(card, soUser)); @@ -249,13 +287,16 @@ void testCreateLibraryCard_InvalidInstitutionId() { @Test void testCreateLibraryCard_InstitutionMismatch() { - User soUser = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), - UserRoles.SIGNINGOFFICIAL.getRoleName()); + User soUser = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); soUser.setInstitutionId(1); LibraryCard card = testLibraryCard(2); - assertThrows(BadRequestException.class, () -> { - service.createLibraryCard(card, soUser); - }); + assertThrows( + BadRequestException.class, + () -> { + service.createLibraryCard(card, soUser); + }); } @Test @@ -270,11 +311,12 @@ void testDeleteLibraryCard_NotFound() { @Test void testFindLibraryCardById_NotFound() { - when(libraryCardDAO.findLibraryCardById(any())) - .thenReturn(null); - assertThrows(NotFoundException.class, () -> { - service.findLibraryCardById(1); - }); + when(libraryCardDAO.findLibraryCardById(any())).thenReturn(null); + assertThrows( + NotFoundException.class, + () -> { + service.findLibraryCardById(1); + }); } @Test @@ -302,8 +344,7 @@ void testFindLibraryCardByIdDaa() { daa2.setDaaId(daaId2); libraryCard.addDaaObject(daa1); libraryCard.addDaaObject(daa2); - when(libraryCardDAO.findLibraryCardDaaById(libraryCard.getId())) - .thenReturn(libraryCard); + when(libraryCardDAO.findLibraryCardDaaById(libraryCard.getId())).thenReturn(libraryCard); LibraryCard result = service.findLibraryCardWithDaasById(libraryCard.getId()); assertNotNull(result); assertEquals(result.getId(), libraryCard.getId()); @@ -331,11 +372,16 @@ void testRemoveDaaFromLibraryCard() { @Test void testAddDaaToUserLibraryCard() { User user = testUser(1); - user.setRoles(List.of(new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()))); - User signingOfficial = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + user.setRoles( + List.of( + new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()))); + User signingOfficial = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); signingOfficial.setInstitutionId(1); Integer userId = user.getUserId(); - when(libraryCardDAO.findLibraryCardByUserId(user.getUserId())).thenReturn(testLibraryCard(userId)); + when(libraryCardDAO.findLibraryCardByUserId(user.getUserId())) + .thenReturn(testLibraryCard(userId)); doNothing().when(libraryCardDAO).createLibraryCardDaaRelation(any(), any()); LibraryCard card = service.addDaaToUserLibraryCard(user, signingOfficial, 1); assertNotNull(card); @@ -344,18 +390,27 @@ void testAddDaaToUserLibraryCard() { @Test void testAddDaaToUserLibraryCardNoMatchingInstitutions() { User user = testUser(1); - user.setRoles(List.of(new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()))); - User signingOfficial = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + user.setRoles( + List.of( + new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()))); + User signingOfficial = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); signingOfficial.setInstitutionId(4); - assertThrows(BadRequestException.class, () -> service.addDaaToUserLibraryCard(user, signingOfficial, 1)); + assertThrows( + BadRequestException.class, () -> service.addDaaToUserLibraryCard(user, signingOfficial, 1)); } @Test void testAddDaaToUserLibraryCardWithNoLibraryCards() { Institution institution = testInstitution(); User user = testUser(institution.getId()); - user.setRoles(List.of(new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()))); - User signingOfficial = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + user.setRoles( + List.of( + new UserRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()))); + User signingOfficial = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); signingOfficial.setInstitutionId(institution.getId()); Integer userId = user.getUserId(); LibraryCard payload = testLibraryCard(user.getUserId()); @@ -368,8 +423,7 @@ void testAddDaaToUserLibraryCardWithNoLibraryCards() { when(institutionDAO.findInstitutionById(institution.getId())).thenReturn(institution); when(institutionService.findInstitutionForEmail(any())).thenReturn(institution); when(userDAO.findUserById(user.getUserId())).thenReturn(user); - when(libraryCardDAO.insertLibraryCard(anyInt(), any(), any(), anyInt(), any())) - .thenReturn(1); + when(libraryCardDAO.insertLibraryCard(anyInt(), any(), any(), anyInt(), any())).thenReturn(1); when(libraryCardDAO.findLibraryCardById(anyInt())).thenReturn(new LibraryCard()); LibraryCard card = service.addDaaToUserLibraryCard(user, signingOfficial, 1); @@ -380,7 +434,8 @@ void testAddDaaToUserLibraryCardWithNoLibraryCards() { void testRemoveDaaFromUserLibraryCards() { User user = testUser(1); Integer userId = user.getUserId(); - when(libraryCardDAO.findLibraryCardByUserId(user.getUserId())).thenReturn(testLibraryCard(userId)); + when(libraryCardDAO.findLibraryCardByUserId(user.getUserId())) + .thenReturn(testLibraryCard(userId)); doNothing().when(libraryCardDAO).deleteLibraryCardDaaRelation(any(), any()); LibraryCard card = service.removeDaaFromUserLibraryCard(user, 1); // The above deletion only affects the lc-daa join table and does not remove library cards @@ -392,7 +447,8 @@ void testRemoveDaaFromUserLibraryCards() { void testRemoveDaaFromUserLibraryCardsNoMatchingInstitutions() { User user = testUser(1); Integer userId = user.getUserId(); - when(libraryCardDAO.findLibraryCardByUserId(user.getUserId())).thenReturn(testLibraryCard(userId)); + when(libraryCardDAO.findLibraryCardByUserId(user.getUserId())) + .thenReturn(testLibraryCard(userId)); LibraryCard card = service.removeDaaFromUserLibraryCard(user, 1); // DAA removal should not delete library cards assertNotNull(card); @@ -402,9 +458,12 @@ void testRemoveDaaFromUserLibraryCardsNoMatchingInstitutions() { @Test void testCreateLibraryCardForSigningOfficial() throws TemplateException, IOException { Institution institution = testInstitution(); - User user = createUserWithRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()); + User user = + createUserWithRole(UserRoles.RESEARCHER.getRoleId(), UserRoles.RESEARCHER.getRoleName()); user.setInstitutionId(institution.getId()); - User signingOfficial = createUserWithRole(UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); + User signingOfficial = + createUserWithRole( + UserRoles.SIGNINGOFFICIAL.getRoleId(), UserRoles.SIGNINGOFFICIAL.getRoleName()); signingOfficial.setInstitutionId(institution.getId()); user.setEmail("testemail"); LibraryCard newLc = new LibraryCard(); @@ -416,8 +475,7 @@ void testCreateLibraryCardForSigningOfficial() throws TemplateException, IOExcep when(institutionService.findInstitutionForEmail(user.getEmail())).thenReturn(institution); when(libraryCardDAO.findLibraryCardByUserId(anyInt())).thenReturn(null); - when(libraryCardDAO.insertLibraryCard(anyInt(), any(), any(), anyInt(), - any())).thenReturn(1); + when(libraryCardDAO.insertLibraryCard(anyInt(), any(), any(), anyInt(), any())).thenReturn(1); when(libraryCardDAO.findLibraryCardById(anyInt())).thenReturn(newLc); LibraryCard card = service.createLibraryCardForSigningOfficial(user, signingOfficial); @@ -431,7 +489,7 @@ void testRemoveDaaFromUserLibraryCardByInstitutionNoLibraryCards() { User user = testUser(1); Integer userId = user.getUserId(); when(libraryCardDAO.findLibraryCardByUserId(userId)).thenReturn(null); - LibraryCard card = service.removeDaaFromUserLibraryCard(user,1); + LibraryCard card = service.removeDaaFromUserLibraryCard(user, 1); assertNull(card); } @@ -465,5 +523,4 @@ private User createUserWithRole(Integer id, String name) { user.addRole(new UserRole(id, name)); return user; } - -} \ No newline at end of file +} diff --git a/src/test/java/org/broadinstitute/consent/http/service/MatchServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/MatchServiceTest.java index c4a193e0f1..19dad24623 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/MatchServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/MatchServiceTest.java @@ -43,37 +43,32 @@ @ExtendWith(MockitoExtension.class) class MatchServiceTest { - @Mock - DatasetDAO datasetDAO; - @Mock - private ServicesConfiguration config; - @Mock - private DataAccessRequestDAO dataAccessRequestDAO; - @Mock - private MatchDAO matchDAO; + @Mock DatasetDAO datasetDAO; + @Mock private ServicesConfiguration config; + @Mock private DataAccessRequestDAO dataAccessRequestDAO; + @Mock private MatchDAO matchDAO; private MatchService service; - @Mock - private Client clientMock; - @Mock - private WebTarget target; - @Mock - private Invocation.Builder builder; - @Mock - private Response response; - @Mock - private UseRestrictionConverter useRestrictionConverter; + @Mock private Client clientMock; + @Mock private WebTarget target; + @Mock private Invocation.Builder builder; + @Mock private Response response; + @Mock private UseRestrictionConverter useRestrictionConverter; private void initService() { - service = new MatchService(clientMock, config, matchDAO, - dataAccessRequestDAO, datasetDAO, - useRestrictionConverter); + service = + new MatchService( + clientMock, + config, + matchDAO, + dataAccessRequestDAO, + datasetDAO, + useRestrictionConverter); } @BeforeAll - public static void setUpClass() { - } + public static void setUpClass() {} @Test void testInsertMatches() { @@ -101,9 +96,11 @@ void testFindMatchByIdNotFound() { when(matchDAO.findMatchById(m.getId())).thenReturn(null); initService(); - assertThrows(NotFoundException.class, () -> { - service.findMatchById(m.getId()); - }); + assertThrows( + NotFoundException.class, + () -> { + service.findMatchById(m.getId()); + }); } @Test @@ -122,18 +119,22 @@ void testFindMatchForDataAccessRequest() { void testSingleEntitiesMatchV3EmptyDataset() { DataAccessRequest dar = new DataAccessRequest(); initService(); - assertThrows(IllegalArgumentException.class, () -> { - service.singleEntitiesMatchV3(null, dar); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + service.singleEntitiesMatchV3(null, dar); + }); } @Test void testSingleEntitiesMatchV3EmptyDar() { Dataset dataset = new Dataset(); initService(); - assertThrows(IllegalArgumentException.class, () -> { - service.singleEntitiesMatchV3(dataset, null); - }); + assertThrows( + IllegalArgumentException.class, + () -> { + service.singleEntitiesMatchV3(dataset, null); + }); } @Test @@ -256,11 +257,11 @@ void testRemoveMatchesForPurpose() { @Test void testFindMatchesForLatestDataAccessElectionsByPurposeIds() { Match m = createMatchObject(); - when(matchDAO.findMatchesForLatestDataAccessElectionsByPurposeIds(anyList())).thenReturn( - List.of(m)); + when(matchDAO.findMatchesForLatestDataAccessElectionsByPurposeIds(anyList())) + .thenReturn(List.of(m)); initService(); - List matches = service.findMatchesForLatestDataAccessElectionsByPurposeIds( - List.of("test")); + List matches = + service.findMatchesForLatestDataAccessElectionsByPurposeIds(List.of("test")); assertEquals(1, matches.size()); assertEquals(m.getId(), matches.get(0).getId()); verify(matchDAO, atLeastOnce()).findMatchesForLatestDataAccessElectionsByPurposeIds(anyList()); @@ -278,7 +279,14 @@ private DataAccessRequest getSampleDataAccessRequest(String referenceId) { } private Match createMatchObject() { - return new Match(1, UUID.randomUUID().toString(), UUID.randomUUID().toString(), true, true, - false, new Date(), MatchAlgorithm.V4.getVersion()); + return new Match( + 1, + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + true, + true, + false, + new Date(), + MatchAlgorithm.V4.getVersion()); } } diff --git a/src/test/java/org/broadinstitute/consent/http/service/MetricsServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/MetricsServiceTest.java index f3a2d5bc87..504987820b 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/MetricsServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/MetricsServiceTest.java @@ -30,17 +30,13 @@ @ExtendWith(MockitoExtension.class) class MetricsServiceTest extends AbstractTestHelper { - @Mock - private DatasetDAO dataSetDAO; + @Mock private DatasetDAO dataSetDAO; - @Mock - private DataAccessRequestDAO darDAO; + @Mock private DataAccessRequestDAO darDAO; - @Mock - private DarCollectionDAO darCollectionDAO; + @Mock private DarCollectionDAO darCollectionDAO; - @Mock - private ElectionDAO electionDAO; + @Mock private ElectionDAO electionDAO; private MetricsService service; @@ -59,8 +55,8 @@ void testGenerateDatasetMetrics() { when(dataSetDAO.findDatasetById(dataset.getDatasetId())).thenReturn(dataset); when(darDAO.findApprovedDARsByDatasetId(any())).thenReturn(List.of(dar)); when(darCollectionDAO.findDARCollectionByCollectionIds(any())).thenReturn(List.of(collection)); - when(electionDAO.findLastElectionsByReferenceIdsAndType(any(), eq("DataAccess"))).thenReturn( - election); + when(electionDAO.findLastElectionsByReferenceIdsAndType(any(), eq("DataAccess"))) + .thenReturn(election); initService(); DatasetMetrics metrics = service.generateDatasetMetrics(1); @@ -76,9 +72,11 @@ void testGenerateDatasetMetricsNotFound() { when(dataSetDAO.findDatasetById(any())).thenReturn(null); initService(); - assertThrows(NotFoundException.class, () -> { - service.generateDatasetMetrics(1); - }); + assertThrows( + NotFoundException.class, + () -> { + service.generateDatasetMetrics(1); + }); } private DataAccessRequest generateDar() { diff --git a/src/test/java/org/broadinstitute/consent/http/service/NihServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/NihServiceTest.java index 9846926745..41519c0255 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/NihServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/NihServiceTest.java @@ -32,14 +32,11 @@ @ExtendWith(MockitoExtension.class) class NihServiceTest extends MockServerTestHelper { - @Mock - private UserDAO userDAO; + @Mock private UserDAO userDAO; - @Mock - private NihServiceDAO nihServiceDAO; + @Mock private NihServiceDAO nihServiceDAO; - @Mock - private DuosUser duosUser; + @Mock private DuosUser duosUser; private NihService service; @@ -49,8 +46,8 @@ void setUp() { servicesConfig.setTimeoutSeconds(1); servicesConfig.setEcmUrl( "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - service = new NihService(userDAO, nihServiceDAO, - new HttpClientUtil(servicesConfig), servicesConfig); + service = + new NihService(userDAO, nihServiceDAO, new HttpClientUtil(servicesConfig), servicesConfig); mockServerClient.reset(); } @@ -59,18 +56,21 @@ void testSyncAccount() throws Exception { User user = new User(); user.setUserId(1); when(duosUser.getUser()).thenReturn(user); - when(userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues())).thenReturn( - user); + when(userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues())) + .thenReturn(user); String timestamp = "2025-08-28T16:54:22.064+00:00"; LinkInfo ecmResponse = new LinkInfo("test", timestamp, true); - NIHUserAccount nihAccount = new NIHUserAccount( - ecmResponse.externalUserId(), - String.valueOf(Instant.parse(timestamp).toEpochMilli()), - ecmResponse.authenticated()); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) - .withBody(GsonUtil.getInstance().toJson(ecmResponse))); + NIHUserAccount nihAccount = + new NIHUserAccount( + ecmResponse.externalUserId(), + String.valueOf(Instant.parse(timestamp).toEpochMilli()), + ecmResponse.authenticated()); + mockServerClient + .when(request()) + .respond( + response() + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .withBody(GsonUtil.getInstance().toJson(ecmResponse))); User syncedUser = service.syncAccount(duosUser); assertEquals(user.getUserId(), syncedUser.getUserId()); verify(nihServiceDAO).updateUserNihStatus(user, nihAccount); @@ -82,10 +82,12 @@ void testSyncAccountBadRequestError() { user.setUserId(1); when(duosUser.getUser()).thenReturn(user); LinkInfo ecmResponse = new LinkInfo("test", "test", true); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .withBody(GsonUtil.getInstance().toJson(ecmResponse))); + mockServerClient + .when(request()) + .respond( + response() + .withStatusCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) + .withBody(GsonUtil.getInstance().toJson(ecmResponse))); assertThrows(BadRequestException.class, () -> service.syncAccount(duosUser)); } @@ -95,10 +97,12 @@ void testSyncAccountServerError() { user.setUserId(1); when(duosUser.getUser()).thenReturn(user); LinkInfo ecmResponse = new LinkInfo("test", "test", true); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .withBody(GsonUtil.getInstance().toJson(ecmResponse))); + mockServerClient + .when(request()) + .respond( + response() + .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) + .withBody(GsonUtil.getInstance().toJson(ecmResponse))); assertThrows(ServerErrorException.class, () -> service.syncAccount(duosUser)); } @@ -107,10 +111,12 @@ void testSyncAccountInvalidECMResponse() { User user = new User(); user.setUserId(1); when(duosUser.getUser()).thenReturn(user); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) - .withBody(GsonUtil.getInstance().toJson("bad response"))); + mockServerClient + .when(request()) + .respond( + response() + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .withBody(GsonUtil.getInstance().toJson("bad response"))); assertThrows(ServerErrorException.class, () -> service.syncAccount(duosUser)); } @@ -119,11 +125,11 @@ void testSyncAccountECMNotFound() throws Exception { User user = new User(); user.setUserId(1); when(duosUser.getUser()).thenReturn(user); - when(userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues())).thenReturn( - user); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND)); + when(userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues())) + .thenReturn(user); + mockServerClient + .when(request()) + .respond(response().withStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND)); User syncedUser = service.syncAccount(duosUser); assertEquals(user.getUserId(), syncedUser.getUserId()); verify(nihServiceDAO).deleteNihAccountById(user.getUserId()); @@ -134,11 +140,11 @@ void testSyncAccountECMNotAuthorized() throws Exception { User user = new User(); user.setUserId(1); when(duosUser.getUser()).thenReturn(user); - when(userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues())).thenReturn( - user); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED)); + when(userDAO.findUserWithPropertiesById(user.getUserId(), UserFields.getValues())) + .thenReturn(user); + mockServerClient + .when(request()) + .respond(response().withStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED)); User syncedUser = service.syncAccount(duosUser); assertEquals(user.getUserId(), syncedUser.getUserId()); verify(nihServiceDAO, never()).deleteNihAccountById(user.getUserId()); diff --git a/src/test/java/org/broadinstitute/consent/http/service/OidcServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/OidcServiceTest.java index c469a94343..99b812cd5c 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/OidcServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/OidcServiceTest.java @@ -18,10 +18,9 @@ class OidcServiceTest { @Mock private OidcAuthorityDAO mockOidcAuthorityDAO; - OidcAuthorityConfiguration testConfig = new OidcAuthorityConfiguration( - "http://example.com", - "http://example.com/authorization", - "http://example.com/token"); + OidcAuthorityConfiguration testConfig = + new OidcAuthorityConfiguration( + "http://example.com", "http://example.com/authorization", "http://example.com/token"); @Test public void testGetAuthorizationURI() throws URISyntaxException { @@ -57,7 +56,14 @@ public void testGetAuthorizationURIAddsClientIdToScope() throws URISyntaxExcepti var parameters = new MultivaluedHashMap(); when(mockOidcAuthorityDAO.getOidcAuthorityConfiguration()).thenReturn(testConfig); var actual = service.getAuthorizationURI(parameters); - assertEquals(new URI(testConfig.authorization_endpoint() + "?" + OidcService.SCOPE_PARAM + "=" + testClientId), actual); + assertEquals( + new URI( + testConfig.authorization_endpoint() + + "?" + + OidcService.SCOPE_PARAM + + "=" + + testClientId), + actual); } @Test @@ -71,7 +77,14 @@ public void testGetAuthorizationURIAddsClientIdToExistingScope() throws URISynta parameters.add(OidcService.SCOPE_PARAM, "foo"); when(mockOidcAuthorityDAO.getOidcAuthorityConfiguration()).thenReturn(testConfig); var actual = service.getAuthorizationURI(parameters); - assertEquals(new URI(testConfig.authorization_endpoint() + "?" + OidcService.SCOPE_PARAM + "=foo+" + testClientId), actual); + assertEquals( + new URI( + testConfig.authorization_endpoint() + + "?" + + OidcService.SCOPE_PARAM + + "=foo+" + + testClientId), + actual); } @Test @@ -96,7 +109,8 @@ public void testTokenExchangeWithClientSecret() { var queryParameters = new MultivaluedHashMap(); var expectedFormParameters = new MultivaluedHashMap<>(formParameters); expectedFormParameters.add(OidcService.CLIENT_SECRET_PARAM, configuration.getClientSecret()); - when(mockOidcAuthorityDAO.oauthTokenPost(expectedFormParameters, queryParameters)).thenReturn("test"); + when(mockOidcAuthorityDAO.oauthTokenPost(expectedFormParameters, queryParameters)) + .thenReturn("test"); var actual = service.tokenExchange(formParameters, queryParameters); assertEquals("test", actual); } diff --git a/src/test/java/org/broadinstitute/consent/http/service/OntologyServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/OntologyServiceTest.java index 14cc3de087..6b5ca1e5d2 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/OntologyServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/OntologyServiceTest.java @@ -26,7 +26,6 @@ class OntologyServiceTest extends MockServerTestHelper { private OntologyService service; - ServicesConfiguration config() { ServicesConfiguration config = new ServicesConfiguration(); config.setLocalURL("http://localhost:8180/"); @@ -44,10 +43,8 @@ void testTranslateDataUseSummary() { mockDataUseTranslateSummarySuccess(); initService(); - DataUse dataUse = new DataUseBuilder() - .setHmbResearch(true) - .setDiseaseRestrictions(List.of("")) - .build(); + DataUse dataUse = + new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(List.of("")).build(); DataUseSummary translation = service.translateDataUseSummary(dataUse); assertNotNull(translation); @@ -73,30 +70,27 @@ void testTranslateDataUseSummary() { assertEquals("OTHER", translation.getSecondary().get(3).getCode()); assertFalse(translation.getSecondary().get(3).getDescription().isEmpty()); - } - @Test void testTranslateDataUse() { mockDataUseTranslateSuccess(); initService(); - DataUse dataUse = new DataUseBuilder() - .setHmbResearch(true) - .setDiseaseRestrictions(List.of("")) - .build(); + DataUse dataUse = + new DataUseBuilder().setHmbResearch(true).setDiseaseRestrictions(List.of("")).build(); String translation = service.translateDataUse(dataUse, DataUseTranslationType.DATASET); - assertEquals(""" + assertEquals( + """ Samples are restricted for use under the following conditions: Data is limited for health/medical/biomedical research. [HMB] Data use is limited for studying: cancerophobia [DS] Commercial use is not prohibited. Data use for methods development research irrespective of the specified data use limitations is not prohibited. Restrictions for use as a control set for diseases other than those defined were not specified. - """, translation); - + """, + translation); } private void mockDataUseTranslateSummarySuccess() { @@ -138,9 +132,7 @@ private void mockDataUseTranslateSummarySuccess() { } ] } - """ - ) - ); + """)); } private void mockDataUseTranslateSuccess() { @@ -150,15 +142,14 @@ private void mockDataUseTranslateSuccess() { response() .withStatusCode(200) .withHeaders(new Header("Content-Type", MediaType.TEXT_PLAIN)) - .withBody(""" + .withBody( + """ Samples are restricted for use under the following conditions: Data is limited for health/medical/biomedical research. [HMB] Data use is limited for studying: cancerophobia [DS] Commercial use is not prohibited. Data use for methods development research irrespective of the specified data use limitations is not prohibited. Restrictions for use as a control set for diseases other than those defined were not specified. - """) - ); + """)); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceIntegrationTest.java b/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceIntegrationTest.java index 30a2352ce6..09f84f5f23 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceIntegrationTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceIntegrationTest.java @@ -14,9 +14,7 @@ import org.junit.jupiter.api.Test; import org.zendesk.client.v2.model.Request; -/** - * This test class should be used for manual integration testing only. - */ +/** This test class should be used for manual integration testing only. */ class SupportRequestServiceIntegrationTest { private SupportRequestService service; @@ -33,17 +31,17 @@ void setUp() { void testPostTicketToSupportWithAttachment() throws Exception { JsonObject tokenObject = service.postAttachmentToSupport("Test Image Content".getBytes()); String token = tokenObject.get("token").getAsString(); - DuosTicket ticket = TicketFactory.createTicket( - new TicketFields( - "Test User Name", - SupportRequestType.QUESTION, - "test@duos.org", - "Test Subject", - "Test Description", - "Test URL", - List.of(token))); + DuosTicket ticket = + TicketFactory.createTicket( + new TicketFields( + "Test User Name", + SupportRequestType.QUESTION, + "test@duos.org", + "Test Subject", + "Test Description", + "Test URL", + List.of(token))); Request request = service.postTicketToSupport(ticket); assertNotNull(request); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceTest.java index 96ccc2ecda..8cc339c9b7 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/SupportRequestServiceTest.java @@ -33,9 +33,7 @@ class SupportRequestServiceTest extends MockServerTestHelper { private SupportRequestService service; - @Mock - private ServicesConfiguration config; - + @Mock private ServicesConfiguration config; @BeforeEach void init() { @@ -48,13 +46,15 @@ void testPostTicketToSupport() throws Exception { String expectedBody = ticket.toString().replaceAll("\\s*", ""); when(config.isActivateSupportNotifications()).thenReturn(true); - when(config.postSupportRequestUrl()).thenReturn( - "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - mockServerClient.when(request().withMethod("POST")) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) - .withBody(expectedBody)); + when(config.postSupportRequestUrl()) + .thenReturn("http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); + mockServerClient + .when(request().withMethod("POST")) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) + .withBody(expectedBody)); service.postTicketToSupport(ticket); HttpRequest[] requests = mockServerClient.retrieveRecordedRequests(null); @@ -68,7 +68,8 @@ void testPostTicketToSupport() throws Exception { void testPostTicketToSupportNotificationsNotActivated() { DuosTicket ticket = generateTicket(); when(config.isActivateSupportNotifications()).thenReturn(false); - // verify no requests sent if activateSupportNotifications is false; throw error if post attempted + // verify no requests sent if activateSupportNotifications is false; throw error if post + // attempted mockServerClient.when(request()).error(new HttpError()); assertThrows(BadRequestException.class, () -> service.postTicketToSupport(ticket)); } @@ -77,12 +78,14 @@ void testPostTicketToSupportNotificationsNotActivated() { void testPostTicketToSupportNotificationsUnprocessableEntity() { DuosTicket ticket = generateTicket(); when(config.isActivateSupportNotifications()).thenReturn(true); - when(config.postSupportRequestUrl()).thenReturn( - "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)); + when(config.postSupportRequestUrl()) + .thenReturn("http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)); assertThrows(UnprocessableEntityException.class, () -> service.postTicketToSupport(ticket)); } @@ -90,29 +93,33 @@ void testPostTicketToSupportNotificationsUnprocessableEntity() { void testPostTicketToSupportServerError() { DuosTicket ticket = generateTicket(); when(config.isActivateSupportNotifications()).thenReturn(true); - when(config.postSupportRequestUrl()).thenReturn( - "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)); + when(config.postSupportRequestUrl()) + .thenReturn("http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)); assertThrows(ServerErrorException.class, () -> service.postTicketToSupport(ticket)); } @Test void testPostAttachmentToSupport() throws Exception { - String expectedBody = """ + String expectedBody = + """ { "upload": { "token": "token string" } } """; when(config.isActivateSupportNotifications()).thenReturn(true); - when(config.postSupportUploadUrl()).thenReturn( - "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - mockServerClient.when(request().withMethod("POST")) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) - .withBody(expectedBody) - ); + when(config.postSupportUploadUrl()) + .thenReturn("http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); + mockServerClient + .when(request().withMethod("POST")) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) + .withBody(expectedBody)); service = new SupportRequestService(config); service.postAttachmentToSupport("Test".getBytes()); HttpRequest[] requests = mockServerClient.retrieveRecordedRequests(null); @@ -123,54 +130,62 @@ void testPostAttachmentToSupport() throws Exception { void testPostTicketToSupportUnableToParseResponse() { // This case should never happen, but we do inspect the response for a valid "upload" object. // We need to ensure that the service handles invalid response formats correctly. - String expectedBody = """ + String expectedBody = + """ { "invalid": { "missing_token": "token string" } } """; when(config.isActivateSupportNotifications()).thenReturn(true); - when(config.postSupportUploadUrl()).thenReturn( - "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - mockServerClient.when(request().withMethod("POST")) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) - .withBody(expectedBody) - ); - assertThrows(ServerErrorException.class, - () -> service.postAttachmentToSupport("Test".getBytes())); + when(config.postSupportUploadUrl()) + .thenReturn("http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); + mockServerClient + .when(request().withMethod("POST")) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) + .withBody(expectedBody)); + assertThrows( + ServerErrorException.class, () -> service.postAttachmentToSupport("Test".getBytes())); } @Test void testPostAttachmentToSupportNotificationsNotActivated() { when(config.isActivateSupportNotifications()).thenReturn(false); - // verify no requests sent if activateSupportNotifications is false; throw error if post attempted + // verify no requests sent if activateSupportNotifications is false; throw error if post + // attempted mockServerClient.when(request()).error(new HttpError()); - assertThrows(BadRequestException.class, - () -> service.postAttachmentToSupport("Test".getBytes())); + assertThrows( + BadRequestException.class, () -> service.postAttachmentToSupport("Test".getBytes())); } @Test void testPostAttachmentToSupportServerError() { when(config.isActivateSupportNotifications()).thenReturn(true); - when(config.postSupportUploadUrl()).thenReturn( - "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)); - assertThrows(ServerErrorException.class, - () -> service.postAttachmentToSupport("Test".getBytes())); + when(config.postSupportUploadUrl()) + .thenReturn("http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)); + assertThrows( + ServerErrorException.class, () -> service.postAttachmentToSupport("Test".getBytes())); } @Test void testPostAttachmentToSupportUnprocessableEntity() { when(config.isActivateSupportNotifications()).thenReturn(true); - when(config.postSupportUploadUrl()).thenReturn( - "http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)); - assertThrows(UnprocessableEntityException.class, + when(config.postSupportUploadUrl()) + .thenReturn("http://" + CONTAINER.getHost() + ":" + CONTAINER.getServerPort() + "/"); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_UNPROCESSABLE_ENTITY)); + assertThrows( + UnprocessableEntityException.class, () -> service.postAttachmentToSupport("Test".getBytes())); } diff --git a/src/test/java/org/broadinstitute/consent/http/service/TDRServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/TDRServiceTest.java index f6ab4b95bd..71139ace31 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/TDRServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/TDRServiceTest.java @@ -35,23 +35,17 @@ @ExtendWith(MockitoExtension.class) class TDRServiceTest extends AbstractTestHelper { - @Mock - private DataAccessRequestService darService; + @Mock private DataAccessRequestService darService; - @Mock - private DatasetDAO datasetDAO; + @Mock private DatasetDAO datasetDAO; - @Mock - private LibraryCardDAO libraryCardDAO; + @Mock private LibraryCardDAO libraryCardDAO; - @Mock - private UserDAO userDAO; + @Mock private UserDAO userDAO; - @Mock - SamDAO samDAO; + @Mock SamDAO samDAO; - @Mock - AuthUser authUser; + @Mock AuthUser authUser; private TDRService service; private void initService() { @@ -71,8 +65,7 @@ void testGetApprovedUsersForDataset() { DataAccessRequest dar1 = new DataAccessRequest(); dar1.setUserId(user1.getUserId()); DataAccessRequestData data = new DataAccessRequestData(); - Collaborator lab = - new Collaborator(null, "lab@gmail.com", null, null, null, null, null); + Collaborator lab = new Collaborator(null, "lab@gmail.com", null, null, null, null, null); data.setLabCollaborators(List.of(lab)); Collaborator internal = new Collaborator(null, "internal@gmail.com", null, null, null, null, null); @@ -91,15 +84,15 @@ void testGetApprovedUsersForDataset() { when(darService.getApprovedDARsForDataset(dataset)).thenReturn(List.of(dar1, dar2)); when(userDAO.findUsers(any())).thenReturn(List.of(user1, user2)); - // Mock that the library cards exist for user 1, 2, and internal collaborator, but not the internal lab staff. + // Mock that the library cards exist for user 1, 2, and internal collaborator, but not the + // internal lab staff. when(libraryCardDAO.findByUserEmails(anyList())) .thenReturn(List.of(libraryCard1, libraryCard2, libraryCard3)); initService(); ApprovedUsers approvedUsers = service.getApprovedUsersForDataset(authUser, dataset); - List approvedUsersEmails = approvedUsers.approvedUsers().stream() - .map(ApprovedUser::email) - .toList(); + List approvedUsersEmails = + approvedUsers.approvedUsers().stream().map(ApprovedUser::email).toList(); assertTrue( approvedUsersEmails.containsAll( @@ -107,8 +100,7 @@ void testGetApprovedUsersForDataset() { "Approved users should include user1, user2, and internal collaborator"); assertFalse( approvedUsersEmails.contains(lab.email()), - "Lab collaborator should not be included as they do not have a library card" - ); + "Lab collaborator should not be included as they do not have a library card"); } @Test @@ -151,11 +143,12 @@ void testGetApprovedUsersForDatasetNoUsers() { @Test void testGetDatasetsByIdentifier() { String identifiers = "DUOS-00001, DUOS-00002"; - List identifierList = Arrays.stream(identifiers.split(",")) - .map(String::trim) - .filter(identifier -> !identifier.isBlank()) - .map(Dataset::parseIdentifierToAlias) - .toList(); + List identifierList = + Arrays.stream(identifiers.split(",")) + .map(String::trim) + .filter(identifier -> !identifier.isBlank()) + .map(Dataset::parseIdentifierToAlias) + .toList(); Dataset dataset1 = new Dataset(); dataset1.setDatasetId(1); @@ -200,7 +193,10 @@ void testGetApprovedUsersForDataset_logsInfo() { spyService.getApprovedUsersForDataset(authUser, dataset); - verify(spyService).logInfo(org.mockito.ArgumentMatchers.contains("Approved users requested. Requesting user:")); + verify(spyService) + .logInfo( + org.mockito.ArgumentMatchers.contains("Approved users requested. Requesting user:")); verify(spyService).logInfo(org.mockito.ArgumentMatchers.contains("user1@example.com")); - verify(spyService).logInfo(org.mockito.ArgumentMatchers.contains("DUOS-000001")); } + verify(spyService).logInfo(org.mockito.ArgumentMatchers.contains("DUOS-000001")); + } } diff --git a/src/test/java/org/broadinstitute/consent/http/service/UseRestrictionConverterTest.java b/src/test/java/org/broadinstitute/consent/http/service/UseRestrictionConverterTest.java index d3288a0ad0..960141d9ab 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/UseRestrictionConverterTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/UseRestrictionConverterTest.java @@ -51,8 +51,7 @@ private void mockDataUseTranslateFailure() { response() .withStatusCode(500) .withHeaders(new Header("Content-Type", MediaType.APPLICATION_JSON)) - .withBody("Exception") - ); + .withBody("Exception")); } public ServicesConfiguration config() { @@ -348,5 +347,4 @@ private DataAccessRequest createDataAccessRequest() { dar.setData(data); return dar; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/UserServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/UserServiceTest.java index 47cd427a31..bbd6936f7a 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/UserServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/UserServiceTest.java @@ -71,57 +71,54 @@ @ExtendWith(MockitoExtension.class) class UserServiceTest extends AbstractTestHelper { - @Mock - private UserDAO userDAO; + @Mock private UserDAO userDAO; - @Mock - private UserPropertyDAO userPropertyDAO; + @Mock private UserPropertyDAO userPropertyDAO; - @Mock - private UserRoleDAO userRoleDAO; + @Mock private UserRoleDAO userRoleDAO; - @Mock - private VoteDAO voteDAO; + @Mock private VoteDAO voteDAO; + @Mock private InstitutionDAO institutionDAO; - @Mock - private InstitutionDAO institutionDAO; + @Mock private LibraryCardDAO libraryCardDAO; - @Mock - private LibraryCardDAO libraryCardDAO; + @Mock private AcknowledgementDAO acknowledgementDAO; - @Mock - private AcknowledgementDAO acknowledgementDAO; + @Mock private FileStorageObjectDAO fileStorageObjectDAO; - @Mock - private FileStorageObjectDAO fileStorageObjectDAO; + @Mock private UserServiceDAO userServiceDAO; - @Mock - private UserServiceDAO userServiceDAO; + @Mock private DaaDAO daaDAO; - @Mock - private DaaDAO daaDAO; + @Mock private DraftServiceDAO draftServiceDAO; - @Mock - private DraftServiceDAO draftServiceDAO; - - @Mock - private InstitutionService institutionService; - @Mock - private DACAutomationRuleDAO ruleDAO; - @Mock - private DatasetAuthorizationReaderDAO datasetAuthorizationReaderDAO; - @Mock - private InstitutionAndLibraryCardEnforcement institutionAndLibraryCardEnforcement; + @Mock private InstitutionService institutionService; + @Mock private DACAutomationRuleDAO ruleDAO; + @Mock private DatasetAuthorizationReaderDAO datasetAuthorizationReaderDAO; + @Mock private InstitutionAndLibraryCardEnforcement institutionAndLibraryCardEnforcement; private UserService service; @BeforeEach void initService() { - service = new UserService(userDAO, userPropertyDAO, userRoleDAO, voteDAO, institutionDAO, - libraryCardDAO, acknowledgementDAO, fileStorageObjectDAO, userServiceDAO, daaDAO, - draftServiceDAO, institutionService, ruleDAO, datasetAuthorizationReaderDAO, - institutionAndLibraryCardEnforcement); + service = + new UserService( + userDAO, + userPropertyDAO, + userRoleDAO, + voteDAO, + institutionDAO, + libraryCardDAO, + acknowledgementDAO, + fileStorageObjectDAO, + userServiceDAO, + daaDAO, + draftServiceDAO, + institutionService, + ruleDAO, + datasetAuthorizationReaderDAO, + institutionAndLibraryCardEnforcement); } @Test @@ -138,8 +135,8 @@ void testUpdateUserFieldsById() { // and one role that should never be removed, but can be added (Researcher) // When we update this user, we'll ensure that the new roles are added, old roles are deleted, // and the researcher & chairperson roles remain. - when(userRoleDAO.findRolesByUserId(user.getUserId())).thenReturn( - List.of(admin, researcher, chair)); + when(userRoleDAO.findRolesByUserId(user.getUserId())) + .thenReturn(List.of(admin, researcher, chair)); when(userDAO.findUserById(any())).thenReturn(user); UserUpdateFields fields = new UserUpdateFields(); @@ -190,13 +187,14 @@ void createUserWithLibraryCardTest() { service.createUser(u); - verify(libraryCardDAO).updateLibraryCardById( - eq(lc.getId()), - eq(u.getUserId()), - eq(lc.getUserName()), - eq(lc.getUserEmail()), - eq(u.getUserId()), - any()); + verify(libraryCardDAO) + .updateLibraryCardById( + eq(lc.getId()), + eq(u.getUserId()), + eq(lc.getUserName()), + eq(lc.getUserEmail()), + eq(u.getUserId()), + any()); } @Test @@ -224,17 +222,22 @@ void testHasValidERACommonsCredentials() { LibraryCard lc = generateLibraryCard(u.getEmail()); u.setLibraryCard(lc); UserProperty eraStatus = new UserProperty(1, u.getUserId(), ERA_STATUS.getValue(), "true"); - //standard practice is that these expire in 30 days. - Timestamp eraExpirationTime = new Timestamp( - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); - UserProperty eraExpirationDate = new UserProperty(2, u.getUserId(), - ERA_EXPIRATION_DATE.getValue(), Long.toString(eraExpirationTime.getTime())); + // standard practice is that these expire in 30 days. + Timestamp eraExpirationTime = + new Timestamp(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); + UserProperty eraExpirationDate = + new UserProperty( + 2, + u.getUserId(), + ERA_EXPIRATION_DATE.getValue(), + Long.toString(eraExpirationTime.getTime())); List userProperties = new ArrayList<>(); userProperties.add(eraStatus); userProperties.add(eraExpirationDate); u.setProperties(userProperties); - when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(u.getUserId(), - UserFields.getValues())).thenReturn(u.getProperties()); + when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + u.getUserId(), UserFields.getValues())) + .thenReturn(u.getProperties()); assertDoesNotThrow(() -> service.validateActiveERACredentials(u)); } @@ -242,17 +245,20 @@ void testHasValidERACommonsCredentials() { void testValidateERACommonsCredentialsMissingLibraryCards() { User u = generateUser(); UserProperty eraStatus = new UserProperty(1, u.getUserId(), ERA_STATUS.getValue(), "true"); - //standard practice is that these expire in 30 days. - Timestamp eraExpirationTime = new Timestamp( - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); - UserProperty eraExpirationDate = new UserProperty(2, u.getUserId(), - ERA_EXPIRATION_DATE.getValue(), Long.toString(eraExpirationTime.getTime())); + // standard practice is that these expire in 30 days. + Timestamp eraExpirationTime = + new Timestamp(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); + UserProperty eraExpirationDate = + new UserProperty( + 2, + u.getUserId(), + ERA_EXPIRATION_DATE.getValue(), + Long.toString(eraExpirationTime.getTime())); List userProperties = new ArrayList<>(); userProperties.add(eraStatus); userProperties.add(eraExpirationDate); u.setProperties(userProperties); - assertThrows(LibraryCardRequiredException.class, - () -> service.validateActiveERACredentials(u)); + assertThrows(LibraryCardRequiredException.class, () -> service.validateActiveERACredentials(u)); } @Test @@ -262,17 +268,20 @@ void testValidateERACommonsCredentialsMissingERACommonsId() { LibraryCard lc = generateLibraryCard(u.getEmail()); u.setLibraryCard(lc); UserProperty eraStatus = new UserProperty(1, u.getUserId(), ERA_STATUS.getValue(), "true"); - //standard practice is that these expire in 30 days. - Timestamp eraExpirationTime = new Timestamp( - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); - UserProperty eraExpirationDate = new UserProperty(2, u.getUserId(), - ERA_EXPIRATION_DATE.getValue(), Long.toString(eraExpirationTime.getTime())); + // standard practice is that these expire in 30 days. + Timestamp eraExpirationTime = + new Timestamp(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); + UserProperty eraExpirationDate = + new UserProperty( + 2, + u.getUserId(), + ERA_EXPIRATION_DATE.getValue(), + Long.toString(eraExpirationTime.getTime())); List userProperties = new ArrayList<>(); userProperties.add(eraStatus); userProperties.add(eraExpirationDate); u.setProperties(userProperties); - assertThrows(BadRequestException.class, - () -> service.validateActiveERACredentials(u)); + assertThrows(BadRequestException.class, () -> service.validateActiveERACredentials(u)); } @Test @@ -280,18 +289,22 @@ void testValidateRACommonsCredentialsMissingERAStatusShouldFail() { User u = generateUser(); LibraryCard lc = generateLibraryCard(u.getEmail()); u.setLibraryCard(lc); - //standard practice is that these expire in 30 days. - Timestamp eraExpirationTime = new Timestamp( - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); - UserProperty eraExpirationDate = new UserProperty(2, u.getUserId(), - ERA_EXPIRATION_DATE.getValue(), Long.toString(eraExpirationTime.getTime())); + // standard practice is that these expire in 30 days. + Timestamp eraExpirationTime = + new Timestamp(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)); + UserProperty eraExpirationDate = + new UserProperty( + 2, + u.getUserId(), + ERA_EXPIRATION_DATE.getValue(), + Long.toString(eraExpirationTime.getTime())); List userProperties = new ArrayList<>(); userProperties.add(eraExpirationDate); u.setProperties(userProperties); - when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(u.getUserId(), - UserFields.getValues())).thenReturn(u.getProperties()); - assertThrows(BadRequestException.class, - () -> service.validateActiveERACredentials(u)); + when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + u.getUserId(), UserFields.getValues())) + .thenReturn(u.getProperties()); + assertThrows(BadRequestException.class, () -> service.validateActiveERACredentials(u)); } @Test @@ -301,10 +314,10 @@ void testValidateERACommonsCredentialsMissingERAStatusAndExpirationShouldFail() u.setLibraryCard(lc); List userProperties = new ArrayList<>(); u.setProperties(userProperties); - when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(u.getUserId(), - UserFields.getValues())).thenReturn(u.getProperties()); - assertThrows(BadRequestException.class, - () -> service.validateActiveERACredentials(u)); + when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + u.getUserId(), UserFields.getValues())) + .thenReturn(u.getProperties()); + assertThrows(BadRequestException.class, () -> service.validateActiveERACredentials(u)); } @Test @@ -314,18 +327,22 @@ void testValidateERACommonsCredentialsWithExpiredERAExpirationDateShouldFail() { u.setLibraryCard(lc); UserProperty eraStatus = new UserProperty(1, u.getUserId(), ERA_STATUS.getValue(), "true"); // set expiration date to 30 days ago! - Timestamp eraExpirationTime = new Timestamp( - System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30)); - UserProperty eraExpirationDate = new UserProperty(2, u.getUserId(), - ERA_EXPIRATION_DATE.getValue(), Long.toString(eraExpirationTime.getTime())); + Timestamp eraExpirationTime = + new Timestamp(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30)); + UserProperty eraExpirationDate = + new UserProperty( + 2, + u.getUserId(), + ERA_EXPIRATION_DATE.getValue(), + Long.toString(eraExpirationTime.getTime())); List userProperties = new ArrayList<>(); userProperties.add(eraStatus); userProperties.add(eraExpirationDate); u.setProperties(userProperties); - when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(u.getUserId(), - UserFields.getValues())).thenReturn(u.getProperties()); - assertThrows(BadRequestException.class, - () -> service.validateActiveERACredentials(u)); + when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + u.getUserId(), UserFields.getValues())) + .thenReturn(u.getProperties()); + assertThrows(BadRequestException.class, () -> service.validateActiveERACredentials(u)); } @Test @@ -333,8 +350,9 @@ void testCreateUserNoRoles() { User u = generateUser(); assertTrue(CollectionUtils.isEmpty(u.getRoles())); int userId = 123; - when(userDAO.insertUser(eq(u.getEmail()), eq(u.getDisplayName()), eq(u.getInstitutionId()), - any())).thenReturn(userId); + when(userDAO.insertUser( + eq(u.getEmail()), eq(u.getDisplayName()), eq(u.getInstitutionId()), any())) + .thenReturn(userId); service.createUser(u); verify(userRoleDAO).insertUserRoles(List.of(UserRoles.Researcher()), userId); } @@ -389,8 +407,10 @@ void testFindUserByIdNoRoles() { @Test void testFindUserByIdWithRoles() { User u = generateUser(); - List roleList = List.of(generateRole(UserRoles.RESEARCHER.getRoleId()), - generateRole(UserRoles.MEMBER.getRoleId())); + List roleList = + List.of( + generateRole(UserRoles.RESEARCHER.getRoleId()), + generateRole(UserRoles.MEMBER.getRoleId())); u.setRoles(roleList); when(userDAO.findUserById(any())).thenReturn(u); @@ -423,8 +443,10 @@ void testFindUserByEmailNoRoles() { @Test void testFindUserByEmailWithRoles() { User u = generateUser(); - List roleList = List.of(generateRole(UserRoles.RESEARCHER.getRoleId()), - generateRole(UserRoles.MEMBER.getRoleId())); + List roleList = + List.of( + generateRole(UserRoles.RESEARCHER.getRoleId()), + generateRole(UserRoles.MEMBER.getRoleId())); u.setRoles(roleList); when(userDAO.findUserByEmail(any())).thenReturn(u); @@ -450,7 +472,7 @@ void testDeleteUser() { when(userDAO.findUserByEmail(any())).thenReturn(u); try { - service.deleteUserByEmail(randomAlphabetic(10), randomInt(1,100)); + service.deleteUserByEmail(randomAlphabetic(10), randomInt(1, 100)); verify(draftServiceDAO).deleteDraftsByUser(u); verify(ruleDAO, atLeastOnce()).auditedDeleteAllDACRuleSettingForUser(anyInt(), anyInt()); verify(datasetAuthorizationReaderDAO, atLeastOnce()).deleteByUserId(u.getUserId()); @@ -462,7 +484,9 @@ void testDeleteUser() { @Test void testDeleteUserFailure() { when(userDAO.findUserByEmail(any())).thenThrow(new NotFoundException()); - assertThrows(NotFoundException.class, () -> service.deleteUserByEmail(randomAlphabetic(10), randomInt(1,100))); + assertThrows( + NotFoundException.class, + () -> service.deleteUserByEmail(randomAlphabetic(10), randomInt(1, 100))); } @Test @@ -528,7 +552,8 @@ void testGetUsersByUserRole_SO() { void testGetUsersAsRoleSO_NoInstitution() { User u = generateUser(); u.setInstitutionId(null); - assertThrows(NotFoundException.class, + assertThrows( + NotFoundException.class, () -> service.getUsersAsRole(u, UserRoles.SIGNINGOFFICIAL.getRoleName())); } @@ -671,21 +696,26 @@ void testFindUsersWithNoInstitution() { void testFindUserWithPropertiesAsJsonObjectById() { User user = generateUser(); user.setLibraryCard(new LibraryCard()); - UserStatusInfo info = new UserStatusInfo().setUserEmail(user.getEmail()).setEnabled(true) - .setUserSubjectId("subjectId"); - AuthUser authUser = new AuthUser().setEmail(user.getEmail()) - .setAuthToken(randomAlphabetic(30)).setUserStatusInfo(info); + UserStatusInfo info = + new UserStatusInfo() + .setUserEmail(user.getEmail()) + .setEnabled(true) + .setUserSubjectId("subjectId"); + AuthUser authUser = + new AuthUser() + .setEmail(user.getEmail()) + .setAuthToken(randomAlphabetic(30)) + .setUserStatusInfo(info); DuosUser activeDuosUser = new DuosUser(authUser, user); - when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(anyInt(), any())).thenReturn( - List.of(new UserProperty())); + when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(anyInt(), any())) + .thenReturn(List.of(new UserProperty())); when(userDAO.findUserById(user.getUserId())).thenReturn(user); - JsonObject userJson = service.findUserWithPropertiesByIdAsJsonObject(activeDuosUser, - user.getUserId()); + JsonObject userJson = + service.findUserWithPropertiesByIdAsJsonObject(activeDuosUser, user.getUserId()); assertNotNull(userJson); assertTrue(userJson.get(UserService.LIBRARY_CARD_FIELD).getAsJsonObject().isJsonObject()); - assertTrue( - userJson.get(UserService.USER_PROPERTIES_FIELD).getAsJsonArray().isJsonArray()); + assertTrue(userJson.get(UserService.USER_PROPERTIES_FIELD).getAsJsonArray().isJsonArray()); assertTrue(userJson.get(UserService.USER_STATUS_INFO_FIELD).getAsJsonObject().isJsonObject()); } @@ -693,21 +723,26 @@ void testFindUserWithPropertiesAsJsonObjectById() { void testFindUserWithPropertiesAsJsonObjectByIdNonAuthUser() { User user = generateUser(); user.setLibraryCard(new LibraryCard()); - UserStatusInfo info = new UserStatusInfo().setUserEmail(user.getEmail()).setEnabled(true) - .setUserSubjectId("subjectId"); - AuthUser authUser = new AuthUser().setEmail("not the user's email address") - .setAuthToken(randomAlphabetic(30)).setUserStatusInfo(info); + UserStatusInfo info = + new UserStatusInfo() + .setUserEmail(user.getEmail()) + .setEnabled(true) + .setUserSubjectId("subjectId"); + AuthUser authUser = + new AuthUser() + .setEmail("not the user's email address") + .setAuthToken(randomAlphabetic(30)) + .setUserStatusInfo(info); DuosUser activeDuosUser = new DuosUser(authUser, user); - when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(anyInt(), any())).thenReturn( - List.of(new UserProperty())); + when(userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys(anyInt(), any())) + .thenReturn(List.of(new UserProperty())); when(userDAO.findUserById(user.getUserId())).thenReturn(user); - JsonObject userJson = service.findUserWithPropertiesByIdAsJsonObject(activeDuosUser, - user.getUserId()); + JsonObject userJson = + service.findUserWithPropertiesByIdAsJsonObject(activeDuosUser, user.getUserId()); assertNotNull(userJson); assertTrue(userJson.get(UserService.LIBRARY_CARD_FIELD).getAsJsonObject().isJsonObject()); - assertTrue( - userJson.get(UserService.USER_PROPERTIES_FIELD).getAsJsonArray().isJsonArray()); + assertTrue(userJson.get(UserService.USER_PROPERTIES_FIELD).getAsJsonArray().isJsonArray()); assertNull(userJson.get(UserService.USER_STATUS_INFO_FIELD)); } @@ -751,18 +786,19 @@ void insertUserRoleAndInstitution_FailingTxn() { assertNull(testUser.getInstitutionId()); UserRole role = UserRoles.Researcher(); when(institutionService.findInstitutionForEmail(testUser.getEmail())).thenReturn(institution); - doThrow(new TransactionException("txn error")).when(userServiceDAO) + doThrow(new TransactionException("txn error")) + .when(userServiceDAO) .insertRoleAndInstitutionTxn(role, institution.getId(), testUser.getUserId()); - assertThrows(TransactionException.class, - () -> service.insertRoleAndInstitutionForUser(role, testUser)); + assertThrows( + TransactionException.class, () -> service.insertRoleAndInstitutionForUser(role, testUser)); } @Test void insertUserRoleAndInstitution_FailingInstitution() { User testUser = generateUserWithoutInstitution(); UserRole role = UserRoles.Researcher(); - assertThrows(BadRequestException.class, - () -> service.insertRoleAndInstitutionForUser(role, testUser)); + assertThrows( + BadRequestException.class, () -> service.insertRoleAndInstitutionForUser(role, testUser)); } @Test @@ -844,5 +880,4 @@ private UserRole generateRole(int roleId) { assert rolesEnum != null; return new UserRole(rolesEnum.getRoleId(), rolesEnum.getRoleName()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/VoteServiceTest.java b/src/test/java/org/broadinstitute/consent/http/service/VoteServiceTest.java index 4ab630b77d..b14c35e8e8 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/VoteServiceTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/VoteServiceTest.java @@ -438,7 +438,8 @@ void testNotifyResearchersOfProgressReportApproval() throws TemplateException, I service.sendDatasetApprovalNotifications(List.of(v1), researcher); - verify(emailService).sendResearcherProgressReportApproved(any(), any(), anyList(), any(), anyBoolean()); + verify(emailService) + .sendResearcherProgressReportApproved(any(), any(), anyList(), any(), anyBoolean()); } @Test @@ -1079,7 +1080,8 @@ void testNotifySigningOfficialsOfApprovedDatasets_DAR() throws TemplateException service.notifySigningOfficialsOfApprovedDatasets( List.of(dataset), researcher, dar, "DAR-000123", "translation", false); verify(emailService, never()) - .sendNewSoProgressReportApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); + .sendNewSoProgressReportApprovedEmail( + any(), any(), any(), any(), any(), any(), anyBoolean()); verify(emailService, times(1)) .sendNewSoDARApprovedEmail(any(), any(), any(), any(), any(), any(), eq(false)); } @@ -1105,7 +1107,8 @@ void testNotifySigningOfficialsOfRADARApprovedDatasets_DAR() service.notifySigningOfficialsOfApprovedDatasets( List.of(dataset), researcher, dar, "DAR-000123", "translation", true); verify(emailService, never()) - .sendNewSoProgressReportApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); + .sendNewSoProgressReportApprovedEmail( + any(), any(), any(), any(), any(), any(), anyBoolean()); verify(emailService, times(1)) .sendNewSoDARApprovedEmail(any(), any(), any(), any(), any(), any(), eq(true)); } @@ -1204,7 +1207,8 @@ void testNotifySigningOfficialsOfApprovedDatasets_PR() throws TemplateException, service.notifySigningOfficialsOfApprovedDatasets( List.of(dataset), researcher, child, "DAR-000123", "translation", false); verify(emailService, times(1)) - .sendNewSoProgressReportApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); + .sendNewSoProgressReportApprovedEmail( + any(), any(), any(), any(), any(), any(), anyBoolean()); verify(emailService, never()) .sendNewSoDARApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); } @@ -1223,7 +1227,8 @@ void testNotifySigningOfficialsOfApprovedDatasets_NoResearcher() service.notifySigningOfficialsOfApprovedDatasets( List.of(dataset), null, dar, "DAR-000123", "translation", false); verify(emailService, never()) - .sendNewSoProgressReportApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); + .sendNewSoProgressReportApprovedEmail( + any(), any(), any(), any(), any(), any(), anyBoolean()); verify(emailService, never()) .sendNewSoDARApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); } @@ -1244,7 +1249,8 @@ void testNotifySigningOfficialsOfApprovedDatasets_NoInstitution() service.notifySigningOfficialsOfApprovedDatasets( List.of(dataset), researcher, dar, "DAR-000123", "translation", false); verify(emailService, never()) - .sendNewSoProgressReportApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); + .sendNewSoProgressReportApprovedEmail( + any(), any(), any(), any(), any(), any(), anyBoolean()); verify(emailService, never()) .sendNewSoDARApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); } @@ -1267,7 +1273,8 @@ void testNotifySigningOfficialsOfApprovedDatasets_NoSigningOfficials() service.notifySigningOfficialsOfApprovedDatasets( List.of(dataset), researcher, dar, "DAR-000123", "translation", false); verify(emailService, never()) - .sendNewSoProgressReportApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); + .sendNewSoProgressReportApprovedEmail( + any(), any(), any(), any(), any(), any(), anyBoolean()); verify(emailService, never()) .sendNewSoDARApprovedEmail(any(), any(), any(), any(), any(), any(), anyBoolean()); } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAOTest.java index ae1e103c18..48fa192c3e 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/DaaServiceDAOTest.java @@ -31,22 +31,28 @@ void setUp() { @Test void testCreateDaa() { User user = createUser(); - Integer dacId = dacDAO.createDac(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10), new Date()); + Integer dacId = + dacDAO.createDac( + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + new Date()); FileStorageObject fso = new FileStorageObject(); fso.setFileName(RandomStringUtils.randomAlphabetic(10)); fso.setCategory(FileCategory.DATA_ACCESS_AGREEMENT); - BlobId blobId = BlobId.of(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10)); + BlobId blobId = + BlobId.of(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10)); fso.setBlobId(blobId); fso.setMediaType(MediaType.TEXT_PLAIN_TYPE.getType()); - assertDoesNotThrow(() -> { - Integer daaId = serviceDAO.createDaaWithFso(user.getUserId(), dacId, fso); - assertNotNull(daaId); - DataAccessAgreement daa = daaDAO.findById(daaId); - assertNotNull(daa); - assertNotNull(daa.getFile()); - assertNotNull(daa.getInitialDacId()); - assertFalse(daa.getDacs().isEmpty()); - }); + assertDoesNotThrow( + () -> { + Integer daaId = serviceDAO.createDaaWithFso(user.getUserId(), dacId, fso); + assertNotNull(daaId); + DataAccessAgreement daa = daaDAO.findById(daaId); + assertNotNull(daa); + assertNotNull(daa.getFile()); + assertNotNull(daa.getInitialDacId()); + assertFalse(daa.getDacs().isEmpty()); + }); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/DacServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/DacServiceDAOTest.java index dc0cbba0b6..bcca8ecfef 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/DacServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/DacServiceDAOTest.java @@ -53,100 +53,129 @@ void testDeleteDac() { // * DatasetAutomationRules associated to the DAC List dacs = createMockDACs(); List createdDatasetIds = new ArrayList<>(); - dacs.forEach(dac -> { - // DAC - int dacId = dacDAO.createDac( - "dac name: " + RandomStringUtils.randomAlphabetic(10), - "dac description: " + RandomStringUtils.randomAlphabetic(10), - "dac email: " + RandomStringUtils.randomAlphabetic(10), - new Date()); - // Data Access Agreement - int daaId = daaDAO.createDaa(superUser.getUserId(), new Date().toInstant(), - superUser.getUserId(), new Date().toInstant(), dacId); - // DAC->DAA Association. - daaDAO.createDacDaaRelation(dacId, daaId); - // Library Card User - User lcUser = createUser(); - // A user's library card needs an institution - int dunsNumber = RandomUtils.nextInt(10, 100); - institutionDAO.insertInstitution( - "institution name: " + RandomStringUtils.randomAlphabetic(10), - "it director name: " + RandomStringUtils.randomAlphabetic(10), - "it director email: " + RandomStringUtils.randomAlphabetic(10), - "institution url: " + RandomStringUtils.randomAlphabetic(10), - dunsNumber, - "org chart url: " + RandomStringUtils.randomAlphabetic(10), - "verification url: " + RandomStringUtils.randomAlphabetic(10), - "verification file name: " + RandomStringUtils.randomAlphabetic(10), - "org type: " + RandomStringUtils.randomAlphabetic(10), - superUser.getUserId(), - new Date()); - int userLcId = libraryCardDAO.insertLibraryCard( - lcUser.getUserId(), - "library card user name: " + RandomStringUtils.randomAlphabetic(10), - "library card user email: " + RandomStringUtils.randomAlphabetic(10), - superUser.getUserId(), - new Date()); - // Library Card User to Data Access Agreement association - libraryCardDAO.createLibraryCardDaaRelation(userLcId, daaId); - // DAC Member User. When deleting the dac, this role will be deleted - User member = createUser(); - userRoleDAO.insertSingleUserRole(UserRoles.MEMBER.getRoleId(), member.getUserId()); - // DAC Chair User. When deleting the dac, this role will be deleted - User chair = createUser(); - userRoleDAO.insertSingleUserRole(UserRoles.CHAIRPERSON.getRoleId(), chair.getUserId()); - // Dataset associated to the DAC. The Dataset will become dissociated from the deleted DAC. - int datasetId = datasetDAO.insertDataset( - "dataset name: " + RandomStringUtils.randomAlphabetic(10), - Timestamp.from(Instant.now()), - superUser.getUserId(), - "object id: " + RandomStringUtils.randomAlphabetic(10), - new DataUseBuilder().setGeneralUse(true).build().toString(), - dacId); - createdDatasetIds.add(datasetId); - datasetDAO.updateDatasetDacId(datasetId, dacId); - Optional activeAutomation = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dacId).stream().filter(r -> r.ruleState() == RuleState.AVAILABLE).findFirst(); - assertTrue(activeAutomation.isPresent()); - dacAutomationRuleDAO.auditedInsertDACRuleSetting(dacId, activeAutomation.get().id(), - chair.getUserId(), Instant.now()); - }); - dacDAO.findAll().forEach(dac -> { - assertDoesNotThrow(() -> serviceDAO.deleteDacAndDaas(superUser, dac), - "Delete should not fail"); - List rules = dacAutomationRuleDAO.findAllDACAutomationRulesByDACId( - dac.getDacId()).stream().filter(r -> r.enabledByUserId() != null).toList(); - assertTrue(rules.isEmpty(), "There should be no dac automation rules enabled by users."); - List datasets = datasetDAO.findDatasetListByDacIds(List.of(dac.getDacId())); - assertTrue(datasets.isEmpty()); - List members = dacDAO.findMembersByDacId(dac.getDacId()); - assertTrue(members.isEmpty()); - DataAccessAgreement daa = daaDAO.findByDacId(dac.getDacId()); - assertNull(daa); - // Assert that there are no DAAs that reference this DAC - daaDAO.findAll().forEach(d -> { - List daaDacIds = d.getDacs().stream().map(Dac::getDacId).toList(); - assertFalse(daaDacIds.contains(dac.getDacId()), - "There should be no DAAs that have DACs matching this deleted Dac ID"); - }); - // Assert that there are no Library Cards with DAAs that reference this DAC - libraryCardDAO.findAllLibraryCards().forEach(lc -> { - List daaIds = lc.getDaaIds(); - if (!daaIds.isEmpty()) { - daaIds.forEach(daaId -> { - DataAccessAgreement innerDaa = daaDAO.findById(daaId); - List innerDacIds = innerDaa.getDacs().stream().map(Dac::getDacId).toList(); - assertFalse(innerDacIds.contains(dac.getDacId()), - "There should be no Library Cards with DAAs that have DACs matching this deleted Dac ID"); - }); - } - }); - }); - createdDatasetIds.forEach(id -> { - Dataset ds = datasetDAO.findDatasetById(id); - assertNull(ds.getDacId(), "Dataset should not have a DAC"); - assertNull(ds.getDacApproval(), "Dataset should not have a DAC approval"); - }); + dacs.forEach( + dac -> { + // DAC + int dacId = + dacDAO.createDac( + "dac name: " + RandomStringUtils.randomAlphabetic(10), + "dac description: " + RandomStringUtils.randomAlphabetic(10), + "dac email: " + RandomStringUtils.randomAlphabetic(10), + new Date()); + // Data Access Agreement + int daaId = + daaDAO.createDaa( + superUser.getUserId(), + new Date().toInstant(), + superUser.getUserId(), + new Date().toInstant(), + dacId); + // DAC->DAA Association. + daaDAO.createDacDaaRelation(dacId, daaId); + // Library Card User + User lcUser = createUser(); + // A user's library card needs an institution + int dunsNumber = RandomUtils.nextInt(10, 100); + institutionDAO.insertInstitution( + "institution name: " + RandomStringUtils.randomAlphabetic(10), + "it director name: " + RandomStringUtils.randomAlphabetic(10), + "it director email: " + RandomStringUtils.randomAlphabetic(10), + "institution url: " + RandomStringUtils.randomAlphabetic(10), + dunsNumber, + "org chart url: " + RandomStringUtils.randomAlphabetic(10), + "verification url: " + RandomStringUtils.randomAlphabetic(10), + "verification file name: " + RandomStringUtils.randomAlphabetic(10), + "org type: " + RandomStringUtils.randomAlphabetic(10), + superUser.getUserId(), + new Date()); + int userLcId = + libraryCardDAO.insertLibraryCard( + lcUser.getUserId(), + "library card user name: " + RandomStringUtils.randomAlphabetic(10), + "library card user email: " + RandomStringUtils.randomAlphabetic(10), + superUser.getUserId(), + new Date()); + // Library Card User to Data Access Agreement association + libraryCardDAO.createLibraryCardDaaRelation(userLcId, daaId); + // DAC Member User. When deleting the dac, this role will be deleted + User member = createUser(); + userRoleDAO.insertSingleUserRole(UserRoles.MEMBER.getRoleId(), member.getUserId()); + // DAC Chair User. When deleting the dac, this role will be deleted + User chair = createUser(); + userRoleDAO.insertSingleUserRole(UserRoles.CHAIRPERSON.getRoleId(), chair.getUserId()); + // Dataset associated to the DAC. The Dataset will become dissociated from the deleted + // DAC. + int datasetId = + datasetDAO.insertDataset( + "dataset name: " + RandomStringUtils.randomAlphabetic(10), + Timestamp.from(Instant.now()), + superUser.getUserId(), + "object id: " + RandomStringUtils.randomAlphabetic(10), + new DataUseBuilder().setGeneralUse(true).build().toString(), + dacId); + createdDatasetIds.add(datasetId); + datasetDAO.updateDatasetDacId(datasetId, dacId); + Optional activeAutomation = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dacId).stream() + .filter(r -> r.ruleState() == RuleState.AVAILABLE) + .findFirst(); + assertTrue(activeAutomation.isPresent()); + dacAutomationRuleDAO.auditedInsertDACRuleSetting( + dacId, activeAutomation.get().id(), chair.getUserId(), Instant.now()); + }); + dacDAO + .findAll() + .forEach( + dac -> { + assertDoesNotThrow( + () -> serviceDAO.deleteDacAndDaas(superUser, dac), "Delete should not fail"); + List rules = + dacAutomationRuleDAO.findAllDACAutomationRulesByDACId(dac.getDacId()).stream() + .filter(r -> r.enabledByUserId() != null) + .toList(); + assertTrue( + rules.isEmpty(), "There should be no dac automation rules enabled by users."); + List datasets = datasetDAO.findDatasetListByDacIds(List.of(dac.getDacId())); + assertTrue(datasets.isEmpty()); + List members = dacDAO.findMembersByDacId(dac.getDacId()); + assertTrue(members.isEmpty()); + DataAccessAgreement daa = daaDAO.findByDacId(dac.getDacId()); + assertNull(daa); + // Assert that there are no DAAs that reference this DAC + daaDAO + .findAll() + .forEach( + d -> { + List daaDacIds = d.getDacs().stream().map(Dac::getDacId).toList(); + assertFalse( + daaDacIds.contains(dac.getDacId()), + "There should be no DAAs that have DACs matching this deleted Dac ID"); + }); + // Assert that there are no Library Cards with DAAs that reference this DAC + libraryCardDAO + .findAllLibraryCards() + .forEach( + lc -> { + List daaIds = lc.getDaaIds(); + if (!daaIds.isEmpty()) { + daaIds.forEach( + daaId -> { + DataAccessAgreement innerDaa = daaDAO.findById(daaId); + List innerDacIds = + innerDaa.getDacs().stream().map(Dac::getDacId).toList(); + assertFalse( + innerDacIds.contains(dac.getDacId()), + "There should be no Library Cards with DAAs that have DACs matching this deleted Dac ID"); + }); + } + }); + }); + createdDatasetIds.forEach( + id -> { + Dataset ds = datasetDAO.findDatasetById(id); + assertNull(ds.getDacId(), "Dataset should not have a DAC"); + assertNull(ds.getDacApproval(), "Dataset should not have a DAC approval"); + }); } /** @@ -155,15 +184,16 @@ void testDeleteDac() { private List createMockDACs() { DataAccessAgreement daa = new DataAccessAgreement(); daa.setDaaId(1); - return IntStream.range(0, 5). - mapToObj(i -> { - Dac dac = new Dac(); - dac.setDacId(i); - dac.setDescription("Dac " + i); - dac.setName("Dac " + i); - dac.setAssociatedDaa(daa); - return dac; - }).collect(Collectors.toList()); + return IntStream.range(0, 5) + .mapToObj( + i -> { + Dac dac = new Dac(); + dac.setDacId(i); + dac.setDescription("Dac " + i); + dac.setName("Dac " + i); + dac.setAssociatedDaa(daa); + return dac; + }) + .collect(Collectors.toList()); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAOTest.java index f08ce02b95..b78b5060e5 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/DarCollectionServiceDAOTest.java @@ -72,38 +72,42 @@ void testCreateElectionsForDarByUserAdmin() throws Exception { // Ensure that we have all primary vote types for each election type // Data Access Elections have Chair, Dac, Final, and Agreement votes - Optional daElectionOption = createdElections.stream() - .filter(e -> ElectionType.DATA_ACCESS.getValue().equals(e.getElectionType())).findFirst(); + Optional daElectionOption = + createdElections.stream() + .filter(e -> ElectionType.DATA_ACCESS.getValue().equals(e.getElectionType())) + .findFirst(); assertTrue(daElectionOption.isPresent()); - assertTrue(createdVotes - .stream() - .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) - .anyMatch(v -> v.getType().equals(VoteType.CHAIRPERSON.getValue()))); - assertTrue(createdVotes - .stream() - .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) - .anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); - assertTrue(createdVotes - .stream() - .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) - .anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); - assertTrue(createdVotes - .stream() - .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) - .anyMatch(v -> v.getType().equals(VoteType.AGREEMENT.getValue()))); + assertTrue( + createdVotes.stream() + .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) + .anyMatch(v -> v.getType().equals(VoteType.CHAIRPERSON.getValue()))); + assertTrue( + createdVotes.stream() + .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) + .anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); + assertTrue( + createdVotes.stream() + .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) + .anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); + assertTrue( + createdVotes.stream() + .filter(v -> v.getElectionId().equals(daElectionOption.get().getElectionId())) + .anyMatch(v -> v.getType().equals(VoteType.AGREEMENT.getValue()))); // RP Elections have Chair and Dac votes - Optional rpElectionOption = createdElections.stream() - .filter(e -> ElectionType.RP.getValue().equals(e.getElectionType())).findFirst(); + Optional rpElectionOption = + createdElections.stream() + .filter(e -> ElectionType.RP.getValue().equals(e.getElectionType())) + .findFirst(); assertTrue(rpElectionOption.isPresent()); - assertTrue(createdVotes - .stream() - .filter(v -> v.getElectionId().equals(rpElectionOption.get().getElectionId())) - .anyMatch(v -> v.getType().equals(VoteType.CHAIRPERSON.getValue()))); - assertTrue(createdVotes - .stream() - .filter(v -> v.getElectionId().equals(rpElectionOption.get().getElectionId())) - .anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); + assertTrue( + createdVotes.stream() + .filter(v -> v.getElectionId().equals(rpElectionOption.get().getElectionId())) + .anyMatch(v -> v.getType().equals(VoteType.CHAIRPERSON.getValue()))); + assertTrue( + createdVotes.stream() + .filter(v -> v.getElectionId().equals(rpElectionOption.get().getElectionId())) + .anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); } /** @@ -142,13 +146,10 @@ void testCreateElectionsForDarCollectionWithMultipleDatasetsForAdminBy() throws assertFalse(createdVotes.isEmpty()); assertTrue( createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.CHAIRPERSON.getValue()))); - assertTrue( - createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); - assertTrue( - createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); + assertTrue(createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); + assertTrue(createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); assertTrue( createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.AGREEMENT.getValue()))); - } /** @@ -164,8 +165,8 @@ void testCreateElectionsForDarByUserChair() throws Exception { Optional dac = dacDAO.findDacsForDatasetIds(List.of(datasetId)).stream().findFirst(); assertTrue(dac.isPresent()); List dacUsers = dacDAO.findMembersByDacId(dac.get().getDacId()); - Optional chair = dacUsers.stream().filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) - .findFirst(); + Optional chair = + dacUsers.stream().filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)).findFirst(); assertTrue(chair.isPresent()); List referenceIds = serviceDAO.createElectionsForDarByUser(chair.get(), dar); @@ -189,10 +190,8 @@ void testCreateElectionsForDarByUserChair() throws Exception { assertFalse(createdVotes.isEmpty()); assertTrue( createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.CHAIRPERSON.getValue()))); - assertTrue( - createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); - assertTrue( - createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); + assertTrue(createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); + assertTrue(createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); assertTrue( createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.AGREEMENT.getValue()))); } @@ -217,8 +216,11 @@ void testCreateElectionsForDarCollectionWithMultipleDatasetsForChairBy() throws Dac dac = dacDAO.findDacsForDatasetIds(List.of(datasetId1)).stream().findFirst().orElseThrow(); assertNotNull(dac); List dacUsers = dacDAO.findMembersByDacId(dac.getDacId()); - User chair = dacUsers.stream().filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) - .findFirst().orElseThrow(); + User chair = + dacUsers.stream() + .filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) + .findFirst() + .orElseThrow(); // refresh the collection collection = darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId()); @@ -232,7 +234,7 @@ void testCreateElectionsForDarCollectionWithMultipleDatasetsForChairBy() throws createdElections.stream().map(Election::getElectionId).collect(Collectors.toList())); assertTrue(referenceIds.contains(dar.getReferenceId())); - assertEquals(2, createdElections.size()); // + assertEquals(2, createdElections.size()); // // Ensure that we have an access and rp election assertFalse(createdElections.isEmpty()); assertTrue( @@ -245,38 +247,47 @@ void testCreateElectionsForDarCollectionWithMultipleDatasetsForChairBy() throws assertFalse(createdVotes.isEmpty()); assertTrue( createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.CHAIRPERSON.getValue()))); - assertTrue( - createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); - assertTrue( - createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); + assertTrue(createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.FINAL.getValue()))); + assertTrue(createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.DAC.getValue()))); assertTrue( createdVotes.stream().anyMatch(v -> v.getType().equals(VoteType.AGREEMENT.getValue()))); - assertEquals(8, createdVotes.size()); // 1 dataset X 2 elections/dataset X 4 votes/election each = 8 votes. + assertEquals( + 8, + createdVotes.size()); // 1 dataset X 2 elections/dataset X 4 votes/election each = 8 votes. // Find the dac chairperson for the second Dataset in the DAR. Dac dac2 = dacDAO.findDacsForDatasetIds(List.of(datasetId2)).stream().findFirst().orElseThrow(); assertNotNull(dac2); List dacUsers2 = dacDAO.findMembersByDacId(dac2.getDacId()); - User chair2 = dacUsers2.stream().filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) - .findFirst().orElseThrow(); + User chair2 = + dacUsers2.stream() + .filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) + .findFirst() + .orElseThrow(); List referenceIds2 = serviceDAO.createElectionsForDarByUser(chair2, dar); assertTrue(referenceIds2.contains(dar.getReferenceId())); - createdElections = - electionDAO.findElectionsByReferenceId(dar.getReferenceId()); + createdElections = electionDAO.findElectionsByReferenceId(dar.getReferenceId()); assertEquals(4, createdElections.size()); // Verify we have elections for both DACs - assertTrue(createdElections.stream().anyMatch(e -> e.getDatasetId().equals(dac.getDatasetIds().get(0)))); - assertTrue(createdElections.stream().anyMatch(e -> e.getDatasetId().equals(dac2.getDatasetIds().get(0)))); + assertTrue( + createdElections.stream() + .anyMatch(e -> e.getDatasetId().equals(dac.getDatasetIds().get(0)))); + assertTrue( + createdElections.stream() + .anyMatch(e -> e.getDatasetId().equals(dac2.getDatasetIds().get(0)))); // Verify we have open votes for both datasets on the DAR. createdVotes = voteDAO.findVotesByElectionIds( createdElections.stream().map(Election::getElectionId).toList()); - assertEquals(16, createdVotes.size()); // 2 datasets X 2 elections/dataset X 4 votes/election each = 16 votes. + assertEquals( + 16, + createdVotes + .size()); // 2 datasets X 2 elections/dataset X 4 votes/election each = 16 votes. } @Test @@ -290,8 +301,11 @@ void testCreateElectionsForProgressReportWithMultipleDatasets() throws SQLExcept // Find the dac chairperson for the current DAR/Dataset combination Dac dac = dacDAO.findDacsForDatasetIds(List.of(datasetId)).stream().findFirst().orElseThrow(); List dacUsers = dacDAO.findMembersByDacId(dac.getDacId()); - User chair = dacUsers.stream().filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) - .findFirst().orElseThrow(); + User chair = + dacUsers.stream() + .filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) + .findFirst() + .orElseThrow(); // Refresh the collection collection = darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId()); @@ -303,7 +317,8 @@ void testCreateElectionsForProgressReportWithMultipleDatasets() throws SQLExcept // Refresh the collection to get the version with the progress report. collection = darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId()); - List electionReferenceIds = serviceDAO.createElectionsForDarByUser(chair, collection.getMostRecentDar()); + List electionReferenceIds = + serviceDAO.createElectionsForDarByUser(chair, collection.getMostRecentDar()); assertTrue(electionReferenceIds.contains(progressReport.getReferenceId())); } @@ -325,13 +340,12 @@ void testCreateElectionsForDarCollectionAfterCancelingEarlierElectionsAsAdminBy( List referenceIds = serviceDAO.createElectionsForDarByUser(user, dar); // cancel those elections: - List canceledElectionIds = electionDAO.findLastElectionsByReferenceIds( - List.of(dar.getReferenceId())) - .stream() - .map(Election::getElectionId) - .toList(); - canceledElectionIds.forEach(id -> - electionDAO.updateElectionById(id, ElectionStatus.CANCELED.getValue(), new Date())); + List canceledElectionIds = + electionDAO.findLastElectionsByReferenceIds(List.of(dar.getReferenceId())).stream() + .map(Election::getElectionId) + .toList(); + canceledElectionIds.forEach( + id -> electionDAO.updateElectionById(id, ElectionStatus.CANCELED.getValue(), new Date())); // re-create elections & new votes: referenceIds.addAll(serviceDAO.createElectionsForDarByUser(user, dar)); @@ -344,10 +358,16 @@ void testCreateElectionsForDarCollectionAfterCancelingEarlierElectionsAsAdminBy( // Ensure that we have the right number of access and rp elections, i.e. 1 each assertFalse(createdElections.isEmpty()); assertEquals(2, createdElections.size()); - assertEquals(1, createdElections.stream().filter(e -> e.getElectionType().equals( - ElectionType.DATA_ACCESS.getValue())).count()); - assertEquals(1, createdElections.stream().filter(e -> e.getElectionType().equals( - ElectionType.RP.getValue())).count()); + assertEquals( + 1, + createdElections.stream() + .filter(e -> e.getElectionType().equals(ElectionType.DATA_ACCESS.getValue())) + .count()); + assertEquals( + 1, + createdElections.stream() + .filter(e -> e.getElectionType().equals(ElectionType.RP.getValue())) + .count()); // Check that the canceled elections are archived List canceledElections = electionDAO.findElectionsByIds(canceledElectionIds); @@ -375,8 +395,8 @@ void testCreateElectionsForDarCollectionAfterCancelingEarlierElectionsAsChairBy( Optional dac = dacDAO.findDacsForDatasetIds(List.of(datasetId)).stream().findFirst(); assertTrue(dac.isPresent()); List dacUsers = dacDAO.findMembersByDacId(dac.get().getDacId()); - Optional chair = dacUsers.stream().filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)) - .findFirst(); + Optional chair = + dacUsers.stream().filter(u -> u.hasUserRole(UserRoles.CHAIRPERSON)).findFirst(); assertTrue(chair.isPresent()); // refresh the collection @@ -386,11 +406,19 @@ void testCreateElectionsForDarCollectionAfterCancelingEarlierElectionsAsChairBy( List referenceIds = serviceDAO.createElectionsForDarByUser(chair.get(), dar); // cancel elections for all DARs in the collection: - collection.getDars().values().forEach(d -> - electionDAO.findLastElectionsByReferenceIds(List.of(d.getReferenceId())).forEach(e -> - electionDAO.updateElectionById(e.getElectionId(), ElectionStatus.CANCELED.getValue(), - new Date())) - ); + collection + .getDars() + .values() + .forEach( + d -> + electionDAO + .findLastElectionsByReferenceIds(List.of(d.getReferenceId())) + .forEach( + e -> + electionDAO.updateElectionById( + e.getElectionId(), + ElectionStatus.CANCELED.getValue(), + new Date()))); // re-create elections & new votes: referenceIds.addAll(serviceDAO.createElectionsForDarByUser(chair.get(), dar)); @@ -401,15 +429,22 @@ void testCreateElectionsForDarCollectionAfterCancelingEarlierElectionsAsChairBy( // Ensure that we have the right number of access and rp elections, i.e. 1 each assertFalse(createdElections.isEmpty()); assertEquals(2, createdElections.size()); - assertEquals(1, createdElections.stream().filter(e -> e.getElectionType().equals( - ElectionType.DATA_ACCESS.getValue())).count()); - assertEquals(1, createdElections.stream().filter(e -> e.getElectionType().equals( - ElectionType.RP.getValue())).count()); + assertEquals( + 1, + createdElections.stream() + .filter(e -> e.getElectionType().equals(ElectionType.DATA_ACCESS.getValue())) + .count()); + assertEquals( + 1, + createdElections.stream() + .filter(e -> e.getElectionType().equals(ElectionType.RP.getValue())) + .count()); - //create progress report + // create progress report createProgressReportFromDAR(dar); collection = darCollectionDAO.findDARCollectionByCollectionId(collection.getDarCollectionId()); - List createdElectionsForProgressReport = serviceDAO.createElectionsForDarByUser(chair.get(), collection.getMostRecentDar()); + List createdElectionsForProgressReport = + serviceDAO.createElectionsForDarByUser(chair.get(), collection.getMostRecentDar()); assertFalse(createdElectionsForProgressReport.isEmpty()); assertEquals(1, createdElectionsForProgressReport.size()); } @@ -424,27 +459,28 @@ private DataAccessRequest createProgressReportFromDAR(DataAccessRequest dar) { dar.getData(), randomAlphabetic(8)); DataAccessRequest progressReport = dataAccessRequestDAO.findByReferenceId(referenceId); - dar.getDatasetIds().forEach(datasetId -> - dataAccessRequestDAO.insertDARDatasetRelation(referenceId, datasetId) - ); + dar.getDatasetIds() + .forEach( + datasetId -> dataAccessRequestDAO.insertDARDatasetRelation(referenceId, datasetId)); return progressReport; } - /** - * Helper method to generate a DarCollection with a Dac, a Dataset, and a create User - */ + + /** Helper method to generate a DarCollection with a Dac, a Dataset, and a create User */ private DarCollection setUpDarCollectionWithDacDataset() { User user = createUser(); String darCode = "DAR-" + RandomUtils.nextInt(100, 1000); DacAndDataset dacAndDataset = createDacAndDataset(); DacAndDataset dacAndDataset2 = createDacAndDataset(); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); createDarForCollection(user, collectionId, dacAndDataset.dataset); DarCollection collection = darCollectionDAO.findDARCollectionByCollectionId(collectionId); DataAccessRequest dar = collection.getDars().values().stream().findFirst().orElseThrow(); assertNotNull(dar.getData()); - dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dacAndDataset.dataset.getDatasetId()); - dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dacAndDataset2.dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + dar.getReferenceId(), dacAndDataset.dataset.getDatasetId()); + dataAccessRequestDAO.insertDARDatasetRelation( + dar.getReferenceId(), dacAndDataset2.dataset.getDatasetId()); Date now = new Date(); dataAccessRequestDAO.updateDataByReferenceId( dar.getReferenceId(), dar.getUserId(), now, now, dar.getData(), user.getEraCommonsId()); @@ -462,10 +498,11 @@ private DacAndDataset createDacAndDataset() { } private Dac createDac() { - Integer id = dacDAO.createDac( - "Test_" + RandomStringUtils.random(20, true, true), - "Test_" + RandomStringUtils.random(20, true, true), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + RandomStringUtils.random(20, true, true), + "Test_" + RandomStringUtils.random(20, true, true), + new Date()); return dacDAO.findById(id); } @@ -480,18 +517,18 @@ private void createDatasetProperties(Integer datasetId) { datasetDAO.insertDatasetProperties(list); } - private DataAccessRequest createDarForCollection(User user, Integer collectionId, - Dataset dataset) { + private DataAccessRequest createDarForCollection( + User user, Integer collectionId, Dataset dataset) { Date now = new Date(); DataAccessRequest dar = new DataAccessRequest(); dar.setReferenceId(UUID.randomUUID().toString()); DataAccessRequestData data = new DataAccessRequestData(); dar.setData(data); - dataAccessRequestDAO.insertDraftDataAccessRequest(dar.getReferenceId(), user.getUserId(), now, - now, data); + dataAccessRequestDAO.insertDraftDataAccessRequest( + dar.getReferenceId(), user.getUserId(), now, now, data); dataAccessRequestDAO.updateDraftToSubmittedForCollection(collectionId, dar.getReferenceId()); - dataAccessRequestDAO.updateDataByReferenceId(dar.referenceId, dar.userId, new Date(), - new Date(), data, user.getEraCommonsId()); + dataAccessRequestDAO.updateDataByReferenceId( + dar.referenceId, dar.userId, new Date(), new Date(), data, user.getEraCommonsId()); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset.getDatasetId()); return dataAccessRequestDAO.findByReferenceId(dar.getReferenceId()); } @@ -502,8 +539,8 @@ private Dataset createDatasetWithDac(Integer dacId) { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + RandomStringUtils.random(20, true, true); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), dacId); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), dacId); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAOTest.java index d2dcdf28de..4e47a70c4b 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/DataAccessRequestServiceDAOTest.java @@ -56,8 +56,15 @@ void testUpdateByReferenceId() throws Exception { DarDataset oldDarDatasetTwo = new DarDataset(referenceId, datasetTwo.getDatasetId()); DarCollection collection = createDarCollection(); Integer collectionId = collection.getDarCollectionId(); - dataAccessRequestDAO.insertDataAccessRequest(collectionId, referenceId, user.getUserId(), old, - old, old, new DataAccessRequestData(), user.getEraCommonsId()); + dataAccessRequestDAO.insertDataAccessRequest( + collectionId, + referenceId, + user.getUserId(), + old, + old, + old, + new DataAccessRequestData(), + user.getEraCommonsId()); dataAccessRequestDAO.insertAllDarDatasets(List.of(oldDarDataset, oldDarDatasetTwo)); DataAccessRequest dar = new DataAccessRequest(); @@ -92,8 +99,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -112,13 +119,13 @@ private void createDatasetProperties(Integer datasetId) { private DarCollection createDarCollection() { User user = createUserWithInstitution(); String darCode = "DAR-" + randomInt(1, 10000); - Integer collectionId = darCollectionDAO.insertDarCollection(darCode, user.getUserId(), - new Date()); + Integer collectionId = + darCollectionDAO.insertDarCollection(darCode, user.getUserId(), new Date()); Dataset dataset = createDataset(); DataAccessRequest dar = createDataAccessRequest(user.getUserId(), collectionId); dataAccessRequestDAO.insertDARDatasetRelation(dar.getReferenceId(), dataset.getDatasetId()); - Election cancelled = createCancelledAccessElection(dar.getReferenceId(), - dataset.getDatasetId()); + Election cancelled = + createCancelledAccessElection(dar.getReferenceId(), dataset.getDatasetId()); Election access = createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); createFinalVote(user.getUserId(), cancelled.getElectionId()); createFinalVote(user.getUserId(), access.getElectionId()); @@ -128,13 +135,13 @@ private DarCollection createDarCollection() { } private Election createCancelledAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.CANCELED.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.CANCELED.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } @@ -151,12 +158,7 @@ private DataAccessRequest createDataAccessRequest(Integer userId, Integer collec String referenceId = UUID.randomUUID().toString(); Date now = new Date(); dataAccessRequestDAO.insertDataAccessRequest( - collectionId, - referenceId, - userId, - now, now, now, - data, - randomAlphabetic(10)); + collectionId, referenceId, userId, now, now, now, data, randomAlphabetic(10)); return dataAccessRequestDAO.findByReferenceId(referenceId); } @@ -165,13 +167,13 @@ private void createFinalVote(Integer userId, Integer electionId) { } private Election createDataAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAOTest.java index 24433025d8..ae3710c1cf 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/DatasetServiceDAOTest.java @@ -86,18 +86,17 @@ void testInsertDatasets() throws Exception { FileStorageObject file1 = new FileStorageObject(); file1.setMediaType(randomAlphabetic(20)); file1.setCategory(FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); - file1.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + file1.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); file1.setFileName(randomAlphabetic(10)); - DatasetServiceDAO.DatasetInsert insert = new DatasetServiceDAO.DatasetInsert( - randomAlphabetic(20), - dac.getDacId(), - new DataUseBuilder().setStigmatizeDiseases(true).setGeneralUse(true).build(), - user.getUserId(), - List.of(prop1, prop2), - List.of(file1)); + DatasetServiceDAO.DatasetInsert insert = + new DatasetServiceDAO.DatasetInsert( + randomAlphabetic(20), + dac.getDacId(), + new DataUseBuilder().setStigmatizeDiseases(true).setGeneralUse(true).build(), + user.getUserId(), + List.of(prop1, prop2), + List.of(file1)); List createdIds = serviceDAO.insertDatasetRegistration(null, List.of(insert)); @@ -110,10 +109,16 @@ void testInsertDatasets() throws Exception { assertEquals(2, created.getProperties().size()); - DatasetProperty createdProp1 = created.getProperties().stream() - .filter((p) -> p.getPropertyName().equals(prop1.getPropertyName())).findFirst().get(); - DatasetProperty createdProp2 = created.getProperties().stream() - .filter((p) -> p.getPropertyName().equals(prop2.getPropertyName())).findFirst().get(); + DatasetProperty createdProp1 = + created.getProperties().stream() + .filter((p) -> p.getPropertyName().equals(prop1.getPropertyName())) + .findFirst() + .get(); + DatasetProperty createdProp2 = + created.getProperties().stream() + .filter((p) -> p.getPropertyName().equals(prop2.getPropertyName())) + .findFirst() + .get(); assertEquals(created.getDatasetId(), createdProp1.getDatasetId()); assertEquals(prop1.getPropertyValue(), createdProp1.getPropertyValue()); @@ -125,13 +130,10 @@ void testInsertDatasets() throws Exception { assertNotNull(created.getNihInstitutionalCertificationFile()); - assertEquals(file1.getFileName(), - created.getNihInstitutionalCertificationFile().getFileName()); - assertEquals(file1.getBlobId(), - created.getNihInstitutionalCertificationFile().getBlobId()); + assertEquals(file1.getFileName(), created.getNihInstitutionalCertificationFile().getFileName()); + assertEquals(file1.getBlobId(), created.getNihInstitutionalCertificationFile().getBlobId()); } - @Test void testInsertMultipleDatasets() throws Exception { @@ -144,31 +146,33 @@ void testInsertMultipleDatasets() throws Exception { prop1.setPropertyValue(new Random().nextInt()); prop1.setPropertyType(PropertyType.Number); - DatasetServiceDAO.DatasetInsert insert1 = new DatasetServiceDAO.DatasetInsert( - randomAlphabetic(20), - dac.getDacId(), - new DataUseBuilder().setGeneralUse(true).build(), - user.getUserId(), - List.of(), - List.of()); - - DatasetServiceDAO.DatasetInsert insert2 = new DatasetServiceDAO.DatasetInsert( - randomAlphabetic(20), - dac.getDacId(), - new DataUseBuilder().setIllegalBehavior(true).build(), - user.getUserId(), - List.of(prop1), - List.of()); - - List createdIds = serviceDAO.insertDatasetRegistration(null, - List.of(insert1, insert2)); + DatasetServiceDAO.DatasetInsert insert1 = + new DatasetServiceDAO.DatasetInsert( + randomAlphabetic(20), + dac.getDacId(), + new DataUseBuilder().setGeneralUse(true).build(), + user.getUserId(), + List.of(), + List.of()); + + DatasetServiceDAO.DatasetInsert insert2 = + new DatasetServiceDAO.DatasetInsert( + randomAlphabetic(20), + dac.getDacId(), + new DataUseBuilder().setIllegalBehavior(true).build(), + user.getUserId(), + List.of(prop1), + List.of()); + + List createdIds = + serviceDAO.insertDatasetRegistration(null, List.of(insert1, insert2)); List datasets = datasetDAO.findDatasetsByIdList(createdIds); assertEquals(2, datasets.size()); - Optional ds1Optional = datasets.stream() - .filter(d -> d.getName().equals(insert1.name())).findFirst(); + Optional ds1Optional = + datasets.stream().filter(d -> d.getName().equals(insert1.name())).findFirst(); assertTrue(ds1Optional.isPresent()); Dataset dataset1 = ds1Optional.get(); @@ -178,8 +182,8 @@ void testInsertMultipleDatasets() throws Exception { assertNull(dataset1.getProperties()); assertNull(dataset1.getNihInstitutionalCertificationFile()); - Optional ds2Optional = datasets.stream() - .filter(d -> d.getName().equals(insert2.name())).findFirst(); + Optional ds2Optional = + datasets.stream().filter(d -> d.getName().equals(insert2.name())).findFirst(); assertTrue(ds2Optional.isPresent()); Dataset dataset2 = ds2Optional.get(); @@ -195,26 +199,28 @@ void testInsertStudyWithDatasets() throws Exception { Dac dac = createDac(); User user = createUser(); - DatasetServiceDAO.StudyInsert studyInsert = new DatasetServiceDAO.StudyInsert( - randomAlphabetic(10), - randomAlphabetic(10), - List.of(randomAlphabetic(10)), - randomAlphabetic(10), - true, - user.getUserId(), - List.of(), - List.of()); - - DatasetServiceDAO.DatasetInsert datasetInsert = new DatasetServiceDAO.DatasetInsert( - randomAlphabetic(20), - dac.getDacId(), - new DataUseBuilder().setGeneralUse(true).build(), - user.getUserId(), - List.of(), - List.of()); - - List createdIds = serviceDAO.insertDatasetRegistration(studyInsert, - List.of(datasetInsert)); + DatasetServiceDAO.StudyInsert studyInsert = + new DatasetServiceDAO.StudyInsert( + randomAlphabetic(10), + randomAlphabetic(10), + List.of(randomAlphabetic(10)), + randomAlphabetic(10), + true, + user.getUserId(), + List.of(), + List.of()); + + DatasetServiceDAO.DatasetInsert datasetInsert = + new DatasetServiceDAO.DatasetInsert( + randomAlphabetic(20), + dac.getDacId(), + new DataUseBuilder().setGeneralUse(true).build(), + user.getUserId(), + List.of(), + List.of()); + + List createdIds = + serviceDAO.insertDatasetRegistration(studyInsert, List.of(datasetInsert)); List datasets = datasetDAO.findDatasetsByIdList(createdIds); @@ -251,26 +257,28 @@ void testInsertStudyWithProps() throws Exception { prop2.setType(PropertyType.Number); prop2.setValue(new Random().nextInt()); - DatasetServiceDAO.StudyInsert studyInsert = new DatasetServiceDAO.StudyInsert( - randomAlphabetic(10), - randomAlphabetic(10), - List.of(randomAlphabetic(10)), - randomAlphabetic(10), - true, - user.getUserId(), - List.of(prop1, prop2), - List.of()); - - DatasetServiceDAO.DatasetInsert datasetInsert = new DatasetServiceDAO.DatasetInsert( - randomAlphabetic(20), - dac.getDacId(), - new DataUseBuilder().setGeneralUse(true).build(), - user.getUserId(), - List.of(), - List.of()); - - List createdIds = serviceDAO.insertDatasetRegistration(studyInsert, - List.of(datasetInsert)); + DatasetServiceDAO.StudyInsert studyInsert = + new DatasetServiceDAO.StudyInsert( + randomAlphabetic(10), + randomAlphabetic(10), + List.of(randomAlphabetic(10)), + randomAlphabetic(10), + true, + user.getUserId(), + List.of(prop1, prop2), + List.of()); + + DatasetServiceDAO.DatasetInsert datasetInsert = + new DatasetServiceDAO.DatasetInsert( + randomAlphabetic(20), + dac.getDacId(), + new DataUseBuilder().setGeneralUse(true).build(), + user.getUserId(), + List.of(), + List.of()); + + List createdIds = + serviceDAO.insertDatasetRegistration(studyInsert, List.of(datasetInsert)); List datasets = datasetDAO.findDatasetsByIdList(createdIds); @@ -288,10 +296,16 @@ void testInsertStudyWithProps() throws Exception { assertEquals(studyInsert.userId(), s.getCreateUserId()); assertNotNull(s.getCreateDate()); - StudyProperty createdProp1 = dataset1.getStudy().getProperties().stream() - .filter((p) -> p.getKey().equals(prop1.getKey())).findFirst().get(); - StudyProperty createdProp2 = dataset1.getStudy().getProperties().stream() - .filter((p) -> p.getKey().equals(prop2.getKey())).findFirst().get(); + StudyProperty createdProp1 = + dataset1.getStudy().getProperties().stream() + .filter((p) -> p.getKey().equals(prop1.getKey())) + .findFirst() + .get(); + StudyProperty createdProp2 = + dataset1.getStudy().getProperties().stream() + .filter((p) -> p.getKey().equals(prop2.getKey())) + .findFirst() + .get(); assertEquals(prop1.getType(), createdProp1.getType()); assertEquals(prop1.getValue(), createdProp1.getValue()); @@ -319,31 +333,31 @@ void testInsertStudyWithAlternativeDataSharingFile() throws Exception { FileStorageObject file = new FileStorageObject(); file.setMediaType(randomAlphabetic(20)); file.setCategory(FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - file.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + file.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); file.setFileName(randomAlphabetic(10)); - DatasetServiceDAO.StudyInsert studyInsert = new DatasetServiceDAO.StudyInsert( - randomAlphabetic(10), - randomAlphabetic(10), - List.of(randomAlphabetic(10)), - randomAlphabetic(10), - true, - user.getUserId(), - List.of(prop1, prop2), - List.of(file)); - - DatasetServiceDAO.DatasetInsert datasetInsert = new DatasetServiceDAO.DatasetInsert( - randomAlphabetic(20), - dac.getDacId(), - new DataUseBuilder().setGeneralUse(true).build(), - user.getUserId(), - List.of(), - List.of()); - - List createdIds = serviceDAO.insertDatasetRegistration(studyInsert, - List.of(datasetInsert)); + DatasetServiceDAO.StudyInsert studyInsert = + new DatasetServiceDAO.StudyInsert( + randomAlphabetic(10), + randomAlphabetic(10), + List.of(randomAlphabetic(10)), + randomAlphabetic(10), + true, + user.getUserId(), + List.of(prop1, prop2), + List.of(file)); + + DatasetServiceDAO.DatasetInsert datasetInsert = + new DatasetServiceDAO.DatasetInsert( + randomAlphabetic(20), + dac.getDacId(), + new DataUseBuilder().setGeneralUse(true).build(), + user.getUserId(), + List.of(), + List.of()); + + List createdIds = + serviceDAO.insertDatasetRegistration(studyInsert, List.of(datasetInsert)); List datasets = datasetDAO.findDatasetsByIdList(createdIds); @@ -361,10 +375,16 @@ void testInsertStudyWithAlternativeDataSharingFile() throws Exception { assertEquals(studyInsert.userId(), s.getCreateUserId()); assertNotNull(s.getCreateDate()); - StudyProperty createdProp1 = dataset1.getStudy().getProperties().stream() - .filter((p) -> p.getKey().equals(prop1.getKey())).findFirst().get(); - StudyProperty createdProp2 = dataset1.getStudy().getProperties().stream() - .filter((p) -> p.getKey().equals(prop2.getKey())).findFirst().get(); + StudyProperty createdProp1 = + dataset1.getStudy().getProperties().stream() + .filter((p) -> p.getKey().equals(prop1.getKey())) + .findFirst() + .get(); + StudyProperty createdProp2 = + dataset1.getStudy().getProperties().stream() + .filter((p) -> p.getKey().equals(prop2.getKey())) + .findFirst() + .get(); assertEquals(prop1.getType(), createdProp1.getType()); assertEquals(prop1.getValue(), createdProp1.getValue()); @@ -374,17 +394,16 @@ void testInsertStudyWithAlternativeDataSharingFile() throws Exception { assertNotNull(s.getAlternativeDataSharingPlan()); assertEquals(file.getBlobId(), s.getAlternativeDataSharingPlan().getBlobId()); - assertEquals(file.getFileName(), - s.getAlternativeDataSharingPlan().getFileName()); - assertEquals(file.getCategory(), - s.getAlternativeDataSharingPlan().getCategory()); + assertEquals(file.getFileName(), s.getAlternativeDataSharingPlan().getFileName()); + assertEquals(file.getCategory(), s.getAlternativeDataSharingPlan().getCategory()); // Validate that an audit record was added for each dataset - datasets.forEach(d -> { - List audits = datasetDAO.findAuditsByDatasetId(d.getDatasetId()); - assertEquals(1, audits.size()); - assertEquals(AuditActions.CREATE.name(), audits.get(0).getAction()); - }); + datasets.forEach( + d -> { + List audits = datasetDAO.findAuditsByDatasetId(d.getDatasetId()); + assertEquals(1, audits.size()); + assertEquals(AuditActions.CREATE.name(), audits.get(0).getAction()); + }); } @Test @@ -442,27 +461,35 @@ void testUpdateDatasetWithProps() throws Exception { prop4.setCreateDate(new Date()); String newName = "New Name"; - DatasetUpdate updates = new DatasetUpdate( - dataset.getDatasetId(), - newName, - dataset.getCreateUserId(), - dataset.getDacId(), - List.of(updateProp1, updateProp2, prop4), - List.of() - ); + DatasetUpdate updates = + new DatasetUpdate( + dataset.getDatasetId(), + newName, + dataset.getCreateUserId(), + dataset.getDacId(), + List.of(updateProp1, updateProp2, prop4), + List.of()); serviceDAO.updateDataset(updates); // Validate that the dataset props have been updated, deleted, or added: - Set updatedProps = datasetDAO.findDatasetPropertiesByDatasetId( - dataset.getDatasetId()); - Optional updated1 = updatedProps.stream() - .filter(p -> p.getPropertyName().equals(prop1.getPropertyName())).findFirst(); - Optional updated2 = updatedProps.stream() - .filter(p -> p.getPropertyName().equals(prop2.getPropertyName())).findFirst(); - Optional deleted3 = updatedProps.stream() - .filter(p -> p.getPropertyName().equals(prop3.getPropertyName())).findFirst(); - Optional added4 = updatedProps.stream() - .filter(p -> p.getPropertyName().equals(prop4.getPropertyName())).findFirst(); + Set updatedProps = + datasetDAO.findDatasetPropertiesByDatasetId(dataset.getDatasetId()); + Optional updated1 = + updatedProps.stream() + .filter(p -> p.getPropertyName().equals(prop1.getPropertyName())) + .findFirst(); + Optional updated2 = + updatedProps.stream() + .filter(p -> p.getPropertyName().equals(prop2.getPropertyName())) + .findFirst(); + Optional deleted3 = + updatedProps.stream() + .filter(p -> p.getPropertyName().equals(prop3.getPropertyName())) + .findFirst(); + Optional added4 = + updatedProps.stream() + .filter(p -> p.getPropertyName().equals(prop4.getPropertyName())) + .findFirst(); assertTrue(updated1.isPresent()); assertEquals(updateProp1.getPropertyValueAsString(), updated1.get().getPropertyValueAsString()); assertTrue(updated2.isPresent()); @@ -488,17 +515,17 @@ void testUpdateStudyDetails() throws Exception { String newStudyDescription = "New Study Description"; String newPIName = "New PI Name"; List newDataTypes = List.of("DT 1", "DT 2", "DT 3"); - StudyUpdate studyUpdate = new StudyUpdate( - newStudyName, - study.getStudyId(), - newStudyDescription, - newDataTypes, - newPIName, - !study.getPublicVisibility(), - study.getCreateUserId(), - List.copyOf(study.getProperties()), - List.of() - ); + StudyUpdate studyUpdate = + new StudyUpdate( + newStudyName, + study.getStudyId(), + newStudyDescription, + newDataTypes, + newPIName, + !study.getPublicVisibility(), + study.getCreateUserId(), + List.copyOf(study.getProperties()), + List.of()); Study updatedStudy = serviceDAO.updateStudy(studyUpdate, List.of(), List.of()); assertEquals(newStudyName, updatedStudy.getName()); @@ -507,13 +534,16 @@ void testUpdateStudyDetails() throws Exception { assertEquals(newDataTypes, updatedStudy.getDataTypes()); // Validate that NO update records were added for each dataset - updatedStudy.getDatasetIds().forEach(id -> { - List audits = datasetDAO.findAuditsByDatasetId(id); - assertFalse(audits.isEmpty()); - assertFalse( - audits.stream() - .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.UPDATE.name()))); - }); + updatedStudy + .getDatasetIds() + .forEach( + id -> { + List audits = datasetDAO.findAuditsByDatasetId(id); + assertFalse(audits.isEmpty()); + assertFalse( + audits.stream() + .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.UPDATE.name()))); + }); } @Test @@ -531,37 +561,44 @@ void testUpdateStudyWithPropUpdates() throws Exception { prop1.setValue(newPropValue); // Create a study update with a changed prop, a new prop, and a to-be-deleted prop - StudyUpdate studyUpdate = new StudyUpdate( - study.getName(), - study.getStudyId(), - study.getDescription(), - study.getDataTypes(), - study.getPiName(), - !study.getPublicVisibility(), - study.getCreateUserId(), - List.of(newProp, prop1), - List.of() - ); + StudyUpdate studyUpdate = + new StudyUpdate( + study.getName(), + study.getStudyId(), + study.getDescription(), + study.getDataTypes(), + study.getPiName(), + !study.getPublicVisibility(), + study.getCreateUserId(), + List.of(newProp, prop1), + List.of()); Study updatedStudy = serviceDAO.updateStudy(studyUpdate, List.of(), List.of()); // Updated prop - Optional updatedProp1 = updatedStudy.getProperties().stream() - .filter(p -> p.getStudyPropertyId().equals(prop1.getStudyPropertyId())).findFirst(); + Optional updatedProp1 = + updatedStudy.getProperties().stream() + .filter(p -> p.getStudyPropertyId().equals(prop1.getStudyPropertyId())) + .findFirst(); assertTrue(updatedProp1.isPresent()); assertEquals(newPropValue, updatedProp1.get().getValue()); // Added prop - Optional addedNewProp = updatedStudy.getProperties().stream() - .filter(p -> newProp.getValue().equals(p.getValue())).findFirst(); + Optional addedNewProp = + updatedStudy.getProperties().stream() + .filter(p -> newProp.getValue().equals(p.getValue())) + .findFirst(); assertTrue(addedNewProp.isPresent()); // Validate that NO update records were added for each dataset - updatedStudy.getDatasetIds().forEach(id -> { - List audits = datasetDAO.findAuditsByDatasetId(id); - assertFalse(audits.isEmpty()); - assertFalse( - audits.stream() - .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.UPDATE.name()))); - }); + updatedStudy + .getDatasetIds() + .forEach( + id -> { + List audits = datasetDAO.findAuditsByDatasetId(id); + assertFalse(audits.isEmpty()); + assertFalse( + audits.stream() + .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.UPDATE.name()))); + }); } @Test @@ -569,55 +606,58 @@ void testUpdateStudyWithDatasetUpdates() throws Exception { Study study = createStudy(null); Dataset dataset = datasetDAO.findDatasetsByIdList(List.copyOf(study.getDatasetIds())).get(0); - StudyUpdate studyUpdate = new StudyUpdate( - study.getName(), - study.getStudyId(), - study.getDescription(), - study.getDataTypes(), - study.getPiName(), - !study.getPublicVisibility(), - study.getCreateUserId(), - List.copyOf(study.getProperties()), - List.of() - ); + StudyUpdate studyUpdate = + new StudyUpdate( + study.getName(), + study.getStudyId(), + study.getDescription(), + study.getDataTypes(), + study.getPiName(), + !study.getPublicVisibility(), + study.getCreateUserId(), + List.copyOf(study.getProperties()), + List.of()); String newDatasetName = "New Dataset Name"; - DatasetUpdate datasetUpdate = new DatasetUpdate( - dataset.getDatasetId(), - newDatasetName, - study.getCreateUserId(), - dataset.getDacId(), - List.copyOf(dataset.getProperties()), - List.of() - ); + DatasetUpdate datasetUpdate = + new DatasetUpdate( + dataset.getDatasetId(), + newDatasetName, + study.getCreateUserId(), + dataset.getDacId(), + List.copyOf(dataset.getProperties()), + List.of()); String newInsertName = "New Dataset Insert Name"; - DatasetInsert datasetInsert = new DatasetInsert( - newInsertName, - dataset.getDacId(), - new DataUseBuilder().setGeneralUse(true).build(), - study.getCreateUserId(), - List.of(), - List.of() - ); - - Study updatedStudy = serviceDAO.updateStudy(studyUpdate, List.of(datasetUpdate), - List.of(datasetInsert)); - List updatedDatasets = datasetDAO.findDatasetsByIdList( - new ArrayList<>(updatedStudy.getDatasetIds())); + DatasetInsert datasetInsert = + new DatasetInsert( + newInsertName, + dataset.getDacId(), + new DataUseBuilder().setGeneralUse(true).build(), + study.getCreateUserId(), + List.of(), + List.of()); + + Study updatedStudy = + serviceDAO.updateStudy(studyUpdate, List.of(datasetUpdate), List.of(datasetInsert)); + List updatedDatasets = + datasetDAO.findDatasetsByIdList(new ArrayList<>(updatedStudy.getDatasetIds())); assertTrue(updatedDatasets.contains(dataset)); assertEquals(updatedStudy.getDatasetIds().size(), updatedDatasets.size()); assertTrue(updatedDatasets.stream().anyMatch(d -> d.getDatasetName().equals(newDatasetName))); assertTrue(updatedDatasets.stream().anyMatch(d -> d.getDatasetName().equals(newInsertName))); // Validate that update records were added for each dataset - updatedStudy.getDatasetIds().forEach(id -> { - List audits = datasetDAO.findAuditsByDatasetId(id); - assertFalse(audits.isEmpty()); - assertTrue( - audits.stream() - .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.CREATE.name()))); - }); + updatedStudy + .getDatasetIds() + .forEach( + id -> { + List audits = datasetDAO.findAuditsByDatasetId(id); + assertFalse(audits.isEmpty()); + assertTrue( + audits.stream() + .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.CREATE.name()))); + }); } @Test @@ -625,91 +665,81 @@ void testUpdateStudyWithFileUpdates() throws Exception { FileStorageObject fso1 = new FileStorageObject(); fso1.setMediaType(randomAlphabetic(20)); fso1.setCategory(FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - fso1.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + fso1.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); fso1.setFileName(randomAlphabetic(10)); FileStorageObject fso2 = new FileStorageObject(); fso2.setMediaType(randomAlphabetic(20)); fso2.setCategory(FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); - fso2.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + fso2.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); fso2.setFileName(randomAlphabetic(10)); Study study = createStudy(List.of(fso1, fso2)); FileStorageObject updatedFso1 = new FileStorageObject(); updatedFso1.setMediaType(randomAlphabetic(20)); updatedFso1.setCategory(FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - updatedFso1.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + updatedFso1.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); updatedFso1.setFileName(randomAlphabetic(10)); FileStorageObject updatedFso2 = new FileStorageObject(); updatedFso2.setMediaType(randomAlphabetic(20)); updatedFso2.setCategory(FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); - updatedFso2.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + updatedFso2.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); updatedFso2.setFileName(randomAlphabetic(10)); - StudyUpdate studyUpdate = new StudyUpdate( - study.getName(), - study.getStudyId(), - study.getDescription(), - study.getDataTypes(), - study.getPiName(), - !study.getPublicVisibility(), - study.getCreateUserId(), - List.copyOf(study.getProperties()), - List.of(updatedFso1, updatedFso2) - ); + StudyUpdate studyUpdate = + new StudyUpdate( + study.getName(), + study.getStudyId(), + study.getDescription(), + study.getDataTypes(), + study.getPiName(), + !study.getPublicVisibility(), + study.getCreateUserId(), + List.copyOf(study.getProperties()), + List.of(updatedFso1, updatedFso2)); Study updatedStudy = serviceDAO.updateStudy(studyUpdate, List.of(), List.of()); assertNotNull(updatedStudy.getAlternativeDataSharingPlan()); - assertEquals(updatedFso1.getFileName(), - updatedStudy.getAlternativeDataSharingPlan().getFileName()); + assertEquals( + updatedFso1.getFileName(), updatedStudy.getAlternativeDataSharingPlan().getFileName()); assertTrue(updatedStudy.getDatasetIds().stream().findFirst().isPresent()); - Dataset dataset = datasetDAO.findDatasetById( - updatedStudy.getDatasetIds().stream().findFirst().get()); + Dataset dataset = + datasetDAO.findDatasetById(updatedStudy.getDatasetIds().stream().findFirst().get()); assertNotNull(dataset.getNihInstitutionalCertificationFile()); - assertEquals(updatedFso2.getFileName(), - dataset.getNihInstitutionalCertificationFile().getFileName()); + assertEquals( + updatedFso2.getFileName(), dataset.getNihInstitutionalCertificationFile().getFileName()); // Validate that NO update records were added for each dataset - updatedStudy.getDatasetIds().forEach(id -> { - List audits = datasetDAO.findAuditsByDatasetId(id); - assertFalse(audits.isEmpty()); - assertFalse( - audits.stream() - .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.UPDATE.name()))); - }); + updatedStudy + .getDatasetIds() + .forEach( + id -> { + List audits = datasetDAO.findAuditsByDatasetId(id); + assertFalse(audits.isEmpty()); + assertFalse( + audits.stream() + .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.UPDATE.name()))); + }); } - @Test void testDeleteStudy() throws Exception { FileStorageObject fso1 = new FileStorageObject(); fso1.setMediaType(randomAlphabetic(20)); fso1.setCategory(FileCategory.ALTERNATIVE_DATA_SHARING_PLAN); - fso1.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + fso1.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); fso1.setFileName(randomAlphabetic(10)); FileStorageObject fso2 = new FileStorageObject(); fso2.setMediaType(randomAlphabetic(20)); fso2.setCategory(FileCategory.NIH_INSTITUTIONAL_CERTIFICATION); - fso2.setBlobId( - BlobId.of(randomAlphabetic(10), - randomAlphabetic(10))); + fso2.setBlobId(BlobId.of(randomAlphabetic(10), randomAlphabetic(10))); fso2.setFileName(randomAlphabetic(10)); Study study = createStudy(List.of(fso1, fso2)); - List datasets = datasetDAO.findDatasetsByIdList( - new ArrayList<>(study.getDatasetIds())); + List datasets = + datasetDAO.findDatasetsByIdList(new ArrayList<>(study.getDatasetIds())); study.addDatasets(datasets); serviceDAO.deleteStudy(study, createUser()); @@ -717,17 +747,19 @@ void testDeleteStudy() throws Exception { assertNull(deletedStudy); // Validate that audit records are added for each dataset: - study.getDatasetIds().forEach(id -> { - List audits = datasetDAO.findAuditsByDatasetId(id); - assertFalse(audits.isEmpty()); - assertTrue( - audits.stream() - .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.CREATE.name()))); - assertTrue( - audits.stream() - .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.DELETE.name()))); - }); - + study + .getDatasetIds() + .forEach( + id -> { + List audits = datasetDAO.findAuditsByDatasetId(id); + assertFalse(audits.isEmpty()); + assertTrue( + audits.stream() + .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.CREATE.name()))); + assertTrue( + audits.stream() + .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.DELETE.name()))); + }); } @Test @@ -735,10 +767,13 @@ void testDeleteStudyWithNoDatasets() throws Exception { // Registration process creates a study and dataset with properties Study study = createStudy(List.of()); // Delete any created datasets - study.getDatasetIds().forEach(id -> { - datasetDAO.deleteDatasetPropertiesByDatasetId(id); - datasetDAO.deleteDatasetById(id); - }); + study + .getDatasetIds() + .forEach( + id -> { + datasetDAO.deleteDatasetPropertiesByDatasetId(id); + datasetDAO.deleteDatasetById(id); + }); // Ensure that study deletion succeeds serviceDAO.deleteStudy(study, createUser()); Study deletedStudy = studyDAO.findStudyById(study.getStudyId()); @@ -751,16 +786,17 @@ void testExecuteUpdateDatasetWithNullName() throws Exception { Study study = createStudy(List.of()); List datasets = datasetDAO.findDatasetsByIdList(study.getDatasetIds()); Dataset dataset = datasets.get(0); - jdbi.useHandle(handle -> serviceDAO.executeUpdateDatasetWithFiles( - handle, - dataset.getDatasetId(), - null, - study.getCreateUserId(), - dataset.getDacId(), - List.of(), - List.of(), - false) - ); + jdbi.useHandle( + handle -> + serviceDAO.executeUpdateDatasetWithFiles( + handle, + dataset.getDatasetId(), + null, + study.getCreateUserId(), + dataset.getDacId(), + List.of(), + List.of(), + false)); Dataset updatedDataset = datasetDAO.findDatasetById(dataset.getDatasetId()); assertNotNull(updatedDataset.getName()); List audits = datasetDAO.findAuditsByDatasetId(dataset.getDatasetId()); @@ -771,18 +807,20 @@ void testExecuteUpdateDatasetWithNullName() throws Exception { void testExecuteUpdateDatasetWithEmptyName() throws Exception { // This creates a study with a single dataset: Study study = createStudy(List.of()); - List datasets = datasetDAO.findDatasetsByIdList(study.getDatasetIds().stream().toList()); + List datasets = + datasetDAO.findDatasetsByIdList(study.getDatasetIds().stream().toList()); Dataset dataset = datasets.get(0); - jdbi.useHandle(handle -> serviceDAO.executeUpdateDatasetWithFiles( - handle, - dataset.getDatasetId(), - "", - study.getCreateUserId(), - dataset.getDacId(), - List.of(), - List.of(), - false) - ); + jdbi.useHandle( + handle -> + serviceDAO.executeUpdateDatasetWithFiles( + handle, + dataset.getDatasetId(), + "", + study.getCreateUserId(), + dataset.getDacId(), + List.of(), + List.of(), + false)); Dataset updatedDataset = datasetDAO.findDatasetById(dataset.getDatasetId()); assertNotNull(updatedDataset.getName()); List audits = datasetDAO.findAuditsByDatasetId(dataset.getDatasetId()); @@ -793,19 +831,21 @@ void testExecuteUpdateDatasetWithEmptyName() throws Exception { void testExecuteUpdateDatasetWithNewName() throws Exception { // This creates a study with a single dataset: Study study = createStudy(List.of()); - List datasets = datasetDAO.findDatasetsByIdList(study.getDatasetIds().stream().toList()); + List datasets = + datasetDAO.findDatasetsByIdList(study.getDatasetIds().stream().toList()); Dataset dataset = datasets.get(0); String newName = randomAlphabetic(dataset.getName().length() + 10); - jdbi.useHandle(handle -> serviceDAO.executeUpdateDatasetWithFiles( - handle, - dataset.getDatasetId(), - newName, - study.getCreateUserId(), - dataset.getDacId(), - List.of(), - List.of(), - false) - ); + jdbi.useHandle( + handle -> + serviceDAO.executeUpdateDatasetWithFiles( + handle, + dataset.getDatasetId(), + newName, + study.getCreateUserId(), + dataset.getDacId(), + List.of(), + List.of(), + false)); Dataset updatedDataset = datasetDAO.findDatasetById(dataset.getDatasetId()); assertEquals(newName, updatedDataset.getName()); List audits = datasetDAO.findAuditsByDatasetId(dataset.getDatasetId()); @@ -815,12 +855,12 @@ void testExecuteUpdateDatasetWithNewName() throws Exception { @Test void testPatchDataset() throws Exception { List dictionaries = datasetDAO.getDictionaryTerms(); - Dictionary one = dictionaries.stream().filter(d -> d.getKeyId().equals(1)).findFirst() - .orElse(null); - Dictionary two = dictionaries.stream().filter(d -> d.getKeyId().equals(2)).findFirst() - .orElse(null); - Dictionary three = dictionaries.stream().filter(d -> d.getKeyId().equals(3)).findFirst() - .orElse(null); + Dictionary one = + dictionaries.stream().filter(d -> d.getKeyId().equals(1)).findFirst().orElse(null); + Dictionary two = + dictionaries.stream().filter(d -> d.getKeyId().equals(2)).findFirst().orElse(null); + Dictionary three = + dictionaries.stream().filter(d -> d.getKeyId().equals(3)).findFirst().orElse(null); assertNotNull(one); assertNotNull(two); assertNotNull(three); @@ -877,24 +917,30 @@ void testPatchDataset() throws Exception { // Validate that the name is updated assertEquals(newName, patched.getDatasetName()); - Set updatedProps = datasetDAO.findDatasetPropertiesByDatasetId( - dataset.getDatasetId()); + Set updatedProps = + datasetDAO.findDatasetPropertiesByDatasetId(dataset.getDatasetId()); // Validate that the first prop was not changed - Optional original = updatedProps.stream() - .filter(p -> p.getPropertyName().equals(prop1.getPropertyName())).findFirst(); + Optional original = + updatedProps.stream() + .filter(p -> p.getPropertyName().equals(prop1.getPropertyName())) + .findFirst(); assertTrue(original.isPresent()); assertEquals(prop1.getPropertyValue(), original.get().getPropertyValue()); // Validate that the new value was updated - Optional updated = updatedProps.stream() - .filter(p -> p.getPropertyName().equals(prop2.getPropertyName())).findFirst(); + Optional updated = + updatedProps.stream() + .filter(p -> p.getPropertyName().equals(prop2.getPropertyName())) + .findFirst(); assertTrue(updated.isPresent()); assertEquals(patchProp.getPropertyValue(), updated.get().getPropertyValue()); // Validate that the new prop was added - Optional added = updatedProps.stream() - .filter(p -> p.getPropertyName().equals(prop3.getPropertyName())).findFirst(); + Optional added = + updatedProps.stream() + .filter(p -> p.getPropertyName().equals(prop3.getPropertyName())) + .findFirst(); assertTrue(added.isPresent()); assertEquals(prop3.getPropertyValue(), added.get().getPropertyValue()); @@ -991,7 +1037,8 @@ void testUpdateDatasetIndexWithNull() throws Exception { List audits = datasetDAO.findAuditsByDatasetId(updatedDataset.getDatasetId()); assertFalse(audits.isEmpty()); assertTrue( - audits.stream().anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.DEINDEXED.name()))); + audits.stream() + .anyMatch(a -> a.getAction().equalsIgnoreCase(AuditActions.DEINDEXED.name()))); } /** @@ -1015,15 +1062,16 @@ private Study createStudy(List fso) throws Exception { prop2.setType(PropertyType.String); prop2.setValue(randomAlphabetic(10)); - DatasetServiceDAO.StudyInsert studyInsert = new DatasetServiceDAO.StudyInsert( - randomAlphabetic(10), - randomAlphabetic(10), - List.of(randomAlphabetic(10)), - randomAlphabetic(10), - true, - user.getUserId(), - List.of(prop1, prop2), - Objects.isNull(fso) ? List.of() : fso); + DatasetServiceDAO.StudyInsert studyInsert = + new DatasetServiceDAO.StudyInsert( + randomAlphabetic(10), + randomAlphabetic(10), + List.of(randomAlphabetic(10)), + randomAlphabetic(10), + true, + user.getUserId(), + List.of(prop1, prop2), + Objects.isNull(fso) ? List.of() : fso); DatasetProperty datasetProperty = new DatasetProperty(); datasetProperty.setSchemaProperty(randomAlphabetic(10)); @@ -1033,16 +1081,17 @@ private Study createStudy(List fso) throws Exception { datasetProperty.setPropertyValue(new Random().nextInt()); datasetProperty.setCreateDate(new Date()); - DatasetServiceDAO.DatasetInsert datasetInsert = new DatasetServiceDAO.DatasetInsert( - randomAlphabetic(20), - dac.getDacId(), - new DataUseBuilder().setGeneralUse(true).build(), - user.getUserId(), - List.of(datasetProperty), - List.of()); - - List createdIds = serviceDAO.insertDatasetRegistration(studyInsert, - List.of(datasetInsert)); + DatasetServiceDAO.DatasetInsert datasetInsert = + new DatasetServiceDAO.DatasetInsert( + randomAlphabetic(20), + dac.getDacId(), + new DataUseBuilder().setGeneralUse(true).build(), + user.getUserId(), + List.of(datasetProperty), + List.of()); + + List createdIds = + serviceDAO.insertDatasetRegistration(studyInsert, List.of(datasetInsert)); Dataset createdDataset = datasetDAO.findDatasetById(createdIds.get(0)); return createdDataset.getStudy(); } @@ -1053,17 +1102,15 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + randomAlphanumeric(20); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); return datasetDAO.findDatasetById(id); } private Dac createDac() { - Integer id = dacDAO.createDac( - "Test_" + randomAlphanumeric(20), - "Test_" + randomAlphanumeric(20), - new Date()); + Integer id = + dacDAO.createDac( + "Test_" + randomAlphanumeric(20), "Test_" + randomAlphanumeric(20), new Date()); return dacDAO.findById(id); } - -} \ No newline at end of file +} diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAOTest.java index 8d11be91f6..334bf44563 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/DraftFileStorageServiceDAOTest.java @@ -37,16 +37,16 @@ @ExtendWith(MockitoExtension.class) class DraftFileStorageServiceDAOTest extends DAOTestHelper { - @Mock - private GCSService gcsService; + @Mock private GCSService gcsService; private DraftFileStorageServiceDAO draftFileStorageServiceDAO; @BeforeEach void setUp() throws IOException { - when(gcsService.storeDocument(any(), anyString(), any())).thenReturn( - BlobId.of(UUID.randomUUID().toString(), UUID.randomUUID().toString())); - draftFileStorageServiceDAO = new DraftFileStorageServiceDAO(jdbi, gcsService, fileStorageObjectDAO); + when(gcsService.storeDocument(any(), anyString(), any())) + .thenReturn(BlobId.of(UUID.randomUUID().toString(), UUID.randomUUID().toString())); + draftFileStorageServiceDAO = + new DraftFileStorageServiceDAO(jdbi, gcsService, fileStorageObjectDAO); } @Test @@ -54,16 +54,17 @@ void testCreateDraftFile() throws SQLException { User user = createUser(); UUID associatedUUID = UUID.randomUUID(); Map testFiles = getRandomFiles(4); - List storedFiles = draftFileStorageServiceDAO.storeDraftFiles(associatedUUID, - user, testFiles); + List storedFiles = + draftFileStorageServiceDAO.storeDraftFiles(associatedUUID, user, testFiles); assertThat(testFiles.values(), hasSize(4)); assertThat(storedFiles, hasSize(4)); - storedFiles.forEach(fileStorageObject -> { - assertThat(testFiles, hasKey(fileStorageObject.getFileName())); - assertFalse(fileStorageObject.getFileName().trim().isEmpty()); - assertEquals(fileStorageObject.getCreateUserId(), user.getUserId()); - assertEquals(fileStorageObject.getCategory(), FileCategory.DRAFT_UPLOADED_FILE); - }); + storedFiles.forEach( + fileStorageObject -> { + assertThat(testFiles, hasKey(fileStorageObject.getFileName())); + assertFalse(fileStorageObject.getFileName().trim().isEmpty()); + assertEquals(fileStorageObject.getCreateUserId(), user.getUserId()); + assertEquals(fileStorageObject.getCategory(), FileCategory.DRAFT_UPLOADED_FILE); + }); } @Test @@ -71,24 +72,26 @@ void testDeleteDraftFiles() throws SQLException { User user = createUser(); UUID associatedUUID = UUID.randomUUID(); Map testFiles = getRandomFiles(2); - List storedFiles = draftFileStorageServiceDAO.storeDraftFiles(associatedUUID, - user, testFiles); + List storedFiles = + draftFileStorageServiceDAO.storeDraftFiles(associatedUUID, user, testFiles); assertThat(testFiles.values(), hasSize(2)); assertThat(storedFiles, hasSize(2)); for (FileStorageObject fileStorageObject : storedFiles) { draftFileStorageServiceDAO.deleteStoredFile(fileStorageObject, user); } - assertThrows(NotFoundException.class, + assertThrows( + NotFoundException.class, () -> draftFileStorageServiceDAO.deleteStoredFile(new FileStorageObject(), user)); } private Map getRandomFiles(Integer count) { Map mapOfFiles = new HashMap<>(); IntStream.range(0, count) - .forEach(index -> { - String name = String.format("file%d", index); - mapOfFiles.put(name, getFormDataBodyPartMock(name)); - }); + .forEach( + index -> { + String name = String.format("file%d", index); + mapOfFiles.put(name, getFormDataBodyPartMock(name)); + }); return mapOfFiles; } @@ -100,5 +103,4 @@ private FormDataBodyPart getFormDataBodyPartMock(String name) { .thenReturn(new ByteArrayInputStream(EMPTY_JSON_DOCUMENT.getBytes())); return part; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAOTest.java index 82147be793..7fa34f68a8 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/DraftServiceDAOTest.java @@ -55,14 +55,13 @@ class DraftServiceDAOTest extends DAOTestHelper { @BeforeEach void beforeEachTestSetup() throws IOException { gcsService = Mockito.mock(GCSService.class); - when(gcsService.storeDocument(any(), anyString(), any())).thenReturn( - BlobId.of(UUID.randomUUID().toString(), UUID.randomUUID().toString())); - DraftFileStorageServiceDAO draftFileStorageServiceDAO = new DraftFileStorageServiceDAO(jdbi, - gcsService, fileStorageObjectDAO); + when(gcsService.storeDocument(any(), anyString(), any())) + .thenReturn(BlobId.of(UUID.randomUUID().toString(), UUID.randomUUID().toString())); + DraftFileStorageServiceDAO draftFileStorageServiceDAO = + new DraftFileStorageServiceDAO(jdbi, gcsService, fileStorageObjectDAO); draftServiceDAO = new DraftServiceDAO(jdbi, draftDAO, draftFileStorageServiceDAO); } - @Test void testCreateDraft() throws SQLException { User user = createUser(); @@ -100,13 +99,15 @@ void testGetAuthorizedDraft() throws SQLException { adminUser.addRole(UserRoles.Admin()); DraftInterface draft = createDraft(goodUser, 4); assertThat(draftDAO.findDraftsByUserId(goodUser.getUserId()), hasSize(1)); - assertThrows(NotFoundException.class, + assertThrows( + NotFoundException.class, () -> draftServiceDAO.getAuthorizedDraft(UUID.randomUUID(), goodUser)); - assertThrows(NotAuthorizedException.class, + assertThrows( + NotAuthorizedException.class, () -> draftServiceDAO.getAuthorizedDraft(draft.getUUID(), badUser)); assertThat(draftDAO.findDraftsByUserId(adminUser.getUserId()), hasSize(0)); - DraftInterface adminVisibleDraft = draftServiceDAO.getAuthorizedDraft(draft.getUUID(), - adminUser); + DraftInterface adminVisibleDraft = + draftServiceDAO.getAuthorizedDraft(draft.getUUID(), adminUser); assertEquals(adminVisibleDraft.getUUID(), draft.getUUID()); assertEquals(adminVisibleDraft.getName(), draft.getName()); assertThat(adminVisibleDraft.getStoredFiles(), hasSize(4)); @@ -157,8 +158,8 @@ void testDeleteAttachmentFromDraft() throws SQLException { for (FileStorageObject file : storedFiles) { draftServiceDAO.deleteDraftAttachment(draft, user, file.getFileStorageObjectId()); } - assertThat(draftServiceDAO.getAuthorizedDraft(draft.getUUID(), user).getStoredFiles(), - hasSize(0)); + assertThat( + draftServiceDAO.getAuthorizedDraft(draft.getUUID(), user).getStoredFiles(), hasSize(0)); } @Test @@ -200,18 +201,17 @@ private void assertThinUser(User user) { private Map getRandomFiles(Integer count) { Map mapOfFiles = new HashMap<>(); - return IntStream.range(0, count).mapToObj("file%d"::formatted).collect(Collectors.toMap( - Function.identity(), this::getFormDataBodyPartMock)); + return IntStream.range(0, count) + .mapToObj("file%d"::formatted) + .collect(Collectors.toMap(Function.identity(), this::getFormDataBodyPartMock)); } private FormDataBodyPart getFormDataBodyPartMock(String name) { FormDataBodyPart part = mock(FormDataBodyPart.class); when(part.getName()).thenReturn(name); when(part.getMediaType()).thenReturn(MediaType.MULTIPART_FORM_DATA_TYPE); - when(part.getValueAs(InputStream.class)).thenReturn( - new ByteArrayInputStream(EMPTY_JSON_DOCUMENT.getBytes())); + when(part.getValueAs(InputStream.class)) + .thenReturn(new ByteArrayInputStream(EMPTY_JSON_DOCUMENT.getBytes())); return part; } - - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/NihServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/NihServiceDAOTest.java index 9c97ec5df0..3912fef56c 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/NihServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/NihServiceDAOTest.java @@ -39,22 +39,18 @@ void testUpdateUserNihStatus_existing() { // create a user User user = createUser(); // Create ERA Account Props - UserProperty prop1 = new UserProperty( - user.getUserId(), - UserFields.ERA_STATUS.getValue(), - Boolean.TRUE.toString() - ); - UserProperty prop2 = new UserProperty( - user.getUserId(), - UserFields.ERA_EXPIRATION_DATE.getValue(), - new Date().toString() - ); + UserProperty prop1 = + new UserProperty( + user.getUserId(), UserFields.ERA_STATUS.getValue(), Boolean.TRUE.toString()); + UserProperty prop2 = + new UserProperty( + user.getUserId(), UserFields.ERA_EXPIRATION_DATE.getValue(), new Date().toString()); String commonsId = "COMMONS_ID"; userDAO.updateEraCommonsId(user.getUserId(), commonsId); userPropertyDAO.insertAll(List.of(prop1, prop2)); // Create Library Card - libraryCardDAO.insertLibraryCard(user.getUserId(), - user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); + libraryCardDAO.insertLibraryCard( + user.getUserId(), user.getDisplayName(), user.getEmail(), user.getUserId(), new Date()); // Build a new NIHUserAccount to update NIHUserAccount userAccount = new NIHUserAccount(); @@ -64,27 +60,28 @@ void testUpdateUserNihStatus_existing() { serviceDAO.updateUserNihStatus(user, userAccount); // assert that props are updated to the new values - List updatedProps = userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( - user.getUserId(), - List.of(UserFields.ERA_STATUS.getValue(), UserFields.ERA_EXPIRATION_DATE.getValue())); - - Optional statusProp = updatedProps - .stream() - .filter( - userProperty -> userProperty.getPropertyKey().equals(UserFields.ERA_STATUS.getValue())) - .findFirst(); + List updatedProps = + userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + user.getUserId(), + List.of(UserFields.ERA_STATUS.getValue(), UserFields.ERA_EXPIRATION_DATE.getValue())); + + Optional statusProp = + updatedProps.stream() + .filter( + userProperty -> + userProperty.getPropertyKey().equals(UserFields.ERA_STATUS.getValue())) + .findFirst(); assertTrue(statusProp.isPresent()); - assertEquals(statusProp.get().getPropertyValue(), - userAccount.getStatus().toString()); - - Optional expirationProp = updatedProps - .stream() - .filter(userProperty -> userProperty.getPropertyKey() - .equals(UserFields.ERA_EXPIRATION_DATE.getValue())) - .findFirst(); + assertEquals(statusProp.get().getPropertyValue(), userAccount.getStatus().toString()); + + Optional expirationProp = + updatedProps.stream() + .filter( + userProperty -> + userProperty.getPropertyKey().equals(UserFields.ERA_EXPIRATION_DATE.getValue())) + .findFirst(); assertTrue(expirationProp.isPresent()); - assertEquals(expirationProp.get().getPropertyValue(), - userAccount.getEraExpiration()); + assertEquals(expirationProp.get().getPropertyValue(), userAccount.getEraExpiration()); // assert that era commons user id is updated appropriately User updatedUser = userDAO.findUserById(user.getUserId()); @@ -107,27 +104,28 @@ void testUpdateUserNihStatus_new() { serviceDAO.updateUserNihStatus(user, userAccount); // assert that props are updated to the new values - List updatedProps = userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( - user.getUserId(), - List.of(UserFields.ERA_STATUS.getValue(), UserFields.ERA_EXPIRATION_DATE.getValue())); - - Optional statusProp = updatedProps - .stream() - .filter( - userProperty -> userProperty.getPropertyKey().equals(UserFields.ERA_STATUS.getValue())) - .findFirst(); + List updatedProps = + userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + user.getUserId(), + List.of(UserFields.ERA_STATUS.getValue(), UserFields.ERA_EXPIRATION_DATE.getValue())); + + Optional statusProp = + updatedProps.stream() + .filter( + userProperty -> + userProperty.getPropertyKey().equals(UserFields.ERA_STATUS.getValue())) + .findFirst(); assertTrue(statusProp.isPresent()); - assertEquals(statusProp.get().getPropertyValue(), - userAccount.getStatus().toString()); - - Optional expirationProp = updatedProps - .stream() - .filter(userProperty -> userProperty.getPropertyKey() - .equals(UserFields.ERA_EXPIRATION_DATE.getValue())) - .findFirst(); + assertEquals(statusProp.get().getPropertyValue(), userAccount.getStatus().toString()); + + Optional expirationProp = + updatedProps.stream() + .filter( + userProperty -> + userProperty.getPropertyKey().equals(UserFields.ERA_EXPIRATION_DATE.getValue())) + .findFirst(); assertTrue(expirationProp.isPresent()); - assertEquals(expirationProp.get().getPropertyValue(), - userAccount.getEraExpiration()); + assertEquals(expirationProp.get().getPropertyValue(), userAccount.getEraExpiration()); // assert that era commons user id is updated appropriately User updatedUser = userDAO.findUserById(user.getUserId()); @@ -161,16 +159,12 @@ void testUpdateUserNihStatus_jdbiError() { @Test void testDeleteNihAccountById() { User user = createUser(); - UserProperty prop1 = new UserProperty( - user.getUserId(), - UserFields.ERA_STATUS.getValue(), - Boolean.TRUE.toString() - ); - UserProperty prop2 = new UserProperty( - user.getUserId(), - UserFields.ERA_EXPIRATION_DATE.getValue(), - new Date().toString() - ); + UserProperty prop1 = + new UserProperty( + user.getUserId(), UserFields.ERA_STATUS.getValue(), Boolean.TRUE.toString()); + UserProperty prop2 = + new UserProperty( + user.getUserId(), UserFields.ERA_EXPIRATION_DATE.getValue(), new Date().toString()); String commonsId = "COMMONS_ID"; userDAO.updateEraCommonsId(user.getUserId(), commonsId); userPropertyDAO.insertAll(List.of(prop1, prop2)); @@ -178,9 +172,10 @@ void testDeleteNihAccountById() { serviceDAO.deleteNihAccountById(user.getUserId()); // assert that props are deleted - List updatedProps = userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( - user.getUserId(), - List.of(UserFields.ERA_STATUS.getValue(), UserFields.ERA_EXPIRATION_DATE.getValue())); + List updatedProps = + userPropertyDAO.findUserPropertiesByUserIdAndPropertyKeys( + user.getUserId(), + List.of(UserFields.ERA_STATUS.getValue(), UserFields.ERA_EXPIRATION_DATE.getValue())); assertTrue(updatedProps.isEmpty()); // assert that era commons id is null diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/SamDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/SamDAOTest.java index fdffc8954a..74d589471c 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/SamDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/SamDAOTest.java @@ -51,8 +51,7 @@ class SamDAOTest extends MockServerTestHelper { private static SamDAO samDAO; - @Mock - private DuosUser duosUser; + @Mock private DuosUser duosUser; private UserStatus status; @@ -67,24 +66,27 @@ public static void setUp() { @BeforeEach public void init() { - UserStatus.UserInfo info = new UserStatus.UserInfo().setUserEmail("test@test.org") - .setUserSubjectId("subjectId"); - UserStatus.Enabled enabled = new UserStatus.Enabled().setAllUsersGroup(true).setGoogle(true) - .setLdap(true); + UserStatus.UserInfo info = + new UserStatus.UserInfo().setUserEmail("test@test.org").setUserSubjectId("subjectId"); + UserStatus.Enabled enabled = + new UserStatus.Enabled().setAllUsersGroup(true).setGoogle(true).setLdap(true); status = new UserStatus().setUserInfo(info).setEnabled(enabled); } @Test void testGetResourceTypes() throws Exception { - ResourceType resourceType = new ResourceType() - .setName(RandomStringUtils.random(10, true, true)) - .setReuseIds(RandomUtils.nextBoolean()); + ResourceType resourceType = + new ResourceType() + .setName(RandomStringUtils.random(10, true, true)) + .setReuseIds(RandomUtils.nextBoolean()); List mockResponseList = Collections.singletonList(resourceType); Gson gson = new Gson(); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) - .withBody(gson.toJson(mockResponseList))); + mockServerClient + .when(request()) + .respond( + response() + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .withBody(gson.toJson(mockResponseList))); List resourceTypeList = samDAO.getResourceTypes(duosUser); assertFalse(resourceTypeList.isEmpty()); @@ -93,16 +95,19 @@ void testGetResourceTypes() throws Exception { @Test void testGetRegistrationInfo() throws Exception { - UserStatusInfo userInfo = new UserStatusInfo() - .setAdminEnabled(RandomUtils.nextBoolean()) - .setUserEmail("test@test.org") - .setUserSubjectId(RandomStringUtils.random(10, false, true)) - .setEnabled(RandomUtils.nextBoolean()); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) - .withBody(userInfo.toString())); + UserStatusInfo userInfo = + new UserStatusInfo() + .setAdminEnabled(RandomUtils.nextBoolean()) + .setUserEmail("test@test.org") + .setUserSubjectId(RandomStringUtils.random(10, false, true)) + .setEnabled(RandomUtils.nextBoolean()); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .withBody(userInfo.toString())); UserStatusInfo authUserUserInfo = samDAO.getRegistrationInfo(duosUser); assertNotNull(authUserUserInfo); @@ -113,80 +118,93 @@ void testGetRegistrationInfo() throws Exception { @Test void testGetRegistrationInfoBadRequest() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST)); assertThrows(BadRequestException.class, () -> samDAO.getRegistrationInfo(duosUser)); } @Test void testNotAuthorized() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED)); assertThrows(NotAuthorizedException.class, () -> samDAO.getRegistrationInfo(duosUser)); } @Test void testForbidden() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_FORBIDDEN)); assertThrows(ForbiddenException.class, () -> samDAO.getRegistrationInfo(duosUser)); } @Test void testNotFound() { setDebugLogging(); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND)); assertThrows(NotFoundException.class, () -> samDAO.getRegistrationInfo(duosUser)); } @Test void testConflict() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_CONFLICT)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_CONFLICT)); assertThrows(ConsentConflictException.class, () -> samDAO.getRegistrationInfo(duosUser)); } @Test void testGetSelfDiagnostics() throws Exception { - UserStatusDiagnostics diagnostics = new UserStatusDiagnostics() - .setAdminEnabled(RandomUtils.nextBoolean()) - .setEnabled(RandomUtils.nextBoolean()) - .setInAllUsersGroup(RandomUtils.nextBoolean()) - .setInGoogleProxyGroup(RandomUtils.nextBoolean()) - .setTosAccepted(RandomUtils.nextBoolean()); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) - .withBody(diagnostics.toString())); + UserStatusDiagnostics diagnostics = + new UserStatusDiagnostics() + .setAdminEnabled(RandomUtils.nextBoolean()) + .setEnabled(RandomUtils.nextBoolean()) + .setInAllUsersGroup(RandomUtils.nextBoolean()) + .setInGoogleProxyGroup(RandomUtils.nextBoolean()) + .setTosAccepted(RandomUtils.nextBoolean()); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .withBody(diagnostics.toString())); UserStatusDiagnostics userDiagnostics = samDAO.getSelfDiagnostics(duosUser); assertNotNull(userDiagnostics); assertEquals(diagnostics.getEnabled(), userDiagnostics.getEnabled()); - assertEquals(diagnostics.getInAllUsersGroup(), - userDiagnostics.getInAllUsersGroup()); - assertEquals(diagnostics.getInGoogleProxyGroup(), - userDiagnostics.getInGoogleProxyGroup()); + assertEquals(diagnostics.getInAllUsersGroup(), userDiagnostics.getInAllUsersGroup()); + assertEquals(diagnostics.getInGoogleProxyGroup(), userDiagnostics.getInGoogleProxyGroup()); } @Test void testPostRegistrationInfo() throws Exception { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) - .withBody(status.toString())); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) + .withBody(status.toString())); UserStatus userStatus = samDAO.postRegistrationInfo(duosUser); assertNotNull(userStatus); @@ -194,15 +212,17 @@ void testPostRegistrationInfo() throws Exception { @Test void testPostRegistrationInfo_Error() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .withBody(("{\"message\":\"errorMessage\"}"))); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) + .withBody(("{\"message\":\"errorMessage\"}"))); when(duosUser.getEmail()).thenReturn("email@email.com"); - WebApplicationException ex = assertThrows(WebApplicationException.class, - () -> samDAO.postRegistrationInfo(duosUser)); + WebApplicationException ex = + assertThrows(WebApplicationException.class, () -> samDAO.postRegistrationInfo(duosUser)); assertEquals( "Error posting user registration information. Email: email@email.com. errorMessage.", ex.getMessage()); @@ -216,11 +236,13 @@ void testPostRegistrationInfo_Error() { */ @Test void testAsyncPostRegistrationInfo() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) - .withBody(status.toString())); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_CREATED) + .withBody(status.toString())); try { samDAO.asyncPostRegistrationInfo(duosUser); @@ -232,11 +254,13 @@ void testAsyncPostRegistrationInfo() { @Test void testGetToSText() { String mockText = "Plain Text"; - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", MediaType.TEXT_PLAIN.getType())) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) - .withBody(mockText)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", MediaType.TEXT_PLAIN.getType())) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .withBody(mockText)); try { String text = samDAO.getToSText(); @@ -248,10 +272,12 @@ void testGetToSText() { @Test void testGetTosResponse() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); try { samDAO.getTosResponse(duosUser); } catch (Exception e) { @@ -261,10 +287,12 @@ void testGetTosResponse() { @Test void testPostTosAcceptedStatus() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); try { samDAO.acceptTosStatus(duosUser); @@ -275,10 +303,12 @@ void testPostTosAcceptedStatus() { @Test void testRemoveTosAcceptedStatus() { - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); try { samDAO.rejectTosStatus(duosUser); @@ -291,11 +321,13 @@ void testRemoveTosAcceptedStatus() { void testGetV1UserByEmail() { EmailResponse emailResponse = new EmailResponse("googleId", "email", "subjectId"); Gson gson = GsonUtil.buildGson(); - mockServerClient.when(request()) - .respond(response() - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) - .withBody(gson.toJson(emailResponse))); + mockServerClient + .when(request()) + .respond( + response() + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .withBody(gson.toJson(emailResponse))); try { EmailResponse response = samDAO.getV1UserByEmail(duosUser, "test@gmail.com"); @@ -317,11 +349,13 @@ void testConnectTimeout() { void testReadTimeout() { // Increase the delay to push the response beyond the read timeout value int delayMilliseconds = samDAO.readTimeoutMilliseconds + 10; - mockServerClient.when(request()) - .respond(response() - .withDelay(new Delay(TimeUnit.MILLISECONDS, delayMilliseconds)) - .withHeader(Header.header("Content-Type", "application/json")) - .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); + mockServerClient + .when(request()) + .respond( + response() + .withDelay(new Delay(TimeUnit.MILLISECONDS, delayMilliseconds)) + .withHeader(Header.header("Content-Type", "application/json")) + .withStatusCode(HttpStatusCodes.STATUS_CODE_OK)); assertThrows( ServerErrorException.class, () -> samDAO.getV1UserByEmail(duosUser, RandomStringUtils.randomAlphabetic(10))); @@ -330,7 +364,8 @@ void testReadTimeout() { @Test void testGetErrorMessageAzureB2cId() { when(duosUser.getEmail()).thenReturn("email@email.com"); - String body = """ + String body = + """ {"code":500, "message": "Cannot update azureB2cId"}"""; assertEquals( "Email: email@email.com. You may have previously signed in with a different authentication provider (Google or Microsoft). Please sign in with that provider. For more information visit: https://support.terra.bio/hc/en-us/community/posts/24089648317467-Cannot-update-azureB2cId-for-user", @@ -340,7 +375,8 @@ void testGetErrorMessageAzureB2cId() { @Test void testGetErrorMessageOther() { when(duosUser.getEmail()).thenReturn("email@email.com"); - String body = """ + String body = + """ {"code":500, "message": "some other error"}"""; assertEquals( "Error posting user registration information. Email: email@email.com. some other error.", @@ -350,9 +386,11 @@ void testGetErrorMessageOther() { @Test void testGetErrorMessageNoMessage() { when(duosUser.getEmail()).thenReturn("email@email.com"); - String body = """ + String body = + """ {"code":500}"""; - assertEquals(""" + assertEquals( + """ Error posting user registration information. Email: email@email.com. {"code":500}.""", getErrorMessage(duosUser, body)); } @@ -361,7 +399,8 @@ void testGetErrorMessageNoMessage() { void testGetErrorMessageNoBody() { when(duosUser.getEmail()).thenReturn("email@email.com"); String body = null; - assertEquals(""" + assertEquals( + """ Error posting user registration information. Email: email@email.com.""", getErrorMessage(duosUser, body)); } @@ -370,7 +409,8 @@ void testGetErrorMessageNoBody() { void testGetErrorMessageNotJson() { when(duosUser.getEmail()).thenReturn("email@email.com"); String body = "random non-JSON string"; - assertEquals(""" + assertEquals( + """ Error posting user registration information. Email: email@email.com. random non-JSON string.""", getErrorMessage(duosUser, body)); } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/UserServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/UserServiceDAOTest.java index 1fe080a6fe..147c32d2e9 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/UserServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/UserServiceDAOTest.java @@ -25,7 +25,8 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; -// This is a utility test to verify a pattern for Database Transactions continues to be supported and works as expected. +// This is a utility test to verify a pattern for Database Transactions continues to be supported +// and works as expected. // It should be updated to include new patterns that are developed. @ExtendWith(MockitoExtension.class) class UserServiceDAOTest extends DAOTestHelper { @@ -57,21 +58,22 @@ void testTransactionRollbackAfterMultipleInserts() { assertTrue(Optional.ofNullable(testUser.getInstitutionId()).isEmpty()); UserRole userRole = UserRoles.SigningOfficial(); try { - //it's necessary to copy the code in from the service dao layer because we're testing that the transaction - //does indeed roll back from postgres. mocking won't confirm that behavior. - jdbi.useTransaction(transactionHandle -> { - UserDAO userDAOT = transactionHandle.attach(UserDAO.class); - UserRoleDAO userRoleDAOT = transactionHandle.attach(UserRoleDAO.class); - userDAOT.updateInstitutionId(testUser.getUserId(), institution.getId()); - userRoleDAOT.insertSingleUserRole(userRole.getRoleId(), testUser.getUserId()); - throw new RuntimeException("interrupt the transaction."); - }); + // it's necessary to copy the code in from the service dao layer because we're testing that + // the transaction + // does indeed roll back from postgres. mocking won't confirm that behavior. + jdbi.useTransaction( + transactionHandle -> { + UserDAO userDAOT = transactionHandle.attach(UserDAO.class); + UserRoleDAO userRoleDAOT = transactionHandle.attach(UserRoleDAO.class); + userDAOT.updateInstitutionId(testUser.getUserId(), institution.getId()); + userRoleDAOT.insertSingleUserRole(userRole.getRoleId(), testUser.getUserId()); + throw new RuntimeException("interrupt the transaction."); + }); } catch (Exception e) { User fetchedUser = userDAO.findUserById(testUser.getUserId()); assertEquals(fetchedUser.getUserId(), testUser.getUserId()); assertEquals(1, fetchedUser.getRoles().size()); - assertEquals(UserRoles.RESEARCHER.getRoleId(), - fetchedUser.getRoles().get(0).getRoleId()); + assertEquals(UserRoles.RESEARCHER.getRoleId(), fetchedUser.getRoles().get(0).getRoleId()); assertNotEquals(fetchedUser.getInstitutionId(), institution.getId()); assertTrue(Optional.ofNullable(fetchedUser.getInstitutionId()).isEmpty()); exceptionCaught = true; @@ -83,17 +85,19 @@ void testTransactionRollbackAfterMultipleInserts() { private Institution createInstitution() { User createUser = createUser(); - Integer id = institutionDAO.insertInstitution(RandomStringUtils.randomAlphabetic(20), - "itDirectorName", - "itDirectorEmail", - RandomStringUtils.randomAlphabetic(10), - new Random().nextInt(), - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10), - OrganizationType.NON_PROFIT.getValue(), - createUser.getUserId(), - createUser.getCreateDate()); + Integer id = + institutionDAO.insertInstitution( + RandomStringUtils.randomAlphabetic(20), + "itDirectorName", + "itDirectorEmail", + RandomStringUtils.randomAlphabetic(10), + new Random().nextInt(), + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + RandomStringUtils.randomAlphabetic(10), + OrganizationType.NON_PROFIT.getValue(), + createUser.getUserId(), + createUser.getCreateDate()); Institution institution = institutionDAO.findInstitutionById(id); User updateUser = createUser(); institutionDAO.updateInstitutionById( @@ -108,8 +112,7 @@ private Institution createInstitution() { institution.getVerificationFilename(), institution.getOrganizationType().getValue(), updateUser.getUserId(), - new Date() - ); + new Date()); return institutionDAO.findInstitutionById(id); } diff --git a/src/test/java/org/broadinstitute/consent/http/service/dao/VoteServiceDAOTest.java b/src/test/java/org/broadinstitute/consent/http/service/dao/VoteServiceDAOTest.java index 88a75a9d55..bc26293c3c 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/dao/VoteServiceDAOTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/dao/VoteServiceDAOTest.java @@ -106,22 +106,21 @@ void testUpdateVotesWithValue_MultipleVotes() throws Exception { Vote vote3 = createDacVote(user.getUserId(), election.getElectionId()); String rationale = "rationale"; - List votes = serviceDAO.updateVotesWithValue(List.of(vote1, vote2, vote3), true, - rationale); + List votes = + serviceDAO.updateVotesWithValue(List.of(vote1, vote2, vote3), true, rationale); assertNotNull(votes); assertFalse(votes.isEmpty()); - List requestVoteIds = Stream.of(vote1, vote2, vote3) - .map(Vote::getVoteId) - .collect(Collectors.toList()); - votes.forEach(v -> { - assertTrue(v.getVote()); - assertEquals(rationale, v.getRationale()); - assertTrue(requestVoteIds.contains(v.getVoteId())); - }); + List requestVoteIds = + Stream.of(vote1, vote2, vote3).map(Vote::getVoteId).collect(Collectors.toList()); + votes.forEach( + v -> { + assertTrue(v.getVote()); + assertEquals(rationale, v.getRationale()); + assertTrue(requestVoteIds.contains(v.getVoteId())); + }); } - @Test void testUpdateVotesWithValue_MultipleElectionTypes() throws Exception { User user = createUser(); @@ -129,31 +128,29 @@ void testUpdateVotesWithValue_MultipleElectionTypes() throws Exception { Dataset dataset = createDataset(); Election rpElection1 = createRPElection(dar.getReferenceId(), dataset.getDatasetId()); Election rpElection2 = createRPElection(dar.getReferenceId(), dataset.getDatasetId()); - Election accessElection = createDataAccessElection(dar.getReferenceId(), - dataset.getDatasetId()); + Election accessElection = + createDataAccessElection(dar.getReferenceId(), dataset.getDatasetId()); electionDAO.updateElectionById( - rpElection1.getElectionId(), - ElectionStatus.CLOSED.getValue(), - new Date()); + rpElection1.getElectionId(), ElectionStatus.CLOSED.getValue(), new Date()); Vote vote1 = createDacVote(user.getUserId(), rpElection1.getElectionId()); Vote vote2 = createDacVote(user.getUserId(), rpElection2.getElectionId()); Vote vote3 = createDacVote(user.getUserId(), accessElection.getElectionId()); String rationale = "rationale"; - List votes = serviceDAO.updateVotesWithValue(List.of(vote1, vote2, vote3), true, - rationale); + List votes = + serviceDAO.updateVotesWithValue(List.of(vote1, vote2, vote3), true, rationale); assertNotNull(votes); assertFalse(votes.isEmpty()); - List requestVoteIds = Stream.of(vote1, vote2, vote3) - .map(Vote::getVoteId) - .collect(Collectors.toList()); - votes.forEach(v -> { - assertTrue(v.getVote()); - assertEquals(rationale, v.getRationale()); - assertTrue(requestVoteIds.contains(v.getVoteId())); - }); + List requestVoteIds = + Stream.of(vote1, vote2, vote3).map(Vote::getVoteId).collect(Collectors.toList()); + votes.forEach( + v -> { + assertTrue(v.getVote()); + assertEquals(rationale, v.getRationale()); + assertTrue(requestVoteIds.contains(v.getVoteId())); + }); } private Dataset createDataset() { @@ -162,8 +159,8 @@ private Dataset createDataset() { Timestamp now = new Timestamp(new Date().getTime()); String objectId = "Object ID_" + RandomStringUtils.random(20, true, true); DataUse dataUse = new DataUseBuilder().setGeneralUse(true).build(); - Integer id = datasetDAO.insertDataset(name, now, user.getUserId(), objectId, - dataUse.toString(), null); + Integer id = + datasetDAO.insertDataset(name, now, user.getUserId(), objectId, dataUse.toString(), null); createDatasetProperties(id); return datasetDAO.findDatasetById(id); } @@ -190,25 +187,24 @@ private Vote createFinalVote(Integer userId, Integer electionId) { } private Election createRPElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.RP.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.RP.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } private Election createDataAccessElection(String referenceId, Integer datasetId) { - Integer electionId = electionDAO.insertElection( - ElectionType.DATA_ACCESS.getValue(), - ElectionStatus.OPEN.getValue(), - new Date(), - referenceId, - datasetId - ); + Integer electionId = + electionDAO.insertElection( + ElectionType.DATA_ACCESS.getValue(), + ElectionStatus.OPEN.getValue(), + new Date(), + referenceId, + datasetId); return electionDAO.findElectionById(electionId); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcementTest.java b/src/test/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcementTest.java index 92be0d904a..8a14f37f79 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcementTest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/feature/InstitutionAndLibraryCardEnforcementTest.java @@ -37,16 +37,11 @@ @ExtendWith(MockitoExtension.class) public class InstitutionAndLibraryCardEnforcementTest extends AbstractTestHelper { - @Mock - private InstitutionDAO institutionDAO; - @Mock - private LibraryCardDAO libraryCardDAO; - @Mock - private UserDAO userDAO; - @Mock - private UserServiceDAO userServiceDAO; - @Mock - private Jdbi jdbi; + @Mock private InstitutionDAO institutionDAO; + @Mock private LibraryCardDAO libraryCardDAO; + @Mock private UserDAO userDAO; + @Mock private UserServiceDAO userServiceDAO; + @Mock private Jdbi jdbi; private InstitutionAndLibraryCardEnforcement service; @@ -60,9 +55,10 @@ void setUp() { @Test void testAsyncEnforceInstitutionAndLibraryCardRulesForAllUsers() { - List allUsers = IntStream.rangeClosed(1, 10) - .mapToObj(InstitutionAndLibraryCardEnforcementTest::generateUser) - .toList(); + List allUsers = + IntStream.rangeClosed(1, 10) + .mapToObj(InstitutionAndLibraryCardEnforcementTest::generateUser) + .toList(); when(userDAO.findUsersWithLCsAndInstitution()).thenReturn(allUsers); allUsers.forEach(u -> when(userDAO.findUserByEmail(u.getEmail())).thenReturn(u)); @@ -143,8 +139,9 @@ void handleUserWithInstitutionInMap_DifferentInDatabaseWithLibraryCard() { when(institutionDAO.findInstitutionByDomain(soDomain)).thenReturn(institutionFromDatabase); assertTrue(service.handleUserWithInstitutionInMap(testUser, institutionFromEmail.getId())); - verify(userServiceDAO).updateInstitutionAndClearLibraryCardForUser(testUser.getUserId(), - institutionFromEmail.getId()); + verify(userServiceDAO) + .updateInstitutionAndClearLibraryCardForUser( + testUser.getUserId(), institutionFromEmail.getId()); } @Test @@ -177,8 +174,9 @@ void handleUserWithInstitutionInMap_DifferentInDatabaseWithLibraryCard_SO_NFE() when(userDAO.findUserById(signingOfficial.getUserId())).thenReturn(null); assertTrue(service.handleUserWithInstitutionInMap(testUser, institutionFromEmail.getId())); - verify(userServiceDAO).updateInstitutionAndClearLibraryCardForUser(testUser.getUserId(), - institutionFromEmail.getId()); + verify(userServiceDAO) + .updateInstitutionAndClearLibraryCardForUser( + testUser.getUserId(), institutionFromEmail.getId()); } @Test @@ -200,7 +198,6 @@ void handleUserWithInstitutionInMap_SameInDatabaseWithLC() { assertFalse(service.handleUserWithInstitutionInMap(testUser, institutionFromEmail.getId())); } - @Test void handleUserWithInstitutionInMap_SameInDatabaseWithLCFromDifferentOrg() { User testUser = generateUser(1); @@ -277,8 +274,7 @@ public static Stream testEnforceInstitutionAndLibraryCardVariations() Arguments.of(institution1, testUser, libraryCard2, false), Arguments.of(institution1, testUser, null, false), Arguments.of(null, testUser, libraryCards1, true), - Arguments.of(null, testUser, null, false) - ); + Arguments.of(null, testUser, null, false)); } @ParameterizedTest @@ -290,11 +286,9 @@ void testEnforceInstitutionAndLibraryCardVariations( alteredUser.setEmail(testUser.getEmail()); String domain = service.trimmedEmailDomain(testUser.getEmail()); if (institutionFromMap != null) { - when(institutionDAO.findInstitutionIdByDomain(domain)) - .thenReturn(institutionFromMap.getId()); + when(institutionDAO.findInstitutionIdByDomain(domain)).thenReturn(institutionFromMap.getId()); } else { - when(institutionDAO.findInstitutionIdByDomain(domain)) - .thenReturn(null); + when(institutionDAO.findInstitutionIdByDomain(domain)).thenReturn(null); } if (expectsUserMod) { when(userDAO.findUserByEmail(testUser.getEmail())).thenReturn(testUser, alteredUser); @@ -310,7 +304,9 @@ void testEnforceInstitutionAndLibraryCardVariations( @Test void testEnforceInstitutionAndLibraryCardThrowsNotFoundExceptionForNewUser() { when(userDAO.findUserByEmail(any())).thenReturn(null); - assertThrows(NotFoundException.class, ()->service.enforceInstitutionAndLibraryCardRules("hello world!")); + assertThrows( + NotFoundException.class, + () -> service.enforceInstitutionAndLibraryCardRules("hello world!")); } private void validateUserIsUnmodified(User left, User right) { @@ -347,5 +343,4 @@ private static Institution generateInstitution(Integer id) { inst.setName(randomAlphabetic(10)); return inst; } - } diff --git a/src/test/java/org/broadinstitute/consent/http/service/mail/SendGridAPITest.java b/src/test/java/org/broadinstitute/consent/http/service/mail/SendGridAPITest.java index ea3fdb8edb..fff1f6a4cb 100644 --- a/src/test/java/org/broadinstitute/consent/http/service/mail/SendGridAPITest.java +++ b/src/test/java/org/broadinstitute/consent/http/service/mail/SendGridAPITest.java @@ -37,8 +37,7 @@ class SendGridAPITest { private SendGrid sendGrid; private SendGridAPI sendGridAPI; - @Mock - private UserDAO userDAO; + @Mock private UserDAO userDAO; @BeforeEach void setUp() throws Exception { @@ -56,12 +55,13 @@ void setUp() throws Exception { @Test void sendMessage() throws Exception { String messageBody = "This is a test message"; - Mail mail = new Mail() { - @Override - public String build() { - return messageBody; - } - }; + Mail mail = + new Mail() { + @Override + public String build() { + return messageBody; + } + }; assertEquals(RESPONSE, sendGridAPI.sendMessage(mail, TO)); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(Request.class); verify(sendGrid).makeCall(requestCaptor.capture()); diff --git a/src/test/java/org/broadinstitute/consent/http/util/ComplianceLoggerTest.java b/src/test/java/org/broadinstitute/consent/http/util/ComplianceLoggerTest.java index 5cd412da6e..17d222b510 100644 --- a/src/test/java/org/broadinstitute/consent/http/util/ComplianceLoggerTest.java +++ b/src/test/java/org/broadinstitute/consent/http/util/ComplianceLoggerTest.java @@ -11,7 +11,6 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import com.google.api.client.http.HttpStatusCodes; -import io.netty.handler.codec.http.HttpHeaderNames; import jakarta.ws.rs.core.HttpHeaders; import java.net.URI; import java.net.URISyntaxException; @@ -30,12 +29,10 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.LoggerFactory; - @ExtendWith(MockitoExtension.class) class ComplianceLoggerTest extends AbstractTestHelper { - @Mock - private ContainerRequest request; + @Mock private ContainerRequest request; private TestAppender testAppender; private final User user = new User(); private final Institution institution = new Institution(); @@ -73,68 +70,82 @@ private void assertMessageContainsValueFields(ILoggingEvent event) { @Test void testLogDARSApproval() { - ComplianceLogger.logDARApproval(user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); + ComplianceLogger.logDARApproval( + user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); assertEquals(1, testAppender.getSize()); ILoggingEvent event = testAppender.getLoggedEvents().get(0); assertMessageContainsValueFields(event); - assertThat(event.getFormattedMessage(), containsString(ComplianceEvent.DAR_APPROVAL.toString())); + assertThat( + event.getFormattedMessage(), containsString(ComplianceEvent.DAR_APPROVAL.toString())); } @Test void testLogRadarApproval() { - ComplianceLogger.logRadarApproval(user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); + ComplianceLogger.logRadarApproval( + user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); assertEquals(1, testAppender.getSize()); ILoggingEvent event = testAppender.getLoggedEvents().get(0); assertMessageContainsValueFields(event); - assertThat(event.getFormattedMessage(), containsString(ComplianceEvent.RADAR_APPROVAL.toString())); + assertThat( + event.getFormattedMessage(), containsString(ComplianceEvent.RADAR_APPROVAL.toString())); } @Test void testLogDARRejection() { - ComplianceLogger.logDARRejection(user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); + ComplianceLogger.logDARRejection( + user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); assertEquals(1, testAppender.getSize()); ILoggingEvent event = testAppender.getLoggedEvents().get(0); assertMessageContainsValueFields(event); - assertThat(event.getFormattedMessage(), containsString(ComplianceEvent.DAR_REJECTION.toString())); + assertThat( + event.getFormattedMessage(), containsString(ComplianceEvent.DAR_REJECTION.toString())); } @Test void testLogDARSubmission() { - ComplianceLogger.logDARSubmission(user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_CREATED); + ComplianceLogger.logDARSubmission( + user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_CREATED); assertEquals(1, testAppender.getSize()); ILoggingEvent event = testAppender.getLoggedEvents().get(0); assertMessageContainsValueFields(event); - assertThat(event.getFormattedMessage(), containsString(ComplianceEvent.DAR_SUBMISSION.toString())); + assertThat( + event.getFormattedMessage(), containsString(ComplianceEvent.DAR_SUBMISSION.toString())); } @Test void testLogDARCancellation() { - ComplianceLogger.logDARCancellation(user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); + ComplianceLogger.logDARCancellation( + user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); assertEquals(1, testAppender.getSize()); ILoggingEvent event = testAppender.getLoggedEvents().get(0); assertMessageContainsValueFields(event); - assertThat(event.getFormattedMessage(), containsString(ComplianceEvent.DAR_CANCELLATION.toString())); + assertThat( + event.getFormattedMessage(), containsString(ComplianceEvent.DAR_CANCELLATION.toString())); } @Test void testLogSOCloseoutApproval() { - ComplianceLogger.logCloseoutApprovalBySigningOfficial(user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); + ComplianceLogger.logCloseoutApprovalBySigningOfficial( + user, List.of(dataset), request, HttpStatusCodes.STATUS_CODE_OK); assertEquals(1, testAppender.getSize()); ILoggingEvent event = testAppender.getLoggedEvents().get(0); assertMessageContainsValueFields(event); - assertThat(event.getFormattedMessage(), containsString(ComplianceEvent.CLOSEOUT_SO_APPROVAL.toString())); + assertThat( + event.getFormattedMessage(), + containsString(ComplianceEvent.CLOSEOUT_SO_APPROVAL.toString())); } private static class TestAppender extends ListAppender { public void reset() { this.list.clear(); } + public int getSize() { return this.list.size(); } + public List getLoggedEvents() { return Collections.unmodifiableList(this.list); } } - } diff --git a/src/test/java/org/broadinstitute/consent/http/util/HttpClientUtilTest.java b/src/test/java/org/broadinstitute/consent/http/util/HttpClientUtilTest.java index f442782429..e12372bf8d 100644 --- a/src/test/java/org/broadinstitute/consent/http/util/HttpClientUtilTest.java +++ b/src/test/java/org/broadinstitute/consent/http/util/HttpClientUtilTest.java @@ -25,8 +25,8 @@ @ExtendWith(MockitoExtension.class) class HttpClientUtilTest extends MockServerTestHelper { - private final String statusUrl = String.format("http://%s:%s/", CONTAINER.getHost(), - CONTAINER.getServerPort()); + private final String statusUrl = + String.format("http://%s:%s/", CONTAINER.getHost(), CONTAINER.getServerPort()); private HttpClientUtil clientUtil; @BeforeEach @@ -36,27 +36,23 @@ void init() { clientUtil = new HttpClientUtil(configuration); } - /** - * Test that the cache works normally - */ + /** Test that the cache works normally */ @Test void testGetCachedResponse_case1() { - mockServerClient.when(request()) - .respond(response() - .withStatusCode(200)); - IntStream.range(3, 10).forEach(i -> { - try { - clientUtil.getCachedResponse(new HttpGet(statusUrl)); - } catch (Exception e) { - fail(e.getMessage()); - } - }); + mockServerClient.when(request()).respond(response().withStatusCode(200)); + IntStream.range(3, 10) + .forEach( + i -> { + try { + clientUtil.getCachedResponse(new HttpGet(statusUrl)); + } catch (Exception e) { + fail(e.getMessage()); + } + }); mockServerClient.verify(request(), VerificationTimes.exactly(1)); } - /** - * Test that when the cache is expired, all calls are made to external servers - */ + /** Test that when the cache is expired, all calls are made to external servers */ @Test void testGetCachedResponse_case2() { ServicesConfiguration configuration = new ServicesConfiguration(); @@ -64,39 +60,37 @@ void testGetCachedResponse_case2() { // Setting the cache to 0 effectively means no caching configuration.setCacheExpireMinutes(0); clientUtil = new HttpClientUtil(configuration); - mockServerClient.when(request()) - .respond(response() - .withStatusCode(200)); + mockServerClient.when(request()).respond(response().withStatusCode(200)); int count = RandomUtils.nextInt(5, 10); - IntStream.range(0, count).forEach(i -> { - try { - clientUtil.getCachedResponse(new HttpGet(statusUrl)); - } catch (Exception e) { - fail(e.getMessage()); - } - }); + IntStream.range(0, count) + .forEach( + i -> { + try { + clientUtil.getCachedResponse(new HttpGet(statusUrl)); + } catch (Exception e) { + fail(e.getMessage()); + } + }); mockServerClient.verify(request(), VerificationTimes.exactly(count)); } @Test void testGetHttpResponseUnderTimeout() throws Exception { - mockServerClient.when(request()) - .respond(response() - .withStatusCode(200)); + mockServerClient.when(request()).respond(response().withStatusCode(200)); SimpleResponse response = clientUtil.getHttpResponse(new HttpGet(statusUrl)); assertEquals(HttpStatusCodes.STATUS_CODE_OK, response.code()); } @Test void testGetHttpResponseOverTimeout() { - mockServerClient.when(request()) - .respond(response() - .withStatusCode(200) - .withDelay(Delay.delay(TimeUnit.SECONDS, 3))); - assertThrows(RequestFailedException.class, () -> { - clientUtil.getHttpResponse(new HttpGet(statusUrl)); - }); + mockServerClient + .when(request()) + .respond(response().withStatusCode(200).withDelay(Delay.delay(TimeUnit.SECONDS, 3))); + assertThrows( + RequestFailedException.class, + () -> { + clientUtil.getHttpResponse(new HttpGet(statusUrl)); + }); } - } diff --git a/src/test/java/org/broadinstitute/consent/http/util/InstitutionUtilTest.java b/src/test/java/org/broadinstitute/consent/http/util/InstitutionUtilTest.java index bb2af59c98..c859003400 100644 --- a/src/test/java/org/broadinstitute/consent/http/util/InstitutionUtilTest.java +++ b/src/test/java/org/broadinstitute/consent/http/util/InstitutionUtilTest.java @@ -21,24 +21,23 @@ @ExtendWith(MockitoExtension.class) class InstitutionUtilTest { - private static final List VALID_DOMAINS = Arrays.asList( - "café.com", - "broad.mit.edu", - "broadinstitute.org", - "mail.google.com", - "www.broadinstitute.org" - ); - - private static final List INVALID_DOMAINS = Arrays.asList( - "invalid", - "", - null - ); - - private static final List MIXED_VALIDITY_DOMAINS = new ArrayList() {{ - addAll(VALID_DOMAINS); - addAll(INVALID_DOMAINS); - }}; + private static final List VALID_DOMAINS = + Arrays.asList( + "café.com", + "broad.mit.edu", + "broadinstitute.org", + "mail.google.com", + "www.broadinstitute.org"); + + private static final List INVALID_DOMAINS = Arrays.asList("invalid", "", null); + + private static final List MIXED_VALIDITY_DOMAINS = + new ArrayList() { + { + addAll(VALID_DOMAINS); + addAll(INVALID_DOMAINS); + } + }; private InstitutionUtil util; @@ -67,10 +66,10 @@ void testGsonBuilderAdmin() { assertEquals(mockInstitution.getName(), deserialized.getName()); assertEquals(mockInstitution.getCreateUserId(), deserialized.getCreateUserId()); assertEquals(mockInstitution.getUpdateUserId(), deserialized.getUpdateUserId()); - assertEquals(mockInstitution.getCreateDate().toString(), - deserialized.getCreateDate().toString()); - assertEquals(mockInstitution.getUpdateDate().toString(), - deserialized.getUpdateDate().toString()); + assertEquals( + mockInstitution.getCreateDate().toString(), deserialized.getCreateDate().toString()); + assertEquals( + mockInstitution.getUpdateDate().toString(), deserialized.getUpdateDate().toString()); assertEquals(mockInstitution.getId(), deserialized.getId()); } @@ -99,9 +98,10 @@ void testGetInvalidInstitutionDomainsMixedValidity() { List invalidDomains = InstitutionUtil.getInvalidInstitutionDomains(institution); assertEquals(3, invalidDomains.size()); - INVALID_DOMAINS.forEach(domain -> { - assertTrue(invalidDomains.contains(domain)); - }); + INVALID_DOMAINS.forEach( + domain -> { + assertTrue(invalidDomains.contains(domain)); + }); } @Test @@ -134,31 +134,46 @@ void testValidateInstitutionDomainsContainsInvalid() { } assertInstanceOf(BadRequestException.class, exception); - assertEquals("Invalid domain(s) provided for institution: invalid, , null", exception.getMessage()); + assertEquals( + "Invalid domain(s) provided for institution: invalid, , null", exception.getMessage()); } @Test void testCanonicalizeInstitutionNameValidInput() { - assertEquals("Harvard University", InstitutionUtil.canonicalizeInstitutionName("Harvard University")); - assertEquals("University of Connecticut", InstitutionUtil.canonicalizeInstitutionName(" University of Connecticut ")); + assertEquals( + "Harvard University", InstitutionUtil.canonicalizeInstitutionName("Harvard University")); + assertEquals( + "University of Connecticut", + InstitutionUtil.canonicalizeInstitutionName(" University of Connecticut ")); } @Test void testCanonicalizeInstitutionNameQuotes() { // Test left/right double quotation marks - assertEquals("A 'Real' University", InstitutionUtil.canonicalizeInstitutionName("A \"Real\" University")); + assertEquals( + "A 'Real' University", + InstitutionUtil.canonicalizeInstitutionName("A \"Real\" University")); // Test left/right single quotation marks - assertEquals("St. John's University", InstitutionUtil.canonicalizeInstitutionName("St. John’s University")); - assertEquals("Mount St. Mary's College", InstitutionUtil.canonicalizeInstitutionName("Mount St. Mary‘s College")); + assertEquals( + "St. John's University", + InstitutionUtil.canonicalizeInstitutionName("St. John’s University")); + assertEquals( + "Mount St. Mary's College", + InstitutionUtil.canonicalizeInstitutionName("Mount St. Mary‘s College")); // Test low-9 quotation marks - assertEquals("A 'Real' University", InstitutionUtil.canonicalizeInstitutionName("A ‚Real„ University")); + assertEquals( + "A 'Real' University", InstitutionUtil.canonicalizeInstitutionName("A ‚Real„ University")); } @Test void testCanonicalizeInstitutionNameWhitespace() { - assertEquals("Harvard University", InstitutionUtil.canonicalizeInstitutionName(" Harvard University ")); - assertEquals("Connecticut College", InstitutionUtil.canonicalizeInstitutionName("\t Connecticut College \n")); + assertEquals( + "Harvard University", + InstitutionUtil.canonicalizeInstitutionName(" Harvard University ")); + assertEquals( + "Connecticut College", + InstitutionUtil.canonicalizeInstitutionName("\t Connecticut College \n")); } } diff --git a/src/test/java/org/broadinstitute/consent/http/util/JsonSchemaUtilTest.java b/src/test/java/org/broadinstitute/consent/http/util/JsonSchemaUtilTest.java index 8c7a8b9888..a90186c47e 100644 --- a/src/test/java/org/broadinstitute/consent/http/util/JsonSchemaUtilTest.java +++ b/src/test/java/org/broadinstitute/consent/http/util/JsonSchemaUtilTest.java @@ -17,7 +17,8 @@ class JsonSchemaUtilTest { private static JsonSchemaUtil schemaUtil; - private final String datasetRegistrationInstance = """ + private final String datasetRegistrationInstance = + """ { "studyType": "Observational", "studyName": "name", @@ -44,7 +45,6 @@ class JsonSchemaUtilTest { } """; - @BeforeAll static void setUp() { schemaUtil = new JsonSchemaUtil(); @@ -65,8 +65,8 @@ void testIsValidDatasetRegistrationObject_v1_case1() { @Test void testParseDatasetRegistrationObject_v1() { - DatasetRegistrationSchemaV1 instance = schemaUtil.deserializeDatasetRegistration( - datasetRegistrationInstance); + DatasetRegistrationSchemaV1 instance = + schemaUtil.deserializeDatasetRegistration(datasetRegistrationInstance); assertNotNull(instance); assertNotNull(instance.getStudyType()); assertNotNull(instance.getStudyName()); @@ -85,7 +85,8 @@ void testParseDatasetRegistrationObject_v1() { @Test void testValidateDatasetRegistrationObject_v1_valid_date() { - String instance = """ + String instance = + """ { "studyType": "Observational", "studyName": "name", @@ -123,7 +124,8 @@ void testValidateDatasetRegistrationObject_v1_valid_date() { @Test void testValidateDatasetRegistrationObject_v1_invalid_dates() { - String instance = """ + String instance = + """ { "studyType": "Observational", "studyName": "name", @@ -163,7 +165,8 @@ void testValidateDatasetRegistrationObject_v1_invalid_dates() { @Test void testValidateDatasetRegistrationObject_v1_gsr_explanation_conditionally_required() { - String noGsrSelected = """ + String noGsrSelected = + """ { "studyType": "Observational", "studyName": "name", @@ -190,7 +193,8 @@ void testValidateDatasetRegistrationObject_v1_gsr_explanation_conditionally_requ }] } """; - String gsrSelectedNoExplanation = """ + String gsrSelectedNoExplanation = + """ { "studyType": "Observational", "studyName": "name", @@ -218,7 +222,8 @@ void testValidateDatasetRegistrationObject_v1_gsr_explanation_conditionally_requ } """; - String gsrSelectedWithExplanation = """ + String gsrSelectedWithExplanation = + """ { "studyType": "Observational", "studyName": "name", @@ -250,8 +255,8 @@ void testValidateDatasetRegistrationObject_v1_gsr_explanation_conditionally_requ assertNoErrors(errors); errors = schemaUtil.validateSchema_v1(gsrSelectedNoExplanation); - assertFieldHasError(errors, - "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation"); + assertFieldHasError( + errors, "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation"); errors = schemaUtil.validateSchema_v1(gsrSelectedWithExplanation); assertNoErrors(errors); @@ -260,7 +265,8 @@ void testValidateDatasetRegistrationObject_v1_gsr_explanation_conditionally_requ @Test void testValidateDatasetRegistrationObject_v1_dbgap_info_conditionally_required() { - String anvilUseYesRequiresDbGapFields = """ + String anvilUseYesRequiresDbGapFields = + """ { "studyType": "Observational", "studyName": "name", @@ -297,7 +303,8 @@ void testValidateDatasetRegistrationObject_v1_dbgap_info_conditionally_required( @Test void testParseValidateRegistrationObject_v1_nih_admin_info_conditionally_required() { - String anvilUseFundedHaveId = """ + String anvilUseFundedHaveId = + """ { "studyType": "Observational", "studyName": "name", @@ -324,7 +331,8 @@ void testParseValidateRegistrationObject_v1_nih_admin_info_conditionally_require } """; - String anvilUseFundedNoId = """ + String anvilUseFundedNoId = + """ { "studyType": "Observational", "studyName": "name", @@ -351,7 +359,8 @@ void testParseValidateRegistrationObject_v1_nih_admin_info_conditionally_require } """; - String anvilUseNotFundedSeekingToSubmit = """ + String anvilUseNotFundedSeekingToSubmit = + """ { "studyType": "Observational", "studyName": "name", @@ -383,8 +392,8 @@ void testParseValidateRegistrationObject_v1_nih_admin_info_conditionally_require Set fundedHaveIdErrors = schemaUtil.validateSchema_v1(anvilUseFundedHaveId); Set fundedNoIdErrors = schemaUtil.validateSchema_v1(anvilUseFundedNoId); - Set seekingToSubmitErrors = schemaUtil.validateSchema_v1( - anvilUseNotFundedSeekingToSubmit); + Set seekingToSubmitErrors = + schemaUtil.validateSchema_v1(anvilUseNotFundedSeekingToSubmit); assertFieldHasError(fundedHaveIdErrors, "piInstitution"); assertFieldHasError(fundedNoIdErrors, "piInstitution"); @@ -393,12 +402,12 @@ void testParseValidateRegistrationObject_v1_nih_admin_info_conditionally_require assertFieldHasError(fundedHaveIdErrors, "nihGrantContractNumber"); assertFieldHasError(fundedNoIdErrors, "nihGrantContractNumber"); assertFieldHasError(seekingToSubmitErrors, "nihGrantContractNumber"); - } @Test void testParseValidateRegistrationObject_v1_dac_id_conditionally_required() { - String openAccessNoDacId = """ + String openAccessNoDacId = + """ { "studyType": "Observational", "studyName": "name", @@ -424,7 +433,8 @@ void testParseValidateRegistrationObject_v1_dac_id_conditionally_required() { } """; - String controlledAccessNoDacId = """ + String controlledAccessNoDacId = + """ { "studyType": "Observational", "studyName": "name", @@ -451,7 +461,8 @@ void testParseValidateRegistrationObject_v1_dac_id_conditionally_required() { } """; - String noAccessManagementNoDacId = """ + String noAccessManagementNoDacId = + """ { "studyType": "Observational", "studyName": "name", @@ -492,7 +503,8 @@ void testParseValidateRegistrationObject_v1_dac_id_conditionally_required() { @Test void testParseValidateRegistrationObject_v1_consent_group_required() { - String noConsentGroup = """ + String noConsentGroup = + """ { "studyType": "Observational", "studyName": "name", @@ -508,7 +520,8 @@ void testParseValidateRegistrationObject_v1_consent_group_required() { } """; - String emptyConsentGroup = """ + String emptyConsentGroup = + """ { "studyType": "Observational", "studyName": "name", @@ -534,7 +547,8 @@ void testParseValidateRegistrationObject_v1_consent_group_required() { @Test void testValidateDatasetRegistrationObject_v1_file_types_not_required() { - String noFileTypes = """ + String noFileTypes = + """ { "studyType": "Observational", "studyName": "name", @@ -557,7 +571,8 @@ void testValidateDatasetRegistrationObject_v1_file_types_not_required() { } """; - String emptyFileTypes = """ + String emptyFileTypes = + """ { "studyType": "Observational", "studyName": "name", @@ -588,10 +603,10 @@ void testValidateDatasetRegistrationObject_v1_file_types_not_required() { assertNoErrors(errors); } - @Test void testValidateDatasetRegistrationObject_v1_needs_at_least_one_disease() { - String emptyDiseaseSpecificUse = """ + String emptyDiseaseSpecificUse = + """ { "studyType": "Observational", "studyName": "name", @@ -618,7 +633,8 @@ void testValidateDatasetRegistrationObject_v1_needs_at_least_one_disease() { } """; - String filledDiseaseSpecificUse = """ + String filledDiseaseSpecificUse = + """ { "studyType": "Observational", "studyName": "name", @@ -654,7 +670,8 @@ void testValidateDatasetRegistrationObject_v1_needs_at_least_one_disease() { @Test void testValidateDatasetRegistrationObject_v1_only_one_primary_consent() { - String hmbAndGru = """ + String hmbAndGru = + """ { "studyType": "Observational", "studyName": "name", @@ -682,7 +699,8 @@ void testValidateDatasetRegistrationObject_v1_only_one_primary_consent() { } """; - String diseaseSpecificAndOpenAccess = """ + String diseaseSpecificAndOpenAccess = + """ { "studyType": "Observational", "studyName": "name", @@ -719,7 +737,8 @@ void testValidateDatasetRegistrationObject_v1_only_one_primary_consent() { @Test void testValidateDatasetRegistrationObject_v1_url_not_required_if_data_loc_not_determined() { - String notDeterminedNoURL = """ + String notDeterminedNoURL = + """ { "studyType": "Observational", "studyName": "name", @@ -746,7 +765,8 @@ void testValidateDatasetRegistrationObject_v1_url_not_required_if_data_loc_not_d } """; ; - String tdrLocationNoUrl = """ + String tdrLocationNoUrl = + """ { "studyType": "Observational", "studyName": "name", @@ -778,13 +798,12 @@ void testValidateDatasetRegistrationObject_v1_url_not_required_if_data_loc_not_d errors = schemaUtil.validateSchema_v1(tdrLocationNoUrl); assertFieldHasError(errors, "url"); - } - @Test void testValidateDatasetRegistrationObject_v1_empty_string_is_invalid_if_required() { - String instance = """ + String instance = + """ { "studyType": "Observational", "studyName": "", @@ -821,18 +840,19 @@ void testValidateDatasetRegistrationObject_v1_empty_string_is_invalid_if_require assertFieldHasError(errors, "studyDescription"); assertFieldHasError(errors, "piName"); assertFieldHasError(errors, "dbGaPPhsID"); - assertFieldHasError(errors, - "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation"); + assertFieldHasError( + errors, "controlledAccessRequiredForGenomicSummaryResultsGSRRequiredExplanation"); assertFieldHasError(errors, "nihGrantContractNumber"); assertFieldHasError(errors, "consentGroupName"); assertFieldHasError(errors, "url"); } - private void assertNoErrors(Set errors) { - assertTrue(errors.isEmpty(), - String.format("Should be empty, instead was: %s", errors.stream().map( - ValidationMessage::toString).toList())); + assertTrue( + errors.isEmpty(), + String.format( + "Should be empty, instead was: %s", + errors.stream().map(ValidationMessage::toString).toList())); } private void assertHasErrors(Set errors) { diff --git a/src/test/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapterTest.java b/src/test/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapterTest.java index d50670e177..728356ed7d 100644 --- a/src/test/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapterTest.java +++ b/src/test/java/org/broadinstitute/consent/http/util/gson/BlobIdTypeAdapterTest.java @@ -15,9 +15,8 @@ class BlobIdTypeAdapterTest { @Test void testBlobIdTypeAdapter() { - BlobId randomId = BlobId.of( - RandomStringUtils.randomAlphabetic(10), - RandomStringUtils.randomAlphabetic(10)); + BlobId randomId = + BlobId.of(RandomStringUtils.randomAlphabetic(10), RandomStringUtils.randomAlphabetic(10)); String randomIdUri = randomId.toGsUtilUri(); boolean failsSerialization = false; boolean failsDeserialization = false; diff --git a/src/test/java/org/broadinstitute/consent/http/util/gson/GsonTestObject.java b/src/test/java/org/broadinstitute/consent/http/util/gson/GsonTestObject.java index e88f53c9d4..22a7ec62ae 100644 --- a/src/test/java/org/broadinstitute/consent/http/util/gson/GsonTestObject.java +++ b/src/test/java/org/broadinstitute/consent/http/util/gson/GsonTestObject.java @@ -9,15 +9,13 @@ */ class GsonTestObject { - GsonTestObject() { - } + GsonTestObject() {} private transient String transientField; private Date date; private Instant instant; - String getTransientField() { return transientField; } diff --git a/src/test/java/org/broadinstitute/consent/http/util/gson/GsonUtilTest.java b/src/test/java/org/broadinstitute/consent/http/util/gson/GsonUtilTest.java index e6f5c4427e..86dc2a245c 100644 --- a/src/test/java/org/broadinstitute/consent/http/util/gson/GsonUtilTest.java +++ b/src/test/java/org/broadinstitute/consent/http/util/gson/GsonUtilTest.java @@ -52,8 +52,8 @@ void testBlobIdJson() { Gson gson = GsonUtil.buildGson(); boolean serializationFailed = false; boolean deserializationFailed = false; - BlobId id = BlobId.of(RandomStringUtils.randomAlphabetic(20), - RandomStringUtils.randomAlphabetic(20)); + BlobId id = + BlobId.of(RandomStringUtils.randomAlphabetic(20), RandomStringUtils.randomAlphabetic(20)); try { gson.toJson(id); } catch (RuntimeException rte) { @@ -90,7 +90,8 @@ void testBuildJsonWithCustomObjects_Serialization() { assertEquals(2, parsedJsonObj.size()); assertEquals(parsedJsonObj.get("date"), parsedJsonObj.get("instant")); assertEquals(obj.getDate().getTime(), parsedJsonObj.get("date").getAsLong()); - assertEquals(obj.getInstant().truncatedTo(ChronoUnit.MILLIS).toEpochMilli(), + assertEquals( + obj.getInstant().truncatedTo(ChronoUnit.MILLIS).toEpochMilli(), parsedJsonObj.get("instant").getAsLong()); assertFalse(parsedJsonObj.has("transientField")); @@ -100,7 +101,8 @@ void testBuildJsonWithCustomObjects_Serialization() { void testBuildJsonWithCustomObjects_Deserialization() { Gson gson = GsonUtil.buildGson(); - String json = """ + String json = + """ { "transientField": "asdfasdfa", "date": 123456, @@ -114,5 +116,4 @@ void testBuildJsonWithCustomObjects_Deserialization() { assertEquals(567890, parsedObj.getInstant().toEpochMilli()); assertNull(parsedObj.getTransientField()); } - } diff --git a/src/test/java/org/broadinstitute/consent/integration/IntegrationTestHelper.java b/src/test/java/org/broadinstitute/consent/integration/IntegrationTestHelper.java index 61d12cb707..83d695070b 100644 --- a/src/test/java/org/broadinstitute/consent/integration/IntegrationTestHelper.java +++ b/src/test/java/org/broadinstitute/consent/integration/IntegrationTestHelper.java @@ -36,10 +36,11 @@ default SimpleResponse fetchGetResponse(String path) throws Exception { HttpGet request = new HttpGet(getBaseUrl() + path); final ScheduledExecutorService executor = Executors.newScheduledThreadPool(poolSize); executor.schedule(request::cancel, delay, TimeUnit.SECONDS); - return client.execute(request, httpResponse -> - new SimpleResponse( - httpResponse.getCode(), - IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset()))); + return client.execute( + request, + httpResponse -> + new SimpleResponse( + httpResponse.getCode(), + IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset()))); } - } diff --git a/src/test/java/org/broadinstitute/consent/integration/status/StatusTests.java b/src/test/java/org/broadinstitute/consent/integration/status/StatusTests.java index 4496d74d1a..7b9f559553 100644 --- a/src/test/java/org/broadinstitute/consent/integration/status/StatusTests.java +++ b/src/test/java/org/broadinstitute/consent/integration/status/StatusTests.java @@ -10,16 +10,10 @@ /** * These tests are not parameterized because that displays poorly in the results xml, i.e. compare: - * Parameterized: - *