src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ProfileService { public Profile getProfile(DbUser userLite) { final DbUser user = userService.findUserWithAuthoritiesAndPageVisits(userLite.getUserId()).orElse(userLite); final @Nullable Double freeTierUsage = freeTierBillingService.getCachedFreeTierUsage(user); final @Nullable Double freeTierDollarQuota = freeTierBillingService.getUserFreeTierDollarLimit(user); final @Nullable VerifiedInstitutionalAffiliation verifiedInstitutionalAffiliation = verifiedInstitutionalAffiliationDao .findFirstByUser(user) .map(verifiedInstitutionalAffiliationMapper::dbToModel) .orElse(null); final @Nullable DbUserTermsOfService latestTermsOfService = userTermsOfServiceDao.findFirstByUserIdOrderByTosVersionDesc(user.getUserId()).orElse(null); return profileMapper.toModel( user, verifiedInstitutionalAffiliation, latestTermsOfService, freeTierUsage, freeTierDollarQuota); } @Autowired ProfileService( AddressMapper addressMapper, Clock clock, DemographicSurveyMapper demographicSurveyMapper, FreeTierBillingService freeTierBillingService, InstitutionDao institutionDao, InstitutionService institutionService, Javers javers, ProfileAuditor profileAuditor, ProfileMapper profileMapper, Provider<DbUser> userProvider, UserDao userDao, UserService userService, UserTermsOfServiceDao userTermsOfServiceDao, VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao, VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); Profile getProfile(DbUser userLite); void validateAffiliation(Profile profile); void updateProfile(DbUser user, Profile updatedProfile, Profile previousProfile); void cleanProfile(Profile profile); @VisibleForTesting void validateProfile(@Nonnull Profile updatedProfile, @Nullable Profile previousProfile); void validateNewProfile(Profile profile); List<Profile> listAllProfiles(); Profile updateAccountProperties(AccountPropertyUpdate request); }
@Test public void testGetProfile_empty() { assertThat(profileService.getProfile(userDao.save(new DbUser()))).isNotNull(); } @Test public void testGetProfile_emptyDemographics() { DbUser user = new DbUser(); user.setDemographicSurvey(new DbDemographicSurvey()); user = userDao.save(user); assertThat(profileService.getProfile(user)).isNotNull(); } @Test public void testReturnsLastAcknowledgedTermsOfService() { DbUserTermsOfService userTermsOfService = new DbUserTermsOfService(); userTermsOfService.setTosVersion(1); userTermsOfService.setAgreementTime(new Timestamp(1)); when(mockUserTermsOfServiceDao.findFirstByUserIdOrderByTosVersionDesc(1)) .thenReturn(Optional.of(userTermsOfService)); DbUser user = new DbUser(); user.setUserId(1); Profile profile = profileService.getProfile(user); assertThat(profile.getLatestTermsOfServiceVersion()).isEqualTo(1); assertThat(profile.getLatestTermsOfServiceTime()).isEqualTo(1); }
ProfileService { public void validateAffiliation(Profile profile) { VerifiedInstitutionalAffiliation verifiedInstitutionalAffiliation = profile.getVerifiedInstitutionalAffiliation(); if (verifiedInstitutionalAffiliation == null) { throw new BadRequestException("Institutional affiliation cannot be empty"); } Optional<DbInstitution> institution = institutionDao.findOneByShortName( verifiedInstitutionalAffiliation.getInstitutionShortName()); if (!institution.isPresent()) { throw new NotFoundException( String.format( "Could not find institution %s in database", verifiedInstitutionalAffiliation.getInstitutionShortName())); } if (verifiedInstitutionalAffiliation.getInstitutionalRoleEnum() == null) { throw new BadRequestException("Institutional role cannot be empty"); } if (verifiedInstitutionalAffiliation.getInstitutionalRoleEnum().equals(InstitutionalRole.OTHER) && (verifiedInstitutionalAffiliation.getInstitutionalRoleOtherText() == null || verifiedInstitutionalAffiliation.getInstitutionalRoleOtherText().equals(""))) { throw new BadRequestException( "Institutional role description cannot be empty when institutional role is set to Other"); } validateAffiliationEmail(profile); } @Autowired ProfileService( AddressMapper addressMapper, Clock clock, DemographicSurveyMapper demographicSurveyMapper, FreeTierBillingService freeTierBillingService, InstitutionDao institutionDao, InstitutionService institutionService, Javers javers, ProfileAuditor profileAuditor, ProfileMapper profileMapper, Provider<DbUser> userProvider, UserDao userDao, UserService userService, UserTermsOfServiceDao userTermsOfServiceDao, VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao, VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); Profile getProfile(DbUser userLite); void validateAffiliation(Profile profile); void updateProfile(DbUser user, Profile updatedProfile, Profile previousProfile); void cleanProfile(Profile profile); @VisibleForTesting void validateProfile(@Nonnull Profile updatedProfile, @Nullable Profile previousProfile); void validateNewProfile(Profile profile); List<Profile> listAllProfiles(); Profile updateAccountProperties(AccountPropertyUpdate request); }
@Test public void validateInstitutionalAffiliation() { Profile profile = new Profile() .verifiedInstitutionalAffiliation(BROAD_AFFILIATION) .contactEmail("[email protected]"); when(mockInstitutionDao.findOneByShortName("Broad")).thenReturn(Optional.of(BROAD_INSTITUTION)); DbVerifiedInstitutionalAffiliation dbVerifiedInstitutionalAffiliation = new DbVerifiedInstitutionalAffiliation(); dbVerifiedInstitutionalAffiliation.setInstitution(BROAD_INSTITUTION); dbVerifiedInstitutionalAffiliation.setInstitutionalRoleEnum(InstitutionalRole.ADMIN); when(mockVerifiedInstitutionalAffiliationMapper.modelToDbWithoutUser( BROAD_AFFILIATION, mockInstitutionService)) .thenReturn(dbVerifiedInstitutionalAffiliation); when(mockInstitutionService.validateAffiliation( dbVerifiedInstitutionalAffiliation, "[email protected]")) .thenReturn(true); profileService.validateAffiliation(profile); ArgumentCaptor<DbVerifiedInstitutionalAffiliation> affiliationSpy = ArgumentCaptor.forClass(DbVerifiedInstitutionalAffiliation.class); ArgumentCaptor<String> unusedSpy = ArgumentCaptor.forClass(String.class); verify(mockInstitutionService) .validateAffiliation(affiliationSpy.capture(), unusedSpy.capture()); assertThat(affiliationSpy.getValue().getInstitution().getShortName()).isEqualTo("Broad"); } @Test public void validateInstitutionalAffiliation_other() { VerifiedInstitutionalAffiliation affiliation = new VerifiedInstitutionalAffiliation() .institutionShortName("Broad") .institutionDisplayName("The Broad Institute") .institutionalRoleEnum(InstitutionalRole.OTHER) .institutionalRoleOtherText("Kibitzing"); Profile profile = new Profile() .verifiedInstitutionalAffiliation(affiliation) .contactEmail("[email protected]"); when(mockInstitutionDao.findOneByShortName("Broad")).thenReturn(Optional.of(BROAD_INSTITUTION)); DbVerifiedInstitutionalAffiliation dbVerifiedInstitutionalAffiliation = new DbVerifiedInstitutionalAffiliation(); dbVerifiedInstitutionalAffiliation.setInstitution(BROAD_INSTITUTION); dbVerifiedInstitutionalAffiliation.setInstitutionalRoleEnum(InstitutionalRole.ADMIN); when(mockVerifiedInstitutionalAffiliationMapper.modelToDbWithoutUser( affiliation, mockInstitutionService)) .thenReturn(dbVerifiedInstitutionalAffiliation); when(mockInstitutionService.validateAffiliation( dbVerifiedInstitutionalAffiliation, "[email protected]")) .thenReturn(true); profileService.validateAffiliation(profile); ArgumentCaptor<DbVerifiedInstitutionalAffiliation> affiliationSpy = ArgumentCaptor.forClass(DbVerifiedInstitutionalAffiliation.class); ArgumentCaptor<String> unusedSpy = ArgumentCaptor.forClass(String.class); verify(mockInstitutionService) .validateAffiliation(affiliationSpy.capture(), unusedSpy.capture()); assertThat(affiliationSpy.getValue().getInstitution().getShortName()).isEqualTo("Broad"); } @Test(expected = BadRequestException.class) public void validateInstitutionalAffiliation_noAffiliation() { profileService.validateAffiliation(new Profile()); } @Test(expected = NotFoundException.class) public void validateInstitutionalAffiliation_noInstitution() { Profile profile = new Profile().verifiedInstitutionalAffiliation(BROAD_AFFILIATION); when(mockInstitutionDao.findOneByShortName("Broad")).thenReturn(Optional.empty()); profileService.validateAffiliation(profile); } @Test(expected = BadRequestException.class) public void validateInstitutionalAffiliation_noRole() { VerifiedInstitutionalAffiliation affiliation = new VerifiedInstitutionalAffiliation() .institutionShortName("Broad") .institutionDisplayName("The Broad Institute"); Profile profile = new Profile().verifiedInstitutionalAffiliation(affiliation); when(mockInstitutionDao.findOneByShortName("Broad")).thenReturn(Optional.of(BROAD_INSTITUTION)); profileService.validateAffiliation(profile); } @Test(expected = BadRequestException.class) public void validateInstitutionalAffiliation_noOtherText() { VerifiedInstitutionalAffiliation affiliation = new VerifiedInstitutionalAffiliation() .institutionShortName("Broad") .institutionDisplayName("The Broad Institute") .institutionalRoleEnum(InstitutionalRole.OTHER); Profile profile = new Profile().verifiedInstitutionalAffiliation(affiliation); when(mockInstitutionDao.findOneByShortName("Broad")).thenReturn(Optional.of(BROAD_INSTITUTION)); profileService.validateAffiliation(profile); } @Test(expected = BadRequestException.class) public void validateInstitutionalAffilation_badEmail() { VerifiedInstitutionalAffiliation affiliation = new VerifiedInstitutionalAffiliation() .institutionShortName("Broad") .institutionDisplayName("The Broad Institute") .institutionalRoleEnum(InstitutionalRole.OTHER) .institutionalRoleOtherText("Kibitzing"); Profile profile = new Profile() .verifiedInstitutionalAffiliation(affiliation) .contactEmail("[email protected]"); when(mockInstitutionDao.findOneByShortName("Broad")).thenReturn(Optional.of(BROAD_INSTITUTION)); when(mockInstitutionService.validateAffiliation( any(DbVerifiedInstitutionalAffiliation.class), anyString())) .thenReturn(false); DbVerifiedInstitutionalAffiliation dbVerifiedInstitutionalAffiliation = new DbVerifiedInstitutionalAffiliation(); dbVerifiedInstitutionalAffiliation.setInstitution(BROAD_INSTITUTION); when(mockVerifiedInstitutionalAffiliationMapper.modelToDbWithoutUser( affiliation, mockInstitutionService)) .thenReturn(dbVerifiedInstitutionalAffiliation); profileService.validateAffiliation(profile); }
ProfileService { public void updateProfile(DbUser user, Profile updatedProfile, Profile previousProfile) { cleanProfile(updatedProfile); cleanProfile(previousProfile); validateProfile(updatedProfile, previousProfile); if (!user.getGivenName().equalsIgnoreCase(updatedProfile.getGivenName()) || !user.getFamilyName().equalsIgnoreCase(updatedProfile.getFamilyName())) { userService.setDataUseAgreementNameOutOfDate( updatedProfile.getGivenName(), updatedProfile.getFamilyName()); } Timestamp now = new Timestamp(clock.instant().toEpochMilli()); user.setContactEmail(updatedProfile.getContactEmail()); user.setGivenName(updatedProfile.getGivenName()); user.setFamilyName(updatedProfile.getFamilyName()); user.setAreaOfResearch(updatedProfile.getAreaOfResearch()); user.setProfessionalUrl(updatedProfile.getProfessionalUrl()); user.setAddress(addressMapper.addressToDbAddress(updatedProfile.getAddress())); Optional.ofNullable(user.getAddress()).ifPresent(address -> address.setUser(user)); DbDemographicSurvey dbDemographicSurvey = demographicSurveyMapper.demographicSurveyToDbDemographicSurvey( updatedProfile.getDemographicSurvey()); if (user.getDemographicSurveyCompletionTime() == null && dbDemographicSurvey != null) { user.setDemographicSurveyCompletionTime(now); } if (dbDemographicSurvey != null && dbDemographicSurvey.getUser() == null) { dbDemographicSurvey.setUser(user); } user.setDemographicSurvey(dbDemographicSurvey); user.setLastModifiedTime(now); userService.updateUserWithConflictHandling(user); DbVerifiedInstitutionalAffiliation newAffiliation = verifiedInstitutionalAffiliationMapper.modelToDbWithoutUser( updatedProfile.getVerifiedInstitutionalAffiliation(), institutionService); newAffiliation.setUser( user); verifiedInstitutionalAffiliationDao .findFirstByUser(user) .map(DbVerifiedInstitutionalAffiliation::getVerifiedInstitutionalAffiliationId) .ifPresent(newAffiliation::setVerifiedInstitutionalAffiliationId); this.verifiedInstitutionalAffiliationDao.save(newAffiliation); final Profile appliedUpdatedProfile = getProfile(user); profileAuditor.fireUpdateAction(previousProfile, appliedUpdatedProfile); } @Autowired ProfileService( AddressMapper addressMapper, Clock clock, DemographicSurveyMapper demographicSurveyMapper, FreeTierBillingService freeTierBillingService, InstitutionDao institutionDao, InstitutionService institutionService, Javers javers, ProfileAuditor profileAuditor, ProfileMapper profileMapper, Provider<DbUser> userProvider, UserDao userDao, UserService userService, UserTermsOfServiceDao userTermsOfServiceDao, VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao, VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); Profile getProfile(DbUser userLite); void validateAffiliation(Profile profile); void updateProfile(DbUser user, Profile updatedProfile, Profile previousProfile); void cleanProfile(Profile profile); @VisibleForTesting void validateProfile(@Nonnull Profile updatedProfile, @Nullable Profile previousProfile); void validateNewProfile(Profile profile); List<Profile> listAllProfiles(); Profile updateAccountProperties(AccountPropertyUpdate request); }
@Test(expected = BadRequestException.class) public void updateProfile_cant_change_contactEmail() { Profile previousProfile = createValidProfile().contactEmail("[email protected]"); Profile updatedProfile = createValidProfile().contactEmail("[email protected]"); DbUser user = new DbUser(); user.setUserId(10); user.setGivenName("John"); user.setFamilyName("Doe"); profileService.updateProfile(user, updatedProfile, previousProfile); }
ProfileService { @VisibleForTesting public void validateProfile(@Nonnull Profile updatedProfile, @Nullable Profile previousProfile) { final Diff diff = javers.compare(previousProfile, updatedProfile); validateProfileForCorrectness(diff, updatedProfile); if (userService.hasAuthority(userProvider.get().getUserId(), Authority.ACCESS_CONTROL_ADMIN)) { validateChangesAllowedByAdmin(diff); } else { validateChangesAllowedByUser(diff); } } @Autowired ProfileService( AddressMapper addressMapper, Clock clock, DemographicSurveyMapper demographicSurveyMapper, FreeTierBillingService freeTierBillingService, InstitutionDao institutionDao, InstitutionService institutionService, Javers javers, ProfileAuditor profileAuditor, ProfileMapper profileMapper, Provider<DbUser> userProvider, UserDao userDao, UserService userService, UserTermsOfServiceDao userTermsOfServiceDao, VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao, VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); Profile getProfile(DbUser userLite); void validateAffiliation(Profile profile); void updateProfile(DbUser user, Profile updatedProfile, Profile previousProfile); void cleanProfile(Profile profile); @VisibleForTesting void validateProfile(@Nonnull Profile updatedProfile, @Nullable Profile previousProfile); void validateNewProfile(Profile profile); List<Profile> listAllProfiles(); Profile updateAccountProperties(AccountPropertyUpdate request); }
@Test public void validateProfile_noChangesOnEmptyProfile() { profileService.validateProfile(new Profile(), new Profile()); } @Test(expected = BadRequestException.class) public void validateProfile_usernameChanged_user() { profileService.validateProfile(new Profile().username("new"), new Profile().username("old")); } @Test(expected = BadRequestException.class) public void validateProfile_usernameChanged_admin() { when(mockUserService.hasAuthority(loggedInUser.getUserId(), Authority.ACCESS_CONTROL_ADMIN)) .thenReturn(true); profileService.validateProfile(new Profile().username("new"), new Profile().username("old")); } @Test(expected = BadRequestException.class) public void validateProfile_usernameTooShort() { profileService.validateProfile(new Profile().username("ab"), new Profile()); } @Test(expected = BadRequestException.class) public void validateProfile_usernameTooLong() { profileService.validateProfile( new Profile().username(StringUtils.repeat("asdf", 30)), new Profile()); } @Test(expected = BadRequestException.class) public void validateProfile_contactEmailChanged_user() { profileService.validateProfile( new Profile().contactEmail("[email protected]"), new Profile().contactEmail("[email protected]")); } @Test public void validateProfile_contactEmailChanged_admin() { when(mockUserService.hasAuthority(loggedInUser.getUserId(), Authority.ACCESS_CONTROL_ADMIN)) .thenReturn(true); profileService.validateProfile( new Profile().contactEmail("[email protected]"), new Profile().contactEmail("[email protected]")); } @Test(expected = BadRequestException.class) public void validateProfile_givenNameTooShort() { Profile newProfile = new Profile().givenName(""); profileService.validateProfile(newProfile, new Profile()); } @Test(expected = BadRequestException.class) public void validateProfile_FamilyNameTooLong() { Profile newProfile = new Profile().familyName(StringUtils.repeat("123", 30)); profileService.validateProfile(newProfile, new Profile()); } @Test(expected = BadRequestException.class) public void validateProfile_addressRemoved() { Profile oldProfile = new Profile().address(new Address().streetAddress1("asdf")); Profile newProfile = new Profile(); profileService.validateProfile(newProfile, oldProfile); } @Test(expected = BadRequestException.class) public void validateProfile_addressRemoveZipCode() { Address oldAddress = new Address() .streetAddress1("asdf") .city("asdf") .state("asdf") .country("asdf") .zipCode("asdf"); Address newAddress = new Address().streetAddress1("asdf").city("asdf").state("asdf").country("asdf"); profileService.validateProfile( new Profile().address(newAddress), new Profile().address(oldAddress)); } @Test(expected = BadRequestException.class) public void validateProfile_addressIncomplete() { Profile newProfile = new Profile().address(new Address().streetAddress1("asdf")); profileService.validateProfile(newProfile, new Profile()); } @Test(expected = BadRequestException.class) public void validateProfile_EmptyAreaOfResearch() { Profile newProfile = new Profile().areaOfResearch(""); profileService.validateProfile(newProfile, new Profile()); }
ProfileService { public void validateNewProfile(Profile profile) throws BadRequestException { final Profile dummyProfile = null; validateProfileForCorrectness(dummyProfile, profile); } @Autowired ProfileService( AddressMapper addressMapper, Clock clock, DemographicSurveyMapper demographicSurveyMapper, FreeTierBillingService freeTierBillingService, InstitutionDao institutionDao, InstitutionService institutionService, Javers javers, ProfileAuditor profileAuditor, ProfileMapper profileMapper, Provider<DbUser> userProvider, UserDao userDao, UserService userService, UserTermsOfServiceDao userTermsOfServiceDao, VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao, VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); Profile getProfile(DbUser userLite); void validateAffiliation(Profile profile); void updateProfile(DbUser user, Profile updatedProfile, Profile previousProfile); void cleanProfile(Profile profile); @VisibleForTesting void validateProfile(@Nonnull Profile updatedProfile, @Nullable Profile previousProfile); void validateNewProfile(Profile profile); List<Profile> listAllProfiles(); Profile updateAccountProperties(AccountPropertyUpdate request); }
@Test(expected = BadRequestException.class) public void validateProfile_emptyNewObject() { profileService.validateNewProfile(new Profile()); }
FreeTierBillingService { public double getUserFreeTierDollarLimit(DbUser user) { return Optional.ofNullable(user.getFreeTierCreditsLimitDollarsOverride()) .orElse(workbenchConfigProvider.get().billing.defaultFreeCreditsDollarLimit); } @Autowired FreeTierBillingService( BigQueryService bigQueryService, Clock clock, MailService mailService, Provider<WorkbenchConfig> workbenchConfigProvider, UserDao userDao, UserServiceAuditor userServiceAuditor, WorkspaceDao workspaceDao, WorkspaceFreeTierUsageDao workspaceFreeTierUsageDao); double getWorkspaceFreeTierBillingUsage(DbWorkspace dbWorkspace); void checkFreeTierBillingUsage(); @Nullable Double getCachedFreeTierUsage(DbUser user); boolean userHasRemainingFreeTierCredits(DbUser user); double getUserFreeTierDollarLimit(DbUser user); boolean maybeSetDollarLimitOverride(DbUser user, double newDollarLimit); Map<Long, Double> getUserIdToTotalCost(); }
@Test public void getUserFreeTierDollarLimit_default() { final DbUser user = createUser(SINGLE_WORKSPACE_TEST_USER); final double initialFreeCreditsDollarLimit = 1.0; workbenchConfig.billing.defaultFreeCreditsDollarLimit = initialFreeCreditsDollarLimit; assertWithinBillingTolerance( freeTierBillingService.getUserFreeTierDollarLimit(user), initialFreeCreditsDollarLimit); final double fractionalFreeCreditsDollarLimit = 123.456; workbenchConfig.billing.defaultFreeCreditsDollarLimit = fractionalFreeCreditsDollarLimit; assertWithinBillingTolerance( freeTierBillingService.getUserFreeTierDollarLimit(user), fractionalFreeCreditsDollarLimit); }
ProfileService { public List<Profile> listAllProfiles() { final Set<DbUser> usersHeavy = userService.findAllUsersWithAuthoritiesAndPageVisits(); final Map<Long, VerifiedInstitutionalAffiliation> userIdToAffiliationModel = StreamSupport.stream(verifiedInstitutionalAffiliationDao.findAll().spliterator(), false) .collect( ImmutableMap.toImmutableMap( (DbVerifiedInstitutionalAffiliation a) -> a.getUser().getUserId(), verifiedInstitutionalAffiliationMapper::dbToModel)); final Multimap<Long, DbUserTermsOfService> userIdToTosRecords = Multimaps.index(userTermsOfServiceDao.findAll(), DbUserTermsOfService::getUserId); final Map<Long, DbUserTermsOfService> userIdToMostRecentTos = userIdToTosRecords.asMap().entrySet().stream() .collect( ImmutableMap.toImmutableMap( Entry::getKey, e -> e.getValue().stream() .max(Comparator.comparing(DbUserTermsOfService::getAgreementTime)) .orElse( null))); final Map<Long, Double> userIdToFreeTierUsage = freeTierBillingService.getUserIdToTotalCost(); final Map<Long, Double> userIdToQuota = usersHeavy.stream() .collect( ImmutableMap.toImmutableMap( DbUser::getUserId, freeTierBillingService::getUserFreeTierDollarLimit)); return usersHeavy.stream() .map( dbUser -> profileMapper.toModel( dbUser, userIdToAffiliationModel.get(dbUser.getUserId()), userIdToMostRecentTos.get(dbUser.getUserId()), userIdToFreeTierUsage.get(dbUser.getUserId()), userIdToQuota.get(dbUser.getUserId()))) .collect(ImmutableList.toImmutableList()); } @Autowired ProfileService( AddressMapper addressMapper, Clock clock, DemographicSurveyMapper demographicSurveyMapper, FreeTierBillingService freeTierBillingService, InstitutionDao institutionDao, InstitutionService institutionService, Javers javers, ProfileAuditor profileAuditor, ProfileMapper profileMapper, Provider<DbUser> userProvider, UserDao userDao, UserService userService, UserTermsOfServiceDao userTermsOfServiceDao, VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao, VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); Profile getProfile(DbUser userLite); void validateAffiliation(Profile profile); void updateProfile(DbUser user, Profile updatedProfile, Profile previousProfile); void cleanProfile(Profile profile); @VisibleForTesting void validateProfile(@Nonnull Profile updatedProfile, @Nullable Profile previousProfile); void validateNewProfile(Profile profile); List<Profile> listAllProfiles(); Profile updateAccountProperties(AccountPropertyUpdate request); }
@Test public void testListAllProfiles_noUsers() { final List<Profile> profiles = profileService.listAllProfiles(); assertThat(profiles).isEmpty(); } @Test public void testListAllProfiles_someUsers() { final DbUser user1 = new DbUser(); user1.setUserId(101L); user1.setUsername("[email protected]"); user1.setDisabled(false); user1.setAboutYou("Just a test user"); final DbUser user2 = new DbUser(); user2.setUserId(102l); user2.setUsername("[email protected]"); user2.setDisabled(true); user2.setAboutYou("a disabled user account"); final DbUser user3 = new DbUser(); user3.setUserId(103l); user3.setUsername("[email protected]"); user3.setDisabled(true); user3.setAboutYou("where to begin..."); doReturn(ImmutableSet.of(user1, user2, user3)) .when(mockUserService) .findAllUsersWithAuthoritiesAndPageVisits(); doReturn( ImmutableMap.of( user1.getUserId(), 1.75, user2.getUserId(), 67.53, user3.getUserId(), 0.00)) .when(mockFreeTierBillingService) .getUserIdToTotalCost(); doReturn(100.00).when(mockFreeTierBillingService).getUserFreeTierDollarLimit(user1); doReturn(200.00).when(mockFreeTierBillingService).getUserFreeTierDollarLimit(user2); doReturn(50.00).when(mockFreeTierBillingService).getUserFreeTierDollarLimit(user3); final DbUserTermsOfService dbTos1 = new DbUserTermsOfService(); dbTos1.setUserTermsOfServiceId(1L); dbTos1.setUserId(user1.getUserId()); dbTos1.setTosVersion(1); dbTos1.setAgreementTime(Timestamp.from(CLOCK.instant())); final DbUserTermsOfService dbTos2 = new DbUserTermsOfService(); dbTos2.setUserTermsOfServiceId(2L); dbTos2.setUserId(user2.getUserId()); dbTos2.setTosVersion(2); dbTos2.setAgreementTime(Timestamp.from(CLOCK.instant().plusSeconds(3600L))); final DbUserTermsOfService dbTos3 = new DbUserTermsOfService(); dbTos3.setUserTermsOfServiceId(3L); dbTos3.setUserId(user2.getUserId()); dbTos3.setTosVersion(2); final Timestamp tos3time = Timestamp.from(CLOCK.instant().plus(Duration.ofDays(30))); dbTos3.setAgreementTime(tos3time); doReturn(ImmutableList.of(dbTos1, dbTos2, dbTos3)).when(mockUserTermsOfServiceDao).findAll(); final DbInstitution dbInstitution1 = new DbInstitution(); dbInstitution1.setShortName("caltech"); dbInstitution1.setDisplayName("California Institute of Technology"); dbInstitution1.setOrganizationTypeEnum(OrganizationType.ACADEMIC_RESEARCH_INSTITUTION); dbInstitution1.setDuaTypeEnum(DuaType.MASTER); dbInstitution1.setInstitutionId(1L); final DbVerifiedInstitutionalAffiliation dbAffiliation1 = new DbVerifiedInstitutionalAffiliation(); dbAffiliation1.setVerifiedInstitutionalAffiliationId(1L); dbAffiliation1.setUser(user1); dbAffiliation1.setInstitution(dbInstitution1); doReturn(ImmutableList.of(dbAffiliation1)) .when(mockVerifiedInstitutionalAffiliationDao) .findAll(); final VerifiedInstitutionalAffiliation verifiedInstitutionalAffiliation1 = new VerifiedInstitutionalAffiliation() .institutionShortName(dbInstitution1.getShortName()) .institutionDisplayName(dbInstitution1.getDisplayName()) .institutionalRoleOtherText(dbInstitution1.getOrganizationTypeOtherText()); doReturn(verifiedInstitutionalAffiliation1) .when(mockVerifiedInstitutionalAffiliationMapper) .dbToModel(dbAffiliation1); final List<Profile> profiles = profileService.listAllProfiles(); assertThat(profiles).hasSize(3); assertThat(profiles.get(0).getVerifiedInstitutionalAffiliation().getInstitutionDisplayName()) .isEqualTo(dbInstitution1.getDisplayName()); assertThat(profiles.get(1).getUserId()).isEqualTo(user2.getUserId()); assertThat(profiles.get(1).getFreeTierDollarQuota()).isWithin(0.02).of(200.00); assertThat((double) profiles.get(1).getLatestTermsOfServiceTime()) .isWithin(500.0) .of(tos3time.getTime()); assertThat(profiles.get(2).getVerifiedInstitutionalAffiliation()).isNull(); assertThat(profiles.get(2).getFreeTierUsage()).isWithin(0.02).of(0.00); }
Matchers { public static Optional<String> getGroup(Matcher matcher, String groupName) { if (matcher.find()) { return Optional.ofNullable(matcher.group(groupName)); } else { return Optional.empty(); } } private Matchers(); static Optional<String> getGroup(Matcher matcher, String groupName); static Optional<String> getGroup(Pattern pattern, String input, String groupName); static String replaceAllInMap(Map<Pattern, String> patternToReplacement, String source); }
@Test public void itMatchesGroup() { final Optional<String> nextLetter = Matchers.getGroup(SINGLE_GROUP_PATTERN, "abcdf", GROUP_NAME); assertThat(nextLetter).hasValue("f"); } @Test public void getGroup_noMatch() { final Optional<String> nextLetter = Matchers.getGroup(SINGLE_GROUP_PATTERN, "abcdk", GROUP_NAME); assertThat(nextLetter).isEmpty(); } @Test public void testGetGroup_noSuchGroup() { final Optional<String> nextLetter = Matchers.getGroup(SINGLE_GROUP_PATTERN, "abcdk", "oops"); assertThat(nextLetter).isEmpty(); } @Test public void testGetGroup_hyphens() { final Pattern VM_NAME_PATTERN = Pattern.compile("all-of-us-(?<userid>\\d+)-m"); final Optional<String> suffix = Matchers.getGroup(VM_NAME_PATTERN, "all-of-us-2222-m", "userid"); assertThat(suffix).hasValue("2222"); }
Matchers { public static String replaceAllInMap(Map<Pattern, String> patternToReplacement, String source) { String result = source; for (Map.Entry<Pattern, String> entry : patternToReplacement.entrySet()) { result = entry.getKey().matcher(result).replaceAll(entry.getValue()); } return result; } private Matchers(); static Optional<String> getGroup(Matcher matcher, String groupName); static Optional<String> getGroup(Pattern pattern, String input, String groupName); static String replaceAllInMap(Map<Pattern, String> patternToReplacement, String source); }
@Test public void testReplaceAll() { final String input = "food is good for you! 2food3."; final Map<Pattern, String> patternToReplacement = ImmutableMap.of( Pattern.compile("\\bfood\\b"), "exercise", Pattern.compile("\\s+"), "_", Pattern.compile("\\dfood\\d\\."), "<3"); final String updated = Matchers.replaceAllInMap(patternToReplacement, input); assertThat(updated).contains("exercise_is_good_for_you!_<3"); } @Test public void testReplaceAll_parameters() { final String input = "AND @after <= TIMESTAMP_MILLIS(CAST(jsonPayload.timestamp AS INT64))"; final Map<Pattern, String> patternToReplacement = ImmutableMap.of( Pattern.compile("(?<=\\W)@after\\b"), "TIMESTAMP 'WHENEVER'", Pattern.compile("\\bAS\\b"), "AS IF"); final String updated = Matchers.replaceAllInMap(patternToReplacement, input); assertThat(updated) .isEqualTo( "AND TIMESTAMP 'WHENEVER' <= TIMESTAMP_MILLIS(CAST(jsonPayload.timestamp AS IF INT64))"); } @Test public void testReplaceAll_multipleOccurrences() { final String input = "And she'll have fun fun fun til her daddy takes the T-bird away."; final Map<Pattern, String> patternToReplacement = ImmutableMap.of(Pattern.compile("\\bfun\\b"), "cat"); final String updated = Matchers.replaceAllInMap(patternToReplacement, input); assertThat(updated).contains("have cat cat cat"); } @Test public void testReplaceAll_emptyMap() { final String input = "food is good for you! 2food3."; final String updated = Matchers.replaceAllInMap(Collections.emptyMap(), input); assertThat(updated).isEqualTo(input); }
FreeTierBillingService { public boolean userHasRemainingFreeTierCredits(DbUser user) { final double usage = Optional.ofNullable(getCachedFreeTierUsage(user)).orElse(0.0); return !costAboveLimit(user, usage); } @Autowired FreeTierBillingService( BigQueryService bigQueryService, Clock clock, MailService mailService, Provider<WorkbenchConfig> workbenchConfigProvider, UserDao userDao, UserServiceAuditor userServiceAuditor, WorkspaceDao workspaceDao, WorkspaceFreeTierUsageDao workspaceFreeTierUsageDao); double getWorkspaceFreeTierBillingUsage(DbWorkspace dbWorkspace); void checkFreeTierBillingUsage(); @Nullable Double getCachedFreeTierUsage(DbUser user); boolean userHasRemainingFreeTierCredits(DbUser user); double getUserFreeTierDollarLimit(DbUser user); boolean maybeSetDollarLimitOverride(DbUser user, double newDollarLimit); Map<Long, Double> getUserIdToTotalCost(); }
@Test public void userHasRemainingFreeTierCredits_newUser() { workbenchConfig.billing.defaultFreeCreditsDollarLimit = 100.0; final DbUser user1 = createUser(SINGLE_WORKSPACE_TEST_USER); assertThat(freeTierBillingService.userHasRemainingFreeTierCredits(user1)).isTrue(); } @Test public void userHasRemainingFreeTierCredits() { workbenchConfig.billing.defaultFreeCreditsDollarLimit = 100.0; final DbUser user1 = createUser(SINGLE_WORKSPACE_TEST_USER); createWorkspace(user1, SINGLE_WORKSPACE_TEST_PROJECT); doReturn(mockBQTableSingleResult(99.99)).when(bigQueryService).executeQuery(any()); freeTierBillingService.checkFreeTierBillingUsage(); assertThat(freeTierBillingService.userHasRemainingFreeTierCredits(user1)).isTrue(); doReturn(mockBQTableSingleResult(100.01)).when(bigQueryService).executeQuery(any()); freeTierBillingService.checkFreeTierBillingUsage(); assertThat(freeTierBillingService.userHasRemainingFreeTierCredits(user1)).isFalse(); workbenchConfig.billing.defaultFreeCreditsDollarLimit = 200.0; assertThat(freeTierBillingService.userHasRemainingFreeTierCredits(user1)).isTrue(); }
FieldValues { public static Optional<Long> getLong(FieldValueList row, int index) { return FieldValues.getValue(row, index).map(FieldValue::getLongValue); } private FieldValues(); static Optional<FieldValue> getValue(FieldValueList row, int index); static Optional<FieldValue> getValue(FieldValueList row, String fieldName); static Optional<Boolean> getBoolean(FieldValueList row, int index); static Optional<Boolean> getBoolean(FieldValueList row, String fieldName); static Optional<byte[]> getBytes(FieldValueList row, int index); static Optional<byte[]> getBytes(FieldValueList row, String fieldName); static Optional<Double> getDouble(FieldValueList row, int index); static Optional<Double> getDouble(FieldValueList row, String fieldName); static Optional<Long> getLong(FieldValueList row, int index); static Optional<Long> getLong(FieldValueList row, String fieldName); static Optional<BigDecimal> getNumeric(FieldValueList row, int index); static Optional<BigDecimal> getNumeric(FieldValueList row, String fieldName); static Optional<FieldValueList> getRecord(FieldValueList row, int index); static Optional<FieldValueList> getRecord(FieldValueList row, String fieldName); static Optional<List<FieldValue>> getRepeated(FieldValueList row, int index); static Optional<List<FieldValue>> getRepeated(FieldValueList row, String fieldName); static Optional<String> getString(FieldValueList row, int index); static Optional<String> getString(FieldValueList row, String fieldName); static Optional<Long> getTimestampMicroseconds(FieldValueList row, int index); static Optional<Long> getTimestampMicroseconds(FieldValueList row, String fieldName); static Optional<DateTime> getDateTime(FieldValueList row, int index); static Optional<OffsetDateTime> getDateTime(FieldValueList row, String fieldName); @VisibleForTesting static FieldValueList buildFieldValueList(FieldList schemaFieldList, List<Object> values); static final int MICROSECONDS_IN_MILLISECOND; }
@Test public void testGetLong() { final Optional<Long> result = FieldValues.getLong(ROW_1, 0); assertThat(result.isPresent()).isTrue(); assertThat(result.get()).isEqualTo(LONG_VALUE); assertThat(FieldValues.getLong(ROW_1, 1).isPresent()).isFalse(); assertThat(FieldValues.getLong(ROW_1, "null_int_field").isPresent()).isFalse(); } @Test(expected = IllegalArgumentException.class) public void testGetLong_invalidFieldName() { FieldValues.getLong(ROW_1, "wrong_name"); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testGetLong_invalidIndex() { FieldValues.getLong(ROW_1, 999); }
FieldValues { public static Optional<Double> getDouble(FieldValueList row, int index) { return FieldValues.getValue(row, index).map(FieldValue::getDoubleValue); } private FieldValues(); static Optional<FieldValue> getValue(FieldValueList row, int index); static Optional<FieldValue> getValue(FieldValueList row, String fieldName); static Optional<Boolean> getBoolean(FieldValueList row, int index); static Optional<Boolean> getBoolean(FieldValueList row, String fieldName); static Optional<byte[]> getBytes(FieldValueList row, int index); static Optional<byte[]> getBytes(FieldValueList row, String fieldName); static Optional<Double> getDouble(FieldValueList row, int index); static Optional<Double> getDouble(FieldValueList row, String fieldName); static Optional<Long> getLong(FieldValueList row, int index); static Optional<Long> getLong(FieldValueList row, String fieldName); static Optional<BigDecimal> getNumeric(FieldValueList row, int index); static Optional<BigDecimal> getNumeric(FieldValueList row, String fieldName); static Optional<FieldValueList> getRecord(FieldValueList row, int index); static Optional<FieldValueList> getRecord(FieldValueList row, String fieldName); static Optional<List<FieldValue>> getRepeated(FieldValueList row, int index); static Optional<List<FieldValue>> getRepeated(FieldValueList row, String fieldName); static Optional<String> getString(FieldValueList row, int index); static Optional<String> getString(FieldValueList row, String fieldName); static Optional<Long> getTimestampMicroseconds(FieldValueList row, int index); static Optional<Long> getTimestampMicroseconds(FieldValueList row, String fieldName); static Optional<DateTime> getDateTime(FieldValueList row, int index); static Optional<OffsetDateTime> getDateTime(FieldValueList row, String fieldName); @VisibleForTesting static FieldValueList buildFieldValueList(FieldList schemaFieldList, List<Object> values); static final int MICROSECONDS_IN_MILLISECOND; }
@Test public void testGetDouble() { assertThat(FieldValues.getDouble(ROW_1, 2).isPresent()).isTrue(); assertThat(FieldValues.getDouble(ROW_1, "double_field").get()) .isWithin(TOLERANCE) .of(DOUBLE_VALUE); }
CloudTaskInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getMethod().equals(HttpMethods.OPTIONS)) { return true; } HandlerMethod method = (HandlerMethod) handler; ApiOperation apiOp = AnnotationUtils.findAnnotation(method.getMethod(), ApiOperation.class); if (apiOp == null) { return true; } boolean requireCloudTaskHeader = false; for (String tag : apiOp.tags()) { if (CLOUD_TASK_TAG.equals(tag)) { requireCloudTaskHeader = true; break; } } boolean hasQueueNameHeader = VALID_QUEUE_NAME_SET.contains(request.getHeader(QUEUE_NAME_REQUEST_HEADER)); if (requireCloudTaskHeader && !hasQueueNameHeader) { response.sendError( HttpServletResponse.SC_FORBIDDEN, String.format( "cloud task endpoints are only invocable via app engine cloudTask, and " + "require the '%s' header", QUEUE_NAME_REQUEST_HEADER)); return false; } return true; } @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler); static final String QUEUE_NAME_REQUEST_HEADER; static final Set<String> VALID_QUEUE_NAME_SET; }
@Test public void preHandleOptions_OPTIONS() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.OPTIONS); assertThat(interceptor.preHandle(request, response, handler)).isTrue(); } @Test public void prehandleForCloudTaskNoHeader() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.POST); when(handler.getMethod()) .thenReturn( CloudTaskRdrExportApi.class.getMethod(CLOUD_TASK_METHOD_NAME, ArrayOfLong.class)); assertThat(interceptor.preHandle(request, response, handler)).isFalse(); } @Test public void prehandleForCloudTaskWithBadHeader() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.POST); when(handler.getMethod()) .thenReturn( CloudTaskRdrExportApi.class.getMethod(CLOUD_TASK_METHOD_NAME, ArrayOfLong.class)); when(request.getHeader(CloudTaskInterceptor.QUEUE_NAME_REQUEST_HEADER)).thenReturn("asdf"); assertThat(interceptor.preHandle(request, response, handler)).isFalse(); } @Test public void prehandleForCloudTaskWithHeader() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.POST); when(handler.getMethod()) .thenReturn( CloudTaskRdrExportApi.class.getMethod(CLOUD_TASK_METHOD_NAME, ArrayOfLong.class)); when(request.getHeader(CloudTaskInterceptor.QUEUE_NAME_REQUEST_HEADER)) .thenReturn("rdrExportQueue"); assertThat(interceptor.preHandle(request, response, handler)).isTrue(); } @Test public void prehandleForNonCloudTask() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.GET); when(handler.getMethod()).thenReturn(WorkspacesApi.class.getMethod("getWorkspaces")); assertThat(interceptor.preHandle(request, response, handler)).isTrue(); }
AuthInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { SecurityContextHolder.clearContext(); if (request.getMethod().equals(HttpMethods.OPTIONS)) { return true; } HandlerMethod method = (HandlerMethod) handler; boolean isAuthRequired = false; ApiOperation apiOp = AnnotationUtils.findAnnotation(method.getMethod(), ApiOperation.class); if (apiOp != null) { for (Authorization auth : apiOp.authorizations()) { if (auth.value().equals(authName)) { isAuthRequired = true; break; } } } if (!isAuthRequired) { return true; } String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION); if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) { log.warning("No bearer token found in request"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } final String token = authorizationHeader.substring("Bearer".length()).trim(); final Userinfoplus userInfo = userInfoService.getUserInfo(token); String userName = userInfo.getEmail(); if (workbenchConfigProvider.get().auth.serviceAccountApiUsers.contains(userName)) { DbUser user = userDao.findUserByUsername(userName); if (user == null) { user = userService.createServiceAccountUser(userName); } SecurityContextHolder.getContext() .setAuthentication( new UserAuthentication(user, userInfo, token, UserType.SERVICE_ACCOUNT)); log.log(Level.INFO, "{0} service account in use", userName); return true; } String gsuiteDomainSuffix = "@" + workbenchConfigProvider.get().googleDirectoryService.gSuiteDomain; if (!userName.endsWith(gsuiteDomainSuffix)) { SecurityContextHolder.getContext() .setAuthentication( new UserAuthentication(null, userInfo, token, UserType.SERVICE_ACCOUNT)); userName = fireCloudService.getMe().getUserInfo().getUserEmail(); if (!userName.endsWith(gsuiteDomainSuffix)) { log.info( String.format( "User %s isn't in domain %s, can't access the workbench", userName, gsuiteDomainSuffix)); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } } DbUser user = userDao.findUserByUsername(userName); if (user == null) { if (workbenchConfigProvider.get().access.unsafeAllowUserCreationFromGSuiteData) { user = devUserRegistrationService.createUser(userInfo); log.info(String.format("Dev user '%s' has been re-created.", user.getUsername())); } else { log.severe(String.format("No User row exists for user '%s'", userName)); return false; } } if (user.getDisabled()) { throw new ForbiddenException( WorkbenchException.errorResponse( "Rejecting request for disabled user account: " + user.getUsername(), ErrorCode.USER_DISABLED)); } SecurityContextHolder.getContext() .setAuthentication(new UserAuthentication(user, userInfo, token, UserType.RESEARCHER)); log.log(Level.INFO, "{0} logged in", userInfo.getEmail()); if (!hasRequiredAuthority(method, user)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return false; } return true; } @Autowired AuthInterceptor( UserInfoService userInfoService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserDao userDao, UserService userService, DevUserRegistrationService devUserRegistrationService); @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler); @Override void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView); }
@Test public void preHandleOptions_OPTIONS() throws Exception { when(mockRequest.getMethod()).thenReturn(HttpMethods.OPTIONS); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isTrue(); } @Test public void preHandleOptions_publicEndpoint() throws Exception { when(mockHandler.getMethod()).thenReturn(getProfileApiMethod("isUsernameTaken")); when(mockRequest.getMethod()).thenReturn(HttpMethods.GET); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isTrue(); } @Test public void preHandleGet_noAuthorization() throws Exception { when(mockHandler.getMethod()).thenReturn(getTestMethod()); when(mockRequest.getMethod()).thenReturn(HttpMethods.GET); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isFalse(); verify(mockResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED); } @Test public void preHandleGet_nonBearerAuthorization() throws Exception { mockGetCallWithBearerToken(); when(mockRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("blah"); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isFalse(); verify(mockResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED); } @Test(expected = NotFoundException.class) public void preHandleGet_userInfoError() throws Exception { mockGetCallWithBearerToken(); when(userInfoService.getUserInfo("foo")).thenThrow(new NotFoundException()); interceptor.preHandle(mockRequest, mockResponse, mockHandler); } @Test(expected = NotFoundException.class) public void preHandleGet_firecloudLookupFails() throws Exception { mockGetCallWithBearerToken(); Userinfoplus userInfo = new Userinfoplus(); userInfo.setEmail("[email protected]"); when(userInfoService.getUserInfo("foo")).thenReturn(userInfo); when(fireCloudService.getMe()).thenThrow(new NotFoundException()); interceptor.preHandle(mockRequest, mockResponse, mockHandler); } @Test public void preHandleGet_firecloudLookupSucceeds() throws Exception { mockGetCallWithBearerToken(); Userinfoplus userInfo = new Userinfoplus(); userInfo.setEmail("[email protected]"); when(userInfoService.getUserInfo("foo")).thenReturn(userInfo); FirecloudUserInfo fcUserInfo = new FirecloudUserInfo(); fcUserInfo.setUserEmail("[email protected]"); FirecloudMe me = new FirecloudMe(); me.setUserInfo(fcUserInfo); when(fireCloudService.getMe()).thenReturn(me); when(userDao.findUserByUsername("[email protected]")).thenReturn(user); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isTrue(); } @Test public void preHandleGet_firecloudLookupSucceedsNoUserRecordWrongDomain() throws Exception { mockGetCallWithBearerToken(); Userinfoplus userInfo = new Userinfoplus(); userInfo.setEmail("[email protected]"); when(userInfoService.getUserInfo("foo")).thenReturn(userInfo); FirecloudUserInfo fcUserInfo = new FirecloudUserInfo(); fcUserInfo.setUserEmail("[email protected]"); FirecloudMe me = new FirecloudMe(); me.setUserInfo(fcUserInfo); when(fireCloudService.getMe()).thenReturn(me); when(userDao.findUserByUsername("[email protected]")).thenReturn(null); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isFalse(); verify(mockResponse).sendError(HttpServletResponse.SC_UNAUTHORIZED); } @Test public void preHandleGet_userInfoSuccess() throws Exception { mockGetCallWithBearerToken(); mockUserInfoSuccess(); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isTrue(); } @Test public void preHandleGet_noUserRecord() throws Exception { workbenchConfig.access.unsafeAllowUserCreationFromGSuiteData = true; mockGetCallWithBearerToken(); mockUserInfoSuccess(); when(userDao.findUserByUsername(eq("[email protected]"))).thenReturn(null); when(devUserRegistrationService.createUser(any())).thenReturn(user); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isTrue(); } @Test public void preHandleGet_noUserRecordAndNoDevRegistration() throws Exception { workbenchConfig.access.unsafeAllowUserCreationFromGSuiteData = false; mockGetCallWithBearerToken(); mockUserInfoSuccess(); when(userDao.findUserByUsername(eq("[email protected]"))).thenReturn(null); assertThat(interceptor.preHandle(mockRequest, mockResponse, mockHandler)).isFalse(); verify(devUserRegistrationService, never()).createUser(any()); }
AuthInterceptor extends HandlerInterceptorAdapter { boolean hasRequiredAuthority(HandlerMethod handlerMethod, DbUser user) { return hasRequiredAuthority(InterceptorUtils.getControllerMethod(handlerMethod), user); } @Autowired AuthInterceptor( UserInfoService userInfoService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserDao userDao, UserService userService, DevUserRegistrationService devUserRegistrationService); @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler); @Override void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView); }
@Test public void authorityCheckPermitsWithNoAnnotation() throws Exception { assertThat(interceptor.hasRequiredAuthority(getTestMethod(), new DbUser())).isTrue(); } @Test public void authorityCheckDeniesWhenUserMissingAuthority() throws Exception { Method apiControllerMethod = FakeController.class.getMethod("handle"); when(userDao.findUserWithAuthorities(USER_ID)).thenReturn(user); assertThat(interceptor.hasRequiredAuthority(apiControllerMethod, user)).isFalse(); } @Test public void authorityCheckPermitsWhenUserHasAuthority() throws Exception { DbUser userWithAuthorities = new DbUser(); Set<Authority> required = new HashSet<>(); required.add(Authority.REVIEW_RESEARCH_PURPOSE); userWithAuthorities.setAuthoritiesEnum(required); when(userDao.findUserWithAuthorities(USER_ID)).thenReturn(userWithAuthorities); Method apiControllerMethod = FakeApiController.class.getMethod("handle"); assertThat(interceptor.hasRequiredAuthority(apiControllerMethod, user)).isTrue(); }
RequestTimeMetricInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) { if (shouldSkip(request, handler)) { return true; } request.setAttribute(RequestAttribute.START_INSTANT.toString(), clock.instant()); return true; } RequestTimeMetricInterceptor(LogsBasedMetricService logsBasedMetricService, Clock clock); @Override boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler); @Override void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView); }
@Test public void testPreHandle_getRequest() { boolean result = requestTimeMetricInterceptor.preHandle( mockHttpServletRequest, mockHttpServletResponse, mockHandlerMethod); assertThat(result).isTrue(); verify(mockHttpServletRequest) .setAttribute(attributeKeyCaptor.capture(), attributeValueCaptor.capture()); assertThat(attributeKeyCaptor.getValue()) .isEqualTo(RequestAttribute.START_INSTANT.getKeyName()); Object attrValueObj = attributeValueCaptor.getValue(); assertThat(attrValueObj instanceof Instant).isTrue(); assertThat((Instant) attrValueObj).isEqualTo(START_INSTANT); } @Test public void testPreHandle_skipsOptionsRequest() { doReturn(HttpMethods.OPTIONS).when(mockHttpServletRequest).getMethod(); boolean result = requestTimeMetricInterceptor.preHandle( mockHttpServletRequest, mockHttpServletResponse, mockHandlerMethod); assertThat(result).isTrue(); verify(mockHttpServletRequest, never()).setAttribute(anyString(), any()); } @Test public void testPreHandle_skipsUnsupportedHandler() { boolean result = requestTimeMetricInterceptor.preHandle( mockHttpServletRequest, mockHttpServletResponse, new Object()); assertThat(result).isTrue(); verify(mockHttpServletRequest, never()).setAttribute(anyString(), any()); }
RequestTimeMetricInterceptor extends HandlerInterceptorAdapter { @Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (shouldSkip(request, handler)) { return; } final String methodName = ((HandlerMethod) handler).getMethod().getName(); Optional.ofNullable(request.getAttribute(RequestAttribute.START_INSTANT.getKeyName())) .map(obj -> (Instant) obj) .map(start -> Duration.between(start, clock.instant())) .map(Duration::toMillis) .ifPresent( elapsedMillis -> logsBasedMetricService.record( MeasurementBundle.builder() .addMeasurement(DistributionMetric.API_METHOD_TIME, elapsedMillis) .addTag(MetricLabel.METHOD_NAME, methodName) .build())); } RequestTimeMetricInterceptor(LogsBasedMetricService logsBasedMetricService, Clock clock); @Override boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler); @Override void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView); }
@Test public void testPostHandle() { doReturn(END_INSTANT).when(mockClock).instant(); doReturn(START_INSTANT) .when(mockHttpServletRequest) .getAttribute(RequestAttribute.START_INSTANT.getKeyName()); requestTimeMetricInterceptor.postHandle( mockHttpServletRequest, mockHttpServletResponse, mockHandlerMethod, mockModelAndView); verify(mockHttpServletRequest).getAttribute(RequestAttribute.START_INSTANT.getKeyName()); verify(mockLogsBasedMetricService).record(measurementBundleCaptor.capture()); assertThat( measurementBundleCaptor .getValue() .getMeasurements() .get(DistributionMetric.API_METHOD_TIME)) .isEqualTo(DURATION_MILLIS); assertThat(measurementBundleCaptor.getValue().getTags()).hasSize(1); assertThat(measurementBundleCaptor.getValue().getTagValue(MetricLabel.METHOD_NAME).get()) .isEqualTo(METHOD_NAME); } @Test public void testPostHandle_skipsOptionsRequest() { doReturn(HttpMethods.OPTIONS).when(mockHttpServletRequest).getMethod(); requestTimeMetricInterceptor.postHandle( mockHttpServletRequest, mockHttpServletResponse, mockHandlerMethod, mockModelAndView); verify(mockHttpServletRequest, never()).setAttribute(anyString(), any()); verifyZeroInteractions(mockLogsBasedMetricService); } @Test public void testPostHandle_skipsUnsupportedHandler() { requestTimeMetricInterceptor.postHandle( mockHttpServletRequest, mockHttpServletResponse, new Object(), mockModelAndView); verify(mockHttpServletRequest, never()).setAttribute(anyString(), any()); verifyZeroInteractions(mockLogsBasedMetricService); }
ConceptSetService { @Transactional public DbConceptSet cloneConceptSetAndConceptIds( DbConceptSet dbConceptSet, DbWorkspace targetWorkspace, boolean cdrVersionChanged) { ConceptSetContext conceptSetContext = new ConceptSetContext.Builder() .name(dbConceptSet.getName()) .creator(targetWorkspace.getCreator()) .workspaceId(targetWorkspace.getWorkspaceId()) .creationTime(targetWorkspace.getCreationTime()) .lastModifiedTime(targetWorkspace.getLastModifiedTime()) .version(CONCEPT_SET_VERSION) .build(); DbConceptSet dbConceptSetClone = conceptSetMapper.dbModelToDbModel(dbConceptSet, conceptSetContext); if (cdrVersionChanged) { String omopTable = BigQueryTableInfo.getTableName(dbConceptSet.getDomainEnum()); dbConceptSetClone.setParticipantCount( conceptBigQueryService.getParticipantCountForConcepts( dbConceptSet.getDomainEnum(), omopTable, dbConceptSet.getConceptIds())); } return conceptSetDao.save(dbConceptSetClone); } @Autowired ConceptSetService( ConceptSetDao conceptSetDao, ConceptBigQueryService conceptBigQueryService, ConceptService conceptService, CohortBuilderService cohortBuilderService, ConceptSetMapper conceptSetMapper, Clock clock, Provider<WorkbenchConfig> configProvider); ConceptSet copyAndSave( Long fromConceptSetId, String newConceptSetName, DbUser creator, Long toWorkspaceId); ConceptSet createConceptSet( CreateConceptSetRequest request, DbUser creator, Long workspaceId); ConceptSet updateConceptSet(Long conceptSetId, ConceptSet conceptSet); ConceptSet updateConceptSetConcepts(Long conceptSetId, UpdateConceptSetRequest request); void delete(Long conceptSetId); ConceptSet getConceptSet(Long conceptSetId); List<ConceptSet> findAll(List<Long> conceptSetIds); List<ConceptSet> findByWorkspaceId(long workspaceId); List<ConceptSet> findByWorkspaceIdAndSurvey(long workspaceId, short surveyId); @Transactional DbConceptSet cloneConceptSetAndConceptIds( DbConceptSet dbConceptSet, DbWorkspace targetWorkspace, boolean cdrVersionChanged); List<DbConceptSet> getConceptSets(DbWorkspace workspace); @VisibleForTesting static int MAX_CONCEPTS_PER_SET; }
@Test public void testCloneConceptSetWithNoCdrVersionChange() { DbWorkspace mockDbWorkspace = mockWorkspace(); DbConceptSet fromConceptSet = mockConceptSet(); DbConceptSet copiedConceptSet = conceptSetService.cloneConceptSetAndConceptIds(fromConceptSet, mockDbWorkspace, false); assertNotNull(copiedConceptSet); assertEquals(copiedConceptSet.getConceptIds().size(), 5); assertEquals(copiedConceptSet.getWorkspaceId(), mockDbWorkspace.getWorkspaceId()); }
FireCloudServiceImpl implements FireCloudService { @Override public FirecloudMe getMe() { ProfileApi profileApi = profileApiProvider.get(); return retryHandler.run((context) -> profileApi.me()); } @Autowired FireCloudServiceImpl( Provider<WorkbenchConfig> configProvider, Provider<ProfileApi> profileApiProvider, Provider<BillingApi> billingApiProvider, Provider<GroupsApi> groupsApiProvider, Provider<NihApi> nihApiProvider, @Qualifier(FireCloudConfig.END_USER_WORKSPACE_API) Provider<WorkspacesApi> endUserWorkspacesApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_WORKSPACE_API) Provider<WorkspacesApi> serviceAccountWorkspaceApiProvider, Provider<StatusApi> statusApiProvider, @Qualifier(FireCloudConfig.END_USER_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> endUserStaticNotebooksApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> serviceAccountStaticNotebooksApiProvider, FirecloudRetryHandler retryHandler, @Qualifier(Constants.FIRECLOUD_ADMIN_CREDS) Provider<ServiceAccountCredentials> fcAdminCredsProvider, IamCredentialsClient iamCredentialsClient, HttpTransport httpTransport); ApiClient getApiClientWithImpersonation(String userEmail); @Override @VisibleForTesting String getApiBasePath(); @Override boolean getFirecloudStatus(); @Override FirecloudMe getMe(); @Override void registerUser(String contactEmail, String firstName, String lastName); @Override void createAllOfUsBillingProject(String projectName); @Override void deleteBillingProject(String billingProject); @Override FirecloudBillingProjectStatus getBillingProjectStatus(String projectName); @Override void addOwnerToBillingProject(String ownerEmail, String projectName); @Override void removeOwnerFromBillingProject( String ownerEmailToRemove, String projectName, Optional<String> callerAccessToken); @Override FirecloudWorkspace createWorkspace(String projectName, String workspaceName); @Override FirecloudWorkspace cloneWorkspace( String fromProject, String fromName, String toProject, String toName); @Override List<FirecloudBillingProjectMembership> getBillingProjectMemberships(); @Override FirecloudWorkspaceACLUpdateResponseList updateWorkspaceACL( String projectName, String workspaceName, List<FirecloudWorkspaceACLUpdate> aclUpdates); @Override FirecloudWorkspaceACL getWorkspaceAclAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspaceAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspace(String projectName, String workspaceName); @Override Optional<FirecloudWorkspaceResponse> getWorkspace(DbWorkspace dbWorkspace); @Override List<FirecloudWorkspaceResponse> getWorkspaces(); @Override void deleteWorkspace(String projectName, String workspaceName); @Override FirecloudManagedGroupWithMembers getGroup(String groupName); @Override FirecloudManagedGroupWithMembers createGroup(String groupName); @Override void addUserToGroup(String email, String groupName); @Override void removeUserFromGroup(String email, String groupName); @Override boolean isUserMemberOfGroup(String email, String groupName); @Override String staticNotebooksConvert(byte[] notebook); @Override String staticNotebooksConvertAsService(byte[] notebook); @Override FirecloudNihStatus getNihStatus(); @Override void postNihCallback(FirecloudJWTWrapper wrapper); static final List<String> FIRECLOUD_API_OAUTH_SCOPES; static final List<String> FIRECLOUD_WORKSPACE_REQUIRED_FIELDS; }
@Test(expected = NotFoundException.class) public void testGetMe_throwsNotFound() throws ApiException { when(profileApi.me()).thenThrow(new ApiException(404, "blah")); service.getMe(); } @Test(expected = ForbiddenException.class) public void testGetMe_throwsForbidden() throws ApiException { when(profileApi.me()).thenThrow(new ApiException(403, "blah")); service.getMe(); } @Test(expected = UnauthorizedException.class) public void testGetMe_throwsUnauthorized() throws ApiException { when(profileApi.me()).thenThrow(new ApiException(401, "blah")); service.getMe(); }
CronInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (request.getMethod().equals(HttpMethods.OPTIONS)) { return true; } HandlerMethod method = (HandlerMethod) handler; ApiOperation apiOp = AnnotationUtils.findAnnotation(method.getMethod(), ApiOperation.class); if (apiOp == null) { return true; } boolean requireCronHeader = false; for (String tag : apiOp.tags()) { if (CRON_TAG.equals(tag)) { requireCronHeader = true; break; } } boolean hasCronHeader = "true".equals(request.getHeader(GAE_CRON_HEADER)); if (requireCronHeader && !hasCronHeader) { response.sendError( HttpServletResponse.SC_FORBIDDEN, String.format( "cronjob endpoints are only invocable via app engine cronjob, and " + "require the '%s' header", GAE_CRON_HEADER)); return false; } return true; } @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler); static final String GAE_CRON_HEADER; }
@Test public void preHandleOptions_OPTIONS() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.OPTIONS); assertThat(interceptor.preHandle(request, response, handler)).isTrue(); } @Test public void prehandleForCronNoHeader() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.GET); when(handler.getMethod()).thenReturn(OfflineAuditApi.class.getMethod("auditBigQuery")); assertThat(interceptor.preHandle(request, response, handler)).isFalse(); } @Test public void prehandleForCronWithBadHeader() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.GET); when(handler.getMethod()).thenReturn(OfflineAuditApi.class.getMethod("auditBigQuery")); when(request.getHeader(CronInterceptor.GAE_CRON_HEADER)).thenReturn("asdf"); assertThat(interceptor.preHandle(request, response, handler)).isFalse(); } @Test public void prehandleForCronWithHeader() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.GET); when(handler.getMethod()).thenReturn(OfflineAuditApi.class.getMethod("auditBigQuery")); when(request.getHeader(CronInterceptor.GAE_CRON_HEADER)).thenReturn("true"); assertThat(interceptor.preHandle(request, response, handler)).isTrue(); } @Test public void prehandleForNonCron() throws Exception { when(request.getMethod()).thenReturn(HttpMethods.GET); when(handler.getMethod()).thenReturn(WorkspacesApi.class.getMethod("getWorkspaces")); assertThat(interceptor.preHandle(request, response, handler)).isTrue(); }
QueryParameterValues { @NotNull public static String decorateParameterName(@NotNull String parameterName) { return "@" + parameterName; } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testDecorateParameterName() { assertThat(decorateParameterName("foo")).isEqualTo("@foo"); }
QueryParameterValues { @NotNull public static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue) { String parameterName = "p" + queryParameterValueMap.size(); queryParameterValueMap.put(parameterName, queryParameterValue); return decorateParameterName(parameterName); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testBuildParameter() { final QueryParameterValue newParameter = QueryParameterValue.int64(42); final String parameter = buildParameter(PARAM_MAP, newParameter); assertThat(parameter).isEqualTo("@p2"); assertThat(PARAM_MAP.get("p2")).isEqualTo(newParameter); } @Test public void testBuildParameter_emptyMap_nullQpv() { PARAM_MAP.clear(); final QueryParameterValue nullString = QueryParameterValue.string(null); final String parameterName = buildParameter(PARAM_MAP, nullString); assertThat(parameterName).isEqualTo("@p0"); assertThat(PARAM_MAP).hasSize(1); assertThat(PARAM_MAP.get("p0")).isEqualTo(nullString); }
QueryParameterValues { @NotNull public static QueryParameterValue instantToQPValue(@Nullable Instant instant) { final Long epochMicros = Optional.ofNullable(instant) .map(Instant::toEpochMilli) .map(milli -> milli * MICROSECONDS_IN_MILLISECOND) .orElse(null); return QueryParameterValue.timestamp(epochMicros); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testInstantToQpvValue_nullInput() { final QueryParameterValue qpv = instantToQPValue(null); assertThat(qpv.getType()).isEqualTo(StandardSQLTypeName.TIMESTAMP); assertThat(qpv.getValue()).isNull(); }
QueryParameterValues { @Nullable public static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime) { final String arg = Optional.ofNullable(offsetDateTime).map(QPV_TIMESTAMP_FORMATTER::format).orElse(null); return QueryParameterValue.timestamp(arg); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testToTimestampQpv() { final QueryParameterValue qpv = toTimestampQpv(OFFSET_DATE_TIME); assertThat(qpv).isNotNull(); assertThat(qpv.getType()).isEqualTo(StandardSQLTypeName.TIMESTAMP); final Optional<OffsetDateTime> roundTripOdt = timestampQpvToOffsetDateTime(qpv); assertThat(roundTripOdt).isPresent(); assertTimeApprox(roundTripOdt.get(), OFFSET_DATE_TIME); }
RdrExportServiceImpl implements RdrExportService { @Override public void exportWorkspaces(List<Long> workspaceIds) { List<RdrWorkspace> rdrWorkspacesList; try { rdrWorkspacesList = workspaceIds.stream() .map( workspaceId -> toRdrWorkspace(workspaceDao.findDbWorkspaceByWorkspaceId(workspaceId))) .filter(Objects::nonNull) .collect(Collectors.toList()); if (!rdrWorkspacesList.isEmpty()) { rdrApiProvider.get().getApiClient().setDebugging(true); rdrApiProvider.get().exportWorkspaces(rdrWorkspacesList); updateDbRdrExport(RdrEntity.WORKSPACE, workspaceIds); } } catch (ApiException ex) { log.severe("Error while sending workspace data to RDR"); } } @Autowired RdrExportServiceImpl( Clock clock, Provider<RdrApi> rdrApiProvider, RdrExportDao rdrExportDao, RdrMapper rdrMapper, WorkspaceDao workspaceDao, InstitutionService institutionService, WorkspaceService workspaceService, UserDao userDao, VerifiedInstitutionalAffiliationDao verifiedInstitutionalAffiliationDao); @Override List<Long> findAllUserIdsToExport(); @Override List<Long> findAllWorkspacesIdsToExport(); @Override void exportUsers(List<Long> userIds); @Override void exportWorkspaces(List<Long> workspaceIds); @Override @VisibleForTesting void updateDbRdrExport(RdrEntity entity, List<Long> idList); }
@Test public void exportWorkspace() throws ApiException { List<Long> workspaceID = new ArrayList<>(); workspaceID.add(1l); RdrWorkspace rdrWorkspace = toDefaultRdrWorkspace(mockWorkspace); when(rdrMapper.toRdrModel(mockWorkspace)).thenReturn(rdrWorkspace); rdrExportService.exportWorkspaces(workspaceID); verify(mockWorkspaceService) .getFirecloudUserRoles( mockWorkspace.getWorkspaceNamespace(), mockWorkspace.getFirecloudName()); verify(rdrExportDao, times(1)).save(anyList()); verify(mockRdrApi).exportWorkspaces(Arrays.asList(rdrWorkspace)); } @Test public void exportWorkspace_FocusOnUnderservedPopulation() throws ApiException { Set<SpecificPopulationEnum> specificPopulationEnumsSet = new HashSet<SpecificPopulationEnum>(); specificPopulationEnumsSet.add(SpecificPopulationEnum.RACE_AA); mockWorkspace.setSpecificPopulationsEnum(specificPopulationEnumsSet); when(mockWorkspaceDao.findDbWorkspaceByWorkspaceId(1)).thenReturn(mockWorkspace); List<Long> workspaceID = new ArrayList<>(); workspaceID.add(1l); RdrWorkspace rdrWorkspace = toDefaultRdrWorkspace(mockWorkspace); when(rdrMapper.toRdrModel(mockWorkspace)).thenReturn(rdrWorkspace); rdrExportService.exportWorkspaces(workspaceID); verify(mockWorkspaceService) .getFirecloudUserRoles( mockWorkspace.getWorkspaceNamespace(), mockWorkspace.getFirecloudName()); verify(rdrExportDao, times(1)).save(anyList()); rdrWorkspace .getWorkspaceDemographic() .setRaceEthnicity(Arrays.asList(RdrWorkspaceDemographic.RaceEthnicityEnum.AA)); rdrWorkspace.setFocusOnUnderrepresentedPopulations(true); verify(mockRdrApi).exportWorkspaces(Arrays.asList(rdrWorkspace)); } @Test public void exportWorkspace_CreatorInformation() throws ApiException { List<Long> workspaceIdList = new ArrayList<>(); workspaceIdList.add(1l); RdrWorkspace rdrWorkspace = toDefaultRdrWorkspace(mockWorkspace); when(rdrMapper.toRdrModel(mockWorkspace)).thenReturn(rdrWorkspace); rdrExportService.exportWorkspaces(workspaceIdList); verify(mockRdrApi).exportWorkspaces(Arrays.asList(rdrWorkspace)); workspaceIdList = new ArrayList<>(); workspaceIdList.add(3l); rdrWorkspace = toDefaultRdrWorkspace(mockCreatorWorkspace); when(rdrMapper.toRdrModel(mockCreatorWorkspace)).thenReturn(rdrWorkspace); rdrExportService.exportWorkspaces(workspaceIdList); rdrWorkspace.setCreator( new RdrWorkspaceCreator().userId(2l).familyName("email").givenName("icannothas")); verify(mockRdrApi).exportWorkspaces(Arrays.asList(rdrWorkspace)); } @Test public void exportWorkspace_DeletedWorkspace() throws ApiException { List<Long> workspaceID = new ArrayList<>(); workspaceID.add(2l); RdrWorkspace rdrWorkspace = toDefaultRdrWorkspace(mockDeletedWorkspace); when(rdrMapper.toRdrModel(mockDeletedWorkspace)).thenReturn(rdrWorkspace); rdrExportService.exportWorkspaces(workspaceID); verify(mockWorkspaceService, never()) .getFirecloudUserRoles( mockDeletedWorkspace.getWorkspaceNamespace(), mockDeletedWorkspace.getFirecloudName()); verify(rdrExportDao, times(1)).save(anyList()); rdrWorkspace.setStatus(RdrWorkspace.StatusEnum.INACTIVE); verify(mockRdrApi).exportWorkspaces(Arrays.asList(rdrWorkspace)); }
QueryParameterValues { public static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv) { verifyQpvType(qpv, StandardSQLTypeName.TIMESTAMP); return Optional.ofNullable(qpv.getValue()) .map(s -> ZonedDateTime.parse(s, QPV_TIMESTAMP_FORMATTER)) .map(ZonedDateTime::toInstant); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testTimestampQpvToInstant_nullQpvValue() { assertThat(timestampQpvToInstant(QueryParameterValue.timestamp((String) null))).isEmpty(); } @Test(expected = IllegalArgumentException.class) public void testTimestampQpvToInstant_wrongQpvType() { timestampQpvToInstant(QueryParameterValue.bool(false)); }
QueryParameterValues { public static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue) { verifyQpvType(queryParameterValue, StandardSQLTypeName.TIMESTAMP); return Optional.ofNullable(queryParameterValue) .flatMap(QueryParameterValues::timestampQpvToInstant) .map(i -> OffsetDateTime.ofInstant(i, ZoneOffset.UTC)); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testTimestampQpvToOffsetDateTime() { final Optional<OffsetDateTime> offsetDateTime = timestampQpvToOffsetDateTime(TIMESTAMP_QPV); assertTimeApprox(offsetDateTime.get().toInstant(), INSTANT); } @Test public void testTimestampQpvToOffset_nullInput() { assertThat(timestampQpvToOffsetDateTime(null)).isEmpty(); }
QueryParameterValues { public static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString) { return Optional.ofNullable(bqTimeString) .filter(s -> s.length() > 0) .map(ROW_TO_INSERT_TIMESTAMP_FORMATTER::parse) .map(LocalDateTime::from) .map(ldt -> OffsetDateTime.of(ldt, ZoneOffset.UTC)); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testRowToInsertStringToOffsetTimestamp() { final String timestampString = "2020-09-17 04:30:15.000000"; final Optional<OffsetDateTime> convertedOdt = rowToInsertStringToOffsetTimestamp(timestampString); assertThat(convertedOdt).isPresent(); final OffsetDateTime expected = OffsetDateTime.parse("2020-09-17T04:30:15Z"); assertTimeApprox(convertedOdt.get(), expected); assertThat(rowToInsertStringToOffsetTimestamp(null)).isEmpty(); }
QueryParameterValues { public static Optional<Instant> timestampStringToInstant(@Nullable String timestamp) { return Optional.ofNullable(timestamp) .map(s -> ZonedDateTime.parse(s, ROW_TO_INSERT_TIMESTAMP_FORMATTER)) .map(ZonedDateTime::toInstant); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testTimestampStringToInstant_nullInput() { assertThat(timestampStringToInstant(null)).isEmpty(); }
QueryParameterValues { @NotNull public static <T extends Enum<T>> QueryParameterValue enumToQpv(@Nullable T enumValue) { return QueryParameterValue.string(enumToString(enumValue)); } @NotNull static String buildParameter( @NotNull Map<String, QueryParameterValue> queryParameterValueMap, @NotNull QueryParameterValue queryParameterValue); @NotNull static QueryParameterValue instantToQPValue(@Nullable Instant instant); static Optional<Instant> timestampStringToInstant(@Nullable String timestamp); static Optional<Instant> timestampQpvToInstant(@NotNull QueryParameterValue qpv); static void verifyQpvType( @Nullable QueryParameterValue queryParameterValue, StandardSQLTypeName expectedType); static Optional<OffsetDateTime> timestampQpvToOffsetDateTime( @Nullable QueryParameterValue queryParameterValue); @NotNull static String replaceNamedParameters( @NotNull QueryJobConfiguration queryJobConfiguration); @NotNull static String formatQuery(@NotNull String query); @NotNull static String decorateParameterName(@NotNull String parameterName); @Nullable static QueryParameterValue toTimestampQpv(@Nullable OffsetDateTime offsetDateTime); @Nullable static String toInsertRowString(@Nullable OffsetDateTime offsetDateTime); static Optional<OffsetDateTime> rowToInsertStringToOffsetTimestamp( @Nullable String bqTimeString); @NotNull static QueryParameterValue enumToQpv(@Nullable T enumValue); @Nullable static String enumToString(@Nullable T enumValue); static final DateTimeFormatter QPV_TIMESTAMP_FORMATTER; static final DateTimeFormatter ROW_TO_INSERT_TIMESTAMP_FORMATTER; }
@Test public void testEnumToQpv() { final QueryParameterValue qpv = enumToQpv(WorkspaceAccessLevel.READER); assertThat(qpv.getType()).isEqualTo(StandardSQLTypeName.STRING); assertThat(qpv.getValue()).isEqualTo("READER"); } @Test public void testEnumToQpv_nullInput() { final QueryParameterValue qpv = enumToQpv(null); assertThat(qpv.getType()).isEqualTo(StandardSQLTypeName.STRING); assertThat(qpv.getValue()).isNull(); }
CriteriaLookupUtil { public Map<SearchParameter, Set<Long>> buildCriteriaLookupMap(SearchRequest req) { Map<CriteriaLookupUtil.FullTreeType, Map<Long, Set<Long>>> childrenByAncestor = Maps.newHashMap(); Map<CriteriaLookupUtil.FullTreeType, Map<Long, Set<Long>>> childrenByParentConcept = Maps.newHashMap(); for (SearchGroup sg : Iterables.concat(req.getIncludes(), req.getExcludes())) { for (SearchGroupItem sgi : sg.getItems()) { from(isEmpty()) .test(sgi.getSearchParameters()) .throwException("Bad Request: search parameters are empty."); for (SearchParameter param : sgi.getSearchParameters()) { if (!param.getGroup() && !param.getAncestorData()) { continue; } CriteriaLookupUtil.FullTreeType treeKey = CriteriaLookupUtil.FullTreeType.fromParam(param); if (param.getAncestorData()) { childrenByAncestor.putIfAbsent(treeKey, Maps.newHashMap()); childrenByAncestor.get(treeKey).putIfAbsent(param.getConceptId(), Sets.newHashSet()); } else { childrenByParentConcept.putIfAbsent(treeKey, Maps.newHashMap()); childrenByParentConcept .get(treeKey) .putIfAbsent(param.getConceptId(), Sets.newHashSet()); } } } } for (CriteriaLookupUtil.FullTreeType treeType : childrenByAncestor.keySet()) { Map<Long, Set<Long>> byParent = childrenByAncestor.get(treeType); Set<String> parentConceptIds = byParent.keySet().stream().map(c -> c.toString()).collect(Collectors.toSet()); List<DbCriteriaLookup> parents = Lists.newArrayList(); List<DbCriteriaLookup> leaves = Lists.newArrayList(); cbCriteriaDao .findCriteriaAncestors( treeType.domain.toString(), treeType.type.toString(), CriteriaType.ATC.equals(treeType.type), parentConceptIds) .forEach( c -> { if (parentConceptIds.contains(String.valueOf(c.getConceptId()))) { parents.add(c); } else { leaves.add(c); } }); putLeavesOnParent(byParent, parents, leaves); } for (CriteriaLookupUtil.FullTreeType treeType : childrenByParentConcept.keySet()) { Map<Long, Set<Long>> byParent = childrenByParentConcept.get(treeType); Set<String> parentConceptIds = byParent.keySet().stream().map(c -> c.toString()).collect(Collectors.toSet()); List<DbCriteriaLookup> parents = Lists.newArrayList(); List<DbCriteriaLookup> leaves = Lists.newArrayList(); if (treeType.type.equals(CriteriaType.ICD9CM)) { List<Long> ids = cbCriteriaDao .findCriteriaParentsByDomainAndTypeAndParentConceptIds( treeType.domain.toString(), treeType.type.toString(), treeType.isStandard, parentConceptIds) .stream() .map(c -> c.getId()) .collect(Collectors.toList()); cbCriteriaDao .findCriteriaLeavesAndParentsByDomainAndTypeAndParentIds( treeType.domain.toString(), treeType.type.toString(), ids) .forEach( c -> { if (parentConceptIds.contains(String.valueOf(c.getConceptId()))) { parents.add(c); } else { leaves.add(c); } }); } else { String ids = cbCriteriaDao .findCriteriaParentsByDomainAndTypeAndParentConceptIds( treeType.domain.toString(), treeType.type.toString(), treeType.isStandard, parentConceptIds) .stream() .map(c -> String.valueOf(c.getId())) .collect(Collectors.joining(",")); List<Long> longIds = new ArrayList<>(); if (!ids.isEmpty()) { longIds = Stream.of(ids.split(",")).map(Long::parseLong).collect(Collectors.toList()); } cbCriteriaDao .findCriteriaLeavesAndParentsByPath(longIds, ids) .forEach( c -> { if (parentConceptIds.contains(String.valueOf(c.getConceptId()))) { parents.add(c); } else { leaves.add(c); } }); } putLeavesOnParent(byParent, parents, leaves); } Map<SearchParameter, Set<Long>> builder = new HashMap<>(); for (SearchGroup sg : Iterables.concat(req.getIncludes(), req.getExcludes())) { for (SearchGroupItem sgi : sg.getItems()) { for (SearchParameter param : sgi.getSearchParameters()) { if (!param.getGroup() && !param.getAncestorData()) { continue; } CriteriaLookupUtil.FullTreeType treeKey = CriteriaLookupUtil.FullTreeType.fromParam(param); if (param.getAncestorData()) { builder.put(param, childrenByAncestor.get(treeKey).get(param.getConceptId())); } else { builder.put(param, childrenByParentConcept.get(treeKey).get(param.getConceptId())); } } } } return builder; } CriteriaLookupUtil(CBCriteriaDao cbCriteriaDao); Map<SearchParameter, Set<Long>> buildCriteriaLookupMap(SearchRequest req); }
@Test public void buildCriteriaLookupMapNoSearchParametersException() { SearchRequest searchRequest = new SearchRequest().addIncludesItem(new SearchGroup().addItemsItem(new SearchGroupItem())); try { lookupUtil.buildCriteriaLookupMap(searchRequest); fail("Should have thrown BadRequestException!"); } catch (BadRequestException bre) { assertEquals("Bad Request: search parameters are empty.", bre.getMessage()); } } @Test public void buildCriteriaLookupMapDrugCriteria_ATC() { DbCriteria drugNode1 = DbCriteria.builder() .addParentId(99999) .addDomainId(DomainType.DRUG.toString()) .addType(CriteriaType.ATC.toString()) .addConceptId("21600002") .addGroup(true) .addSelectable(true) .build(); saveCriteriaWithPath("0", drugNode1); DbCriteria drugNode2 = DbCriteria.builder() .addParentId(drugNode1.getId()) .addDomainId(DomainType.DRUG.toString()) .addType(CriteriaType.RXNORM.toString()) .addConceptId("19069022") .addGroup(false) .addSelectable(true) .build(); saveCriteriaWithPath(drugNode1.getPath(), drugNode2); DbCriteria drugNode3 = DbCriteria.builder() .addParentId(drugNode1.getId()) .addDomainId(DomainType.DRUG.toString()) .addType(CriteriaType.RXNORM.toString()) .addConceptId("1036094") .addGroup(false) .addSelectable(true) .build(); saveCriteriaWithPath(drugNode1.getPath(), drugNode3); jdbcTemplate.execute( "create table cb_criteria_ancestor(ancestor_id integer, descendant_id integer)"); jdbcTemplate.execute( "insert into cb_criteria_ancestor(ancestor_id, descendant_id) values (19069022, 19069022)"); jdbcTemplate.execute( "insert into cb_criteria_ancestor(ancestor_id, descendant_id) values (1036094, 1036094)"); List<Long> childConceptIds = ImmutableList.of(19069022L, 1036094L); SearchParameter searchParameter = new SearchParameter() .domain(DomainType.DRUG.toString()) .type(CriteriaType.ATC.toString()) .group(true) .ancestorData(true) .conceptId(21600002L); SearchRequest searchRequest = new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(searchParameter))); assertEquals( ImmutableMap.of(searchParameter, new HashSet<>(childConceptIds)), lookupUtil.buildCriteriaLookupMap(searchRequest)); jdbcTemplate.execute("drop table cb_criteria_ancestor"); } @Test public void buildCriteriaLookupMapDrugCriteria_RXNORM() { DbCriteria drugNode1 = DbCriteria.builder() .addParentId(99999) .addDomainId(DomainType.DRUG.toString()) .addType(CriteriaType.ATC.toString()) .addConceptId("21600002") .addGroup(true) .addSelectable(true) .build(); saveCriteriaWithPath("0", drugNode1); DbCriteria drugNode2 = DbCriteria.builder() .addParentId(drugNode1.getId()) .addDomainId(DomainType.DRUG.toString()) .addType(CriteriaType.RXNORM.toString()) .addConceptId("19069022") .addGroup(false) .addSelectable(true) .build(); saveCriteriaWithPath(drugNode1.getPath(), drugNode2); jdbcTemplate.execute( "create table cb_criteria_ancestor(ancestor_id integer, descendant_id integer)"); jdbcTemplate.execute( "insert into cb_criteria_ancestor(ancestor_id, descendant_id) values (19069022, 19069022)"); jdbcTemplate.execute( "insert into cb_criteria_ancestor(ancestor_id, descendant_id) values (19069022, 1666666)"); List<Long> childConceptIds = ImmutableList.of(1666666L); SearchParameter searchParameter = new SearchParameter() .domain(DomainType.DRUG.toString()) .type(CriteriaType.RXNORM.toString()) .group(true) .ancestorData(true) .conceptId(19069022L); SearchRequest searchRequest = new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(searchParameter))); assertEquals( ImmutableMap.of(searchParameter, new HashSet<>(childConceptIds)), lookupUtil.buildCriteriaLookupMap(searchRequest)); jdbcTemplate.execute("drop table cb_criteria_ancestor"); } @Test public void buildCriteriaLookupMapConditionICD9Criteria() { DbCriteria icd9Parent = DbCriteria.builder() .addParentId(0) .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD9CM.toString()) .addGroup(true) .addSelectable(true) .addStandard(false) .addConceptId("44829696") .addSynonyms("[CONDITION_rank1]") .build(); saveCriteriaWithPath("0", icd9Parent); DbCriteria icd9Child1 = DbCriteria.builder() .addParentId(icd9Parent.getId()) .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD9CM.toString()) .addGroup(false) .addSelectable(true) .addStandard(false) .addConceptId("44829697") .addSynonyms("[CONDITION_rank1]") .build(); saveCriteriaWithPath(icd9Parent.getPath(), icd9Child1); DbCriteria icd9Child2 = DbCriteria.builder() .addParentId(icd9Parent.getId()) .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD9CM.toString()) .addGroup(false) .addSelectable(true) .addStandard(false) .addConceptId("44835564") .addSynonyms("[CONDITION_rank1]") .build(); saveCriteriaWithPath(icd9Parent.getPath(), icd9Child2); List<Long> childConceptIds = ImmutableList.of(44829697L, 44835564L); SearchParameter searchParameter = new SearchParameter() .domain(DomainType.CONDITION.toString()) .type(CriteriaType.ICD9CM.toString()) .group(true) .standard(false) .ancestorData(false) .conceptId(44829696L); SearchRequest searchRequest = new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(searchParameter))); assertEquals( ImmutableMap.of(searchParameter, new HashSet<>(childConceptIds)), lookupUtil.buildCriteriaLookupMap(searchRequest)); }
DelegatedUserCredentials extends OAuth2Credentials { @VisibleForTesting public JsonWebToken.Payload createJwtPayload() { JsonWebToken.Payload payload = new JsonWebToken.Payload(); payload.setIssuedAtTimeSeconds(Instant.now().getEpochSecond()); payload.setExpirationTimeSeconds( Instant.now().getEpochSecond() + ACCESS_TOKEN_DURATION.getSeconds()); payload.setAudience(GoogleOAuthConstants.TOKEN_SERVER_URL); payload.setIssuer(this.serviceAccountEmail); payload.setSubject(this.userEmail); payload.set("scope", String.join(" ", this.scopes)); return payload; } DelegatedUserCredentials( String serviceAccountEmail, String userEmail, List<String> scopes, IamCredentialsClient credentialsClient, HttpTransport httpTransport); @VisibleForTesting void setClock(Clock clock); @VisibleForTesting JsonWebToken.Payload createJwtPayload(); @Override AccessToken refreshAccessToken(); static final Duration ACCESS_TOKEN_DURATION; }
@Test public void testClaims() { JsonWebToken.Payload payload = delegatedCredentials.createJwtPayload(); assertThat(payload.getAudience()).isEqualTo(GoogleOAuthConstants.TOKEN_SERVER_URL); assertThat(payload.getIssuer()).isEqualTo(SERVICE_ACCOUNT_EMAIL); assertThat(payload.getSubject()).isEqualTo(USER_EMAIL); assertThat(payload.get("scope")).isEqualTo(String.join(" ", SCOPES)); }
CohortMaterializationService { @VisibleForTesting CdrQuery getCdrQuery( SearchRequest searchRequest, DataTableSpecification dataTableSpecification, @Nullable DbCohortReview cohortReview, @Nullable Set<Long> conceptIds) { DbCdrVersion cdrVersion = CdrVersionContext.getCdrVersion(); CdrQuery cdrQuery = new CdrQuery() .bigqueryDataset(cdrVersion.getBigqueryDataset()) .bigqueryProject(cdrVersion.getBigqueryProject()); List<CohortStatus> statusFilter = dataTableSpecification.getStatusFilter(); if (statusFilter == null) { statusFilter = NOT_EXCLUDED; } ParticipantCriteria criteria = getParticipantCriteria(statusFilter, cohortReview, searchRequest); TableQueryAndConfig tableQueryAndConfig = getTableQueryAndConfig(dataTableSpecification.getTableQuery(), conceptIds); cdrQuery.setColumns(tableQueryAndConfig.getTableQuery().getColumns()); if (criteria.getParticipantIdsToInclude() != null && criteria.getParticipantIdsToInclude().isEmpty()) { return cdrQuery; } QueryJobConfiguration jobConfiguration = fieldSetQueryBuilder.getQueryJobConfiguration( criteria, tableQueryAndConfig, dataTableSpecification.getMaxResults()); cdrQuery.setSql(jobConfiguration.getQuery()); ImmutableMap.Builder<String, Object> configurationMap = ImmutableMap.builder(); ImmutableMap.Builder<String, Object> queryConfigurationMap = ImmutableMap.builder(); queryConfigurationMap.put( "queryParameters", jobConfiguration.getNamedParameters().entrySet().stream() .map(TO_QUERY_PARAMETER_MAP) .<Map<String, Object>>toArray()); configurationMap.put("query", queryConfigurationMap.build()); cdrQuery.setConfiguration(configurationMap.build()); return cdrQuery; } @Autowired CohortMaterializationService( FieldSetQueryBuilder fieldSetQueryBuilder, AnnotationQueryBuilder annotationQueryBuilder, ParticipantCohortStatusDao participantCohortStatusDao, CdrBigQuerySchemaConfigService cdrBigQuerySchemaConfigService, ConceptService conceptService, Provider<WorkbenchConfig> configProvider); CdrQuery getCdrQuery( String cohortSpec, DataTableSpecification dataTableSpecification, @Nullable DbCohortReview cohortReview, @Nullable Set<Long> conceptIds); MaterializeCohortResponse materializeCohort( @Nullable DbCohortReview cohortReview, String cohortSpec, @Nullable Set<Long> conceptIds, MaterializeCohortRequest request); CohortAnnotationsResponse getAnnotations( DbCohortReview cohortReview, CohortAnnotationsRequest request); }
@Test public void testGetCdrQueryNoTableQuery() { CdrQuery cdrQuery = cohortMaterializationService.getCdrQuery( SearchRequests.allGenders(), new DataTableSpecification(), cohortReview, null); assertThat(cdrQuery.getBigqueryDataset()).isEqualTo(DATA_SET_ID); assertThat(cdrQuery.getBigqueryProject()).isEqualTo(PROJECT_ID); assertThat(cdrQuery.getColumns()).isEqualTo(ImmutableList.of("person_id")); assertThat(cdrQuery.getSql()) .isEqualTo( "select person.person_id person_id\n" + "from `project_id.data_set_id.person` person\n" + "where\n" + "person.person_id in (select person_id\n" + "from `project_id.data_set_id.person` p\n" + "where\n" + "gender_concept_id in unnest(@p0)\n" + ")\n" + "and person.person_id not in unnest(@person_id_blacklist)\n\n" + "order by person.person_id\n"); Map<String, Map<String, Object>> params = getParameters(cdrQuery); Map<String, Object> genderParam = params.get("p0"); Map<String, Object> personIdBlacklistParam = params.get("person_id_blacklist"); assertParameterArray(genderParam, 8507, 8532, 2); assertParameterArray(personIdBlacklistParam, 2L); } @Test public void testGetCdrQueryWithTableQuery() { CdrQuery cdrQuery = cohortMaterializationService.getCdrQuery( SearchRequests.allGenders(), new DataTableSpecification() .tableQuery( new TableQuery() .tableName("measurement") .columns( ImmutableList.of("person_id", "measurement_concept.concept_name"))), cohortReview, null); assertThat(cdrQuery.getBigqueryDataset()).isEqualTo(DATA_SET_ID); assertThat(cdrQuery.getBigqueryProject()).isEqualTo(PROJECT_ID); assertThat(cdrQuery.getColumns()) .isEqualTo(ImmutableList.of("person_id", "measurement_concept.concept_name")); assertThat(cdrQuery.getSql()) .isEqualTo( "select inner_results.person_id, " + "measurement_concept.concept_name measurement_concept__concept_name\n" + "from (select measurement.person_id person_id, " + "measurement.measurement_concept_id measurement_measurement_concept_id, " + "measurement.person_id measurement_person_id, " + "measurement.measurement_id measurement_measurement_id\n" + "from `project_id.data_set_id.measurement` measurement\n" + "where\n" + "measurement.person_id in (select person_id\n" + "from `project_id.data_set_id.person` p\n" + "where\n" + "gender_concept_id in unnest(@p0)\n" + ")\n" + "and measurement.person_id not in unnest(@person_id_blacklist)\n" + "\n" + "order by measurement.person_id, measurement.measurement_id\n" + ") inner_results\n" + "LEFT OUTER JOIN `project_id.data_set_id.concept` measurement_concept ON " + "inner_results.measurement_measurement_concept_id = measurement_concept.concept_id\n" + "order by measurement_person_id, measurement_measurement_id"); Map<String, Map<String, Object>> params = getParameters(cdrQuery); Map<String, Object> genderParam = params.get("p0"); Map<String, Object> personIdBlacklistParam = params.get("person_id_blacklist"); assertParameterArray(genderParam, 8507, 8532, 2); assertParameterArray(personIdBlacklistParam, 2L); }
CohortMaterializationService { public MaterializeCohortResponse materializeCohort( @Nullable DbCohortReview cohortReview, String cohortSpec, @Nullable Set<Long> conceptIds, MaterializeCohortRequest request) { SearchRequest searchRequest; try { searchRequest = new Gson().fromJson(cohortSpec, SearchRequest.class); } catch (JsonSyntaxException e) { throw new BadRequestException("Invalid cohort spec"); } return materializeCohort( cohortReview, searchRequest, conceptIds, Objects.hash(cohortSpec, conceptIds), request); } @Autowired CohortMaterializationService( FieldSetQueryBuilder fieldSetQueryBuilder, AnnotationQueryBuilder annotationQueryBuilder, ParticipantCohortStatusDao participantCohortStatusDao, CdrBigQuerySchemaConfigService cdrBigQuerySchemaConfigService, ConceptService conceptService, Provider<WorkbenchConfig> configProvider); CdrQuery getCdrQuery( String cohortSpec, DataTableSpecification dataTableSpecification, @Nullable DbCohortReview cohortReview, @Nullable Set<Long> conceptIds); MaterializeCohortResponse materializeCohort( @Nullable DbCohortReview cohortReview, String cohortSpec, @Nullable Set<Long> conceptIds, MaterializeCohortRequest request); CohortAnnotationsResponse getAnnotations( DbCohortReview cohortReview, CohortAnnotationsRequest request); }
@Test public void testMaterializeAnnotationQueryNoPagination() { FieldSet fieldSet = new FieldSet().annotationQuery(new AnnotationQuery()); MaterializeCohortResponse response = cohortMaterializationService.materializeCohort( cohortReview, SearchRequests.allGenders(), null, 0, makeRequest(fieldSet, 1000)); ImmutableMap<String, Object> p1Map = ImmutableMap.of("person_id", 1L, "review_status", "INCLUDED"); assertResults(response, p1Map); assertThat(response.getNextPageToken()).isNull(); } @Test public void testMaterializeAnnotationQueryWithPagination() { FieldSet fieldSet = new FieldSet().annotationQuery(new AnnotationQuery()); MaterializeCohortRequest request = makeRequest(fieldSet, 1) .statusFilter(ImmutableList.of(CohortStatus.INCLUDED, CohortStatus.EXCLUDED)); MaterializeCohortResponse response = cohortMaterializationService.materializeCohort( cohortReview, SearchRequests.allGenders(), null, 0, request); ImmutableMap<String, Object> p1Map = ImmutableMap.of("person_id", 1L, "review_status", "INCLUDED"); assertResults(response, p1Map); assertThat(response.getNextPageToken()).isNotNull(); request.setPageToken(response.getNextPageToken()); MaterializeCohortResponse response2 = cohortMaterializationService.materializeCohort( cohortReview, SearchRequests.allGenders(), null, 0, request); ImmutableMap<String, Object> p2Map = ImmutableMap.of("person_id", 2L, "review_status", "EXCLUDED"); assertResults(response2, p2Map); assertThat(response2.getNextPageToken()).isNull(); }
CohortMaterializationService { public CohortAnnotationsResponse getAnnotations( DbCohortReview cohortReview, CohortAnnotationsRequest request) { List<CohortStatus> statusFilter = request.getStatusFilter(); if (statusFilter == null) { statusFilter = NOT_EXCLUDED; } AnnotationQueryBuilder.AnnotationResults results = annotationQueryBuilder.materializeAnnotationQuery( cohortReview, statusFilter, request.getAnnotationQuery(), null, 0L); return new CohortAnnotationsResponse() .results(ImmutableList.copyOf(results.getResults())) .columns(results.getColumns()); } @Autowired CohortMaterializationService( FieldSetQueryBuilder fieldSetQueryBuilder, AnnotationQueryBuilder annotationQueryBuilder, ParticipantCohortStatusDao participantCohortStatusDao, CdrBigQuerySchemaConfigService cdrBigQuerySchemaConfigService, ConceptService conceptService, Provider<WorkbenchConfig> configProvider); CdrQuery getCdrQuery( String cohortSpec, DataTableSpecification dataTableSpecification, @Nullable DbCohortReview cohortReview, @Nullable Set<Long> conceptIds); MaterializeCohortResponse materializeCohort( @Nullable DbCohortReview cohortReview, String cohortSpec, @Nullable Set<Long> conceptIds, MaterializeCohortRequest request); CohortAnnotationsResponse getAnnotations( DbCohortReview cohortReview, CohortAnnotationsRequest request); }
@Test public void testGetAnnotations() { CohortAnnotationsResponse response = cohortMaterializationService.getAnnotations( cohortReview, new CohortAnnotationsRequest().annotationQuery(new AnnotationQuery())); ImmutableMap<String, Object> p1Map = ImmutableMap.of("person_id", 1L, "review_status", "INCLUDED"); assertResults(response.getResults(), p1Map); }
MailServiceImpl implements MailService { @Override public void sendWelcomeEmail(final String contactEmail, final String password, final User user) throws MessagingException { final MandrillMessage msg = new MandrillMessage() .to(Collections.singletonList(validatedRecipient(contactEmail))) .html(buildHtml(WELCOME_RESOURCE, welcomeMessageSubstitutionMap(password, user))) .subject("Your new All of Us Researcher Workbench Account") .fromEmail(workbenchConfigProvider.get().mandrill.fromEmail); sendWithRetries(msg, String.format("Welcome for %s", user.getName())); } @Autowired MailServiceImpl( Provider<MandrillApi> mandrillApiProvider, Provider<CloudStorageService> cloudStorageServiceProvider, Provider<WorkbenchConfig> workbenchConfigProvider); @Override void sendBetaAccessRequestEmail(final String userName); @Override void sendWelcomeEmail(final String contactEmail, final String password, final User user); @Override void sendInstitutionUserInstructions(String contactEmail, String userInstructions); @Override void alertUserFreeTierDollarThreshold( final DbUser user, double threshold, double currentUsage, double remainingBalance); @Override void alertUserFreeTierExpiration(final DbUser user); @Override void sendBetaAccessCompleteEmail(final String contactEmail, final String username); }
@Test(expected = MessagingException.class) public void testSendWelcomeEmail_throwsMessagingException() throws MessagingException, ApiException { when(msgStatus.getRejectReason()).thenReturn("this was rejected"); User user = createUser(); service.sendWelcomeEmail(CONTACT_EMAIL, PASSWORD, user); verify(mandrillApi, times(1)).send(any()); } @Test(expected = MessagingException.class) public void testSendWelcomeEmail_throwsApiException() throws MessagingException, ApiException { doThrow(ApiException.class).when(mandrillApi).send(any()); User user = createUser(); service.sendWelcomeEmail(CONTACT_EMAIL, PASSWORD, user); verify(mandrillApi, times(3)).send(any()); } @Test(expected = MessagingException.class) public void testSendWelcomeEmail_invalidEmail() throws MessagingException { User user = createUser(); service.sendWelcomeEmail("Nota valid email", PASSWORD, user); } @Test public void testSendWelcomeEmail() throws MessagingException, ApiException { User user = createUser(); service.sendWelcomeEmail(CONTACT_EMAIL, PASSWORD, user); verify(mandrillApi, times(1)).send(any(MandrillApiKeyAndMessage.class)); }
AnnotationQueryBuilder { public AnnotationResults materializeAnnotationQuery( DbCohortReview cohortReview, List<CohortStatus> statusFilter, AnnotationQuery annotationQuery, Integer limit, long offset) { if (statusFilter == null || statusFilter.isEmpty()) { throw new BadRequestException("statusFilter cannot be empty"); } Map<String, DbCohortAnnotationDefinition> annotationDefinitions = null; List<String> columns = annotationQuery.getColumns(); if (columns == null || columns.isEmpty()) { columns = new ArrayList<>(); columns.add(PERSON_ID_COLUMN); columns.add(REVIEW_STATUS_COLUMN); annotationDefinitions = getAnnotationDefinitions(cohortReview); columns.addAll( annotationDefinitions.values().stream() .map(DbCohortAnnotationDefinition::getColumnName) .collect(Collectors.toList())); annotationQuery.setColumns(columns); } List<String> orderBy = annotationQuery.getOrderBy(); if (orderBy == null || orderBy.isEmpty()) { annotationQuery.setOrderBy(ImmutableList.of(PERSON_ID_COLUMN)); } ImmutableMap.Builder<String, Object> parameters = ImmutableMap.builder(); String sql = getSql( cohortReview, statusFilter, annotationQuery, limit, offset, annotationDefinitions, parameters); Iterable<Map<String, Object>> results = namedParameterJdbcTemplate.query( sql, parameters.build(), new RowMapper<Map<String, Object>>() { @Override public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { ImmutableMap.Builder<String, Object> result = ImmutableMap.builder(); List<String> columns = annotationQuery.getColumns(); for (int i = 0; i < columns.size(); i++) { Object obj = rs.getObject(i + 1); if (obj != null) { String column = columns.get(i); if (column.equals(REVIEW_STATUS_COLUMN)) { result.put( column, DbStorageEnums.cohortStatusFromStorage(((Number) obj).shortValue()) .name()); } else if (obj instanceof java.sql.Date) { result.put(column, DATE_FORMAT.format((java.sql.Date) obj)); } else { result.put(column, obj); } } } return result.build(); } }); return new AnnotationResults(results, annotationQuery.getColumns()); } @Autowired AnnotationQueryBuilder( NamedParameterJdbcTemplate namedParameterJdbcTemplate, CohortAnnotationDefinitionDao cohortAnnotationDefinitionDao); AnnotationResults materializeAnnotationQuery( DbCohortReview cohortReview, List<CohortStatus> statusFilter, AnnotationQuery annotationQuery, Integer limit, long offset); static final String PERSON_ID_COLUMN; static final String REVIEW_STATUS_COLUMN; static final ImmutableSet<String> RESERVED_COLUMNS; static final String DESCENDING_PREFIX; }
@Test public void testQueryEmptyReview() { assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, INCLUDED_ONLY, new AnnotationQuery(), 10, 0), allColumns); } @Test public void testQueryOneIncluded() { saveReviewStatuses(); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, INCLUDED_ONLY, new AnnotationQuery(), 10, 0), allColumns, ImmutableMap.of("person_id", INCLUDED_PERSON_ID, "review_status", "INCLUDED")); } @Test public void testQueryAllStatuses() { saveReviewStatuses(); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, new AnnotationQuery(), 10, 0), allColumns, ImmutableMap.of("person_id", INCLUDED_PERSON_ID, "review_status", "INCLUDED"), ImmutableMap.of("person_id", EXCLUDED_PERSON_ID, "review_status", "EXCLUDED")); } @Test public void testQueryAllStatusesReviewStatusOrder() { saveReviewStatuses(); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setOrderBy(ImmutableList.of("review_status")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, annotationQuery, 10, 0), allColumns, ImmutableMap.of("person_id", EXCLUDED_PERSON_ID, "review_status", "EXCLUDED"), ImmutableMap.of("person_id", INCLUDED_PERSON_ID, "review_status", "INCLUDED")); } @Test public void testQueryAllStatusesReviewPersonIdOrderDescending() { saveReviewStatuses(); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setOrderBy(ImmutableList.of("DESCENDING(person_id)")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, annotationQuery, 10, 0), allColumns, ImmutableMap.of("person_id", EXCLUDED_PERSON_ID, "review_status", "EXCLUDED"), ImmutableMap.of("person_id", INCLUDED_PERSON_ID, "review_status", "INCLUDED")); } @Test public void testQueryIncludedWithAnnotations() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); ImmutableMap<String, Object> expectedResult = ImmutableMap.<String, Object>builder() .put("person_id", INCLUDED_PERSON_ID) .put("review_status", "INCLUDED") .put("integer annotation", 123) .put("string annotation", "foo") .put("boolean annotation", true) .put("date annotation", "2017-02-14") .put("enum annotation", "zebra") .build(); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, INCLUDED_ONLY, new AnnotationQuery(), 10, 0), allColumns, expectedResult); } @Test public void testQueryIncludedWithAnnotationsNoReviewStatus() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); ImmutableMap<String, Object> expectedResult = ImmutableMap.<String, Object>builder() .put("person_id", INCLUDED_PERSON_ID) .put("integer annotation", 123) .put("string annotation", "foo") .put("boolean annotation", true) .put("date annotation", "2017-02-14") .put("enum annotation", "zebra") .build(); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setColumns( ImmutableList.of( "person_id", "integer annotation", "string annotation", "boolean annotation", "date annotation", "enum annotation")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, INCLUDED_ONLY, annotationQuery, 10, 0), annotationQuery.getColumns(), expectedResult); } @Test public void testQueryAllWithAnnotations() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, new AnnotationQuery(), 10, 0), allColumns, expectedResult1, expectedResult2); } @Test public void testQueryAllWithAnnotationsLimit1() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, new AnnotationQuery(), 1, 0), allColumns, expectedResult1); } @Test public void testQueryAllWithAnnotationsLimit1Offset1() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, new AnnotationQuery(), 1, 1), allColumns, expectedResult2); } @Test public void testQueryAllWithAnnotationsOrderByIntegerDescending() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setOrderBy(ImmutableList.of("DESCENDING(integer annotation)", "person_id")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, annotationQuery, 10, 0), allColumns, expectedResult2, expectedResult1); } @Test public void testQueryAllWithAnnotationsOrderByBoolean() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setOrderBy(ImmutableList.of("boolean annotation", "person_id")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, annotationQuery, 10, 0), allColumns, expectedResult2, expectedResult1); } @Test public void testQueryAllWithAnnotationsOrderByDateDescending() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setOrderBy(ImmutableList.of("DESCENDING(date annotation)", "person_id")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, annotationQuery, 10, 0), allColumns, expectedResult2, expectedResult1); } @Test public void testQueryAllWithAnnotationsOrderByString() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setOrderBy(ImmutableList.of("string annotation", "person_id")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, annotationQuery, 10, 0), allColumns, expectedResult2, expectedResult1); } @Test public void testQueryAllWithAnnotationsOrderByEnum() throws Exception { saveReviewStatuses(); saveAnnotations(INCLUDED_PERSON_ID, 123, "foo", true, "2017-02-14", "zebra"); saveAnnotations(EXCLUDED_PERSON_ID, 456, null, false, "2017-02-15", "aardvark"); AnnotationQuery annotationQuery = new AnnotationQuery(); annotationQuery.setOrderBy(ImmutableList.of("enum annotation", "person_id")); assertResults( annotationQueryBuilder.materializeAnnotationQuery( cohortReview, ALL_STATUSES, annotationQuery, 10, 0), allColumns, expectedResult2, expectedResult1); }
RandomizeVcf extends VariantWalker { @VisibleForTesting protected VariantContext randomizeVariant(VariantContext variant) { VariantContextBuilder variantContextBuilder = new VariantContextBuilder(variant); variantContextBuilder.alleles(variant.getAlleles()); List<Genotype> randomizedGenotypes = this.sampleNames.stream() .map(name -> randomizeGenotype(variant, variant.getGenotype(0), name)) .collect(Collectors.toList()); GenotypesContext randomizedGenotypesContext = GenotypesContext.create(new ArrayList<>(randomizedGenotypes)); variantContextBuilder.genotypes(randomizedGenotypesContext); return variantContextBuilder.make(); } RandomizeVcf(); @VisibleForTesting protected RandomizeVcf(List<String> sampleNames, Random random); static void main(String[] argv); @Override void apply( VariantContext variant, ReadsContext readsContext, ReferenceContext referenceContext, FeatureContext featureContext); @Override void onTraversalStart(); @Override void closeTool(); }
@Test public void testRandomizeVariant() { VariantContext randomizedVariant = randomizeVcf.randomizeVariant(variantContext); assertThat(randomizedVariant.getGenotypes().size()).isEqualTo(2); assertThat(randomizedVariant.getGenotypes().getSampleNames()) .isEqualTo(new HashSet<>(sampleNames)); randomizedVariant.getGenotypes().stream() .flatMap(genotype -> genotype.getAlleles().stream()) .forEach( allele -> assertThat( variantContext.getAlleles().stream() .anyMatch(vcAllele -> vcAllele.basesMatch(allele))) .isTrue()); }
RandomizeVcf extends VariantWalker { @VisibleForTesting protected List<Allele> randomizeAlleles(VariantContext variantContext) { List<Allele> alleles = new ArrayList<>(); double genotypeTypeIndex = random.nextDouble(); if (variantContext.getAlternateAlleles().size() == 2) { if (genotypeTypeIndex < .8240) { alleles.add(Allele.NO_CALL); alleles.add(Allele.NO_CALL); return alleles; } else if (genotypeTypeIndex < .8654) { alleles.add(variantContext.getAlternateAllele(0)); alleles.add(variantContext.getAlternateAllele(1)); } else if (genotypeTypeIndex < .9268) { alleles.add(variantContext.getAlternateAllele(1)); alleles.add(variantContext.getAlternateAllele(0)); } else { alleles.add(variantContext.getAlternateAllele(1)); alleles.add(variantContext.getAlternateAllele(1)); } } else { if (genotypeTypeIndex < .0145) { alleles.add(Allele.NO_CALL); alleles.add(Allele.NO_CALL); return alleles; } else if (genotypeTypeIndex < .8095) { alleles.add(variantContext.getReference()); alleles.add(variantContext.getReference()); } else if (genotypeTypeIndex < .8654) { alleles.add(variantContext.getReference()); alleles.add(variantContext.getAlternateAllele(0)); } else if (genotypeTypeIndex < .9268) { alleles.add(variantContext.getAlternateAllele(0)); alleles.add(variantContext.getReference()); } else { alleles.add(variantContext.getAlternateAllele(0)); alleles.add(variantContext.getAlternateAllele(0)); } } return alleles; } RandomizeVcf(); @VisibleForTesting protected RandomizeVcf(List<String> sampleNames, Random random); static void main(String[] argv); @Override void apply( VariantContext variant, ReadsContext readsContext, ReferenceContext referenceContext, FeatureContext featureContext); @Override void onTraversalStart(); @Override void closeTool(); }
@Test public void testRandomizeAlleles() { List<Allele> alleles = randomizeVcf.randomizeAlleles(variantContext); assertThat(alleles.size()).isEqualTo(2); alleles.forEach(allele -> assertThat(variantContext.getAlleles()).contains(allele)); }
ShibbolethServiceImpl implements ShibbolethService { @Override public void updateShibbolethToken(String jwt) { ShibbolethApi shibbolethApi = shibbolethApiProvider.get(); shibbolethRetryHandler.run( (context) -> { shibbolethApi.postShibbolethToken(jwt); return null; }); } @Autowired ShibbolethServiceImpl( Provider<ShibbolethApi> shibbolethApiProvider, ShibbolethRetryHandler shibbolethRetryHandler); @Override void updateShibbolethToken(String jwt); }
@Test public void testUpdateShibbolethToken() throws Exception { shibbolethService.updateShibbolethToken("asdf"); verify(shibbolethApi, times(1)).postShibbolethToken("asdf"); }
ExceptionUtils { public static WorkbenchException convertNotebookException( org.pmiops.workbench.notebooks.ApiException e) { if (isSocketTimeoutException(e.getCause())) { throw new GatewayTimeoutException(); } throw codeToException(e.getCode()); } private ExceptionUtils(); static boolean isGoogleServiceUnavailableException(IOException e); static boolean isGoogleConflictException(IOException e); static WorkbenchException convertGoogleIOException(IOException e); static boolean isSocketTimeoutException(Throwable e); static WorkbenchException convertFirecloudException(ApiException e); static WorkbenchException convertNotebookException( org.pmiops.workbench.notebooks.ApiException e); static WorkbenchException convertLeonardoException( org.pmiops.workbench.leonardo.ApiException e); static WorkbenchException convertShibbolethException( org.pmiops.workbench.shibboleth.ApiException e); static boolean isServiceUnavailable(int code); }
@Test(expected = GatewayTimeoutException.class) public void convertNotebookException() throws Exception { ApiException cause = new ApiException(new SocketTimeoutException()); ExceptionUtils.convertNotebookException(cause); }
AggregationUtils { public static AggregationBuilder buildDemoChartAggregation( GenderOrSexType genderOrSexType, AgeType ageType, String ageRange) { String[] ages = ageRange.split("-"); Integer lo = Integer.valueOf(ages[0]); Integer hi = (ages.length > 1) ? Integer.valueOf(ages[1]) : null; LocalDate startDate = (hi != null) ? ElasticUtils.todayMinusYears(hi + 1) : null; LocalDate endDate = ElasticUtils.todayMinusYears(lo); boolean isGender = GenderOrSexType.GENDER.equals(genderOrSexType); boolean isAgeAtConsent = AgeType.AGE_AT_CONSENT.equals(ageType); TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms(GENDER_OR_SEX + ageRange) .field(isGender ? "gender_concept_name" : "sex_at_birth_concept_name") .order(BucketOrder.key(true)) .subAggregation( AggregationBuilders.terms(RACE + ageRange) .field("race_concept_name") .order(BucketOrder.key(true)) .minDocCount(1)); return AgeType.AGE.equals(ageType) ? AggregationBuilders.dateRange(DATE + ageRange) .field("birth_datetime") .format("yyyy-MM-dd") .addRange((startDate == null) ? null : startDate.toString(), endDate.toString()) .subAggregation(termsAggregationBuilder) : AggregationBuilders.range(DATE + ageRange) .field(isAgeAtConsent ? "age_at_consent" : "age_at_cdr") .addRange(new Double(lo), new Double(hi)) .subAggregation(termsAggregationBuilder); } static AggregationBuilder buildDemoChartAggregation( GenderOrSexType genderOrSexType, AgeType ageType, String ageRange); static List<DemoChartInfo> unwrapDemoChartBuckets( SearchResponse searchResponse, String... ageRanges); static final String RANGE_18_44; static final String RANGE_45_64; static final String RANGE_GT_65; static final String DATE; static final String GENDER_OR_SEX; static final String RACE; }
@Test public void buildDemoChartAggregationAgeGenderRace() { AggregationBuilder actualBuilder = AggregationUtils.buildDemoChartAggregation( GenderOrSexType.GENDER, AgeType.AGE, RANGE_18_44); assertThat(actualBuilder.getName()).isEqualTo(DATE + RANGE_18_44); assertThat(actualBuilder.getType()).isEqualTo("date_range"); assertThat(actualBuilder.getSubAggregations().size()).isEqualTo(1); AggregationBuilder genderBuilder = actualBuilder.getSubAggregations().iterator().next(); assertThat(genderBuilder.getName()).isEqualTo(GENDER_OR_SEX + RANGE_18_44); assertThat(genderBuilder.getType()).isEqualTo("terms"); assertThat(genderBuilder.getSubAggregations().size()).isEqualTo(1); AggregationBuilder raceBuilder = genderBuilder.getSubAggregations().iterator().next(); assertThat(raceBuilder.getName()).isEqualTo(RACE + RANGE_18_44); assertThat(raceBuilder.getType()).isEqualTo("terms"); assertThat(raceBuilder.getSubAggregations().isEmpty()).isTrue(); } @Test public void buildDemoChartAggregationAgeSexAtBirthRace() { AggregationBuilder actualBuilder = AggregationUtils.buildDemoChartAggregation( GenderOrSexType.SEX_AT_BIRTH, AgeType.AGE, RANGE_18_44); assertThat(actualBuilder.getName()).isEqualTo(DATE + RANGE_18_44); assertThat(actualBuilder.getType()).isEqualTo("date_range"); assertThat(actualBuilder.getSubAggregations().size()).isEqualTo(1); AggregationBuilder genderBuilder = actualBuilder.getSubAggregations().iterator().next(); assertThat(genderBuilder.getName()).isEqualTo(GENDER_OR_SEX + RANGE_18_44); assertThat(genderBuilder.getType()).isEqualTo("terms"); assertThat(genderBuilder.getSubAggregations().size()).isEqualTo(1); AggregationBuilder raceBuilder = genderBuilder.getSubAggregations().iterator().next(); assertThat(raceBuilder.getName()).isEqualTo(RACE + RANGE_18_44); assertThat(raceBuilder.getType()).isEqualTo("terms"); assertThat(raceBuilder.getSubAggregations().isEmpty()).isTrue(); } @Test public void buildDemoChartAggregationAgeAtConsentGenderRace() { AggregationBuilder actualBuilder = AggregationUtils.buildDemoChartAggregation( GenderOrSexType.GENDER, AgeType.AGE_AT_CONSENT, RANGE_18_44); assertThat(actualBuilder.getName()).isEqualTo(DATE + RANGE_18_44); assertThat(actualBuilder.getType()).isEqualTo("range"); assertThat(actualBuilder.getSubAggregations().size()).isEqualTo(1); AggregationBuilder genderBuilder = actualBuilder.getSubAggregations().iterator().next(); assertThat(genderBuilder.getName()).isEqualTo(GENDER_OR_SEX + RANGE_18_44); assertThat(genderBuilder.getType()).isEqualTo("terms"); assertThat(genderBuilder.getSubAggregations().size()).isEqualTo(1); AggregationBuilder raceBuilder = genderBuilder.getSubAggregations().iterator().next(); assertThat(raceBuilder.getName()).isEqualTo(RACE + RANGE_18_44); assertThat(raceBuilder.getType()).isEqualTo("terms"); assertThat(raceBuilder.getSubAggregations().isEmpty()).isTrue(); }
ElasticFilters { public static QueryBuilder fromCohortSearch(CBCriteriaDao cbCriteriaDao, SearchRequest req) { ElasticFilters f = new ElasticFilters(cbCriteriaDao); return f.process(req); } private ElasticFilters(CBCriteriaDao cbCriteriaDao); static QueryBuilder fromCohortSearch(CBCriteriaDao cbCriteriaDao, SearchRequest req); }
@Test public void testLeafQuery() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(leafParam2))) .addDataFiltersItem("has_ehr_data") .addDataFiltersItem("has_physical_measurement_data")); assertThat(resp) .isEqualTo( singleNestedQuery( ImmutableList.of("has_ehr_data", "has_physical_measurement_data"), QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("772")))); } @Test public void testParentConceptQuery() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem( new SearchParameter() .conceptId(21600002L) .domain(DomainType.DRUG.toString()) .type(CriteriaType.ATC.toString()) .ancestorData(true) .standard(true) .group(true))))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery( "events.concept_id", ImmutableList.of("21600002", "21600009")))); } @Test public void testICD9Query() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem( new SearchParameter() .value("001") .conceptId(771L) .domain(DomainType.CONDITION.toString()) .type(CriteriaType.ICD9CM.toString()) .group(true) .ancestorData(false) .standard(false))))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery( "events.source_concept_id", ImmutableList.of("771", "772", "773")))); } @Test public void testICD9AndSnomedQuery() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem( new SearchParameter() .value("001") .conceptId(771L) .domain(DomainType.CONDITION.toString()) .type(CriteriaType.ICD9CM.toString()) .group(false) .ancestorData(false) .standard(false)) .addSearchParametersItem( new SearchParameter() .conceptId(477L) .domain(DomainType.CONDITION.toString()) .type(CriteriaType.SNOMED.toString()) .group(false) .ancestorData(false) .standard(true))))); BoolQueryBuilder source = QueryBuilders.boolQuery(); source.filter(QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("771"))); BoolQueryBuilder standard = QueryBuilders.boolQuery(); standard.filter(QueryBuilders.termsQuery("events.concept_id", ImmutableList.of("477"))); QueryBuilder expected = QueryBuilders.boolQuery() .filter( QueryBuilders.boolQuery() .should( QueryBuilders.functionScoreQuery( QueryBuilders.nestedQuery( "events", QueryBuilders.constantScoreQuery(source), ScoreMode.Total)) .setMinScore(1)) .should( QueryBuilders.functionScoreQuery( QueryBuilders.nestedQuery( "events", QueryBuilders.constantScoreQuery(standard), ScoreMode.Total)) .setMinScore(1))); assertThat(resp).isEqualTo(expected); } @Test public void testPPIAnswerQuery() { Attribute attr = new Attribute().name(AttrName.NUM).operator(Operator.EQUAL).addOperandsItem("1"); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem( new SearchParameter() .domain(DomainType.SURVEY.toString()) .type(CriteriaType.PPI.toString()) .subtype(CriteriaSubType.ANSWER.toString()) .conceptId(7771L) .group(false) .ancestorData(false) .standard(false) .addAttributesItem(attr))))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("7771")), QueryBuilders.rangeQuery("events.value_as_number").gte(1.0F).lte(1.0F))); } @Test public void testPPIAnswerQueryCat() { Attribute attr = new Attribute().name(AttrName.CAT).operator(Operator.IN).addOperandsItem("1"); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem( new SearchParameter() .domain(DomainType.SURVEY.toString()) .type(CriteriaType.PPI.toString()) .subtype(CriteriaSubType.ANSWER.toString()) .conceptId(777L) .group(false) .ancestorData(false) .standard(false) .addAttributesItem(attr))))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("777")), QueryBuilders.termsQuery( "events.value_as_source_concept_id", ImmutableList.of("1")))); } @Test public void testAgeAtEventModifierQuery() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem(leafParam2) .addModifiersItem( new Modifier() .name(ModifierType.AGE_AT_EVENT) .operator(Operator.GREATER_THAN_OR_EQUAL_TO) .addOperandsItem("18"))))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("772")), QueryBuilders.rangeQuery("events.age_at_start").gte(18))); } @Test public void testDateModifierQuery() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem(leafParam2) .addModifiersItem( new Modifier() .name(ModifierType.EVENT_DATE) .operator(Operator.BETWEEN) .addOperandsItem("12/25/1988") .addOperandsItem("12/27/1988"))))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("772")), QueryBuilders.rangeQuery("events.start_date").gte("12/25/1988").lte("12/27/1988"))); } @Test public void testVisitsModifierQuery() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem(leafParam2) .addModifiersItem( new Modifier() .name(ModifierType.ENCOUNTERS) .operator(Operator.IN) .addOperandsItem("123"))))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("772")), QueryBuilders.termsQuery("events.visit_concept_id", ImmutableList.of("123")))); } @Test public void testNumOfOccurrencesModifierQuery() { QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .addSearchParametersItem(leafParam2) .addModifiersItem( new Modifier() .name(ModifierType.NUM_OF_OCCURRENCES) .operator(Operator.GREATER_THAN_OR_EQUAL_TO) .addOperandsItem("13"))))); assertThat(resp) .isEqualTo( singleNestedQueryOccurrences( NO_DATA_FILTERS, 13, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of("772")))); } @Test public void testHeightAnyQuery() { String conceptId = "903133"; SearchParameter heightAnyParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PHYSICAL_MEASUREMENT.toString()) .type(CriteriaType.PPI.toString()) .standard(false) .ancestorData(false) .group(false); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem().addSearchParametersItem(heightAnyParam)))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of(conceptId)))); } @Test public void testHeightEqualQuery() { Attribute attr = new Attribute().name(AttrName.NUM).operator(Operator.EQUAL).operands(ImmutableList.of("1")); Object left = Float.parseFloat(attr.getOperands().get(0)); Object right = Float.parseFloat(attr.getOperands().get(0)); String conceptId = "903133"; SearchParameter heightParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PHYSICAL_MEASUREMENT.toString()) .type(CriteriaType.PPI.toString()) .group(false) .ancestorData(false) .standard(false) .addAttributesItem(attr); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(heightParam)))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of(conceptId)), QueryBuilders.rangeQuery("events.value_as_number").gte(left).lte(right))); } @Test public void testWeightBetweenQuery() { Attribute attr = new Attribute() .name(AttrName.NUM) .operator(Operator.BETWEEN) .operands(ImmutableList.of("1", "2")); Object left = Float.parseFloat(attr.getOperands().get(0)); Object right = Float.parseFloat(attr.getOperands().get(1)); String conceptId = "903121"; SearchParameter weightParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PHYSICAL_MEASUREMENT.toString()) .type(CriteriaType.PPI.toString()) .standard(false) .ancestorData(false) .group(false) .addAttributesItem(attr); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(weightParam)))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of(conceptId)), QueryBuilders.rangeQuery("events.value_as_number").gte(left).lte(right))); } @Test public void testGenderQuery() { String conceptId = "8507"; SearchParameter genderParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PERSON.toString()) .type(CriteriaType.GENDER.toString()) .standard(true) .ancestorData(false) .group(false); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(genderParam)))); assertThat(resp) .isEqualTo( nonNestedQuery( QueryBuilders.termsQuery("gender_concept_id", ImmutableList.of(conceptId)))); } @Test public void testGenderExcludeQuery() { String conceptId = "8507"; SearchParameter genderParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PERSON.toString()) .type(CriteriaType.GENDER.toString()) .group(false) .ancestorData(false) .standard(true); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addExcludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(genderParam)))); assertThat(resp) .isEqualTo( nonNestedQuery( QueryBuilders.termsQuery("gender_concept_id", ImmutableList.of(conceptId)))); } @Test public void testGenderIncludeAndExcludeQuery() { String conceptId = "8507"; SearchParameter genderParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PERSON.toString()) .type(CriteriaType.GENDER.toString()) .group(false) .ancestorData(false) .standard(true); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(genderParam))) .addExcludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(genderParam)))); assertThat(resp) .isEqualTo( nonNestedMustNotQuery( QueryBuilders.termsQuery("gender_concept_id", ImmutableList.of(conceptId)))); } @Test public void testRaceQuery() { String conceptId = "8515"; SearchParameter raceParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PERSON.toString()) .type(CriteriaType.RACE.toString()) .group(false) .ancestorData(false) .standard(true); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(raceParam)))); assertThat(resp) .isEqualTo( nonNestedQuery( QueryBuilders.termsQuery("race_concept_id", ImmutableList.of(conceptId)))); } @Test public void testEthnicityQuery() { String conceptId = "38003563"; SearchParameter ethParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PERSON.toString()) .type(CriteriaType.ETHNICITY.toString()) .group(false) .ancestorData(false) .standard(true); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(ethParam)))); assertThat(resp) .isEqualTo( nonNestedQuery( QueryBuilders.termsQuery("ethnicity_concept_id", ImmutableList.of(conceptId)))); } @Test public void testDeceasedQuery() { SearchParameter deceasedParam = new SearchParameter() .domain(DomainType.PERSON.toString()) .type(CriteriaType.DECEASED.toString()) .standard(true) .ancestorData(false) .group(false); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem().addSearchParametersItem(deceasedParam)))); assertThat(resp).isEqualTo(nonNestedQuery(QueryBuilders.termQuery("is_deceased", true))); } @Test public void testPregnancyQuery() { String conceptId = "903120"; String operand = "12345"; Attribute attr = new Attribute() .name(AttrName.CAT) .operator(Operator.IN) .operands(ImmutableList.of(operand)); SearchParameter pregParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PHYSICAL_MEASUREMENT.toString()) .type(CriteriaType.PPI.toString()) .group(false) .ancestorData(false) .standard(false) .attributes(ImmutableList.of(attr)); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(pregParam)))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.source_concept_id", ImmutableList.of(conceptId)), QueryBuilders.termsQuery("events.value_as_concept_id", ImmutableList.of(operand)))); } @Test public void testMeasurementCategoricalQuery() { String conceptId = "3015813"; String operand1 = "12345"; String operand2 = "12346"; Attribute attr = new Attribute() .name(AttrName.CAT) .operator(Operator.IN) .operands(ImmutableList.of(operand1, operand2)); SearchParameter measParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.MEASUREMENT.toString()) .type(CriteriaType.LOINC.toString()) .group(false) .ancestorData(false) .standard(true) .attributes(ImmutableList.of(attr)); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(measParam)))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.concept_id", ImmutableList.of(conceptId)), QueryBuilders.termsQuery( "events.value_as_concept_id", ImmutableList.of(operand1, operand2)))); } @Test public void testVisitQuery() { String conceptId = "9202"; SearchParameter visitParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.VISIT.toString()) .type(CriteriaType.VISIT.toString()) .ancestorData(false) .standard(true) .group(false); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(visitParam)))); assertThat(resp) .isEqualTo( singleNestedQuery( NO_DATA_FILTERS, QueryBuilders.termsQuery("events.concept_id", ImmutableList.of(conceptId)))); } @Test public void testAgeQuery() { OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); Object left = now.minusYears(34).minusYears(1).toLocalDate(); Object right = now.minusYears(20).toLocalDate(); SearchParameter ageParam = new SearchParameter() .domain(DomainType.PERSON.toString()) .type(CriteriaType.AGE.toString()) .group(false) .ancestorData(false) .standard(true) .addAttributesItem( new Attribute() .name(AttrName.AGE) .operator(Operator.BETWEEN) .operands(ImmutableList.of("20", "34"))); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem(new SearchGroupItem().addSearchParametersItem(ageParam)))); BoolQueryBuilder ageBuilder = QueryBuilders.boolQuery() .filter(QueryBuilders.termQuery("is_deceased", false)) .filter( QueryBuilders.rangeQuery("birth_datetime") .gte(left) .lte(right) .format("yyyy-MM-dd")); assertThat(resp).isEqualTo(nonNestedQuery(ageBuilder)); } @Test public void testAgeAtConsentQuery() { OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); Object left = 20; Object right = 34; SearchParameter ageAtConsentParam = new SearchParameter() .domain(DomainType.PERSON.toString()) .type(CriteriaType.AGE.toString()) .group(false) .ancestorData(false) .standard(true) .addAttributesItem( new Attribute() .name(AttrName.AGE_AT_CONSENT) .operator(Operator.BETWEEN) .operands(ImmutableList.of("20", "34"))); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem().addSearchParametersItem(ageAtConsentParam)))); BoolQueryBuilder ageBuilder = QueryBuilders.boolQuery() .filter(QueryBuilders.termQuery("is_deceased", false)) .filter(QueryBuilders.rangeQuery("age_at_consent").gte(left).lte(right)); assertThat(resp).isEqualTo(nonNestedQuery(ageBuilder)); } @Test public void testAgeAndEthnicityQuery() { OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); Object left = now.minusYears(34).minusYears(1).toLocalDate(); Object right = now.minusYears(20).toLocalDate(); SearchParameter ageParam = new SearchParameter() .domain(DomainType.PERSON.toString()) .type(CriteriaType.AGE.toString()) .group(false) .ancestorData(false) .standard(true) .addAttributesItem( new Attribute() .name(AttrName.AGE) .operator(Operator.BETWEEN) .operands(ImmutableList.of("20", "34"))); String conceptId = "38003563"; SearchParameter ethParam = new SearchParameter() .conceptId(Long.parseLong(conceptId)) .domain(DomainType.PERSON.toString()) .type(CriteriaType.ETHNICITY.toString()) .group(false) .ancestorData(false) .standard(true) .conceptId(Long.parseLong(conceptId)); QueryBuilder resp = ElasticFilters.fromCohortSearch( cbCriteriaDao, new SearchRequest() .addIncludesItem( new SearchGroup() .addItemsItem( new SearchGroupItem() .searchParameters(ImmutableList.of(ageParam, ethParam))))); BoolQueryBuilder ageBuilder = QueryBuilders.boolQuery() .filter(QueryBuilders.termQuery("is_deceased", false)) .filter( QueryBuilders.rangeQuery("birth_datetime") .gte(left) .lte(right) .format("yyyy-MM-dd")); assertThat(resp) .isEqualTo( nonNestedQuery( ageBuilder, QueryBuilders.termsQuery("ethnicity_concept_id", ImmutableList.of(conceptId)))); }
FireCloudServiceImpl implements FireCloudService { @Override public FirecloudNihStatus getNihStatus() { NihApi nihApi = nihApiProvider.get(); return retryHandler.run( (context) -> { try { return nihApi.nihStatus(); } catch (ApiException e) { if (e.getCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { return null; } else { throw e; } } }); } @Autowired FireCloudServiceImpl( Provider<WorkbenchConfig> configProvider, Provider<ProfileApi> profileApiProvider, Provider<BillingApi> billingApiProvider, Provider<GroupsApi> groupsApiProvider, Provider<NihApi> nihApiProvider, @Qualifier(FireCloudConfig.END_USER_WORKSPACE_API) Provider<WorkspacesApi> endUserWorkspacesApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_WORKSPACE_API) Provider<WorkspacesApi> serviceAccountWorkspaceApiProvider, Provider<StatusApi> statusApiProvider, @Qualifier(FireCloudConfig.END_USER_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> endUserStaticNotebooksApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> serviceAccountStaticNotebooksApiProvider, FirecloudRetryHandler retryHandler, @Qualifier(Constants.FIRECLOUD_ADMIN_CREDS) Provider<ServiceAccountCredentials> fcAdminCredsProvider, IamCredentialsClient iamCredentialsClient, HttpTransport httpTransport); ApiClient getApiClientWithImpersonation(String userEmail); @Override @VisibleForTesting String getApiBasePath(); @Override boolean getFirecloudStatus(); @Override FirecloudMe getMe(); @Override void registerUser(String contactEmail, String firstName, String lastName); @Override void createAllOfUsBillingProject(String projectName); @Override void deleteBillingProject(String billingProject); @Override FirecloudBillingProjectStatus getBillingProjectStatus(String projectName); @Override void addOwnerToBillingProject(String ownerEmail, String projectName); @Override void removeOwnerFromBillingProject( String ownerEmailToRemove, String projectName, Optional<String> callerAccessToken); @Override FirecloudWorkspace createWorkspace(String projectName, String workspaceName); @Override FirecloudWorkspace cloneWorkspace( String fromProject, String fromName, String toProject, String toName); @Override List<FirecloudBillingProjectMembership> getBillingProjectMemberships(); @Override FirecloudWorkspaceACLUpdateResponseList updateWorkspaceACL( String projectName, String workspaceName, List<FirecloudWorkspaceACLUpdate> aclUpdates); @Override FirecloudWorkspaceACL getWorkspaceAclAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspaceAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspace(String projectName, String workspaceName); @Override Optional<FirecloudWorkspaceResponse> getWorkspace(DbWorkspace dbWorkspace); @Override List<FirecloudWorkspaceResponse> getWorkspaces(); @Override void deleteWorkspace(String projectName, String workspaceName); @Override FirecloudManagedGroupWithMembers getGroup(String groupName); @Override FirecloudManagedGroupWithMembers createGroup(String groupName); @Override void addUserToGroup(String email, String groupName); @Override void removeUserFromGroup(String email, String groupName); @Override boolean isUserMemberOfGroup(String email, String groupName); @Override String staticNotebooksConvert(byte[] notebook); @Override String staticNotebooksConvertAsService(byte[] notebook); @Override FirecloudNihStatus getNihStatus(); @Override void postNihCallback(FirecloudJWTWrapper wrapper); static final List<String> FIRECLOUD_API_OAUTH_SCOPES; static final List<String> FIRECLOUD_WORKSPACE_REQUIRED_FIELDS; }
@Test public void testNihStatus() throws Exception { FirecloudNihStatus status = new FirecloudNihStatus().linkedNihUsername("test").linkExpireTime(500L); when(nihApi.nihStatus()).thenReturn(status); assertThat(service.getNihStatus()).isNotNull(); assertThat(service.getNihStatus()).isEqualTo(status); } @Test public void testNihStatusNotFound() throws Exception { when(nihApi.nihStatus()).thenThrow(new ApiException(404, "Not Found")); assertThat(service.getNihStatus()).isNull(); } @Test(expected = ServerErrorException.class) public void testNihStatusException() throws Exception { when(nihApi.nihStatus()).thenThrow(new ApiException(500, "Internal Server Error")); service.getNihStatus(); }
GaugeRecorderService { public void record() { logsBasedMetricService.recordElapsedTime( MeasurementBundle.builder(), DistributionMetric.GAUGE_COLLECTION_TIME, () -> { ImmutableList.Builder<MeasurementBundle> bundlesToLogBuilder = ImmutableList.builder(); for (GaugeDataCollector collector : gaugeDataCollectors) { Collection<MeasurementBundle> bundles = collector.getGaugeData(); monitoringService.recordBundles(bundles); bundlesToLogBuilder.addAll(bundles); } logValues(bundlesToLogBuilder.build()); }); } GaugeRecorderService( List<GaugeDataCollector> gaugeDataCollectors, MonitoringService monitoringService, LogsBasedMetricService logsBasedMetricService); void record(); }
@Test public void testRecord() { gaugeRecorderService.record(); verify(mockMonitoringService, atLeast(1)).recordBundles(measurementBundlesListCaptor.capture()); verify(mockWorkspaceServiceImpl).getGaugeData(); verify(mockBillingProjectBufferService).getGaugeData(); final List<Collection<MeasurementBundle>> allRecordedBundles = measurementBundlesListCaptor.getAllValues(); final int expectedSize = mockWorkspaceServiceImpl.getGaugeData().size() + mockBillingProjectBufferService.getGaugeData().size() + standAloneGaugeDataCollector.getGaugeData().size(); final int flatSize = allRecordedBundles.stream().map(Collection::size).mapToInt(Integer::valueOf).sum(); assertThat(flatSize).isEqualTo(expectedSize); final Optional<MeasurementBundle> workspacesBundle = allRecordedBundles.stream() .flatMap(Collection::stream) .filter(b -> b.getMeasurements().containsKey(GaugeMetric.WORKSPACE_COUNT)) .findFirst(); assertThat( workspacesBundle.map(MeasurementBundle::getMeasurements).orElse(Collections.emptyMap())) .hasSize(1); assertThat( workspacesBundle .map(wb -> wb.getMeasurements().get(GaugeMetric.WORKSPACE_COUNT)) .orElse(0)) .isEqualTo(WORKSPACES_COUNT); }
MeasurementBundle { public static Builder builder() { return new Builder(); } private MeasurementBundle(Map<Metric, Number> measurements, Map<MetricLabel, TagValue> tags); Map<Metric, Number> getMeasurements(); Map<TagKey, TagValue> getTags(); Optional<String> getTagValue(MetricLabel metricLabel); static Builder builder(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test(expected = IllegalStateException.class) public void testBuild_unsupportedAttachmentValueThrows() { MeasurementBundle.builder() .addTag(MetricLabel.BUFFER_ENTRY_STATUS, "lost and gone forever") .build(); }
MeasurementBundle { public Optional<String> getTagValue(MetricLabel metricLabel) { return Optional.ofNullable(tags.get(metricLabel)).map(TagValue::asString); } private MeasurementBundle(Map<Metric, Number> measurements, Map<MetricLabel, TagValue> tags); Map<Metric, Number> getMeasurements(); Map<TagKey, TagValue> getTags(); Optional<String> getTagValue(MetricLabel metricLabel); static Builder builder(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testGetTagValue() { final MeasurementBundle measurementBundle = MeasurementBundle.builder() .addMeasurement(GaugeMetric.BILLING_BUFFER_PROJECT_COUNT, 101L) .addTag(MetricLabel.BUFFER_ENTRY_STATUS, BufferEntryStatus.AVAILABLE.toString()) .build(); final Optional<String> labelValue = measurementBundle.getTagValue(MetricLabel.BUFFER_ENTRY_STATUS); assertThat(labelValue.isPresent()).isTrue(); assertThat(labelValue.orElse("wrong")).isEqualTo(BufferEntryStatus.AVAILABLE.toString()); final Optional<String> missingValue = measurementBundle.getTagValue(MetricLabel.METHOD_NAME); assertThat(missingValue.isPresent()).isFalse(); }
StackdriverStatsExporterService { @VisibleForTesting public StackdriverStatsConfiguration makeStackdriverStatsConfiguration() { return StackdriverStatsConfiguration.builder() .setMetricNamePrefix(STACKDRIVER_CUSTOM_METRICS_PREFIX) .setProjectId(getProjectId()) .setMonitoredResource(getMonitoringMonitoredResource()) .build(); } StackdriverStatsExporterService( Provider<WorkbenchConfig> workbenchConfigProvider, ModulesService modulesService); void createAndRegister(); @VisibleForTesting StackdriverStatsConfiguration makeStackdriverStatsConfiguration(); com.google.cloud.MonitoredResource getLoggingMonitoredResource(); static final String PROJECT_ID_LABEL; static final String LOCATION_LABEL; static final String NAMESPACE_LABEL; static final String NODE_ID_LABEL; static final String UNKNOWN_INSTANCE_PREFIX; static final Set<String> MONITORED_RESOURCE_LABELS; }
@Test public void testMakeMonitoredResource_noInstanceIdAvailable() { doThrow(ModulesException.class).when(mockModulesService).getCurrentInstanceId(); final MonitoredResource monitoredResource = exporterService.makeStackdriverStatsConfiguration().getMonitoredResource(); assertThat(monitoredResource.getLabelsMap().get("node_id")).isNotEmpty(); }
RuntimeController implements RuntimeApiDelegate { @Override @AuthorityRequired(Authority.SECURITY_ADMIN) public ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req) { if (billingProjectId == null) { throw new BadRequestException("Must specify billing project"); } List<LeonardoListRuntimeResponse> runtimesToDelete = filterByRuntimesInList( leonardoNotebooksClient.listRuntimesByProjectAsService(billingProjectId).stream(), req.getRuntimesToDelete()) .collect(Collectors.toList()); runtimesToDelete.forEach( runtime -> leonardoNotebooksClient.deleteRuntimeAsService( runtime.getGoogleProject(), runtime.getRuntimeName())); List<LeonardoListRuntimeResponse> runtimesInProjectAffected = filterByRuntimesInList( leonardoNotebooksClient.listRuntimesByProjectAsService(billingProjectId).stream(), req.getRuntimesToDelete()) .collect(Collectors.toList()); List<LeonardoRuntimeStatus> acceptableStates = ImmutableList.of(LeonardoRuntimeStatus.DELETING, LeonardoRuntimeStatus.ERROR); runtimesInProjectAffected.stream() .filter(runtime -> !acceptableStates.contains(runtime.getStatus())) .forEach( clusterInBadState -> log.log( Level.SEVERE, String.format( "Runtime %s/%s is not in a deleting state", clusterInBadState.getGoogleProject(), clusterInBadState.getRuntimeName()))); leonardoRuntimeAuditor.fireDeleteRuntimesInProject( billingProjectId, runtimesToDelete.stream() .map(LeonardoListRuntimeResponse::getRuntimeName) .collect(Collectors.toList())); return ResponseEntity.ok( runtimesInProjectAffected.stream() .map(leonardoMapper::toApiListRuntimeResponse) .collect(Collectors.toList())); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void testDeleteRuntimesInProject() throws ApiException { List<LeonardoListRuntimeResponse> listRuntimeResponseList = ImmutableList.of(testLeoListRuntimeResponse); when(serviceRuntimesApi.listRuntimesByProject(BILLING_PROJECT_ID, null, false)) .thenReturn(listRuntimeResponseList); runtimeController.deleteRuntimesInProject( BILLING_PROJECT_ID, new ListRuntimeDeleteRequest() .runtimesToDelete(ImmutableList.of(testLeoRuntime.getRuntimeName()))); verify(serviceRuntimesApi) .deleteRuntime(BILLING_PROJECT_ID, testLeoRuntime.getRuntimeName(), false); verify(mockLeonardoRuntimeAuditor) .fireDeleteRuntimesInProject( BILLING_PROJECT_ID, listRuntimeResponseList.stream() .map(LeonardoListRuntimeResponse::getRuntimeName) .collect(Collectors.toList())); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); leonardoNotebooksClient.deleteRuntime(workspaceNamespace, userProvider.get().getRuntimeName()); return ResponseEntity.ok(new EmptyResponse()); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void testDeleteRuntime() throws ApiException { runtimeController.deleteRuntime(BILLING_PROJECT_ID); verify(userRuntimesApi).deleteRuntime(BILLING_PROJECT_ID, getRuntimeName(), false); }
S3Utilities { public URL getUrl(Consumer<GetUrlRequest.Builder> getUrlRequest) { return getUrl(GetUrlRequest.builder().applyMutation(getUrlRequest).build()); } private S3Utilities(Builder builder); static Builder builder(); URL getUrl(Consumer<GetUrlRequest.Builder> getUrlRequest); URL getUrl(GetUrlRequest getUrlRequest); }
@Test public void test_utilities_createdThroughS3Client() throws MalformedURLException { assertThat(defaultUtilities.getUrl(requestWithoutSpaces()) .toExternalForm()) .isEqualTo("https: assertThat(defaultUtilities.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https: } @Test public void testAsync() throws MalformedURLException { assertThat(utilitiesFromAsyncClient.getUrl(requestWithoutSpaces()) .toExternalForm()) .isEqualTo("https: assertThat(utilitiesFromAsyncClient.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https: }
ChecksumValidatingPublisher implements SdkPublisher<ByteBuffer> { @Override public void subscribe(Subscriber<? super ByteBuffer> s) { if (contentLength > 0) { publisher.subscribe(new ChecksumValidatingSubscriber(s, sdkChecksum, contentLength)); } else { publisher.subscribe(new ChecksumSkippingSubscriber(s)); } } ChecksumValidatingPublisher(Publisher<ByteBuffer> publisher, SdkChecksum sdkChecksum, long contentLength); @Override void subscribe(Subscriber<? super ByteBuffer> s); }
@Test public void testSinglePacket() { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, TEST_DATA_SIZE)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE); p.subscribe(s); driver.doOnNext(ByteBuffer.wrap(testData)); driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } @Test public void testTwoPackets() { for (int i = 1; i < TEST_DATA_SIZE + CHECKSUM_SIZE - 1; i++) { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, TEST_DATA_SIZE)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE); p.subscribe(s); driver.doOnNext(ByteBuffer.wrap(testData, 0, i)); driver.doOnNext(ByteBuffer.wrap(testData, i, TEST_DATA_SIZE + CHECKSUM_SIZE - i)); driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } } @Test public void testTinyPackets() { for (int packetSize = 1; packetSize < CHECKSUM_SIZE; packetSize++) { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, TEST_DATA_SIZE)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE); p.subscribe(s); int currOffset = 0; while (currOffset < TEST_DATA_SIZE + CHECKSUM_SIZE) { final int toSend = Math.min(packetSize, TEST_DATA_SIZE + CHECKSUM_SIZE - currOffset); driver.doOnNext(ByteBuffer.wrap(testData, currOffset, toSend)); currOffset += toSend; } driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } } @Test public void testUnknownLength() { final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(testData, 0, TEST_DATA_SIZE)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), 0); p.subscribe(s); byte[] randomChecksumData = new byte[testData.length]; System.arraycopy(testData, 0, randomChecksumData, 0, TEST_DATA_SIZE); for (int i = TEST_DATA_SIZE; i < randomChecksumData.length; i++) { randomChecksumData[i] = (byte)((testData[i] + 1) & 0x7f); } driver.doOnNext(ByteBuffer.wrap(randomChecksumData)); driver.doOnComplete(); assertTrue(s.hasCompleted()); assertFalse(s.isOnErrorCalled()); } @Test public void checksumValidationFailure_throwsSdkClientException_NotNPE() { final byte[] incorrectData = new byte[0]; final TestPublisher driver = new TestPublisher(); final TestSubscriber s = new TestSubscriber(Arrays.copyOfRange(incorrectData, 0, TEST_DATA_SIZE)); final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE); p.subscribe(s); driver.doOnNext(ByteBuffer.wrap(incorrectData)); driver.doOnComplete(); assertTrue(s.isOnErrorCalled()); assertFalse(s.hasCompleted()); }
ChecksumsEnabledValidator { public static boolean getObjectChecksumEnabledPerRequest(SdkRequest request, ExecutionAttributes executionAttributes) { return request instanceof GetObjectRequest && checksumEnabledPerConfig(executionAttributes); } private ChecksumsEnabledValidator(); static boolean getObjectChecksumEnabledPerRequest(SdkRequest request, ExecutionAttributes executionAttributes); static boolean getObjectChecksumEnabledPerResponse(SdkRequest request, SdkHttpHeaders responseHeaders); static boolean shouldRecordChecksum(SdkRequest sdkRequest, ClientType expectedClientType, ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest); static boolean responseChecksumIsValid(SdkHttpResponse httpResponse); static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes); static final ExecutionAttribute<SdkChecksum> CHECKSUM; }
@Test public void getObjectChecksumEnabledPerRequest_nonGetObjectRequestFalse() { assertThat(getObjectChecksumEnabledPerRequest(GetObjectAclRequest.builder().build(), new ExecutionAttributes())).isFalse(); } @Test public void getObjectChecksumEnabledPerRequest_defaultReturnTrue() { assertThat(getObjectChecksumEnabledPerRequest(GetObjectRequest.builder().build(), new ExecutionAttributes())).isTrue(); } @Test public void getObjectChecksumEnabledPerRequest_disabledPerConfig() { assertThat(getObjectChecksumEnabledPerRequest(GetObjectRequest.builder().build(), getExecutionAttributesWithChecksumDisabled())).isFalse(); }
ChecksumsEnabledValidator { public static boolean getObjectChecksumEnabledPerResponse(SdkRequest request, SdkHttpHeaders responseHeaders) { return request instanceof GetObjectRequest && checksumEnabledPerResponse(responseHeaders); } private ChecksumsEnabledValidator(); static boolean getObjectChecksumEnabledPerRequest(SdkRequest request, ExecutionAttributes executionAttributes); static boolean getObjectChecksumEnabledPerResponse(SdkRequest request, SdkHttpHeaders responseHeaders); static boolean shouldRecordChecksum(SdkRequest sdkRequest, ClientType expectedClientType, ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest); static boolean responseChecksumIsValid(SdkHttpResponse httpResponse); static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes); static final ExecutionAttribute<SdkChecksum> CHECKSUM; }
@Test public void getObjectChecksumEnabledPerResponse_nonGetObjectRequestFalse() { assertThat(getObjectChecksumEnabledPerResponse(GetObjectAclRequest.builder().build(), getSdkHttpResponseWithChecksumHeader())).isFalse(); } @Test public void getObjectChecksumEnabledPerResponse_responseContainsChecksumHeader_returnTrue() { assertThat(getObjectChecksumEnabledPerResponse(GetObjectRequest.builder().build(), getSdkHttpResponseWithChecksumHeader())).isTrue(); } @Test public void getObjectChecksumEnabledPerResponse_responseNotContainsChecksumHeader_returnFalse() { assertThat(getObjectChecksumEnabledPerResponse(GetObjectRequest.builder().build(), SdkHttpFullResponse.builder().build())).isFalse(); }
PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private PresignedGetObjectRequest(DefaultBuilder builder); static Builder builder(); @Override Builder toBuilder(); }
@Test public void equalsAndHashCode_differentProperty_signedHeaders() { Map<String, List<String>> otherSignedHeaders = new HashMap<>(); otherSignedHeaders.put("fake-key", Collections.unmodifiableList(Arrays.asList("other-one", "other-two"))); PresignedGetObjectRequest request = generateMaximal(); PresignedGetObjectRequest otherRequest = request.toBuilder().signedHeaders(otherSignedHeaders).build(); assertThat(request).isNotEqualTo(otherRequest); assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode()); } @Test public void build_missingProperty_expiration() { assertThatThrownBy(() -> generateMinimal().toBuilder().expiration(null).build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("expiration"); } @Test public void build_missingProperty_httpRequest() { assertThatThrownBy(() -> generateMinimal().toBuilder().httpRequest(null).build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("httpRequest"); } @Test public void equalsAndHashCode_differentProperty_httpRequest() throws URISyntaxException { SdkHttpRequest otherHttpRequest = mock(SdkHttpRequest.class); when(otherHttpRequest.getUri()).thenReturn(FAKE_URL.toURI()); PresignedGetObjectRequest request = generateMaximal(); PresignedGetObjectRequest otherRequest = request.toBuilder().httpRequest(otherHttpRequest).build(); assertThat(request).isNotEqualTo(otherRequest); assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode()); } @Test public void equalsAndHashCode_differentProperty_expiration() { PresignedGetObjectRequest request = generateMaximal(); PresignedGetObjectRequest otherRequest = request.toBuilder().expiration(Instant.MIN).build(); assertThat(request).isNotEqualTo(otherRequest); assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode()); } @Test public void equalsAndHashCode_differentProperty_signedPayload() { SdkBytes otherSignedPayload = SdkBytes.fromString("other-payload", StandardCharsets.UTF_8); PresignedGetObjectRequest request = generateMaximal(); PresignedGetObjectRequest otherRequest = request.toBuilder().signedPayload(otherSignedPayload).build(); assertThat(request).isNotEqualTo(otherRequest); assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode()); }
ChecksumsEnabledValidator { public static boolean shouldRecordChecksum(SdkRequest sdkRequest, ClientType expectedClientType, ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest) { if (!(sdkRequest instanceof PutObjectRequest)) { return false; } ClientType actualClientType = executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE); if (!expectedClientType.equals(actualClientType)) { return false; } if (hasServerSideEncryptionHeader(httpRequest)) { return false; } return checksumEnabledPerConfig(executionAttributes); } private ChecksumsEnabledValidator(); static boolean getObjectChecksumEnabledPerRequest(SdkRequest request, ExecutionAttributes executionAttributes); static boolean getObjectChecksumEnabledPerResponse(SdkRequest request, SdkHttpHeaders responseHeaders); static boolean shouldRecordChecksum(SdkRequest sdkRequest, ClientType expectedClientType, ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest); static boolean responseChecksumIsValid(SdkHttpResponse httpResponse); static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes); static final ExecutionAttribute<SdkChecksum> CHECKSUM; }
@Test public void putObjectChecksumEnabled_defaultShouldRecord() { assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(), ClientType.SYNC, getSyncExecutionAttributes(), emptyHttpRequest().build())).isTrue(); } @Test public void putObjectChecksumEnabled_nonPutObjectRequest_false() { assertThat(shouldRecordChecksum(PutBucketAclRequest.builder().build(), ClientType.SYNC, getSyncExecutionAttributes(), emptyHttpRequest().build())).isFalse(); } @Test public void putObjectChecksumEnabled_disabledFromConfig_false() { ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled(); assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(), ClientType.SYNC, executionAttributes, emptyHttpRequest().build())).isFalse(); } @Test public void putObjectChecksumEnabled_wrongClientType_false() { ExecutionAttributes executionAttributes = getSyncExecutionAttributes(); assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(), ClientType.ASYNC, executionAttributes, emptyHttpRequest().build())).isFalse(); } @Test public void putObjectChecksumEnabled_serverSideCustomerEncryption_false() { ExecutionAttributes executionAttributes = getSyncExecutionAttributes(); SdkHttpRequest response = emptyHttpRequest().putHeader(SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER, "test") .build(); assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(), ClientType.SYNC, executionAttributes, response)).isFalse(); } @Test public void putObjectChecksumEnabled_serverSideEncryption_false() { ExecutionAttributes executionAttributes = getSyncExecutionAttributes(); SdkHttpRequest response = emptyHttpRequest().putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString()) .build(); assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(), ClientType.SYNC, executionAttributes, response)).isFalse(); }
ChecksumsEnabledValidator { public static boolean responseChecksumIsValid(SdkHttpResponse httpResponse) { return !hasServerSideEncryptionHeader(httpResponse); } private ChecksumsEnabledValidator(); static boolean getObjectChecksumEnabledPerRequest(SdkRequest request, ExecutionAttributes executionAttributes); static boolean getObjectChecksumEnabledPerResponse(SdkRequest request, SdkHttpHeaders responseHeaders); static boolean shouldRecordChecksum(SdkRequest sdkRequest, ClientType expectedClientType, ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest); static boolean responseChecksumIsValid(SdkHttpResponse httpResponse); static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes); static final ExecutionAttribute<SdkChecksum> CHECKSUM; }
@Test public void responseChecksumIsValid_defaultTrue() { assertThat(responseChecksumIsValid(SdkHttpResponse.builder().build())).isTrue(); } @Test public void responseChecksumIsValid_serverSideCustomerEncryption_false() { SdkHttpResponse response = SdkHttpResponse.builder() .putHeader(SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER, "test") .build(); assertThat(responseChecksumIsValid(response)).isFalse(); } @Test public void responseChecksumIsValid_serverSideEncryption_false() { SdkHttpResponse response = SdkHttpResponse.builder() .putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString()) .build(); assertThat(responseChecksumIsValid(response)).isFalse(); }
CreateMultipartUploadRequestInterceptor implements ExecutionInterceptor { @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof CreateMultipartUploadRequest) { return Optional.of(RequestBody.fromInputStream(new ByteArrayInputStream(new byte[0]), 0)); } return context.requestBody(); } @Override Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }
@Test public void createMultipartRequest_shouldModifyHttpContent() { Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(CreateMultipartUploadRequest.builder().build()); Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest, new ExecutionAttributes()); assertThat(modifyHttpRequest.requestBody().get()).isNotEqualTo(requestBody.get()); } @Test public void nonCreateMultipartRequest_shouldNotModifyHttpContent() { Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build()); Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest, new ExecutionAttributes()); assertThat(modifyHttpRequest.requestBody().get()).isEqualTo(requestBody.get()); }
GeneratePreSignUrlInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); SdkRequest originalRequest = context.request(); if (originalRequest instanceof CopySnapshotRequest) { CopySnapshotRequest originalCopySnapshotRequest = (CopySnapshotRequest) originalRequest; if (originalCopySnapshotRequest.presignedUrl() != null) { return request; } String serviceName = "ec2"; String sourceRegion = originalCopySnapshotRequest.sourceRegion(); String sourceSnapshotId = originalCopySnapshotRequest .sourceSnapshotId(); String destinationRegion = originalCopySnapshotRequest.destinationRegion(); if (destinationRegion == null) { destinationRegion = AwsHostNameUtils.parseSigningRegion(request.host(), serviceName) .orElseThrow(() -> new IllegalArgumentException("Could not determine region for " + request.host())) .id(); } URI endPointSource = createEndpoint(sourceRegion, serviceName); SdkHttpFullRequest requestForPresigning = generateRequestForPresigning( sourceSnapshotId, sourceRegion, destinationRegion) .toBuilder() .uri(endPointSource) .method(SdkHttpMethod.GET) .build(); Aws4Signer signer = Aws4Signer.create(); Aws4PresignerParams signingParams = getPresignerParams(executionAttributes, sourceRegion, serviceName); SdkHttpFullRequest presignedRequest = signer.presign(requestForPresigning, signingParams); return request.toBuilder() .putRawQueryParameter("DestinationRegion", destinationRegion) .putRawQueryParameter("PresignedUrl", presignedRequest.getUri().toString()) .build(); } return request; } GeneratePreSignUrlInterceptor(); @SdkTestInternalApi GeneratePreSignUrlInterceptor(Clock testClock); @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }
@Test public void copySnapshotRequest_httpsProtocolAddedToEndpoint() { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .uri(URI.create("https: .method(SdkHttpMethod.POST) .build(); CopySnapshotRequest ec2Request = CopySnapshotRequest.builder() .sourceRegion("us-west-2") .destinationRegion("us-east-2") .build(); when(mockContext.httpRequest()).thenReturn(request); when(mockContext.request()).thenReturn(ec2Request); ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AWS_CREDENTIALS, AwsBasicCredentials.create("foo", "bar")); SdkHttpRequest modifiedRequest = INTERCEPTOR.modifyHttpRequest(mockContext, attrs); String presignedUrl = modifiedRequest.rawQueryParameters().get("PresignedUrl").get(0); assertThat(presignedUrl).startsWith("https: } @Test public void copySnapshotRequest_generatesCorrectPresignedUrl() { String expectedPresignedUrl = "https: "&Version=2016-11-15" + "&DestinationRegion=us-east-1" + "&SourceRegion=us-west-2" + "&SourceSnapshotId=SNAPSHOT_ID" + "&X-Amz-Algorithm=AWS4-HMAC-SHA256" + "&X-Amz-Date=20200107T205609Z" + "&X-Amz-SignedHeaders=host" + "&X-Amz-Expires=604800" + "&X-Amz-Credential=akid%2F20200107%2Fus-west-2%2Fec2%2Faws4_request" + "&X-Amz-Signature=c1f5e34834292a86ff2b46b5e97cebaf2967b09641b4e2e60a382a37d137a03b"; ZoneId utcZone = ZoneId.of("UTC").normalized(); Instant signingInstant = ZonedDateTime.of(2020, 1, 7, 20, 56, 9, 0, utcZone).toInstant(); Clock signingClock = Clock.fixed(signingInstant, utcZone); GeneratePreSignUrlInterceptor interceptor = new GeneratePreSignUrlInterceptor(signingClock); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .uri(URI.create("https: .method(SdkHttpMethod.POST) .build(); CopySnapshotRequest ec2Request = CopySnapshotRequest.builder() .sourceRegion("us-west-2") .destinationRegion("us-east-1") .sourceSnapshotId("SNAPSHOT_ID") .build(); when(mockContext.httpRequest()).thenReturn(request); when(mockContext.request()).thenReturn(ec2Request); ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")); SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(mockContext, attrs); String generatedPresignedUrl = modifiedRequest.rawQueryParameters().get("PresignedUrl").get(0); assertThat(generatedPresignedUrl).isEqualTo(expectedPresignedUrl); }
S3ControlArnConverter implements ArnConverter<S3Resource> { @Override public S3Resource convertArn(Arn arn) { S3ControlResourceType s3ResourceType; try { s3ResourceType = arn.resource().resourceType().map(S3ControlResourceType::fromValue) .orElseThrow(() -> new IllegalArgumentException("resource type cannot be null")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown ARN type '" + arn.resource().resourceType() + "'"); } switch (s3ResourceType) { case OUTPOST: return parseS3OutpostArn(arn); default: throw new IllegalArgumentException("Unknown ARN type '" + arn.resource().resourceType() + "'"); } } private S3ControlArnConverter(); static S3ControlArnConverter getInstance(); @Override S3Resource convertArn(Arn arn); }
@Test public void parseArn_outpostBucketArn() { S3Resource resource = ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost/1234/bucket/myBucket") .build()); assertThat(resource, instanceOf(S3ControlBucketResource.class)); S3ControlBucketResource bucketResource = (S3ControlBucketResource) resource; assertThat(bucketResource.bucketName(), is("myBucket")); assertThat(bucketResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class)); S3OutpostResource outpostResource = (S3OutpostResource) bucketResource.parentS3Resource().get(); assertThat(outpostResource.accountId(), is(Optional.of("123456789012"))); assertThat(outpostResource.partition(), is(Optional.of("aws"))); assertThat(outpostResource.region(), is(Optional.of("us-east-1"))); assertThat(outpostResource.type(), is(S3ControlResourceType.OUTPOST.toString())); assertThat(outpostResource.outpostId(), is("1234")); } @Test public void parseArn_outpostAccessPointArn() { S3Resource resource = ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3-outposts") .region("us-east-1") .accountId("123456789012") .resource("outpost/1234/accesspoint/myAccessPoint") .build()); assertThat(resource, instanceOf(S3AccessPointResource.class)); S3AccessPointResource accessPointResource = (S3AccessPointResource) resource; assertThat(accessPointResource.accessPointName(), is("myAccessPoint")); assertThat(accessPointResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class)); S3OutpostResource outpostResource = (S3OutpostResource) accessPointResource.parentS3Resource().get(); assertThat(outpostResource.outpostId(), is("1234")); assertThat(outpostResource.accountId(), is(Optional.of("123456789012"))); assertThat(outpostResource.partition(), is(Optional.of("aws"))); assertThat(outpostResource.region(), is(Optional.of("us-east-1"))); } @Test public void parseArn_invalidOutpostAccessPointMissingAccessPointName_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:op-01234567890123456:accesspoint") .build()); } @Test public void parseArn_invalidOutpostAccessPointMissingOutpostId_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Invalid format"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost/myaccesspoint") .build()); } @Test public void parseArn_malformedOutpostArn_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Unknown outpost ARN"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("outpost:1:accesspoin1:1") .build()); } @Test public void parseArn_unknownResource() { exception.expect(IllegalArgumentException.class); exception.expectMessage("ARN type"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("unknown:foobar") .build()); } @Test public void parseArn_unknownType_throwsCorrectException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("invalidType"); ARN_PARSER.convertArn(Arn.builder() .partition("aws") .service("s3") .region("us-east-1") .accountId("123456789012") .resource("invalidType:something") .build()); }
ArnHandler { public SdkHttpRequest resolveHostForArn(SdkHttpRequest request, S3ControlConfiguration configuration, Arn arn, ExecutionAttributes executionAttributes) { S3Resource s3Resource = S3ControlArnConverter.getInstance().convertArn(arn); String clientRegion = executionAttributes.getAttribute(SIGNING_REGION).id(); String originalArnRegion = s3Resource.region().orElseThrow(() -> new IllegalArgumentException("Region is missing")); boolean isFipsEnabled = isFipsEnabledInClientConfig(configuration) || isFipsRegionProvided(clientRegion, originalArnRegion, useArnRegion(configuration)); String arnRegion = removeFipsIfNeeded(originalArnRegion); validateConfiguration(executionAttributes, arn.partition(), arnRegion, configuration); executionAttributes.putAttribute(SIGNING_REGION, Region.of(arnRegion)); S3Resource parentS3Resource = s3Resource.parentS3Resource().orElse(null); if (parentS3Resource instanceof S3OutpostResource) { return handleOutpostArn(request, (S3OutpostResource) parentS3Resource, isFipsEnabled, configuration, executionAttributes); } else { throw new IllegalArgumentException("Parent resource invalid, outpost resource expected."); } } private ArnHandler(); static ArnHandler getInstance(); SdkHttpRequest resolveHostForArn(SdkHttpRequest request, S3ControlConfiguration configuration, Arn arn, ExecutionAttributes executionAttributes); }
@Test public void outpostBucketArn_shouldResolveHost() { Arn arn = Arn.fromString("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"); SdkHttpRequest modifiedRequest = arnHandler.resolveHostForArn(request, configuration, arn, executionAttributes); assertThat(modifiedRequest.host(), is("s3-outposts.us-west-2.amazonaws.com")); assertThat(executionAttributes.getAttribute(SERVICE_SIGNING_NAME), is("s3-outposts")); assertThat(modifiedRequest.headers().get("x-amz-outpost-id").get(0), is("op-01234567890123456")); assertThat(modifiedRequest.headers().get("x-amz-account-id").get(0), is(ACCOUNT_ID)); } @Test public void outpostAccessPointArn_shouldResolveHost() { Arn arn = Arn.fromString("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"); SdkHttpRequest modifiedRequest = arnHandler.resolveHostForArn(request, configuration, arn, executionAttributes); assertThat(modifiedRequest.host(), is("s3-outposts.us-west-2.amazonaws.com")); assertThat(executionAttributes.getAttribute(SERVICE_SIGNING_NAME), is("s3-outposts")); assertThat(modifiedRequest.headers().get("x-amz-outpost-id").get(0), is("op-01234567890123456")); assertThat(modifiedRequest.headers().get("x-amz-account-id").get(0), is(ACCOUNT_ID)); } @Test public void outpostArnWithFipsEnabled_shouldThrowException() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("FIPS"); Arn arn = Arn.fromString("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"); arnHandler.resolveHostForArn(request, enableFips(), arn, executionAttributes); } @Test public void outpostArnWithDualstackEnabled_shouldThrowException() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Dualstack"); Arn arn = Arn.fromString("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:bucket:mybucket"); arnHandler.resolveHostForArn(request, enableDualstack(), arn, executionAttributes); }
CreateMultipartUploadRequestInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof CreateMultipartUploadRequest) { SdkHttpRequest.Builder builder = context.httpRequest() .toBuilder() .putHeader(CONTENT_LENGTH, String.valueOf(0)); if (!context.httpRequest().firstMatchingHeader(CONTENT_TYPE).isPresent()) { builder.putHeader(CONTENT_TYPE, "binary/octet-stream"); } return builder.build(); } return context.httpRequest(); } @Override Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }
@Test public void createMultipartRequest_shouldModifyHttpRequest() { Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(CreateMultipartUploadRequest.builder().build()); SdkHttpRequest httpRequest = interceptor.modifyHttpRequest(modifyHttpRequest, new ExecutionAttributes()); assertThat(httpRequest).isNotEqualTo(modifyHttpRequest.httpRequest()); assertThat(httpRequest.headers()).containsEntry(CONTENT_LENGTH, Collections.singletonList("0")); assertThat(httpRequest.headers()).containsEntry(CONTENT_TYPE, Collections.singletonList("binary/octet-stream")); } @Test public void createMultipartRequest_contentTypePresent_shouldNotModifyContentType() { String overrideContentType = "application/json"; Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(CreateMultipartUploadRequest.builder().build(), sdkHttpFullRequest().toBuilder() .putHeader(CONTENT_TYPE, overrideContentType).build()); SdkHttpRequest httpRequest = interceptor.modifyHttpRequest(modifyHttpRequest, new ExecutionAttributes()); assertThat(httpRequest).isNotEqualTo(modifyHttpRequest.httpRequest()); assertThat(httpRequest.headers()).containsEntry(CONTENT_LENGTH, Collections.singletonList("0")); assertThat(httpRequest.headers()).containsEntry(CONTENT_TYPE, Collections.singletonList(overrideContentType)); } @Test public void nonCreateMultipartRequest_shouldNotModifyHttpRequest() { Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(GetObjectAclRequest.builder().build()); SdkHttpRequest httpRequest = interceptor.modifyHttpRequest(modifyHttpRequest, new ExecutionAttributes()); assertThat(httpRequest).isEqualTo(modifyHttpRequest.httpRequest()); }
EndpointAddressInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); S3ControlConfiguration config = (S3ControlConfiguration) executionAttributes.getAttribute( AwsSignerExecutionAttribute.SERVICE_CONFIG); S3ArnableField arnableField = executionAttributes.getAttribute(S3_ARNABLE_FIELD); if (arnableField != null && arnableField.arn() != null) { return arnHandler.resolveHostForArn(request, config, arnableField.arn(), executionAttributes); } String host; if (isNonArnOutpostRequest(context.request())) { host = resolveHostForNonArnOutpostRequest(config, executionAttributes); } else { host = resolveHost(request, config); } return request.toBuilder() .host(host) .build(); } EndpointAddressInterceptor(); @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }
@Test public void modifyHttpRequest_ResolvesCorrectHost_StandardSettings() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request), new ExecutionAttributes()); assertThat(modified.host()).isEqualTo("s3-control.us-east-1.amazonaws.com"); } @Test public void modifyHttpRequest_ResolvesCorrectHost_Dualstack() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().dualstackEnabled(true).build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request), executionAttributes); assertThat(modified.host()).isEqualTo("s3-control.dualstack.us-east-1.amazonaws.com"); } @Test public void modifyHttpRequest_ResolvesCorrectHost_Fips() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().fipsModeEnabled(true).build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request), executionAttributes); assertThat(modified.host()).isEqualTo("s3-control-fips.us-east-1.amazonaws.com"); } @Test public void createBucketRequestWithOutpostId_shouldRedirect() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); CreateBucketRequest createBucketRequest = CreateBucketRequest.builder().outpostId("1234").build(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); executionAttributes.putAttribute(SIGNING_REGION, Region.US_EAST_1); SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request).request(createBucketRequest), executionAttributes); assertThat(executionAttributes.getAttribute(SERVICE_SIGNING_NAME)).isEqualTo("s3-outposts"); assertThat(modified.host()).isEqualTo("s3-outposts.us-east-1.amazonaws.com"); } @Test public void listRegionalBucketsRequestsWithOutpostId_shouldRedirect() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); ListRegionalBucketsRequest sdkRequest = ListRegionalBucketsRequest.builder().outpostId("1234").build(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); executionAttributes.putAttribute(SIGNING_REGION, Region.US_EAST_1); executionAttributes.putAttribute(SERVICE_SIGNING_NAME, "s3"); SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request).request(sdkRequest), executionAttributes); assertThat(executionAttributes.getAttribute(SERVICE_SIGNING_NAME)).isEqualTo("s3-outposts"); assertThat(modified.host()).isEqualTo("s3-outposts.us-east-1.amazonaws.com"); } @Test public void listRegionalBucketsRequestsWithoutOutpostId_shouldNotRedirect() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); ListRegionalBucketsRequest sdkRequest = ListRegionalBucketsRequest.builder().build(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder() .dualstackEnabled(true) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); executionAttributes.putAttribute(SIGNING_REGION, Region.US_EAST_1); executionAttributes.putAttribute(SERVICE_SIGNING_NAME, "s3"); SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request).request(sdkRequest), executionAttributes); assertThat(executionAttributes.getAttribute(SERVICE_SIGNING_NAME)).isEqualTo("s3"); assertThat(modified.host()).isEqualTo("s3-control.dualstack.us-east-1.amazonaws.com"); } @Test public void createBucketRequestsWithoutOutpostId_shouldNotRedirect() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); ListRegionalBucketsRequest sdkRequest = ListRegionalBucketsRequest.builder() .build(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder() .fipsModeEnabled(true) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); executionAttributes.putAttribute(SIGNING_REGION, Region.US_EAST_1); executionAttributes.putAttribute(SERVICE_SIGNING_NAME, "s3"); SdkHttpRequest modified = interceptor.modifyHttpRequest(new Context(request).request(sdkRequest), executionAttributes); assertThat(executionAttributes.getAttribute(SERVICE_SIGNING_NAME)).isEqualTo("s3"); assertThat(modified.host()).isEqualTo("s3-control-fips.us-east-1.amazonaws.com"); } @Test public void listRegionalBucketsRequestWithOutpostId_fipsEnabled_shouldThrowException() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); ListRegionalBucketsRequest sdkRequest = ListRegionalBucketsRequest.builder() .outpostId("123") .build(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().fipsModeEnabled(true).build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); executionAttributes.putAttribute(SIGNING_REGION, Region.US_EAST_1); executionAttributes.putAttribute(SERVICE_SIGNING_NAME, "s3"); assertThatThrownBy(() -> interceptor.modifyHttpRequest(new Context(request).request(sdkRequest), executionAttributes)).hasMessageContaining("FIPS endpoints are " + "not supported"); } @Test public void listRegionalBucketsRequestWithOutpostId_fipsDualsackEnabled_shouldThrowException() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); ListRegionalBucketsRequest sdkRequest = ListRegionalBucketsRequest.builder() .outpostId("123") .build(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder().dualstackEnabled(true).build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); executionAttributes.putAttribute(SIGNING_REGION, Region.US_EAST_1); executionAttributes.putAttribute(SERVICE_SIGNING_NAME, "s3"); assertThatThrownBy(() -> interceptor.modifyHttpRequest(new Context(request).request(sdkRequest), executionAttributes)).hasMessageContaining("Dualstack endpoints are " + "not supported"); } @Test(expected = SdkClientException.class) public void modifyHttpRequest_ThrowsException_FipsAndDualstack() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder() .fipsModeEnabled(true) .dualstackEnabled(true) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); interceptor.modifyHttpRequest(new Context(request), executionAttributes); } @Test(expected = SdkClientException.class) public void modifyHttpRequest_ThrowsException_NonStandardEndpoint() { EndpointAddressInterceptor interceptor = new EndpointAddressInterceptor(); S3ControlConfiguration controlConfiguration = S3ControlConfiguration.builder() .dualstackEnabled(true) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, controlConfiguration); interceptor.modifyHttpRequest(new Context(request.toBuilder().host("some-garbage").build()), executionAttributes); }
PayloadSigningInterceptor implements ExecutionInterceptor { public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true); if (!context.requestBody().isPresent() && context.httpRequest().method().equals(SdkHttpMethod.POST)) { return Optional.of(RequestBody.fromBytes(new byte[0])); } return context.requestBody(); } Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }
@Test public void modifyHttpContent_AddsExecutionAttributeAndPayload() { PayloadSigningInterceptor interceptor = new PayloadSigningInterceptor(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); Optional<RequestBody> modified = interceptor.modifyHttpContent(new Context(request, null), executionAttributes); assertThat(modified.isPresent()).isTrue(); assertThat(modified.get().contentLength()).isEqualTo(0); assertThat(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING)).isTrue(); } @Test public void modifyHttpContent_DoesNotReplaceBody() { PayloadSigningInterceptor interceptor = new PayloadSigningInterceptor(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); Optional<RequestBody> modified = interceptor.modifyHttpContent(new Context(request, RequestBody.fromString("hello")), executionAttributes); assertThat(modified.isPresent()).isTrue(); assertThat(modified.get().contentLength()).isEqualTo(5); assertThat(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING)).isTrue(); }
AcceptJsonInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest httpRequest = context.httpRequest(); if (!httpRequest.headers().containsKey("Accept")) { return httpRequest .toBuilder() .putHeader("Accept", "application/json") .build(); } return httpRequest; } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); }
@Test public void doesNotClobberExistingValue() { SdkHttpRequest request = newRequest("some-value"); Mockito.when(ctx.httpRequest()).thenReturn(request); request = interceptor.modifyHttpRequest(ctx, new ExecutionAttributes()); assertThat(request.headers().get("Accept")).containsOnly("some-value"); } @Test public void addsStandardAcceptHeaderIfMissing() { SdkHttpRequest request = newRequest(null); Mockito.when(ctx.httpRequest()).thenReturn(request); request = interceptor.modifyHttpRequest(ctx, new ExecutionAttributes()); assertThat(request.headers().get("Accept")).containsOnly("application/json"); }
RegionValidationUtil { public static boolean validRegion(String region, String regex) { return matchesRegex(region, regex) || matchesRegexFipsSuffix(region, regex) || matchesRegexFipsPrefix(region, regex) || isGlobal(region); } private RegionValidationUtil(); static boolean validRegion(String region, String regex); }
@Test public void usEast1_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-east-1", AWS_PARTITION_REGEX)); } @Test public void usWest2Fips_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-west-2-fips", AWS_PARTITION_REGEX)); } @Test public void fipsUsWest2_AwsPartition_IsNotValidRegion() { assertTrue(RegionValidationUtil.validRegion("fips-us-west-2", AWS_PARTITION_REGEX)); } @Test public void fips_AwsPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("fips", AWS_PARTITION_REGEX)); } @Test public void prodFips_AwsPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("ProdFips", AWS_PARTITION_REGEX)); } @Test public void cnNorth1_AwsCnPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("cn-north-1", AWS_PARTITION_REGEX)); } @Test public void cnNorth1_AwsCnPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("cn-north-1", AWS_CN_PARTITION_REGEX)); } @Test public void usEast1_AwsCnPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("us-east-1", AWS_CN_PARTITION_REGEX)); } @Test public void usGovWest1_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-gov-west-1", AWS_GOV_PARTITION_REGEX)); } @Test public void usGovWest1Fips_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("us-gov-west-1-fips", AWS_GOV_PARTITION_REGEX)); } @Test public void fipsUsGovWest1_AwsGovPartition_IsNotValidRegion() { assertTrue(RegionValidationUtil.validRegion("fips-us-gov-west-1", AWS_GOV_PARTITION_REGEX)); } @Test public void fips_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("fips", AWS_GOV_PARTITION_REGEX)); } @Test public void prodFips_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("ProdFips", AWS_GOV_PARTITION_REGEX)); } @Test public void cnNorth1_AwsGovPartition_IsNotValidRegion() { assertFalse(RegionValidationUtil.validRegion("cn-north-1", AWS_GOV_PARTITION_REGEX)); } @Test public void awsGlobal_AwsPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-global", AWS_PARTITION_REGEX)); } @Test public void awsGovGlobal_AwsGovPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-us-gov-global", AWS_GOV_PARTITION_REGEX)); } @Test public void awsCnGlobal_AwsCnPartition_IsValidRegion() { assertTrue(RegionValidationUtil.validRegion("aws-cn-global", AWS_CN_PARTITION_REGEX)); }
EnhancedType { public Class<T> rawClass() { Validate.isTrue(!isWildcard, "A wildcard type is not expected here."); return rawClass; } protected EnhancedType(); private EnhancedType(Type type); private EnhancedType(Class<?> rawClass, List<EnhancedType<?>> rawClassParameters, TableSchema<T> tableSchema); static EnhancedType<T> of(Class<T> type); static EnhancedType<?> of(Type type); static EnhancedType<Optional<T>> optionalOf(Class<T> valueType); static EnhancedType<List<T>> listOf(Class<T> valueType); static EnhancedType<List<T>> listOf(EnhancedType<T> valueType); static EnhancedType<Set<T>> setOf(Class<T> valueType); static EnhancedType<Set<T>> setOf(EnhancedType<T> valueType); static EnhancedType<SortedSet<T>> sortedSetOf(Class<T> valueType); static EnhancedType<SortedSet<T>> sortedSetOf(EnhancedType<T> valueType); static EnhancedType<Deque<T>> dequeOf(Class<T> valueType); static EnhancedType<Deque<T>> dequeOf(EnhancedType<T> valueType); static EnhancedType<NavigableSet<T>> navigableSetOf(Class<T> valueType); static EnhancedType<NavigableSet<T>> navigableSetOf(EnhancedType<T> valueType); static EnhancedType<Collection<T>> collectionOf(Class<T> valueType); static EnhancedType<Collection<T>> collectionOf(EnhancedType<T> valueType); static EnhancedType<Map<T, U>> mapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<Map<T, U>> mapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<SortedMap<T, U>> sortedMapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<SortedMap<T, U>> sortedMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<ConcurrentMap<T, U>> concurrentMapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<ConcurrentMap<T, U>> concurrentMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<NavigableMap<T, U>> navigableMapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<NavigableMap<T, U>> navigableMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<T> documentOf(Class<T> documentClass, TableSchema<T> documentTableSchema); boolean isWildcard(); Class<T> rawClass(); Optional<TableSchema<T>> tableSchema(); List<EnhancedType<?>> rawClassParameters(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void customTypesWork() { EnhancedType<EnhancedTypeTest> enhancedType = new EnhancedType<EnhancedTypeTest>(){}; assertThat(enhancedType.rawClass()).isEqualTo(EnhancedTypeTest.class); } @Test public void nonStaticInnerTypesWork() { EnhancedType<InnerType> enhancedType = new EnhancedType<InnerType>(){}; assertThat(enhancedType.rawClass()).isEqualTo(InnerType.class); } @Test public void staticInnerTypesWork() { EnhancedType<InnerStaticType> enhancedType = new EnhancedType<InnerStaticType>(){}; assertThat(enhancedType.rawClass()).isEqualTo(InnerStaticType.class); }
EnhancedType { public static <T> EnhancedType<T> of(Class<T> type) { return new EnhancedType<>(type); } protected EnhancedType(); private EnhancedType(Type type); private EnhancedType(Class<?> rawClass, List<EnhancedType<?>> rawClassParameters, TableSchema<T> tableSchema); static EnhancedType<T> of(Class<T> type); static EnhancedType<?> of(Type type); static EnhancedType<Optional<T>> optionalOf(Class<T> valueType); static EnhancedType<List<T>> listOf(Class<T> valueType); static EnhancedType<List<T>> listOf(EnhancedType<T> valueType); static EnhancedType<Set<T>> setOf(Class<T> valueType); static EnhancedType<Set<T>> setOf(EnhancedType<T> valueType); static EnhancedType<SortedSet<T>> sortedSetOf(Class<T> valueType); static EnhancedType<SortedSet<T>> sortedSetOf(EnhancedType<T> valueType); static EnhancedType<Deque<T>> dequeOf(Class<T> valueType); static EnhancedType<Deque<T>> dequeOf(EnhancedType<T> valueType); static EnhancedType<NavigableSet<T>> navigableSetOf(Class<T> valueType); static EnhancedType<NavigableSet<T>> navigableSetOf(EnhancedType<T> valueType); static EnhancedType<Collection<T>> collectionOf(Class<T> valueType); static EnhancedType<Collection<T>> collectionOf(EnhancedType<T> valueType); static EnhancedType<Map<T, U>> mapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<Map<T, U>> mapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<SortedMap<T, U>> sortedMapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<SortedMap<T, U>> sortedMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<ConcurrentMap<T, U>> concurrentMapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<ConcurrentMap<T, U>> concurrentMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<NavigableMap<T, U>> navigableMapOf(Class<T> keyType, Class<U> valueType); static EnhancedType<NavigableMap<T, U>> navigableMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType); static EnhancedType<T> documentOf(Class<T> documentClass, TableSchema<T> documentTableSchema); boolean isWildcard(); Class<T> rawClass(); Optional<TableSchema<T>> tableSchema(); List<EnhancedType<?>> rawClassParameters(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void equalityIsBasedOnInnerEquality() { assertThat(EnhancedType.of(String.class)).isEqualTo(EnhancedType.of(String.class)); assertThat(EnhancedType.of(String.class)).isNotEqualTo(EnhancedType.of(Integer.class)); assertThat(new EnhancedType<Map<String, List<String>>>(){}).isEqualTo(new EnhancedType<Map<String, List<String>>>(){}); assertThat(new EnhancedType<Map<String, List<String>>>(){}).isNotEqualTo(new EnhancedType<Map<String, List<Integer>>>(){}); }
GetItemEnhancedRequest { public Builder toBuilder() { return builder().key(key).consistentRead(consistentRead); } private GetItemEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Boolean consistentRead(); Key key(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { Key key = Key.builder().partitionValue("key").build(); GetItemEnhancedRequest builtObject = GetItemEnhancedRequest.builder() .key(key) .build(); GetItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
EnableChunkedEncodingInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { SdkRequest sdkRequest = context.request(); if (sdkRequest instanceof PutObjectRequest || sdkRequest instanceof UploadPartRequest) { S3Configuration serviceConfiguration = (S3Configuration) executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG); boolean enableChunkedEncoding; if (serviceConfiguration != null) { enableChunkedEncoding = serviceConfiguration.chunkedEncodingEnabled(); } else { enableChunkedEncoding = true; } executionAttributes.putAttributeIfAbsent(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, enableChunkedEncoding); } return sdkRequest; } @Override SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes); }
@Test public void modifyRequest_EnablesChunckedEncoding_ForPutObectRequest() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull(); interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(true); } @Test public void modifyRequest_EnablesChunckedEncoding_ForUploadPartRequest() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull(); interceptor.modifyRequest(context(UploadPartRequest.builder().build()), executionAttributes); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(true); } @Test public void modifyRequest_DoesNotEnableChunckedEncoding_ForGetObjectRequest() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull(); interceptor.modifyRequest(context(GetObjectRequest.builder().build()), executionAttributes); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull(); } @Test public void modifyRequest_DoesNotOverwriteExistingAttributeValue() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes); boolean newValue = !executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING); executionAttributes.putAttribute(ENABLE_CHUNKED_ENCODING, newValue); interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(newValue); } @Test public void modifyRequest_valueOnServiceConfig_TakesPrecedenceOverDefaultEnabled() { S3Configuration config = S3Configuration.builder() .chunkedEncodingEnabled(false) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes() .putAttribute(SERVICE_CONFIG, config); interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(false); } @Test public void modifyRequest_existingValueInExecutionAttributes_TakesPrecedenceOverClientConfig() { boolean configValue = false; S3Configuration config = S3Configuration.builder() .chunkedEncodingEnabled(configValue) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes() .putAttribute(SERVICE_CONFIG, config) .putAttribute(ENABLE_CHUNKED_ENCODING, !configValue); interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes); assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(!configValue); }
BatchWriteItemEnhancedRequest { public Builder toBuilder() { return new Builder().writeBatches(writeBatches); } private BatchWriteItemEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Collection<WriteBatch> writeBatches(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { BatchWriteItemEnhancedRequest builtObject = BatchWriteItemEnhancedRequest.builder().build(); BatchWriteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
PutItemEnhancedRequest { public Builder<T> toBuilder() { return new Builder<T>().item(item).conditionExpression(conditionExpression); } private PutItemEnhancedRequest(Builder<T> builder); static Builder<T> builder(Class<? extends T> itemClass); Builder<T> toBuilder(); T item(); Expression conditionExpression(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class).build(); PutItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
ScanEnhancedRequest { public static Builder builder() { return new Builder(); } private ScanEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Map<String, AttributeValue> exclusiveStartKey(); Integer limit(); Boolean consistentRead(); Expression filterExpression(); List<String> attributesToProject(); List<NestedAttributeName> nestedAttributesToProject(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void test_nestedAttributesNullNestedAttributeElement() { List<NestedAttributeName> attributeNames = new ArrayList<>(); attributeNames.add(NestedAttributeName.create("foo")); attributeNames.add(null); assertFails(() -> ScanEnhancedRequest.builder() .addNestedAttributesToProject(attributeNames) .build()); assertFails(() -> ScanEnhancedRequest.builder() .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar"), null) .build()); NestedAttributeName nestedAttributeName = null; ScanEnhancedRequest.builder() .addNestedAttributeToProject(nestedAttributeName) .build(); assertFails(() -> ScanEnhancedRequest.builder() .addNestedAttributesToProject(nestedAttributeName) .build()); }
ScanEnhancedRequest { public Builder toBuilder() { return builder().exclusiveStartKey(exclusiveStartKey) .limit(limit) .consistentRead(consistentRead) .filterExpression(filterExpression) .addNestedAttributesToProject(attributesToProject); } private ScanEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Map<String, AttributeValue> exclusiveStartKey(); Integer limit(); Boolean consistentRead(); Expression filterExpression(); List<String> attributesToProject(); List<NestedAttributeName> nestedAttributesToProject(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { ScanEnhancedRequest builtObject = ScanEnhancedRequest.builder().exclusiveStartKey(null).build(); ScanEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
CreateTableEnhancedRequest { public Builder toBuilder() { return builder().provisionedThroughput(provisionedThroughput) .localSecondaryIndices(localSecondaryIndices) .globalSecondaryIndices(globalSecondaryIndices); } private CreateTableEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); ProvisionedThroughput provisionedThroughput(); Collection<EnhancedLocalSecondaryIndex> localSecondaryIndices(); Collection<EnhancedGlobalSecondaryIndex> globalSecondaryIndices(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { CreateTableEnhancedRequest builtObject = CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .build(); CreateTableEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
DeleteItemEnhancedRequest { public Builder toBuilder() { return builder().key(key).conditionExpression(conditionExpression); } private DeleteItemEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Key key(); Expression conditionExpression(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { Key key = Key.builder().partitionValue("key").build(); DeleteItemEnhancedRequest builtObject = DeleteItemEnhancedRequest.builder().key(key).build(); DeleteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
QueryEnhancedRequest { public static Builder builder() { return new Builder(); } private QueryEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); QueryConditional queryConditional(); Map<String, AttributeValue> exclusiveStartKey(); Boolean scanIndexForward(); Integer limit(); Boolean consistentRead(); Expression filterExpression(); List<String> attributesToProject(); List<NestedAttributeName> nestedAttributesToProject(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void test_nestedAttributesNullNestedAttributeElement() { List<NestedAttributeName> attributeNames = new ArrayList<>(); attributeNames.add(NestedAttributeName.create("foo")); attributeNames.add(null); assertFails(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(attributeNames) .build()); assertFails(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar"), null) .build()); NestedAttributeName nestedAttributeName = null; QueryEnhancedRequest.builder() .addNestedAttributeToProject(nestedAttributeName) .build(); assertFails(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(nestedAttributeName) .build()); }
QueryEnhancedRequest { public Builder toBuilder() { return builder().queryConditional(queryConditional) .exclusiveStartKey(exclusiveStartKey) .scanIndexForward(scanIndexForward) .limit(limit) .consistentRead(consistentRead) .filterExpression(filterExpression) .addNestedAttributesToProject(attributesToProject); } private QueryEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); QueryConditional queryConditional(); Map<String, AttributeValue> exclusiveStartKey(); Boolean scanIndexForward(); Integer limit(); Boolean consistentRead(); Expression filterExpression(); List<String> attributesToProject(); List<NestedAttributeName> nestedAttributesToProject(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { QueryEnhancedRequest builtObject = QueryEnhancedRequest.builder().build(); QueryEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
UpdateItemEnhancedRequest { public Builder<T> toBuilder() { return new Builder<T>().item(item).ignoreNulls(ignoreNulls); } private UpdateItemEnhancedRequest(Builder<T> builder); static Builder<T> builder(Class<? extends T> itemClass); Builder<T> toBuilder(); T item(); Boolean ignoreNulls(); Expression conditionExpression(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { UpdateItemEnhancedRequest<FakeItem> builtObject = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); UpdateItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
BatchGetItemEnhancedRequest { public Builder toBuilder() { return new Builder().readBatches(readBatches); } private BatchGetItemEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Collection<ReadBatch> readBatches(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder().build(); BatchGetItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); }
BeanTableSchema extends WrappedTableSchema<T, StaticTableSchema<T>> { public static <T> BeanTableSchema<T> create(Class<T> beanClass) { return create(beanClass, new MetaTableSchemaCache()); } private BeanTableSchema(StaticTableSchema<T> staticTableSchema); static BeanTableSchema<T> create(Class<T> beanClass); }
@Test public void simpleBean_correctlyAssignsPrimaryPartitionKey() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.tableMetadata().primaryPartitionKey(), is("id")); } @Test public void sortKeyBean_correctlyAssignsSortKey() { BeanTableSchema<SortKeyBean> beanTableSchema = BeanTableSchema.create(SortKeyBean.class); assertThat(beanTableSchema.tableMetadata().primarySortKey(), is(Optional.of("sort"))); } @Test public void simpleBean_hasNoSortKey() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.tableMetadata().primarySortKey(), is(Optional.empty())); } @Test public void simpleBean_hasNoAdditionalKeys() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.tableMetadata().allKeys(), contains("id")); } @Test public void sortKeyBean_hasNoAdditionalKeys() { BeanTableSchema<SortKeyBean> beanTableSchema = BeanTableSchema.create(SortKeyBean.class); assertThat(beanTableSchema.tableMetadata().allKeys(), containsInAnyOrder("id", "sort")); } @Test public void secondaryIndexBean_definesGsiCorrectly() { BeanTableSchema<SecondaryIndexBean> beanTableSchema = BeanTableSchema.create(SecondaryIndexBean.class); assertThat(beanTableSchema.tableMetadata().indexPartitionKey("gsi"), is("sort")); assertThat(beanTableSchema.tableMetadata().indexSortKey("gsi"), is(Optional.of("attribute"))); } @Test public void secondaryIndexBean_definesLsiCorrectly() { BeanTableSchema<SecondaryIndexBean> beanTableSchema = BeanTableSchema.create(SecondaryIndexBean.class); assertThat(beanTableSchema.tableMetadata().indexPartitionKey("lsi"), is("id")); assertThat(beanTableSchema.tableMetadata().indexSortKey("lsi"), is(Optional.of("attribute"))); } @Test public void dynamoDbIgnore_propertyIsIgnored() { BeanTableSchema<IgnoredAttributeBean> beanTableSchema = BeanTableSchema.create(IgnoredAttributeBean.class); IgnoredAttributeBean ignoredAttributeBean = new IgnoredAttributeBean(); ignoredAttributeBean.setId("id-value"); ignoredAttributeBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(ignoredAttributeBean, false); assertThat(itemMap.size(), is(1)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); } @Test public void setterAnnotations_alsoWork() { BeanTableSchema<SetterAnnotatedBean> beanTableSchema = BeanTableSchema.create(SetterAnnotatedBean.class); SetterAnnotatedBean setterAnnotatedBean = new SetterAnnotatedBean(); setterAnnotatedBean.setId("id-value"); setterAnnotatedBean.setIntegerAttribute(123); assertThat(beanTableSchema.tableMetadata().primaryPartitionKey(), is("id")); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setterAnnotatedBean, false); assertThat(itemMap.size(), is(1)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); } @Test public void dynamoDbAttribute_remapsAttributeName() { BeanTableSchema<RemappedAttributeBean> beanTableSchema = BeanTableSchema.create(RemappedAttributeBean.class); assertThat(beanTableSchema.tableMetadata().primaryPartitionKey(), is("remappedAttribute")); } @Test public void dynamoDbFlatten_correctlyFlattensBeanAttributes() { BeanTableSchema<FlattenedBeanBean> beanTableSchema = BeanTableSchema.create(FlattenedBeanBean.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); FlattenedBeanBean flattenedBeanBean = new FlattenedBeanBean(); flattenedBeanBean.setId("id-value"); flattenedBeanBean.setAttribute1("one"); flattenedBeanBean.setAbstractBean(abstractBean); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(flattenedBeanBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test public void dynamoDbFlatten_correctlyFlattensImmutableAttributes() { BeanTableSchema<FlattenedImmutableBean> beanTableSchema = BeanTableSchema.create(FlattenedImmutableBean.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); FlattenedImmutableBean flattenedImmutableBean = new FlattenedImmutableBean(); flattenedImmutableBean.setId("id-value"); flattenedImmutableBean.setAttribute1("one"); flattenedImmutableBean.setAbstractImmutable(abstractImmutable); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(flattenedImmutableBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test public void documentBean_correctlyMapsBeanAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBean(abstractBean); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBean", expectedDocument)); } @Test public void documentBean_list_correctlyMapsBeanAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBeanList(Arrays.asList(abstractBean1, abstractBean2)); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanList", expectedList)); } @Test public void documentBean_map_correctlyMapsBeanAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); Map<String, AbstractBean> abstractBeanMap = new HashMap<>(); abstractBeanMap.put("key1", abstractBean1); abstractBeanMap.put("key2", abstractBean2); documentBean.setAbstractBeanMap(abstractBeanMap); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanMap", expectedMap)); } @Test public void documentBean_correctlyMapsImmutableAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractImmutable(abstractImmutable); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutable", expectedDocument)); } @Test public void documentBean_list_correctlyMapsImmutableAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractImmutableList(Arrays.asList(abstractImmutable1, abstractImmutable2)); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableList", expectedList)); } @Test public void documentBean_map_correctlyMapsImmutableAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); Map<String, AbstractImmutable> abstractImmutableMap = new HashMap<>(); abstractImmutableMap.put("key1", abstractImmutable1); abstractImmutableMap.put("key2", abstractImmutable2); documentBean.setAbstractImmutableMap(abstractImmutableMap); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableMap", expectedMap)); } @Test public void parameterizedDocumentBean_correctlyMapsAttributes() { BeanTableSchema<ParameterizedDocumentBean> beanTableSchema = BeanTableSchema.create(ParameterizedDocumentBean.class); ParameterizedAbstractBean<String> abstractBean = new ParameterizedAbstractBean<>(); abstractBean.setAttribute2("two"); ParameterizedDocumentBean documentBean = new ParameterizedDocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBean(abstractBean); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBean", expectedDocument)); } @Test public void parameterizedDocumentBean_list_correctlyMapsAttributes() { BeanTableSchema<ParameterizedDocumentBean> beanTableSchema = BeanTableSchema.create(ParameterizedDocumentBean.class); ParameterizedAbstractBean<String> abstractBean1 = new ParameterizedAbstractBean<>(); abstractBean1.setAttribute2("two"); ParameterizedAbstractBean<String> abstractBean2 = new ParameterizedAbstractBean<>(); abstractBean2.setAttribute2("three"); ParameterizedDocumentBean documentBean = new ParameterizedDocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBeanList(Arrays.asList(abstractBean1, abstractBean2)); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanList", expectedList)); } @Test public void parameterizedDocumentBean_map_correctlyMapsAttributes() { BeanTableSchema<ParameterizedDocumentBean> beanTableSchema = BeanTableSchema.create(ParameterizedDocumentBean.class); ParameterizedAbstractBean<String> abstractBean1 = new ParameterizedAbstractBean<>(); abstractBean1.setAttribute2("two"); ParameterizedAbstractBean<String> abstractBean2 = new ParameterizedAbstractBean<>(); abstractBean2.setAttribute2("three"); ParameterizedDocumentBean documentBean = new ParameterizedDocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); Map<String, ParameterizedAbstractBean<String>> abstractBeanMap = new HashMap<>(); abstractBeanMap.put("key1", abstractBean1); abstractBeanMap.put("key2", abstractBean2); documentBean.setAbstractBeanMap(abstractBeanMap); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanMap", expectedMap)); } @Test public void extendedBean_correctlyExtendsAttributes() { BeanTableSchema<ExtendedBean> beanTableSchema = BeanTableSchema.create(ExtendedBean.class); ExtendedBean extendedBean = new ExtendedBean(); extendedBean.setId("id-value"); extendedBean.setAttribute1("one"); extendedBean.setAttribute2("two"); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(extendedBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test(expected = IllegalArgumentException.class) public void invalidBean_throwsIllegalArgumentException() { BeanTableSchema.create(InvalidBean.class); } @Test public void itemToMap_nullAttribute_ignoreNullsTrue() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(simpleBean, true); assertThat(itemMap.size(), is(1)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); } @Test public void itemToMap_nullAttribute_ignoreNullsFalse() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(simpleBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerAttribute", AttributeValues.nullAttributeValue())); } @Test public void itemToMap_nonNullAttribute() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); simpleBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(simpleBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); } @Test public void mapToItem_createsItem() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", stringValue("id-value")); itemMap.put("integerAttribute", numberValue(123)); SimpleBean expectedBean = new SimpleBean(); expectedBean.setId("id-value"); expectedBean.setIntegerAttribute(123); SimpleBean result = beanTableSchema.mapToItem(itemMap); assertThat(result, is(expectedBean)); } @Test public void attributeValue_returnsValue() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); simpleBean.setIntegerAttribute(123); assertThat(beanTableSchema.attributeValue(simpleBean, "integerAttribute"), is(numberValue(123))); } @Test public void enumBean_invalidEnum() { BeanTableSchema<EnumBean> beanTableSchema = BeanTableSchema.create(EnumBean.class); Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", stringValue("id-value")); itemMap.put("testEnum", stringValue("invalid-value")); exception.expect(IllegalArgumentException.class); exception.expectMessage("invalid-value"); exception.expectMessage("TestEnum"); beanTableSchema.mapToItem(itemMap); } @Test public void enumBean_singleEnum() { BeanTableSchema<EnumBean> beanTableSchema = BeanTableSchema.create(EnumBean.class); EnumBean enumBean = new EnumBean(); enumBean.setId("id-value"); enumBean.setTestEnum(EnumBean.TestEnum.ONE); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(enumBean, true); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("testEnum", stringValue("ONE"))); EnumBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(enumBean))); } @Test public void enumBean_listEnum() { BeanTableSchema<EnumBean> beanTableSchema = BeanTableSchema.create(EnumBean.class); EnumBean enumBean = new EnumBean(); enumBean.setId("id-value"); enumBean.setTestEnumList(Arrays.asList(EnumBean.TestEnum.ONE, EnumBean.TestEnum.TWO)); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(enumBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .l(stringValue("ONE"), stringValue("TWO")) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("testEnumList", expectedAttributeValue)); EnumBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(enumBean))); } @Test public void listBean_stringList() { BeanTableSchema<ListBean> beanTableSchema = BeanTableSchema.create(ListBean.class); ListBean listBean = new ListBean(); listBean.setId("id-value"); listBean.setStringList(Arrays.asList("one", "two", "three")); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(listBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .l(stringValue("one"), stringValue("two"), stringValue("three")) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringList", expectedAttributeValue)); ListBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(listBean))); } @Test public void listBean_stringListList() { BeanTableSchema<ListBean> beanTableSchema = BeanTableSchema.create(ListBean.class); ListBean listBean = new ListBean(); listBean.setId("id-value"); listBean.setStringListList(Arrays.asList(Arrays.asList("one", "two"), Arrays.asList("three", "four"))); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(listBean, true); AttributeValue list1 = AttributeValue.builder().l(stringValue("one"), stringValue("two")).build(); AttributeValue list2 = AttributeValue.builder().l(stringValue("three"), stringValue("four")).build(); AttributeValue expectedAttributeValue = AttributeValue.builder() .l(list1, list2) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringListList", expectedAttributeValue)); ListBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(listBean))); } @Test public void setBean_stringSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<String> stringSet = new LinkedHashSet<>(); stringSet.add("one"); stringSet.add("two"); stringSet.add("three"); setBean.setStringSet(stringSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ss("one", "two", "three") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_integerSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Integer> integerSet = new LinkedHashSet<>(); integerSet.add(1); integerSet.add(2); integerSet.add(3); setBean.setIntegerSet(integerSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_longSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Long> longSet = new LinkedHashSet<>(); longSet.add(1L); longSet.add(2L); longSet.add(3L); setBean.setLongSet(longSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("longSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_shortSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Short> shortSet = new LinkedHashSet<>(); shortSet.add((short)1); shortSet.add((short)2); shortSet.add((short)3); setBean.setShortSet(shortSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("shortSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_byteSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Byte> byteSet = new LinkedHashSet<>(); byteSet.add((byte)1); byteSet.add((byte)2); byteSet.add((byte)3); setBean.setByteSet(byteSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("byteSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_doubleSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Double> doubleSet = new LinkedHashSet<>(); doubleSet.add(1.1); doubleSet.add(2.2); doubleSet.add(3.3); setBean.setDoubleSet(doubleSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1.1", "2.2", "3.3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("doubleSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_floatSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Float> floatSet = new LinkedHashSet<>(); floatSet.add(1.1f); floatSet.add(2.2f); floatSet.add(3.3f); setBean.setFloatSet(floatSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1.1", "2.2", "3.3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("floatSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_binarySet() { SdkBytes buffer1 = SdkBytes.fromString("one", StandardCharsets.UTF_8); SdkBytes buffer2 = SdkBytes.fromString("two", StandardCharsets.UTF_8); SdkBytes buffer3 = SdkBytes.fromString("three", StandardCharsets.UTF_8); BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<SdkBytes> binarySet = new LinkedHashSet<>(); binarySet.add(buffer1); binarySet.add(buffer2); binarySet.add(buffer3); setBean.setBinarySet(binarySet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .bs(buffer1, buffer2, buffer3) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("binarySet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void mapBean_stringStringMap() { BeanTableSchema<MapBean> beanTableSchema = BeanTableSchema.create(MapBean.class); MapBean mapBean = new MapBean(); mapBean.setId("id-value"); Map<String, String> testMap = new HashMap<>(); testMap.put("one", "two"); testMap.put("three", "four"); mapBean.setStringMap(testMap); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(mapBean, true); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("one", stringValue("two")); expectedMap.put("three", stringValue("four")); AttributeValue expectedMapValue = AttributeValue.builder() .m(expectedMap) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringMap", expectedMapValue)); MapBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(mapBean))); } @Test public void mapBean_nestedStringMap() { BeanTableSchema<MapBean> beanTableSchema = BeanTableSchema.create(MapBean.class); MapBean mapBean = new MapBean(); mapBean.setId("id-value"); Map<String, Map<String, String>> testMap = new HashMap<>(); testMap.put("five", singletonMap("one", "two")); testMap.put("six", singletonMap("three", "four")); mapBean.setNestedStringMap(testMap); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(mapBean, true); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("five", AttributeValue.builder().m(singletonMap("one", stringValue("two"))).build()); expectedMap.put("six", AttributeValue.builder().m(singletonMap("three", stringValue("four"))).build()); AttributeValue expectedMapValue = AttributeValue.builder() .m(expectedMap) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("nestedStringMap", expectedMapValue)); MapBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(mapBean))); } @Test public void commonTypesBean() { BeanTableSchema<CommonTypesBean> beanTableSchema = BeanTableSchema.create(CommonTypesBean.class); CommonTypesBean commonTypesBean = new CommonTypesBean(); SdkBytes binaryLiteral = SdkBytes.fromString("test-string", StandardCharsets.UTF_8); commonTypesBean.setId("id-value"); commonTypesBean.setBooleanAttribute(true); commonTypesBean.setIntegerAttribute(123); commonTypesBean.setLongAttribute(234L); commonTypesBean.setShortAttribute((short) 345); commonTypesBean.setByteAttribute((byte) 45); commonTypesBean.setDoubleAttribute(56.7); commonTypesBean.setFloatAttribute((float) 67.8); commonTypesBean.setBinaryAttribute(binaryLiteral); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(commonTypesBean, true); assertThat(itemMap.size(), is(9)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("booleanAttribute", AttributeValue.builder().bool(true).build())); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); assertThat(itemMap, hasEntry("longAttribute", numberValue(234))); assertThat(itemMap, hasEntry("shortAttribute", numberValue(345))); assertThat(itemMap, hasEntry("byteAttribute", numberValue(45))); assertThat(itemMap, hasEntry("doubleAttribute", numberValue(56.7))); assertThat(itemMap, hasEntry("floatAttribute", numberValue(67.8))); assertThat(itemMap, hasEntry("binaryAttribute", binaryValue(binaryLiteral))); CommonTypesBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(commonTypesBean))); } @Test public void primitiveTypesBean() { BeanTableSchema<PrimitiveTypesBean> beanTableSchema = BeanTableSchema.create(PrimitiveTypesBean.class); PrimitiveTypesBean primitiveTypesBean = new PrimitiveTypesBean(); primitiveTypesBean.setId("id-value"); primitiveTypesBean.setBooleanAttribute(true); primitiveTypesBean.setIntegerAttribute(123); primitiveTypesBean.setLongAttribute(234L); primitiveTypesBean.setShortAttribute((short) 345); primitiveTypesBean.setByteAttribute((byte) 45); primitiveTypesBean.setDoubleAttribute(56.7); primitiveTypesBean.setFloatAttribute((float) 67.8); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(primitiveTypesBean, true); assertThat(itemMap.size(), is(8)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("booleanAttribute", AttributeValue.builder().bool(true).build())); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); assertThat(itemMap, hasEntry("longAttribute", numberValue(234))); assertThat(itemMap, hasEntry("shortAttribute", numberValue(345))); assertThat(itemMap, hasEntry("byteAttribute", numberValue(45))); assertThat(itemMap, hasEntry("doubleAttribute", numberValue(56.7))); assertThat(itemMap, hasEntry("floatAttribute", numberValue(67.8))); PrimitiveTypesBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(primitiveTypesBean))); } @Test public void itemToMap_specificAttributes() { BeanTableSchema<CommonTypesBean> beanTableSchema = BeanTableSchema.create(CommonTypesBean.class); CommonTypesBean commonTypesBean = new CommonTypesBean(); commonTypesBean.setId("id-value"); commonTypesBean.setIntegerAttribute(123); commonTypesBean.setLongAttribute(234L); commonTypesBean.setFloatAttribute((float) 67.8); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(commonTypesBean, Arrays.asList("longAttribute", "floatAttribute")); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("longAttribute", numberValue(234))); assertThat(itemMap, hasEntry("floatAttribute", numberValue(67.8))); } @Test public void itemType_returnsCorrectClass() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.itemType(), is(equalTo(EnhancedType.of(SimpleBean.class)))); } @Test public void attributeConverterWithoutConstructor_throwsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("default constructor"); BeanTableSchema.create(AttributeConverterNoConstructorBean.class); } @Test public void usesCustomAttributeConverter() { BeanTableSchema<AttributeConverterBean> beanTableSchema = BeanTableSchema.create(AttributeConverterBean.class); AttributeConverterBean.AttributeItem attributeItem = new AttributeConverterBean.AttributeItem(); attributeItem.setInnerValue("inner-value"); AttributeConverterBean converterBean = new AttributeConverterBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); converterBean.setAttributeItem(attributeItem); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); assertThat(itemMap, hasEntry("attributeItem", stringValue("inner-value"))); AttributeConverterBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(converterBean))); } @Test public void converterProviderWithoutConstructor_throwsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("default constructor"); BeanTableSchema.create(NoConstructorConverterProvidersBean.class); } @Test public void usesCustomAttributeConverterProvider() { BeanTableSchema<SingleConverterProvidersBean> beanTableSchema = BeanTableSchema.create(SingleConverterProvidersBean.class); SingleConverterProvidersBean converterBean = new SingleConverterProvidersBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value-custom"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(133))); SingleConverterProvidersBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse.getId(), is(equalTo("id-value-custom"))); assertThat(reverse.getIntegerAttribute(), is(equalTo(133))); } @Test public void usesCustomAttributeConverterProviders() { BeanTableSchema<MultipleConverterProvidersBean> beanTableSchema = BeanTableSchema.create(MultipleConverterProvidersBean.class); MultipleConverterProvidersBean converterBean = new MultipleConverterProvidersBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value-custom"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(133))); MultipleConverterProvidersBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse.getId(), is(equalTo("id-value-custom"))); assertThat(reverse.getIntegerAttribute(), is(equalTo(133))); } @Test public void emptyConverterProviderList_fails_whenAttributeConvertersAreMissing() { exception.expect(NullPointerException.class); BeanTableSchema.create(EmptyConverterProvidersInvalidBean.class); } @Test public void emptyConverterProviderList_correct_whenAttributeConvertersAreSupplied() { BeanTableSchema<EmptyConverterProvidersValidBean> beanTableSchema = BeanTableSchema.create(EmptyConverterProvidersValidBean.class); EmptyConverterProvidersValidBean converterBean = new EmptyConverterProvidersValidBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value-custom"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(133))); EmptyConverterProvidersValidBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse.getId(), is(equalTo("id-value-custom"))); assertThat(reverse.getIntegerAttribute(), is(equalTo(133))); }
ExceptionTranslationInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!isS3Exception404(context.exception()) || !isHeadRequest(context.request())) { return context.exception(); } String message = context.exception().getMessage(); S3Exception exception = (S3Exception) (context.exception()); String requestIdFromHeader = exception.awsErrorDetails() .sdkHttpResponse() .firstMatchingHeader("x-amz-request-id") .orElse(null); String requestId = Optional.ofNullable(exception.requestId()).orElse(requestIdFromHeader); AwsErrorDetails errorDetails = exception.awsErrorDetails(); if (context.request() instanceof HeadObjectRequest) { return NoSuchKeyException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchKey", "The specified key does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } if (context.request() instanceof HeadBucketRequest) { return NoSuchBucketException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchBucket", "The specified bucket does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } return context.exception(); } @Override Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes); }
@Test public void headBucket404_shouldTranslateException() { S3Exception s3Exception = create404S3Exception(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, HeadBucketRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())) .isExactlyInstanceOf(NoSuchBucketException.class); } @Test public void headObject404_shouldTranslateException() { S3Exception s3Exception = create404S3Exception(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, HeadObjectRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())) .isExactlyInstanceOf(NoSuchKeyException.class); } @Test public void headObjectOtherException_shouldNotThrowException() { S3Exception s3Exception = (S3Exception) S3Exception.builder().statusCode(500).build(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, HeadObjectRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())).isEqualTo(s3Exception); } @Test public void otherRequest_shouldNotThrowException() { S3Exception s3Exception = create404S3Exception(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, PutObjectRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())).isEqualTo(s3Exception); }
ImmutableAttribute { public Builder<T, B, R> toBuilder() { return new Builder<T, B, R>(this.type).name(this.name) .getter(this.getter) .setter(this.setter) .tags(this.tags) .attributeConverter(this.attributeConverter); } private ImmutableAttribute(Builder<T, B, R> builder); static Builder<T, B, R> builder(Class<T> itemClass, Class<B> builderClass, EnhancedType<R> attributeType); static Builder<T, B, R> builder(Class<T> itemClass, Class<B> builderClass, Class<R> attributeClass); String name(); Function<T, R> getter(); BiConsumer<B, R> setter(); Collection<StaticAttributeTag> tags(); EnhancedType<R> type(); AttributeConverter<R> attributeConverter(); Builder<T, B, R> toBuilder(); }
@Test public void toBuilder() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag, mockTag2) .attributeConverter(attributeConverter) .build(); ImmutableAttribute<Object, Object, String> clonedAttribute = immutableAttribute.toBuilder().build(); assertThat(clonedAttribute.name()).isEqualTo("test-attribute"); assertThat(clonedAttribute.getter()).isSameAs(TEST_GETTER); assertThat(clonedAttribute.setter()).isSameAs(TEST_SETTER); assertThat(clonedAttribute.tags()).containsExactly(mockTag, mockTag2); assertThat(clonedAttribute.type()).isEqualTo(EnhancedType.of(String.class)); assertThat(clonedAttribute.attributeConverter()).isSameAs(attributeConverter); }
ImmutableTableSchema extends WrappedTableSchema<T, StaticImmutableTableSchema<T, ?>> { public static <T> ImmutableTableSchema<T> create(Class<T> immutableClass) { return create(immutableClass, new MetaTableSchemaCache()); } private ImmutableTableSchema(StaticImmutableTableSchema<T, ?> wrappedTableSchema); static ImmutableTableSchema<T> create(Class<T> immutableClass); }
@Test public void documentImmutable_correctlyMapsBeanAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); DocumentImmutable documentImmutable = DocumentImmutable.builder().id("id-value") .attribute1("one") .abstractBean(abstractBean) .build(); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBean", expectedDocument)); } @Test public void documentImmutable_list_correctlyMapsBeanAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractBeanList(Arrays.asList(abstractBean1, abstractBean2)) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanList", expectedList)); } @Test public void documentImmutable_map_correctlyMapsBeanAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); Map<String, AbstractBean> abstractBeanMap = new HashMap<>(); abstractBeanMap.put("key1", abstractBean1); abstractBeanMap.put("key2", abstractBean2); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractBeanMap(abstractBeanMap) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanMap", expectedMap)); } @Test public void documentImmutable_correctlyMapsImmutableAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); DocumentImmutable documentImmutable = DocumentImmutable.builder().id("id-value") .attribute1("one") .abstractImmutable(abstractImmutable) .build(); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutable", expectedDocument)); } @Test public void documentImmutable_list_correctlyMapsImmutableAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractImmutableList(Arrays.asList(abstractImmutable1, abstractImmutable2)) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableList", expectedList)); } @Test public void documentImmutable_map_correctlyMapsImmutableAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); Map<String, AbstractImmutable> abstractImmutableMap = new HashMap<>(); abstractImmutableMap.put("key1", abstractImmutable1); abstractImmutableMap.put("key2", abstractImmutable2); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractImmutableMap(abstractImmutableMap) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableMap", expectedMap)); } @Test public void dynamoDbFlatten_correctlyFlattensBeanAttributes() { ImmutableTableSchema<FlattenedBeanImmutable> tableSchema = ImmutableTableSchema.create(FlattenedBeanImmutable.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); FlattenedBeanImmutable flattenedBeanImmutable = new FlattenedBeanImmutable.Builder().setId("id-value") .setAttribute1("one") .setAbstractBean(abstractBean) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(flattenedBeanImmutable, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test public void dynamoDbFlatten_correctlyFlattensImmutableAttributes() { ImmutableTableSchema<FlattenedImmutableImmutable> tableSchema = ImmutableTableSchema.create(FlattenedImmutableImmutable.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); FlattenedImmutableImmutable FlattenedImmutableImmutable = new FlattenedImmutableImmutable.Builder().setId("id-value") .setAttribute1("one") .setAbstractImmutable(abstractImmutable) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(FlattenedImmutableImmutable, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); }
StaticTableSchema extends WrappedTableSchema<T, StaticImmutableTableSchema<T, T>> { public static <T> Builder<T> builder(Class<T> itemClass) { return new Builder<>(itemClass); } private StaticTableSchema(Builder<T> builder); static Builder<T> builder(Class<T> itemClass); AttributeConverterProvider attributeConverterProvider(); }
@Test public void itemToMap_omitsNullAttributes() { FakeMappedItem fakeMappedItemWithNulls = FakeMappedItem.builder().aPrimitiveBoolean(true).build(); Map<String, AttributeValue> attributeMap = createSimpleTableSchema().itemToMap(fakeMappedItemWithNulls, true); assertThat(attributeMap.size(), is(1)); assertThat(attributeMap, hasEntry("a_primitive_boolean", ATTRIBUTE_VALUE_B)); } @Test public void mapperCanHandleEnum() { verifyNullableAttribute(EnhancedType.of(FakeMappedItem.TestEnum.class), a -> a.name("value") .getter(FakeMappedItem::getTestEnum) .setter(FakeMappedItem::setTestEnum), FakeMappedItem.builder().testEnum(FakeMappedItem.TestEnum.ONE).build(), AttributeValue.builder().s("ONE").build()); } @Test public void mapperCanHandleDocument() { FakeDocument fakeDocument = FakeDocument.of("test-123", 123); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("documentInteger", AttributeValue.builder().n("123").build()); expectedMap.put("documentString", AttributeValue.builder().s("test-123").build()); verifyNullableAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().aFakeDocument(fakeDocument).build(), AttributeValue.builder().m(expectedMap).build()); } @Test public void mapperCanHandleDocumentWithNullValues() { verifyNullAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().build()); } @Test public void mapperCanHandleInteger() { verifyNullableAttribute(EnhancedType.of(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnInteger) .setter(FakeMappedItem::setAnInteger), FakeMappedItem.builder().anInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveInteger() { verifyAttribute(EnhancedType.of(int.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveInteger) .setter(FakeMappedItem::setAPrimitiveInteger), FakeMappedItem.builder().aPrimitiveInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleBoolean() { verifyNullableAttribute(EnhancedType.of(Boolean.class), a -> a.name("value") .getter(FakeMappedItem::getABoolean) .setter(FakeMappedItem::setABoolean), FakeMappedItem.builder().aBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandlePrimitiveBoolean() { verifyAttribute(EnhancedType.of(boolean.class), a -> a.name("value") .getter(FakeMappedItem::isAPrimitiveBoolean) .setter(FakeMappedItem::setAPrimitiveBoolean), FakeMappedItem.builder().aPrimitiveBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandleString() { verifyNullableAttribute(EnhancedType.of(String.class), a -> a.name("value") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString), FakeMappedItem.builder().aString("onetwothree").build(), AttributeValue.builder().s("onetwothree").build()); } @Test public void mapperCanHandleLong() { verifyNullableAttribute(EnhancedType.of(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALong) .setter(FakeMappedItem::setALong), FakeMappedItem.builder().aLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveLong() { verifyAttribute(EnhancedType.of(long.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveLong) .setter(FakeMappedItem::setAPrimitiveLong), FakeMappedItem.builder().aPrimitiveLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleShort() { verifyNullableAttribute(EnhancedType.of(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShort) .setter(FakeMappedItem::setAShort), FakeMappedItem.builder().aShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveShort() { verifyAttribute(EnhancedType.of(short.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveShort) .setter(FakeMappedItem::setAPrimitiveShort), FakeMappedItem.builder().aPrimitiveShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleByte() { verifyNullableAttribute(EnhancedType.of(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByte) .setter(FakeMappedItem::setAByte), FakeMappedItem.builder().aByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveByte() { verifyAttribute(EnhancedType.of(byte.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveByte) .setter(FakeMappedItem::setAPrimitiveByte), FakeMappedItem.builder().aPrimitiveByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleDouble() { verifyNullableAttribute(EnhancedType.of(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADouble) .setter(FakeMappedItem::setADouble), FakeMappedItem.builder().aDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveDouble() { verifyAttribute(EnhancedType.of(double.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveDouble) .setter(FakeMappedItem::setAPrimitiveDouble), FakeMappedItem.builder().aPrimitiveDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleFloat() { verifyNullableAttribute(EnhancedType.of(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloat) .setter(FakeMappedItem::setAFloat), FakeMappedItem.builder().aFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveFloat() { verifyAttribute(EnhancedType.of(float.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveFloat) .setter(FakeMappedItem::setAPrimitiveFloat), FakeMappedItem.builder().aPrimitiveFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleBinary() { SdkBytes sdkBytes = SdkBytes.fromString("test", UTF_8); verifyNullableAttribute(EnhancedType.of(SdkBytes.class), a -> a.name("value") .getter(FakeMappedItem::getABinaryValue) .setter(FakeMappedItem::setABinaryValue), FakeMappedItem.builder().aBinaryValue(sdkBytes).build(), AttributeValue.builder().b(sdkBytes).build()); } @Test public void mapperCanHandleSimpleList() { verifyNullableAttribute(EnhancedType.listOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerList) .setter(FakeMappedItem::setAnIntegerList), FakeMappedItem.builder().anIntegerList(asList(1, 2, 3)).build(), AttributeValue.builder().l(asList(AttributeValue.builder().n("1").build(), AttributeValue.builder().n("2").build(), AttributeValue.builder().n("3").build())).build()); } @Test public void mapperCanHandleNestedLists() { FakeMappedItem fakeMappedItem = FakeMappedItem.builder() .aNestedStructure(singletonList(singletonList(FakeDocument.of("nested", null)))) .build(); Map<String, AttributeValue> documentMap = new HashMap<>(); documentMap.put("documentString", AttributeValue.builder().s("nested").build()); documentMap.put("documentInteger", AttributeValue.builder().nul(true).build()); AttributeValue attributeValue = AttributeValue.builder() .l(singletonList(AttributeValue.builder() .l(AttributeValue.builder().m(documentMap).build()) .build())) .build(); verifyNullableAttribute( EnhancedType.listOf(EnhancedType.listOf(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA))), a -> a.name("value") .getter(FakeMappedItem::getANestedStructure) .setter(FakeMappedItem::setANestedStructure), fakeMappedItem, attributeValue); } @Test public void mapperCanHandleIntegerSet() { Set<Integer> valueSet = new HashSet<>(asList(1, 2, 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerSet) .setter(FakeMappedItem::setAnIntegerSet), FakeMappedItem.builder().anIntegerSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleStringSet() { Set<String> valueSet = new HashSet<>(asList("one", "two", "three")); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringSet) .setter(FakeMappedItem::setAStringSet), FakeMappedItem.builder().aStringSet(valueSet).build(), AttributeValue.builder().ss(expectedList).build()); } @Test public void mapperCanHandleLongSet() { Set<Long> valueSet = new HashSet<>(asList(1L, 2L, 3L)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALongSet) .setter(FakeMappedItem::setALongSet), FakeMappedItem.builder().aLongSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleShortSet() { Set<Short> valueSet = new HashSet<>(asList((short) 1, (short) 2, (short) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShortSet) .setter(FakeMappedItem::setAShortSet), FakeMappedItem.builder().aShortSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleByteSet() { Set<Byte> valueSet = new HashSet<>(asList((byte) 1, (byte) 2, (byte) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByteSet) .setter(FakeMappedItem::setAByteSet), FakeMappedItem.builder().aByteSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleDoubleSet() { Set<Double> valueSet = new HashSet<>(asList(1.2, 3.4, 5.6)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADoubleSet) .setter(FakeMappedItem::setADoubleSet), FakeMappedItem.builder().aDoubleSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleFloatSet() { Set<Float> valueSet = new HashSet<>(asList(1.2f, 3.4f, 5.6f)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloatSet) .setter(FakeMappedItem::setAFloatSet), FakeMappedItem.builder().aFloatSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleGenericMap() { Map<String, String> stringMap = new ConcurrentHashMap<>(); stringMap.put("one", "two"); stringMap.put("three", "four"); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("one", AttributeValue.builder().s("two").build()); attributeValueMap.put("three", AttributeValue.builder().s("four").build()); verifyNullableAttribute(EnhancedType.mapOf(String.class, String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringMap) .setter(FakeMappedItem::setAStringMap), FakeMappedItem.builder().aStringMap(stringMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void mapperCanHandleIntDoubleMap() { Map<Integer, Double> intDoubleMap = new ConcurrentHashMap<>(); intDoubleMap.put(1, 1.0); intDoubleMap.put(2, 3.0); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("1", AttributeValue.builder().n("1.0").build()); attributeValueMap.put("2", AttributeValue.builder().n("3.0").build()); verifyNullableAttribute(EnhancedType.mapOf(Integer.class, Double.class), a -> a.name("value") .getter(FakeMappedItem::getAIntDoubleMap) .setter(FakeMappedItem::setAIntDoubleMap), FakeMappedItem.builder().aIntDoubleMap(intDoubleMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void getAttributeValue_correctlyMapsSuperclassAttributes() { FakeItem fakeItem = FakeItem.builder().id("id-value").build(); fakeItem.setSubclassAttribute("subclass-value"); AttributeValue attributeValue = FakeItem.getTableSchema().attributeValue(fakeItem, "subclass_attribute"); assertThat(attributeValue, is(AttributeValue.builder().s("subclass-value").build())); } @Test public void getAttributeValue_correctlyMapsComposedClassAttributes() { FakeItem fakeItem = FakeItem.builder().id("id-value") .composedObject(FakeItemComposedClass.builder().composedAttribute("composed-value").build()) .build(); AttributeValue attributeValue = FakeItem.getTableSchema().attributeValue(fakeItem, "composed_attribute"); assertThat(attributeValue, is(AttributeValue.builder().s("composed-value").build())); } @Test public void mapToItem_correctlyConstructsComposedClass() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", AttributeValue.builder().s("id-value").build()); itemMap.put("composed_attribute", AttributeValue.builder().s("composed-value").build()); FakeItem fakeItem = FakeItem.getTableSchema().mapToItem(itemMap); assertThat(fakeItem, is(FakeItem.builder() .id("id-value") .composedObject(FakeItemComposedClass.builder() .composedAttribute("composed-value") .build()) .build())); } @Test public void buildAbstractTableSchema() { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .build(); assertThat(tableSchema.itemToMap(FAKE_ITEM, false), is(singletonMap("aString", stringValue("test-string")))); exception.expect(UnsupportedOperationException.class); exception.expectMessage("abstract"); tableSchema.mapToItem(singletonMap("aString", stringValue("test-string"))); } @Test public void buildAbstractWithFlatten() { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .flatten(FAKE_DOCUMENT_TABLE_SCHEMA, FakeMappedItem::getAFakeDocument, FakeMappedItem::setAFakeDocument) .build(); FakeDocument document = FakeDocument.of("test-string", null); FakeMappedItem item = FakeMappedItem.builder().aFakeDocument(document).build(); assertThat(tableSchema.itemToMap(item, true), is(singletonMap("documentString", AttributeValue.builder().s("test-string").build()))); } @Test public void buildAbstractExtends() { StaticTableSchema<FakeAbstractSuperclass> superclassTableSchema = StaticTableSchema.builder(FakeAbstractSuperclass.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeAbstractSuperclass::getAString) .setter(FakeAbstractSuperclass::setAString)) .build(); StaticTableSchema<FakeAbstractSubclass> subclassTableSchema = StaticTableSchema.builder(FakeAbstractSubclass.class) .extend(superclassTableSchema) .build(); FakeAbstractSubclass item = new FakeAbstractSubclass(); item.setAString("test-string"); assertThat(subclassTableSchema.itemToMap(item, true), is(singletonMap("aString", AttributeValue.builder().s("test-string").build()))); } @Test public void buildAbstractTagWith() { StaticTableSchema<FakeDocument> abstractTableSchema = StaticTableSchema .builder(FakeDocument.class) .tags(new TestStaticTableTag()) .build(); assertThat(abstractTableSchema.tableMetadata().customMetadataObject(TABLE_TAG_KEY, String.class), is(Optional.of(TABLE_TAG_VALUE))); } @Test public void buildConcreteTagWith() { StaticTableSchema<FakeDocument> concreteTableSchema = StaticTableSchema .builder(FakeDocument.class) .newItemSupplier(FakeDocument::new) .tags(new TestStaticTableTag()) .build(); assertThat(concreteTableSchema.tableMetadata().customMetadataObject(TABLE_TAG_KEY, String.class), is(Optional.of(TABLE_TAG_VALUE))); } @Test public void instantiateFlattenedAbstractClassShouldThrowException() { StaticTableSchema<FakeAbstractSuperclass> superclassTableSchema = StaticTableSchema.builder(FakeAbstractSuperclass.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeAbstractSuperclass::getAString) .setter(FakeAbstractSuperclass::setAString)) .build(); exception.expect(IllegalArgumentException.class); exception.expectMessage("abstract"); StaticTableSchema.builder(FakeBrokenClass.class) .newItemSupplier(FakeBrokenClass::new) .flatten(superclassTableSchema, FakeBrokenClass::getAbstractObject, FakeBrokenClass::setAbstractObject); } @Test public void usesCustomAttributeConverterProvider() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(provider1.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter1); when(attributeConverter1.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void usesCustomAttributeConverterProviders() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(provider2.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter2); when(attributeConverter2.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1, provider2) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void noConverterProvider_throwsException_whenMissingAttributeConverters() { exception.expect(NullPointerException.class); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(Collections.emptyList()) .build(); } @Test public void noConverterProvider_handlesCorrectly_whenAttributeConvertersAreSupplied() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(attributeConverter1.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString) .attributeConverter(attributeConverter1)) .attributeConverterProviders(Collections.emptyList()) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); }
DecodeUrlEncodedResponseInterceptor implements ExecutionInterceptor { @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); if (shouldHandle(response)) { if (response instanceof ListObjectsResponse) { return modifyListObjectsResponse((ListObjectsResponse) response); } if (response instanceof ListObjectsV2Response) { return modifyListObjectsV2Response((ListObjectsV2Response) response); } if (response instanceof ListObjectVersionsResponse) { return modifyListObjectVersionsResponse((ListObjectVersionsResponse) response); } if (response instanceof ListMultipartUploadsResponse) { return modifyListMultipartUploadsResponse((ListMultipartUploadsResponse) response); } } return response; } @Override SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes); }
@Test public void encodingTypeSet_decodesListObjectsResponseParts() { Context.ModifyResponse ctx = newContext(V1_TEST_ENCODED_RESPONSE); ListObjectsResponse decoded = (ListObjectsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes()); assertDecoded(decoded::delimiter, " delimiter"); assertDecoded(decoded::nextMarker, " nextmarker"); assertDecoded(decoded::prefix, " prefix"); assertDecoded(decoded::marker, " marker"); assertKeysAreDecoded(decoded.contents()); assertCommonPrefixesAreDecoded(decoded.commonPrefixes()); } @Test public void encodingTypeSet_decodesListObjectsV2ResponseParts() { Context.ModifyResponse ctx = newContext(V2_TEST_ENCODED_RESPONSE); ListObjectsV2Response decoded = (ListObjectsV2Response) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes()); assertDecoded(decoded::delimiter, " delimiter"); assertDecoded(decoded::prefix, " prefix"); assertDecoded(decoded::startAfter, " startafter"); assertKeysAreDecoded(decoded.contents()); assertCommonPrefixesAreDecoded(decoded.commonPrefixes()); } @Test public void encodingTypeSet_decodesListObjectVersionsResponse() { Context.ModifyResponse ctx = newContext(TEST_LIST_OBJECT_VERSION_RESPONSE); ListObjectVersionsResponse decoded = (ListObjectVersionsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes()); assertDecoded(decoded::delimiter, " delimiter"); assertDecoded(decoded::prefix, " prefix"); assertDecoded(decoded::keyMarker, " keyMarker"); assertDecoded(decoded::nextKeyMarker, " nextKeyMarker"); assertCommonPrefixesAreDecoded(decoded.commonPrefixes()); assertVersionsAreDecoded(decoded.versions()); } @Test public void encodingTypeSet_decodesListMultipartUploadsResponse() { Context.ModifyResponse ctx = newContext(TEST_LIST_MULTIPART_UPLOADS_RESPONSE); ListMultipartUploadsResponse decoded = (ListMultipartUploadsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes()); assertDecoded(decoded::delimiter, " delimiter"); assertDecoded(decoded::prefix, " prefix"); assertDecoded(decoded::keyMarker, " keyMarker"); assertDecoded(decoded::nextKeyMarker, " nextKeyMarker"); assertCommonPrefixesAreDecoded(decoded.commonPrefixes()); assertUploadsAreDecoded(decoded.uploads()); assertCommonPrefixesAreDecoded(decoded.commonPrefixes()); } @Test public void encodingTypeNotSet_doesNotDecodeListObjectsResponseParts() { ListObjectsResponse original = V1_TEST_ENCODED_RESPONSE.toBuilder() .encodingType((String) null) .build(); Context.ModifyResponse ctx = newContext(original); ListObjectsResponse fromInterceptor = (ListObjectsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes()); assertThat(fromInterceptor).isEqualTo(original); } @Test public void encodingTypeNotSet_doesNotDecodeListObjectsV2ResponseParts() { ListObjectsV2Response original = V2_TEST_ENCODED_RESPONSE.toBuilder() .encodingType((String) null) .build(); Context.ModifyResponse ctx = newContext(original); ListObjectsV2Response fromInterceptor = (ListObjectsV2Response) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes()); assertThat(fromInterceptor).isEqualTo(original); } @Test public void otherResponses_shouldNotModifyResponse() { HeadObjectResponse original = HeadObjectResponse.builder().build(); Context.ModifyResponse ctx = newContext(original); SdkResponse sdkResponse = INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes()); assertThat(original.hashCode()).isEqualTo(sdkResponse.hashCode()); }
StaticImmutableTableSchema implements TableSchema<T> { @Override public EnhancedType<T> itemType() { return this.itemType; } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }
@Test public void itemType_returnsCorrectClass() { assertThat(FakeItem.getTableSchema().itemType(), is(equalTo(EnhancedType.of(FakeItem.class)))); }
StaticImmutableTableSchema implements TableSchema<T> { @Override public StaticTableMetadata tableMetadata() { return tableMetadata; } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }
@Test public void getTableMetadata_hasCorrectFields() { TableMetadata tableMetadata = FakeItemWithSort.getTableSchema().tableMetadata(); assertThat(tableMetadata.primaryPartitionKey(), is("id")); assertThat(tableMetadata.primarySortKey(), is(Optional.of("sort"))); }
StaticImmutableTableSchema implements TableSchema<T> { @Override public Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeMappers.forEach(attributeMapper -> { String attributeKey = attributeMapper.attributeName(); AttributeValue attributeValue = attributeMapper.attributeGetterMethod().apply(item); if (!ignoreNulls || !isNullAttributeValue(attributeValue)) { attributeValueMap.put(attributeKey, attributeValue); } }); indexedFlattenedMappers.forEach((name, flattenedMapper) -> { attributeValueMap.putAll(flattenedMapper.itemToMap(item, ignoreNulls)); }); return unmodifiableMap(attributeValueMap); } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }
@Test public void itemToMap_returnsCorrectMapWithMultipleAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema().itemToMap(FAKE_ITEM, false); assertThat(attributeMap.size(), is(3)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_primitive_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); } @Test public void itemToMap_filtersAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema() .itemToMap(FAKE_ITEM, asList("a_boolean", "a_string")); assertThat(attributeMap.size(), is(2)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); } @Test(expected = IllegalArgumentException.class) public void itemToMap_attributeNotFound_throwsIllegalArgumentException() { createSimpleTableSchema().itemToMap(FAKE_ITEM, singletonList("unknown_key")); }
StaticImmutableTableSchema implements TableSchema<T> { @Override public T mapToItem(Map<String, AttributeValue> attributeMap) { B builder = null; Map<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> flattenedAttributeValuesMap = new LinkedHashMap<>(); for (Map.Entry<String, AttributeValue> entry : attributeMap.entrySet()) { String key = entry.getKey(); AttributeValue value = entry.getValue(); if (!isNullAttributeValue(value)) { ResolvedImmutableAttribute<T, B> attributeMapper = indexedMappers.get(key); if (attributeMapper != null) { if (builder == null) { builder = constructNewBuilder(); } attributeMapper.updateItemMethod().accept(builder, value); } else { FlattenedMapper<T, B, ?> flattenedMapper = this.indexedFlattenedMappers.get(key); if (flattenedMapper != null) { Map<String, AttributeValue> flattenedAttributeValues = flattenedAttributeValuesMap.get(flattenedMapper); if (flattenedAttributeValues == null) { flattenedAttributeValues = new HashMap<>(); } flattenedAttributeValues.put(key, value); flattenedAttributeValuesMap.put(flattenedMapper, flattenedAttributeValues); } } } } for (Map.Entry<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> entry : flattenedAttributeValuesMap.entrySet()) { builder = entry.getKey().mapToItem(builder, this::constructNewBuilder, entry.getValue()); } return builder == null ? null : buildItemFunction.apply(builder); } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }
@Test public void mapToItem_returnsCorrectItemWithMultipleAttributes() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_S); FakeMappedItem fakeMappedItem = createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); assertThat(fakeMappedItem, is(FAKE_ITEM)); } @Test public void mapToItem_unknownAttributes_doNotCauseErrors() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("unknown_attribute", ATTRIBUTE_VALUE_S); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); } @Test(expected = IllegalArgumentException.class) public void mapToItem_attributesWrongType_throwsException() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_B); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); }
StaticImmutableTableSchema implements TableSchema<T> { public static <T, B> Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass) { return new Builder<>(itemClass, builderClass); } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }
@Test public void mapperCanHandleEnum() { verifyNullableAttribute(EnhancedType.of(FakeMappedItem.TestEnum.class), a -> a.name("value") .getter(FakeMappedItem::getTestEnum) .setter(FakeMappedItem::setTestEnum), FakeMappedItem.builder().testEnum(FakeMappedItem.TestEnum.ONE).build(), AttributeValue.builder().s("ONE").build()); } @Test public void mapperCanHandleDocument() { FakeDocument fakeDocument = FakeDocument.of("test-123", 123); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("documentInteger", AttributeValue.builder().n("123").build()); expectedMap.put("documentString", AttributeValue.builder().s("test-123").build()); verifyNullableAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().aFakeDocument(fakeDocument).build(), AttributeValue.builder().m(expectedMap).build()); } @Test public void mapperCanHandleDocumentWithNullValues() { verifyNullAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().build()); } @Test public void mapperCanHandleInteger() { verifyNullableAttribute(EnhancedType.of(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnInteger) .setter(FakeMappedItem::setAnInteger), FakeMappedItem.builder().anInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveInteger() { verifyAttribute(EnhancedType.of(int.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveInteger) .setter(FakeMappedItem::setAPrimitiveInteger), FakeMappedItem.builder().aPrimitiveInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleBoolean() { verifyNullableAttribute(EnhancedType.of(Boolean.class), a -> a.name("value") .getter(FakeMappedItem::getABoolean) .setter(FakeMappedItem::setABoolean), FakeMappedItem.builder().aBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandlePrimitiveBoolean() { verifyAttribute(EnhancedType.of(boolean.class), a -> a.name("value") .getter(FakeMappedItem::isAPrimitiveBoolean) .setter(FakeMappedItem::setAPrimitiveBoolean), FakeMappedItem.builder().aPrimitiveBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandleString() { verifyNullableAttribute(EnhancedType.of(String.class), a -> a.name("value") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString), FakeMappedItem.builder().aString("onetwothree").build(), AttributeValue.builder().s("onetwothree").build()); } @Test public void mapperCanHandleLong() { verifyNullableAttribute(EnhancedType.of(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALong) .setter(FakeMappedItem::setALong), FakeMappedItem.builder().aLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveLong() { verifyAttribute(EnhancedType.of(long.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveLong) .setter(FakeMappedItem::setAPrimitiveLong), FakeMappedItem.builder().aPrimitiveLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleShort() { verifyNullableAttribute(EnhancedType.of(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShort) .setter(FakeMappedItem::setAShort), FakeMappedItem.builder().aShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveShort() { verifyAttribute(EnhancedType.of(short.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveShort) .setter(FakeMappedItem::setAPrimitiveShort), FakeMappedItem.builder().aPrimitiveShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleByte() { verifyNullableAttribute(EnhancedType.of(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByte) .setter(FakeMappedItem::setAByte), FakeMappedItem.builder().aByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveByte() { verifyAttribute(EnhancedType.of(byte.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveByte) .setter(FakeMappedItem::setAPrimitiveByte), FakeMappedItem.builder().aPrimitiveByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleDouble() { verifyNullableAttribute(EnhancedType.of(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADouble) .setter(FakeMappedItem::setADouble), FakeMappedItem.builder().aDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveDouble() { verifyAttribute(EnhancedType.of(double.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveDouble) .setter(FakeMappedItem::setAPrimitiveDouble), FakeMappedItem.builder().aPrimitiveDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleFloat() { verifyNullableAttribute(EnhancedType.of(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloat) .setter(FakeMappedItem::setAFloat), FakeMappedItem.builder().aFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveFloat() { verifyAttribute(EnhancedType.of(float.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveFloat) .setter(FakeMappedItem::setAPrimitiveFloat), FakeMappedItem.builder().aPrimitiveFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleBinary() { SdkBytes sdkBytes = SdkBytes.fromString("test", UTF_8); verifyNullableAttribute(EnhancedType.of(SdkBytes.class), a -> a.name("value") .getter(FakeMappedItem::getABinaryValue) .setter(FakeMappedItem::setABinaryValue), FakeMappedItem.builder().aBinaryValue(sdkBytes).build(), AttributeValue.builder().b(sdkBytes).build()); } @Test public void mapperCanHandleSimpleList() { verifyNullableAttribute(EnhancedType.listOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerList) .setter(FakeMappedItem::setAnIntegerList), FakeMappedItem.builder().anIntegerList(asList(1, 2, 3)).build(), AttributeValue.builder().l(asList(AttributeValue.builder().n("1").build(), AttributeValue.builder().n("2").build(), AttributeValue.builder().n("3").build())).build()); } @Test public void mapperCanHandleNestedLists() { FakeMappedItem fakeMappedItem = FakeMappedItem.builder() .aNestedStructure(singletonList(singletonList(FakeDocument.of("nested", null)))) .build(); Map<String, AttributeValue> documentMap = new HashMap<>(); documentMap.put("documentString", AttributeValue.builder().s("nested").build()); documentMap.put("documentInteger", AttributeValue.builder().nul(true).build()); AttributeValue attributeValue = AttributeValue.builder() .l(singletonList(AttributeValue.builder() .l(AttributeValue.builder().m(documentMap).build()) .build())) .build(); verifyNullableAttribute( EnhancedType.listOf(EnhancedType.listOf(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA))), a -> a.name("value") .getter(FakeMappedItem::getANestedStructure) .setter(FakeMappedItem::setANestedStructure), fakeMappedItem, attributeValue); } @Test public void mapperCanHandleIntegerSet() { Set<Integer> valueSet = new HashSet<>(asList(1, 2, 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerSet) .setter(FakeMappedItem::setAnIntegerSet), FakeMappedItem.builder().anIntegerSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleStringSet() { Set<String> valueSet = new HashSet<>(asList("one", "two", "three")); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringSet) .setter(FakeMappedItem::setAStringSet), FakeMappedItem.builder().aStringSet(valueSet).build(), AttributeValue.builder().ss(expectedList).build()); } @Test public void mapperCanHandleLongSet() { Set<Long> valueSet = new HashSet<>(asList(1L, 2L, 3L)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALongSet) .setter(FakeMappedItem::setALongSet), FakeMappedItem.builder().aLongSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleShortSet() { Set<Short> valueSet = new HashSet<>(asList((short) 1, (short) 2, (short) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShortSet) .setter(FakeMappedItem::setAShortSet), FakeMappedItem.builder().aShortSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleByteSet() { Set<Byte> valueSet = new HashSet<>(asList((byte) 1, (byte) 2, (byte) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByteSet) .setter(FakeMappedItem::setAByteSet), FakeMappedItem.builder().aByteSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleDoubleSet() { Set<Double> valueSet = new HashSet<>(asList(1.2, 3.4, 5.6)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADoubleSet) .setter(FakeMappedItem::setADoubleSet), FakeMappedItem.builder().aDoubleSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleFloatSet() { Set<Float> valueSet = new HashSet<>(asList(1.2f, 3.4f, 5.6f)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloatSet) .setter(FakeMappedItem::setAFloatSet), FakeMappedItem.builder().aFloatSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleGenericMap() { Map<String, String> stringMap = new ConcurrentHashMap<>(); stringMap.put("one", "two"); stringMap.put("three", "four"); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("one", AttributeValue.builder().s("two").build()); attributeValueMap.put("three", AttributeValue.builder().s("four").build()); verifyNullableAttribute(EnhancedType.mapOf(String.class, String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringMap) .setter(FakeMappedItem::setAStringMap), FakeMappedItem.builder().aStringMap(stringMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void mapperCanHandleIntDoubleMap() { Map<Integer, Double> intDoubleMap = new ConcurrentHashMap<>(); intDoubleMap.put(1, 1.0); intDoubleMap.put(2, 3.0); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("1", AttributeValue.builder().n("1.0").build()); attributeValueMap.put("2", AttributeValue.builder().n("3.0").build()); verifyNullableAttribute(EnhancedType.mapOf(Integer.class, Double.class), a -> a.name("value") .getter(FakeMappedItem::getAIntDoubleMap) .setter(FakeMappedItem::setAIntDoubleMap), FakeMappedItem.builder().aIntDoubleMap(intDoubleMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void instantiateFlattenedAbstractClassShouldThrowException() { StaticTableSchema<FakeAbstractSuperclass> superclassTableSchema = StaticTableSchema.builder(FakeAbstractSuperclass.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeAbstractSuperclass::getAString) .setter(FakeAbstractSuperclass::setAString)) .build(); exception.expect(IllegalArgumentException.class); exception.expectMessage("abstract"); StaticTableSchema.builder(FakeBrokenClass.class) .newItemSupplier(FakeBrokenClass::new) .flatten(superclassTableSchema, FakeBrokenClass::getAbstractObject, FakeBrokenClass::setAbstractObject); } @Test public void noConverterProvider_throwsException_whenMissingAttributeConverters() { exception.expect(NullPointerException.class); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(Collections.emptyList()) .build(); }
S3Utilities { public static Builder builder() { return new Builder(); } private S3Utilities(Builder builder); static Builder builder(); URL getUrl(Consumer<GetUrlRequest.Builder> getUrlRequest); URL getUrl(GetUrlRequest getUrlRequest); }
@Test (expected = NullPointerException.class) public void failIfRegionIsNotSetOnS3UtilitiesObject() throws MalformedURLException { S3Utilities.builder().build(); }
StaticAttribute { public Builder<T, R> toBuilder() { return new Builder<>(this.delegateAttribute.toBuilder()); } private StaticAttribute(Builder<T, R> builder); static Builder<T, R> builder(Class<T> itemClass, EnhancedType<R> attributeType); static Builder<T, R> builder(Class<T> itemClass, Class<R> attributeClass); String name(); Function<T, R> getter(); BiConsumer<T, R> setter(); Collection<StaticAttributeTag> tags(); EnhancedType<R> type(); AttributeConverter<R> attributeConverter(); Builder<T, R> toBuilder(); }
@Test public void toBuilder() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag, mockTag2) .attributeConverter(attributeConverter) .build(); StaticAttribute<Object, String> clonedAttribute = staticAttribute.toBuilder().build(); assertThat(clonedAttribute.name()).isEqualTo("test-attribute"); assertThat(clonedAttribute.getter()).isSameAs(TEST_GETTER); assertThat(clonedAttribute.setter()).isSameAs(TEST_SETTER); assertThat(clonedAttribute.tags()).containsExactly(mockTag, mockTag2); assertThat(clonedAttribute.type()).isEqualTo(EnhancedType.of(String.class)); assertThat(clonedAttribute.attributeConverter()).isSameAs(attributeConverter); }
StaticTableMetadata implements TableMetadata { public static Builder builder() { return new Builder(); } private StaticTableMetadata(Builder builder); static Builder builder(); @Override Optional<T> customMetadataObject(String key, Class<? extends T> objectClass); @Override String indexPartitionKey(String indexName); @Override Optional<String> indexSortKey(String indexName); @Override Collection<String> indexKeys(String indexName); @Override Collection<String> allKeys(); @Override Collection<IndexMetadata> indices(); @Override Map<String, Object> customMetadata(); @Override Collection<KeyAttributeMetadata> keyAttributes(); @Override Optional<ScalarAttributeType> scalarAttributeType(String keyAttribute); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void setAndRetrievePrimaryPartitionKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.primaryPartitionKey(), is(ATTRIBUTE_NAME)); } @Test public void setAndRetrievePrimarySortKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexSortKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.primarySortKey(), is(Optional.of(ATTRIBUTE_NAME))); } @Test(expected = IllegalArgumentException.class) public void retrieveUnsetPrimaryPartitionKey() { TableMetadata tableMetadata = StaticTableMetadata.builder().build(); tableMetadata.primaryPartitionKey(); } @Test(expected = IllegalArgumentException.class) public void retrieveUnsetPrimaryPartitionKey_withSortKeySet() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexSortKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); tableMetadata.primaryPartitionKey(); } @Test public void retrieveUnsetPrimarySortKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.primarySortKey(), is(Optional.empty())); } @Test(expected = IllegalArgumentException.class) public void setSamePartitionKeyTwice() { StaticTableMetadata.builder() .addIndexPartitionKey("idx", "id", AttributeValueType.S) .addIndexPartitionKey("idx", "id", AttributeValueType.S) .build(); } @Test(expected = IllegalArgumentException.class) public void setSameSortKeyTwice() { StaticTableMetadata.builder() .addIndexSortKey("idx", "id", AttributeValueType.S) .addIndexSortKey("idx", "id", AttributeValueType.S) .build(); } @Test public void getPrimaryKeys_partitionAndSort() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); assertThat(tableMetadata.primaryKeys(), containsInAnyOrder("primary_id", "primary_sort")); } @Test public void getPrimaryKeys_partition() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); assertThat(tableMetadata.primaryKeys(), contains("primary_id")); } @Test(expected = IllegalArgumentException.class) public void getPrimaryKeys_unset() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); tableMetadata.primaryKeys(); } @Test public void mergeFullIntoEmpty() { StaticTableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .addCustomMetadataObject("custom1", "value1") .addCustomMetadataObject("custom2", "value2") .build(); StaticTableMetadata mergedTableMetadata = StaticTableMetadata.builder().mergeWith(tableMetadata).build(); assertThat(mergedTableMetadata, is(tableMetadata)); } @Test public void mergeEmptyIntoFull() { StaticTableMetadata emptyTableMetadata = StaticTableMetadata.builder().build(); StaticTableMetadata.Builder tableMetadataBuilder = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .addCustomMetadataObject("custom1", "value1") .addCustomMetadataObject("custom2", "value2"); StaticTableMetadata original = tableMetadataBuilder.build(); StaticTableMetadata merged = tableMetadataBuilder.mergeWith(emptyTableMetadata).build(); assertThat(merged, is(original)); } @Test public void mergeWithDuplicateIndexPartitionKey() { StaticTableMetadata.Builder builder = StaticTableMetadata.builder().addIndexPartitionKey(INDEX_NAME, "id", AttributeValueType.S); exception.expect(IllegalArgumentException.class); exception.expectMessage("partition key"); exception.expectMessage(INDEX_NAME); builder.mergeWith(builder.build()); } @Test public void mergeWithDuplicateIndexSortKey() { StaticTableMetadata.Builder builder = StaticTableMetadata.builder().addIndexSortKey(INDEX_NAME, "id", AttributeValueType.S); exception.expect(IllegalArgumentException.class); exception.expectMessage("sort key"); exception.expectMessage(INDEX_NAME); builder.mergeWith(builder.build()); } @Test public void mergeWithDuplicateCustomMetadata() { StaticTableMetadata.Builder builder = StaticTableMetadata.builder().addCustomMetadataObject(INDEX_NAME, "id"); exception.expect(IllegalArgumentException.class); exception.expectMessage("custom metadata"); exception.expectMessage(INDEX_NAME); builder.mergeWith(builder.build()); }
EnableTrailingChecksumInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerRequest(context.request(), executionAttributes)) { return context.httpRequest().toBuilder().putHeader(ENABLE_CHECKSUM_REQUEST_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE) .build(); } return context.httpRequest(); } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes); @Override SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes); }
@Test public void modifyHttpRequest_getObjectTrailingChecksumEnabled_shouldAddTrailingChecksumHeader() { Context.ModifyHttpRequest modifyHttpRequestContext = modifyHttpRequestContext(GetObjectRequest.builder().build()); SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes()); assertThat(sdkHttpRequest.headers().get(ENABLE_CHECKSUM_REQUEST_HEADER)).containsOnly(ENABLE_MD5_CHECKSUM_HEADER_VALUE); } @Test public void modifyHttpRequest_getObjectTrailingChecksumDisabled_shouldNotModifyHttpRequest() { Context.ModifyHttpRequest modifyHttpRequestContext = modifyHttpRequestContext(GetObjectRequest.builder().build()); SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG, S3Configuration.builder().checksumValidationEnabled(false).build())); assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest()); } @Test public void modifyHttpRequest_nonGetObjectRequest_shouldNotModifyHttpRequest() { Context.ModifyHttpRequest modifyHttpRequestContext = modifyHttpRequestContext(PutObjectRequest.builder().build()); SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes()); assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest()); }
Key { public Optional<AttributeValue> sortKeyValue() { return Optional.ofNullable(sortValue); } private Key(Builder builder); static Builder builder(); Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index); AttributeValue partitionKeyValue(); Optional<AttributeValue> sortKeyValue(); Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getSortKeyValue_partitionOnly() { assertThat(partitionOnlyKey.sortKeyValue(), is(Optional.empty())); }
Key { public Builder toBuilder() { return new Builder().partitionValue(this.partitionValue).sortValue(this.sortValue); } private Key(Builder builder); static Builder builder(); Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index); AttributeValue partitionKeyValue(); Optional<AttributeValue> sortKeyValue(); Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void toBuilder() { Key keyClone = key.toBuilder().build(); assertThat(key, is(equalTo(keyClone))); }
Key { public static Builder builder() { return new Builder(); } private Key(Builder builder); static Builder builder(); Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index); AttributeValue partitionKeyValue(); Optional<AttributeValue> sortKeyValue(); Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void nullPartitionKey_shouldThrowException() { AttributeValue attributeValue = null; assertThatThrownBy(() -> Key.builder().partitionValue(attributeValue).build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null"); assertThatThrownBy(() -> Key.builder().partitionValue(AttributeValue.builder().nul(true).build()).build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null"); }
ImmutableIntrospector { public static <T> ImmutableInfo<T> getImmutableInfo(Class<T> immutableClass) { if (INSTANCE == null) { synchronized (ImmutableIntrospector.class) { if (INSTANCE == null) { INSTANCE = new ImmutableIntrospector(); } } } return INSTANCE.introspect(immutableClass); } private ImmutableIntrospector(); static ImmutableInfo<T> getImmutableInfo(Class<T> immutableClass); }
@Test public void simpleImmutableMixedStyle() { ImmutableInfo<SimpleImmutableMixedStyle> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableMixedStyle.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableMixedStyle.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableMixedStyle.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableMixedStyle.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasSize(3); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("attribute1"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("attribute2"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(Integer.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(Integer.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("attribute3"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(Boolean.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(Boolean.class); }); } @Test public void simpleImmutableWithPrimitives() { ImmutableInfo<SimpleImmutableWithPrimitives> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithPrimitives.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithPrimitives.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithPrimitives.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithPrimitives.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } @Test public void simpleImmutableWithTrickyNames() { ImmutableInfo<SimpleImmutableWithTrickyNames> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithTrickyNames.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithTrickyNames.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithTrickyNames.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithTrickyNames.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasSize(3); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("isAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("getAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("setAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); } @Test public void immutableWithNoMatchingSetter() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("matching setter"); ImmutableIntrospector.getImmutableInfo(ImmutableWithNoMatchingSetter.class); } @Test public void immutableWithGetterParams() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("getter"); exception.expectMessage("parameters"); ImmutableIntrospector.getImmutableInfo(ImmutableWithGetterParams.class); } @Test public void immutableWithVoidAttribute() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("getter"); exception.expectMessage("void"); ImmutableIntrospector.getImmutableInfo(ImmutableWithVoidAttribute.class); } @Test public void immutableWithNoMatchingGetter() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("matching getter"); ImmutableIntrospector.getImmutableInfo(ImmutableWithNoMatchingGetter.class); } @Test public void immutableWithNoBuildMethod() { exception.expect(IllegalArgumentException.class); exception.expectMessage("build"); ImmutableIntrospector.getImmutableInfo(ImmutableWithNoBuildMethod.class); } @Test public void immutableWithWrongSetter() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("matching setter"); ImmutableIntrospector.getImmutableInfo(ImmutableWithWrongSetter.class); } @Test public void immutableWithWrongBuildType() { exception.expect(IllegalArgumentException.class); exception.expectMessage("build"); ImmutableIntrospector.getImmutableInfo(ImmutableWithWrongBuildType.class); } @Test public void immutableMissingAnnotation() { exception.expect(IllegalArgumentException.class); exception.expectMessage("@DynamoDbImmutable"); ImmutableIntrospector.getImmutableInfo(ImmutableMissingAnnotation.class); } @Test public void simpleImmutableWithIgnoredGetter() { ImmutableInfo<SimpleImmutableWithIgnoredGetter> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithIgnoredGetter.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithIgnoredGetter.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithIgnoredGetter.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithIgnoredGetter.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } @Test public void simpleImmutableWithIgnoredSetter() { ImmutableInfo<SimpleImmutableWithIgnoredSetter> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithIgnoredSetter.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithIgnoredSetter.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithIgnoredSetter.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithIgnoredSetter.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } @Test public void extendedImmutable() { ImmutableInfo<ExtendedImmutable> immutableInfo = ImmutableIntrospector.getImmutableInfo(ExtendedImmutable.class); assertThat(immutableInfo.immutableClass()).isSameAs(ExtendedImmutable.class); assertThat(immutableInfo.builderClass()).isSameAs(ExtendedImmutable.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(ExtendedImmutable.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasSize(2); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("baseAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("childAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } @Test public void immutableWithPrimitiveBoolean() { ImmutableInfo<ImmutableWithPrimitiveBoolean> immutableInfo = ImmutableIntrospector.getImmutableInfo(ImmutableWithPrimitiveBoolean.class); assertThat(immutableInfo.immutableClass()).isSameAs(ImmutableWithPrimitiveBoolean.class); assertThat(immutableInfo.builderClass()).isSameAs(ImmutableWithPrimitiveBoolean.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(ImmutableWithPrimitiveBoolean.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(boolean.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(boolean.class); }); } @Test public void immutableWithStaticBuilder() { ImmutableInfo<ImmutableWithStaticBuilder> immutableInfo = ImmutableIntrospector.getImmutableInfo(ImmutableWithStaticBuilder.class); assertThat(immutableInfo.immutableClass()).isSameAs(ImmutableWithStaticBuilder.class); assertThat(immutableInfo.builderClass()).isSameAs(ImmutableWithStaticBuilder.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(ImmutableWithStaticBuilder.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()) .hasValueSatisfying(m -> assertThat(m.getName()).isEqualTo("builder")); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(boolean.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(boolean.class); }); }
ApplyUserAgentInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { if (!(context.request() instanceof DynamoDbRequest)) { return context.request(); } DynamoDbRequest request = (DynamoDbRequest) context.request(); AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration().map(c -> c.toBuilder() .applyMutation(USER_AGENT_APPLIER) .build()) .orElse((AwsRequestOverrideConfiguration.builder() .applyMutation(USER_AGENT_APPLIER) .build())); return request.toBuilder().overrideConfiguration(overrideConfiguration).build(); } @Override SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes); }
@Test public void ddbRequest_shouldModifyRequest() { GetItemRequest getItemRequest = GetItemRequest.builder().build(); SdkRequest sdkRequest = interceptor.modifyRequest(() -> getItemRequest, new ExecutionAttributes()); RequestOverrideConfiguration requestOverrideConfiguration = sdkRequest.overrideConfiguration().get(); assertThat(requestOverrideConfiguration.apiNames() .stream() .filter(a -> a.name() .equals("hll") && a.version().equals("ddb-enh")).findAny()) .isPresent(); } @Test public void otherRequest_shouldNotModifyRequest() { SdkRequest someOtherRequest = new SdkRequest() { @Override public List<SdkField<?>> sdkFields() { return null; } @Override public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() { return Optional.empty(); } @Override public Builder toBuilder() { return null; } }; SdkRequest sdkRequest = interceptor.modifyRequest(() -> someOtherRequest, new ExecutionAttributes()); assertThat(sdkRequest).isEqualTo(someOtherRequest); }