SGF-408 - Provide support in the SDG XML namespace to load a pre-defined data set using GemFire Snapshot Service for development and testing purposes.

Refactored the ServiceSnapshotFactoryBean class to handle ZIP and JAR files as input sources on GemFire Cache data imports.
Added additional unit tests for SnapshotServiceFactoryBean to improve coverage along with a basic integration test covering import and export.
Fixed bugs in the SnapshotServiceParser and the XSD.
Moved the iterable(:Enumeration) and iterable(:Iterator) methods from the test CollectionUtils class to the 'official' CollectionUtils class.
(cherry picked from commit b47884c88c52b612aff6b8aa01fc0994ac42095c)

Signed-off-by: John Blum <jblum@pivotal.io>
This commit is contained in:
John Blum
2015-08-24 22:45:44 -07:00
parent f3d1617dde
commit e78169eda2
12 changed files with 845 additions and 144 deletions

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2010-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire;
/**
* The SnapshotServiceFactoryBeanIntegrationTest class...
*
* @author John Blum
* @see org.springframework.data.gemfire.
* @since 1.7.0
*/
public class SnapshotServiceFactoryBeanIntegrationTest {
}

View File

@@ -25,6 +25,7 @@ import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
@@ -34,21 +35,26 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.data.gemfire.SnapshotServiceFactoryBean.ArchiveFileFilter;
import static org.springframework.data.gemfire.SnapshotServiceFactoryBean.CacheSnapshotServiceAdapter;
import static org.springframework.data.gemfire.SnapshotServiceFactoryBean.RegionSnapshotServiceAdapter;
import static org.springframework.data.gemfire.SnapshotServiceFactoryBean.SnapshotMetadata;
import static org.springframework.data.gemfire.SnapshotServiceFactoryBean.SnapshotServiceAdapter;
import static org.springframework.data.gemfire.SnapshotServiceFactoryBean.SnapshotServiceAdapterSupport;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.logging.Log;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Matchers;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.gemfire.test.support.FileSystemUtils;
import com.gemstone.gemfire.cache.Cache;
@@ -140,7 +146,8 @@ public class SnapshotServiceFactoryBeanTest {
@Test
public void nullSafeIsDirectoryWithNonDirectories() {
assertThat(SnapshotServiceFactoryBean.nullSafeIsDirectory(new File("path/to/non-existing/directory")), is(false));
assertThat(SnapshotServiceFactoryBean.nullSafeIsDirectory(new File("path/to/non-existing/directory")),
is(false));
assertThat(SnapshotServiceFactoryBean.nullSafeIsDirectory(FileSystemUtils.JAVA_EXE), is(false));
}
@@ -246,6 +253,27 @@ public class SnapshotServiceFactoryBeanTest {
assertThat(factoryBean.isSingleton(), is(true));
}
@Test
public void afterPropertiesSetCreatesSnapshotServiceAdapterAndDoesImportWithConfiguredImports() throws Exception {
final SnapshotServiceAdapter mockSnapshotService = mock(SnapshotServiceAdapter.class,
"MockSnapshotServiceAdapter");
SnapshotServiceFactoryBean factoryBean = new SnapshotServiceFactoryBean() {
@Override protected SnapshotServiceAdapter create() {
return mockSnapshotService;
}
};
SnapshotMetadata expectedSnapshotMetadata = newSnapshotMetadata();
factoryBean.setImports(toArray(expectedSnapshotMetadata));
factoryBean.afterPropertiesSet();
assertThat(factoryBean.getImports()[0], is(equalTo(expectedSnapshotMetadata)));
verify(mockSnapshotService, times(1)).doImport(eq(toArray(expectedSnapshotMetadata)));
}
@Test
public void createCacheSnapshotService() {
Cache mockCache = mock(Cache.class, "MockCache");
@@ -282,49 +310,6 @@ public class SnapshotServiceFactoryBeanTest {
verify(mockRegion, times(1)).getSnapshotService();
}
@Test
public void createSnapshotMetadataWithNullLocation() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("The File location (null) must exist");
new SnapshotMetadata(null, mock(SnapshotFilter.class), SnapshotFormat.GEMFIRE);
}
@Test
public void createSnapshotMetadataWithNonExistingLocation() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("The File location (/path/to/non-existing/location) must exist");
new SnapshotMetadata(new File("/path/to/non-existing/location"), mock(SnapshotFilter.class),
SnapshotFormat.GEMFIRE);
}
@Test
public void createSnapshotMetadataWithDirectoryFilterAndUnspecifiedFormat() {
SnapshotFilter mockSnapshotFilter = mock(SnapshotFilter.class, "MockSnapshotFilter");
SnapshotMetadata metadata = new SnapshotMetadata(FileSystemUtils.WORKING_DIRECTORY, mockSnapshotFilter, null);
assertThat(metadata.getLocation(), is(equalTo(FileSystemUtils.WORKING_DIRECTORY)));
assertThat(metadata.isDirectory(), is(true));
assertThat(metadata.isFile(), is(false));
assertThat(metadata.getFilter(), is(equalTo(mockSnapshotFilter)));
assertThat(metadata.isFilterPresent(), is(true));
assertThat(metadata.getFormat(), is(equalTo(SnapshotFormat.GEMFIRE)));
}
@Test
public void createSnapshotMetadataWithFileNullFilterAndGemFireFormat() throws Exception {
SnapshotMetadata metadata = new SnapshotMetadata(snapshotDat, null, SnapshotFormat.GEMFIRE);
assertThat(metadata.getLocation(), is(equalTo(snapshotDat)));
assertThat(metadata.isDirectory(), is(false));
assertThat(metadata.isFile(), is(true));
assertThat(metadata.getFilter(), is(nullValue()));
assertThat(metadata.isFilterPresent(), is(false));
assertThat(metadata.getFormat(), is(equalTo(SnapshotFormat.GEMFIRE)));
}
@Test
public void wrapNullCacheSnapshotService() {
expectedException.expect(IllegalArgumentException.class);
@@ -341,6 +326,27 @@ public class SnapshotServiceFactoryBeanTest {
factoryBean.wrap((RegionSnapshotService) null);
}
@Test
public void destroyPerformsExportWithConfiguredExports() throws Exception {
final SnapshotServiceAdapter mockSnapshotService = mock(SnapshotServiceAdapter.class,
"MockSnapshotServiceAdapter");
SnapshotServiceFactoryBean factoryBean = new SnapshotServiceFactoryBean() {
@Override public SnapshotServiceAdapter getObject() throws Exception {
return mockSnapshotService;
}
};
SnapshotMetadata expectedSnapshotMetadata = newSnapshotMetadata();
factoryBean.setExports(toArray(expectedSnapshotMetadata));
factoryBean.destroy();
assertThat(factoryBean.getExports()[0], is(equalTo(expectedSnapshotMetadata)));
verify(mockSnapshotService, times(1)).doExport(eq(toArray(expectedSnapshotMetadata)));
}
@Test
public void onApplicationEventWhenMatchUsingEventSnapshotMetadataPerformsExport() throws Exception {
Region mockRegion = mock(Region.class, "MockRegion");
@@ -399,7 +405,8 @@ public class SnapshotServiceFactoryBeanTest {
verify(mockSnapshotService, never()).createOptions();
verify(mockSnapshotService, never()).save(any(File.class), any(SnapshotFormat.class));
verify(mockSnapshotService, never()).save(any(File.class), any(SnapshotFormat.class), any(SnapshotOptions.class));
verify(mockSnapshotService, never()).save(any(File.class), any(SnapshotFormat.class),
any(SnapshotOptions.class));
}
@Test
@@ -517,7 +524,8 @@ public class SnapshotServiceFactoryBeanTest {
verify(mockCacheSnapshotService, times(2)).createOptions();
verify(mockCacheSnapshotService, times(1)).load(eq(FileSystemUtils.safeListFiles(FileSystemUtils.USER_HOME, FileSystemUtils.FileOnlyFilter.INSTANCE)),
eq(SnapshotFormat.GEMFIRE), eq(mockSnapshotOptionsOne));
verify(mockCacheSnapshotService, times(1)).load(eq(FileSystemUtils.safeListFiles(FileSystemUtils.WORKING_DIRECTORY, FileSystemUtils.FileOnlyFilter.INSTANCE)),
verify(mockCacheSnapshotService, times(1)).load(eq(FileSystemUtils.safeListFiles(
FileSystemUtils.WORKING_DIRECTORY, FileSystemUtils.FileOnlyFilter.INSTANCE)),
eq(SnapshotFormat.GEMFIRE), eq(mockSnapshotOptionsTwo));
verify(mockSnapshotOptionsOne, times(1)).setFilter(eq(mockSnapshotFilterOne));
verify(mockSnapshotOptionsTwo, times(1)).setFilter(eq(mockSnapshotFilterTwo));
@@ -667,6 +675,97 @@ public class SnapshotServiceFactoryBeanTest {
verify(mockSnapshotOptionsTwo, times(1)).setFilter(eq(mockSnapshotFilterTwo));
}
@Test
public void createOptionsWithFilterOnSnapshotServiceAdapterSupport() {
SnapshotFilter mockSnapshotFilter = mock(SnapshotFilter.class, "MockSnapshotFilter");
final SnapshotOptions mockSnapshotOptions = mock(SnapshotOptions.class, "MockSnapshotOptions");
when(mockSnapshotOptions.setFilter(any(SnapshotFilter.class))).thenReturn(mockSnapshotOptions);
TestSnapshotServiceAdapter snapshotService = new TestSnapshotServiceAdapter() {
@Override public SnapshotOptions<Object, Object> createOptions() {
return mockSnapshotOptions;
}
};
assertThat(snapshotService.createOptions(mockSnapshotFilter), is(equalTo(mockSnapshotOptions)));
verify(mockSnapshotOptions, times(1)).setFilter(eq(mockSnapshotFilter));
}
@Test
public void invokeExceptionSuppressingCloseOnSnapshotServiceAdapterSupportIsSuccessful() throws Exception {
Closeable mockCloseable = mock(Closeable.class, "MockCloseable");
assertThat(new TestSnapshotServiceAdapter().exceptionSuppressingClose(mockCloseable), is(true));
verify(mockCloseable, times(1)).close();
}
@Test
public void invokeExceptionSuppressingCloseOnSnapshotServiceAdapterSupportIsUnsuccessful() throws Exception {
Closeable mockCloseable = mock(Closeable.class, "MockCloseable");
doThrow(new IOException("TEST")).when(mockCloseable).close();
assertThat(new TestSnapshotServiceAdapter().exceptionSuppressingClose(mockCloseable), is(false));
verify(mockCloseable, times(1)).close();
}
@Test
public void logDebugWhenDebugging() {
final Log mockLog = mock(Log.class, "MockLog");
when(mockLog.isDebugEnabled()).thenReturn(true);
TestSnapshotServiceAdapter snapshotService = new TestSnapshotServiceAdapter() {
@Override Log createLog() {
return mockLog;
}
};
Exception expectedException = new Exception("test");
snapshotService.logDebug(expectedException, "Log message with argument (%1$s)", "test");
verify(mockLog, times(1)).isDebugEnabled();
verify(mockLog, times(1)).debug(eq("Log message with argument (test)"), eq(expectedException));
}
@Test
public void logDebugWhenNotDebugging() {
final Log mockLog = mock(Log.class, "MockLog");
when(mockLog.isDebugEnabled()).thenReturn(false);
TestSnapshotServiceAdapter snapshotService = new TestSnapshotServiceAdapter() {
@Override Log createLog() {
return mockLog;
}
};
snapshotService.logDebug(null, "Log message with argument (%1$s)", "test");
verify(mockLog, times(1)).isDebugEnabled();
verify(mockLog, never()).debug(any(String.class), any(Throwable.class));
}
@Test
public void toSimpleFilenameUsingVariousPathnames() {
TestSnapshotServiceAdapter snapshotService = new TestSnapshotServiceAdapter();
assertThat(snapshotService.toSimpleFilename("/path/to/file.ext"), is(equalTo("file.ext")));
assertThat(snapshotService.toSimpleFilename("/path/to/file "), is(equalTo("file")));
assertThat(snapshotService.toSimpleFilename("/ file.ext"), is(equalTo("file.ext")));
assertThat(snapshotService.toSimpleFilename(" file.ext "), is(equalTo("file.ext")));
assertThat(snapshotService.toSimpleFilename("/ "), is(equalTo("")));
assertThat(snapshotService.toSimpleFilename(" "), is(equalTo("")));
assertThat(snapshotService.toSimpleFilename(""), is(equalTo("")));
assertThat(snapshotService.toSimpleFilename(null), is(nullValue()));
}
@Test(expected = ImportSnapshotException.class)
public void loadCacheSnapshotWithDirectoryAndFormatHandlesExceptionAppropriately() throws Exception {
CacheSnapshotService mockCacheSnapshotService = mock(CacheSnapshotService.class, "MockCacheSnapshotService");
@@ -893,4 +992,117 @@ public class SnapshotServiceFactoryBeanTest {
}
}
@Test
public void createSnapshotMetadataWithNullLocation() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectCause(is(nullValue(Throwable.class)));
expectedException.expectMessage("Location must not be null");
new SnapshotMetadata(null, mock(SnapshotFilter.class), SnapshotFormat.GEMFIRE);
}
@Test
public void createSnapshotMetadataWithDirectoryFilterAndUnspecifiedFormat() {
SnapshotFilter mockSnapshotFilter = mock(SnapshotFilter.class, "MockSnapshotFilter");
SnapshotMetadata metadata = new SnapshotMetadata(FileSystemUtils.WORKING_DIRECTORY, mockSnapshotFilter, null);
assertThat(metadata.getLocation(), is(equalTo(FileSystemUtils.WORKING_DIRECTORY)));
assertThat(metadata.isDirectory(), is(true));
assertThat(metadata.isFile(), is(false));
assertThat(metadata.getFilter(), is(equalTo(mockSnapshotFilter)));
assertThat(metadata.isFilterPresent(), is(true));
assertThat(metadata.getFormat(), is(equalTo(SnapshotFormat.GEMFIRE)));
}
@Test
public void createSnapshotMetadataWithFileNullFilterAndGemFireFormat() throws Exception {
SnapshotMetadata metadata = new SnapshotMetadata(snapshotDat, null, SnapshotFormat.GEMFIRE);
assertThat(metadata.getLocation(), is(equalTo(snapshotDat)));
assertThat(metadata.isDirectory(), is(false));
assertThat(metadata.isFile(), is(true));
assertThat(metadata.getFilter(), is(nullValue()));
assertThat(metadata.isFilterPresent(), is(false));
assertThat(metadata.getFormat(), is(equalTo(SnapshotFormat.GEMFIRE)));
}
@Test
public void isJarFileIsTrue() {
// JRE
File runtimeDotJar = new File(new File(FileSystemUtils.JAVA_HOME, "lib"), "rt.jar");
// JDK
if (!runtimeDotJar.isFile()) {
runtimeDotJar = new File(new File(new File(FileSystemUtils.JAVA_HOME, "jre"), "lib"), "rt.jar");
assumeThat(runtimeDotJar.isFile(), is(true));
}
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(runtimeDotJar), is(true));
}
@Test
public void isJarFileIsFalse() throws Exception {
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(new File("/path/to/non-existing/file.jar")), is(false));
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(new ClassPathResource("/cluster_config.zip").getFile()), is(false));
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(new File("to/file.tar")), is(false));
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(new File("jar.file")), is(false));
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(new File(" ")), is(false));
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(new File("")), is(false));
assertThat(ArchiveFileFilter.INSTANCE.isJarFile(null), is(false));
}
@Test
public void getFileExtensionOfVariousFiles() throws Exception {
assertThat(ArchiveFileFilter.INSTANCE.getFileExtension(new ClassPathResource("/cluster_config.zip").getFile()), is(equalTo("zip")));
assertThat(ArchiveFileFilter.INSTANCE.getFileExtension(new File("/path/to/non-existing/file.jar")), is(equalTo("")));
assertThat(ArchiveFileFilter.INSTANCE.getFileExtension(new File("to/non-existing/file.tar")), is(equalTo("")));
assertThat(ArchiveFileFilter.INSTANCE.getFileExtension(FileSystemUtils.WORKING_DIRECTORY), is(equalTo("")));
assertThat(ArchiveFileFilter.INSTANCE.getFileExtension(new File(" ")), is(equalTo("")));
assertThat(ArchiveFileFilter.INSTANCE.getFileExtension(new File("")), is(equalTo("")));
assertThat(ArchiveFileFilter.INSTANCE.getFileExtension(null), is(equalTo("")));
}
@Test
public void archiveFileFilterAcceptsJarOrZipFile() throws Exception {
assertThat(ArchiveFileFilter.INSTANCE.accept(new ClassPathResource("/cluster_config.zip").getFile()), is(true));
}
@Test
public void archiveFileFilterRejectsTarFile() {
assertThat(ArchiveFileFilter.INSTANCE.accept(new File("/path/to/file.tar")), is(false));
}
protected static class TestSnapshotServiceAdapter extends SnapshotServiceAdapterSupport<Object, Object> {
@Override
public SnapshotOptions<Object, Object> createOptions() {
throw new UnsupportedOperationException("not implemented");
}
@Override
protected File[] handleLocation(final SnapshotMetadata<Object, Object> configuration) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void load(final File directory, final SnapshotFormat format) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void load(SnapshotFormat format, SnapshotOptions<Object, Object> options, File... snapshots) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void save(final File location, final SnapshotFormat format) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void save(File location, SnapshotFormat format, SnapshotOptions<Object, Object> options) {
throw new UnsupportedOperationException("not implemented");
}
}
}

