method2testcases
stringlengths 118
6.63k
|
---|
### Question:
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); FsImageData load(RandomAccessFile file); }### Answer:
@Test public void testLoadHadoop27xFsImage() throws IOException { try (RandomAccessFile file = new RandomAccessFile("src/test/resources/fsi_small_h2x.img", "r")) { final FsImageData hadoopV2xImage = new FsImageLoader.Builder().parallel().build().load(file); loadAndVisit(hadoopV2xImage, new FsVisitor.Builder()); } }
@Test public void testLoadHadoop33xCompressedFsImage() throws IOException { try (RandomAccessFile file = new RandomAccessFile("src/test/resources/fsimage_d800_f210k_compressed.img", "r")) { final FsImageData hadoopV3xCompressedImage = new FsImageLoader.Builder().parallel().build().load(file); final CountingVisitor visitor = new CountingVisitor(hadoopV3xCompressedImage); new FsVisitor.Builder().parallel().visit(hadoopV3xCompressedImage, visitor); assertThat(visitor.groups.size()).isEqualTo(1); assertThat(visitor.users.size()).isEqualTo(1); assertThat(visitor.numFiles.get()).isEqualTo(209560L); assertThat(visitor.numDirs.get()).isEqualTo(807L); assertThat(visitor.numSymLinks.get()).isEqualTo(0L); } }
@Test public void testLoadEmptyFSImage() throws IOException { try (RandomAccessFile file = new RandomAccessFile("src/test/resources/fsimage_0000000000000000000", "r")) { final FsImageData emptyImage = new FsImageLoader.Builder().build().load(file); AtomicBoolean rootVisited = new AtomicBoolean(false); new FsVisitor.Builder().visit(emptyImage, new FsVisitor() { @Override public void onFile(FsImageProto.INodeSection.INode inode, String path) { } @Override public void onDirectory(FsImageProto.INodeSection.INode inode, String path) { rootVisited.set(ROOT_PATH.equals(path)); } @Override public void onSymLink(FsImageProto.INodeSection.INode inode, String path) { } }); assertThat(rootVisited).isTrue(); } } |
### Question:
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } @Override void run(); }### Answer:
@Test public void testRun() { PathReportCommand pathReportCommand = new PathReportCommand(); pathReportCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { pathReportCommand.mainCommand.out = printStream; pathReportCommand.mainCommand.err = pathReportCommand.mainCommand.out; pathReportCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); pathReportCommand.run(); final String actualStdout = byteArrayOutputStream.toString(); assertThat(actualStdout) .isEqualTo("\n" + "Path report (path=/, no filter) :\n" + "---------------------------------\n" + "\n" + "11 files, 8 directories and 0 symlinks\n" + "\n" + "drwxr-xr-x mm supergroup /\n" + "drwxr-xr-x mm supergroup /test1\n" + "drwxr-xr-x mm supergroup /test2\n" + "drwxr-xr-x mm supergroup /test3\n" + "drwxr-xr-x mm supergroup /test3/foo\n" + "drwxr-xr-x mm supergroup /test3/foo/bar\n" + "-rw-r--r-- mm nobody /test3/foo/bar/test_20MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_2MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_40MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_4MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_5MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_80MiB.img\n" + "-rw-r--r-- root root /test3/foo/test_1KiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/test_20MiB.img\n" + "-rw-r--r-- mm supergroup /test3/test.img\n" + "-rw-r--r-- foo nobody /test3/test_160MiB.img\n" + "-rw-r--r-- mm supergroup /test_2KiB.img\n" + "drwxr-xr-x mm supergroup /user\n" + "drwxr-xr-x mm supergroup /user/mm\n" ); } }
@Test public void testRunWithFilterForUserFoo() { PathReportCommand pathReportCommand = new PathReportCommand(); pathReportCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { pathReportCommand.mainCommand.out = printStream; pathReportCommand.mainCommand.err = printStream; pathReportCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); pathReportCommand.mainCommand.userNameFilter = "foo"; pathReportCommand.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo("\n" + "Path report (path=/, user=~foo) :\n" + "---------------------------------\n" + "\n" + "1 file, 0 directories and 0 symlinks\n" + "\n" + "-rw-r--r-- foo nobody /test3/test_160MiB.img\n" ); } } |
### Question:
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } static void main(String[] args); }### Answer:
@Test public void testVersion() { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); HdfsFSImageTool.out = new PrintStream(byteArrayOutputStream); HdfsFSImageTool.err = HdfsFSImageTool.out; HdfsFSImageTool.run(new String[]{"-V"}); Pattern pattern = Pattern.compile("Version 1\\..*\n" + "Build timestamp 20.*\n" + "SCM Version .*\n" + "SCM Branch .*\n"); assertThat(byteArrayOutputStream.toString()) .matches(pattern); }
@Test public void testHelp() { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); HdfsFSImageTool.out = new PrintStream(byteArrayOutputStream); HdfsFSImageTool.err = HdfsFSImageTool.out; HdfsFSImageTool.run(new String[]{"-h"}); assertThat(byteArrayOutputStream.toString()) .isEqualTo("Analyze Hadoop FSImage file for user/group reports\n" + "Usage: hfsa-tool [-hVv] [-fun=<userNameFilter>] [-p=<dirs>[,<dirs>...]]... FILE\n" + " [COMMAND]\n" + " FILE FSImage file to process.\n" + " -fun, --filter-by-user=<userNameFilter>\n" + " Filter user name by <regexp>.\n" + " -h, --help Show this help message and exit.\n" + " -p, --path=<dirs>[,<dirs>...]\n" + " Directory path(s) to start traversing (default: [/]).\n" + " Default: [/]\n" + " -v Turns on verbose output. Use `-vv` for debug output.\n" + " -V, --version Print version information and exit.\n" + "Commands:\n" + " summary Generates an HDFS usage summary (default command if no other\n" + " command specified)\n" + " smallfiles, sf Reports on small file usage\n" + " inode, i Shows INode details\n" + " path, p Lists INode paths\n" + "Runs summary command by default.\n" ); } |
### Question:
SummaryReportCommand extends AbstractReportCommand { static List<UserStats> filterByUserName(Collection<UserStats> userStats, String userNamePattern) { List<UserStats> filtered = new ArrayList<>(userStats); if (null != userNamePattern && !userNamePattern.isEmpty()) { Pattern pattern = Pattern.compile(userNamePattern); filtered.removeIf(u -> !pattern.matcher(u.userName).find()); } return filtered; } @Override void run(); }### Answer:
@Test public void testFilter() { final List<UserStats> list = Arrays.asList(new UserStats("foobar"), new UserStats("foo_bar"), new UserStats("fo_obar"), new UserStats("nofoobar")); String userNameFilter = "^foo.*"; List<UserStats> filtered = filterByUserName(list, userNameFilter); assertThat(filtered.size()).isEqualTo(2); assertThat(filtered.get(0).userName).isEqualTo("foobar"); assertThat(filtered.get(1).userName).isEqualTo("foo_bar"); userNameFilter = "foo.*"; filtered = filterByUserName(list, userNameFilter); assertThat(filtered).extracting(userStats -> userStats.userName) .isEqualTo(Arrays.asList("foobar", "foo_bar", "nofoobar")); userNameFilter = ".*bar.*"; filtered = filterByUserName(list, userNameFilter); assertThat(filtered).isEqualTo(list); } |
### Question:
InodeInfoCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String inodeId : inodeIds) { showInodeDetails(fsImageData, inodeId); } } } @Override void run(); }### Answer:
@Test public void testRun() { InodeInfoCommand infoCommand = new InodeInfoCommand(); infoCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { infoCommand.mainCommand.out = printStream; infoCommand.mainCommand.err = infoCommand.mainCommand.out; infoCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); infoCommand.inodeIds = new String[]{"/", "/test3", "/test3/test_160MiB.img", "16387"}; infoCommand.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo( "type: DIRECTORY\n" + "id: 16385\n" + "name: \"\"\n" + "directory {\n" + " modificationTime: 1499493618390\n" + " nsQuota: 9223372036854775807\n" + " dsQuota: 18446744073709551615\n" + " permission: 1099511759341\n" + "}\n" + "\n" + "type: DIRECTORY\n" + "id: 16388\n" + "name: \"test3\"\n" + "directory {\n" + " modificationTime: 1497734744891\n" + " nsQuota: 18446744073709551615\n" + " dsQuota: 18446744073709551615\n" + " permission: 1099511759341\n" + "}\n" + "\n" + "type: FILE\n" + "id: 16402\n" + "name: \"test_160MiB.img\"\n" + "file {\n" + " replication: 1\n" + " modificationTime: 1497734744886\n" + " accessTime: 1497734743534\n" + " preferredBlockSize: 134217728\n" + " permission: 5497558401444\n" + " blocks {\n" + " blockId: 1073741834\n" + " genStamp: 1010\n" + " numBytes: 134217728\n" + " }\n" + " blocks {\n" + " blockId: 1073741835\n" + " genStamp: 1011\n" + " numBytes: 33554432\n" + " }\n" + " storagePolicyID: 0\n" + "}\n" + "\n" + "type: DIRECTORY\n" + "id: 16387\n" + "name: \"test2\"\n" + "directory {\n" + " modificationTime: 1497733426149\n" + " nsQuota: 18446744073709551615\n" + " dsQuota: 18446744073709551615\n" + " permission: 1099511759341\n" + "}\n" + "\n" ); } } |
### Question:
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); validateTerm(term); return ResponseEntity.ok( new DomainInfoResponse().items(cohortBuilderService.findDomainInfos(term))); } @Autowired CohortBuilderController(
CdrVersionService cdrVersionService,
ElasticSearchService elasticSearchService,
Provider<WorkbenchConfig> configProvider,
CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete(
Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue(
Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId(
Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm(
Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions(
Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId(
Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo(
Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId(
Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy(
Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId(
Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId(
Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }### Answer:
@Test public void findDomainInfos() { cbCriteriaDao.save( DbCriteria.builder() .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD9CM.toString()) .addCount(0L) .addHierarchy(true) .addStandard(false) .addParentId(0) .addFullText("term*[CONDITION_rank1]") .build()); DbDomainInfo dbDomainInfo = domainInfoDao.save( new DbDomainInfo() .conceptId(1L) .domain((short) 0) .domainId("CONDITION") .name("Conditions") .description("descr") .allConceptCount(0) .standardConceptCount(0) .participantCount(1000)); DomainInfo domainInfo = controller.findDomainInfos(1L, "term").getBody().getItems().get(0); assertEquals(domainInfo.getName(), dbDomainInfo.getName()); assertEquals(domainInfo.getDescription(), dbDomainInfo.getDescription()); assertEquals(domainInfo.getParticipantCount().longValue(), dbDomainInfo.getParticipantCount()); assertEquals(domainInfo.getAllConceptCount().longValue(), 1); assertEquals(domainInfo.getStandardConceptCount().longValue(), 0); } |
### Question:
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId( Long cdrVersionId, String domain, Long conceptId) { cdrVersionService.setCdrVersion(cdrVersionId); validateDomain(domain); return ResponseEntity.ok( new CriteriaListResponse() .items( cohortBuilderService.findStandardCriteriaByDomainAndConceptId(domain, conceptId))); } @Autowired CohortBuilderController(
CdrVersionService cdrVersionService,
ElasticSearchService elasticSearchService,
Provider<WorkbenchConfig> configProvider,
CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete(
Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue(
Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId(
Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm(
Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions(
Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId(
Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo(
Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId(
Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy(
Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId(
Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId(
Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }### Answer:
@Test public void findStandardCriteriaByDomainAndConceptId() { jdbcTemplate.execute( "create table cb_criteria_relationship(concept_id_1 integer, concept_id_2 integer)"); jdbcTemplate.execute( "insert into cb_criteria_relationship(concept_id_1, concept_id_2) values (12345, 1)"); DbCriteria criteria = DbCriteria.builder() .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD10CM.toString()) .addStandard(true) .addCount(1L) .addConceptId("1") .addSynonyms("[CONDITION_rank1]") .build(); cbCriteriaDao.save(criteria); assertEquals( createResponseCriteria(criteria), controller .findStandardCriteriaByDomainAndConceptId(1L, DomainType.CONDITION.toString(), 12345L) .getBody() .getItems() .get(0)); jdbcTemplate.execute("drop table cb_criteria_relationship"); } |
### Question:
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId( Long cdrVersionId, Long conceptId) { cdrVersionService.setCdrVersion(cdrVersionId); return ResponseEntity.ok( new CriteriaAttributeListResponse() .items(cohortBuilderService.findCriteriaAttributeByConceptId(conceptId))); } @Autowired CohortBuilderController(
CdrVersionService cdrVersionService,
ElasticSearchService elasticSearchService,
Provider<WorkbenchConfig> configProvider,
CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete(
Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue(
Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId(
Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm(
Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions(
Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId(
Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo(
Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId(
Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy(
Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId(
Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId(
Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }### Answer:
@Test public void findCriteriaAttributeByConceptId() { DbCriteriaAttribute criteriaAttributeMin = cbCriteriaAttributeDao.save( DbCriteriaAttribute.builder() .addConceptId(1L) .addConceptName("MIN") .addEstCount("10") .addType("NUM") .addValueAsConceptId(0L) .build()); DbCriteriaAttribute criteriaAttributeMax = cbCriteriaAttributeDao.save( DbCriteriaAttribute.builder() .addConceptId(1L) .addConceptName("MAX") .addEstCount("100") .addType("NUM") .addValueAsConceptId(0L) .build()); List<CriteriaAttribute> attrs = controller .findCriteriaAttributeByConceptId(1L, criteriaAttributeMin.getConceptId()) .getBody() .getItems(); assertTrue(attrs.contains(createResponseCriteriaAttribute(criteriaAttributeMin))); assertTrue(attrs.contains(createResponseCriteriaAttribute(criteriaAttributeMax))); } |
### Question:
UserMetricsController implements UserMetricsApiDelegate { @Override public ResponseEntity<WorkspaceResource> updateRecentResource( String workspaceNamespace, String workspaceId, RecentResourceRequest recentResourceRequest) { long wId = getWorkspaceId(workspaceNamespace, workspaceId); String notebookPath; if (recentResourceRequest.getNotebookName().startsWith("gs: notebookPath = recentResourceRequest.getNotebookName(); } else { String bucket = fireCloudService .getWorkspace(workspaceNamespace, workspaceId) .getWorkspace() .getBucketName(); notebookPath = "gs: } DbUserRecentResource recentResource = userRecentResourceService.updateNotebookEntry( wId, userProvider.get().getUserId(), notebookPath); return ResponseEntity.ok(TO_CLIENT.apply(recentResource)); } @Autowired UserMetricsController(
Provider<DbUser> userProvider,
Provider<WorkbenchConfig> workbenchConfigProvider,
UserRecentResourceService userRecentResourceService,
WorkspaceService workspaceService,
FireCloudService fireCloudService,
CloudStorageService cloudStorageService,
CommonMappers commonMappers,
FirecloudMapper firecloudMapper); @VisibleForTesting void setDistinctWorkspaceLimit(int limit); @Override ResponseEntity<WorkspaceResource> updateRecentResource(
String workspaceNamespace, String workspaceId, RecentResourceRequest recentResourceRequest); @Override ResponseEntity<EmptyResponse> deleteRecentResource(
String workspaceNamespace, String workspaceId, RecentResourceRequest recentResourceRequest); @Override ResponseEntity<WorkspaceResourceResponse> getUserRecentResources(); @VisibleForTesting boolean hasValidBlobIdIfNotebookNamePresent(DbUserRecentResource dbUserRecentResource); }### Answer:
@Test public void testUpdateRecentResource() { Timestamp now = new Timestamp(fakeClock.instant().toEpochMilli()); DbUserRecentResource mockUserRecentResource = new DbUserRecentResource(); mockUserRecentResource.setCohort(null); mockUserRecentResource.setWorkspaceId(dbWorkspace2.getWorkspaceId()); mockUserRecentResource.setUserId(dbUser.getUserId()); mockUserRecentResource.setNotebookName("gs: mockUserRecentResource.setLastAccessDate(now); when(mockUserRecentResourceService.updateNotebookEntry( dbWorkspace2.getWorkspaceId(), dbUser.getUserId(), "gs: .thenReturn(mockUserRecentResource); RecentResourceRequest request = new RecentResourceRequest(); request.setNotebookName("gs: WorkspaceResource addedEntry = userMetricsController .updateRecentResource( dbWorkspace2.getWorkspaceNamespace(), dbWorkspace2.getFirecloudName(), request) .getBody(); assertNotNull(addedEntry); assertEquals((long) addedEntry.getWorkspaceId(), dbWorkspace2.getWorkspaceId()); assertNull(addedEntry.getCohort()); assertNotNull(addedEntry.getNotebook()); assertEquals(addedEntry.getNotebook().getName(), "notebook.ipynb"); assertEquals(addedEntry.getNotebook().getPath(), "gs: } |
### Question:
UserMetricsController implements UserMetricsApiDelegate { @VisibleForTesting public boolean hasValidBlobIdIfNotebookNamePresent(DbUserRecentResource dbUserRecentResource) { return Optional.ofNullable(dbUserRecentResource.getNotebookName()) .map(name -> uriToBlobId(name).isPresent()) .orElse(true); } @Autowired UserMetricsController(
Provider<DbUser> userProvider,
Provider<WorkbenchConfig> workbenchConfigProvider,
UserRecentResourceService userRecentResourceService,
WorkspaceService workspaceService,
FireCloudService fireCloudService,
CloudStorageService cloudStorageService,
CommonMappers commonMappers,
FirecloudMapper firecloudMapper); @VisibleForTesting void setDistinctWorkspaceLimit(int limit); @Override ResponseEntity<WorkspaceResource> updateRecentResource(
String workspaceNamespace, String workspaceId, RecentResourceRequest recentResourceRequest); @Override ResponseEntity<EmptyResponse> deleteRecentResource(
String workspaceNamespace, String workspaceId, RecentResourceRequest recentResourceRequest); @Override ResponseEntity<WorkspaceResourceResponse> getUserRecentResources(); @VisibleForTesting boolean hasValidBlobIdIfNotebookNamePresent(DbUserRecentResource dbUserRecentResource); }### Answer:
@Test public void testHasValidBlobIdIfNotebookNamePresent_nullNotebookName_passes() { dbUserRecentResource1.setNotebookName(null); assertTrue(userMetricsController.hasValidBlobIdIfNotebookNamePresent(dbUserRecentResource1)); }
@Test public void testHasValidBlobIdIfNotebookNamePresent_validNotebookName_passes() { assertTrue(userMetricsController.hasValidBlobIdIfNotebookNamePresent(dbUserRecentResource1)); }
@Test public void testHasValidBlobIdIfNotebookNamePresent_invalidNotebookName_fails() { dbUserRecentResource1.setNotebookName("invalid-notebook@name"); assertFalse(userMetricsController.hasValidBlobIdIfNotebookNamePresent(dbUserRecentResource1)); } |
### Question:
ProfileController implements ProfileApiDelegate { @Override public ResponseEntity<Void> invitationKeyVerification( InvitationVerificationRequest invitationVerificationRequest) { verifyInvitationKey(invitationVerificationRequest.getInvitationKey()); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } @Autowired ProfileController(
ActionAuditQueryService actionAuditQueryService,
CaptchaVerificationService captchaVerificationService,
Clock clock,
CloudStorageService cloudStorageService,
DemographicSurveyMapper demographicSurveyMapper,
DirectoryService directoryService,
FireCloudService fireCloudService,
InstitutionService institutionService,
PageVisitMapper pageVisitMapper,
ProfileAuditor profileAuditor,
ProfileService profileService,
Provider<DbUser> userProvider,
Provider<MailService> mailServiceProvider,
Provider<UserAuthentication> userAuthenticationProvider,
Provider<WorkbenchConfig> workbenchConfigProvider,
ShibbolethService shibbolethService,
UserDao userDao,
UserService userService,
VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); @Override ResponseEntity<Profile> getMe(); @Override ResponseEntity<UsernameTakenResponse> isUsernameTaken(String username); @Override ResponseEntity<Profile> createAccount(CreateAccountRequest request); @Override ResponseEntity<Profile> requestBetaAccess(); @Override ResponseEntity<Profile> submitDataUseAgreement(
Integer dataUseAgreementSignedVersion, String initials); @Override ResponseEntity<Profile> syncComplianceTrainingStatus(); @Override ResponseEntity<Profile> syncEraCommonsStatus(); @Override ResponseEntity<Profile> syncTwoFactorAuthStatus(); @Override ResponseEntity<Void> invitationKeyVerification(
InvitationVerificationRequest invitationVerificationRequest); @Override ResponseEntity<Void> updateContactEmail(
UpdateContactEmailRequest updateContactEmailRequest); @Override ResponseEntity<Void> resendWelcomeEmail(ResendWelcomeEmailRequest resendRequest); @Override ResponseEntity<Profile> updatePageVisits(PageVisit newPageVisit); @Override ResponseEntity<Void> updateProfile(Profile updatedProfile); @AuthorityRequired(Authority.ACCESS_CONTROL_ADMIN) @Override @Deprecated // use updateAccountProperties() ResponseEntity<EmptyResponse> updateVerifiedInstitutionalAffiliation(
Long userId, VerifiedInstitutionalAffiliation verifiedAffiliation); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<UserListResponse> getAllUsers(); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUser(Long userId); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUserByUsername(String username); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<EmptyResponse> bypassAccessRequirement(
Long userId, AccessBypassRequest request); @Override ResponseEntity<EmptyResponse> unsafeSelfBypassAccessRequirement(
AccessBypassRequest request); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> updateAccountProperties(AccountPropertyUpdate request); @Override ResponseEntity<Profile> updateNihToken(NihToken token); @Override ResponseEntity<Void> deleteProfile(); @Override ResponseEntity<UserAuditLogQueryResponse> getAuditLogEntries(
String usernameWithoutGsuiteDomain,
Integer limit,
Long afterMillis,
Long beforeMillisNullable); }### Answer:
@Test(expected = BadRequestException.class) public void testInvitationKeyVerification_invitationKeyMismatch() { invitationVerificationRequest.setInvitationKey("wrong key"); profileController.invitationKeyVerification(invitationVerificationRequest); } |
### Question:
ProfileController implements ProfileApiDelegate { @Override public ResponseEntity<Profile> syncEraCommonsStatus() { userService.syncEraCommonsStatus(); return getProfileResponse(userProvider.get()); } @Autowired ProfileController(
ActionAuditQueryService actionAuditQueryService,
CaptchaVerificationService captchaVerificationService,
Clock clock,
CloudStorageService cloudStorageService,
DemographicSurveyMapper demographicSurveyMapper,
DirectoryService directoryService,
FireCloudService fireCloudService,
InstitutionService institutionService,
PageVisitMapper pageVisitMapper,
ProfileAuditor profileAuditor,
ProfileService profileService,
Provider<DbUser> userProvider,
Provider<MailService> mailServiceProvider,
Provider<UserAuthentication> userAuthenticationProvider,
Provider<WorkbenchConfig> workbenchConfigProvider,
ShibbolethService shibbolethService,
UserDao userDao,
UserService userService,
VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); @Override ResponseEntity<Profile> getMe(); @Override ResponseEntity<UsernameTakenResponse> isUsernameTaken(String username); @Override ResponseEntity<Profile> createAccount(CreateAccountRequest request); @Override ResponseEntity<Profile> requestBetaAccess(); @Override ResponseEntity<Profile> submitDataUseAgreement(
Integer dataUseAgreementSignedVersion, String initials); @Override ResponseEntity<Profile> syncComplianceTrainingStatus(); @Override ResponseEntity<Profile> syncEraCommonsStatus(); @Override ResponseEntity<Profile> syncTwoFactorAuthStatus(); @Override ResponseEntity<Void> invitationKeyVerification(
InvitationVerificationRequest invitationVerificationRequest); @Override ResponseEntity<Void> updateContactEmail(
UpdateContactEmailRequest updateContactEmailRequest); @Override ResponseEntity<Void> resendWelcomeEmail(ResendWelcomeEmailRequest resendRequest); @Override ResponseEntity<Profile> updatePageVisits(PageVisit newPageVisit); @Override ResponseEntity<Void> updateProfile(Profile updatedProfile); @AuthorityRequired(Authority.ACCESS_CONTROL_ADMIN) @Override @Deprecated // use updateAccountProperties() ResponseEntity<EmptyResponse> updateVerifiedInstitutionalAffiliation(
Long userId, VerifiedInstitutionalAffiliation verifiedAffiliation); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<UserListResponse> getAllUsers(); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUser(Long userId); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUserByUsername(String username); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<EmptyResponse> bypassAccessRequirement(
Long userId, AccessBypassRequest request); @Override ResponseEntity<EmptyResponse> unsafeSelfBypassAccessRequirement(
AccessBypassRequest request); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> updateAccountProperties(AccountPropertyUpdate request); @Override ResponseEntity<Profile> updateNihToken(NihToken token); @Override ResponseEntity<Void> deleteProfile(); @Override ResponseEntity<UserAuditLogQueryResponse> getAuditLogEntries(
String usernameWithoutGsuiteDomain,
Integer limit,
Long afterMillis,
Long beforeMillisNullable); }### Answer:
@Test public void testSyncEraCommons() { FirecloudNihStatus nihStatus = new FirecloudNihStatus(); String linkedUsername = "linked"; nihStatus.setLinkedNihUsername(linkedUsername); nihStatus.setLinkExpireTime(TIMESTAMP.getTime()); when(mockFireCloudService.getNihStatus()).thenReturn(nihStatus); createAccountAndDbUserWithAffiliation(); profileController.syncEraCommonsStatus(); assertThat(userDao.findUserByUsername(PRIMARY_EMAIL).getEraCommonsLinkedNihUsername()) .isEqualTo(linkedUsername); assertThat(userDao.findUserByUsername(PRIMARY_EMAIL).getEraCommonsLinkExpireTime()).isNotNull(); assertThat(userDao.findUserByUsername(PRIMARY_EMAIL).getEraCommonsCompletionTime()).isNotNull(); } |
### Question:
ProfileController implements ProfileApiDelegate { @Override public ResponseEntity<Void> deleteProfile() { if (!workbenchConfigProvider.get().featureFlags.unsafeAllowDeleteUser) { throw new ForbiddenException("Self account deletion is disallowed in this environment."); } DbUser user = userProvider.get(); log.log(Level.WARNING, "Deleting profile: user email: " + user.getUsername()); directoryService.deleteUser(user.getUsername()); userDao.delete(user.getUserId()); profileAuditor.fireDeleteAction(user.getUserId(), user.getUsername()); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } @Autowired ProfileController(
ActionAuditQueryService actionAuditQueryService,
CaptchaVerificationService captchaVerificationService,
Clock clock,
CloudStorageService cloudStorageService,
DemographicSurveyMapper demographicSurveyMapper,
DirectoryService directoryService,
FireCloudService fireCloudService,
InstitutionService institutionService,
PageVisitMapper pageVisitMapper,
ProfileAuditor profileAuditor,
ProfileService profileService,
Provider<DbUser> userProvider,
Provider<MailService> mailServiceProvider,
Provider<UserAuthentication> userAuthenticationProvider,
Provider<WorkbenchConfig> workbenchConfigProvider,
ShibbolethService shibbolethService,
UserDao userDao,
UserService userService,
VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); @Override ResponseEntity<Profile> getMe(); @Override ResponseEntity<UsernameTakenResponse> isUsernameTaken(String username); @Override ResponseEntity<Profile> createAccount(CreateAccountRequest request); @Override ResponseEntity<Profile> requestBetaAccess(); @Override ResponseEntity<Profile> submitDataUseAgreement(
Integer dataUseAgreementSignedVersion, String initials); @Override ResponseEntity<Profile> syncComplianceTrainingStatus(); @Override ResponseEntity<Profile> syncEraCommonsStatus(); @Override ResponseEntity<Profile> syncTwoFactorAuthStatus(); @Override ResponseEntity<Void> invitationKeyVerification(
InvitationVerificationRequest invitationVerificationRequest); @Override ResponseEntity<Void> updateContactEmail(
UpdateContactEmailRequest updateContactEmailRequest); @Override ResponseEntity<Void> resendWelcomeEmail(ResendWelcomeEmailRequest resendRequest); @Override ResponseEntity<Profile> updatePageVisits(PageVisit newPageVisit); @Override ResponseEntity<Void> updateProfile(Profile updatedProfile); @AuthorityRequired(Authority.ACCESS_CONTROL_ADMIN) @Override @Deprecated // use updateAccountProperties() ResponseEntity<EmptyResponse> updateVerifiedInstitutionalAffiliation(
Long userId, VerifiedInstitutionalAffiliation verifiedAffiliation); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<UserListResponse> getAllUsers(); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUser(Long userId); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUserByUsername(String username); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<EmptyResponse> bypassAccessRequirement(
Long userId, AccessBypassRequest request); @Override ResponseEntity<EmptyResponse> unsafeSelfBypassAccessRequirement(
AccessBypassRequest request); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> updateAccountProperties(AccountPropertyUpdate request); @Override ResponseEntity<Profile> updateNihToken(NihToken token); @Override ResponseEntity<Void> deleteProfile(); @Override ResponseEntity<UserAuditLogQueryResponse> getAuditLogEntries(
String usernameWithoutGsuiteDomain,
Integer limit,
Long afterMillis,
Long beforeMillisNullable); }### Answer:
@Test public void testDeleteProfile() { createAccountAndDbUserWithAffiliation(); profileController.deleteProfile(); verify(mockProfileAuditor).fireDeleteAction(dbUser.getUserId(), dbUser.getUsername()); } |
### Question:
ProfileController implements ProfileApiDelegate { @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) public ResponseEntity<EmptyResponse> bypassAccessRequirement( Long userId, AccessBypassRequest request) { userService.updateBypassTime(userId, request); return ResponseEntity.ok(new EmptyResponse()); } @Autowired ProfileController(
ActionAuditQueryService actionAuditQueryService,
CaptchaVerificationService captchaVerificationService,
Clock clock,
CloudStorageService cloudStorageService,
DemographicSurveyMapper demographicSurveyMapper,
DirectoryService directoryService,
FireCloudService fireCloudService,
InstitutionService institutionService,
PageVisitMapper pageVisitMapper,
ProfileAuditor profileAuditor,
ProfileService profileService,
Provider<DbUser> userProvider,
Provider<MailService> mailServiceProvider,
Provider<UserAuthentication> userAuthenticationProvider,
Provider<WorkbenchConfig> workbenchConfigProvider,
ShibbolethService shibbolethService,
UserDao userDao,
UserService userService,
VerifiedInstitutionalAffiliationMapper verifiedInstitutionalAffiliationMapper); @Override ResponseEntity<Profile> getMe(); @Override ResponseEntity<UsernameTakenResponse> isUsernameTaken(String username); @Override ResponseEntity<Profile> createAccount(CreateAccountRequest request); @Override ResponseEntity<Profile> requestBetaAccess(); @Override ResponseEntity<Profile> submitDataUseAgreement(
Integer dataUseAgreementSignedVersion, String initials); @Override ResponseEntity<Profile> syncComplianceTrainingStatus(); @Override ResponseEntity<Profile> syncEraCommonsStatus(); @Override ResponseEntity<Profile> syncTwoFactorAuthStatus(); @Override ResponseEntity<Void> invitationKeyVerification(
InvitationVerificationRequest invitationVerificationRequest); @Override ResponseEntity<Void> updateContactEmail(
UpdateContactEmailRequest updateContactEmailRequest); @Override ResponseEntity<Void> resendWelcomeEmail(ResendWelcomeEmailRequest resendRequest); @Override ResponseEntity<Profile> updatePageVisits(PageVisit newPageVisit); @Override ResponseEntity<Void> updateProfile(Profile updatedProfile); @AuthorityRequired(Authority.ACCESS_CONTROL_ADMIN) @Override @Deprecated // use updateAccountProperties() ResponseEntity<EmptyResponse> updateVerifiedInstitutionalAffiliation(
Long userId, VerifiedInstitutionalAffiliation verifiedAffiliation); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<UserListResponse> getAllUsers(); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUser(Long userId); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> getUserByUsername(String username); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<EmptyResponse> bypassAccessRequirement(
Long userId, AccessBypassRequest request); @Override ResponseEntity<EmptyResponse> unsafeSelfBypassAccessRequirement(
AccessBypassRequest request); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Profile> updateAccountProperties(AccountPropertyUpdate request); @Override ResponseEntity<Profile> updateNihToken(NihToken token); @Override ResponseEntity<Void> deleteProfile(); @Override ResponseEntity<UserAuditLogQueryResponse> getAuditLogEntries(
String usernameWithoutGsuiteDomain,
Integer limit,
Long afterMillis,
Long beforeMillisNullable); }### Answer:
@Test public void testBypassAccessModule() { Profile profile = createAccountAndDbUserWithAffiliation(); profileController.bypassAccessRequirement( profile.getUserId(), new AccessBypassRequest().isBypassed(true).moduleName(AccessModule.DATA_USE_AGREEMENT)); DbUser dbUser = userDao.findUserByUsername(PRIMARY_EMAIL); assertThat(dbUser.getDataUseAgreementBypassTime()).isNotNull(); } |
### Question:
SumoLogicController implements SumoLogicApiDelegate { @Override public ResponseEntity<Void> logEgressEvent(String X_API_KEY, EgressEventRequest request) { authorizeRequest(X_API_KEY, request); try { ObjectMapper mapper = new ObjectMapper(); EgressEvent[] events = mapper.readValue(request.getEventsJsonArray(), EgressEvent[].class); Arrays.stream(events).forEach(egressEventService::handleEvent); return ResponseEntity.noContent().build(); } catch (IOException e) { log.severe( String.format( "Failed to parse SumoLogic egress event JSON: %s", request.getEventsJsonArray())); log.severe(e.getMessage()); this.egressEventAuditor.fireFailedToParseEgressEventRequest(request); throw new BadRequestException("Error parsing event details"); } } @Autowired SumoLogicController(
CloudStorageService cloudStorageService,
EgressEventAuditor egressEventAuditor,
EgressEventService egressEventService,
Provider<WorkbenchConfig> workbenchConfigProvider); @Override ResponseEntity<Void> logEgressEvent(String X_API_KEY, EgressEventRequest request); static final String SUMOLOGIC_KEY_FILENAME; }### Answer:
@Test public void testLogsApiKeyFailure() { assertThrows( UnauthorizedException.class, () -> sumoLogicController.logEgressEvent("bad-key", request)); verify(mockEgressEventAuditor).fireBadApiKey("bad-key", request); }
@Test public void testLogsRequestParsingFailure() { request.setEventsJsonArray("bad-json"); assertThrows( BadRequestException.class, () -> sumoLogicController.logEgressEvent(API_KEY, request)); verify(mockEgressEventAuditor).fireFailedToParseEgressEventRequest(request); }
@Test public void testLogsSingleEvent() { sumoLogicController.logEgressEvent(API_KEY, request); verify(mockEgressEventService).handleEvent(event); }
@Test public void testLogsMultipleEvents() throws JsonProcessingException { EgressEvent event2 = new EgressEvent(); request.setEventsJsonArray(objectMapper.writeValueAsString(Arrays.asList(event, event2))); sumoLogicController.logEgressEvent(API_KEY, request); verify(mockEgressEventService, times(2)).handleEvent(any()); } |
### Question:
CohortsController implements CohortsApiDelegate { @Override public ResponseEntity<CohortListResponse> getCohortsInWorkspace( String workspaceNamespace, String workspaceId) { workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); DbWorkspace workspace = workspaceService.getRequiredWithCohorts(workspaceNamespace, workspaceId); CohortListResponse response = new CohortListResponse(); Set<DbCohort> cohorts = workspace.getCohorts(); if (cohorts != null) { response.setItems( cohorts.stream() .map(cohortMapper::dbModelToClient) .sorted(Comparator.comparing(c -> c.getName())) .collect(Collectors.toList())); } return ResponseEntity.ok(response); } @Autowired CohortsController(
WorkspaceService workspaceService,
CohortDao cohortDao,
CdrVersionDao cdrVersionDao,
CohortFactory cohortFactory,
CohortMapper cohortMapper,
CohortReviewDao cohortReviewDao,
ConceptSetDao conceptSetDao,
CohortMaterializationService cohortMaterializationService,
Provider<DbUser> userProvider,
Clock clock,
CdrVersionService cdrVersionService,
UserRecentResourceService userRecentResourceService); @Override ResponseEntity<Cohort> createCohort(
String workspaceNamespace, String workspaceId, Cohort cohort); @Override ResponseEntity<Cohort> duplicateCohort(
String workspaceNamespace, String workspaceId, DuplicateCohortRequest params); @Override ResponseEntity<EmptyResponse> deleteCohort(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<Cohort> getCohort(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<CohortListResponse> getCohortsInWorkspace(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<Cohort> updateCohort(
String workspaceNamespace, String workspaceId, Long cohortId, Cohort cohort); @Override ResponseEntity<MaterializeCohortResponse> materializeCohort(
String workspaceNamespace, String workspaceId, MaterializeCohortRequest request); @Override ResponseEntity<CdrQuery> getDataTableQuery(
String workspaceNamespace, String workspaceId, DataTableSpecification request); @Override ResponseEntity<CohortAnnotationsResponse> getCohortAnnotations(
String workspaceNamespace, String workspaceId, CohortAnnotationsRequest request); }### Answer:
@Test public void testGetCohortsInWorkspace() throws Exception { Cohort c1 = createDefaultCohort(); c1.setName("c1"); c1 = cohortsController.createCohort(workspace.getNamespace(), workspace.getId(), c1).getBody(); Cohort c2 = createDefaultCohort(); c2.setName("c2"); c2 = cohortsController.createCohort(workspace.getNamespace(), workspace.getId(), c2).getBody(); List<Cohort> cohorts = cohortsController .getCohortsInWorkspace(workspace.getNamespace(), workspace.getId()) .getBody() .getItems(); assertThat(cohorts).containsAllOf(c1, c2); assertThat(cohorts.size()).isEqualTo(2); } |
### Question:
CohortsController implements CohortsApiDelegate { @Override public ResponseEntity<Cohort> createCohort( String workspaceNamespace, String workspaceId, Cohort cohort) { workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, workspaceId, WorkspaceAccessLevel.WRITER); DbWorkspace workspace = workspaceService.getRequired(workspaceNamespace, workspaceId); try { new Gson().fromJson(cohort.getCriteria(), SearchRequest.class); } catch (JsonSyntaxException e) { throw new ServerErrorException( String.format( "Could not save Cohort (\"/%s/%s/%s\")", workspace.getWorkspaceNamespace(), workspace.getWorkspaceId(), cohort.getName()), e); } checkForDuplicateCohortNameException(cohort.getName(), workspace); DbCohort newCohort = cohortFactory.createCohort(cohort, userProvider.get(), workspace.getWorkspaceId()); try { newCohort = cohortDao.save(newCohort); userRecentResourceService.updateCohortEntry( workspace.getWorkspaceId(), userProvider.get().getUserId(), newCohort.getCohortId()); } catch (DataIntegrityViolationException e) { throw new ServerErrorException( String.format( "Could not save Cohort (\"/%s/%s/%s\")", workspace.getWorkspaceNamespace(), workspace.getWorkspaceId(), newCohort.getName()), e); } return ResponseEntity.ok(cohortMapper.dbModelToClient(newCohort)); } @Autowired CohortsController(
WorkspaceService workspaceService,
CohortDao cohortDao,
CdrVersionDao cdrVersionDao,
CohortFactory cohortFactory,
CohortMapper cohortMapper,
CohortReviewDao cohortReviewDao,
ConceptSetDao conceptSetDao,
CohortMaterializationService cohortMaterializationService,
Provider<DbUser> userProvider,
Clock clock,
CdrVersionService cdrVersionService,
UserRecentResourceService userRecentResourceService); @Override ResponseEntity<Cohort> createCohort(
String workspaceNamespace, String workspaceId, Cohort cohort); @Override ResponseEntity<Cohort> duplicateCohort(
String workspaceNamespace, String workspaceId, DuplicateCohortRequest params); @Override ResponseEntity<EmptyResponse> deleteCohort(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<Cohort> getCohort(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<CohortListResponse> getCohortsInWorkspace(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<Cohort> updateCohort(
String workspaceNamespace, String workspaceId, Long cohortId, Cohort cohort); @Override ResponseEntity<MaterializeCohortResponse> materializeCohort(
String workspaceNamespace, String workspaceId, MaterializeCohortRequest request); @Override ResponseEntity<CdrQuery> getDataTableQuery(
String workspaceNamespace, String workspaceId, DataTableSpecification request); @Override ResponseEntity<CohortAnnotationsResponse> getCohortAnnotations(
String workspaceNamespace, String workspaceId, CohortAnnotationsRequest request); }### Answer:
@Test(expected = ServerErrorException.class) public void testCreateCohortBadCriteria() { Cohort cohort = createDefaultCohort(); cohort.setCriteria(badCohortCriteria); cohortsController.createCohort(workspace.getNamespace(), workspace.getId(), cohort).getBody(); } |
### Question:
CohortsController implements CohortsApiDelegate { @Override public ResponseEntity<Cohort> duplicateCohort( String workspaceNamespace, String workspaceId, DuplicateCohortRequest params) { workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, workspaceId, WorkspaceAccessLevel.WRITER); DbWorkspace workspace = workspaceService.getRequired(workspaceNamespace, workspaceId); checkForDuplicateCohortNameException(params.getNewName(), workspace); DbCohort originalCohort = getDbCohort(workspaceNamespace, workspaceId, params.getOriginalCohortId()); DbCohort newCohort = cohortFactory.duplicateCohort( params.getNewName(), userProvider.get(), workspace, originalCohort); try { newCohort = cohortDao.save(newCohort); userRecentResourceService.updateCohortEntry( workspace.getWorkspaceId(), userProvider.get().getUserId(), newCohort.getCohortId()); } catch (Exception e) { throw new ServerErrorException( String.format( "Could not save Cohort (\"/%s/%s/%s\")", workspace.getWorkspaceNamespace(), workspace.getWorkspaceId(), newCohort.getName()), e); } return ResponseEntity.ok(cohortMapper.dbModelToClient(newCohort)); } @Autowired CohortsController(
WorkspaceService workspaceService,
CohortDao cohortDao,
CdrVersionDao cdrVersionDao,
CohortFactory cohortFactory,
CohortMapper cohortMapper,
CohortReviewDao cohortReviewDao,
ConceptSetDao conceptSetDao,
CohortMaterializationService cohortMaterializationService,
Provider<DbUser> userProvider,
Clock clock,
CdrVersionService cdrVersionService,
UserRecentResourceService userRecentResourceService); @Override ResponseEntity<Cohort> createCohort(
String workspaceNamespace, String workspaceId, Cohort cohort); @Override ResponseEntity<Cohort> duplicateCohort(
String workspaceNamespace, String workspaceId, DuplicateCohortRequest params); @Override ResponseEntity<EmptyResponse> deleteCohort(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<Cohort> getCohort(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<CohortListResponse> getCohortsInWorkspace(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<Cohort> updateCohort(
String workspaceNamespace, String workspaceId, Long cohortId, Cohort cohort); @Override ResponseEntity<MaterializeCohortResponse> materializeCohort(
String workspaceNamespace, String workspaceId, MaterializeCohortRequest request); @Override ResponseEntity<CdrQuery> getDataTableQuery(
String workspaceNamespace, String workspaceId, DataTableSpecification request); @Override ResponseEntity<CohortAnnotationsResponse> getCohortAnnotations(
String workspaceNamespace, String workspaceId, CohortAnnotationsRequest request); }### Answer:
@Test public void testDuplicateCohort() { Cohort originalCohort = createDefaultCohort(); originalCohort = cohortsController .createCohort(workspace.getNamespace(), workspace.getId(), originalCohort) .getBody(); DuplicateCohortRequest params = new DuplicateCohortRequest(); params.setNewName("New Cohort Name"); params.setOriginalCohortId(originalCohort.getId()); Cohort newCohort = cohortsController .duplicateCohort(workspace.getNamespace(), workspace.getId(), params) .getBody(); newCohort = cohortsController .getCohort(workspace.getNamespace(), workspace.getId(), newCohort.getId()) .getBody(); assertThat(newCohort.getName()).isEqualTo(params.getNewName()); assertThat(newCohort.getCriteria()).isEqualTo(originalCohort.getCriteria()); assertThat(newCohort.getType()).isEqualTo(originalCohort.getType()); assertThat(newCohort.getDescription()).isEqualTo(originalCohort.getDescription()); } |
### Question:
DataSetController implements DataSetApiDelegate { @VisibleForTesting public void addFieldValuesFromBigQueryToPreviewList( List<DataSetPreviewValueList> valuePreviewList, FieldValueList fieldValueList) { IntStream.range(0, fieldValueList.size()) .forEach( columnNumber -> valuePreviewList .get(columnNumber) .addQueryValueItem( Optional.ofNullable(fieldValueList.get(columnNumber).getValue()) .map(Object::toString) .orElse(EMPTY_CELL_MARKER))); } @Autowired DataSetController(
BigQueryService bigQueryService,
CdrVersionService cdrVersionService,
DataSetService dataSetService,
FireCloudService fireCloudService,
NotebooksService notebooksService,
Provider<DbUser> userProvider,
@Qualifier(DatasetConfig.DATASET_PREFIX_CODE) Provider<String> prefixProvider,
WorkspaceService workspaceService); @Override ResponseEntity<DataSet> createDataSet(
String workspaceNamespace, String workspaceFirecloudName, DataSetRequest dataSetRequest); @VisibleForTesting String generateRandomEightCharacterQualifier(); ResponseEntity<DataSetCodeResponse> generateCode(
String workspaceNamespace,
String workspaceId,
String kernelTypeEnumString,
DataSetRequest dataSetRequest); @Override ResponseEntity<DataSetPreviewResponse> previewDataSetByDomain(
String workspaceNamespace, String workspaceId, DataSetPreviewRequest dataSetPreviewRequest); @VisibleForTesting void addFieldValuesFromBigQueryToPreviewList(
List<DataSetPreviewValueList> valuePreviewList, FieldValueList fieldValueList); @Override ResponseEntity<EmptyResponse> exportToNotebook(
String workspaceNamespace, String workspaceId, DataSetExportRequest dataSetExportRequest); @Override ResponseEntity<Boolean> markDirty(
String workspaceNamespace, String workspaceId, MarkDataSetRequest markDataSetRequest); @Override ResponseEntity<EmptyResponse> deleteDataSet(
String workspaceNamespace, String workspaceId, Long dataSetId); @Override ResponseEntity<DataSet> updateDataSet(
String workspaceNamespace, String workspaceId, Long dataSetId, DataSetRequest request); @Override ResponseEntity<DataSet> getDataSet(
String workspaceNamespace, String workspaceId, Long dataSetId); @Override ResponseEntity<DataSetListResponse> getDataSetByResourceId(
String workspaceNamespace, String workspaceId, ResourceType resourceType, Long id); @Override ResponseEntity<DataDictionaryEntry> getDataDictionaryEntry(
Long cdrVersionId, String domain, String domainValue); @Override ResponseEntity<DomainValuesResponse> getValuesFromDomain(
String workspaceNamespace, String workspaceId, String domainValue); static final String EMPTY_CELL_MARKER; }### Answer:
@Test public void testAddFieldValuesFromBigQueryToPreviewListWorksWithNullValues() { DataSetPreviewValueList dataSetPreviewValueList = new DataSetPreviewValueList(); List<DataSetPreviewValueList> valuePreviewList = ImmutableList.of(dataSetPreviewValueList); List<FieldValue> fieldValueListRows = ImmutableList.of(FieldValue.of(FieldValue.Attribute.PRIMITIVE, null)); FieldValueList fieldValueList = FieldValueList.of(fieldValueListRows); dataSetController.addFieldValuesFromBigQueryToPreviewList(valuePreviewList, fieldValueList); assertThat(valuePreviewList.get(0).getQueryValue().get(0)) .isEqualTo(DataSetController.EMPTY_CELL_MARKER); } |
### Question:
DataSetController implements DataSetApiDelegate { @Override public ResponseEntity<DomainValuesResponse> getValuesFromDomain( String workspaceNamespace, String workspaceId, String domainValue) { workspaceService.getWorkspaceEnforceAccessLevelAndSetCdrVersion( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); DomainValuesResponse response = new DomainValuesResponse(); FieldList fieldList = bigQueryService.getTableFieldsFromDomain(Domain.valueOf(domainValue)); response.setItems( fieldList.stream() .map(field -> new DomainValue().value(field.getName().toLowerCase())) .collect(Collectors.toList())); return ResponseEntity.ok(response); } @Autowired DataSetController(
BigQueryService bigQueryService,
CdrVersionService cdrVersionService,
DataSetService dataSetService,
FireCloudService fireCloudService,
NotebooksService notebooksService,
Provider<DbUser> userProvider,
@Qualifier(DatasetConfig.DATASET_PREFIX_CODE) Provider<String> prefixProvider,
WorkspaceService workspaceService); @Override ResponseEntity<DataSet> createDataSet(
String workspaceNamespace, String workspaceFirecloudName, DataSetRequest dataSetRequest); @VisibleForTesting String generateRandomEightCharacterQualifier(); ResponseEntity<DataSetCodeResponse> generateCode(
String workspaceNamespace,
String workspaceId,
String kernelTypeEnumString,
DataSetRequest dataSetRequest); @Override ResponseEntity<DataSetPreviewResponse> previewDataSetByDomain(
String workspaceNamespace, String workspaceId, DataSetPreviewRequest dataSetPreviewRequest); @VisibleForTesting void addFieldValuesFromBigQueryToPreviewList(
List<DataSetPreviewValueList> valuePreviewList, FieldValueList fieldValueList); @Override ResponseEntity<EmptyResponse> exportToNotebook(
String workspaceNamespace, String workspaceId, DataSetExportRequest dataSetExportRequest); @Override ResponseEntity<Boolean> markDirty(
String workspaceNamespace, String workspaceId, MarkDataSetRequest markDataSetRequest); @Override ResponseEntity<EmptyResponse> deleteDataSet(
String workspaceNamespace, String workspaceId, Long dataSetId); @Override ResponseEntity<DataSet> updateDataSet(
String workspaceNamespace, String workspaceId, Long dataSetId, DataSetRequest request); @Override ResponseEntity<DataSet> getDataSet(
String workspaceNamespace, String workspaceId, Long dataSetId); @Override ResponseEntity<DataSetListResponse> getDataSetByResourceId(
String workspaceNamespace, String workspaceId, ResourceType resourceType, Long id); @Override ResponseEntity<DataDictionaryEntry> getDataDictionaryEntry(
Long cdrVersionId, String domain, String domainValue); @Override ResponseEntity<DomainValuesResponse> getValuesFromDomain(
String workspaceNamespace, String workspaceId, String domainValue); static final String EMPTY_CELL_MARKER; }### Answer:
@Test public void testGetValuesFromDomain() { when(mockBigQueryService.getTableFieldsFromDomain(Domain.CONDITION)) .thenReturn( FieldList.of( Field.of("FIELD_ONE", LegacySQLTypeName.STRING), Field.of("FIELD_TWO", LegacySQLTypeName.STRING))); List<DomainValue> domainValues = dataSetController .getValuesFromDomain( workspace.getNamespace(), WORKSPACE_NAME, Domain.CONDITION.toString()) .getBody() .getItems(); verify(mockBigQueryService).getTableFieldsFromDomain(Domain.CONDITION); assertThat(domainValues) .containsExactly( new DomainValue().value("field_one"), new DomainValue().value("field_two")); } |
### Question:
OfflineUserController implements OfflineUserApiDelegate { @Override public ResponseEntity<Void> bulkSyncEraCommonsStatus() { int errorCount = 0; int userCount = 0; int changeCount = 0; int accessLevelChangeCount = 0; for (DbUser user : userService.getAllUsers()) { userCount++; try { if (user.getFirstSignInTime() == null) { continue; } Timestamp oldTime = user.getEraCommonsCompletionTime(); DataAccessLevel oldLevel = user.getDataAccessLevelEnum(); DbUser updatedUser = userService.syncEraCommonsStatusUsingImpersonation(user, Agent.asSystem()); Timestamp newTime = updatedUser.getEraCommonsCompletionTime(); DataAccessLevel newLevel = user.getDataAccessLevelEnum(); if (!Objects.equals(newTime, oldTime)) { log.info( String.format( "eRA Commons completion changed for user %s. Old %s, new %s", user.getUsername(), oldTime, newTime)); changeCount++; } if (oldLevel != newLevel) { log.info( String.format( "Data access level changed for user %s. Old %s, new %s", user.getUsername(), oldLevel.toString(), newLevel.toString())); accessLevelChangeCount++; } } catch (org.pmiops.workbench.firecloud.ApiException e) { errorCount++; log.severe( String.format( "Error syncing eRA Commons status for user %s: %s", user.getUsername(), e.getMessage())); } catch (IOException e) { errorCount++; log.severe( String.format( "Error fetching impersonated creds for user %s: %s", user.getUsername(), e.getMessage())); } } log.info( String.format( "Checked %d users, updated %d completion times, updated %d access levels", userCount, changeCount, accessLevelChangeCount)); if (errorCount > 0) { throw new ServerErrorException( String.format("%d errors encountered during eRA Commons sync", errorCount)); } return ResponseEntity.noContent().build(); } @Autowired OfflineUserController(
CloudResourceManagerService cloudResourceManagerService,
UserService userService,
Provider<WorkbenchConfig> workbenchConfigProvider); @Override ResponseEntity<Void> bulkSyncComplianceTrainingStatus(); @Override ResponseEntity<Void> bulkSyncEraCommonsStatus(); @Override ResponseEntity<Void> bulkSyncTwoFactorAuthStatus(); @Override ResponseEntity<Void> bulkAuditProjectAccess(); }### Answer:
@Test public void testBulkSyncEraCommonsStatus() throws IOException, org.pmiops.workbench.firecloud.ApiException { doAnswer(i -> i.getArgument(0)) .when(userService) .syncEraCommonsStatusUsingImpersonation(any(), any()); offlineUserController.bulkSyncEraCommonsStatus(); verify(userService, times(3)).syncEraCommonsStatusUsingImpersonation(any(), any()); }
@Test(expected = ServerErrorException.class) public void testBulkSyncEraCommonsStatusWithSingleUserError() throws ApiException, NotFoundException, IOException, org.pmiops.workbench.firecloud.ApiException { doAnswer(i -> i.getArgument(0)) .when(userService) .syncEraCommonsStatusUsingImpersonation(any(), any()); doThrow(new org.pmiops.workbench.firecloud.ApiException("Unknown error")) .when(userService) .syncEraCommonsStatusUsingImpersonation( argThat(user -> user.getUsername().equals("[email protected]")), any()); offlineUserController.bulkSyncEraCommonsStatus(); verify(userService, times(3)).syncEraCommonsStatusUsingImpersonation(any(), any()); } |
### Question:
OfflineUserController implements OfflineUserApiDelegate { @Override public ResponseEntity<Void> bulkAuditProjectAccess() { int errorCount = 0; List<DbUser> users = userService.getAllUsers(); for (DbUser user : users) { try { List<String> unauthorizedLogs = cloudResourceManagerService.getAllProjectsForUser(user).stream() .filter( project -> project.getParent() == null || !(WHITELISTED_ORG_IDS.contains(project.getParent().getId()))) .map( project -> project.getName() + " in organization " + Optional.ofNullable(project.getParent()) .map(ResourceId::getId) .orElse("[none]")) .collect(Collectors.toList()); if (unauthorizedLogs.size() > 0) { log.warning( "User " + user.getUsername() + " has access to projects: " + String.join(", ", unauthorizedLogs)); } } catch (IOException e) { log.log(Level.SEVERE, "failed to audit project access for user " + user.getUsername(), e); errorCount++; } } if (errorCount > 0) { log.severe(String.format("encountered errors on %d/%d users", errorCount, users.size())); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } log.info(String.format("successfully audited %d users", users.size())); return ResponseEntity.noContent().build(); } @Autowired OfflineUserController(
CloudResourceManagerService cloudResourceManagerService,
UserService userService,
Provider<WorkbenchConfig> workbenchConfigProvider); @Override ResponseEntity<Void> bulkSyncComplianceTrainingStatus(); @Override ResponseEntity<Void> bulkSyncEraCommonsStatus(); @Override ResponseEntity<Void> bulkSyncTwoFactorAuthStatus(); @Override ResponseEntity<Void> bulkAuditProjectAccess(); }### Answer:
@Test public void testBulkProjectAudit() throws Exception { List<Project> projectList = new ArrayList<>(); doReturn(projectList).when(cloudResourceManagerService).getAllProjectsForUser(any()); offlineUserController.bulkAuditProjectAccess(); verify(cloudResourceManagerService, times(4)).getAllProjectsForUser(any()); } |
### Question:
AuthDomainController implements AuthDomainApiDelegate { @AuthorityRequired({Authority.DEVELOPER}) @Override public ResponseEntity<EmptyResponse> createAuthDomain(String groupName) { fireCloudService.createGroup(groupName); return ResponseEntity.ok(new EmptyResponse()); } @Autowired AuthDomainController(
FireCloudService fireCloudService,
UserService userService,
UserDao userDao,
AuthDomainAuditor authDomainAuditAdapter); @AuthorityRequired({Authority.DEVELOPER}) @Override ResponseEntity<EmptyResponse> createAuthDomain(String groupName); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Void> updateUserDisabledStatus(UpdateUserDisabledRequest request); }### Answer:
@Test public void testCreateAuthDomain() { ResponseEntity<EmptyResponse> response = this.authDomainController.createAuthDomain(""); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } |
### Question:
AuthDomainController implements AuthDomainApiDelegate { @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) public ResponseEntity<Void> updateUserDisabledStatus(UpdateUserDisabledRequest request) { final DbUser targetDbUser = userService.getByUsernameOrThrow(request.getEmail()); final Boolean previousDisabled = targetDbUser.getDisabled(); final DbUser updatedTargetUser = userService.setDisabledStatus(targetDbUser.getUserId(), request.getDisabled()); auditAdminActions(request, previousDisabled, updatedTargetUser); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } @Autowired AuthDomainController(
FireCloudService fireCloudService,
UserService userService,
UserDao userDao,
AuthDomainAuditor authDomainAuditAdapter); @AuthorityRequired({Authority.DEVELOPER}) @Override ResponseEntity<EmptyResponse> createAuthDomain(String groupName); @Override @AuthorityRequired({Authority.ACCESS_CONTROL_ADMIN}) ResponseEntity<Void> updateUserDisabledStatus(UpdateUserDisabledRequest request); }### Answer:
@Test public void testDisableUser() { final boolean oldDisabledValue = false; final DbUser createdUser = createUser(oldDisabledValue); final boolean newDisabledValue = true; UpdateUserDisabledRequest request = new UpdateUserDisabledRequest().email(PRIMARY_EMAIL).disabled(newDisabledValue); ResponseEntity<Void> response = this.authDomainController.updateUserDisabledStatus(request); verify(mockAuthDomainAuditAdapter) .fireSetAccountDisabledStatus(createdUser.getUserId(), newDisabledValue, oldDisabledValue); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); DbUser updatedUser = userDao.findUserByUsername(PRIMARY_EMAIL); assertThat(updatedUser.getDisabled()).isTrue(); }
@Test public void testEnableUser() { final boolean oldDisabledValue = true; final DbUser createdUser = createUser(oldDisabledValue); final boolean newDisabledValue = false; UpdateUserDisabledRequest request = new UpdateUserDisabledRequest().email(PRIMARY_EMAIL).disabled(newDisabledValue); ResponseEntity<Void> response = this.authDomainController.updateUserDisabledStatus(request); verify(mockAuthDomainAuditAdapter) .fireSetAccountDisabledStatus(createdUser.getUserId(), newDisabledValue, oldDisabledValue); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); DbUser updatedUser = userDao.findUserByUsername(PRIMARY_EMAIL); assertThat(updatedUser.getDisabled()).isFalse(); } |
### Question:
CohortAnnotationDefinitionController implements CohortAnnotationDefinitionApiDelegate { @Override public ResponseEntity<EmptyResponse> deleteCohortAnnotationDefinition( String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId) { workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, workspaceId, WorkspaceAccessLevel.WRITER); validateCohortExist(cohortId); findCohortAnnotationDefinition(cohortId, annotationDefinitionId); cohortAnnotationDefinitionService.delete(annotationDefinitionId); return ResponseEntity.ok(new EmptyResponse()); } @Autowired CohortAnnotationDefinitionController(
CohortAnnotationDefinitionService cohortAnnotationDefinitionService,
CohortReviewService cohortReviewService,
WorkspaceService workspaceService); @Override ResponseEntity<CohortAnnotationDefinition> createCohortAnnotationDefinition(
String workspaceNamespace,
String workspaceId,
Long cohortId,
CohortAnnotationDefinition cohortAnnotationDefinition); @Override ResponseEntity<EmptyResponse> deleteCohortAnnotationDefinition(
String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId); @Override ResponseEntity<CohortAnnotationDefinition> getCohortAnnotationDefinition(
String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId); @Override ResponseEntity<CohortAnnotationDefinitionListResponse> getCohortAnnotationDefinitions(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<CohortAnnotationDefinition> updateCohortAnnotationDefinition(
String workspaceNamespace,
String workspaceId,
Long cohortId,
Long annotationDefinitionId,
CohortAnnotationDefinition cohortAnnotationDefinitionRequest); }### Answer:
@Test public void deleteCohortAnnotationDefinition_BadCohortId() { setupWorkspaceServiceMock(); try { cohortAnnotationDefinitionController.deleteCohortAnnotationDefinition( NAMESPACE, NAME, 99L, dbCohortAnnotationDefinition.getCohortAnnotationDefinitionId()); fail("Should have thrown a NotFoundException!"); } catch (NotFoundException e) { assertEquals("Not Found: No Cohort exists for cohortId: " + 99L, e.getMessage()); } }
@Test public void deleteCohortAnnotationDefinition_BadAnnotationDefinitionId() { setupWorkspaceServiceMock(); try { cohortAnnotationDefinitionController.deleteCohortAnnotationDefinition( NAMESPACE, NAME, cohort.getCohortId(), 99L); fail("Should have thrown a NotFoundException!"); } catch (NotFoundException e) { assertEquals( "Not Found: No Cohort Annotation Definition exists for annotationDefinitionId: " + 99L, e.getMessage()); } }
@Test public void deleteCohortAnnotationDefinition() { setupWorkspaceServiceMock(); EmptyResponse response = cohortAnnotationDefinitionController .deleteCohortAnnotationDefinition( NAMESPACE, NAME, cohort.getCohortId(), dbCohortAnnotationDefinition.getCohortAnnotationDefinitionId()) .getBody(); assertEquals(new EmptyResponse(), response); } |
### Question:
CohortAnnotationDefinitionController implements CohortAnnotationDefinitionApiDelegate { @Override public ResponseEntity<CohortAnnotationDefinition> getCohortAnnotationDefinition( String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId) { workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); validateCohortExist(cohortId); return ResponseEntity.ok(findCohortAnnotationDefinition(cohortId, annotationDefinitionId)); } @Autowired CohortAnnotationDefinitionController(
CohortAnnotationDefinitionService cohortAnnotationDefinitionService,
CohortReviewService cohortReviewService,
WorkspaceService workspaceService); @Override ResponseEntity<CohortAnnotationDefinition> createCohortAnnotationDefinition(
String workspaceNamespace,
String workspaceId,
Long cohortId,
CohortAnnotationDefinition cohortAnnotationDefinition); @Override ResponseEntity<EmptyResponse> deleteCohortAnnotationDefinition(
String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId); @Override ResponseEntity<CohortAnnotationDefinition> getCohortAnnotationDefinition(
String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId); @Override ResponseEntity<CohortAnnotationDefinitionListResponse> getCohortAnnotationDefinitions(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<CohortAnnotationDefinition> updateCohortAnnotationDefinition(
String workspaceNamespace,
String workspaceId,
Long cohortId,
Long annotationDefinitionId,
CohortAnnotationDefinition cohortAnnotationDefinitionRequest); }### Answer:
@Test public void getCohortAnnotationDefinition_NotFoundCohort() { setupWorkspaceServiceMock(); try { cohortAnnotationDefinitionController.getCohortAnnotationDefinition( NAMESPACE, NAME, 99L, dbCohortAnnotationDefinition.getCohortAnnotationDefinitionId()); fail("Should have thrown a NotFoundException!"); } catch (NotFoundException e) { assertEquals("Not Found: No Cohort exists for cohortId: " + 99L, e.getMessage()); } }
@Test public void getCohortAnnotationDefinition_NotFoundAnnotationDefinition() { setupWorkspaceServiceMock(); try { cohortAnnotationDefinitionController.getCohortAnnotationDefinition( NAMESPACE, NAME, cohort.getCohortId(), 99L); fail("Should have thrown a NotFoundException!"); } catch (NotFoundException e) { assertEquals( "Not Found: No Cohort Annotation Definition exists for annotationDefinitionId: " + 99L, e.getMessage()); } }
@Test public void getCohortAnnotationDefinition() { setupWorkspaceServiceMock(); CohortAnnotationDefinition responseDefinition = cohortAnnotationDefinitionController .getCohortAnnotationDefinition( NAMESPACE, NAME, cohort.getCohortId(), dbCohortAnnotationDefinition.getCohortAnnotationDefinitionId()) .getBody(); CohortAnnotationDefinition expectedResponse = new CohortAnnotationDefinition() .cohortAnnotationDefinitionId( dbCohortAnnotationDefinition.getCohortAnnotationDefinitionId()) .cohortId(cohort.getCohortId()) .annotationType(AnnotationType.STRING) .columnName(dbCohortAnnotationDefinition.getColumnName()) .enumValues(new ArrayList<>()) .etag(Etags.fromVersion(0)); assertEquals(expectedResponse, responseDefinition); } |
### Question:
CohortAnnotationDefinitionController implements CohortAnnotationDefinitionApiDelegate { @Override public ResponseEntity<CohortAnnotationDefinitionListResponse> getCohortAnnotationDefinitions( String workspaceNamespace, String workspaceId, Long cohortId) { workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); validateCohortExist(cohortId); List<CohortAnnotationDefinition> defs = cohortAnnotationDefinitionService.findByCohortId(cohortId); return ResponseEntity.ok(new CohortAnnotationDefinitionListResponse().items(defs)); } @Autowired CohortAnnotationDefinitionController(
CohortAnnotationDefinitionService cohortAnnotationDefinitionService,
CohortReviewService cohortReviewService,
WorkspaceService workspaceService); @Override ResponseEntity<CohortAnnotationDefinition> createCohortAnnotationDefinition(
String workspaceNamespace,
String workspaceId,
Long cohortId,
CohortAnnotationDefinition cohortAnnotationDefinition); @Override ResponseEntity<EmptyResponse> deleteCohortAnnotationDefinition(
String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId); @Override ResponseEntity<CohortAnnotationDefinition> getCohortAnnotationDefinition(
String workspaceNamespace, String workspaceId, Long cohortId, Long annotationDefinitionId); @Override ResponseEntity<CohortAnnotationDefinitionListResponse> getCohortAnnotationDefinitions(
String workspaceNamespace, String workspaceId, Long cohortId); @Override ResponseEntity<CohortAnnotationDefinition> updateCohortAnnotationDefinition(
String workspaceNamespace,
String workspaceId,
Long cohortId,
Long annotationDefinitionId,
CohortAnnotationDefinition cohortAnnotationDefinitionRequest); }### Answer:
@Test public void getCohortAnnotationDefinitions_NotFoundCohort() { setupWorkspaceServiceMock(); try { cohortAnnotationDefinitionController.getCohortAnnotationDefinitions(NAMESPACE, NAME, 99L); fail("Should have thrown a NotFoundException!"); } catch (NotFoundException e) { assertEquals("Not Found: No Cohort exists for cohortId: " + 99L, e.getMessage()); } }
@Test public void getCohortAnnotationDefinitions() { setupWorkspaceServiceMock(); CohortAnnotationDefinitionListResponse responseDefinition = cohortAnnotationDefinitionController .getCohortAnnotationDefinitions(NAMESPACE, NAME, cohort.getCohortId()) .getBody(); CohortAnnotationDefinition expectedResponse = new CohortAnnotationDefinition() .cohortAnnotationDefinitionId( dbCohortAnnotationDefinition.getCohortAnnotationDefinitionId()) .cohortId(cohort.getCohortId()) .annotationType(AnnotationType.STRING) .columnName(dbCohortAnnotationDefinition.getColumnName()) .enumValues(new ArrayList<>()) .etag(Etags.fromVersion(0)); assertEquals(1, responseDefinition.getItems().size()); assertEquals(expectedResponse, responseDefinition.getItems().get(0)); } |
### Question:
BillingProjectBufferService implements GaugeDataCollector { public DbBillingProjectBufferEntry assignBillingProject(DbUser dbUser) { DbBillingProjectBufferEntry bufferEntry = consumeBufferEntryForAssignment(); fireCloudService.addOwnerToBillingProject( dbUser.getUsername(), bufferEntry.getFireCloudProjectName()); bufferEntry.setStatusEnum(BufferEntryStatus.ASSIGNED, this::getCurrentTimestamp); bufferEntry.setAssignedUser(dbUser); bufferEntry = billingProjectBufferEntryDao.save(bufferEntry); return bufferEntry; } @Autowired BillingProjectBufferService(
BillingProjectBufferEntryDao billingProjectBufferEntryDao,
Clock clock,
FireCloudService fireCloudService,
Provider<WorkbenchConfig> workbenchConfigProvider); void bufferBillingProjects(); @Override Collection<MeasurementBundle> getGaugeData(); void syncBillingProjectStatus(); void cleanBillingBuffer(); DbBillingProjectBufferEntry assignBillingProject(DbUser dbUser); BillingProjectBufferStatus getStatus(); }### Answer:
@Test public void assignBillingProject() { DbBillingProjectBufferEntry entry = new DbBillingProjectBufferEntry(); entry.setStatusEnum(BufferEntryStatus.AVAILABLE, this::getCurrentTimestamp); entry.setFireCloudProjectName("test-project-name"); entry.setCreationTime(getCurrentTimestamp()); billingProjectBufferEntryDao.save(entry); DbUser user = mock(DbUser.class); doReturn("[email protected]").when(user).getUsername(); DbBillingProjectBufferEntry assignedEntry = billingProjectBufferService.assignBillingProject(user); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> secondCaptor = ArgumentCaptor.forClass(String.class); verify(mockFireCloudService).addOwnerToBillingProject(captor.capture(), secondCaptor.capture()); String invokedEmail = captor.getValue(); String invokedProjectName = secondCaptor.getValue(); assertThat(invokedEmail).isEqualTo("[email protected]"); assertThat(invokedProjectName).isEqualTo("test-project-name"); assertThat(billingProjectBufferEntryDao.findOne(assignedEntry.getId()).getStatusEnum()) .isEqualTo(BufferEntryStatus.ASSIGNED); } |
### Question:
WorkspaceAdminController implements WorkspaceAdminApiDelegate { @Override @AuthorityRequired({Authority.RESEARCHER_DATA_VIEW}) public ResponseEntity<WorkspaceAdminView> getWorkspaceAdminView(String workspaceNamespace) { return ResponseEntity.ok(workspaceAdminService.getWorkspaceAdminView(workspaceNamespace)); } @Autowired WorkspaceAdminController(WorkspaceAdminService workspaceAdminService); @Override @AuthorityRequired({Authority.RESEARCHER_DATA_VIEW}) ResponseEntity<CloudStorageTraffic> getCloudStorageTraffic(String workspaceNamespace); @Override @AuthorityRequired({Authority.RESEARCHER_DATA_VIEW}) ResponseEntity<WorkspaceAdminView> getWorkspaceAdminView(String workspaceNamespace); @Override @AuthorityRequired({Authority.RESEARCHER_DATA_VIEW}) ResponseEntity<WorkspaceAuditLogQueryResponse> getAuditLogEntries(
String workspaceNamespace,
Integer limit,
Long afterMillis,
@Nullable Long beforeMillisNullable); @Override @AuthorityRequired({Authority.RESEARCHER_DATA_VIEW}) ResponseEntity<ReadOnlyNotebookResponse> adminReadOnlyNotebook(
String workspaceNamespace, String notebookName, AccessReason accessReason); @Override @AuthorityRequired({Authority.RESEARCHER_DATA_VIEW}) ResponseEntity<List<FileDetail>> listFiles(String workspaceNamespace); }### Answer:
@Test(expected = NotFoundException.class) public void getWorkspaceAdminView_404sWhenNotFound() { doThrow( new NotFoundException( String.format("No workspace found for namespace %s", NONSENSE_NAMESPACE))) .when(mockWorkspaceAdminService) .getWorkspaceAdminView(NONSENSE_NAMESPACE); workspaceAdminController.getWorkspaceAdminView(NONSENSE_NAMESPACE); } |
### Question:
ConceptsController implements ConceptsApiDelegate { @Override public ResponseEntity<DomainCountsListResponse> domainCounts( String workspaceNamespace, String workspaceId, DomainCountsRequest request) { workspaceService.getWorkspaceEnforceAccessLevelAndSetCdrVersion( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); List<DomainCount> counts = conceptService.countDomains( request.getQuery(), request.getSurveyName(), request.getStandardConceptFilter()); return ResponseEntity.ok(new DomainCountsListResponse().domainCounts(counts)); } @Autowired ConceptsController(ConceptService conceptService, WorkspaceService workspaceService); @Override ResponseEntity<DomainInfoResponse> getDomainInfo(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<List<SurveyQuestions>> searchSurveys(
String workspaceNamespace, String workspaceId, SearchSurveysRequest request); @Override ResponseEntity<SurveysResponse> getSurveyInfo(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<DomainCountsListResponse> domainCounts(
String workspaceNamespace, String workspaceId, DomainCountsRequest request); @Override ResponseEntity<ConceptListResponse> searchConcepts(
String workspaceNamespace, String workspaceId, SearchConceptsRequest request); }### Answer:
@Test public void testDomainCountSourceAndStandardTotalCount() { saveConcepts(); saveDomains(); ResponseEntity<DomainCountsListResponse> response = conceptsController.domainCounts( "ns", "name", new DomainCountsRequest().standardConceptFilter(StandardConceptFilter.ALL_CONCEPTS)); assertCounts( response, ImmutableList.of( toDomainCount(CONDITION_DOMAIN, false), toDomainCount(DRUG_DOMAIN, false), toDomainCount(MEASUREMENT_DOMAIN, false), toDomainCount(OBSERVATION_DOMAIN, false), toDomainCount(PROCEDURE_DOMAIN, false), toDomainCount(SURVEY_DOMAIN, 0))); }
@Test public void testDomainCountStandardTotalCount() { saveConcepts(); saveDomains(); ResponseEntity<DomainCountsListResponse> response = conceptsController.domainCounts( "ns", "name", new DomainCountsRequest() .standardConceptFilter(StandardConceptFilter.STANDARD_CONCEPTS)); assertCounts( response, ImmutableList.of( toDomainCount(CONDITION_DOMAIN, true), toDomainCount(DRUG_DOMAIN, true), toDomainCount(MEASUREMENT_DOMAIN, true), toDomainCount(OBSERVATION_DOMAIN, true), toDomainCount(PROCEDURE_DOMAIN, true), toDomainCount(SURVEY_DOMAIN, true))); }
@Test public void testDomainCountStandardWithSearchTerm() { saveConcepts(); saveDomains(); ResponseEntity<DomainCountsListResponse> response = conceptsController.domainCounts( "ns", "name", new DomainCountsRequest() .query("conceptD") .standardConceptFilter(StandardConceptFilter.STANDARD_CONCEPTS)); assertCounts( response, ImmutableList.of( toDomainCount(CONDITION_DOMAIN, 1), toDomainCount(DRUG_DOMAIN, 0), toDomainCount(MEASUREMENT_DOMAIN, 0), toDomainCount(OBSERVATION_DOMAIN, 1), toDomainCount(PROCEDURE_DOMAIN, 0), toDomainCount(SURVEY_DOMAIN, 0))); }
@Test public void testSurveyCountSourceAndStandardWithSurveyName() { saveConcepts(); saveDomains(); ResponseEntity<DomainCountsListResponse> response = conceptsController.domainCounts( "ns", "name", new DomainCountsRequest() .surveyName("The Basics") .standardConceptFilter(StandardConceptFilter.ALL_CONCEPTS)); assertCounts( response, ImmutableList.of( toDomainCount(CONDITION_DOMAIN, false), toDomainCount(DRUG_DOMAIN, false), toDomainCount(MEASUREMENT_DOMAIN, false), toDomainCount(OBSERVATION_DOMAIN, false), toDomainCount(PROCEDURE_DOMAIN, false), toDomainCount(SURVEY_DOMAIN, 0))); } |
### Question:
BillingProjectBufferService implements GaugeDataCollector { public BillingProjectBufferStatus getStatus() { final long bufferSize = billingProjectBufferEntryDao.countByStatus( DbStorageEnums.billingProjectBufferEntryStatusToStorage(BufferEntryStatus.AVAILABLE)); return new BillingProjectBufferStatus().bufferSize(bufferSize); } @Autowired BillingProjectBufferService(
BillingProjectBufferEntryDao billingProjectBufferEntryDao,
Clock clock,
FireCloudService fireCloudService,
Provider<WorkbenchConfig> workbenchConfigProvider); void bufferBillingProjects(); @Override Collection<MeasurementBundle> getGaugeData(); void syncBillingProjectStatus(); void cleanBillingBuffer(); DbBillingProjectBufferEntry assignBillingProject(DbUser dbUser); BillingProjectBufferStatus getStatus(); }### Answer:
@Test public void testGetStatus() { final long numberAvailable = billingProjectBufferEntryDao.countByStatus( DbStorageEnums.billingProjectBufferEntryStatusToStorage(BufferEntryStatus.AVAILABLE)); final BillingProjectBufferStatus bufferStatus = billingProjectBufferService.getStatus(); assertThat(bufferStatus.getBufferSize()).isEqualTo(numberAvailable); } |
### Question:
BillingProjectBufferService implements GaugeDataCollector { @Override public Collection<MeasurementBundle> getGaugeData() { final ImmutableMap<BufferEntryStatus, Long> entryStatusToCount = ImmutableMap.copyOf(billingProjectBufferEntryDao.getCountByStatusMap()); return Arrays.stream(BufferEntryStatus.values()) .map( status -> MeasurementBundle.builder() .addMeasurement( GaugeMetric.BILLING_BUFFER_PROJECT_COUNT, entryStatusToCount.getOrDefault(status, 0L)) .addTag(MetricLabel.BUFFER_ENTRY_STATUS, status.toString()) .build()) .collect(Collectors.toList()); } @Autowired BillingProjectBufferService(
BillingProjectBufferEntryDao billingProjectBufferEntryDao,
Clock clock,
FireCloudService fireCloudService,
Provider<WorkbenchConfig> workbenchConfigProvider); void bufferBillingProjects(); @Override Collection<MeasurementBundle> getGaugeData(); void syncBillingProjectStatus(); void cleanBillingBuffer(); DbBillingProjectBufferEntry assignBillingProject(DbUser dbUser); BillingProjectBufferStatus getStatus(); }### Answer:
@Test public void testGetGaugeData() { final Collection<MeasurementBundle> bundles = billingProjectBufferService.getGaugeData(); assertThat(bundles.size()).isGreaterThan(0); Optional<MeasurementBundle> entryStatusBundle = bundles.stream() .filter(b -> b.getMeasurements().containsKey(GaugeMetric.BILLING_BUFFER_PROJECT_COUNT)) .findFirst(); assertThat(entryStatusBundle.isPresent()).isTrue(); assertThat(entryStatusBundle.get().getTags()).isNotEmpty(); } |
### Question:
ConceptsController implements ConceptsApiDelegate { @Override public ResponseEntity<DomainInfoResponse> getDomainInfo( String workspaceNamespace, String workspaceId) { workspaceService.getWorkspaceEnforceAccessLevelAndSetCdrVersion( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); return ResponseEntity.ok( new DomainInfoResponse() .items( conceptService.getDomainInfo().stream() .map(this::toClientDomainInfo) .collect(Collectors.toList()))); } @Autowired ConceptsController(ConceptService conceptService, WorkspaceService workspaceService); @Override ResponseEntity<DomainInfoResponse> getDomainInfo(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<List<SurveyQuestions>> searchSurveys(
String workspaceNamespace, String workspaceId, SearchSurveysRequest request); @Override ResponseEntity<SurveysResponse> getSurveyInfo(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<DomainCountsListResponse> domainCounts(
String workspaceNamespace, String workspaceId, DomainCountsRequest request); @Override ResponseEntity<ConceptListResponse> searchConcepts(
String workspaceNamespace, String workspaceId, SearchConceptsRequest request); }### Answer:
@Test public void testGetDomainInfo() { saveConcepts(); saveDomains(); List<DomainInfo> domainInfos = conceptsController.getDomainInfo("ns", "name").getBody().getItems(); assertThat(domainInfos) .containsExactly( new DomainInfo() .domain(CONDITION_DOMAIN.getDomainEnum()) .name(CONDITION_DOMAIN.getName()) .description(CONDITION_DOMAIN.getDescription()) .participantCount(CONDITION_DOMAIN.getParticipantCount()) .allConceptCount(CONDITION_DOMAIN.getAllConceptCount()) .standardConceptCount(CONDITION_DOMAIN.getStandardConceptCount()), new DomainInfo() .domain(DRUG_DOMAIN.getDomainEnum()) .name(DRUG_DOMAIN.getName()) .description(DRUG_DOMAIN.getDescription()) .participantCount(DRUG_DOMAIN.getParticipantCount()) .allConceptCount(DRUG_DOMAIN.getAllConceptCount()) .standardConceptCount(DRUG_DOMAIN.getStandardConceptCount()), new DomainInfo() .domain(MEASUREMENT_DOMAIN.getDomainEnum()) .name(MEASUREMENT_DOMAIN.getName()) .description(MEASUREMENT_DOMAIN.getDescription()) .participantCount(MEASUREMENT_DOMAIN.getParticipantCount()) .allConceptCount(MEASUREMENT_DOMAIN.getAllConceptCount()) .standardConceptCount(MEASUREMENT_DOMAIN.getStandardConceptCount()), new DomainInfo() .domain(OBSERVATION_DOMAIN.getDomainEnum()) .name(OBSERVATION_DOMAIN.getName()) .description(OBSERVATION_DOMAIN.getDescription()) .participantCount(OBSERVATION_DOMAIN.getParticipantCount()) .allConceptCount(OBSERVATION_DOMAIN.getAllConceptCount()) .standardConceptCount(OBSERVATION_DOMAIN.getStandardConceptCount()), new DomainInfo() .domain(PROCEDURE_DOMAIN.getDomainEnum()) .name(PROCEDURE_DOMAIN.getName()) .description(PROCEDURE_DOMAIN.getDescription()) .participantCount(PROCEDURE_DOMAIN.getParticipantCount()) .allConceptCount(PROCEDURE_DOMAIN.getAllConceptCount()) .standardConceptCount(PROCEDURE_DOMAIN.getStandardConceptCount())) .inOrder(); } |
### Question:
ConceptsController implements ConceptsApiDelegate { @Override public ResponseEntity<SurveysResponse> getSurveyInfo( String workspaceNamespace, String workspaceId) { workspaceService.getWorkspaceEnforceAccessLevelAndSetCdrVersion( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); return ResponseEntity.ok( new SurveysResponse() .items( conceptService.getSurveyInfo().stream() .map(this::toClientSurveyModule) .collect(Collectors.toList()))); } @Autowired ConceptsController(ConceptService conceptService, WorkspaceService workspaceService); @Override ResponseEntity<DomainInfoResponse> getDomainInfo(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<List<SurveyQuestions>> searchSurveys(
String workspaceNamespace, String workspaceId, SearchSurveysRequest request); @Override ResponseEntity<SurveysResponse> getSurveyInfo(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<DomainCountsListResponse> domainCounts(
String workspaceNamespace, String workspaceId, DomainCountsRequest request); @Override ResponseEntity<ConceptListResponse> searchConcepts(
String workspaceNamespace, String workspaceId, SearchConceptsRequest request); }### Answer:
@Test public void testGetSurveyInfo() { saveSurveyInfo(); List<SurveyModule> surveyModules = conceptsController.getSurveyInfo("ns", "name").getBody().getItems(); assertThat(surveyModules) .containsExactly( new SurveyModule() .conceptId(BASICS_SURVEY_MODULE.getConceptId()) .description(BASICS_SURVEY_MODULE.getDescription()) .name(BASICS_SURVEY_MODULE.getName()) .orderNumber(BASICS_SURVEY_MODULE.getOrderNumber()) .participantCount(BASICS_SURVEY_MODULE.getParticipantCount()) .questionCount(BASICS_SURVEY_MODULE.getQuestionCount()), new SurveyModule() .conceptId(OVERALL_HEALTH_SURVEY_MODULE.getConceptId()) .description(OVERALL_HEALTH_SURVEY_MODULE.getDescription()) .name(OVERALL_HEALTH_SURVEY_MODULE.getName()) .orderNumber(OVERALL_HEALTH_SURVEY_MODULE.getOrderNumber()) .participantCount(OVERALL_HEALTH_SURVEY_MODULE.getParticipantCount()) .questionCount(OVERALL_HEALTH_SURVEY_MODULE.getQuestionCount()), new SurveyModule() .conceptId(LIFESTYLE_SURVEY_MODULE.getConceptId()) .description(LIFESTYLE_SURVEY_MODULE.getDescription()) .name(LIFESTYLE_SURVEY_MODULE.getName()) .orderNumber(LIFESTYLE_SURVEY_MODULE.getOrderNumber()) .participantCount(LIFESTYLE_SURVEY_MODULE.getParticipantCount()) .questionCount(LIFESTYLE_SURVEY_MODULE.getQuestionCount())) .inOrder(); } |
### Question:
ConceptSetsController implements ConceptSetsApiDelegate { @Override public ResponseEntity<ConceptSetListResponse> getConceptSetsInWorkspace( String workspaceNamespace, String workspaceId) { DbWorkspace workspace = workspaceService.getWorkspaceEnforceAccessLevelAndSetCdrVersion( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); List<ConceptSet> conceptSets = conceptSetService.findByWorkspaceId(workspace.getWorkspaceId()).stream() .sorted(Comparator.comparing(ConceptSet::getName)) .collect(Collectors.toList()); return ResponseEntity.ok(new ConceptSetListResponse().items(conceptSets)); } @Autowired ConceptSetsController(
WorkspaceService workspaceService,
ConceptSetService conceptSetService,
UserRecentResourceService userRecentResourceService,
Provider<DbUser> userProvider); @Override ResponseEntity<ConceptSet> createConceptSet(
String workspaceNamespace, String workspaceId, CreateConceptSetRequest request); @Override ResponseEntity<EmptyResponse> deleteConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSet> getConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSetListResponse> getConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<ConceptSetListResponse> getSurveyConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId, String surveyName); @Override ResponseEntity<ConceptSet> updateConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId, ConceptSet conceptSet); @Override ResponseEntity<ConceptSet> updateConceptSetConcepts(
String workspaceNamespace,
String workspaceId,
Long conceptSetId,
UpdateConceptSetRequest request); @Override ResponseEntity<ConceptSet> copyConceptSet(
String fromWorkspaceNamespace,
String fromWorkspaceId,
String fromConceptSetId,
CopyRequest copyRequest); }### Answer:
@Test public void testGetConceptSetsInWorkspaceEmpty() { assertThat( conceptSetsController .getConceptSetsInWorkspace(workspace.getNamespace(), WORKSPACE_NAME) .getBody() .getItems()) .isEmpty(); } |
### Question:
ConceptSetsController implements ConceptSetsApiDelegate { @Override public ResponseEntity<ConceptSet> getConceptSet( String workspaceNamespace, String workspaceId, Long conceptSetId) { workspaceService.getWorkspaceEnforceAccessLevelAndSetCdrVersion( workspaceNamespace, workspaceId, WorkspaceAccessLevel.READER); return ResponseEntity.ok(conceptSetService.getConceptSet(conceptSetId)); } @Autowired ConceptSetsController(
WorkspaceService workspaceService,
ConceptSetService conceptSetService,
UserRecentResourceService userRecentResourceService,
Provider<DbUser> userProvider); @Override ResponseEntity<ConceptSet> createConceptSet(
String workspaceNamespace, String workspaceId, CreateConceptSetRequest request); @Override ResponseEntity<EmptyResponse> deleteConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSet> getConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSetListResponse> getConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<ConceptSetListResponse> getSurveyConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId, String surveyName); @Override ResponseEntity<ConceptSet> updateConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId, ConceptSet conceptSet); @Override ResponseEntity<ConceptSet> updateConceptSetConcepts(
String workspaceNamespace,
String workspaceId,
Long conceptSetId,
UpdateConceptSetRequest request); @Override ResponseEntity<ConceptSet> copyConceptSet(
String fromWorkspaceNamespace,
String fromWorkspaceId,
String fromConceptSetId,
CopyRequest copyRequest); }### Answer:
@Test(expected = NotFoundException.class) public void testGetConceptSetNotExists() { conceptSetsController.getConceptSet(workspace.getNamespace(), WORKSPACE_NAME, 1L); }
@Test(expected = NotFoundException.class) public void testGetSurveyConceptSetWrongConceptId() { makeSurveyConceptSet1(); conceptSetsController.getConceptSet(workspace2.getNamespace(), WORKSPACE_NAME_2, 99L); }
@Test public void testGetConceptSet() { ConceptSet conceptSet = makeConceptSet1(); assertThat( conceptSetsController .getConceptSet(workspace.getNamespace(), WORKSPACE_NAME, conceptSet.getId()) .getBody()) .isEqualTo(conceptSet); assertThat( conceptSetsController .getConceptSetsInWorkspace(workspace.getNamespace(), WORKSPACE_NAME) .getBody() .getItems()) .contains(conceptSet.concepts(null)); assertThat( conceptSetsController .getConceptSetsInWorkspace(workspace2.getNamespace(), WORKSPACE_NAME_2) .getBody() .getItems()) .isEmpty(); }
@Test(expected = NotFoundException.class) public void testGetConceptSetWrongConceptSetId() { makeConceptSet1(); conceptSetsController.getConceptSet(workspace2.getNamespace(), WORKSPACE_NAME_2, 99L); } |
### Question:
ConceptSetsController implements ConceptSetsApiDelegate { @Override public ResponseEntity<ConceptSet> createConceptSet( String workspaceNamespace, String workspaceId, CreateConceptSetRequest request) { validateCreateConceptSetRequest(request); DbWorkspace workspace = workspaceService.getWorkspaceEnforceAccessLevelAndSetCdrVersion( workspaceNamespace, workspaceId, WorkspaceAccessLevel.WRITER); ConceptSet conceptSet = conceptSetService.createConceptSet(request, userProvider.get(), workspace.getWorkspaceId()); userRecentResourceService.updateConceptSetEntry( workspace.getWorkspaceId(), userProvider.get().getUserId(), conceptSet.getId()); return ResponseEntity.ok(conceptSet); } @Autowired ConceptSetsController(
WorkspaceService workspaceService,
ConceptSetService conceptSetService,
UserRecentResourceService userRecentResourceService,
Provider<DbUser> userProvider); @Override ResponseEntity<ConceptSet> createConceptSet(
String workspaceNamespace, String workspaceId, CreateConceptSetRequest request); @Override ResponseEntity<EmptyResponse> deleteConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSet> getConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSetListResponse> getConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<ConceptSetListResponse> getSurveyConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId, String surveyName); @Override ResponseEntity<ConceptSet> updateConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId, ConceptSet conceptSet); @Override ResponseEntity<ConceptSet> updateConceptSetConcepts(
String workspaceNamespace,
String workspaceId,
Long conceptSetId,
UpdateConceptSetRequest request); @Override ResponseEntity<ConceptSet> copyConceptSet(
String fromWorkspaceNamespace,
String fromWorkspaceId,
String fromConceptSetId,
CopyRequest copyRequest); }### Answer:
@Test public void testCreateConceptSet() { ConceptSet conceptSet = new ConceptSet(); conceptSet.setDescription("desc 1"); conceptSet.setName("concept set 1"); conceptSet.setDomain(Domain.CONDITION); conceptSet = conceptSetsController .createConceptSet( workspace.getNamespace(), WORKSPACE_NAME, new CreateConceptSetRequest() .conceptSet(conceptSet) .addAddedIdsItem(CLIENT_CONCEPT_1.getConceptId())) .getBody(); assertThat(conceptSet.getConcepts()).isNotNull(); assertThat(conceptSet.getCreationTime()).isEqualTo(NOW.toEpochMilli()); assertThat(conceptSet.getDescription()).isEqualTo("desc 1"); assertThat(conceptSet.getDomain()).isEqualTo(Domain.CONDITION); assertThat(conceptSet.getEtag()).isEqualTo(Etags.fromVersion(1)); assertThat(conceptSet.getLastModifiedTime()).isEqualTo(NOW.toEpochMilli()); assertThat(conceptSet.getName()).isEqualTo("concept set 1"); assertThat(conceptSet.getParticipantCount()).isEqualTo(0); assertThat( conceptSetsController .getConceptSet(workspace.getNamespace(), WORKSPACE_NAME, conceptSet.getId()) .getBody()) .isEqualTo(conceptSet); assertThat( conceptSetsController .getConceptSetsInWorkspace(workspace.getNamespace(), WORKSPACE_NAME) .getBody() .getItems()) .contains(conceptSet.concepts(null)); assertThat( conceptSetsController .getConceptSetsInWorkspace(workspace2.getNamespace(), WORKSPACE_NAME_2) .getBody() .getItems()) .isEmpty(); } |
### Question:
ConceptSetsController implements ConceptSetsApiDelegate { @Override public ResponseEntity<EmptyResponse> deleteConceptSet( String workspaceNamespace, String workspaceId, Long conceptSetId) { conceptSetService.delete(conceptSetId); return ResponseEntity.ok(new EmptyResponse()); } @Autowired ConceptSetsController(
WorkspaceService workspaceService,
ConceptSetService conceptSetService,
UserRecentResourceService userRecentResourceService,
Provider<DbUser> userProvider); @Override ResponseEntity<ConceptSet> createConceptSet(
String workspaceNamespace, String workspaceId, CreateConceptSetRequest request); @Override ResponseEntity<EmptyResponse> deleteConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSet> getConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId); @Override ResponseEntity<ConceptSetListResponse> getConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId); @Override ResponseEntity<ConceptSetListResponse> getSurveyConceptSetsInWorkspace(
String workspaceNamespace, String workspaceId, String surveyName); @Override ResponseEntity<ConceptSet> updateConceptSet(
String workspaceNamespace, String workspaceId, Long conceptSetId, ConceptSet conceptSet); @Override ResponseEntity<ConceptSet> updateConceptSetConcepts(
String workspaceNamespace,
String workspaceId,
Long conceptSetId,
UpdateConceptSetRequest request); @Override ResponseEntity<ConceptSet> copyConceptSet(
String fromWorkspaceNamespace,
String fromWorkspaceId,
String fromConceptSetId,
CopyRequest copyRequest); }### Answer:
@Test public void testDeleteConceptSet() { saveConcepts(); ConceptSetService.MAX_CONCEPTS_PER_SET = 1000; ConceptSet conceptSet1 = makeConceptSet1(); ConceptSet conceptSet2 = makeConceptSet2(); ConceptSet updatedConceptSet = conceptSetsController .updateConceptSetConcepts( workspace.getNamespace(), WORKSPACE_NAME, conceptSet1.getId(), addConceptsRequest( conceptSet1.getEtag(), CLIENT_CONCEPT_1.getConceptId(), CLIENT_CONCEPT_3.getConceptId(), CLIENT_CONCEPT_4.getConceptId())) .getBody(); ConceptSet updatedConceptSet2 = conceptSetsController .updateConceptSetConcepts( workspace.getNamespace(), WORKSPACE_NAME, conceptSet2.getId(), addConceptsRequest(conceptSet2.getEtag(), CLIENT_CONCEPT_2.getConceptId())) .getBody(); assertThat(updatedConceptSet.getConcepts()) .containsExactly(CLIENT_CONCEPT_1, CLIENT_CONCEPT_3, CLIENT_CONCEPT_4); assertThat(updatedConceptSet2.getConcepts()).containsExactly(CLIENT_CONCEPT_2); conceptSetsController.deleteConceptSet( workspace.getNamespace(), WORKSPACE_NAME, conceptSet1.getId()); try { conceptSetsController.getConceptSet( workspace.getNamespace(), WORKSPACE_NAME, conceptSet1.getId()); fail("NotFoundException expected"); } catch (NotFoundException e) { } conceptSet2 = conceptSetsController .getConceptSet(workspace.getNamespace(), WORKSPACE_NAME, conceptSet2.getId()) .getBody(); assertThat(conceptSet2.getConcepts()).containsExactly(CLIENT_CONCEPT_2); } |
### Question:
StatusAlertController implements StatusAlertApiDelegate { @Override public ResponseEntity<StatusAlert> getStatusAlert() { Optional<DbStatusAlert> dbStatusAlertOptional = statusAlertDao.findFirstByOrderByStatusAlertIdDesc(); if (dbStatusAlertOptional.isPresent()) { DbStatusAlert dbStatusAlert = dbStatusAlertOptional.get(); return ResponseEntity.ok(StatusAlertConversionUtils.toApiStatusAlert(dbStatusAlert)); } else { return ResponseEntity.ok(new StatusAlert()); } } @Autowired StatusAlertController(StatusAlertDao statusAlertDao); @Override ResponseEntity<StatusAlert> getStatusAlert(); @Override @AuthorityRequired(Authority.COMMUNICATIONS_ADMIN) ResponseEntity<StatusAlert> postStatusAlert(StatusAlert statusAlert); }### Answer:
@Test public void testGetStatusAlert() { StatusAlert statusAlert = statusAlertController.getStatusAlert().getBody(); assertThat(statusAlert.getTitle()).matches(STATUS_ALERT_INITIAL_TITLE); assertThat(statusAlert.getMessage()).matches(STATUS_ALERT_INITIAL_DESCRIPTION); } |
### Question:
StatusAlertController implements StatusAlertApiDelegate { @Override @AuthorityRequired(Authority.COMMUNICATIONS_ADMIN) public ResponseEntity<StatusAlert> postStatusAlert(StatusAlert statusAlert) { Iterable<DbStatusAlert> dbStatusAlertList = statusAlertDao.findAll(); dbStatusAlertList.forEach( statusAlert1 -> statusAlertDao.delete(statusAlert1.getStatusAlertId())); DbStatusAlert dbStatusAlert = statusAlertDao.save(StatusAlertConversionUtils.toDbStatusAlert(statusAlert)); return ResponseEntity.ok(StatusAlertConversionUtils.toApiStatusAlert(dbStatusAlert)); } @Autowired StatusAlertController(StatusAlertDao statusAlertDao); @Override ResponseEntity<StatusAlert> getStatusAlert(); @Override @AuthorityRequired(Authority.COMMUNICATIONS_ADMIN) ResponseEntity<StatusAlert> postStatusAlert(StatusAlert statusAlert); }### Answer:
@Test public void testPostStatusAlert() { String updatedStatusAlertTitle = "Title 2"; String updatedStatusAlertDescription = "Description 2"; String updatedStatusAlertLink = "This has a link"; StatusAlert statusAlert = new StatusAlert() .title(updatedStatusAlertTitle) .message(updatedStatusAlertDescription) .link(updatedStatusAlertLink); statusAlertController.postStatusAlert(statusAlert); StatusAlert updatedStatusAlert = statusAlertController.getStatusAlert().getBody(); assertThat(updatedStatusAlert.getTitle()).matches(updatedStatusAlertTitle); assertThat(updatedStatusAlert.getMessage()).matches(updatedStatusAlertDescription); assertThat(updatedStatusAlert.getLink()).matches(updatedStatusAlertLink); } |
### Question:
CdrVersionsController implements CdrVersionsApiDelegate { @Override public ResponseEntity<CdrVersionListResponse> getCdrVersions() { DataAccessLevel accessLevel = userProvider.get().getDataAccessLevelEnum(); List<DbCdrVersion> cdrVersions = cdrVersionService.findAuthorizedCdrVersions(accessLevel); if (cdrVersions.isEmpty()) { throw new ForbiddenException("User does not have access to any CDR versions"); } List<Long> defaultVersions = cdrVersions.stream() .filter(v -> v.getIsDefault()) .map(DbCdrVersion::getCdrVersionId) .collect(Collectors.toList()); if (defaultVersions.isEmpty()) { throw new ForbiddenException("User does not have access to a default CDR version"); } if (defaultVersions.size() > 1) { log.severe( String.format( "Found multiple (%d) default CDR versions, picking one", defaultVersions.size())); } return ResponseEntity.ok( new CdrVersionListResponse() .items( cdrVersions.stream() .map(cdrVersionMapper::dbModelToClient) .collect(Collectors.toList())) .defaultCdrVersionId(Long.toString(defaultVersions.get(0)))); } @Autowired CdrVersionsController(
CdrVersionService cdrVersionService,
CdrVersionMapper cdrVersionMapper,
Provider<DbUser> userProvider); @Override ResponseEntity<CdrVersionListResponse> getCdrVersions(); }### Answer:
@Test public void testGetCdrVersionsRegistered() { assertResponse(cdrVersionsController.getCdrVersions().getBody(), defaultCdrVersion); }
@Test public void testGetCdrVersions_microarray() { user.setDataAccessLevelEnum(DataAccessLevel.PROTECTED); List<CdrVersion> cdrVersions = cdrVersionsController.getCdrVersions().getBody().getItems(); assertThat( cdrVersions.stream() .filter(v -> v.getName().equals("Test Registered CDR")) .findFirst() .get() .getHasMicroarrayData()) .isFalse(); assertThat( cdrVersions.stream() .filter(v -> v.getName().equals("Test Protected CDR")) .findFirst() .get() .getHasMicroarrayData()) .isTrue(); }
@Test public void testGetCdrVersionsProtected() { user.setDataAccessLevelEnum(DataAccessLevel.PROTECTED); assertResponse( cdrVersionsController.getCdrVersions().getBody(), protectedCdrVersion, defaultCdrVersion); }
@Test(expected = ForbiddenException.class) public void testGetCdrVersionsUnregistered() { user.setDataAccessLevelEnum(DataAccessLevel.UNREGISTERED); cdrVersionsController.getCdrVersions(); } |
### Question:
OfflineAuditController implements OfflineAuditApiDelegate { @VisibleForTesting static String auditTableSuffix(Instant now, int daysAgo) { Instant target = now.minus(daysAgo, ChronoUnit.DAYS); return auditTableNameDateFormatter.withZone(ZoneId.of("UTC")).format(target); } @Autowired OfflineAuditController(
Clock clock,
BigQueryService bigQueryService,
CdrVersionDao cdrVersionDao,
WorkspaceDao workspaceDao); @Override ResponseEntity<AuditBigQueryResponse> auditBigQuery(); }### Answer:
@Test public void testAuditTableSuffix() { assertThat(OfflineAuditController.auditTableSuffix(Instant.parse("2007-01-03T00:00:00.00Z"), 0)) .isEqualTo("20070103"); assertThat(OfflineAuditController.auditTableSuffix(Instant.parse("2018-01-01T23:59:59.00Z"), 3)) .isEqualTo("20171229"); } |
### Question:
OfflineAuditController implements OfflineAuditApiDelegate { @Override public ResponseEntity<AuditBigQueryResponse> auditBigQuery() { Set<String> cdrProjects = ImmutableList.copyOf(cdrVersionDao.findAll()).stream() .map(v -> v.getBigqueryProject()) .collect(Collectors.toSet()); Set<String> whitelist = Sets.union(workspaceDao.findAllWorkspaceNamespaces(), cdrProjects); Instant now = clock.instant(); List<String> suffixes = IntStream.range(0, AUDIT_DAY_RANGE) .mapToObj(i -> auditTableSuffix(now, i)) .collect(Collectors.toList()); int numBad = 0; int numQueries = 0; for (String cdrProjectId : cdrProjects) { TableResult result = bigQueryService.executeQuery(QueryJobConfiguration.of(auditSql(cdrProjectId, suffixes))); Map<String, Integer> rm = bigQueryService.getResultMapper(result); for (List<FieldValue> row : result.iterateAll()) { String project_id = bigQueryService.getString(row, rm.get("client_project_id")); String email = bigQueryService.getString(row, rm.get("user_email")); long total = bigQueryService.getLong(row, rm.get("total")); if (bigQueryService.isNull(row, rm.get("client_project_id"))) { log.severe( String.format( "AUDIT: (CDR project '%s') %d queries with missing project ID from user '%s'; " + "indicates an ACL misconfiguration, this user can access the CDR but is not a " + "project jobUser", cdrProjectId, total, email)); numBad += total; } else if (!whitelist.contains(project_id)) { log.severe( String.format( "AUDIT: (CDR project '%s') %d queries in unrecognized project '%s' from user '%s'", cdrProjectId, total, project_id, email)); numBad += total; } numQueries += total; } } log.info( String.format("AUDIT: found audit issues with %d/%d BigQuery queries", numBad, numQueries)); return ResponseEntity.ok(new AuditBigQueryResponse().numQueryIssues(numBad)); } @Autowired OfflineAuditController(
Clock clock,
BigQueryService bigQueryService,
CdrVersionDao cdrVersionDao,
WorkspaceDao workspaceDao); @Override ResponseEntity<AuditBigQueryResponse> auditBigQuery(); }### Answer:
@Test public void testAuditBigQueryCdrV1Queries() { stubBigQueryCalls(CDR_V1_PROJECT_ID, USER_EMAIL, 5); assertThat(offlineAuditController.auditBigQuery().getBody().getNumQueryIssues()).isEqualTo(0); }
@Test public void testAuditBigQueryCdrV2Queries() { stubBigQueryCalls(CDR_V2_PROJECT_ID, USER_EMAIL, 5); assertThat(offlineAuditController.auditBigQuery().getBody().getNumQueryIssues()).isEqualTo(0); }
@Test public void testAuditBigQueryFirecloudQueries() { stubBigQueryCalls(FC_PROJECT_ID, USER_EMAIL, 5); assertThat(offlineAuditController.auditBigQuery().getBody().getNumQueryIssues()).isEqualTo(0); }
@Test public void testAuditBigQueryUnrecognizedProjectQueries() { stubBigQueryCalls("my-personal-gcp-project", USER_EMAIL, 5); assertThat(offlineAuditController.auditBigQuery().getBody().getNumQueryIssues()).isEqualTo(10); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@Test(expected = BadRequestException.class) public void validateProfile_emptyNewObject() { profileService.validateNewProfile(new Profile()); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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; }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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; }### Answer:
@Test public void testDecorateParameterName() { assertThat(decorateParameterName("foo")).isEqualTo("@foo"); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test public void testInstantToQpvValue_nullInput() { final QueryParameterValue qpv = instantToQPValue(null); assertThat(qpv.getType()).isEqualTo(StandardSQLTypeName.TIMESTAMP); assertThat(qpv.getValue()).isNull(); } |
### Question:
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; }### Answer:
@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); } |
### Question:
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; }### Answer:
@Test public void testTimestampQpvToInstant_nullQpvValue() { assertThat(timestampQpvToInstant(QueryParameterValue.timestamp((String) null))).isEmpty(); }
@Test(expected = IllegalArgumentException.class) public void testTimestampQpvToInstant_wrongQpvType() { timestampQpvToInstant(QueryParameterValue.bool(false)); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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; }### Answer:
@Test public void testTimestampStringToInstant_nullInput() { assertThat(timestampStringToInstant(null)).isEmpty(); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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; }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void testRandomizeAlleles() { List<Allele> alleles = randomizeVcf.randomizeAlleles(variantContext); assertThat(alleles.size()).isEqualTo(2); alleles.forEach(allele -> assertThat(variantContext.getAlleles()).contains(allele)); } |
### Question:
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); }### Answer:
@Test public void testUpdateShibbolethToken() throws Exception { shibbolethService.updateShibbolethToken("asdf"); verify(shibbolethApi, times(1)).postShibbolethToken("asdf"); } |
### Question:
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); }### Answer:
@Test(expected = GatewayTimeoutException.class) public void convertNotebookException() throws Exception { ApiException cause = new ApiException(new SocketTimeoutException()); ExceptionUtils.convertNotebookException(cause); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test(expected = IllegalStateException.class) public void testBuild_unsupportedAttachmentValueThrows() { MeasurementBundle.builder() .addTag(MetricLabel.BUFFER_ENTRY_STATUS, "lost and gone forever") .build(); } |
### Question:
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(); }### Answer:
@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(); } |
### Question:
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; }### Answer:
@Test public void testMakeMonitoredResource_noInstanceIdAvailable() { doThrow(ModulesException.class).when(mockModulesService).getCurrentInstanceId(); final MonitoredResource monitoredResource = exporterService.makeStackdriverStatsConfiguration().getMonitoredResource(); assertThat(monitoredResource.getLabelsMap().get("node_id")).isNotEmpty(); } |
### Question:
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); }### Answer:
@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())); } |
### Question:
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); }### Answer:
@Test public void testDeleteRuntime() throws ApiException { runtimeController.deleteRuntime(BILLING_PROJECT_ID); verify(userRuntimesApi).deleteRuntime(BILLING_PROJECT_ID, getRuntimeName(), false); } |
### Question:
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); }### Answer:
@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: } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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; }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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()); } |
### Question:
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); }### Answer:
@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(); } |
### Question:
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); }### Answer:
@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"); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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>>>(){}); } |
### Question:
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(); }### Answer:
@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)); } |
### Question:
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); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@Test public void toBuilder() { BatchWriteItemEnhancedRequest builtObject = BatchWriteItemEnhancedRequest.builder().build(); BatchWriteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
### Question:
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(); }### Answer:
@Test public void toBuilder() { PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class).build(); PutItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
### Question:
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(); }### Answer:
@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()); } |
### Question:
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(); }### Answer:
@Test public void toBuilder() { ScanEnhancedRequest builtObject = ScanEnhancedRequest.builder().exclusiveStartKey(null).build(); ScanEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.