method2testcases
stringlengths
118
6.63k
### 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: AliOSSBlobStore extends BaseBlobStore { @Override public boolean blobExists(String container, String name) { return doOssOperation(oss -> oss.doesObjectExist(container, name)); } @Inject protected AliOSSBlobStore(AliOSSApi aliOSSApi, BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation, LocationsSupplier locations, PayloadSlicer slicer); @Override boolean containerExists(String container); @Override PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options); @Override boolean blobExists(String container, String name); @Override String putBlob(String container, Blob blob); @Override String putBlob(String container, Blob blob, PutOptions options); @Override Blob getBlob(String container, String name, GetOptions options); @Override void removeBlob(String container, String name); @Override PageSet<? extends StorageMetadata> list(); @Override boolean createContainerInLocation(Location location, String container); @Override boolean createContainerInLocation(Location location, String container, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override BlobMetadata blobMetadata(String container, String name); @Override BlobAccess getBlobAccess(String container, String name); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override MultipartUpload initiateMultipartUpload(String container, BlobMetadata blob, PutOptions options); @Override void abortMultipartUpload(MultipartUpload mpu); @Override String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts); @Override MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload); @Override List<MultipartPart> listMultipartUpload(MultipartUpload mpu); @Override List<MultipartUpload> listMultipartUploads(String container); @Override long getMinimumMultipartPartSize(); @Override long getMaximumMultipartPartSize(); @Override int getMaximumNumberOfParts(); }### Answer: @Test void testBlobExists() { Mockito.when(ossClient.doesObjectExist(CONTAINER, FILENAME)) .thenReturn(true) .thenReturn(false); assertTrue(aliOSSBlobStore.blobExists(CONTAINER, FILENAME)); assertFalse(aliOSSBlobStore.blobExists(CONTAINER, FILENAME)); }
### Question: AliOSSBlobStore extends BaseBlobStore { @Override public String putBlob(String container, Blob blob) { return doOssOperation(oss -> { try { ObjectMetadata objectMetadata = createObjectMetadataFromBlob(blob); PutObjectRequest request = new PutObjectRequest(container, blob.getMetadata() .getProviderId(), blob.getPayload() .openStream(), objectMetadata); PutObjectResult result = oss.putObject(request); return result.getETag(); } catch (IOException e) { throw new SLException(e); } }); } @Inject protected AliOSSBlobStore(AliOSSApi aliOSSApi, BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation, LocationsSupplier locations, PayloadSlicer slicer); @Override boolean containerExists(String container); @Override PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options); @Override boolean blobExists(String container, String name); @Override String putBlob(String container, Blob blob); @Override String putBlob(String container, Blob blob, PutOptions options); @Override Blob getBlob(String container, String name, GetOptions options); @Override void removeBlob(String container, String name); @Override PageSet<? extends StorageMetadata> list(); @Override boolean createContainerInLocation(Location location, String container); @Override boolean createContainerInLocation(Location location, String container, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override BlobMetadata blobMetadata(String container, String name); @Override BlobAccess getBlobAccess(String container, String name); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override MultipartUpload initiateMultipartUpload(String container, BlobMetadata blob, PutOptions options); @Override void abortMultipartUpload(MultipartUpload mpu); @Override String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts); @Override MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload); @Override List<MultipartPart> listMultipartUpload(MultipartUpload mpu); @Override List<MultipartUpload> listMultipartUploads(String container); @Override long getMinimumMultipartPartSize(); @Override long getMaximumMultipartPartSize(); @Override int getMaximumNumberOfParts(); }### Answer: @Test void testPutBlob() { Mockito.when(ossClient.putObject(any())) .thenReturn(new PutObjectResult()); Blob blob = new BlobBuilderImpl().name(FILENAME) .payload(PAYLOAD) .userMetadata(getUserMetadata()) .build(); aliOSSBlobStore.putBlob(CONTAINER, blob); Mockito.verify(ossClient) .putObject(any(PutObjectRequest.class)); }
### Question: AliOSSBlobStore extends BaseBlobStore { @Override public Blob getBlob(String container, String name, GetOptions options) { return doOssOperation(oss -> { GetObjectRequest req = toGetObjectRequest(container, name, options); OSSObject object = oss.getObject(req); return convertToBlob(object); }, false); } @Inject protected AliOSSBlobStore(AliOSSApi aliOSSApi, BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation, LocationsSupplier locations, PayloadSlicer slicer); @Override boolean containerExists(String container); @Override PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options); @Override boolean blobExists(String container, String name); @Override String putBlob(String container, Blob blob); @Override String putBlob(String container, Blob blob, PutOptions options); @Override Blob getBlob(String container, String name, GetOptions options); @Override void removeBlob(String container, String name); @Override PageSet<? extends StorageMetadata> list(); @Override boolean createContainerInLocation(Location location, String container); @Override boolean createContainerInLocation(Location location, String container, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override BlobMetadata blobMetadata(String container, String name); @Override BlobAccess getBlobAccess(String container, String name); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override MultipartUpload initiateMultipartUpload(String container, BlobMetadata blob, PutOptions options); @Override void abortMultipartUpload(MultipartUpload mpu); @Override String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts); @Override MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload); @Override List<MultipartPart> listMultipartUpload(MultipartUpload mpu); @Override List<MultipartUpload> listMultipartUploads(String container); @Override long getMinimumMultipartPartSize(); @Override long getMaximumMultipartPartSize(); @Override int getMaximumNumberOfParts(); }### Answer: @Test void testGetBlob() throws Exception { OSSObject ossObject = new OSSObject(); ossObject.setKey(FILENAME); ossObject.setObjectContent(new ByteArrayInputStream(PAYLOAD.getBytes())); Mockito.when(blobUtils.blobBuilder()) .thenReturn(new BlobBuilderImpl()); Mockito.when(ossClient.getObject(any(GetObjectRequest.class))) .thenReturn(ossObject); Blob blob = aliOSSBlobStore.getBlob(CONTAINER, FILENAME); String actualPayload = IOUtils.toString(blob.getPayload() .openStream(), StandardCharsets.UTF_8); assertEquals(PAYLOAD, actualPayload); }
### Question: AliOSSBlobStore extends BaseBlobStore { @Override public void removeBlob(String container, String name) { doOssOperation(oss -> { oss.deleteObject(container, name); return null; }); } @Inject protected AliOSSBlobStore(AliOSSApi aliOSSApi, BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation, LocationsSupplier locations, PayloadSlicer slicer); @Override boolean containerExists(String container); @Override PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options); @Override boolean blobExists(String container, String name); @Override String putBlob(String container, Blob blob); @Override String putBlob(String container, Blob blob, PutOptions options); @Override Blob getBlob(String container, String name, GetOptions options); @Override void removeBlob(String container, String name); @Override PageSet<? extends StorageMetadata> list(); @Override boolean createContainerInLocation(Location location, String container); @Override boolean createContainerInLocation(Location location, String container, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override BlobMetadata blobMetadata(String container, String name); @Override BlobAccess getBlobAccess(String container, String name); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override MultipartUpload initiateMultipartUpload(String container, BlobMetadata blob, PutOptions options); @Override void abortMultipartUpload(MultipartUpload mpu); @Override String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts); @Override MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload); @Override List<MultipartPart> listMultipartUpload(MultipartUpload mpu); @Override List<MultipartUpload> listMultipartUploads(String container); @Override long getMinimumMultipartPartSize(); @Override long getMaximumMultipartPartSize(); @Override int getMaximumNumberOfParts(); }### Answer: @Test void testRemoveBlob() { aliOSSBlobStore.removeBlob(CONTAINER, FILENAME); Mockito.verify(ossClient) .deleteObject(CONTAINER, FILENAME); }
### Question: AliOSSBlobStore extends BaseBlobStore { @Override public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) { return doOssOperation(oss -> { ListObjectsRequest request = toListObjectRequest(container, options); ObjectListing objectListing = oss.listObjects(request); List<StorageMetadata> storageMetadataList = toStorageMetadataList(oss, container, objectListing); return new PageSetImpl<>(storageMetadataList, objectListing.getNextMarker()); }); } @Inject protected AliOSSBlobStore(AliOSSApi aliOSSApi, BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation, LocationsSupplier locations, PayloadSlicer slicer); @Override boolean containerExists(String container); @Override PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options); @Override boolean blobExists(String container, String name); @Override String putBlob(String container, Blob blob); @Override String putBlob(String container, Blob blob, PutOptions options); @Override Blob getBlob(String container, String name, GetOptions options); @Override void removeBlob(String container, String name); @Override PageSet<? extends StorageMetadata> list(); @Override boolean createContainerInLocation(Location location, String container); @Override boolean createContainerInLocation(Location location, String container, CreateContainerOptions options); @Override ContainerAccess getContainerAccess(String container); @Override void setContainerAccess(String container, ContainerAccess access); @Override BlobMetadata blobMetadata(String container, String name); @Override BlobAccess getBlobAccess(String container, String name); @Override void setBlobAccess(String container, String name, BlobAccess access); @Override MultipartUpload initiateMultipartUpload(String container, BlobMetadata blob, PutOptions options); @Override void abortMultipartUpload(MultipartUpload mpu); @Override String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts); @Override MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload); @Override List<MultipartPart> listMultipartUpload(MultipartUpload mpu); @Override List<MultipartUpload> listMultipartUploads(String container); @Override long getMinimumMultipartPartSize(); @Override long getMaximumMultipartPartSize(); @Override int getMaximumNumberOfParts(); }### Answer: @Test void testList() throws Exception { ObjectListing objectListing = new ObjectListing(); objectListing.setBucketName(CONTAINER); objectListing.setObjectSummaries(getObjectSummaries(3)); Mockito.when(ossClient.listObjects(any(ListObjectsRequest.class))) .thenReturn(objectListing); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setUserMetadata(getUserMetadata()); Mockito.when(ossClient.getObjectMetadata(any(String.class), any(String.class))) .thenReturn(objectMetadata); Mockito.when(ossClient.generatePresignedUrl(any(), any(), any())) .thenReturn(new URL("https: aliOSSBlobStore.list(CONTAINER, new ListContainerOptions().withDetails()) .forEach(storageMetadata -> { assertTrue(storageMetadata.getName() .startsWith(FILENAME)); assertEquals(PAYLOAD.length(), storageMetadata.getSize()); assertTrue(storageMetadata.getETag() .startsWith(FILENAME)); assertEquals(getUserMetadata(), storageMetadata.getUserMetadata()); }); }
### Question: FlowableHistoricDataCleaner implements Cleaner { @Override public void execute(Date expirationTime) { long deletedProcessesCount = 0; long expiredProcessesPages = getExpiredProcessesPageCount(expirationTime); for (int i = 0; i < expiredProcessesPages; i++) { deletedProcessesCount += deleteExpiredProcessesPage(expirationTime); } LOGGER.info(CleanUpJob.LOG_MARKER, format(Messages.DELETED_HISTORIC_PROCESSES_0, deletedProcessesCount)); } @Inject FlowableHistoricDataCleaner(HistoryService historyService); FlowableHistoricDataCleaner(HistoryService historyService, int pageSize); @Override void execute(Date expirationTime); }### Answer: @Test void testExecuteWithMultiplePages() { HistoricProcessInstance process1 = mockHistoricProcessInstanceWithId(OPERATION_ID_1); HistoricProcessInstance process2 = mockHistoricProcessInstanceWithId(OPERATION_ID_2); HistoricProcessInstance process3 = mockHistoricProcessInstanceWithId(OPERATION_ID_3); List<HistoricProcessInstance> page1 = List.of(process1, process2); List<HistoricProcessInstance> page2 = List.of(process3); List<HistoricProcessInstance> page3 = Collections.emptyList(); HistoricProcessInstanceQuery query = mockHistoricProcessInstanceQueryWithPages(List.of(page1, page2, page3)); when(historyService.createHistoricProcessInstanceQuery()).thenReturn(query); cleaner.execute(EXPIRATION_TIME); verify(historyService).deleteHistoricProcessInstance(OPERATION_ID_1); verify(historyService).deleteHistoricProcessInstance(OPERATION_ID_2); verify(historyService).deleteHistoricProcessInstance(OPERATION_ID_3); } @Test void testExecuteResilience() { HistoricProcessInstance process1 = mockHistoricProcessInstanceWithId(OPERATION_ID_1); HistoricProcessInstance process2 = mockHistoricProcessInstanceWithId(OPERATION_ID_2); List<HistoricProcessInstance> page1 = List.of(process1, process2); List<HistoricProcessInstance> page2 = Collections.emptyList(); HistoricProcessInstanceQuery query = mockHistoricProcessInstanceQueryWithPages(List.of(page1, page2)); when(historyService.createHistoricProcessInstanceQuery()).thenReturn(query); doThrow(new FlowableObjectNotFoundException("Oops! Someone was faster than you!")).when(historyService) .deleteHistoricProcessInstance(OPERATION_ID_1); cleaner.execute(EXPIRATION_TIME); verify(historyService).deleteHistoricProcessInstance(OPERATION_ID_1); verify(historyService).deleteHistoricProcessInstance(OPERATION_ID_2); }
### 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: ClusterStatus { public static boolean isZookeeperReady(String zkConnectString, int timeoutMs) { log.debug("Check if Zookeeper is ready: {} ", zkConnectString); ZooKeeper zookeeper = null; try { CountDownLatch waitForConnection = new CountDownLatch(1); boolean isSaslEnabled = false; if (System.getProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, null) != null) { isSaslEnabled = true; log.info( "SASL is enabled. java.security.auth.login.config={}", System.getProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG) ); } ZookeeperConnectionWatcher connectionWatcher = new ZookeeperConnectionWatcher(waitForConnection, isSaslEnabled); zookeeper = new ZooKeeper(zkConnectString, timeoutMs, connectionWatcher); boolean timedOut = !waitForConnection.await(timeoutMs, TimeUnit.MILLISECONDS); if (timedOut) { log.error( "Timed out waiting for connection to Zookeeper server [{}].", zkConnectString ); return false; } else if (!connectionWatcher.isSuccessful()) { log.error( "Error occurred while connecting to Zookeeper server[{}]. {} ", zkConnectString, connectionWatcher.getFailureMessage() ); return false; } else { return true; } } catch (Exception e) { log.error( "Error while waiting for Zookeeper client to connect to the server [{}].", zkConnectString, e ); return false; } finally { if (zookeeper != null) { try { zookeeper.close(); } catch (InterruptedException e) { log.error("Error while shutting down Zookeeper client.", e); Thread.currentThread().interrupt(); } } } } static boolean isZookeeperReady(String zkConnectString, int timeoutMs); static boolean isKafkaReady( Map<String, String> config, int minBrokerCount, int timeoutMs ); static Map<String, String> getKafkaEndpointFromZookeeper( String zkConnectString, int timeoutMs ); static final String JAVA_SECURITY_AUTH_LOGIN_CONFIG; static final String BROKERS_IDS_PATH; static final int BROKER_METADATA_REQUEST_BACKOFF_MS; }### Answer: @Test(timeout = 120000) public void zookeeperReady() throws Exception { assertThat( ClusterStatus.isZookeeperReady(this.kafka.getZookeeperConnectString(), 10000)) .isTrue(); } @Test(timeout = 120000) public void zookeeperReadyWithBadConnectString() throws Exception { assertThat( ClusterStatus.isZookeeperReady("localhost:3245", 10000)) .isFalse(); }
### Question: ClusterStatus { public static boolean isKafkaReady( Map<String, String> config, int minBrokerCount, int timeoutMs ) { log.debug("Check if Kafka is ready: {}", config); AdminClient adminClient = AdminClient.create(new HashMap<String, Object>(config)); long begin = System.currentTimeMillis(); long remainingWaitMs = timeoutMs; Collection<Node> brokers = new ArrayList<>(); while (remainingWaitMs > 0) { try { brokers = adminClient.describeCluster(new DescribeClusterOptions().timeoutMs( (int) Math.min(Integer.MAX_VALUE, remainingWaitMs))).nodes().get(); log.debug("Broker list: {}", (brokers != null ? brokers : "[]")); if ((brokers != null) && (brokers.size() >= minBrokerCount)) { return true; } } catch (Exception e) { log.error("Error while getting broker list.", e); } sleep(Math.min(BROKER_METADATA_REQUEST_BACKOFF_MS, remainingWaitMs)); log.info( "Expected {} brokers but found only {}. Trying to query Kafka for metadata again ...", minBrokerCount, brokers == null ? 0 : brokers.size() ); long elapsed = System.currentTimeMillis() - begin; remainingWaitMs = timeoutMs - elapsed; } log.error( "Expected {} brokers but found only {}. Brokers found {}.", minBrokerCount, brokers == null ? 0 : brokers.size(), brokers != null ? brokers : "[]" ); return false; } static boolean isZookeeperReady(String zkConnectString, int timeoutMs); static boolean isKafkaReady( Map<String, String> config, int minBrokerCount, int timeoutMs ); static Map<String, String> getKafkaEndpointFromZookeeper( String zkConnectString, int timeoutMs ); static final String JAVA_SECURITY_AUTH_LOGIN_CONFIG; static final String BROKERS_IDS_PATH; static final int BROKER_METADATA_REQUEST_BACKOFF_MS; }### Answer: @Test(timeout = 120000) public void isKafkaReady() throws Exception { Map<String, String> config = new HashMap<>(); config.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapBroker (SecurityProtocol.PLAINTEXT)); assertThat(ClusterStatus.isKafkaReady(config, 3, 10000)) .isTrue(); } @Test(timeout = 120000) public void isKafkaReadyFailWithLessBrokers() throws Exception { try { Map<String, String> config = new HashMap<>(); config.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapBroker (SecurityProtocol.PLAINTEXT)); assertThat(ClusterStatus.isKafkaReady(config, 5, 10000)) .isFalse(); } catch (Exception e) { fail("Unexpected error. " + e.getMessage()); } } @Test(timeout = 120000) public void isKafkaReadyWaitFailureWithNoBroker() throws Exception { try { Map<String, String> config = new HashMap<>(); config.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, "localhost:6789"); assertThat(ClusterStatus.isKafkaReady(config, 3, 10000)).isFalse(); } catch (Exception e) { fail("Unexpected error." + e.getMessage()); } }
### Question: OnHeapCachingTier implements CachingTier<K, V> { @Override public V get(final K key, final Callable<V> source, final boolean updateStats) { if (updateStats) { getObserver.begin(); } Object cachedValue = backEnd.get(key); if (cachedValue == null) { if (updateStats) { getObserver.end(GetOutcome.MISS); } Fault<V> f = new Fault<V>(source); cachedValue = backEnd.putIfAbsent(key, f); if (cachedValue == null) { try { V value = f.get(); putObserver.begin(); if (value == null) { backEnd.remove(key, f); } else if (backEnd.replace(key, f, value)) { putObserver.end(PutOutcome.ADDED); } return value; } catch (Throwable e) { backEnd.remove(key, f); if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new CacheException(e); } } } } else { if (updateStats) { getObserver.end(GetOutcome.HIT); } } return getValue(cachedValue); } OnHeapCachingTier(final HeapCacheBackEnd<K, Object> backEnd); static OnHeapCachingTier<Object, Element> createOnHeapCache(final Ehcache cache, final Pool onHeapPool); @Override V get(final K key, final Callable<V> source, final boolean updateStats); @Override V remove(final K key); @Override void clear(); @Override void addListener(final Listener<K, V> listener); @Statistic(name = "size", tags = "local-heap") @Override int getInMemorySize(); @Override int getOffHeapSize(); @Override boolean contains(final K key); @Statistic(name = "size-in-bytes", tags = "local-heap") @Override long getInMemorySizeInBytes(); @Override long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override void recalculateSize(final K key); }### Answer: @Test public void testOnlyPopulatesOnce() throws InterruptedException, BrokenBarrierException { final int threadCount = Runtime.getRuntime().availableProcessors() * 2; final CachingTier<String, String> cache = new OnHeapCachingTier<String, String>(new CountBasedBackEnd<String, Object>(threadCount * 2)); final AtomicBoolean failure = new AtomicBoolean(); final AtomicInteger invocationCounter = new AtomicInteger(); final AtomicInteger valuesRead = new AtomicInteger(); final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { try { final int await = barrier.await(); cache.get(KEY, new Callable<String>() { @Override public String call() throws Exception { invocationCounter.incrementAndGet(); return "0x" + Integer.toHexString(await); } }, false); valuesRead.getAndIncrement(); } catch (Exception e) { e.printStackTrace(); failure.set(true); } } }; threads[i].start(); } barrier.await(); for (Thread thread : threads) { thread.join(); } assertThat(failure.get(), is(false)); assertThat(invocationCounter.get(), is(1)); assertThat(valuesRead.get(), is(threadCount)); }
### Question: CountBasedBackEnd extends ConcurrentHashMap<K, V> implements HeapCacheBackEnd<K, V> { @Override public V putIfAbsent(final K key, final V value) { final V v = super.putIfAbsent(key, value); if (v == null) { try { evictIfRequired(key, value); } catch (Throwable e) { LOG.warn("Caught throwable while evicting", e); } } return v; } CountBasedBackEnd(final long maxEntriesLocalHeap); CountBasedBackEnd(final long maxEntriesLocalHeap, final Policy policy); void setPolicy(final Policy policy); @Override V putIfAbsent(final K key, final V value); @Override void registerEvictionCallback(final EvictionCallback<K, V> callback); @Override void recalculateSize(final K key); void setMaxEntriesLocalHeap(final long maxEntriesLocalHeap); long getMaxEntriesLocalHeap(); }### Answer: @Test public void testEvictsWhenAtCapacityMultiThreaded() throws InterruptedException { final int limit = 1000; final int threadNumber = Runtime.getRuntime().availableProcessors() * 2; final CountBasedBackEnd<String, Element> countBasedBackEnd = new CountBasedBackEnd<String, Element>(limit); final AtomicInteger counter = new AtomicInteger(0); final Runnable runnable = new Runnable() { @Override public void run() { int i; while ((i = counter.getAndIncrement()) < limit * threadNumber * 10) { final String key = Integer.toString(i); countBasedBackEnd.putIfAbsent(key, new Element(key, i)); } } }; Thread[] threads = new Thread[threadNumber]; for (int i = 0, threadsLength = threads.length; i < threadsLength; i++) { threads[i] = new Thread(runnable); threads[i].start(); } for (Thread thread : threads) { thread.join(); } assertThat("Grew to " + countBasedBackEnd.size(), countBasedBackEnd.size() <= limit, is(true)); int size = countBasedBackEnd.size(); for (String s : countBasedBackEnd.keySet()) { assertThat(countBasedBackEnd.remove(s), notNullValue()); size--; } assertThat(size, is(0)); }
### Question: CacheManager { public Cache getCache(String name) throws IllegalStateException, ClassCastException { checkStatus(); Ehcache ehcache = ehcaches.get(name); return ehcache instanceof Cache ? (Cache) ehcache : null; } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); Pool getOnHeapPool(); Pool getOnDiskPool(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager newInstance(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager newInstance(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager newInstance(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager newInstance(InputStream inputStream); static CacheManager create(Configuration config); static CacheManager newInstance(Configuration config); static CacheManager getCacheManager(String name); Cache getCache(String name); Ehcache getEhcache(String name); synchronized void addCache(String cacheName); void addCache(Cache cache); synchronized void addCache(Ehcache cache); synchronized void addDecoratedCache(Ehcache decoratedCache); synchronized void addDecoratedCacheIfAbsent(Ehcache decoratedCache); boolean cacheExists(String cacheName); void removalAll(); synchronized void removeCache(String cacheName); void shutdown(); String[] getCacheNames(); Status getStatus(); void clearAll(); void clearAllStartingWith(String prefix); CacheManagerPeerProvider getCacheManagerPeerProvider(String scheme); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); CacheManagerPeerListener getCachePeerListener(String scheme); CacheManagerEventListener getCacheManagerEventListener(); void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener); CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry(); synchronized void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache); String getName(); boolean isNamed(); void setName(String name); @Override String toString(); DiskStorePathManager getDiskStorePathManager(); FailSafeTimer getTimer(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); Configuration getConfiguration(); synchronized Ehcache addCacheIfAbsent(final Ehcache cache); synchronized Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); TransactionIDFactory getOrCreateTransactionIDFactory(); FeaturesManager getFeaturesManager(); static final String DEFAULT_NAME; static final double ON_HEAP_THRESHOLD; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testGetCache() throws CacheException { CacheManager manager = new CacheManager(new Configuration().cache(new CacheConfiguration("foo", 100))); try { assertNotNull(manager.getCache("foo")); } finally { manager.shutdown(); } }
### Question: Element implements Serializable, Cloneable { public final boolean isSerializable() { return isKeySerializable() && (value instanceof Serializable || value == null); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long nextToLastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan, final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value, final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer: @Test public void testIsSerializable() { Element element = new Element(null, null); assertTrue(element.isSerializable()); Element elementWithNullValue = new Element("1", null); assertTrue(elementWithNullValue.isSerializable()); Element elementWithNullKey = new Element(null, "1"); assertTrue(elementWithNullValue.isSerializable()); Element elementWithObjectKey = new Element(new Object(), "1"); assertTrue(elementWithNullValue.isSerializable()); }
### Question: Element implements Serializable, Cloneable { @Override public final boolean equals(final Object object) { if (object == null || !(object instanceof Element)) { return false; } Element element = (Element) object; if (key == null || element.getObjectKey() == null) { return false; } return key.equals(element.getObjectKey()); } Element(final Serializable key, final Serializable value, final long version); Element(final Object key, final Object value, final long version); @Deprecated Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long nextToLastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long lastUpdateTime, final long hitCount); Element(final Object key, final Object value, final long version, final long creationTime, final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan, final int timeToLive, final int timeToIdle, final long lastUpdateTime); Element(final Object key, final Object value, final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds); Element(final Serializable key, final Serializable value); Element(final Object key, final Object value); @Deprecated final Serializable getKey(); final Object getObjectKey(); @Deprecated final Serializable getValue(); final Object getObjectValue(); @Override final boolean equals(final Object object); void setTimeToLive(final int timeToLiveSeconds); void setTimeToIdle(final int timeToIdleSeconds); @Override final int hashCode(); final void setVersion(final long version); @Deprecated final void setCreateTime(); final long getCreationTime(); final long getLatestOfCreationAndUpdateTime(); final long getVersion(); final long getLastAccessTime(); @Deprecated final long getNextToLastAccessTime(); final long getHitCount(); final void resetAccessStatistics(); final void updateAccessStatistics(); final void updateUpdateStatistics(); @Override final String toString(); @Override final Object clone(); final long getSerializedSize(); final boolean isSerializable(); final boolean isKeySerializable(); long getLastUpdateTime(); boolean isExpired(); boolean isExpired(CacheConfiguration config); long getExpirationTime(); boolean isEternal(); void setEternal(final boolean eternal); boolean isLifespanSet(); int getTimeToLive(); int getTimeToIdle(); boolean usesCacheDefaultLifespan(); }### Answer: @Test public void testEquals() { Element element = new Element("key", "value"); assertFalse(element.equals("dog")); assertTrue(element.equals(element)); assertFalse(element.equals(null)); assertFalse(element.equals(new Element("cat", "hat"))); }
### 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: BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); }### Answer: @Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.log(Level.FINE, "Thrash Duration:" + duration); } @Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.debug("Thrash Duration:" + duration); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "CacheManager already shutdown"); } return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } 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(); 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 testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### 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(); 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: ApplicationEhCache extends DefaultApplication { @Override public Set<Class<?>> getClasses() { Set<Class<?>> s = new HashSet<Class<?>>(super.getClasses()); s.add(net.sf.ehcache.management.resource.services.ElementsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheStatisticSamplesResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CachesResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheManagersResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheManagerConfigsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.CacheConfigsResourceServiceImpl.class); s.add(net.sf.ehcache.management.resource.services.AgentsResourceServiceImpl.class); return s; } @Override Set<Class<?>> getClasses(); }### Answer: @Test public void testGetClasses() throws Exception { List<String> classpathElements = getClasspathElements(); ApplicationEhCache applicationEhCache = new ApplicationEhCache(); Set<Class<?>> applicationClasses = applicationEhCache.getClasses(); Set<Class<?>> allClassesFound = new HashSet<Class<?>>(); for (String cpElement : classpathElements) { if (cpElement.endsWith(".jar")) { if (pathOfJarNotFiltered(cpElement)) { System.out.println("last scanned path : " + cpElement); allClassesFound.addAll(getAllClassesFromJar(cpElement)); } } else { System.out.println("last scanned path : " + cpElement); allClassesFound.addAll(getAllClassesFromDirectory(cpElement)); } } Set<Class<?>> annotatedClasses = new HashSet<Class<?>>(); for (Class<?> aClass : allClassesFound) { if (aClass.isAnnotationPresent(javax.ws.rs.ext.Provider.class) || aClass.isAnnotationPresent(javax.ws.rs.Path.class)) { annotatedClasses.add(aClass); } } Assert.assertThat(annotatedClasses, equalTo(applicationClasses)); }
### 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: DfltSamplerRepositoryServiceV2 implements SamplerRepositoryServiceV2, EntityResourceFactoryV2, CacheManagerServiceV2, CacheServiceV2, AgentServiceV2, EventServiceV2 { @Override public ResponseEntityV2<CacheStatisticSampleEntityV2> createCacheStatisticSampleEntity(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> sampleNames) { CacheStatisticSampleEntityBuilderV2 builder = CacheStatisticSampleEntityBuilderV2.createWith(sampleNames); ResponseEntityV2<CacheStatisticSampleEntityV2> responseEntityV2 = new ResponseEntityV2<CacheStatisticSampleEntityV2>(); cacheManagerSamplerRepoLock.readLock().lock(); List<SamplerRepoEntry> disabledSamplerRepoEntries = new ArrayList<SamplerRepoEntry>(); try { if (cacheManagerNames == null) { for (Map.Entry<String, SamplerRepoEntry> entry : cacheManagerSamplerRepo.entrySet()) { enableNonStopFor(entry.getValue(), false); disabledSamplerRepoEntries.add(entry.getValue()); for (CacheSampler sampler : entry.getValue().getComprehensiveCacheSamplers(cacheNames)) { builder.add(sampler, entry.getKey()); } } } else { for (String cmName : cacheManagerNames) { SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName); if (entry != null) { enableNonStopFor(entry, false); disabledSamplerRepoEntries.add(entry); for (CacheSampler sampler : entry.getComprehensiveCacheSamplers(cacheNames)) { builder.add(sampler, cmName); } } } } responseEntityV2.getEntities().addAll(builder.build()); return responseEntityV2; } finally { for (SamplerRepoEntry samplerRepoEntry : disabledSamplerRepoEntries) { enableNonStopFor(samplerRepoEntry, true); } cacheManagerSamplerRepoLock.readLock().unlock(); } } DfltSamplerRepositoryServiceV2(ManagementRESTServiceConfiguration configuration, RemoteAgentEndpointImpl remoteAgentEndpoint); @Override void dispose(); @Override void register(CacheManager cacheManager); @Override void unregister(CacheManager cacheManager); @Override boolean hasRegistered(); @Override ResponseEntityV2<CacheManagerEntityV2> createCacheManagerEntities(Set<String> cacheManagerNames, Set<String> attributes); @Override ResponseEntityV2<CacheManagerConfigEntityV2> createCacheManagerConfigEntities(Set<String> cacheManagerNames); @Override ResponseEntityV2<CacheEntityV2> createCacheEntities(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> attributes); @Override ResponseEntityV2<CacheConfigEntityV2> createCacheConfigEntities(Set<String> cacheManagerNames, Set<String> cacheNames); @Override ResponseEntityV2<CacheStatisticSampleEntityV2> createCacheStatisticSampleEntity(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> sampleNames); @Override void createOrUpdateCache(String cacheManagerName, String cacheName, CacheEntityV2 resource); @Override void clearCache(String cacheManagerName, String cacheName); @Override void updateCacheManager(String cacheManagerName, CacheManagerEntityV2 resource); @Override ResponseEntityV2<QueryResultsEntityV2> executeQuery(String cacheManagerName, String queryString); @Override ResponseEntityV2<AgentEntityV2> getAgents(Set<String> ids); @Override ResponseEntityV2<AgentMetadataEntityV2> getAgentsMetadata(Set<String> ids); @Override void registerEventListener(EventListener listener, boolean localOnly); @Override void unregisterEventListener(EventListener listener); static final String AGENCY; }### Answer: @Test public void testCreateCacheStatisticSampleEntityDisablesNonStop() throws Exception { repositoryService.createCacheStatisticSampleEntity(Collections.singleton("testCacheManager"), Collections.singleton("testCache1"), Collections.singleton("Size")); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); } @Test public void testCreateCacheStatisticSampleEntityDisablesNonStop() throws Exception { repositoryService.createCacheStatisticSampleEntity(Collections.singleton("testCacheManager"), Collections.singleton("testCache1"), Collections.singleton("Size")); verify(clusteredInstanceFactory, times(4)).enableNonStopForCurrentThread(anyBoolean()); }
### Question: DfltSamplerRepositoryServiceV2 implements SamplerRepositoryServiceV2, EntityResourceFactoryV2, CacheManagerServiceV2, CacheServiceV2, AgentServiceV2, EventServiceV2 { @Override public void clearCache(String cacheManagerName, String cacheName) { cacheManagerSamplerRepoLock.readLock().lock(); SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cacheManagerName); try { enableNonStopFor(entry, false); if (entry != null) { entry.clearCache(cacheName); } } finally { enableNonStopFor(entry, true); cacheManagerSamplerRepoLock.readLock().unlock(); } } DfltSamplerRepositoryServiceV2(ManagementRESTServiceConfiguration configuration, RemoteAgentEndpointImpl remoteAgentEndpoint); @Override void dispose(); @Override void register(CacheManager cacheManager); @Override void unregister(CacheManager cacheManager); @Override boolean hasRegistered(); @Override ResponseEntityV2<CacheManagerEntityV2> createCacheManagerEntities(Set<String> cacheManagerNames, Set<String> attributes); @Override ResponseEntityV2<CacheManagerConfigEntityV2> createCacheManagerConfigEntities(Set<String> cacheManagerNames); @Override ResponseEntityV2<CacheEntityV2> createCacheEntities(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> attributes); @Override ResponseEntityV2<CacheConfigEntityV2> createCacheConfigEntities(Set<String> cacheManagerNames, Set<String> cacheNames); @Override ResponseEntityV2<CacheStatisticSampleEntityV2> createCacheStatisticSampleEntity(Set<String> cacheManagerNames, Set<String> cacheNames, Set<String> sampleNames); @Override void createOrUpdateCache(String cacheManagerName, String cacheName, CacheEntityV2 resource); @Override void clearCache(String cacheManagerName, String cacheName); @Override void updateCacheManager(String cacheManagerName, CacheManagerEntityV2 resource); @Override ResponseEntityV2<QueryResultsEntityV2> executeQuery(String cacheManagerName, String queryString); @Override ResponseEntityV2<AgentEntityV2> getAgents(Set<String> ids); @Override ResponseEntityV2<AgentMetadataEntityV2> getAgentsMetadata(Set<String> ids); @Override void registerEventListener(EventListener listener, boolean localOnly); @Override void unregisterEventListener(EventListener listener); static final String AGENCY; }### Answer: @Test public void testClearCacheDisablesNonStop() throws Exception { repositoryService.clearCache("testCacheManager", "testCache1"); verify(clusteredInstanceFactory, times(2)).enableNonStopForCurrentThread(anyBoolean()); } @Test public void testClearCacheDisablesNonStop() throws Exception { repositoryService.clearCache("testCacheManager", "testCache1"); verify(clusteredInstanceFactory, times(4)).enableNonStopForCurrentThread(anyBoolean()); }
### Question: ConfigurationFactory { static Set extractPropertyTokens(String sourceDocument) { Set propertyTokens = new HashSet(); Pattern pattern = Pattern.compile("\\$\\{.+?\\}"); Matcher matcher = pattern.matcher(sourceDocument); while (matcher.find()) { String token = matcher.group(); propertyTokens.add(token); } return propertyTokens; } private ConfigurationFactory(); static Configuration parseConfiguration(final File file); static Configuration parseConfiguration(final URL url); static Configuration parseConfiguration(); static Configuration parseConfiguration(final InputStream inputStream); static CacheConfiguration parseCacheConfiguration(String xmlString); }### Answer: @Test public void testMatchPropertyTokensProperlyFormed() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress}, " + "multicastGroupPort=4446, timeToLive=1\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(1, propertyTokens.size()); String firstPropertyToken = (String) (propertyTokens.toArray())[0]; assertEquals("${multicastAddress}", firstPropertyToken); } @Test public void testMatchPropertyTokensProperlyFormedUrl() { String example = "<terracottaConfig url=\"${serverAndPort}\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(1, propertyTokens.size()); String firstPropertyToken = (String) (propertyTokens.toArray())[0]; assertEquals("${serverAndPort}", firstPropertyToken); } @Test public void testMatchPropertyTokensProperlyFormedTwo() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress}\n, " + "multicastGroupPort=4446, timeToLive=${multicastAddress}\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(1, propertyTokens.size()); String firstPropertyToken = (String) (propertyTokens.toArray())[0]; assertEquals("${multicastAddress}", firstPropertyToken); } @Test public void testMatchPropertyTokensProperlyFormedTwoUnique() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress}\n, " + "multicastGroupPort=4446, timeToLive=${multicastAddress1}\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(2, propertyTokens.size()); } @Test public void testMatchPropertyTokensNotClosed() { String example = "<cacheManagerPeerProviderFactory class=\"net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory\"" + "properties=\"peerDiscovery=automatic, " + "multicastGroupAddress=${multicastAddress\n, " + "multicastGroupPort=4446, timeToLive=${multicastAddress\"/>"; Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example); assertEquals(0, propertyTokens.size()); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "CacheManager already shutdown"); } return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } 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 testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource("/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } Thread.sleep(300); int endingThreadCount = countThreads(); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### 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: CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache cache = null; try { cache = (Ehcache) defaultCache.clone(); } catch (CloneNotSupportedException e) { throw new CacheException("Failure adding cache. Initial cause was " + e.getMessage(), e); } if (cache != null) { cache.setName(cacheName); } addCache(cache); } 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 testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (int i = 0; i < cacheNames.length; i++) { String cacheName = cacheNames[i]; if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); }
### Question: SelfPopulatingCache extends BlockingCache { @Override public Element get(final Object key) throws LockTimeoutException { try { Element element = super.get(key); if (element == null) { Object value = factory.createEntry(key); element = makeAndCheckElement(key, value); put(element); } return element; } catch (LockTimeoutException e) { String message = "Timeout after " + timeoutMillis + " waiting on another thread " + "to fetch object for cache entry \"" + key + "\"."; throw new LockTimeoutException(message, e); } catch (final Throwable throwable) { put(new Element(key, null)); throw new CacheException("Could not fetch object for cache entry with key \"" + key + "\".", throwable); } } 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 testCreateOnce() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); final Cache cache = manager.getCache("sampleCacheNoIdle"); final Ehcache selfPopulatingCache = new SelfPopulatingCache(cache, factory); for (int i = 0; i < 5; i++) { assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); } } @Test public void testFetch() throws Exception { LOG.error("."); final Element element = selfPopulatingCache.get("key"); assertEquals("value", element.getValue()); } @Test public void testFetchUnknown() throws Exception { final CacheEntryFactory factory = new CountingCacheEntryFactory(null); selfPopulatingCache = new SelfPopulatingCache(cache, factory); assertNull(cache.get("key")); } @Test public void testFetchFail() throws Exception { final Exception exception = new Exception("Failed."); final CacheEntryFactory factory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { throw exception; } }; selfPopulatingCache = new SelfPopulatingCache(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()); } } @Test public void testCreateOnce() throws Exception { final String value = "value"; final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value); selfPopulatingCache = new SelfPopulatingCache(cache, factory); for (int i = 0; i < 5; i++) { assertSame(value, selfPopulatingCache.get("key").getObjectValue()); assertEquals(1, factory.getCount()); } } @Test public void testCacheEntryFactoryReturningElementMake() throws Exception { final long specialVersionNumber = 54321L; final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Element e = new Element(key, "V_" + key); e.setVersion(specialVersionNumber); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); Element e = null; e = selfPopulatingCache.get("key1"); assertEquals("V_key1", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); e = selfPopulatingCache.get("key2"); assertEquals("V_key2", e.getValue()); assertEquals(specialVersionNumber, e.getVersion()); assertEquals(2, selfPopulatingCache.getSize()); } @Test public void testCacheEntryFactoryReturningElementBadKey() throws Exception { final CacheEntryFactory elementReturningFactory = new CacheEntryFactory() { public Object createEntry(final Object key) throws Exception { Object modifiedKey = key.toString() + "XX"; Element e = new Element(modifiedKey, "V_" + modifiedKey); return e; } }; selfPopulatingCache = new SelfPopulatingCache(cache, elementReturningFactory); try { selfPopulatingCache.get("key"); fail("Should fail because key was changed"); } catch (final Exception e) { Thread.sleep(20); assertEquals("Could not fetch object for cache entry with key \"key\".", e.getMessage()); } }
### Question: Statistics implements Serializable { public void clearStatistics() { if (cache == null) { throw new IllegalStateException("This statistics object no longer references a Cache."); } cache.clearStatistics(); } Statistics(Ehcache cache, int statisticsAccuracy, long cacheHits, long onDiskHits, long offHeapHits, long inMemoryHits, long misses, long onDiskMisses, long offHeapMisses, long inMemoryMisses, long size, float averageGetTime, long evictionCount, long memoryStoreSize, long offHeapStoreSize, long diskStoreSize); void clearStatistics(); long getCacheHits(); long getInMemoryHits(); long getOffHeapHits(); long getOnDiskHits(); long getCacheMisses(); long getInMemoryMisses(); long getOffHeapMisses(); long getOnDiskMisses(); long getObjectCount(); long getMemoryStoreObjectCount(); long getOffHeapStoreObjectCount(); long getDiskStoreObjectCount(); int getStatisticsAccuracy(); String getStatisticsAccuracyDescription(); String getAssociatedCacheName(); Ehcache getAssociatedCache(); @Override final String toString(); float getAverageGetTime(); long getEvictionCount(); static boolean isValidStatisticsAccuracy(int statisticsAccuracy); static final int STATISTICS_ACCURACY_NONE; static final int STATISTICS_ACCURACY_BEST_EFFORT; static final int STATISTICS_ACCURACY_GUARANTEED; }### Answer: @Test public void testClearStatistics() throws InterruptedException { Cache cache = new Cache("test", 1, true, false, 5, 2); manager.addCache(cache); cache.setStatisticsEnabled(true); cache.put(new Element("key1", "value1")); cache.put(new Element("key2", "value1")); Thread.sleep(100); cache.get("key1"); Statistics statistics = cache.getStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(1, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); } @Test public void testClearStatistics() throws InterruptedException { Cache cache = new Cache("test", 1, true, false, 5, 2); manager.addCache(cache); cache.setStatisticsEnabled(true); cache.put(new Element("key1", "value1")); cache.put(new Element("key2", "value1")); cache.get("key1"); Statistics statistics = cache.getStatistics(); assertEquals(1, statistics.getCacheHits()); assertEquals(1, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); statistics.clearStatistics(); statistics = cache.getStatistics(); assertEquals(0, statistics.getCacheHits()); assertEquals(0, statistics.getOnDiskHits()); assertEquals(0, statistics.getInMemoryHits()); assertEquals(0, statistics.getCacheMisses()); }
### 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: BlockingCache implements Ehcache { protected Ehcache getCache() { return cache; } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isClusterCoherent(); boolean isNodeCoherent(); void setNodeCoherence(boolean coherent); void waitUntilClusterCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); }### Answer: @Test public void testThrashBlockingCache() throws Exception { Ehcache cache = manager.getCache("sampleCache1"); blockingCache = new BlockingCache(cache); long duration = thrashCache(blockingCache, 50, 500L, 1000L); LOG.debug("Thrash Duration:" + duration); }
### Question: BlockingCache implements Ehcache { public Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument) throws CacheException { throw new CacheException("This method is not appropriate for a Blocking Cache"); } BlockingCache(final Ehcache cache, int numberOfStripes); BlockingCache(final Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); CacheWriterManager getWriterManager(); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); void putWithWriter(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); boolean removeWithWriter(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void setTimeoutMillis(int timeoutMillis); int getTimeoutMillis(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); void registerCacheWriter(CacheWriter cacheWriter); void unregisterCacheWriter(); CacheWriter getRegisteredCacheWriter(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void disableDynamicFeatures(); boolean isClusterCoherent(); boolean isNodeCoherent(); void setNodeCoherence(boolean coherent); void waitUntilClusterCoherent(); void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup); }### Answer: @Test public void testGetWithLoader() { super.testGetWithLoader(); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } 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 testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### 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(); 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 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(); 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: 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(); 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 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: CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache cache = null; try { cache = (Ehcache) defaultCache.clone(); } catch (CloneNotSupportedException e) { throw new CacheException("Failure adding cache. Initial cause was " + e.getMessage(), e); } if (cache != null) { cache.setName(cacheName); } addCache(cache); } 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 testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } if (defaultCache != null) { defaultCache.dispose(); } status = Status.STATUS_SHUTDOWN; XARequestProcessor.shutdown(); if (this == singleton) { singleton = null; } terracottaClient.shutdown(); transactionController = null; removeShutdownHook(); CacheManagerExecutorServiceFactory.getInstance().shutdown(this); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); 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); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); 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(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### 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 void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); Collection cacheSet = ehcaches.values(); for (Iterator iterator = cacheSet.iterator(); iterator.hasNext();) { Ehcache cache = (Ehcache) iterator.next(); if (cache != null) { cache.dispose(); } } defaultCache.dispose(); status = Status.STATUS_SHUTDOWN; if (this == singleton) { singleton = null; } removeShutdownHook(); } } } 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 testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### 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: CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache cache = null; try { cache = (Ehcache) defaultCache.clone(); } catch (CloneNotSupportedException e) { throw new CacheException("Failure adding cache. Initial cause was " + e.getMessage(), e); } if (cache != null) { cache.setName(cacheName); } addCache(cache); } 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 testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); }
### 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: ManagementService implements CacheManagerEventListener { private void registerCacheManager(CacheManager cacheManager) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { if (registerCacheManager) { mBeanServer.registerMBean(cacheManager, cacheManager.getObjectName()); } } 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 testRegisterCacheManager() throws Exception { Ehcache ehcache = new net.sf.ehcache.Cache("testNoOverflowToDisk", 1, false, false, 500, 200); manager.addCache(ehcache); ehcache.put(new Element("key1", "value1")); ehcache.put(new Element("key2", "value1")); assertNull(ehcache.get("key1")); assertNotNull(ehcache.get("key2")); ObjectName name = new ObjectName("net.sf.ehcache:type=CacheManager,name=1"); CacheManager cacheManager = new CacheManager(manager); mBeanServer.registerMBean(cacheManager, name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=testOverflowToDisk"); mBeanServer.registerMBean(new Cache(ehcache), name); mBeanServer.unregisterMBean(name); name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=sampleCache1"); mBeanServer.registerMBean(new Cache(manager.getCache("sampleCache1")), name); mBeanServer.unregisterMBean(name); }
### Question: CacheManager { public void removeCache(String cacheName) throws IllegalStateException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } Ehcache cache = ehcaches.remove(cacheName); if (cache != null && cache.getStatus().equals(Status.STATUS_ALIVE)) { cache.dispose(); cacheManagerEventListenerRegistry.notifyCacheRemoved(cache.getName()); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); 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); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); 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(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; 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: CacheManager { public void addCache(String cacheName) throws IllegalStateException, ObjectExistsException, CacheException { checkStatus(); if (cacheName == null || cacheName.length() == 0) { return; } if (ehcaches.get(cacheName) != null) { throw new ObjectExistsException("Cache " + cacheName + " already exists"); } Ehcache clonedDefaultCache = cloneDefaultCache(cacheName); addCache(clonedDefaultCache); for (Ehcache ehcache : createDefaultCacheDecorators(clonedDefaultCache)) { addOrReplaceDecoratedCache(clonedDefaultCache, ehcache); } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); 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); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); 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(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); singletonManager.addCache("test"); singletonManager.addCache("test2"); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); } @Test public void testAddCache() throws CacheException { singletonManager = CacheManager.create(); assertEquals(15, singletonManager.getConfiguration().getCacheConfigurations().size()); singletonManager.addCache("test"); singletonManager.addCache("test2"); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().size()); Ehcache cache = singletonManager.getCache("test"); assertNotNull(cache); assertEquals("test", cache.getName()); String[] cacheNames = singletonManager.getCacheNames(); boolean match = false; for (String cacheName : cacheNames) { if (cacheName.equals("test")) { match = true; } } assertTrue(match); singletonManager.addCache(""); assertEquals(17, singletonManager.getConfiguration().getCacheConfigurations().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: OnHeapCachingTier implements CachingTier<K, V> { @Override public V get(final K key, final Callable<V> source, final boolean updateStats) { if (updateStats) { getObserver.begin(); } Object cachedValue = backEnd.get(key); if (cachedValue == null) { if (updateStats) { getObserver.end(GetOutcome.MISS); } Fault<V> f = new Fault<V>(source); cachedValue = backEnd.putIfAbsent(key, f); if (cachedValue == null) { try { V value = f.get(); putObserver.begin(); if (value == null) { backEnd.remove(key, f); } else if (backEnd.replace(key, f, value)) { putObserver.end(PutOutcome.ADDED); } else { V p = getValue(backEnd.remove(key)); return p == null ? value : p; } return value; } catch (Throwable e) { backEnd.remove(key, f); if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new CacheException(e); } } } } else { if (updateStats) { getObserver.end(GetOutcome.HIT); } } return getValue(cachedValue); } OnHeapCachingTier(final HeapCacheBackEnd<K, Object> backEnd); static OnHeapCachingTier<Object, Element> createOnHeapCache(final Ehcache cache, final Pool onHeapPool); @Override boolean loadOnPut(); @Override V get(final K key, final Callable<V> source, final boolean updateStats); @Override V remove(final K key); @Override void clear(); @Override void clearAndNotify(); @Override void addListener(final Listener<K, V> listener); @Statistic(name = "size", tags = "local-heap") @Override int getInMemorySize(); @Override int getOffHeapSize(); @Override boolean contains(final K key); @Statistic(name = "size-in-bytes", tags = "local-heap") @Override long getInMemorySizeInBytes(); @Override long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override void recalculateSize(final K key); @Override Policy getEvictionPolicy(); @Override void setEvictionPolicy(final Policy policy); }### Answer: @Test public void testOnlyPopulatesOnce() throws InterruptedException, BrokenBarrierException { final int threadCount = Runtime.getRuntime().availableProcessors() * 2; final CachingTier<String, String> cache = new OnHeapCachingTier<String, String>(new CountBasedBackEnd<String, Object>(threadCount * 2)); final AtomicBoolean failure = new AtomicBoolean(); final AtomicInteger invocationCounter = new AtomicInteger(); final AtomicInteger valuesRead = new AtomicInteger(); final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); final Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { try { final int await = barrier.await(); cache.get(KEY, new Callable<String>() { @Override public String call() throws Exception { invocationCounter.incrementAndGet(); return "0x" + Integer.toHexString(await); } }, false); valuesRead.getAndIncrement(); } catch (Exception e) { e.printStackTrace(); failure.set(true); } } }; threads[i].start(); } barrier.await(); for (Thread thread : threads) { thread.join(); } assertThat(failure.get(), is(false)); assertThat(invocationCounter.get(), is(1)); assertThat(valuesRead.get(), is(threadCount)); }
### Question: Segment extends ReentrantReadWriteLock { Element put(Object key, int hash, Element element, boolean onlyIfAbsent, boolean faulted) { boolean installed = false; DiskSubstitute encoded = disk.create(element); final long incomingHeapSize = onHeapPoolAccessor.add(key, encoded, NULL_HASH_ENTRY, cachePinned || faulted); if (incomingHeapSize < 0) { LOG.debug("put failed to add on heap"); evictionObserver.end(EvictionOutcome.SUCCESS); cacheEventNotificationService.notifyElementEvicted(element, false); return null; } else { LOG.debug("put added {} on heap", incomingHeapSize); encoded.onHeapSize = incomingHeapSize; } writeLock().lock(); try { if (count + 1 > threshold) { rehash(); } HashEntry[] tab = table; int index = hash & (tab.length - 1); HashEntry first = tab[index]; HashEntry e = first; while (e != null && (e.hash != hash || !key.equals(e.key))) { e = e.next; } Element oldElement; if (e != null) { DiskSubstitute onDiskSubstitute = e.element; if (!onlyIfAbsent) { e.element = encoded; installed = true; oldElement = decode(onDiskSubstitute); free(onDiskSubstitute); final long existingHeapSize = onHeapPoolAccessor.delete(onDiskSubstitute.onHeapSize); LOG.debug("put updated, deleted {} on heap", existingHeapSize); if (onDiskSubstitute instanceof DiskStorageFactory.DiskMarker) { final long existingDiskSize = onDiskPoolAccessor.delete(((DiskStorageFactory.DiskMarker) onDiskSubstitute).getSize()); LOG.debug("put updated, deleted {} on disk", existingDiskSize); } e.faulted.set(faulted); cacheEventNotificationService.notifyElementUpdatedOrdered(oldElement, element); } else { oldElement = decode(onDiskSubstitute); free(encoded); final long outgoingHeapSize = onHeapPoolAccessor.delete(encoded.onHeapSize); LOG.debug("put if absent failed, deleted {} on heap", outgoingHeapSize); } } else { oldElement = null; ++modCount; tab[index] = new HashEntry(key, hash, first, encoded, new AtomicBoolean(faulted)); installed = true; count = count + 1; cacheEventNotificationService.notifyElementPutOrdered(element); } return oldElement; } finally { writeLock().unlock(); if (installed) { encoded.installed(); } } } Segment(int initialCapacity, float loadFactor, DiskStorageFactory primary, CacheConfiguration cacheConfiguration, PoolAccessor onHeapPoolAccessor, PoolAccessor onDiskPoolAccessor, RegisteredEventListeners cacheEventNotificationService, OperationObserver<EvictionOutcome> evictionObserver); @Override String toString(); boolean isFaulted(final int hash, final Object key); }### Answer: @Test public void testInlineEvictionNotified() { PoolAccessor onHeapAccessor = mock(PoolAccessor.class); when(onHeapAccessor.add(eq("key"), any(DiskStorageFactory.DiskSubstitute.class), any(HashEntry.class), eq(false))).thenReturn(-1L); RegisteredEventListeners cacheEventNotificationService = new RegisteredEventListeners(mock(Ehcache.class), null); CacheEventListener listener = mock(CacheEventListener.class); cacheEventNotificationService.registerListener(listener); OperationObserver<CacheOperationOutcomes.EvictionOutcome> evictionObserver = mock(OperationObserver.class); Segment segment = new Segment(10, .95f, mock(DiskStorageFactory.class), mock(CacheConfiguration.class), onHeapAccessor, mock(PoolAccessor.class), cacheEventNotificationService, evictionObserver); Element element = new Element("key", "value"); segment.put("key", 12, element, false, false); verify(listener).notifyElementEvicted(any(Ehcache.class), eq(element)); verify(evictionObserver).end(CacheOperationOutcomes.EvictionOutcome.SUCCESS); }
### 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: CopyStrategyHandler { public Element copyElementForReadIfNeeded(Element element) { if (element == null) { return null; } if (copyOnRead && copyOnWrite) { return copyStrategy.copyForRead(element, loader); } else if (copyOnRead) { return copyStrategy.copyForRead(copyStrategy.copyForWrite(element, loader), loader); } else { return element; } } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy, ClassLoader loader); Element copyElementForReadIfNeeded(Element element); }### Answer: @Test public void given_no_copy_when_copyElementForReadIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null, loader); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(element), sameInstance(element)); } @Test public void given_no_copy_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null, loader); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); } @Test public void given_copy_on_read_when_copyElementForReadIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element, loader)).thenReturn(serial); when(copyStrategy.copyForRead(serial, loader)).thenReturn(new Element("key", "value")); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(element), allOf(not(sameInstance(element)), is(element))); verify(copyStrategy).copyForWrite(element, loader); verify(copyStrategy).copyForRead(serial, loader); } @Test public void given_copy_on_read_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); } @Test public void given_copy_on_write_when_copyElementForReadIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy, loader); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(element), sameInstance(element)); } @Test public void given_copy_on_write_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); } @Test public void given_copy_on_read_and_write_when_copyElementForReadIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForRead(serial, loader)).thenReturn(new Element("key", "value")); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(serial), is(element)); verify(copyStrategy).copyForRead(serial, loader); } @Test public void given_copy_on_read_and_write_when_copyElementForReadIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForReadIfNeeded(null), nullValue()); }
### Question: CopyStrategyHandler { Element copyElementForWriteIfNeeded(Element element) { if (element == null) { return null; } if (copyOnRead && copyOnWrite) { return copyStrategy.copyForWrite(element, loader); } else if (copyOnWrite) { return copyStrategy.copyForRead(copyStrategy.copyForWrite(element, loader), loader); } else { return element; } } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy, ClassLoader loader); Element copyElementForReadIfNeeded(Element element); }### Answer: @Test public void given_no_copy_when_copyElementForWriteIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null, loader); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), sameInstance(element)); } @Test public void given_no_copy_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null, loader); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); } @Test public void given_copy_on_read_when_copyElementForWriteIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), sameInstance(element)); } @Test public void given_copy_on_read_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); } @Test public void given_copy_on_write_when_copyElementForWriteIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element, loader)).thenReturn(serial); when(copyStrategy.copyForRead(serial, loader)).thenReturn(new Element("key", "value")); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), allOf(not(sameInstance(element)), equalTo(element))); verify(copyStrategy).copyForWrite(element, loader); verify(copyStrategy).copyForRead(serial, loader); } @Test public void given_copy_on_write_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); } @Test public void given_copy_on_read_and_write_when_copyElementForWriteIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element, loader)).thenReturn(new Element("key", new byte[] { })); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(element), is(serial)); verify(copyStrategy).copyForWrite(element, loader); } @Test public void given_copy_on_read_and_write_when_copyElementForWriteIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForWriteIfNeeded(null), nullValue()); }
### Question: CopyStrategyHandler { Element copyElementForRemovalIfNeeded(Element element) { if (element == null) { return null; } if (copyOnRead && copyOnWrite) { return copyStrategy.copyForWrite(element, loader); } else { return element; } } CopyStrategyHandler(boolean copyOnRead, boolean copyOnWrite, ReadWriteCopyStrategy<Element> copyStrategy, ClassLoader loader); Element copyElementForReadIfNeeded(Element element); }### Answer: @Test public void given_no_copy_when_copyElementForRemovalIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null, loader); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), sameInstance(element)); } @Test public void given_no_copy_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, false, null, loader); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); } @Test public void given_copy_on_read_when_copyElementForRemovalIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), sameInstance(element)); } @Test public void given_copy_on_read_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, false, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); } @Test public void given_copy_on_write_when_copyElementForRemovalIfNeeded_with_Element_then_returns_same() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy, loader); Element element = new Element("key", "value"); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), sameInstance(element)); } @Test public void given_copy_on_write_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(false, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); } @Test public void given_copy_on_read_and_write_when_copyElementForRemovalIfNeeded_with_Element_then_returns_different() { Element element = new Element("key", "value"); Element serial = new Element("key", new byte[] { }); when(copyStrategy.copyForWrite(element, loader)).thenReturn(new Element("key", new byte[] { })); CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(element), is(serial)); verify(copyStrategy).copyForWrite(element, loader); } @Test public void given_copy_on_read_and_write_when_copyElementForRemovalIfNeeded_with_null_then_returns_null() { CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(true, true, copyStrategy, loader); assertThat(copyStrategyHandler.copyElementForRemovalIfNeeded(null), nullValue()); }
### Question: ScheduledRefreshCacheExtension implements CacheExtension { @Override public void init() { if (config.getUniqueNamePart() != null) { this.name = "scheduledRefresh_" + underlyingCache.getCacheManager().getName() + "_" + underlyingCache.getName() + "_" + config.getUniqueNamePart(); } else { this.name = "scheduledRefresh_" + underlyingCache.getCacheManager().getName() + "_" + underlyingCache.getName(); } this.groupName = name + "_grp"; try { makeAndStartQuartzScheduler(); try { JobDetail seed = addOverseerJob(); try { scheduleOverseerJob(seed); status = Status.STATUS_ALIVE; } catch (SchedulerException e) { LOG.error("Unable to schedule control job for Scheduled Refresh", e); } } catch (SchedulerException e) { LOG.error("Unable to add Scheduled Refresh control job to Quartz Job Scheduler", e); } } catch (SchedulerException e) { LOG.error("Unable to instantiate Quartz Job Scheduler for Scheduled Refresh", e); } } ScheduledRefreshCacheExtension(ScheduledRefreshConfiguration config, Ehcache cache); @Override void init(); @Override void dispose(); @Override CacheExtension clone(Ehcache cache); @Override Status getStatus(); }### Answer: @Test public void testSimpleCaseProgrammatic() { CacheManager manager = new CacheManager(); manager.removalAll(); manager.addCache(new Cache(new CacheConfiguration().name("test").eternal(true).maxEntriesLocalHeap(5000))); Ehcache cache = manager.getEhcache("test"); cache.registerCacheLoader(stupidCacheLoaderEvens); cache.registerCacheLoader(stupidCacheLoaderOdds); int second = (new GregorianCalendar().get(Calendar.SECOND) + 5) % 60; ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration().batchSize(100).quartzThreadCount (4).cronExpression(second + "/5 * * * * ?").build(); ScheduledRefreshCacheExtension cacheExtension = new ScheduledRefreshCacheExtension(config, cache); cache.registerCacheExtension(cacheExtension); cacheExtension.init(); for (int i = 0; i < 10; i++) { cache.put(new Element(new Integer(i), i + "")); } sleepySeconds(8); for (Object key : cache.getKeys()) { Element val = cache.get(key); int iVal = ((Number) key).intValue(); if ((iVal & 0x01) == 0) { Assert.assertEquals(iVal + 20000, Long.parseLong((String) val.getObjectValue())); } else { Assert.assertEquals(iVal + 10000, Long.parseLong((String) val.getObjectValue())); } } manager.removalAll(); manager.shutdown(); } @Test public void testPolling() { CacheManager manager = new CacheManager(); manager.removalAll(); manager.addCache(new Cache(new CacheConfiguration().name("tt").eternal(true).maxEntriesLocalHeap(5000).overflowToDisk(false))); Ehcache cache = manager.getEhcache("tt"); stupidCacheLoaderEvens.setMsDelay(100); cache.registerCacheLoader(stupidCacheLoaderEvens); cache.registerCacheLoader(stupidCacheLoaderOdds); int second = (new GregorianCalendar().get(Calendar.SECOND) + 5) % 60; ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration().batchSize(2).quartzThreadCount (2).pollTimeMs(100).cronExpression(second + "/1 * * * * ?").build(); ScheduledRefreshCacheExtension cacheExtension = new ScheduledRefreshCacheExtension(config, cache); cache.registerCacheExtension(cacheExtension); cacheExtension.init(); final int ELEMENT_COUNT=50; long[] orig=new long[ELEMENT_COUNT]; for (int i = 0; i < ELEMENT_COUNT; i++) { Element elem = new Element(new Integer(i), i + ""); orig[i]=elem.getCreationTime(); cache.put(elem); } sleepySeconds(20); manager.removalAll(); manager.shutdown(); }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public Element putIfAbsent(Element element) throws NullPointerException { String pKey = generatePortableKeyFor(element.getObjectKey()); ElementData value = valueModeHandler.createElementData(element); Serializable data = backend.putIfAbsent(pKey, value); return data == null ? null : this.valueModeHandler.createElement(element.getKey(), data); } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override void quickClear(); @Override @Statistic(name = "size", tags = "remote") int quickSize(); @Override int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Set<Attribute> getSearchAttributes(); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); @Override WriteBehind createWriteBehind(); @Override synchronized void notifyCacheEventListenersChanged(); }### Answer: @Test public void clusteredStore_putIfAbsent_enabled_in_eventual_consistency() { clusteredStore.putIfAbsent(new Element("key", "value")); verify(toolkitCacheInternal).putIfAbsent(eq("key"), any(NonEternalElementData.class)); }
### 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: MemoryLimitedCacheLoader implements BootstrapCacheLoader, Cloneable { protected boolean isInMemoryLimitReached(final Ehcache cache, final int loadedElements) { long maxBytesInMem; long maxElementsInMem; final boolean overflowToOffHeap = cache.getCacheConfiguration().isOverflowToOffHeap(); maxElementsInMem = cache.getCacheConfiguration().getMaxEntriesLocalHeap() == 0 ? Integer.MAX_VALUE : cache.getCacheConfiguration().getMaxEntriesLocalHeap(); if (overflowToOffHeap) { maxBytesInMem = cache.getCacheConfiguration().getMaxBytesLocalOffHeap(); } else { maxBytesInMem = cache.getCacheConfiguration().getMaxBytesLocalHeap(); } if (maxBytesInMem != 0) { final long inMemoryCount = overflowToOffHeap ? cache.getStatistics().getLocalOffHeapSize() : cache.getStatistics().getLocalHeapSize(); if (inMemoryCount == 0L) { return false; } else { final long inMemorySizeInBytes = overflowToOffHeap ? cache.getStatistics().getLocalOffHeapSizeInBytes() : cache.getStatistics() .getLocalHeapSizeInBytes(); final long avgSize = inMemorySizeInBytes / inMemoryCount; return inMemorySizeInBytes + (avgSize * 2) >= maxBytesInMem; } } else { return loadedElements >= maxElementsInMem; } } @Override Object clone(); }### Answer: @Test public void testCountBasedLimitSetToNoLimit() { configuration.setOverflowToOffHeap(false); configuration.setMaxEntriesLocalHeap(0); assertThat(loader.isInMemoryLimitReached(cache, 0), is(false)); assertThat(loader.isInMemoryLimitReached(cache, Integer.MAX_VALUE), is(true)); } @Test public void testCountBasedLimitSetToSomeLimit() { configuration.setOverflowToOffHeap(false); int maxEntriesLocalHeap = 10; configuration.setMaxEntriesLocalHeap(maxEntriesLocalHeap); assertThat(loader.isInMemoryLimitReached(cache, maxEntriesLocalHeap - 2), is(false)); assertThat(loader.isInMemoryLimitReached(cache, maxEntriesLocalHeap), is(true)); assertThat(loader.isInMemoryLimitReached(cache, maxEntriesLocalHeap + 2), is(true)); } @Test public void testLocalHeapSizeBased() { configuration.setOverflowToOffHeap(false); configuration.setMaxBytesLocalHeap(1024L); when(statisticsGateway.getLocalHeapSize()).thenReturn(0L, 1L, 4L); when(statisticsGateway.getLocalHeapSizeInBytes()).thenReturn(250L, 1000L); assertThat(loader.isInMemoryLimitReached(cache, 0), is(false)); assertThat(loader.isInMemoryLimitReached(cache, 1), is(false)); assertThat(loader.isInMemoryLimitReached(cache, 4), is(true)); } @Test public void testOffHeapSizeBased() { configuration.setOverflowToOffHeap(true); configuration.setMaxBytesLocalHeap(1024L); configuration.setMaxBytesLocalOffHeap(2048L); when(statisticsGateway.getLocalOffHeapSize()).thenReturn(0L, 1L, 4L); when(statisticsGateway.getLocalOffHeapSizeInBytes()).thenReturn(500L, 2000L); assertThat(loader.isInMemoryLimitReached(cache, 0), is(false)); assertThat(loader.isInMemoryLimitReached(cache, 1), is(false)); assertThat(loader.isInMemoryLimitReached(cache, 4), is(true)); } @Test public void testPooledOffHeapSizeBased() { configuration.setOverflowToOffHeap(true); assertThat(loader.isInMemoryLimitReached(cache, 0), is(false)); assertThat(loader.isInMemoryLimitReached(cache, Integer.MAX_VALUE), is(true)); } @Test public void testPooledHeapSizeBased() { assertThat(loader.isInMemoryLimitReached(cache, 0), is(false)); assertThat(loader.isInMemoryLimitReached(cache, Integer.MAX_VALUE), is(true)); }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public Element putIfAbsent(Element element) throws NullPointerException { if (isEventual && !EVENTUAL_CAS_ENABLED) { throw new UnsupportedOperationException("CAS operations are not supported in eventual consistency mode, consider using a StronglyConsistentCacheAccessor"); } String pKey = generatePortableKeyFor(element.getObjectKey()); ElementData value = valueModeHandler.createElementData(element); Serializable data = backend.putIfAbsent(pKey, value); return data == null ? null : this.valueModeHandler.createElement(element.getKey(), data); } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override void quickClear(); @Override @Statistic(name = "size", tags = "remote") int quickSize(); @Override int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Set<Attribute> getSearchAttributes(); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); boolean isThisNodeLeader(); @Override WriteBehind createWriteBehind(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void clusteredStore_putIfAbsent_throw_in_eventual_consistency() { clusteredStore.putIfAbsent(new Element("key", "value")); }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException, IllegalArgumentException { if (isEventual && !EVENTUAL_CAS_ENABLED) { throw new UnsupportedOperationException("CAS operations are not supported in eventual consistency mode, consider using a StronglyConsistentCacheAccessor"); } String pKey = generatePortableKeyFor(element.getKey()); ToolkitReadWriteLock lock = backend.createLockForKey(pKey); lock.writeLock().lock(); try { Element oldElement = getQuiet(element.getKey()); if (comparator.equals(oldElement, old)) { return putInternal(element); } } finally { lock.writeLock().unlock(); } return false; } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override void quickClear(); @Override @Statistic(name = "size", tags = "remote") int quickSize(); @Override int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Set<Attribute> getSearchAttributes(); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); boolean isThisNodeLeader(); @Override WriteBehind createWriteBehind(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void clusteredStore_replace_1_arg_throw_in_eventual_consistency() { clusteredStore.replace(new Element("key", "value")); } @Test(expected = UnsupportedOperationException.class) public void clusteredStore_replace_2_args_throw_in_eventual_consistency() { clusteredStore.replace(new Element("key", "value"), new Element("key", "other"), new DefaultElementValueComparator(cacheConfiguration)); }
### Question: ClusteredStore implements TerracottaStore, StoreListener { @Override public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException { if (isEventual && !EVENTUAL_CAS_ENABLED) { throw new UnsupportedOperationException("CAS operations are not supported in eventual consistency mode, consider using a StronglyConsistentCacheAccessor"); } String pKey = generatePortableKeyFor(element.getKey()); ToolkitReadWriteLock lock = backend.createLockForKey(pKey); lock.writeLock().lock(); try { Element oldElement = getQuiet(element.getKey()); if (comparator.equals(oldElement, element)) { return remove(element.getKey()); } } finally { lock.writeLock().unlock(); } return null; } ClusteredStore(ToolkitInstanceFactory toolkitInstanceFactory, Ehcache cache, CacheCluster topology); String getFullyQualifiedCacheName(); @Override void recalculateSize(Object key); @Override synchronized void addStoreListener(StoreListener listener); @Override synchronized void removeStoreListener(StoreListener listener); @Override void clusterCoherent(final boolean clusterCoherent); @Override boolean put(Element element); @Override boolean putWithWriter(Element element, CacheWriterManager writerManager); @Override void putAll(Collection<Element> elements); @Override Element get(Object key); @Override Element getQuiet(Object key); @Override List getKeys(); @Override Element remove(Object key); @Override void removeAll(Collection<?> keys); @Override Element removeWithWriter(Object key, CacheWriterManager writerManager); @Override void removeAll(); @Override Element putIfAbsent(Element element); @Override Element removeElement(Element element, ElementValueComparator comparator); @Override boolean replace(Element old, Element element, ElementValueComparator comparator); @Override Element replace(Element element); @Override void dispose(); @Override int getSize(); @Override @Statistic(name = "size", tags = "local-heap") int getInMemorySize(); @Override @Statistic(name = "size", tags = "local-offheap") int getOffHeapSize(); @Override int getOnDiskSize(); @Override void quickClear(); @Override @Statistic(name = "size", tags = "remote") int quickSize(); @Override int getTerracottaClusteredSize(); @Override @Statistic(name = "size-in-bytes", tags = "local-heap") long getInMemorySizeInBytes(); @Override @Statistic(name = "size-in-bytes", tags = "local-offheap") long getOffHeapSizeInBytes(); @Override long getOnDiskSizeInBytes(); @Override boolean hasAbortedSizeOf(); @Override Status getStatus(); @Override boolean containsKey(Object key); @Override boolean containsKeyOnDisk(Object key); @Override boolean containsKeyOffHeap(Object key); @Override boolean containsKeyInMemory(Object key); @Override void expireElements(); @Override void flush(); @Override boolean bufferFull(); @Override Policy getInMemoryEvictionPolicy(); @Override void setInMemoryEvictionPolicy(Policy policy); @Override Object getInternalContext(); @Override boolean isCacheCoherent(); @Override boolean isClusterCoherent(); @Override boolean isNodeCoherent(); @Override void setNodeCoherent(boolean coherent); @Override void waitUntilClusterCoherent(); @Override Object getMBean(); @Override void setAttributeExtractors(Map<String, AttributeExtractor> extractors); @Override Results executeQuery(StoreQuery query); @Override Set<Attribute> getSearchAttributes(); @Override Attribute<T> getSearchAttribute(String attributeName); @Override Map<Object, Element> getAllQuiet(Collection<?> keys); @Override Map<Object, Element> getAll(Collection<?> keys); String generatePortableKeyFor(final Object obj); @Override Element unsafeGet(Object key); @Override Set getLocalKeys(); @Override TransactionalMode getTransactionalMode(); boolean isSearchable(); String getLeader(); boolean isThisNodeLeader(); @Override WriteBehind createWriteBehind(); }### Answer: @Test(expected = UnsupportedOperationException.class) public void clusteredStore_removeElement_throw_in_eventual_consistency() { clusteredStore.removeElement(new Element("key", "value"), new DefaultElementValueComparator(cacheConfiguration)); }
### Question: ToolkitInstanceFactoryImpl implements ToolkitInstanceFactory { void addCacheEntityInfo(final String cacheName, final CacheConfiguration ehcacheConfig, String toolkitCacheName) { if (clusteredCacheManagerEntity == null) { throw new IllegalStateException(format("ClusteredCacheManger entity not configured for cache %s", cacheName)); } ClusteredCache cacheEntity = clusteredCacheManagerEntity.getCache(cacheName); if (cacheEntity == null) { ToolkitReadWriteLock cacheRWLock = clusteredCacheManagerEntity.getCacheLock(cacheName); ToolkitLock cacheWriteLock = cacheRWLock.writeLock(); while (cacheEntity == null) { if (cacheWriteLock.tryLock()) { try { cacheEntity = createClusteredCacheEntity(cacheName, ehcacheConfig, toolkitCacheName); } finally { cacheWriteLock.unlock(); } } else { cacheEntity = clusteredCacheManagerEntity.getCache(cacheName); } } } clusteredCacheManagerEntity.markCacheInUse(cacheEntity); } ToolkitInstanceFactoryImpl(TerracottaClientConfiguration terracottaClientConfiguration); ToolkitInstanceFactoryImpl(Toolkit toolkit, ClusteredEntityManager clusteredEntityManager); @Override void waitForOrchestrator(String cacheManagerName); @Override void markCacheWanDisabled(String cacheManagerName, String cacheName); @Override Toolkit getToolkit(); @Override ToolkitCacheInternal<String, Serializable> getOrCreateToolkitCache(final Ehcache cache); @Override ToolkitCacheInternal<String, Serializable> getOrCreateWanAwareToolkitCache(final String cacheManagerName, final String cacheName, final CacheConfiguration ehcacheConfig); @Override ToolkitNotifier<CacheConfigChangeNotificationMsg> getOrCreateConfigChangeNotifier(Ehcache cache); @Override ToolkitNotifier<CacheEventNotificationMsg> getOrCreateCacheEventNotifier(Ehcache cache); @Override ToolkitNotifier<CacheDisposalNotification> getOrCreateCacheDisposalNotifier(Ehcache cache); @Override String getFullyQualifiedCacheName(Ehcache cache); @Override ToolkitLock getOrCreateStoreLock(Ehcache cache); @Override ToolkitMap<String, AttributeExtractor> getOrCreateExtractorsMap(Ehcache cache); @Override ToolkitMap<String, String> getOrCreateAttributeMap(Ehcache cache); @Override void shutdown(); @Override SerializedToolkitCache<ClusteredSoftLockIDKey, SerializedReadCommittedClusteredSoftLock> getOrCreateAllSoftLockMap(String cacheManagerName, String cacheName); @Override ToolkitMap<SerializedReadCommittedClusteredSoftLock, Integer> getOrCreateNewSoftLocksSet(String cacheManagerName, String cacheName); @Override ToolkitMap<String, AsyncConfig> getOrCreateAsyncConfigMap(); @Override ToolkitMap<String, Set<String>> getOrCreateAsyncListNamesMap(String fullAsyncName); @Override ToolkitMap<String, Serializable> getOrCreateClusteredStoreConfigMap(String cacheManagerName, String cacheName); @Override SerializedToolkitCache<TransactionID, Decision> getOrCreateTransactionCommitStateMap(String cacheManagerName); @Override ToolkitLock getSoftLockWriteLock(String cacheManagerName, String cacheName, TransactionID transactionID, Object key); @Override ToolkitLock getLockForCache(Ehcache cache, String lockName); @Override ToolkitReadWriteLock getSoftLockFreezeLock(String cacheManagerName, String cacheName, TransactionID transactionID, Object key); @Override ToolkitReadWriteLock getSoftLockNotifierLock(String cacheManagerName, String cacheName, TransactionID transactionID, Object key); @Override boolean destroy(final String cacheManagerName, final String cacheName); @Override void removeNonStopConfigforCache(Ehcache cache); @Override void linkClusteredCacheManager(String cacheManagerName, net.sf.ehcache.config.Configuration configuration); @Override void unlinkCache(String cacheName); static final String DELIMITER; }### Answer: @Test public void testAddCacheEntityInfo() { factory.addCacheEntityInfo(CACHE_NAME, new CacheConfiguration(), "testTKCacheName"); }
### 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: CachesResource { @GET public Caches getCaches() { LOG.info("GET Caches"); String[] cacheNames = MANAGER.getCacheNames(); List<Cache> cacheList = new ArrayList<Cache>(); for (String cacheName : cacheNames) { Ehcache ehcache = MANAGER.getCache(cacheName); URI cacheUri = uriInfo.getAbsolutePathBuilder().path(cacheName).build().normalize(); Cache cache = new Cache(cacheName, cacheUri.toString(), ehcache.toString(), new Statistics(ehcache.getStatistics()), ehcache.getCacheConfiguration()); cacheList.add(cache); } return new Caches(cacheList); } @Path("{cache}") CacheResource getCacheResource(@PathParam("cache") String cache); @GET Caches getCaches(); }### Answer: @Test public void testCacheNames() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Caches caches = (Caches) unmarshaller.unmarshal(result.getInputStream()); List<net.sf.ehcache.server.jaxb.Cache> cacheList = caches.getCaches(); for (net.sf.ehcache.server.jaxb.Cache cache : cacheList) { assertNotNull(cache.getName()); } } @Test public void testGetCaches() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.parse(result.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); String cacheCount = xpath.evaluate("count( assertTrue(Integer.parseInt(cacheCount) >= 6); } @Test public void testGetCachesJaxb() throws Exception { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Caches caches = (Caches) unmarshaller.unmarshal(result.getInputStream()); assertTrue(caches.getCaches().size() >= 6); } @Test public void testCacheNames() throws Exception, IOException, ParserConfigurationException, SAXException { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Caches caches = (Caches) unmarshaller.unmarshal(result.getInputStream()); List<net.sf.ehcache.server.jaxb.Cache> cacheList = caches.getCaches(); for (net.sf.ehcache.server.jaxb.Cache cache : cacheList) { assertNotNull(cache.getName()); } } @Test public void testGetCaches() throws IOException, ParserConfigurationException, SAXException, XPathExpressionException { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.parse(result.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); String cacheCount = xpath.evaluate("count( assertTrue(Integer.parseInt(cacheCount) >= 6); } @Test public void testGetCachesJaxb() throws Exception, SAXException, XPathExpressionException, JAXBException { HttpURLConnection result = HttpUtil.get("http: assertEquals(200, result.getResponseCode()); JAXBContext jaxbContext = new JAXBContextResolver().getContext(Caches.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Caches caches = (Caches) unmarshaller.unmarshal(result.getInputStream()); assertTrue(caches.getCaches().size() >= 6); }
### Question: ExplicitLockingCache implements Ehcache { public boolean putIfAbsent(Element element) { try { acquireWriteLockOnKey(element.getKey()); if (!isKeyInCache(element.getKey())) { this.put(element); return true; } return false; } finally { releaseWriteLockOnKey(element.getKey()); } } ExplicitLockingCache(Ehcache cache); String getName(); void setName(String name); boolean isExpired(Element element); @Override Object clone(); RegisteredEventListeners getCacheEventNotificationService(); boolean isElementInMemory(Serializable key); boolean isElementInMemory(Object key); boolean isElementOnDisk(Serializable key); boolean isElementOnDisk(Object key); String getGuid(); CacheManager getCacheManager(); void clearStatistics(); int getStatisticsAccuracy(); void setStatisticsAccuracy(int statisticsAccuracy); void evictExpiredElements(); boolean isKeyInCache(Object key); boolean isValueInCache(Object value); Statistics getStatistics(); LiveCacheStatistics getLiveCacheStatistics(); void setCacheManager(CacheManager cacheManager); BootstrapCacheLoader getBootstrapCacheLoader(); void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader); void setDiskStorePath(String diskStorePath); void initialise(); void bootstrap(); void dispose(); CacheConfiguration getCacheConfiguration(); Element get(final Object key); void put(Element element); void put(Element element, boolean doNotNotifyCacheReplicators); void putQuiet(Element element); Element get(Serializable key); Element getQuiet(Serializable key); Element getQuiet(Object key); List getKeys(); List getKeysWithExpiryCheck(); List getKeysNoDuplicateCheck(); boolean remove(Serializable key); boolean remove(Object key); boolean remove(Serializable key, boolean doNotNotifyCacheReplicators); boolean remove(Object key, boolean doNotNotifyCacheReplicators); boolean removeQuiet(Serializable key); boolean removeQuiet(Object key); void removeAll(); void removeAll(boolean doNotNotifyCacheReplicators); void flush(); int getSize(); int getSizeBasedOnAccuracy(int statisticsAccuracy); long calculateInMemorySize(); long getMemoryStoreSize(); int getDiskStoreSize(); Status getStatus(); synchronized String liveness(); void registerCacheExtension(CacheExtension cacheExtension); void unregisterCacheExtension(CacheExtension cacheExtension); List<CacheExtension> getRegisteredCacheExtensions(); float getAverageGetTime(); void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler); CacheExceptionHandler getCacheExceptionHandler(); void registerCacheLoader(CacheLoader cacheLoader); void unregisterCacheLoader(CacheLoader cacheLoader); List<CacheLoader> getRegisteredCacheLoaders(); Element getWithLoader(Object key, CacheLoader loader, Object loaderArgument); Map getAllWithLoader(Collection keys, Object loaderArgument); void load(Object key); void loadAll(Collection keys, Object argument); boolean isDisabled(); void setDisabled(boolean disabled); void registerCacheUsageListener(CacheUsageListener cacheUsageListener); void removeCacheUsageListener(CacheUsageListener cacheUsageListener); boolean isStatisticsEnabled(); void setStatisticsEnabled(boolean enabledStatistics); SampledCacheStatistics getSampledCacheStatistics(); void setSampledStatisticsEnabled(boolean enabledStatistics); boolean isSampledStatisticsEnabled(); Object getInternalContext(); void acquireReadLockOnKey(Object key); void acquireWriteLockOnKey(Object key); void releaseReadLockOnKey(Object key); void releaseWriteLockOnKey(Object key); boolean tryReadLockOnKey(Object key, long timeout); boolean tryWriteLockOnKey(Object key, long timeout); boolean putIfAbsent(Element element); }### Answer: @Test public void testPutIfAbsent() { }
### Question: CacheWriterConfiguration implements Cloneable { public CacheWriterConfiguration writeMode(String writeMode) { setWriteMode(writeMode); return this; } @Override CacheWriterConfiguration clone(); void setWriteMode(String writeMode); CacheWriterConfiguration writeMode(String writeMode); CacheWriterConfiguration writeMode(WriteMode writeMode); WriteMode getWriteMode(); void setNotifyListenersOnException(boolean notifyListenersOnException); CacheWriterConfiguration notifyListenersOnException(boolean notifyListenersOnException); boolean getNotifyListenersOnException(); void setMinWriteDelay(int minWriteDelay); CacheWriterConfiguration minWriteDelay(int minWriteDelay); int getMinWriteDelay(); void setMaxWriteDelay(int maxWriteDelay); CacheWriterConfiguration maxWriteDelay(int maxWriteDelay); int getMaxWriteDelay(); void setRateLimitPerSecond(int rateLimitPerSecond); CacheWriterConfiguration rateLimitPerSecond(int rateLimitPerSecond); int getRateLimitPerSecond(); void setWriteCoalescing(boolean writeCoalescing); CacheWriterConfiguration writeCoalescing(boolean writeCoalescing); boolean getWriteCoalescing(); void setWriteBatching(boolean writeBatching); CacheWriterConfiguration writeBatching(boolean writeBatching); boolean getWriteBatching(); void setWriteBatchSize(int writeBatchSize); CacheWriterConfiguration writeBatchSize(int writeBatchSize); int getWriteBatchSize(); void setRetryAttempts(int retryAttempts); CacheWriterConfiguration retryAttempts(int retryAttempts); int getRetryAttempts(); void setRetryAttemptDelaySeconds(int retryAttemptDelaySeconds); CacheWriterConfiguration retryAttemptDelaySeconds(int retryAttemptDelaySeconds); int getRetryAttemptDelaySeconds(); final void addCacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactoryConfiguration); CacheWriterConfiguration cacheWriterFactory(CacheWriterFactoryConfiguration cacheWriterFactory); CacheWriterFactoryConfiguration getCacheWriterFactoryConfiguration(); void setWriteBehindConcurrency(int concurrency); CacheWriterConfiguration writeBehindConcurrency(int concurrency); int getWriteBehindConcurrency(); @Override int hashCode(); @Override boolean equals(Object obj); static final WriteMode DEFAULT_WRITE_MODE; static final boolean DEFAULT_NOTIFY_LISTENERS_ON_EXCEPTION; static final int DEFAULT_MIN_WRITE_DELAY; static final int DEFAULT_MAX_WRITE_DELAY; static final int DEFAULT_RATE_LIMIT_PER_SECOND; static final boolean DEFAULT_WRITE_COALESCING; static final boolean DEFAULT_WRITE_BATCHING; static final int DEFAULT_WRITE_BATCH_SIZE; static final int DEFAULT_RETRY_ATTEMPTS; static final int DEFAULT_RETRY_ATTEMPT_DELAY_SECONDS; static final int DEFAULT_WRITE_BEHIND_CONCURRENCY; }### Answer: @Test(expected = IllegalArgumentException.class) public void testNullWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode((CacheWriterConfiguration.WriteMode) null); } @Test(expected = IllegalArgumentException.class) public void testInvalidWriteMode() { CacheWriterConfiguration config = new CacheWriterConfiguration() .writeMode("invalid"); }
### Question: CacheManager { public void shutdown() { synchronized (CacheManager.class) { if (status.equals(Status.STATUS_SHUTDOWN)) { LOG.debug("CacheManager already shutdown"); return; } for (CacheManagerPeerProvider cacheManagerPeerProvider : cacheManagerPeerProviders.values()) { if (cacheManagerPeerProvider != null) { cacheManagerPeerProvider.dispose(); } } if (cacheManagerTimer != null) { cacheManagerTimer.cancel(); cacheManagerTimer.purge(); } cacheManagerEventListenerRegistry.dispose(); synchronized (CacheManager.class) { ALL_CACHE_MANAGERS.remove(this); for (Ehcache cache : ehcaches.values()) { if (cache != null) { cache.dispose(); } } if (defaultCache != null) { defaultCache.dispose(); } status = Status.STATUS_SHUTDOWN; XARequestProcessor.shutdown(); if (this == singleton) { singleton = null; } terracottaClient.shutdown(); removeShutdownHook(); CacheManagerExecutorServiceFactory.getInstance().shutdown(this); } } } CacheManager(Configuration configuration); CacheManager(String configurationFileName); CacheManager(URL configurationURL); CacheManager(InputStream configurationInputStream); CacheManager(); String getClusterUUID(); Store createTerracottaStore(Ehcache cache); WriteBehind createTerracottaWriteBehind(Ehcache cache); CacheEventListener createTerracottaEventReplicator(Ehcache cache); static CacheManager create(); static CacheManager getInstance(); static CacheManager create(String configurationFileName); static CacheManager create(URL configurationFileURL); static CacheManager create(InputStream inputStream); static CacheManager create(Configuration config); Cache getCache(String name); Ehcache getEhcache(String name); void addCache(String cacheName); void addCache(Cache cache); void addCache(Ehcache cache); void addDecoratedCache(Ehcache decoratedCache); void addDecoratedCacheIfAbsent(Ehcache decoratedCache); 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); Map<String, CacheManagerPeerProvider> getCacheManagerPeerProviders(); 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(); CacheCluster getCluster(ClusterScheme scheme); String getOriginalConfigurationText(); String getActiveConfigurationText(); String getOriginalConfigurationText(String cacheName); String getActiveConfigurationText(String cacheName); @Override int hashCode(); Ehcache addCacheIfAbsent(final Ehcache cache); Ehcache addCacheIfAbsent(final String cacheName); TransactionController getTransactionController(); static final String DEFAULT_NAME; static final List<CacheManager> ALL_CACHE_MANAGERS; static final String ENABLE_SHUTDOWN_HOOK_PROPERTY; }### Answer: @Test public void testForCacheManagerThreadLeak() throws CacheException, InterruptedException { int startingThreadCount = countThreads(); URL secondCacheConfiguration = this.getClass().getResource( "/ehcache-2.xml"); for (int i = 0; i < 100; i++) { instanceManager = new CacheManager(secondCacheConfiguration); instanceManager.shutdown(); } int endingThreadCount; int tries = 0; do { Thread.sleep(500); endingThreadCount = countThreads(); } while (tries++ < 5 || endingThreadCount >= startingThreadCount + 2); assertTrue(endingThreadCount < startingThreadCount + 2); } @Test public void testMultipleCacheManagers() { CacheManager[] managers = new CacheManager[2]; managers[0] = new CacheManager(makeCacheManagerConfig()); managers[1] = new CacheManager(makeCacheManagerConfig()); managers[0].shutdown(); managers[1].shutdown(); }
### 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"); }