View File

@@ -0,0 +1,166 @@
/*
* Copyright 2010-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.gemfire;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.gemfire.repository.sample.Person;
import org.springframework.data.gemfire.test.support.FileSystemUtils;
import org.springframework.data.gemfire.test.support.ThreadUtils;
import org.springframework.util.FileCopyUtils;
import com.gemstone.gemfire.cache.Region;
/**
* The SnapshotServiceImportExportIntegrationTest class is a test suite of test cases testing the import and export
* of GemFire Cache Region data configured with SDG's Data Namespace &gt;gfe-data:snapshot-service&lt; (XML) element.
*
* @author John Blum
* @see org.junit.Test
* @see org.springframework.context.ConfigurableApplicationContext
* @see org.springframework.context.support.ClassPathXmlApplicationContext
* @see org.springframework.data.gemfire.SnapshotServiceFactoryBean
* @see org.springframework.data.gemfire.repository.sample.Person
* @since 1.7.0
*/
@SuppressWarnings("unused")
public class SnapshotServiceImportExportIntegrationTest {
protected static final AtomicLong ID_SEQUENCE = new AtomicLong(0l);
private static ConfigurableApplicationContext applicationContext;
private static File importPeopleSnapshot;
private static Region<Long, Person> people;
protected static void assertPerson(Person expectedPerson, Person actualPerson) {
assertThat(actualPerson, is(notNullValue()));
assertThat(actualPerson.getId(), is(equalTo(expectedPerson.getId())));
assertThat(actualPerson.getFirstname(), is(equalTo(expectedPerson.getFirstname())));
assertThat(actualPerson.getLastname(), is(equalTo(expectedPerson.getLastname())));
}
protected static void assertRegion(Region<?, ?> actualRegion, String expectedName, int expectedSize) {
assertThat(actualRegion, is(notNullValue()));
assertThat(actualRegion.getName(), is(equalTo("People")));
assertThat(actualRegion.getFullPath(), is(equalTo(String.format("%1$s%2$s", Region.SEPARATOR, expectedName))));
assertThat(actualRegion.size(), is(expectedSize));
}
protected static Person createPerson(String firstName, String lastName) {
return createPerson(ID_SEQUENCE.incrementAndGet(), firstName, lastName);
}
protected static Person createPerson(Long id, String firstName, String lastName) {
return new Person(id, firstName, lastName);
}
@BeforeClass
@SuppressWarnings("unchecked")
public static void setupBeforeClass() throws Exception {
File exportDirectory = new File("./gemfire/snapshots/export");
File importDirectory = new File("./gemfire/snapshots/import");
assertThat(exportDirectory.isDirectory() || exportDirectory.mkdirs(), is(true));
assertThat(importDirectory.isDirectory() || importDirectory.mkdirs(), is(true));
importPeopleSnapshot = new File(importDirectory, "people.snapshot");
FileCopyUtils.copy(new ClassPathResource("/people.snapshot").getFile(), importPeopleSnapshot);
assertThat(importPeopleSnapshot.isFile(), is(true));
assertThat(importPeopleSnapshot.length() > 0, is(true));
applicationContext = new ClassPathXmlApplicationContext(
SnapshotServiceImportExportIntegrationTest.class.getName().replaceAll("\\.", File.separator)
.concat("-context.xml"));
applicationContext.registerShutdownHook();
people = applicationContext.getBean("People", Region.class);
}
@AfterClass
public static void tearDownAfterClass() {
applicationContext.close();
File exportPeopleSnapshot = new File("gemfire/snapshots/export/people.snapshot");
assertThat(exportPeopleSnapshot.isFile(), is(true));
assertThat(exportPeopleSnapshot.length(), is(equalTo(importPeopleSnapshot.length())));
FileSystemUtils.deleteRecursive(new File(FileSystemUtils.WORKING_DIRECTORY, "gemfire"));
}
@Before
public void setup() {
//setupPeople();
ThreadUtils.timedWait(TimeUnit.SECONDS.toMillis(5), 500, new ThreadUtils.WaitCondition() {
@Override public boolean waiting() {
return !(people.size() > 0);
}
});
}
protected void setupPeople() {
put(createPerson("Jon", "Doe"));
put(createPerson("Jane", "Doe"));
put(createPerson("Cookie", "Doe"));
put(createPerson("Fro", "Doe"));
put(createPerson("Joe", "Doe"));
put(createPerson("Lan", "Doe"));
put(createPerson("Pie", "Doe"));
put(createPerson("Play", "Doe"));
put(createPerson("Sour", "Doe"));
}
protected Person put(Person person) {
people.putIfAbsent(person.getId(), person);
return person;
}
@Test
public void peopleRegionIsLoaded() {
assertRegion(people, "People", 9);
assertPerson(people.get(1l), createPerson(1l, "Jon", "Doe"));
assertPerson(people.get(2l), createPerson(2l, "Jane", "Doe"));
assertPerson(people.get(3l), createPerson(3l, "Cookie", "Doe"));
assertPerson(people.get(4l), createPerson(4l, "Fro", "Doe"));
assertPerson(people.get(5l), createPerson(5l, "Joe", "Doe"));
assertPerson(people.get(6l), createPerson(6l, "Lan", "Doe"));
assertPerson(people.get(7l), createPerson(7l, "Pie", "Doe"));
assertPerson(people.get(8l), createPerson(8l, "Play", "Doe"));
assertPerson(people.get(9l), createPerson(9l, "Sour", "Doe"));
}
}

