method2testcases
stringlengths
118
3.08k
### Question: ServiceNameValidator implements ParameterValidator { @Override public Object attemptToCorrect(Object serviceName, final Map<String, Object> relatedParameters) { if (!(serviceName instanceof String)) { throw new ContentException(Messages.COULD_NOT_CREATE_VALID_SERVICE_NAME_FROM_0, serviceName); } boolean applyNamespaceLocal = MapUtil.parseBooleanFlag(relatedParameters, SupportedParameters.APPLY_NAMESPACE, true); boolean applyNamespace = applyNamespaceGlobal && applyNamespaceLocal; return NameUtil.computeValidServiceName((String) serviceName, namespace, applyNamespace); } ServiceNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object serviceName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object serviceName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer: @Test void testCorrectionWithNoNamespaces() { ServiceNameValidator serviceNameValidator = new ServiceNameValidator(null, false); String result = (String) serviceNameValidator.attemptToCorrect(SERVICE_NAME, CONTEXT_DO_NOT_APPLY_NAMESPACE); assertEquals(SERVICE_NAME, result); } @Test void testCorrectionWithNamespaces() { ServiceNameValidator serviceNameValidator = new ServiceNameValidator(NAMESPACE, true); String result = (String) serviceNameValidator.attemptToCorrect(SERVICE_NAME, CONTEXT_APPLY_NAMESPACE); assertEquals(String.format("%s" + Constants.NAMESPACE_SEPARATOR + "%s", NAMESPACE, SERVICE_NAME), result); } @Test void testCorrectionWithInvalidServiceName() { ServiceNameValidator serviceNameValidator = new ServiceNameValidator(NAMESPACE, false); assertThrows(ContentException.class, () -> serviceNameValidator.attemptToCorrect(Collections.emptyList(), CONTEXT_DO_NOT_APPLY_NAMESPACE)); }
### Question: ServiceNameValidator implements ParameterValidator { @Override public boolean isValid(Object serviceName, final Map<String, Object> context) { return false; } ServiceNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object serviceName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object serviceName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer: @Test void testValidation() { ServiceNameValidator serviceNameValidator = new ServiceNameValidator(NAMESPACE, false); assertFalse(serviceNameValidator.isValid(SERVICE_NAME, null)); }
### Question: ServiceNameValidator implements ParameterValidator { @Override public Class<?> getContainerType() { return Resource.class; } ServiceNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object serviceName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object serviceName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer: @Test void testGetContainerType() { ServiceNameValidator serviceNameValidator = new ServiceNameValidator(NAMESPACE, false); assertEquals(Resource.class, serviceNameValidator.getContainerType()); }
### Question: ServiceNameValidator implements ParameterValidator { @Override public String getParameterName() { return SupportedParameters.SERVICE_NAME; } ServiceNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object serviceName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object serviceName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer: @Test void testGetParameterName() { ServiceNameValidator serviceNameValidator = new ServiceNameValidator(NAMESPACE, false); assertEquals(SupportedParameters.SERVICE_NAME, serviceNameValidator.getParameterName()); }
### Question: ServiceNameValidator implements ParameterValidator { @Override public boolean canCorrect() { return true; } ServiceNameValidator(String namespace, boolean applyNamespace); @Override Class<?> getContainerType(); @Override String getParameterName(); @Override boolean isValid(Object serviceName, final Map<String, Object> context); @Override boolean canCorrect(); @Override Object attemptToCorrect(Object serviceName, final Map<String, Object> relatedParameters); @Override Set<String> getRelatedParameterNames(); }### Answer: @Test void testCanCorrect() { ServiceNameValidator serviceNameValidator = new ServiceNameValidator(NAMESPACE, false); assertTrue(serviceNameValidator.canCorrect()); }
### Question: CachedObject { public synchronized T get(Supplier<T> refreshFunction) { long currentTime = currentTimeSupplier.getAsLong(); long millisecondsSinceLastRefresh = currentTime - lastRefreshTime; long secondsSinceLastRefresh = TimeUnit.MILLISECONDS.toSeconds(millisecondsSinceLastRefresh); if (object == null || secondsSinceLastRefresh > expirationTimeInSeconds) { this.object = refreshFunction.get(); this.lastRefreshTime = currentTimeSupplier.getAsLong(); } return object; } CachedObject(long expirationTimeInSeconds); CachedObject(long expirationTimeInSeconds, LongSupplier currentTimeSupplier); synchronized T get(Supplier<T> refreshFunction); synchronized T forceRefresh(Supplier<T> refreshFunction); }### Answer: @SuppressWarnings("unchecked") @Test void testGet() { LongSupplier currentTimeSupplier = Mockito.mock(LongSupplier.class); Mockito.when(currentTimeSupplier.getAsLong()) .thenReturn(0L, toMillis(5), toMillis(15), toMillis(25), toMillis(30)); Supplier<String> refreshFunction = Mockito.mock(Supplier.class); Mockito.when(refreshFunction.get()) .thenReturn("a", "b"); CachedObject<String> cachedName = new CachedObject<>(10, currentTimeSupplier); assertEquals("a", cachedName.get(refreshFunction)); assertEquals("a", cachedName.get(refreshFunction)); assertEquals("b", cachedName.get(refreshFunction)); assertEquals("b", cachedName.get(refreshFunction)); assertEquals("b", cachedName.get(refreshFunction)); }
### Question: CachedObject { public synchronized T forceRefresh(Supplier<T> refreshFunction) { object = refreshFunction.get(); lastRefreshTime = currentTimeSupplier.getAsLong(); return object; } CachedObject(long expirationTimeInSeconds); CachedObject(long expirationTimeInSeconds, LongSupplier currentTimeSupplier); synchronized T get(Supplier<T> refreshFunction); synchronized T forceRefresh(Supplier<T> refreshFunction); }### Answer: @SuppressWarnings("unchecked") @Test void testForceRefresh() { LongSupplier currentTimeSupplier = Mockito.mock(LongSupplier.class); Mockito.when(currentTimeSupplier.getAsLong()) .thenReturn(0L, toMillis(5), toMillis(10), toMillis(15), toMillis(25)); Supplier<String> refreshFunction = Mockito.mock(Supplier.class); Mockito.when(refreshFunction.get()) .thenReturn("a", "b", "c"); CachedObject<String> cachedName = new CachedObject<>(20, currentTimeSupplier); assertEquals("a", cachedName.get(refreshFunction)); assertEquals("a", cachedName.get(refreshFunction)); assertEquals("b", cachedName.forceRefresh(refreshFunction)); assertEquals("b", cachedName.get(refreshFunction)); }
### Question: HealthRetriever { public Health getHealth() { HealthCheckConfiguration healthCheckConfiguration = configuration.getHealthCheckConfiguration(); ZonedDateTime currentTime = currentTimeSupplier.get(); ZonedDateTime xSecondsAgo = currentTime.minusSeconds(healthCheckConfiguration.getTimeRangeInSeconds()); List<Operation> healthCheckOperations = getHealthCheckOperations(healthCheckConfiguration, xSecondsAgo); return Health.fromOperations(healthCheckOperations); } @Inject HealthRetriever(OperationService operationService, ApplicationConfiguration configuration); protected HealthRetriever(OperationService operationService, ApplicationConfiguration configuration, Supplier<ZonedDateTime> currentTimeSupplier); Health getHealth(); }### Answer: @Test void testGetHealth() { prepareConfiguration(ImmutableHealthCheckConfiguration.builder() .mtaId(MTA_ID) .spaceId(SPACE_ID) .userName(USER_NAME) .timeRangeInSeconds(TIME_RANGE_IN_SECONDS) .build()); Health health = healthRetriever.getHealth(); assertTrue(health.isHealthy()); assertEquals(1, health.getHealthCheckOperations() .size()); HealthCheckOperation healthCheckOperation = health.getHealthCheckOperations() .get(0); validateHealthCheckOperationParameters(healthCheckOperation); Mockito.verify(operationQuery, times(1)) .user(USER_NAME); validateMandatoryParametersAreSet(); }
### Question: ObjectStoreFileStorage implements FileStorage { @Override public void deleteFilesBySpace(String space) { removeBlobsByFilter(blob -> filterBySpace(blob, space)); } ObjectStoreFileStorage(BlobStore blobStore, String container); @Override void addFile(FileEntry fileEntry, File file); @Override List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries); @Override void deleteFile(String id, String space); @Override void deleteFilesBySpace(String space); @Override void deleteFilesBySpaceAndNamespace(String space, String namespace); @Override int deleteFilesModifiedBefore(Date modificationTime); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); }### Answer: @Test void deleteFilesBySpace() throws Exception { FileEntry firstFile = addFile(TEST_FILE_LOCATION); FileEntry secondFile = addFile(SECOND_FILE_TEST_LOCATION); FileEntry fileInOtherSpace = addFile(TEST_FILE_LOCATION, "otherspace", namespace); fileStorage.deleteFilesBySpace(spaceId); assertFileExists(false, firstFile); assertFileExists(false, secondFile); assertFileExists(true, fileInOtherSpace); }
### Question: DataTerminationService { public void deleteOrphanUserData() { assertGlobalAuditorCredentialsExist(); List<String> deleteSpaceEventsToBeDeleted = getDeleteSpaceEvents(); for (String spaceId : deleteSpaceEventsToBeDeleted) { deleteConfigurationSubscriptionOrphanData(spaceId); deleteConfigurationEntryOrphanData(spaceId); deleteUserOperationsOrphanData(spaceId); deleteSpaceLeftovers(spaceId); } } void deleteOrphanUserData(); }### Answer: @Test void testMissingAuditorCredentials() { Exception exception = assertThrows(IllegalStateException.class, () -> dataTerminationService.deleteOrphanUserData()); assertEquals(Messages.MISSING_GLOBAL_AUDITOR_CREDENTIALS, exception.getMessage()); } @Test void testFailToDeleteSpace() throws FileStorageException { prepareGlobalAuditorCredentials(); prepareCfOptimizedEventsGetter(generateDeletedSpaces(1)); when(configurationEntryService.createQuery()).thenReturn(configurationEntryQuery); when(configurationSubscriptionService.createQuery()).thenReturn(configurationSubscriptionQuery); when(operationService.createQuery()).thenReturn(operationQuery); when(fileService.deleteBySpace(anyString())).thenThrow(new FileStorageException("")); Exception exception = assertThrows(SLException.class, () -> dataTerminationService.deleteOrphanUserData()); assertEquals(Messages.COULD_NOT_DELETE_SPACE_LEFTOVERS, exception.getMessage()); }
### Question: CredentialsGenerator { public String next(int length) { StringBuilder credential = new StringBuilder(length); for (int i = 0; i < length; i++) { int randomIndex = randomGenerator.nextInt(LEGAL_CHARACTERS.length); credential.append(LEGAL_CHARACTERS[randomIndex]); } return credential.toString(); } CredentialsGenerator(); protected CredentialsGenerator(SecureRandom randomGenerator); String next(int length); }### Answer: @Test void testGenerate() throws NoSuchAlgorithmException, NoSuchProviderException { SecureRandom randomGenerator = SecureRandom.getInstance("SHA1PRNG", "SUN"); randomGenerator.setSeed(69); CredentialsGenerator credentialsGenerator = new CredentialsGenerator(randomGenerator); assertEquals("r&k37&tl2*D[MK7C", credentialsGenerator.next(16)); assertEquals("dd*Qz99LI1CB49(*", credentialsGenerator.next(16)); assertEquals("4y(m4ZMfpcY8#g7ur74K@@vXmAAJ4s2(", credentialsGenerator.next(32)); }
### Question: MtaConfigurationPurger { public void purge(String org, String space) { CloudTarget targetSpace = new CloudTarget(org, space); String targetId = new ClientHelper(client).computeSpaceId(org, space); List<CloudApplication> existingApps = getExistingApps(); purgeConfigurationSubscriptions(targetId, existingApps); purgeConfigurationEntries(targetSpace, existingApps); } MtaConfigurationPurger(CloudControllerClient client, ConfigurationEntryService configurationEntryService, ConfigurationSubscriptionService configurationSubscriptionService, MtaMetadataParser mtaMetadataParser); void purge(String org, String space); }### Answer: @Test void testPurge() { MtaConfigurationPurger purger = new MtaConfigurationPurger(client, configurationEntryService, configurationSubscriptionService, new MtaMetadataParser(new MtaMetadataValidator())); purger.purge("org", "space"); verifyConfigurationEntriesDeleted(); verifyConfigurationEntriesNotDeleted(); Mockito.verify(auditLoggingFacade) .logConfigDelete(ENTRY_TO_DELETE); Mockito.verify(auditLoggingFacade) .logConfigDelete(SUBSCRIPTION_TO_DELETE); }
### Question: DescriptorParserFacadeFactory { public DescriptorParserFacade getInstance() { LoaderOptions loaderOptions = new LoaderOptions(); loaderOptions.setMaxAliasesForCollections(applicationConfiguration.getSnakeyamlMaxAliasesForCollections()); YamlParser yamlParser = new YamlParser(loaderOptions); return new DescriptorParserFacade(yamlParser); } @Inject DescriptorParserFacadeFactory(ApplicationConfiguration applicationConfiguration); DescriptorParserFacade getInstance(); }### Answer: @Test void testGetInstance() { final int maxAliases = 5; ApplicationConfiguration applicationConfiguration = Mockito.mock(ApplicationConfiguration.class); Mockito.when(applicationConfiguration.getSnakeyamlMaxAliasesForCollections()) .thenReturn(maxAliases); DescriptorParserFacadeFactory descriptorParserFacadeFactory = new DescriptorParserFacadeFactory(applicationConfiguration); DescriptorParserFacade instance = descriptorParserFacadeFactory.getInstance(); InputStream mtadYaml = getClass().getResourceAsStream("billion-laughs.mtad.yaml"); Assertions.assertThrows(ParsingException.class, () -> instance.parseDeploymentDescriptor(mtadYaml)); }
### Question: ClientHelper { public void deleteRoute(String uri) { ApplicationURI route = new ApplicationURI(uri); client.deleteRoute(route.getHost(), route.getDomain(), route.getPath()); } ClientHelper(CloudControllerClient client); void deleteRoute(String uri); String computeSpaceId(String orgName, String spaceName); CloudTarget computeTarget(String spaceId); }### Answer: @Test void testDeleteRoute() { String uri = "https: clientHelper.deleteRoute(uri); ApplicationURI route = new ApplicationURI(uri); Mockito.verify(client) .deleteRoute(route.getHost(), route.getDomain(), route.getPath()); }
### Question: ClientHelper { public String computeSpaceId(String orgName, String spaceName) { CloudSpace space = client.getSpace(orgName, spaceName, false); if (space != null) { return space.getMetadata() .getGuid() .toString(); } return null; } ClientHelper(CloudControllerClient client); void deleteRoute(String uri); String computeSpaceId(String orgName, String spaceName); CloudTarget computeTarget(String spaceId); }### Answer: @Test void testComputeSpaceId() { Mockito.when(client.getSpace(ORG_NAME, SPACE_NAME, false)) .thenReturn(createCloudSpace(GUID, SPACE_NAME, ORG_NAME)); String spaceId = clientHelper.computeSpaceId(ORG_NAME, SPACE_NAME); Assertions.assertEquals(GUID.toString(), spaceId); } @Test void testComputeSpaceIdIfSpaceIsNull() { Assertions.assertNull(clientHelper.computeSpaceId(ORG_NAME, SPACE_NAME)); }
### Question: ClientHelper { public CloudTarget computeTarget(String spaceId) { CloudSpace space = attemptToFindSpace(spaceId); if (space != null) { return new CloudTarget(space.getOrganization() .getName(), space.getName()); } return null; } ClientHelper(CloudControllerClient client); void deleteRoute(String uri); String computeSpaceId(String orgName, String spaceName); CloudTarget computeTarget(String spaceId); }### Answer: @Test void testComputeTarget() { Mockito.when(client.getSpace(Matchers.any(UUID.class))) .thenReturn(createCloudSpace(GUID, SPACE_NAME, ORG_NAME)); CloudTarget target = clientHelper.computeTarget(SPACE_ID); Assertions.assertEquals(ORG_NAME, target.getOrganizationName()); Assertions.assertEquals(SPACE_NAME, target.getSpaceName()); } @Test void testComputeTargetCloudOperationExceptionForbiddenThrown() { Mockito.when(client.getSpace(Matchers.any(UUID.class))) .thenThrow(new CloudOperationException(HttpStatus.FORBIDDEN)); Assertions.assertNull(clientHelper.computeTarget(SPACE_ID)); } @Test void testComputeTargetCloudOperationExceptionNotFoundThrown() { Mockito.when(client.getSpace(Matchers.any(UUID.class))) .thenThrow(new CloudOperationException(HttpStatus.NOT_FOUND)); Assertions.assertNull(clientHelper.computeTarget(SPACE_ID)); } @Test void testComputeTargetCloudOperationExceptionBadRequestThrown() { Mockito.when(client.getSpace(Matchers.any(UUID.class))) .thenThrow(new CloudOperationException(HttpStatus.BAD_REQUEST)); CloudOperationException cloudOperationException = Assertions.assertThrows(CloudOperationException.class, () -> clientHelper.computeTarget(SPACE_ID)); Assertions.assertEquals(HttpStatus.BAD_REQUEST, cloudOperationException.getStatusCode()); }
### Question: ObjectStoreFileStorage implements FileStorage { @Override public void deleteFilesBySpaceAndNamespace(String space, String namespace) { removeBlobsByFilter(blob -> filterBySpaceAndNamespace(blob, space, namespace)); } ObjectStoreFileStorage(BlobStore blobStore, String container); @Override void addFile(FileEntry fileEntry, File file); @Override List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries); @Override void deleteFile(String id, String space); @Override void deleteFilesBySpace(String space); @Override void deleteFilesBySpaceAndNamespace(String space, String namespace); @Override int deleteFilesModifiedBefore(Date modificationTime); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); }### Answer: @Test void deleteFilesBySpaceAndNamespace() throws Exception { FileEntry firstFile = addFile(TEST_FILE_LOCATION); FileEntry secondFile = addFile(SECOND_FILE_TEST_LOCATION); FileEntry fileInOtherSpace = addFile(TEST_FILE_LOCATION, "otherspace", namespace); FileEntry fileInOtherNamespace = addFile(TEST_FILE_LOCATION, spaceId, "othernamespace"); fileStorage.deleteFilesBySpaceAndNamespace(spaceId, namespace); assertFileExists(true, fileInOtherNamespace); assertFileExists(true, fileInOtherSpace); assertFileExists(false, firstFile); assertFileExists(false, secondFile); }
### Question: ObjectStoreFileStorage implements FileStorage { @Override public int deleteFilesModifiedBefore(Date modificationTime) { return removeBlobsByFilter(blob -> filterByModificationTime(blob, modificationTime)); } ObjectStoreFileStorage(BlobStore blobStore, String container); @Override void addFile(FileEntry fileEntry, File file); @Override List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries); @Override void deleteFile(String id, String space); @Override void deleteFilesBySpace(String space); @Override void deleteFilesBySpaceAndNamespace(String space, String namespace); @Override int deleteFilesModifiedBefore(Date modificationTime); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); }### Answer: @Test void deleteFilesModifiedBefore() throws Exception { long currentMillis = System.currentTimeMillis(); final long oldFilesTtl = 1000 * 60 * 10; final long pastMoment = currentMillis - 1000 * 60 * 15; FileEntry fileEntryToRemain1 = addFile(TEST_FILE_LOCATION); FileEntry fileEntryToRemain2 = addFile(SECOND_FILE_TEST_LOCATION); FileEntry fileEntryToDelete1 = addFile(TEST_FILE_LOCATION, spaceId, namespace, new Date(pastMoment)); FileEntry fileEntryToDelete2 = addFile(SECOND_FILE_TEST_LOCATION, spaceId, null, new Date(pastMoment)); String blobWithNoMetadataId = addBlobWithNoMetadata(); int deletedFiles = fileStorage.deleteFilesModifiedBefore(new Date(currentMillis - oldFilesTtl)); assertEquals(3, deletedFiles); assertFileExists(true, fileEntryToRemain1); assertFileExists(true, fileEntryToRemain2); assertFileExists(false, fileEntryToDelete1); assertFileExists(false, fileEntryToDelete2); assertNull(blobStoreContext.getBlobStore() .getBlob(CONTAINER, blobWithNoMetadataId)); }
### Question: MemoryParametersParser implements ParametersParser<Integer> { @Override public Integer parse(List<Map<String, Object>> parametersList) { return parseMemory((String) PropertiesUtil.getPropertyValue(parametersList, parameterName, defaultMemory)); } MemoryParametersParser(String parameterName, String defaultMemory); @Override Integer parse(List<Map<String, Object>> parametersList); static Integer parseMemory(String value); }### Answer: @Test void testInvalidMemoryParsing() { List<Map<String, Object>> parametersList = List.of(Map.of(SupportedParameters.MEMORY, "test-mb")); assertThrows(ContentException.class, () -> parser.parse(parametersList)); } @Test void testDefaultMemoryParsing() { Integer memory = parser.parse(Collections.emptyList()); assertEquals(DEFAULT_MEMORY, memory); }
### Question: AuditLogManager { AuditLogManager(DataSource dataSource, UserInfoProvider userInfoProvider) { securityLogger = setUpLogger(dataSource, userInfoProvider, "SECURITY"); configLogger = setUpLogger(dataSource, userInfoProvider, "CONFIG"); actionLogger = setUpLogger(dataSource, userInfoProvider, "ACTION"); } AuditLogManager(DataSource dataSource, UserInfoProvider userInfoProvider); }### Answer: @Test void testAuditLogManager() { List<Logger> loggers = loadAuditLoggers(); logMessage(loggers); assertNull(auditLogManager.getException()); }
### Question: FlowableJobExecutorInformation { public int getCurrentJobExecutorQueueSize() { if (lastUpdateTime == null || isPastCacheTimeout()) { updateCurrentJobExecutorQueueSize(); } return currentJobExecutorQueueSize; } @Inject FlowableJobExecutorInformation(DefaultAsyncJobExecutor jobExecutor); int getCurrentJobExecutorQueueSize(); }### Answer: @Test void testGetCurrentJobExecutorQueueSize() { prepareJobExecutor(JOBS_IN_QUEUE); int currentJobExecutorQueueSize = flowableJobExecutorInformation.getCurrentJobExecutorQueueSize(); assertEquals(JOBS_IN_QUEUE, currentJobExecutorQueueSize); } @Test void testGetCurrentJobExecutorQueueSizeFromCache() { prepareJobExecutor(JOBS_IN_QUEUE); flowableJobExecutorInformation.getCurrentJobExecutorQueueSize(); prepareJobExecutor(UPDATED_JOBS_IN_QUEUE); int currentJobExecutorQueueSize = flowableJobExecutorInformation.getCurrentJobExecutorQueueSize(); assertEquals(JOBS_IN_QUEUE, currentJobExecutorQueueSize); } @Test void testGetCurrentJobExecutorQueueSizeExpiredCache() { flowableJobExecutorInformation = new FlowableJobExecutorInformation(asyncExecutor) { @Override protected void updateTime() { lastUpdateTime = Instant.now() .minusSeconds(120); } }; prepareJobExecutor(JOBS_IN_QUEUE); flowableJobExecutorInformation.getCurrentJobExecutorQueueSize(); prepareJobExecutor(UPDATED_JOBS_IN_QUEUE); int currentJobExecutorQueueSize = flowableJobExecutorInformation.getCurrentJobExecutorQueueSize(); assertEquals(UPDATED_JOBS_IN_QUEUE, currentJobExecutorQueueSize); }
### Question: PurgeApiAuthorizationFilter extends SpaceNameBasedAuthorizationFilter { @Override public String getUriRegex() { return "/rest/configuration-entries/purge"; } @Inject PurgeApiAuthorizationFilter(AuthorizationChecker authorizationChecker); @Override String getUriRegex(); }### Answer: @Test void testUriRegexMatches() { assertTrue("/rest/configuration-entries/purge".matches(purgeApiAuthorizationFilter.getUriRegex())); }
### Question: PurgeApiAuthorizationFilter extends SpaceNameBasedAuthorizationFilter { @Override protected CloudTarget extractTarget(HttpServletRequest request) { String organizationName = request.getParameter(ConfigurationEntriesResource.REQUEST_PARAM_ORGANIZATION); String spaceName = request.getParameter(ConfigurationEntriesResource.REQUEST_PARAM_SPACE); if (StringUtils.isAnyEmpty(organizationName, spaceName)) { throw new SLException(Messages.ORG_AND_SPACE_MUST_BE_SPECIFIED); } return new CloudTarget(organizationName, spaceName); } @Inject PurgeApiAuthorizationFilter(AuthorizationChecker authorizationChecker); @Override String getUriRegex(); }### Answer: @Test void testExtractTarget() { Mockito.when(request.getParameter(ConfigurationEntriesResource.REQUEST_PARAM_ORGANIZATION)) .thenReturn(ORGANIZATION_NAME); Mockito.when(request.getParameter(ConfigurationEntriesResource.REQUEST_PARAM_SPACE)) .thenReturn(SPACE_NAME); assertEquals(new CloudTarget(ORGANIZATION_NAME, SPACE_NAME), purgeApiAuthorizationFilter.extractTarget(request)); } @Test void testExtractTargetWithMissingParameters() { assertThrows(SLException.class, () -> purgeApiAuthorizationFilter.extractTarget(request)); }
### Question: SpaceNameBasedAuthorizationFilter implements UriAuthorizationFilter { @Override public final boolean ensureUserIsAuthorized(HttpServletRequest request, HttpServletResponse response) throws IOException { CloudTarget target = extractAndLogTarget(request); try { authorizationChecker.ensureUserIsAuthorized(request, SecurityContextUtil.getUserInfo(), target, null); return true; } catch (ResponseStatusException e) { logUnauthorizedRequest(request, e); response.sendError(HttpStatus.UNAUTHORIZED.value(), MessageFormat.format(Messages.NOT_AUTHORIZED_TO_OPERATE_IN_ORGANIZATION_0_AND_SPACE_1, target.getOrganizationName(), target.getSpaceName())); return false; } } SpaceNameBasedAuthorizationFilter(AuthorizationChecker authorizationChecker); @Override final boolean ensureUserIsAuthorized(HttpServletRequest request, HttpServletResponse response); }### Answer: @Test void testWithSuccessfulAuthorization() throws IOException { dummyUriAuthorizationFilter.ensureUserIsAuthorized(request, response); Mockito.verify(authorizationChecker) .ensureUserIsAuthorized(Mockito.eq(request), Mockito.any(), Mockito.eq(new CloudTarget(ORGANIZATION_NAME, SPACE_NAME)), Mockito.any()); } @Test void testWithException() throws IOException { Mockito.doThrow(new ResponseStatusException(HttpStatus.FORBIDDEN)) .when(authorizationChecker) .ensureUserIsAuthorized(Mockito.eq(request), Mockito.any(), Mockito.eq(new CloudTarget(ORGANIZATION_NAME, SPACE_NAME)), Mockito.any()); dummyUriAuthorizationFilter.ensureUserIsAuthorized(request, response); Mockito.verify(response) .sendError(Mockito.eq(HttpStatus.UNAUTHORIZED.value()), Mockito.any()); }
### Question: ObjectStoreFileStorage implements FileStorage { @Override public <T> T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor) throws FileStorageException { FileEntry fileEntry = createFileEntry(space, id); try { Blob blob = getBlobWithRetries(fileEntry, 3); if (blob == null) { throw new FileStorageException(MessageFormat.format(Messages.FILE_WITH_ID_AND_SPACE_DOES_NOT_EXIST, fileEntry.getId(), fileEntry.getSpace())); } Payload payload = blob.getPayload(); return processContent(fileContentProcessor, payload); } catch (Exception e) { throw new FileStorageException(e); } } ObjectStoreFileStorage(BlobStore blobStore, String container); @Override void addFile(FileEntry fileEntry, File file); @Override List<FileEntry> getFileEntriesWithoutContent(List<FileEntry> fileEntries); @Override void deleteFile(String id, String space); @Override void deleteFilesBySpace(String space); @Override void deleteFilesBySpaceAndNamespace(String space, String namespace); @Override int deleteFilesModifiedBefore(Date modificationTime); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); }### Answer: @Test void processFileContent() throws Exception { FileEntry fileEntry = addFile(TEST_FILE_LOCATION); String testFileDigest = DigestHelper.computeFileChecksum(Paths.get(TEST_FILE_LOCATION), DIGEST_METHOD) .toLowerCase(); validateFileContent(fileEntry, testFileDigest); }
### Question: SpaceGuidBasedAuthorizationFilter implements UriAuthorizationFilter { @Override public final boolean ensureUserIsAuthorized(HttpServletRequest request, HttpServletResponse response) throws IOException { String spaceGuid = extractAndLogSpaceGuid(request); try { authorizationChecker.ensureUserIsAuthorized(request, SecurityContextUtil.getUserInfo(), spaceGuid, null); return true; } catch (ResponseStatusException e) { logUnauthorizedRequest(request, e); response.sendError(e.getStatus() .value(), MessageFormat.format(Messages.NOT_AUTHORIZED_TO_OPERATE_IN_SPACE_WITH_GUID_0, spaceGuid)); return false; } } SpaceGuidBasedAuthorizationFilter(AuthorizationChecker authorizationChecker); @Override final boolean ensureUserIsAuthorized(HttpServletRequest request, HttpServletResponse response); }### Answer: @Test void testWithSuccessfulAuthorization() throws IOException { dummyUriAuthorizationFilter.ensureUserIsAuthorized(request, response); Mockito.verify(authorizationChecker) .ensureUserIsAuthorized(Mockito.eq(request), Mockito.any(), Mockito.eq(SPACE_GUID), Mockito.any()); } @Test void testWithException() throws IOException { Mockito.doThrow(new ResponseStatusException(HttpStatus.FORBIDDEN)) .when(authorizationChecker) .ensureUserIsAuthorized(Mockito.eq(request), Mockito.any(), Mockito.eq(SPACE_GUID), Mockito.any()); dummyUriAuthorizationFilter.ensureUserIsAuthorized(request, response); Mockito.verify(response) .sendError(Mockito.eq(HttpStatus.FORBIDDEN.value()), Mockito.any()); }
### Question: OperationService extends PersistenceService<Operation, OperationDto, String> { public OperationQuery createQuery() { return new OperationQueryImpl(createEntityManager(), operationMapper); } @Inject OperationService(EntityManagerFactory entityManagerFactory); OperationQuery createQuery(); }### Answer: @Test void testAdd() { operationService.add(OPERATION_1); assertEquals(Collections.singletonList(OPERATION_1), operationService.createQuery() .list()); assertEquals(OPERATION_1, operationService.createQuery() .processId(OPERATION_1.getProcessId()) .singleResult()); } @Test void testAddWithNonEmptyDatabase() { addOperations(List.of(OPERATION_1, OPERATION_2)); assertOperationExists(OPERATION_1.getProcessId()); assertOperationExists(OPERATION_2.getProcessId()); assertEquals(List.of(OPERATION_1, OPERATION_2), operationService.createQuery() .list()); }
### Question: AdminApiAuthorizationFilter extends SpaceGuidBasedAuthorizationFilter { @Override protected String extractSpaceGuid(HttpServletRequest request) { String spaceGuid = applicationConfiguration.getSpaceGuid(); if (StringUtils.isEmpty(spaceGuid)) { throw new SLException("Could not retrieve the MTA deployer's space GUID."); } return spaceGuid; } @Inject AdminApiAuthorizationFilter(ApplicationConfiguration applicationConfiguration, AuthorizationChecker authorizationChecker); @Override String getUriRegex(); }### Answer: @Test void testExtractSpaceGuid() { Mockito.when(applicationConfiguration.getSpaceGuid()) .thenReturn(SPACE_GUID); assertEquals(SPACE_GUID, adminApiAuthorizationFilter.extractSpaceGuid(request)); } @Test void testExtractSpaceGuidWithEmptyString() { Mockito.when(applicationConfiguration.getSpaceGuid()) .thenReturn(""); assertThrows(SLException.class, () -> adminApiAuthorizationFilter.extractSpaceGuid(request)); }
### Question: MtasApiAuthorizationFilter extends SpaceGuidBasedAuthorizationFilter { @Override protected String extractSpaceGuid(HttpServletRequest request) { String uri = ServletUtil.decodeUri(request); return extractSpaceGuid(ServletUtil.removeInvalidForwardSlashes(uri)); } @Inject MtasApiAuthorizationFilter(AuthorizationChecker authorizationChecker); @Override String getUriRegex(); }### Answer: @Test void testExtractSpaceGuid() { Mockito.when(request.getRequestURI()) .thenReturn(String.format("/api/v1/spaces/%s/mtas", SPACE_GUID)); assertEquals(SPACE_GUID, mtasApiAuthorizationFilter.extractSpaceGuid(request)); } @Test void testExtractSpaceGuidWithDoubleForwardSlashes() { Mockito.when(request.getRequestURI()) .thenReturn(String.format("/api assertEquals(SPACE_GUID, mtasApiAuthorizationFilter.extractSpaceGuid(request)); } @Test void testExtractSpaceGuidWithNonMatchingUri() { Mockito.when(request.getRequestURI()) .thenReturn("/public/ping"); assertThrows(SLException.class, () -> mtasApiAuthorizationFilter.extractSpaceGuid(request)); }
### Question: MtasApiServiceImpl implements MtasApiService { @Override public ResponseEntity<List<Mta>> getMtas(String spaceGuid) { List<DeployedMta> deployedMtas = deployedMtaDetector.detectDeployedMtasWithoutNamespace(getCloudFoundryClient(spaceGuid)); List<Mta> mtas = getMtas(deployedMtas); return ResponseEntity.ok() .body(mtas); } @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid); @Override ResponseEntity<Mta> getMta(String spaceGuid, String mtaId); @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid, String namespace, String name); }### Answer: @Test void testGetMtas() { Mockito.when(deployedMtaDetector.detectDeployedMtasWithoutNamespace(Mockito.any())) .thenReturn(getDeployedMtas(mtas)); ResponseEntity<List<Mta>> response = testedClass.getMtas(SPACE_GUID); assertEquals(HttpStatus.OK, response.getStatusCode()); List<Mta> responseMtas = response.getBody(); assertEquals(mtas, responseMtas); }
### Question: MtasApiServiceImpl implements MtasApiService { protected ResponseEntity<List<Mta>> getAllMtas(String spaceGuid) { List<DeployedMta> deployedMtas = deployedMtaDetector.detectDeployedMtas(getCloudFoundryClient(spaceGuid)); return ResponseEntity.ok() .body(getMtas(deployedMtas)); } @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid); @Override ResponseEntity<Mta> getMta(String spaceGuid, String mtaId); @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid, String namespace, String name); }### Answer: @Test void testGetAllMtas() { Mockito.when(deployedMtaDetector.detectDeployedMtas(Mockito.any())) .thenReturn(getDeployedMtas(mtas)); ResponseEntity<List<Mta>> response = testedClass.getMtas(SPACE_GUID, null, null); assertEquals(HttpStatus.OK, response.getStatusCode()); List<Mta> responseMtas = response.getBody(); assertEquals(mtas, responseMtas); }
### Question: MtasApiServiceImpl implements MtasApiService { protected ResponseEntity<List<Mta>> getMtasByName(String spaceGuid, String name) { List<DeployedMta> deployedMtas = deployedMtaDetector.detectDeployedMtasByName(name, getCloudFoundryClient(spaceGuid)); if (deployedMtas.isEmpty()) { throw new NotFoundException(Messages.MTAS_NOT_FOUND_BY_NAME, name); } return ResponseEntity.ok() .body(getMtas(deployedMtas)); } @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid); @Override ResponseEntity<Mta> getMta(String spaceGuid, String mtaId); @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid, String namespace, String name); }### Answer: @Test void testGetMtasByName() { Mta mtaToGet = mtas.get(1); Mockito.when(deployedMtaDetector.detectDeployedMtasByName(mtaToGet.getMetadata() .getId(), client)) .thenReturn(List.of(getDeployedMta(mtaToGet))); ResponseEntity<List<Mta>> response = testedClass.getMtas(SPACE_GUID, null, mtaToGet.getMetadata() .getId()); assertEquals(HttpStatus.OK, response.getStatusCode()); List<Mta> responseMtas = response.getBody(); assertEquals(List.of(mtaToGet), responseMtas); }
### Question: MtasApiServiceImpl implements MtasApiService { protected ResponseEntity<List<Mta>> getMtasByNamespace(String spaceGuid, String namespace) { List<DeployedMta> deployedMtas = deployedMtaDetector.detectDeployedMtasByNamespace(namespace, getCloudFoundryClient(spaceGuid)); if (deployedMtas.isEmpty()) { throw new NotFoundException(Messages.MTAS_NOT_FOUND_BY_NAMESPACE, namespace); } return ResponseEntity.ok() .body(getMtas(deployedMtas)); } @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid); @Override ResponseEntity<Mta> getMta(String spaceGuid, String mtaId); @Override ResponseEntity<List<Mta>> getMtas(String spaceGuid, String namespace, String name); }### Answer: @Test void testGetMtasByNamespace() { Mta mtaToGet = mtas.get(0); Mockito.when(deployedMtaDetector.detectDeployedMtasByNamespace(mtaToGet.getMetadata() .getNamespace(), client)) .thenReturn(List.of(getDeployedMta(mtaToGet))); ResponseEntity<List<Mta>> response = testedClass.getMtas(SPACE_GUID, mtaToGet.getMetadata() .getNamespace(), null); assertEquals(HttpStatus.OK, response.getStatusCode()); List<Mta> responseMtas = response.getBody(); assertEquals(List.of(mtaToGet), responseMtas); }
### Question: OperationsApiServiceImpl implements OperationsApiService { @Override public ResponseEntity<List<Operation>> getOperations(String spaceGuid, String mtaId, List<String> stateStrings, Integer last) { List<Operation.State> states = getStates(stateStrings); List<Operation> operations = filterByQueryParameters(last, states, spaceGuid, mtaId); return ResponseEntity.ok() .body(operations); } @Override ResponseEntity<List<Operation>> getOperations(String spaceGuid, String mtaId, List<String> stateStrings, Integer last); @Override ResponseEntity<Void> executeOperationAction(HttpServletRequest request, String spaceGuid, String operationId, String actionId); @Override ResponseEntity<List<Log>> getOperationLogs(String spaceGuid, String operationId); @Override ResponseEntity<String> getOperationLogContent(String spaceGuid, String operationId, String logId); @Override ResponseEntity<Operation> startOperation(HttpServletRequest request, String spaceGuid, Operation operation); @Override ResponseEntity<Operation> getOperation(String spaceGuid, String operationId, String embed); @Override ResponseEntity<List<String>> getOperationActions(String spaceGuid, String operationId); }### Answer: @Test void testGetOperations() { ResponseEntity<List<Operation>> response = testedClass.getOperations(SPACE_GUID, null, List.of(Operation.State.FINISHED.toString(), Operation.State.ABORTED.toString()), 1); List<Operation> operations = response.getBody(); assertEquals(2, operations.size()); assertEquals(Operation.State.FINISHED, operations.get(0) .getState()); assertEquals(Operation.State.ABORTED, operations.get(1) .getState()); } @Test void testGetOperationsNotFound() { ResponseEntity<List<Operation>> response = testedClass.getOperations(SPACE_GUID, MTA_ID, Collections.singletonList(Operation.State.ACTION_REQUIRED.toString()), 1); List<Operation> operations = response.getBody(); assertTrue(operations.isEmpty()); }
### Question: ConfigurationSubscriptionService extends PersistenceService<ConfigurationSubscription, ConfigurationSubscriptionDto, Long> { public ConfigurationSubscriptionQuery createQuery() { return new ConfigurationSubscriptionQueryImpl(createEntityManager(), subscriptionMapper); } ConfigurationSubscriptionService(EntityManagerFactory entityManagerFactory, ConfigurationSubscriptionMapper subscriptionMapper); ConfigurationSubscriptionQuery createQuery(); }### Answer: @Test void testAdd() { configurationSubscriptionService.add(CONFIGURATION_SUBSCRIPTION_1); assertEquals(1, configurationSubscriptionService.createQuery() .list() .size()); assertEquals(CONFIGURATION_SUBSCRIPTION_1.getId(), configurationSubscriptionService.createQuery() .id(CONFIGURATION_SUBSCRIPTION_1.getId()) .singleResult() .getId()); } @Test void testAddWithNonEmptyDatabase() { addConfigurationSubscriptions(List.of(CONFIGURATION_SUBSCRIPTION_1, CONFIGURATION_SUBSCRIPTION_2)); assertConfigurationSubscriptionExists(CONFIGURATION_SUBSCRIPTION_1.getId()); assertConfigurationSubscriptionExists(CONFIGURATION_SUBSCRIPTION_2.getId()); assertEquals(2, configurationSubscriptionService.createQuery() .list() .size()); } @Test void testQueryByFilterMatching() { addConfigurationSubscriptions(List.of(CONFIGURATION_SUBSCRIPTION_1, CONFIGURATION_SUBSCRIPTION_2)); int foundSubscriptions = configurationSubscriptionService.createQuery() .onSelectMatching(Collections.singletonList(new ConfigurationEntry(null, null, Version.parseVersion("3.1"), "default", null, null, null, null, null))) .list() .size(); assertEquals(1, foundSubscriptions); }
### Question: OperationsApiServiceImpl implements OperationsApiService { @Override public ResponseEntity<Operation> startOperation(HttpServletRequest request, String spaceGuid, Operation operation) { String user = getAuthenticatedUser(request); String processDefinitionKey = operationsHelper.getProcessDefinitionKey(operation); Set<ParameterMetadata> predefinedParameters = operationMetadataMapper.getOperationMetadata(operation.getProcessType()) .getParameters(); operation = addServiceParameters(operation, spaceGuid, user); operation = addParameterValues(operation, predefinedParameters); ensureRequiredParametersSet(operation, predefinedParameters); ProcessInstance processInstance = flowableFacade.startProcess(processDefinitionKey, operation.getParameters()); AuditLoggingProvider.getFacade() .logConfigCreate(operation); return ResponseEntity.accepted() .header("Location", getLocationHeader(processInstance.getProcessInstanceId(), spaceGuid)) .build(); } @Override ResponseEntity<List<Operation>> getOperations(String spaceGuid, String mtaId, List<String> stateStrings, Integer last); @Override ResponseEntity<Void> executeOperationAction(HttpServletRequest request, String spaceGuid, String operationId, String actionId); @Override ResponseEntity<List<Log>> getOperationLogs(String spaceGuid, String operationId); @Override ResponseEntity<String> getOperationLogContent(String spaceGuid, String operationId, String logId); @Override ResponseEntity<Operation> startOperation(HttpServletRequest request, String spaceGuid, Operation operation); @Override ResponseEntity<Operation> getOperation(String spaceGuid, String operationId, String embed); @Override ResponseEntity<List<String>> getOperationActions(String spaceGuid, String operationId); }### Answer: @Test void testStartOperation() { Map<String, Object> parameters = Map.of(Variables.MTA_ID.getName(), "test"); Operation operation = createOperation(null, null, parameters); Mockito.when(operationsHelper.getProcessDefinitionKey(operation)) .thenReturn("deploy"); testedClass.startOperation(mockHttpServletRequest(EXAMPLE_USER), SPACE_GUID, operation); Mockito.verify(flowableFacade) .startProcess(Mockito.any(), Mockito.anyMap()); }
### Question: FilesApiServiceImpl implements FilesApiService { @Override public ResponseEntity<List<FileMetadata>> getFiles(String spaceGuid, String namespace) { try { List<FileEntry> entries = fileService.listFiles(spaceGuid, namespace); List<FileMetadata> files = entries.stream() .map(this::parseFileEntry) .collect(Collectors.toList()); return ResponseEntity.ok() .body(files); } catch (FileStorageException e) { throw new SLException(e, Messages.COULD_NOT_GET_FILES_0, e.getMessage()); } } @Override ResponseEntity<List<FileMetadata>> getFiles(String spaceGuid, String namespace); @Override ResponseEntity<FileMetadata> uploadFile(HttpServletRequest request, String spaceGuid, String namespace); }### Answer: @Test void testGetMtaFiles() throws Exception { FileEntry entryOne = createFileEntry("test.mtar"); FileEntry entryTwo = createFileEntry("extension.mtaet"); Mockito.when(fileService.listFiles(Mockito.eq(SPACE_GUID), Mockito.eq(NAMESPACE_GUID))) .thenReturn(List.of(entryOne, entryTwo)); ResponseEntity<List<FileMetadata>> response = testedClass.getFiles(SPACE_GUID, NAMESPACE_GUID); assertEquals(HttpStatus.OK, response.getStatusCode()); List<FileMetadata> files = response.getBody(); assertEquals(2, files.size()); assertMetadataMatches(entryOne, files.get(0)); assertMetadataMatches(entryTwo, files.get(1)); } @Test void testGetMtaFilesError() throws Exception { Mockito.when(fileService.listFiles(Mockito.eq(SPACE_GUID), Mockito.eq(null))) .thenThrow(new FileStorageException("error")); Assertions.assertThrows(SLException.class, () -> testedClass.getFiles(SPACE_GUID, null)); }
### Question: DatabaseSequenceMigrationExecutor extends DatabaseMigrationExecutor { private long getLastSequenceValue(String sequenceName) throws SQLException { return getSourceDatabaseQueryClient().getLastSequenceValue(sequenceName); } @Override void executeMigrationInternal(String sequenceName); }### Answer: @Test void testExecuteMigrationInternalWhenLastSequenceValueIsZero() throws SQLException { Mockito.when(mockSourceDatabaseQueryClient.getLastSequenceValue(TEST_SEQUENCE_NAME)) .thenReturn(0L); Assertions.assertThrows(IllegalStateException.class, () -> databaseSequenceMigrationExecutor.executeMigration(TEST_SEQUENCE_NAME)); } @Test void testExecuteMigrationInternalWhenLastSequenceValueIsNegative() throws SQLException { Mockito.when(mockSourceDatabaseQueryClient.getLastSequenceValue(TEST_SEQUENCE_NAME)) .thenReturn(-1L); Assertions.assertThrows(IllegalStateException.class, () -> databaseSequenceMigrationExecutor.executeMigration(TEST_SEQUENCE_NAME)); } @Test void testExecuteMigrationInternalWhenLastSequenceValueIsPositive() throws SQLException { Mockito.when(mockSourceDatabaseQueryClient.getLastSequenceValue(TEST_SEQUENCE_NAME)) .thenReturn(1L); databaseSequenceMigrationExecutor.executeMigration(TEST_SEQUENCE_NAME); Mockito.verify(mockTargetDatabaseQueryClient) .updateSequence(TEST_SEQUENCE_NAME, 1L); }
### Question: FileService { public void consumeFileContent(String space, String id, FileContentConsumer fileContentConsumer) throws FileStorageException { processFileContent(space, id, inputStream -> { fileContentConsumer.consume(inputStream); return null; }); } FileService(DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); FileService(String tableName, DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); protected FileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider, FileStorage fileStorage); FileEntry addFile(String space, String namespace, String name, InputStream inputStream); FileEntry addFile(String space, String namespace, String name, File existingFile); List<FileEntry> listFiles(String space, String namespace); FileEntry getFile(String space, String id); void consumeFileContent(String space, String id, FileContentConsumer fileContentConsumer); T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); int deleteBySpaceAndNamespace(String space, String namespace); int deleteBySpace(String space); int deleteModifiedBefore(Date modificationTime); boolean deleteFile(String space, String id); int deleteFilesEntriesWithoutContent(); }### Answer: @Test void consumeFileContentTest() throws Exception { fileService.consumeFileContent(SPACE_1, "1111-2222-3333-4444", Mockito.mock(FileContentConsumer.class)); Mockito.verify(fileStorage) .processFileContent(Mockito.eq(SPACE_1), Mockito.eq("1111-2222-3333-4444"), Mockito.any()); }
### Question: DatabaseTableInsertQueryGenerator { public String generate(DatabaseTableData tableMetadata) { StringBuilder result = new StringBuilder(); return result.append("INSERT INTO ") .append(tableMetadata.getTableName()) .append(OPEN_BRACKET) .append(generateInsertStatementTableColums(tableMetadata.getTableColumnsMetadata())) .append(CLOSING_BRACKET) .append(" VALUES ") .append(OPEN_BRACKET) .append(generateInsertStatementParameters(tableMetadata.getTableColumnsMetadata() .size())) .append(CLOSING_BRACKET) .toString(); } String generate(DatabaseTableData tableMetadata); }### Answer: @Test void testGenerateWithTestDatabaseMetadataWhenSingleColumn() { DatabaseTableColumnMetadata databaseTableColumnMetadata = buildDatabaseTableColumnMetadata(TEST_COLUMN_NAME, TEST_COLUMN_TYPE); DatabaseTableData databaseTableMetadata = buildDatabaseTableData(List.of(databaseTableColumnMetadata), TEST_TABLE_NAME); String expectedQuery = "INSERT INTO testTableName(testColumnName) VALUES (?)"; String resultQuery = databaseTableInsertQueryGenerator.generate(databaseTableMetadata); Assertions.assertEquals(expectedQuery, resultQuery); } @Test void testGenerateWithTestDatabaseMetadataWhenMultipleColumns() { List<DatabaseTableColumnMetadata> multipleDatabaseTableColumnMetadata = List.of(buildDatabaseTableColumnMetadata(TEST_COLUMN_NAME, TEST_COLUMN_TYPE), buildDatabaseTableColumnMetadata(TEST_COLUMN_NAME_2, TEST_COLUMN_TYPE)); DatabaseTableData databaseTableMetadata = buildDatabaseTableData(multipleDatabaseTableColumnMetadata, TEST_TABLE_NAME); String resultQuery = databaseTableInsertQueryGenerator.generate(databaseTableMetadata); String expectedQuery = "INSERT INTO testTableName(testColumnName, testColumnName2) VALUES (?, ?)"; Assertions.assertEquals(expectedQuery, resultQuery); }
### Question: FileService { public int deleteBySpaceAndNamespace(String space, String namespace) throws FileStorageException { fileStorage.deleteFilesBySpaceAndNamespace(space, namespace); return deleteFileAttributesBySpaceAndNamespace(space, namespace); } FileService(DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); FileService(String tableName, DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); protected FileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider, FileStorage fileStorage); FileEntry addFile(String space, String namespace, String name, InputStream inputStream); FileEntry addFile(String space, String namespace, String name, File existingFile); List<FileEntry> listFiles(String space, String namespace); FileEntry getFile(String space, String id); void consumeFileContent(String space, String id, FileContentConsumer fileContentConsumer); T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); int deleteBySpaceAndNamespace(String space, String namespace); int deleteBySpace(String space); int deleteModifiedBefore(Date modificationTime); boolean deleteFile(String space, String id); int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteBySpaceAndNamespaceTest() throws Exception { super.deleteBySpaceAndNamespaceTest(); Mockito.verify(fileStorage) .deleteFilesBySpaceAndNamespace(Mockito.eq(SPACE_1), Mockito.eq(NAMESPACE_1)); }
### Question: FileService { public int deleteBySpace(String space) throws FileStorageException { fileStorage.deleteFilesBySpace(space); return deleteFileAttributesBySpace(space); } FileService(DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); FileService(String tableName, DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); protected FileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider, FileStorage fileStorage); FileEntry addFile(String space, String namespace, String name, InputStream inputStream); FileEntry addFile(String space, String namespace, String name, File existingFile); List<FileEntry> listFiles(String space, String namespace); FileEntry getFile(String space, String id); void consumeFileContent(String space, String id, FileContentConsumer fileContentConsumer); T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); int deleteBySpaceAndNamespace(String space, String namespace); int deleteBySpace(String space); int deleteModifiedBefore(Date modificationTime); boolean deleteFile(String space, String id); int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteBySpaceTest() throws Exception { super.deleteBySpaceTest(); Mockito.verify(fileStorage) .deleteFilesBySpace(Mockito.eq(SPACE_1)); }
### Question: FileService { public boolean deleteFile(String space, String id) throws FileStorageException { fileStorage.deleteFile(id, space); return deleteFileAttribute(space, id); } FileService(DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); FileService(String tableName, DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); protected FileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider, FileStorage fileStorage); FileEntry addFile(String space, String namespace, String name, InputStream inputStream); FileEntry addFile(String space, String namespace, String name, File existingFile); List<FileEntry> listFiles(String space, String namespace); FileEntry getFile(String space, String id); void consumeFileContent(String space, String id, FileContentConsumer fileContentConsumer); T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); int deleteBySpaceAndNamespace(String space, String namespace); int deleteBySpace(String space); int deleteModifiedBefore(Date modificationTime); boolean deleteFile(String space, String id); int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteFileTest() throws Exception { FileEntry fileEntry = addTestFile(SPACE_1, NAMESPACE_1); boolean deleteFile = fileService.deleteFile(SPACE_2, fileEntry.getId()); assertFalse(deleteFile); Mockito.verify(fileStorage) .deleteFile(Mockito.eq(fileEntry.getId()), Mockito.eq(SPACE_2)); deleteFile = fileService.deleteFile(SPACE_1, fileEntry.getId()); assertTrue(deleteFile); Mockito.verify(fileStorage) .deleteFile(Mockito.eq(fileEntry.getId()), Mockito.eq(SPACE_1)); }
### Question: FileService { public int deleteFilesEntriesWithoutContent() throws FileStorageException { try { List<FileEntry> entries = getSqlQueryExecutor().execute(getSqlFileQueryProvider().getListAllFilesQuery()); List<FileEntry> missing = fileStorage.getFileEntriesWithoutContent(entries); return deleteFileEntries(missing); } catch (SQLException e) { throw new FileStorageException(Messages.ERROR_GETTING_ALL_FILES, e); } } FileService(DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); FileService(String tableName, DataSourceWithDialect dataSourceWithDialect, FileStorage fileStorage); protected FileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider, FileStorage fileStorage); FileEntry addFile(String space, String namespace, String name, InputStream inputStream); FileEntry addFile(String space, String namespace, String name, File existingFile); List<FileEntry> listFiles(String space, String namespace); FileEntry getFile(String space, String id); void consumeFileContent(String space, String id, FileContentConsumer fileContentConsumer); T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); int deleteBySpaceAndNamespace(String space, String namespace); int deleteBySpace(String space); int deleteModifiedBefore(Date modificationTime); boolean deleteFile(String space, String id); int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteFilesEntriesWithoutContentTest() throws Exception { FileEntry noContent = addTestFile(SPACE_1, NAMESPACE_1); FileEntry noContent2 = addTestFile(SPACE_2, NAMESPACE_1); addTestFile(SPACE_1, NAMESPACE_2); addTestFile(SPACE_2, NAMESPACE_2); Mockito.when(fileStorage.getFileEntriesWithoutContent(Mockito.anyList())) .thenReturn(List.of(noContent, noContent2)); int deleteWithoutContent = fileService.deleteFilesEntriesWithoutContent(); assertEquals(2, deleteWithoutContent); assertNull(fileService.getFile(SPACE_1, noContent.getId())); assertNull(fileService.getFile(SPACE_2, noContent2.getId())); }
### Question: EnvironmentServicesFinder { public CfJdbcService findJdbcService(String name) { if (StringUtils.isEmpty(name)) { return null; } try { return env.findJdbcServiceByName(name); } catch (IllegalArgumentException e) { return null; } } EnvironmentServicesFinder(); EnvironmentServicesFinder(CfJdbcEnv env); CfJdbcService findJdbcService(String name); CfService findService(String name); }### Answer: @Test void testFindJdbcService() { CfJdbcService expectedService = Mockito.mock(CfJdbcService.class); Mockito.when(env.findJdbcServiceByName(SERVICE_NAME)) .thenReturn(expectedService); CfJdbcService service = environmentServicesFinder.findJdbcService(SERVICE_NAME); Assertions.assertEquals(expectedService, service); } @Test void testFindJdbcServiceWithZeroOrMultipleMatches() { Mockito.when(env.findJdbcServiceByName(SERVICE_NAME)) .thenThrow(IllegalArgumentException.class); CfJdbcService service = environmentServicesFinder.findJdbcService(SERVICE_NAME); Assertions.assertNull(service); } @Test void testFindJdbcServiceWithNullOrEmptyServiceName() { Assertions.assertNull(environmentServicesFinder.findJdbcService(null)); Assertions.assertNull(environmentServicesFinder.findJdbcService("")); }
### Question: DatabaseFileService extends FileService { @Override public <T> T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor) throws FileStorageException { try { return getSqlQueryExecutor().execute(getSqlFileQueryProvider().getProcessFileWithContentQuery(space, id, fileContentProcessor)); } catch (SQLException e) { throw new FileStorageException(e.getMessage(), e); } } DatabaseFileService(DataSourceWithDialect dataSourceWithDialect); DatabaseFileService(String tableName, DataSourceWithDialect dataSourceWithDialect); protected DatabaseFileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); @Override int deleteBySpaceAndNamespace(String space, String namespace); @Override int deleteBySpace(String space); @Override int deleteModifiedBefore(Date modificationTime); @Override boolean deleteFile(String space, String id); @Override int deleteFilesEntriesWithoutContent(); }### Answer: @Test void processFileContentTest() throws Exception { Path expectedFile = Paths.get("src/test/resources/", PIC_RESOURCE_NAME); FileEntry fileEntry = addTestFile(SPACE_1, NAMESPACE_1); String expectedFileDigest = DigestHelper.computeFileChecksum(expectedFile, DIGEST_METHOD) .toLowerCase(); validateFileContent(fileEntry, expectedFileDigest); }
### Question: DatabaseFileService extends FileService { @Override public int deleteBySpaceAndNamespace(String space, String namespace) throws FileStorageException { return deleteFileAttributesBySpaceAndNamespace(space, namespace); } DatabaseFileService(DataSourceWithDialect dataSourceWithDialect); DatabaseFileService(String tableName, DataSourceWithDialect dataSourceWithDialect); protected DatabaseFileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); @Override int deleteBySpaceAndNamespace(String space, String namespace); @Override int deleteBySpace(String space); @Override int deleteModifiedBefore(Date modificationTime); @Override boolean deleteFile(String space, String id); @Override int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteBySpaceAndNamespaceTest() throws Exception { addTestFile(SPACE_1, NAMESPACE_1); addTestFile(SPACE_1, NAMESPACE_1); int deleteByWrongSpace = fileService.deleteBySpaceAndNamespace(SPACE_2, NAMESPACE_1); assertEquals(0, deleteByWrongSpace); int deleteByWrongNamespace = fileService.deleteBySpaceAndNamespace(SPACE_2, NAMESPACE_2); assertEquals(0, deleteByWrongNamespace); int correctDelete = fileService.deleteBySpaceAndNamespace(SPACE_1, NAMESPACE_1); assertEquals(2, correctDelete); List<FileEntry> listFiles = fileService.listFiles(SPACE_1, NAMESPACE_1); assertEquals(0, listFiles.size()); } @Test void deleteBySpaceAndNamespaceWithTwoNamespacesTest() throws Exception { addTestFile(SPACE_1, NAMESPACE_1); addTestFile(SPACE_1, NAMESPACE_2); int correctDelete = fileService.deleteBySpaceAndNamespace(SPACE_1, NAMESPACE_1); assertEquals(1, correctDelete); List<FileEntry> listFiles = fileService.listFiles(SPACE_1, NAMESPACE_1); assertEquals(0, listFiles.size()); listFiles = fileService.listFiles(SPACE_1, NAMESPACE_2); assertEquals(1, listFiles.size()); }
### Question: DatabaseFileService extends FileService { @Override public int deleteBySpace(String space) throws FileStorageException { return deleteFileAttributesBySpace(space); } DatabaseFileService(DataSourceWithDialect dataSourceWithDialect); DatabaseFileService(String tableName, DataSourceWithDialect dataSourceWithDialect); protected DatabaseFileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); @Override int deleteBySpaceAndNamespace(String space, String namespace); @Override int deleteBySpace(String space); @Override int deleteModifiedBefore(Date modificationTime); @Override boolean deleteFile(String space, String id); @Override int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteBySpaceTest() throws Exception { addTestFile(SPACE_1, NAMESPACE_1); addTestFile(SPACE_1, NAMESPACE_2); int deleteByWrongSpace = fileService.deleteBySpace(SPACE_2); assertEquals(0, deleteByWrongSpace); int correctDelete = fileService.deleteBySpace(SPACE_1); assertEquals(2, correctDelete); List<FileEntry> listFiles = fileService.listFiles(SPACE_1, null); assertEquals(0, listFiles.size()); }
### Question: DatabaseFileService extends FileService { @Override public boolean deleteFile(String space, String id) throws FileStorageException { return deleteFileAttribute(space, id); } DatabaseFileService(DataSourceWithDialect dataSourceWithDialect); DatabaseFileService(String tableName, DataSourceWithDialect dataSourceWithDialect); protected DatabaseFileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); @Override int deleteBySpaceAndNamespace(String space, String namespace); @Override int deleteBySpace(String space); @Override int deleteModifiedBefore(Date modificationTime); @Override boolean deleteFile(String space, String id); @Override int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteFileTest() throws Exception { FileEntry fileEntry = addTestFile(SPACE_1, NAMESPACE_1); boolean deleteFile = fileService.deleteFile(SPACE_2, fileEntry.getId()); assertFalse(deleteFile); deleteFile = fileService.deleteFile(SPACE_1, fileEntry.getId()); assertTrue(deleteFile); }
### Question: DatabaseFileService extends FileService { @Override public int deleteModifiedBefore(Date modificationTime) throws FileStorageException { return deleteFileAttributesModifiedBefore(modificationTime); } DatabaseFileService(DataSourceWithDialect dataSourceWithDialect); DatabaseFileService(String tableName, DataSourceWithDialect dataSourceWithDialect); protected DatabaseFileService(DataSourceWithDialect dataSourceWithDialect, SqlFileQueryProvider sqlFileQueryProvider); @Override T processFileContent(String space, String id, FileContentProcessor<T> fileContentProcessor); @Override int deleteBySpaceAndNamespace(String space, String namespace); @Override int deleteBySpace(String space); @Override int deleteModifiedBefore(Date modificationTime); @Override boolean deleteFile(String space, String id); @Override int deleteFilesEntriesWithoutContent(); }### Answer: @Test void deleteByModificationTimeTest() throws Exception { long currentMillis = System.currentTimeMillis(); final long oldFilesTtl = 1000 * 60 * 10; Date pastMoment = new Date(currentMillis - 1000 * 60 * 15); FileEntry fileEntryToRemain1 = addFileEntry(SPACE_1); FileEntry fileEntryToRemain2 = addFileEntry(SPACE_2); FileEntry fileEntryToDelete1 = addFileEntry(SPACE_1); FileEntry fileEntryToDelete2 = addFileEntry(SPACE_2); setMofidicationDate(fileEntryToDelete1, pastMoment); setMofidicationDate(fileEntryToDelete2, pastMoment); Date deleteDate = new Date(currentMillis - oldFilesTtl); int deletedFiles = fileService.deleteModifiedBefore(deleteDate); assertNotNull(fileService.getFile(SPACE_1, fileEntryToRemain1.getId())); assertNotNull(fileService.getFile(SPACE_2, fileEntryToRemain2.getId())); assertEquals(2, deletedFiles); assertNull(fileService.getFile(SPACE_1, fileEntryToDelete1.getId())); assertNull(fileService.getFile(SPACE_2, fileEntryToDelete2.getId())); }
### Question: ProgressMessagesCleaner implements Cleaner { @Override public void execute(Date expirationTime) { LOGGER.debug(CleanUpJob.LOG_MARKER, format(Messages.DELETING_PROGRESS_MESSAGES_STORED_BEFORE_0, expirationTime)); int removedProgressMessages = progressMessageService.createQuery() .olderThan(expirationTime) .delete(); LOGGER.info(CleanUpJob.LOG_MARKER, format(Messages.DELETED_PROGRESS_MESSAGES_0, removedProgressMessages)); } @Inject ProgressMessagesCleaner(ProgressMessageService progressMessageService); @Override void execute(Date expirationTime); }### Answer: @Test void testExecute() { cleaner.execute(EXPIRATION_TIME); verify(progressMessageService.createQuery() .olderThan(EXPIRATION_TIME)).delete(); }
### Question: AbortedOperationsCleaner implements Cleaner { @Override public void execute(Date expirationTime) { Instant instant = Instant.now() .minus(30, ChronoUnit.MINUTES); List<HistoricOperationEvent> abortedOperations = historicOperationEventService.createQuery() .type(HistoricOperationEvent.EventType.ABORTED) .olderThan(new Date(instant.toEpochMilli())) .list(); abortedOperations.stream() .map(HistoricOperationEvent::getProcessId) .distinct() .filter(this::isInActiveState) .forEach(this::deleteProcessInstance); } @Inject AbortedOperationsCleaner(HistoricOperationEventService historicOperationEventService, FlowableFacade flowableFacade); @Override void execute(Date expirationTime); }### Answer: @Test void testExecuteWithNoAbortedOperations() { prepareMocksWithProcesses(Collections.emptyList()); abortedOperationsCleaner.execute(new Date()); Mockito.verify(historicOperationEventService) .createQuery(); Mockito.verifyNoInteractions(flowableFacade); } @Test void testExecute() { prepareMocksWithProcesses(List.of(new CustomProcess("foo", true), new CustomProcess("bar", true))); abortedOperationsCleaner.execute(new Date()); Mockito.verify(flowableFacade, Mockito.times(2)) .getProcessInstance(anyString()); Mockito.verify(flowableFacade) .deleteProcessInstance("foo", Operation.State.ABORTED.name()); Mockito.verify(flowableFacade) .deleteProcessInstance("bar", Operation.State.ABORTED.name()); }
### Question: TokensCleaner implements Cleaner { @Override public void execute(Date expirationTime) { Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId(SecurityUtil.CLIENT_ID); LOGGER.debug(CleanUpJob.LOG_MARKER, Messages.REMOVING_EXPIRED_TOKENS_FROM_TOKEN_STORE); int removedTokens = removeTokens(tokens); LOGGER.info(CleanUpJob.LOG_MARKER, format(Messages.REMOVED_TOKENS_0, removedTokens)); } @Inject TokensCleaner(@Named("tokenStore") TokenStore tokenStore); @Override void execute(Date expirationTime); }### Answer: @Test void testExecute() { OAuth2AccessToken expiredToken = mock(OAuth2AccessToken.class); when(expiredToken.isExpired()).thenReturn(true); OAuth2AccessToken token = mock(OAuth2AccessToken.class); when(token.isExpired()).thenReturn(false); when(tokenStore.findTokensByClientId(anyString())).thenReturn(List.of(expiredToken, token)); cleaner.execute(null); verify(tokenStore).removeAccessToken(expiredToken); verify(tokenStore, never()).removeAccessToken(token); }
### Question: FilesCleaner implements Cleaner { @Override public void execute(Date expirationTime) { LOGGER.debug(CleanUpJob.LOG_MARKER, format(Messages.DELETING_FILES_MODIFIED_BEFORE_0, expirationTime)); try { int removedOldFilesCount = fileService.deleteModifiedBefore(expirationTime); LOGGER.info(CleanUpJob.LOG_MARKER, format(Messages.DELETED_FILES_0, removedOldFilesCount)); } catch (FileStorageException e) { throw new SLException(e, Messages.COULD_NOT_DELETE_FILES_MODIFIED_BEFORE_0, expirationTime); } } @Inject FilesCleaner(FileService fileService); @Override void execute(Date expirationTime); }### Answer: @Test void testExecute() throws FileStorageException { cleaner.execute(EXPIRATION_TIME); verify(fileService).deleteModifiedBefore(EXPIRATION_TIME); }
### Question: ProcessLogsCleaner implements Cleaner { @Override public void execute(Date expirationTime) { LOGGER.debug(CleanUpJob.LOG_MARKER, format(Messages.DELETING_PROCESS_LOGS_MODIFIED_BEFORE_0, expirationTime)); try { int deletedProcessLogs = processLogsPersistenceService.deleteModifiedBefore(expirationTime); LOGGER.info(CleanUpJob.LOG_MARKER, format(Messages.DELETED_PROCESS_LOGS_0, deletedProcessLogs)); } catch (FileStorageException e) { throw new SLException(e, Messages.COULD_NOT_DELETE_PROCESS_LOGS_MODIFIED_BEFORE_0, expirationTime); } } @Inject ProcessLogsCleaner(ProcessLogsPersistenceService processLogsPersistenceService); @Override void execute(Date expirationTime); }### Answer: @Test void testExecute() throws FileStorageException { cleaner.execute(EXPIRATION_TIME); verify(processLogsPersistenceService).deleteModifiedBefore(EXPIRATION_TIME); }
### Question: CleanUpJob implements Job { @Override public void execute(JobExecutionContext context) { LOGGER.info(LOG_MARKER, format(Messages.CLEAN_UP_JOB_STARTED_BY_APPLICATION_INSTANCE_0_AT_1, configuration.getApplicationInstanceIndex(), Instant.now())); Date expirationTime = computeExpirationTime(); LOGGER.info(LOG_MARKER, format(Messages.WILL_CLEAN_UP_DATA_STORED_BEFORE_0, expirationTime)); LOGGER.info(LOG_MARKER, format(Messages.REGISTERED_CLEANERS_IN_CLEAN_UP_JOB_0, cleaners)); for (Cleaner cleaner : cleaners) { safeExecutor.execute(() -> cleaner.execute(expirationTime)); } LOGGER.info(LOG_MARKER, format(Messages.CLEAN_UP_JOB_FINISHED_AT_0, Instant.now())); } @Override void execute(JobExecutionContext context); static final Marker LOG_MARKER; }### Answer: @Test void testExecutionResilience() { Cleaner cleaner1 = Mockito.mock(Cleaner.class); Cleaner cleaner2 = Mockito.mock(Cleaner.class); Mockito.doThrow(new SLException("Will it work?")) .when(cleaner2) .execute(Mockito.any()); Cleaner cleaner3 = Mockito.mock(Cleaner.class); List<Cleaner> cleaners = List.of(cleaner1, cleaner2, cleaner3); CleanUpJob cleanUpJob = createCleanUpJob(new ApplicationConfiguration(), cleaners); cleanUpJob.execute(null); Mockito.verify(cleaner1) .execute(Mockito.any()); Mockito.verify(cleaner2) .execute(Mockito.any()); Mockito.verify(cleaner3) .execute(Mockito.any()); }
### Question: ErrorProcessListener extends AbstractFlowableEngineEventListener { @Override protected void jobExecutionFailure(FlowableEngineEntityEvent event) { if (event instanceof FlowableExceptionEvent) { handleWithCorrelationId(event, () -> handle(event, (FlowableExceptionEvent) event)); } } @Inject ErrorProcessListener(OperationInErrorStateHandler eventHandler); @Override boolean isFailOnException(); }### Answer: @Test void testJobExecutionFailureWithWrongEventClass() { FlowableEngineEntityEvent engineEntityEvent = Mockito.mock(FlowableEngineEntityEvent.class); errorProcessListener.jobExecutionFailure(engineEntityEvent); Mockito.verifyNoInteractions(eventHandler); } @Test void testJobExecutionFailureWithNoException() { FlowableEngineEntityEvent engineEntityEvent = Mockito.mock(FlowableEngineEntityEvent.class, Mockito.withSettings() .extraInterfaces(FlowableExceptionEvent.class)); errorProcessListener.jobExecutionFailure(engineEntityEvent); Mockito.verifyNoInteractions(eventHandler); } @Test void testJobExecutionFailure() { FlowableEngineEntityEvent engineEntityEvent = Mockito.mock(FlowableEngineEntityEvent.class, Mockito.withSettings() .extraInterfaces(FlowableExceptionEvent.class)); FlowableExceptionEvent exceptionEvent = (FlowableExceptionEvent) engineEntityEvent; Throwable t = new Throwable(); Mockito.when(exceptionEvent.getCause()) .thenReturn(t); errorProcessListener.jobExecutionFailure(engineEntityEvent); Mockito.verify(eventHandler) .handle(engineEntityEvent, t); }
### Question: ErrorProcessListener extends AbstractFlowableEngineEventListener { @Override protected void entityCreated(FlowableEngineEntityEvent event) { Object entity = event.getEntity(); if (entity instanceof DeadLetterJobEntity) { handleWithCorrelationId(event, () -> handle(event, (DeadLetterJobEntity) entity)); } } @Inject ErrorProcessListener(OperationInErrorStateHandler eventHandler); @Override boolean isFailOnException(); }### Answer: @Test void testEntityCreatedWithWrongEntityClass() { FlowableEngineEntityEvent engineEntityEvent = Mockito.mock(FlowableEngineEntityEvent.class); JobEntity job = Mockito.mock(JobEntity.class); Mockito.when(engineEntityEvent.getEntity()) .thenReturn(job); errorProcessListener.entityCreated(engineEntityEvent); Mockito.verifyNoInteractions(eventHandler); } @Test void testEntityCreatedWithNoException() { FlowableEngineEntityEvent engineEntityEvent = Mockito.mock(FlowableEngineEntityEvent.class); DeadLetterJobEntity job = Mockito.mock(DeadLetterJobEntity.class); Mockito.when(engineEntityEvent.getEntity()) .thenReturn(job); errorProcessListener.entityCreated(engineEntityEvent); Mockito.verifyNoInteractions(eventHandler); } @Test void testEntityCreated() { FlowableEngineEntityEvent engineEntityEvent = Mockito.mock(FlowableEngineEntityEvent.class); DeadLetterJobEntity job = Mockito.mock(DeadLetterJobEntity.class); Mockito.when(engineEntityEvent.getEntity()) .thenReturn(job); Mockito.when(job.getExceptionMessage()) .thenReturn(ERROR_MESSAGE); errorProcessListener.entityCreated(engineEntityEvent); Mockito.verify(eventHandler) .handle(engineEntityEvent, ERROR_MESSAGE); }
### Question: SetBeforeApplicationStopPhaseListener implements ExecutionListener { @Override public void notify(DelegateExecution execution) { VariableHandling.set(execution, Variables.SUBPROCESS_PHASE, SubprocessPhase.BEFORE_APPLICATION_STOP); } @Override void notify(DelegateExecution execution); }### Answer: @Test void testNotify() { setBeforeApplicationStopPhaseListener.notify(delegateExecution); Assertions.assertEquals(SubprocessPhase.BEFORE_APPLICATION_STOP.toString(), delegateExecution.getVariable(Variables.SUBPROCESS_PHASE.getName())); }
### Question: SetBeforeApplicationStartPhaseListener implements ExecutionListener { @Override public void notify(DelegateExecution execution) { VariableHandling.set(execution, Variables.SUBPROCESS_PHASE, SubprocessPhase.BEFORE_APPLICATION_START); } @Override void notify(DelegateExecution execution); }### Answer: @Test void testNotify() { setBeforeApplicationStartPhaseListener.notify(delegateExecution); Assertions.assertEquals(SubprocessPhase.BEFORE_APPLICATION_START.toString(), delegateExecution.getVariable(Variables.SUBPROCESS_PHASE.getName())); }
### Question: EndProcessListener extends AbstractProcessExecutionListener { @Override protected void notifyInternal(DelegateExecution execution) { if (isRootProcess(execution)) { eventHandler.handle(execution, Operation.State.FINISHED); } } @Inject EndProcessListener(OperationInFinalStateHandler eventHandler); }### Answer: @Test void testNotifyInternal() { EndProcessListener endProcessListener = new EndProcessListener(eventHandler); VariableHandling.set(execution, Variables.CORRELATION_ID, execution.getProcessInstanceId()); endProcessListener.notifyInternal(execution); Mockito.verify(eventHandler) .handle(execution, Operation.State.FINISHED); }
### Question: SetUndeployPhaseListener implements ExecutionListener { @Override public void notify(DelegateExecution execution) { VariableHandling.set(execution, Variables.PHASE, Phase.UNDEPLOY); } @Override void notify(DelegateExecution execution); }### Answer: @Test void testNotify() { setUndeployPhaseListener.notify(delegateExecution); Assertions.assertEquals(Phase.UNDEPLOY.toString(), delegateExecution.getVariable(Variables.PHASE.getName())); }
### Question: SetAfterResumePhaseListener implements ExecutionListener { @Override public void notify(DelegateExecution execution) { VariableHandling.set(execution, Variables.PHASE, Phase.AFTER_RESUME); } @Override void notify(DelegateExecution execution); }### Answer: @Test void testNotify() { setResumePhaseListener.notify(delegateExecution); Assertions.assertEquals(Phase.AFTER_RESUME.toString(), delegateExecution.getVariable(Variables.PHASE.getName())); }
### Question: ApplicationZipBuilder { public Path extractApplicationInNewArchive(ApplicationArchiveContext applicationArchiveContext) { Path appPath = null; try { appPath = createTempFile(); saveAllEntries(appPath, applicationArchiveContext); return appPath; } catch (Exception e) { FileUtils.cleanUp(appPath, LOGGER); throw new SLException(e, Messages.ERROR_RETRIEVING_MTA_MODULE_CONTENT, applicationArchiveContext.getModuleFileName()); } } @Inject ApplicationZipBuilder(ApplicationArchiveReader applicationArchiveReader); Path extractApplicationInNewArchive(ApplicationArchiveContext applicationArchiveContext); }### Answer: @Test void testFailToCreateZip() { String fileName = "db/"; ApplicationArchiveReader reader = new ApplicationArchiveReader(); ApplicationZipBuilder zipBuilder = new ApplicationZipBuilder(reader) { @Override protected void copy(InputStream input, OutputStream output, ApplicationArchiveContext applicationArchiveContext) throws IOException { throw new IOException(); } }; ApplicationArchiveContext applicationArchiveContext = getApplicationArchiveContext(SAMPLE_MTAR, fileName); Assertions.assertThrows(SLException.class, () -> appPath = zipBuilder.extractApplicationInNewArchive(applicationArchiveContext)); }
### Question: OperationInErrorStateHandler { HistoricOperationEvent.EventType toEventType(Throwable throwable) { return hasCause(throwable, ContentException.class) ? HistoricOperationEvent.EventType.FAILED_BY_CONTENT_ERROR : HistoricOperationEvent.EventType.FAILED_BY_INFRASTRUCTURE_ERROR; } @Inject OperationInErrorStateHandler(ProgressMessageService progressMessageService, FlowableFacade flowableFacade, HistoricOperationEventService historicOperationEventService, ClientReleaser clientReleaser); void handle(FlowableEngineEvent event, String errorMessage); void handle(FlowableEngineEvent event, Throwable throwable); }### Answer: @Test void testToEventType() { OperationInErrorStateHandler handler = mockHandler(); Throwable throwable = new RuntimeException(new SLException(new IOException())); HistoricOperationEvent.EventType eventType = handler.toEventType(throwable); assertEquals(HistoricOperationEvent.EventType.FAILED_BY_INFRASTRUCTURE_ERROR, eventType); } @Test void testToEventTypeWithContentException() { OperationInErrorStateHandler handler = mockHandler(); Throwable throwable = new RuntimeException(new SLException(new IOException(new ParsingException("")))); HistoricOperationEvent.EventType eventType = handler.toEventType(throwable); assertEquals(HistoricOperationEvent.EventType.FAILED_BY_CONTENT_ERROR, eventType); }
### Question: OperationInErrorStateHandler { public void handle(FlowableEngineEvent event, String errorMessage) { handle(event, HistoricOperationEvent.EventType.FAILED_BY_INFRASTRUCTURE_ERROR, errorMessage); } @Inject OperationInErrorStateHandler(ProgressMessageService progressMessageService, FlowableFacade flowableFacade, HistoricOperationEventService historicOperationEventService, ClientReleaser clientReleaser); void handle(FlowableEngineEvent event, String errorMessage); void handle(FlowableEngineEvent event, Throwable throwable); }### Answer: @Test void testWithErrorMessageAlreadyPersisted() { Mockito.when(flowableFacadeMock.getProcessInstanceId(Mockito.any())) .thenReturn("foo"); ProgressMessageQuery queryMock = new MockBuilder<>(progressMessageQuery).on(query -> query.processId("foo")) .build(); Mockito.doReturn(List.of(ImmutableProgressMessage.builder() .processId("foo") .taskId("") .text("") .type(ProgressMessageType.ERROR) .build())) .when(queryMock) .list(); FlowableEngineEvent event = Mockito.mock(FlowableEngineEvent.class); OperationInErrorStateHandler handler = mockHandler(); handler.handle(event, new Exception("test-message")); Mockito.verify(progressMessageServiceMock, Mockito.never()) .add(Mockito.any()); }
### Question: OperationInErrorStateHandler { private String getCurrentTaskId(FlowableEngineEvent flowableEngineEvent) { Execution currentExecutionForProcess = findCurrentExecution(flowableEngineEvent); return currentExecutionForProcess != null ? currentExecutionForProcess.getActivityId() : flowableFacade.getCurrentTaskId(flowableEngineEvent.getExecutionId()); } @Inject OperationInErrorStateHandler(ProgressMessageService progressMessageService, FlowableFacade flowableFacade, HistoricOperationEventService historicOperationEventService, ClientReleaser clientReleaser); void handle(FlowableEngineEvent event, String errorMessage); void handle(FlowableEngineEvent event, Throwable throwable); }### Answer: @Test void testWithNoErrorMessageAndTaskIdFromContext() { Mockito.when(flowableFacadeMock.getCurrentTaskId("bar")) .thenReturn("barbar"); testWithNoErrorMessageWithExecutionEntity(false); }
### Question: TopicEnsure { public boolean topicExists(TopicSpec spec, Integer timeOut) throws Exception { try { DescribeTopicsResult topicDescribeResult = adminClient.describeTopics( Collections.singletonList(spec.name()), new DescribeTopicsOptions().timeoutMs(timeOut) ); topicDescribeResult.all().get().get(spec.name()); } catch (ExecutionException e) { if (e.getCause() instanceof UnknownTopicOrPartitionException) { return false; } else { throw e; } } return true; } TopicEnsure(Properties props); boolean createTopic(TopicSpec spec, int timeOut); boolean validateTopic(TopicSpec spec, int timeOut); boolean topicExists(TopicSpec spec, Integer timeOut); }### Answer: @Test public void testTopicExistsForNonexistentTopic() throws Exception { assertFalse(topicEnsure.topicExists(simpleTopicSpec("unknown-topic"), TIMEOUT_MS)); }
### Question: TopicEnsure { public boolean validateTopic(TopicSpec spec, int timeOut) throws Exception { DescribeTopicsResult topicDescribeResult = adminClient.describeTopics( Collections.singletonList(spec.name()), new DescribeTopicsOptions().timeoutMs(timeOut) ); TopicDescription topic = topicDescribeResult.all().get().get(spec.name()); ConfigResource configResource = new ConfigResource(ConfigResource.Type.TOPIC, spec.name()); DescribeConfigsResult configResult = adminClient.describeConfigs( Collections.singletonList(configResource) ); Map<ConfigResource, Config> resultMap = configResult.all().get(); Config config = resultMap.get(configResource); Map<String, String> actualConfig = new HashMap<>(); for (Map.Entry<String, String> entry : spec.config().entrySet()) { ConfigEntry actualConfigEntry = config.get(entry.getKey()); if (actualConfigEntry != null) { actualConfig.put(entry.getKey(), actualConfigEntry.value()); } } TopicSpec actualSpec = new TopicSpec( topic.name(), topic.partitions().size(), topic.partitions().get(0).replicas().size(), actualConfig ); boolean isTopicValid = actualSpec.equals(spec); if (!isTopicValid) { System.err.printf( "Invalid topic [ %s ] ! Expected %s but got %s\n", spec.name(), spec, actualSpec ); } return isTopicValid; } TopicEnsure(Properties props); boolean createTopic(TopicSpec spec, int timeOut); boolean validateTopic(TopicSpec spec, int timeOut); boolean topicExists(TopicSpec spec, Integer timeOut); }### Answer: @Test(expected = Exception.class) public void testValidateNonexistentTopic() throws Exception { assertFalse(topicEnsure.validateTopic(simpleTopicSpec("unknown-topic"), TIMEOUT_MS)); }
### Question: UpdateChecker extends TimerTask { public void checkForUpdate() { try { if (!Boolean.getBoolean("net.sf.ehcache.skipUpdateCheck")) { doCheck(); } } catch (Throwable t) { LOG.log(Level.WARNING, "Update check failed: " + t.toString()); } } @Override void run(); void checkForUpdate(); }### Answer: @Test public void testErrorNotBubleUp() { System.setProperty("net.sf.ehcache.skipUpdateCheck", "false"); System.setProperty("ehcache.update-check.url", "this is a bad url"); UpdateChecker uc = new UpdateChecker(); uc.checkForUpdate(); }
### Question: WANUtil { public void addCurrentOrchestrator(String cacheManagerName, String cacheName, String orchestrator) { final ConcurrentMap<String, Serializable> cacheConfigMap = getCacheConfigMap(cacheManagerName, cacheName); cacheConfigMap.put(WAN_CURRENT_ORCHESTRATOR, orchestrator); LOGGER.info("Added '{}' as orchestrator for Cache '{}' in CacheManager '{}'", orchestrator, cacheName, cacheManagerName); } WANUtil(ToolkitInstanceFactory factory); void markWANReady(String cacheManagerName); void clearWANReady(String cacheManagerName); boolean isWANReady(String cacheManagerName); void waitForOrchestrator(String cacheManagerName); void markCacheWanEnabled(String cacheManagerName, String cacheName); void markCacheAsReplica(String cacheManagerName, String cacheName); void markCacheAsMaster(String cacheManagerName, String cacheName); boolean isCacheReplica(String cacheManagerName, String cacheName); void markCacheAsBidirectional(String cacheManagerName, String cacheName); void markCacheAsUnidirectional(String cacheManagerName, String cacheName); void addCurrentOrchestrator(String cacheManagerName, String cacheName, String orchestrator); boolean isCacheBidirectional(String cacheManagerName, String cacheName); void markCacheWanDisabled(String cacheManagerName, String cacheName); boolean isWanEnabledCache(String cacheManagerName, String cacheName); void cleanUpCacheMetaData(String cacheManagerName, String cacheName); }### Answer: @Test public void testaddCurrentOrchestrator() throws Exception { final String ORCHESTRATOR = "localhost:1000"; final String WAN_CURRENT_ORCHESTRATOR = "__WAN__CURRENT_ORCHESTRATOR"; wanUtil.addCurrentOrchestrator(CACHE_MANAGER_NAME, CACHE_NAME, ORCHESTRATOR); Assert.assertEquals(cacheConfigMap.get(WAN_CURRENT_ORCHESTRATOR), ORCHESTRATOR); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Creating new CacheManager with default config"); } singleton = new CacheManager(); } else { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Attempting to create an existing singleton. Existing singleton returned."); } } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 75 threads: " + threads, countThreads() <= 75); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return (Cache) caches.get(name); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = (Ehcache) ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } caches.remove(cacheName); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); void setName(String name); String toString(); String getDiskStorePath(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); }
### Question: ValueModeHandlerSerialization implements ValueModeHandler { @Override public ElementData createElementData(Element element) { if(element.isEternal()) { return new EternalElementData(element); } else { return new NonEternalElementData(element); } } @Override Object getRealKeyObject(String portableKey); @Override String createPortableKey(Object key); @Override ElementData createElementData(Element element); @Override Element createElement(Object key, Serializable value); }### Answer: @Test public void testCreateElementDataForEternalElement() { ElementData elementData = valueModeHandler.createElementData(eternalElement); Assert.assertTrue(elementData instanceof EternalElementData); } @Test public void testCreateElementDataForNonEternalElement() { ElementData elementData = valueModeHandler.createElementData(nonEternalElement); Assert.assertTrue(elementData instanceof NonEternalElementData); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return (Cache) caches.get(name); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); }
### Question: PayloadUtil { public static byte[] gzip(byte[] ungzipped) { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try { final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes); gzipOutputStream.write(ungzipped); gzipOutputStream.close(); } catch (IOException e) { LOG.error("Could not gzip " + ungzipped); } return bytes.toByteArray(); } private PayloadUtil(); static List<byte[]> createCompressedPayloadList(final List<CachePeer> localCachePeers, final int maximumPeersPerSend); static byte[] assembleUrlList(List localCachePeers); static byte[] gzip(byte[] ungzipped); static byte[] ungzip(final byte[] gzipped); static final int MTU; static final String URL_DELIMITER; }### Answer: @Test public void testMaximumDatagram() throws IOException { String payload = createReferenceString(); final byte[] compressed = PayloadUtil.gzip(payload.getBytes()); int length = compressed.length; LOG.info("gzipped size: " + length); assertTrue("Heartbeat too big for one Datagram " + length, length <= 1500); } @Test public void testGzipSanityAndPerformance() throws IOException, InterruptedException { String payload = createReferenceString(); for (int i = 0; i < 10; i++) { byte[] compressed = PayloadUtil.gzip(payload.getBytes()); assertTrue(compressed.length > 300); Thread.sleep(20); } int hashCode = payload.hashCode(); StopWatch stopWatch = new StopWatch(); for (int i = 0; i < 10000; i++) { if (hashCode != payload.hashCode()) { PayloadUtil.gzip(payload.getBytes()); } } long elapsed = stopWatch.getElapsedTime(); LOG.info("Gzip took " + elapsed / 10F + " µs"); }
### Question: CacheManager { public static CacheManager create() throws CacheException { if (singleton != null) { return singleton; } synchronized (CacheManager.class) { if (singleton == null) { LOG.debug("Creating new CacheManager with default config"); singleton = new CacheManager(); } else { LOG.debug("Attempting to create an existing singleton. Existing singleton returned."); } return singleton; } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testCacheManagerThreads() throws CacheException, InterruptedException { singletonManager = CacheManager .create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml"); int threads = countThreads(); assertTrue("More than 145 threads: " + threads, countThreads() <= 145); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); return (Cache) caches.get(name); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { instanceManager = CacheManager.create(); Ehcache cache = instanceManager.getCache("sampleCache1"); assertNotNull(cache); }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = (Ehcache) ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } caches.remove(cacheName); } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); boolean cacheExists(String cacheName); void removalAll(); void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); String getDiskStorePath(); FailSafeTimer getTimer(); static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testRemoveCache() throws CacheException { singletonManager = CacheManager.create(); Ehcache cache = singletonManager.getCache("sampleCache1"); assertNotNull(cache); singletonManager.removeCache("sampleCache1"); cache = singletonManager.getCache("sampleCache1"); assertNull(cache); singletonManager.removeCache(null); singletonManager.removeCache(""); }
### Question: ManagementService implements CacheManagerEventListener { public void init() throws CacheException { CacheManager cacheManager = new CacheManager(backingCacheManager); try { registerCacheManager(cacheManager); registerPeerProviders(); List caches = cacheManager.getCaches(); for (int i = 0; i < caches.size(); i++) { Cache cache = (Cache) caches.get(i); registerCachesIfRequired(cache); registerCacheStatisticsIfRequired(cache); registerCacheConfigurationIfRequired(cache); registerCacheStoreIfRequired(cache); } } catch (Exception e) { throw new CacheException(e); } status = Status.STATUS_ALIVE; backingCacheManager.getCacheManagerEventListenerRegistry().registerListener(this); } ManagementService(net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics, boolean registerCacheStores); static void registerMBeans( net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics, boolean registerCacheStores); void init(); Status getStatus(); void dispose(); void notifyCacheAdded(String cacheName); void notifyCacheRemoved(String cacheName); }### Answer: @Test public void testRegistrationServiceFourTrueUsing14MBeanServerWithConstructorInjection() throws Exception { mBeanServer = create14MBeanServer(); ManagementService managementService = new ManagementService(manager, mBeanServer, true, true, true, true, true); managementService.init(); assertEquals(OBJECTS_IN_TEST_EHCACHE, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size()); }
### Question: CacheKeySet implements Set<E> { public int size() { int size = 0; for (Collection keySet : keySets) { size += keySet.size(); } return size; } CacheKeySet(final Collection<E>... keySets); int size(); boolean isEmpty(); boolean contains(final Object o); Iterator<E> iterator(); Object[] toArray(); T[] toArray(final T[] a); boolean add(final Object o); boolean remove(final Object o); boolean containsAll(final Collection<?> c); boolean addAll(final Collection c); boolean removeAll(final Collection<?> c); boolean retainAll(final Collection<?> c); void clear(); }### Answer: @Test public void testSizeSumsAllCollections() { assertThat(keySet.size(), is(9)); }
### Question: CacheKeySet implements Set<E> { public boolean contains(final Object o) { for (Collection keySet : keySets) { if (keySet.contains(o)) { return true; } } return false; } CacheKeySet(final Collection<E>... keySets); int size(); boolean isEmpty(); boolean contains(final Object o); Iterator<E> iterator(); Object[] toArray(); T[] toArray(final T[] a); boolean add(final Object o); boolean remove(final Object o); boolean containsAll(final Collection<?> c); boolean addAll(final Collection c); boolean removeAll(final Collection<?> c); boolean retainAll(final Collection<?> c); void clear(); }### Answer: @Test public void testContainsIsSupported() { Set<Integer> keys = new HashSet<Integer>(keySet); for (Integer key : keys) { assertThat(keySet.contains(key), is(true)); } }
### Question: CacheKeySet implements Set<E> { public boolean isEmpty() { for (Collection keySet : keySets) { if (!keySet.isEmpty()) { return false; } } return true; } CacheKeySet(final Collection<E>... keySets); int size(); boolean isEmpty(); boolean contains(final Object o); Iterator<E> iterator(); Object[] toArray(); T[] toArray(final T[] a); boolean add(final Object o); boolean remove(final Object o); boolean containsAll(final Collection<?> c); boolean addAll(final Collection c); boolean removeAll(final Collection<?> c); boolean retainAll(final Collection<?> c); void clear(); }### Answer: @Test public void testSupportsEmptyKeySets() { final CacheKeySet cacheKeySet = new CacheKeySet(); assertThat(cacheKeySet.isEmpty(), is(true)); for (Object o : cacheKeySet) { fail("Shouldn't get anything!"); } }
### Question: CopyStrategyHandler { boolean isCopyActive() { return copyOnRead || copyOnWrite; } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy, ClassLoader loader); Element copyElementForReadIfNeeded(Element element); }### Answer: @Test public void given_no_copy_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null, loader); assertThat(copyStrategyHandler.isCopyActive(), is(false)); } @Test public void given_copy_on_read_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); assertThat(copyStrategyHandler.isCopyActive(), is(true)); } @Test public void given_copy_on_write_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); assertThat(copyStrategyHandler.isCopyActive(), is(true)); } @Test public void given_copy_on_read_and_write_when_isCopyActive_then_false() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); assertThat(copyStrategyHandler.isCopyActive(), is(true)); }
### Question: ValueModeHandlerSerialization implements ValueModeHandler { @Override public Element createElement(Object key, Serializable value) { return value == null ? null : ((ElementData) value).createElement(key); } @Override Object getRealKeyObject(String portableKey); @Override String createPortableKey(Object key); @Override ElementData createElementData(Element element); @Override Element createElement(Object key, Serializable value); }### Answer: @Test public void testCreateElementForEternalElement() { Element createdElement = valueModeHandler.createElement(KEY, new EternalElementData(eternalElement)); Assert.assertTrue(createdElement.isEternal()); } @Test public void testCreateElementForNonEternalElement() { Element createdElement = valueModeHandler.createElement(KEY, new NonEternalElementData(nonEternalElement)); Assert.assertFalse(createdElement.isEternal()); }
### Question: TxCopyingCacheStore extends AbstractCopyingCacheStore<T> { private static <T extends Store> TxCopyingCacheStore<T> wrap(final T cacheStore, final CacheConfiguration cacheConfiguration) { final ReadWriteCopyStrategy<Element> copyStrategyInstance = cacheConfiguration.getCopyStrategyConfiguration() .getCopyStrategyInstance(cacheConfiguration.getClassLoader()); return new TxCopyingCacheStore<T>(cacheStore, cacheConfiguration.isCopyOnRead(), cacheConfiguration.isCopyOnWrite(), copyStrategyInstance, cacheConfiguration.getClassLoader()); } TxCopyingCacheStore(T store, boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategyInstance, ClassLoader loader); Element getOldElement(Object key); static Store wrapTxStore(final AbstractTransactionStore cacheStore, final CacheConfiguration cacheConfiguration); static ElementValueComparator wrap(final ElementValueComparator comparator, final CacheConfiguration cacheConfiguration); }### Answer: @Test public void testWrappingElementValueComparatorEquals() throws Exception { CacheConfiguration cacheConfiguration = mock(CacheConfiguration.class); CopyStrategyConfiguration copyStrategyConfiguration = mock(CopyStrategyConfiguration.class); when(copyStrategyConfiguration.getCopyStrategyInstance(any(ClassLoader.class))).thenReturn(new ReadWriteSerializationCopyStrategy()); when(cacheConfiguration.getCopyStrategyConfiguration()).thenReturn(copyStrategyConfiguration); when(cacheConfiguration.isCopyOnRead()).thenReturn(true); when(cacheConfiguration.isCopyOnWrite()).thenReturn(true); when(cacheConfiguration.getClassLoader()).thenReturn(getClass().getClassLoader()); ElementValueComparator wrappedComparator = TxCopyingCacheStore.wrap(new DefaultElementValueComparator(cacheConfiguration), cacheConfiguration); Element e = new Element(1, serialize("aaa")); assertThat(wrappedComparator.equals(e, e), is(true)); assertThat(wrappedComparator.equals(null, null), is(true)); assertThat(wrappedComparator.equals(null, e), is(false)); assertThat(wrappedComparator.equals(e, null), is(false)); }
### Question: ElementResource { @DELETE public void deleteElement() throws NotFoundException { LOG.debug("DELETE element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); if (element.equals("*")) { ehcache.removeAll(); } else { boolean removed = ehcache.remove(element); if (!removed) { throw new NotFoundException("Element " + element + " not found"); } } } ElementResource(UriInfo uriInfo, Request request, String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer: @Test public void testDeleteElement() throws Exception { long beforeCreated = System.currentTimeMillis(); Thread.sleep(10); String originalString = "The rain in Spain falls mainly on the plain"; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(originalString.getBytes()); int status = HttpUtil.put("http: assertEquals(201, status); HttpURLConnection urlConnection = HttpUtil.get("http: assertEquals(200, urlConnection.getResponseCode()); urlConnection = HttpUtil.delete("http: assertEquals(404, HttpUtil.get("http: }
### Question: ElementResource { @GET public Response getElement() throws NotFoundException { LOG.debug("GET element {}", element); net.sf.ehcache.Cache ehcache = lookupCache(); net.sf.ehcache.Element ehcacheElement = lookupElement(ehcache); Element localElement = new Element(ehcacheElement, uriInfo.getAbsolutePath().toString()); Date lastModifiedDate = createLastModified(ehcacheElement); EntityTag entityTag = createETag(ehcacheElement); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(lastModifiedDate, entityTag); if (responseBuilder != null) { return responseBuilder.build(); } else { return Response.ok(localElement.getValue(), localElement.getMimeType()) .lastModified(lastModifiedDate) .tag(entityTag) .header("Expires", (new Date(localElement.getExpirationDate())).toString()) .build(); } } ElementResource(UriInfo uriInfo, Request request, String cache, String element); @HEAD Response getElementHeader(); @GET Response getElement(); @PUT Response putElement(@Context HttpHeaders headers, byte[] data); @DELETE void deleteElement(); }### Answer: @Test public void testGetElement() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: }
### Question: CacheResource { @GET public Cache getCache() { LOG.debug("GET Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); if (ehcache == null) { throw new NotFoundException("Cache not found"); } String cacheAsString = ehcache.toString(); cacheAsString = cacheAsString.substring(0, cacheAsString.length() - 1); cacheAsString = cacheAsString + "size = " + ehcache.getSize() + " ]"; return new Cache(ehcache.getName(), uriInfo.getAbsolutePath().toString(), cacheAsString, new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element") String element); }### Answer: @Test public void testGetCache() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); assertEquals("application/xml", result.getContentType()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Cache cache = (Cache) unmarshaller.unmarshal(result.getInputStream()); assertEquals("sampleCache1", cache.getName()); assertEquals("http: assertNotNull("http: }
### Question: CacheResource { @DELETE public Response deleteCache() { LOG.debug("DELETE Cache {}" + cache); net.sf.ehcache.Cache ehcache = MANAGER.getCache(cache); Response response; if (ehcache == null) { throw new NotFoundException("Cache not found " + cache); } else { CacheManager.getInstance().removeCache(cache); response = Response.ok().build(); } return response; } CacheResource(UriInfo uriInfo, Request request, String cache); @HEAD Response getCacheHeader(); @GET Cache getCache(); @PUT Response putCache(); @DELETE Response deleteCache(); @Path(value = "{element}") ElementResource getElementResource(@PathParam("element") String element); }### Answer: @Test public void testDeleteCache() throws Exception { HttpURLConnection urlConnection = HttpUtil.put("http: urlConnection = HttpUtil.delete("http: assertEquals(200, urlConnection.getResponseCode()); if (urlConnection.getHeaderField("Server").matches("(.*)Glassfish(.*)")) { assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); } String responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); assertEquals("", responseBody); urlConnection = HttpUtil.delete("http: assertEquals(404, urlConnection.getResponseCode()); assertTrue(urlConnection.getContentType().matches("text/plain(.*)")); try { responseBody = HttpUtil.inputStreamToText(urlConnection.getInputStream()); } catch (IOException e) { } }
### Question: DiskStorePathManager { public File getFile(String cacheName, String suffix) { return getFile(safeName(cacheName) + suffix); } DiskStorePathManager(String initialPath); DiskStorePathManager(); boolean resolveAndLockIfExists(String file); boolean isAutoCreated(); boolean isDefault(); synchronized void releaseLock(); File getFile(String cacheName, String suffix); File getFile(String name); }### Answer: @Test public void testCollisionDifferentThread() throws Exception { final String diskStorePath = getTempDir("testCollisionDifferentThread"); dspm1 = new DiskStorePathManager(diskStorePath); dspm1.getFile("foo"); Thread newThread = new Thread() { @Override public void run() { dspm2 = new DiskStorePathManager(diskStorePath); dspm2.getFile("foo"); } }; newThread.start(); newThread.join(10 * 1000L); Assert.assertFalse(getDiskStorePath(dspm1).equals(getDiskStorePath(dspm2))); } @Test(expected = CacheException.class) public void testIllegalPath() { Assume.assumeTrue(System.getProperty("os.name").contains("Windows")); String diskStorePath = getTempDir("testIllegalPath") + "/com1"; dspm1 = new DiskStorePathManager(diskStorePath); dspm1.getFile("foo"); }
### Question: ConcurrencyUtil { public static int selectLock(final Object key, int numberOfLocks) throws CacheException { int number = numberOfLocks & (numberOfLocks - 1); if (number != 0) { throw new CacheException("Lock number must be a power of two: " + numberOfLocks); } if (key == null) { return 0; } else { int hash = hash(key) & (numberOfLocks - 1); return hash; } } private ConcurrencyUtil(); static int hash(Object object); static int selectLock(final Object key, int numberOfLocks); static void shutdownAndWaitForTermination(ExecutorService pool, int waitSeconds); }### Answer: @Test public void testStripingDistribution() { int[] lockIndexes = new int[2048]; for (int i = 0; i < 20480 * 3; i++) { String key = "" + i * 3 / 2 + i; key += key.hashCode(); int lock = ConcurrencyUtil.selectLock(key, 2048); lockIndexes[lock]++; } int outliers = 0; for (int i = 0; i < 2048; i++) { if (20 <= lockIndexes[i] && lockIndexes[i] <= 40) { continue; } LOG.info(i + ": " + lockIndexes[i]); outliers++; } assertTrue(outliers <= 128); } @Test public void testNullKey() { ConcurrencyUtil.selectLock(null, 2048); ConcurrencyUtil.selectLock("", 2048); } @Test public void testEvenLockNumber() { try { ConcurrencyUtil.selectLock("anything", 100); } catch (CacheException e) { } }
### Question: SizeOfEngineLoader implements SizeOfEngineFactory { @Override public SizeOfEngine createSizeOfEngine(final int maxObjectCount, final boolean abort, final boolean silent) { SizeOfEngineFactory currentFactory = this.factory; if (currentFactory != null) { return currentFactory.createSizeOfEngine(maxObjectCount, abort, silent); } return new DefaultSizeOfEngine(maxObjectCount, abort, silent); } SizeOfEngineLoader(ClassLoader classLoader); private SizeOfEngineLoader(); static SizeOfEngine newSizeOfEngine(final int maxObjectCount, final boolean abort, final boolean silent); @Override SizeOfEngine createSizeOfEngine(final int maxObjectCount, final boolean abort, final boolean silent); void reload(); synchronized boolean load(Class<? extends SizeOfEngineFactory> clazz, boolean reload); static final SizeOfEngineLoader INSTANCE; }### Answer: @Test public void testFallsBackToDefaultSizeOfEngine() { final SizeOfEngine sizeOfEngine = SizeOfEngineLoader.INSTANCE.createSizeOfEngine(10, true, true); assertThat(sizeOfEngine, notNullValue()); assertThat(sizeOfEngine, instanceOf(DefaultSizeOfEngine.class)); } @Test public void testUsesServiceLoaderWhenItCan() { ClassLoader cl = new CheatingClassLoader(); SizeOfEngineLoader loader = new SizeOfEngineLoader(cl); assertThat(loader.createSizeOfEngine(10, true, true), sameInstance(constantSizeOfEngine)); }
### Question: ResourceClassLoader extends ClassLoader { @Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith("java.")) { return getParent().loadClass(name); } Class c = findLoadedClass(name); if (c == null) { try { c = findClass(name); } catch (ClassNotFoundException e) { c = super.loadClass(name, resolve); } } if (resolve) { resolveClass(c); } return c; } ResourceClassLoader(String prefix, ClassLoader parent); @Override synchronized Class<?> loadClass(String name, boolean resolve); @Override URL getResource(String name); }### Answer: @Test(expected = ClassNotFoundException.class) public void contentOfTheJarNotVisibleWithNormalClassLoaderTest() throws ClassNotFoundException { Class<?> simpleClass = testCaseClassLoader.loadClass("pof.Simple"); } @Test public void workingWithClassFromPrivateClassPathTest() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { ResourceClassLoader resourceClassLoader = new ResourceClassLoader("private-classpath", testCaseClassLoader); Class<?> simpleClass = resourceClassLoader.loadClass("pof.Simple"); Constructor<?> simpleClassConstructor = simpleClass.getConstructor(new Class[] {}); Object simpleObject = simpleClassConstructor.newInstance(new Object[] {}); Method sayHelloMethod = simpleClass.getMethod("sayHello", new Class[] {}); Object sayHello = sayHelloMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("hello!", sayHello); Method printVersionMethod = simpleClass.getMethod("printVersion", new Class[] {}); Object printVersion = printVersionMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("2.6.0-SNAPSHOT", printVersion); Method getMessageInTextFileMethod = simpleClass.getMethod("getMessageInTextFile", new Class[] {}); Object message = getMessageInTextFileMethod.invoke(simpleObject, new Object[] {}); Assert.assertEquals("Congratulations ! You could read a file from a hidden resource location !", message); }
### Question: SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { refresh(true); } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); @Override Element get(final Object key); void refresh(); void refresh(boolean quiet); Element refresh(Object key); Element refresh(Object key, boolean quiet); }### Answer: @Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertEquals(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertEquals(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); } @Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); }
### Question: ManagementService implements CacheManagerEventListener { public void init() throws CacheException { CacheManager cacheManager = new CacheManager(backingCacheManager); try { registerCacheManager(cacheManager); List caches = cacheManager.getCaches(); for (int i = 0; i < caches.size(); i++) { Cache cache = (Cache) caches.get(i); registerCachesIfRequired(cache); registerCacheStatisticsIfRequired(cache); registerCacheConfigurationIfRequired(cache); } } catch (Exception e) { throw new CacheException(e); } status = Status.STATUS_ALIVE; backingCacheManager.getCacheManagerEventListenerRegistry().registerListener(this); } ManagementService(net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics); static void registerMBeans( net.sf.ehcache.CacheManager cacheManager, MBeanServer mBeanServer, boolean registerCacheManager, boolean registerCaches, boolean registerCacheConfigurations, boolean registerCacheStatistics); void init(); Status getStatus(); void dispose(); void notifyCacheAdded(String cacheName); void notifyCacheRemoved(String cacheName); }### Answer: @Test public void testRegistrationServiceFourTrueUsing14MBeanServerWithConstructorInjection() throws Exception { mBeanServer = create14MBeanServer(); ManagementService managementService = new ManagementService(manager, mBeanServer, true, true, true, true); managementService.init(); assertEquals(OBJECTS_IN_TEST_EHCACHE, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size()); }
### Question: SelfPopulatingCache extends BlockingCache { public void refresh() throws CacheException { Exception exception = null; Object keyWithException = null; final Collection keys = getKeys(); if (LOG.isLoggable(Level.FINE)) { LOG.fine(getName() + ": found " + keys.size() + " keys to refresh"); } for (Iterator iterator = keys.iterator(); iterator.hasNext();) { final Object key = iterator.next(); try { Ehcache backingCache = getCache(); final Element element = backingCache.getQuiet(key); if (element == null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine(getName() + ": entry with key " + key + " has been removed - skipping it"); } continue; } refreshElement(element, backingCache); } catch (final Exception e) { LOG.log(Level.WARNING, getName() + "Could not refresh element " + key, e); exception = e; } } if (exception != null) { throw new CacheException(exception.getMessage() + " on refresh with key " + keyWithException); } } SelfPopulatingCache(final Ehcache cache, final CacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer: @Test public void testRefresh() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); selfPopulatingCache.refresh(); assertEquals(2, factory.getCount()); assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(2, factory.getCount()); }
### Question: UpdatingSelfPopulatingCache extends SelfPopulatingCache { public Element get(final Object key) throws LockTimeoutException { try { Ehcache backingCache = getCache(); Element element = backingCache.get(key); if (element == null) { element = super.get(key); } else { Mutex lock = stripedMutex.getMutexForKey(key); try { lock.acquire(); update(key); } finally { lock.release(); } } return element; } catch (final Throwable throwable) { put(new Element(key, null)); throw new LockTimeoutException("Could not fetch object for cache entry with key \"" + key + "\".", throwable); } } UpdatingSelfPopulatingCache(Ehcache cache, final UpdatingCacheEntryFactory factory); Element get(final Object key); void refresh(); }### Answer: @Test public void testFetchAndUpdate() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); Element element = selfPopulatingCache.get(null); element = selfPopulatingCache.get("key"); assertSame(value, element.getObjectValue()); assertEquals(2, factory.getCount()); Object actualValue = selfPopulatingCache.get("key").getObjectValue(); assertSame(value, actualValue); assertEquals(3, factory.getCount()); actualValue = selfPopulatingCache.get("key").getObjectValue(); assertSame(value, actualValue); assertEquals(4, factory.getCount()); } @Test public void testFetchFail() throws Exception { final Exception exception = new Exception("Failed."); final UpdatingCacheEntryFactory factory = new UpdatingCacheEntryFactory() { public Object createEntry(final Object key) throws Exception { throw exception; } public void updateEntryValue(Object key, Object value) throws Exception { throw exception; } }; selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory); try { selfPopulatingCache.get("key"); fail(); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } }
### Question: CachesResource { @GET public Caches getCaches() { LOG.info("GET Caches"); String[] cacheNames = CacheManager.getInstance().getCacheNames(); List<Cache> cacheList = new ArrayList<Cache>(); for (String cacheName : cacheNames) { URI cacheUri = uriInfo.getAbsolutePathBuilder().path(cacheName).build().normalize(); Cache cache = new Cache(cacheName, cacheUri.toString()); cacheList.add(cache); } return new Caches(cacheList); } @Path("{cache}") CacheResource getCacheResource(@PathParam("cache") String cache); @GET Caches getCaches(); }### Answer: @Test public void testGetCaches() throws IOException, ParserConfigurationException, SAXException { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); }