View File

@@ -20,19 +20,27 @@ import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.gemfire.mapping.Region;
import com.gemstone.gemfire.management.internal.cli.util.spring.ObjectUtils;
/**
* The Person class models a person.
*
* @author Oliver Gierke
* @author John Blum
* @see java.io.Serializable
*/
@Region("simple")
public class Person implements Serializable {
private static final long serialVersionUID = 508843183613325255L;
public Address address;
@Id
public Long id;
public String firstname;
public String lastname;
public Address address;
public Person(Long id, String firstname, String lastname) {
this.id = id;
@@ -40,6 +48,15 @@ public class Person implements Serializable {
this.lastname = lastname;
}
/**
* Returns the identifier (ID) of this Person.
*
* @return a Long value with the ID of this Person.
*/
public Long getId() {
return id;
}
/**
* @return the firstname
*/
@@ -54,13 +71,23 @@ public class Person implements Serializable {
return lastname;
}
/**
* Returns the Person's full name.
*
* @return the first and last name of the Person.
* @see #getFirstname()
* @see #getLastname()
*/
public String getName() {
return String.format("%1$s %2$s", getFirstname(), getLastname());
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
@@ -71,7 +98,7 @@ public class Person implements Serializable {
Person that = (Person) obj;
return this.id == null ? false : this.id.equals(that.id);
return (this.id != null && this.id.equals(that.id));
}
/*
@@ -80,6 +107,12 @@ public class Person implements Serializable {
*/
@Override
public int hashCode() {
return this.id == null ? 0 : this.id.hashCode();
return ObjectUtils.nullSafeHashCode(this.id);
}
@Override
public String toString() {
return String.format("{ @type = %1$s, id = %2$d, name = %3$s }", getClass().getName(), id, getName());
}
}

View File

@@ -17,8 +17,6 @@
package org.springframework.data.gemfire.test.support;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
/**
@@ -31,25 +29,8 @@ import java.util.List;
* @since 1.5.0
*/
@SuppressWarnings("unused")
// TODO replace with org.springframework.data.gemfire.util.CollectionUtils
public abstract class CollectionUtils extends org.springframework.data.gemfire.util.CollectionUtils {
public static <T> Iterable<T> iterable(final Enumeration<T> enumeration) {
return new Iterable<T>() {
@Override public Iterator<T> iterator() {
return org.springframework.util.CollectionUtils.toIterator(enumeration);
}
};
}
public static <T> Iterable<T> iterable(final Iterator<T> iterator) {
return new Iterable<T>() {
@Override public Iterator<T> iterator() {
return iterator;
}
};
}
public static <T> List<T> subList(final List<T> source, final int... indices) {
List<T> result = new ArrayList<T>(indices.length);
for (int index : indices) {

View File

@@ -19,6 +19,7 @@ package org.springframework.data.gemfire.util;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertNotNull;
@@ -26,8 +27,14 @@ import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
@@ -40,6 +47,7 @@ import org.junit.Test;
*
* @author John Blum
* @see java.util.Collection
* @see java.util.Enumeration
* @see java.util.Iterator
* @see org.junit.Test
* @see org.mockito.Mockito
@@ -48,16 +56,83 @@ import org.junit.Test;
*/
public class CollectionUtilsTest {
@Test
@SuppressWarnings("unchecked")
public void iterableEnumeration() {
Enumeration<String> mockEnumeration = mock(Enumeration.class, "MockEnumeration");
when(mockEnumeration.hasMoreElements()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(mockEnumeration.nextElement()).thenReturn("zero").thenReturn("one").thenReturn("two")
.thenThrow(new NoSuchElementException("Enumeration exhausted"));
Iterable<String> iterable = CollectionUtils.iterable(mockEnumeration);
assertThat(iterable, is(notNullValue()));
List<String> actualList = new ArrayList<String>(3);
for (String element : iterable) {
actualList.add(element);
}
assertThat(actualList, is(equalTo(Arrays.asList("zero", "one", "two"))));
verify(mockEnumeration, times(4)).hasMoreElements();
verify(mockEnumeration, times(3)).nextElement();
}
@Test
@SuppressWarnings("unchecked")
public void iterableIterator() {
Iterator<String> mockIterator = mock(Iterator.class, "MockIterator");
when(mockIterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
when(mockIterator.next()).thenReturn("zero").thenReturn("one").thenReturn("two")
.thenThrow(new NoSuchElementException("Iterator exhausted"));
Iterable<String> iterable = CollectionUtils.iterable(mockIterator);
assertThat(iterable, is(notNullValue()));
List<String> actualList = new ArrayList<String>(3);
for (String element : iterable) {
actualList.add(element);
}
assertThat(actualList, is(equalTo(Arrays.asList("zero", "one", "two"))));
verify(mockIterator, times(4)).hasNext();
verify(mockIterator, times(3)).next();
}
@Test
public void nullSafeCollectionWithNonNullCollection() {
List<?> mockList = mock(List.class);
assertSame(mockList, CollectionUtils.nullSafeCollection(mockList));
}
@Test
public void nullSafeCollectionWithNullCollection() {
Collection collection = CollectionUtils.nullSafeCollection(null);
assertNotNull(collection);
assertTrue(collection.isEmpty());
}
@Test
@SuppressWarnings("unchecked")
public void nullSafeIterableWithNonNullIterable() {
Iterable<Object> mockIterable = mock(Iterable.class);
assertThat(CollectionUtils.nullSafeIterable(mockIterable), is(sameInstance(mockIterable)));
}
@Test
public void nullSafeIterableWithNullIterable() {
Iterable<Object> iterable = CollectionUtils.nullSafeIterable(null);
assertThat(iterable, is(not(nullValue())));
assertThat(iterable.iterator(), is(not(nullValue())));
}
@@ -87,18 +162,4 @@ public class CollectionUtilsTest {
}
}
@Test
public void nullSafeCollectionWithNonNullCollection() {
List<?> mockList = mock(List.class);
assertSame(mockList, CollectionUtils.nullSafeCollection(mockList));
}
@Test
public void nullSafeCollectionWithNullCollection() {
Collection collection = CollectionUtils.nullSafeCollection(null);
assertNotNull(collection);
assertTrue(collection.isEmpty());
}
}