file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
SimpleMailPublisher.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/support/SimpleMailPublisher.java
package io.mvvm.halo.plugins.email.support; import io.mvvm.halo.plugins.email.MailMessage; import io.mvvm.halo.plugins.email.MailPublisher; import io.mvvm.halo.plugins.email.event.SendMailEvent; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; /** * SimpleMailPublisher. * * @author: pan **/ @Slf4j @Component public class SimpleMailPublisher implements MailPublisher { private final Queue<MailMessage> queue = new ConcurrentLinkedQueue<>(); public SimpleMailPublisher(ApplicationEventPublisher publisher) { Timer timer = new Timer("mail-publish-queue", true); timer.schedule(new TimerTask() { @Override public void run() { try { if (null != queue.peek()) { MailMessage message = queue.poll(); publisher.publishEvent(new SendMailEvent(this, message)); } } catch (Exception ignored) { } } }, 3000, 1000); } @Override public void publish(MailMessage message) { queue.add(message); } }
1,346
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
SimpleMailService.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/support/SimpleMailService.java
package io.mvvm.halo.plugins.email.support; import io.mvvm.halo.plugins.email.MailMessage; import io.mvvm.halo.plugins.email.MailSender; import io.mvvm.halo.plugins.email.MailService; import io.mvvm.halo.plugins.email.event.SendMailEvent; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.concurrent.atomic.AtomicReference; /** * SimpleMailService. * * @author: pan **/ @Slf4j @Component public class SimpleMailService implements MailService { private final AtomicReference<MailSender> sender = new AtomicReference<>(); @Override public Boolean connection(MailServerConfig config) { log.debug("连接初始化配置: {}", config); if (null == config) { throw new RuntimeException("暂未初始化配置,请前往插件设置中配置后重试"); } try { MailSender mailSender = sender.updateAndGet(old -> MailSender.createSender(config)); return mailSender.testConnection(); } catch (Exception ex) { log.error("连接初始化失败: {}", ex.getMessage(), ex); throw new RuntimeException("连接初始化失败: " + ex.getMessage()); } } @Override public boolean send(MailMessage message) { if (null == sender.get()) { log.info("邮件发送失败, 请优先测试连接成功后发送."); return false; } if (!StringUtils.hasLength(message.to()) || !StringUtils.hasLength(message.content()) || !StringUtils.hasLength(message.subject())) { log.debug("邮件发送取消, 邮件参数错误."); return false; } return sender.get().send(message); } @EventListener(SendMailEvent.class) public void sendMailEvent(SendMailEvent event) { send(event.getMessage()); } }
1,995
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
MailEnvironmentFetcher.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/support/MailEnvironmentFetcher.java
package io.mvvm.halo.plugins.email.support; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.github.fge.jsonpatch.JsonPatchException; import com.github.fge.jsonpatch.mergepatch.JsonMergePatch; import org.apache.commons.lang3.StringUtils; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; import run.halo.app.extension.ConfigMap; import run.halo.app.extension.ReactiveExtensionClient; import run.halo.app.infra.SystemSetting; import run.halo.app.infra.utils.JsonParseException; import run.halo.app.infra.utils.JsonUtils; import java.util.LinkedHashMap; import java.util.Map; /** * A fetcher that fetches the system configuration from the extension client. * If there are {@link ConfigMap}s named <code>system-default</code> and <code>system</code> at * the same time, the {@link ConfigMap} named system will be json merge patch to * {@link ConfigMap} named <code>system-default</code> * * @author guqing * @since 2.0.0 */ @Component public class MailEnvironmentFetcher { private final ReactiveExtensionClient extensionClient; public MailEnvironmentFetcher(ReactiveExtensionClient extensionClient) { this.extensionClient = extensionClient; } public <T> Mono<T> fetchSystemConfig(String key, Class<T> type) { return fetch(SystemSetting.SYSTEM_CONFIG_DEFAULT, key, type); } public <T> Mono<T> fetch(String name, String key, Class<T> type) { return getValuesInternal(name) .filter(map -> map.containsKey(key)) .map(map -> map.get(key)) .mapNotNull(stringValue -> JsonUtils.jsonToObject(stringValue, type)); } public Mono<SystemSetting.Comment> fetchComment() { return fetchSystemConfig(SystemSetting.Comment.GROUP, SystemSetting.Comment.class) .switchIfEmpty(Mono.just(new SystemSetting.Comment())); } public Mono<SystemSetting.Post> fetchPost() { return fetchSystemConfig(SystemSetting.Post.GROUP, SystemSetting.Post.class) .switchIfEmpty(Mono.just(new SystemSetting.Post())); } public Mono<String> fetchActiveTheme() { return fetchSystemConfig(SystemSetting.Theme.GROUP, SystemSetting.Theme.class) .map(SystemSetting.Theme::getActive); } public Mono<MailServerConfig> fetchMailServer() { return fetch(MailServerConfig.NAME, MailServerConfig.GROUP, MailServerConfig.class) .switchIfEmpty(Mono.empty()); } @NonNull private Mono<Map<String, String>> getValuesInternal(String name) { return getConfigMap(name) .filter(configMap -> configMap.getData() != null) .map(ConfigMap::getData) .defaultIfEmpty(Map.of()); } /** * Gets config map. * * @return a new {@link ConfigMap} named <code>system</code> by json merge patch. */ public Mono<ConfigMap> getConfigMap(String name) { Mono<ConfigMap> mapMono = extensionClient.fetch(ConfigMap.class, name); if (mapMono == null) { return Mono.empty(); } return mapMono.flatMap(systemDefault -> extensionClient.fetch(ConfigMap.class, SystemSetting.SYSTEM_CONFIG) .map(system -> { Map<String, String> defaultData = systemDefault.getData(); Map<String, String> data = system.getData(); Map<String, String> mergedData = mergeData(defaultData, data); system.setData(mergedData); return system; }) .switchIfEmpty(Mono.just(systemDefault))); } private Map<String, String> mergeData(Map<String, String> defaultData, Map<String, String> data) { if (defaultData == null) { return data; } if (data == null) { return defaultData; } Map<String, String> copiedDefault = new LinkedHashMap<>(defaultData); // // merge the data map entries into the default map data.forEach((group, dataValue) -> { // https://www.rfc-editor.org/rfc/rfc7386 String defaultV = copiedDefault.get(group); String newValue; if (dataValue == null) { if (copiedDefault.containsKey(group)) { newValue = null; } else { newValue = defaultV; } } else { newValue = mergeRemappingFunction(dataValue, defaultV); } if (newValue == null) { copiedDefault.remove(group); } else { copiedDefault.put(group, newValue); } }); return copiedDefault; } String mergeRemappingFunction(String dataV, String defaultV) { JsonNode dataJsonValue = nullSafeToJsonNode(dataV); // original JsonNode defaultJsonValue = nullSafeToJsonNode(defaultV); try { // patch JsonMergePatch jsonMergePatch = JsonMergePatch.fromJson(dataJsonValue); // apply patch to original JsonNode patchedNode = jsonMergePatch.apply(defaultJsonValue); return JsonUtils.objectToJson(patchedNode); } catch (JsonPatchException e) { throw new JsonParseException(e); } } JsonNode nullSafeToJsonNode(String json) { return StringUtils.isBlank(json) ? JsonNodeFactory.instance.nullNode() : JsonUtils.jsonToObject(json, JsonNode.class); } }
5,803
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
MailServerConfig.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/support/MailServerConfig.java
package io.mvvm.halo.plugins.email.support; import lombok.Data; /** * MailConfig. * * @author: pan **/ @Data public class MailServerConfig { public static final String NAME = "mail-settings"; public static final String GROUP = "basic"; /** * SMTP server host. For instance, 'smtp.example.com'. */ private String host; /** * SMTP server port. */ private Integer port; /** * Login user of the SMTP server. */ private String username; /** * Login password of the SMTP server. */ private String password; /** * Protocol used by the SMTP server. */ private String protocol = "smtp"; private boolean enable = true; private String adminMail; private String fromName; private boolean enableTls = false; }
827
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
FileUtils.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/utils/FileUtils.java
package io.mvvm.halo.plugins.email.utils; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.ClassPathResource; import org.springframework.util.StreamUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; /** * FileUtils. * * @author: pan **/ @Slf4j public class FileUtils { public static String readFilePathAsString(String path) { try { return Files.readString(Paths.get(path), StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalArgumentException("读取文件内容失败 [ %s ]".formatted(path), e); } } public static String readResourceAsString(ClassPathResource resource) { try (InputStream inputStream = resource.getInputStream()) { return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalArgumentException("读取文件内容失败", e); } } }
1,071
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
TemplateResolver.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/template/TemplateResolver.java
package io.mvvm.halo.plugins.email.template; import io.mvvm.halo.plugins.email.comment.CommentContext; import io.mvvm.halo.plugins.email.template.loader.TemplateLoader; import org.springframework.stereotype.Component; import org.thymeleaf.context.Context; import org.thymeleaf.spring6.ISpringWebFluxTemplateEngine; import org.thymeleaf.spring6.SpringWebFluxTemplateEngine; import reactor.core.publisher.Mono; /** * TemplateResolver. * * @author: pan **/ @Component public class TemplateResolver { private final TemplateLoader loader; private final ISpringWebFluxTemplateEngine engine = new SpringWebFluxTemplateEngine(); public TemplateResolver(TemplateLoader loader) { this.loader = loader; } public Mono<String> process(String path, CommentContext ctx) { return loader.load(path).map(content -> { Context context = new Context(); context.setVariable("ctx", ctx); return engine.process(content, context); }); } }
1,009
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
TemplateLoader.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/template/loader/TemplateLoader.java
package io.mvvm.halo.plugins.email.template.loader; import reactor.core.publisher.Mono; /** * TemplateLoader. * * @author: pan **/ public interface TemplateLoader { Mono<String> load(String path); }
219
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
ClassPathLoader.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/template/loader/ClassPathLoader.java
package io.mvvm.halo.plugins.email.template.loader; import io.mvvm.halo.plugins.email.MailPlugin; import io.mvvm.halo.plugins.email.utils.FileUtils; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; /** * ClassPathLoader. * * @author: pan **/ @Component public class ClassPathLoader implements TemplateLoader { private final ClassLoader loader = MailPlugin.class.getClassLoader(); @Override public Mono<String> load(String path) { return Mono.fromSupplier(() -> { ClassPathResource resource = new ClassPathResource(path, loader); return FileUtils.readResourceAsString(resource); }); } }
740
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
SendMailEvent.java
/FileExtraction/Java_unseen/pannanxu_halo-plugin-email/src/main/java/io/mvvm/halo/plugins/email/event/SendMailEvent.java
package io.mvvm.halo.plugins.email.event; import io.mvvm.halo.plugins.email.MailMessage; import lombok.Getter; import org.springframework.context.ApplicationEvent; /** * SendMailEvent. * * @author: pan **/ public class SendMailEvent extends ApplicationEvent { @Getter private final MailMessage message; public SendMailEvent(Object source, MailMessage message) { super(source); this.message = message; } }
453
Java
.java
pannanxu/halo-plugin-email
17
0
4
2022-10-14T12:23:00Z
2023-03-01T12:22:46Z
ChronoDBTestSuite.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/_suite/ChronoDBTestSuite.java
package org.chronos.chronodb.test._suite; import org.chronos.common.test.junit.ExcludeCategories; import org.chronos.common.test.junit.PackageSuite; import org.chronos.common.test.junit.SuitePackages; import org.chronos.common.test.junit.categories.PerformanceTest; import org.chronos.common.test.junit.categories.SlowTest; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Suite; @Category(Suite.class) @RunWith(PackageSuite.class) @SuitePackages("org.chronos.chronodb.test") @ExcludeCategories({PerformanceTest.class, SlowTest.class}) public class ChronoDBTestSuite { }
634
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DumpUtilsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/dbdump/DumpUtilsTest.java
package org.chronos.chronodb.test.cases.engine.dbdump; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.chronos.chronodb.internal.impl.dump.ChronoDBDumpUtil; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.time.DayOfWeek; import java.util.HashMap; import static org.junit.Assert.*; @Category(UnitTest.class) public class DumpUtilsTest extends ChronoDBUnitTest { @Test public void canRecognizePrimitivesAsWellKnownTypes() { assertTrue(ChronoDBDumpUtil.isWellKnownObject(false)); assertTrue(ChronoDBDumpUtil.isWellKnownObject((byte) 5)); assertTrue(ChronoDBDumpUtil.isWellKnownObject((short) 5)); assertTrue(ChronoDBDumpUtil.isWellKnownObject('a')); assertTrue(ChronoDBDumpUtil.isWellKnownObject(123)); assertTrue(ChronoDBDumpUtil.isWellKnownObject(123L)); assertTrue(ChronoDBDumpUtil.isWellKnownObject(123.4f)); assertTrue(ChronoDBDumpUtil.isWellKnownObject(123.4d)); } @Test public void canRecognizeStringAsWellKnownType() { assertTrue(ChronoDBDumpUtil.isWellKnownObject("Hello World!")); } @Test public void canRecognizeListOfPrimitiveAsWellKnownType() { assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList(true, false))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList((byte) 1, (byte) 2))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList((short) 1, (short) 2))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList('a', 'b'))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList(123, 456))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList(123L, 456L))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList(123.5f, 456.5f))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList(123.5d, 456.5d))); } @Test public void canRecognizeListOfStringsAsWellKnownType() { assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList("Hello", "World!"))); } @Test public void canRecognizeSetOfPrimitiveAsWellKnownType() { assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet(true, false))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet((byte) 1, (byte) 2))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet((short) 1, (short) 2))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet('a', 'b'))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet(123, 456))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet(123L, 456L))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet(123.5f, 456.5f))); assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet(123.5d, 456.5d))); } @Test public void canRecognizeSetOfStringsAsWellKnownType() { assertTrue(ChronoDBDumpUtil.isWellKnownObject(Sets.newHashSet("Hello", "World!"))); } @Test public void canRecognizeMapOfPrimitiveAsWellKnownType() { HashMap<Object, Object> map = Maps.newHashMap(); map.put("Hello", "World"); map.put(123, 456); map.put('a', 'b'); assertTrue(ChronoDBDumpUtil.isWellKnownObject(map)); } @Test public void canRecognizeEnumsAsWellKnownType() { assertTrue(ChronoDBDumpUtil.isWellKnownObject(DayOfWeek.MONDAY)); } @Test public void canRecognizeListOfEnumsAsWellKnownType() { assertTrue(ChronoDBDumpUtil.isWellKnownObject(Lists.newArrayList(DayOfWeek.MONDAY, DayOfWeek.TUESDAY))); } }
3,877
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DBDumpTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/dbdump/DBDumpTest.java
package org.chronos.chronodb.test.cases.engine.dbdump; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.io.FileUtils; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.DumpOption; import org.chronos.chronodb.api.dump.ChronoConverter; import org.chronos.chronodb.api.dump.ChronoDBDumpFormat; import org.chronos.chronodb.api.dump.annotations.ChronosExternalizable; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.internal.util.ChronosFileUtils; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.File; import java.io.IOException; import java.time.DayOfWeek; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class DBDumpTest extends AllChronoDBBackendsTest { // ================================================================================================================= // TEST METHODS // ================================================================================================================= @Test public void canCreateDumpFileIfNotExists() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new Person("John", "Doe")); tx.put("p2", new Person("Jane", "Doe")); tx.commit(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // delete the file (we only want the file "pointer") dumpFile.delete(); // write to output db.writeDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person"), // use the default converter for persons DumpOption.defaultConverter(Person.class, new PersonDefaultConverter()) // end of dump command ); // assert that the output file exists assertTrue(dumpFile.exists()); // delete it again dumpFile.delete(); } @Test public void canLoadDumpWithInMemoryDB() { ChronoDB db = this.getChronoDB(); // fill the database with some data ChronoDBTransaction tx = db.tx(); tx.put("first", 123); tx.put("MyKeyspace", "second", 456); tx.commit(); long writeTimestamp1 = tx.getTimestamp(); sleep(5); // create a branch db.getBranchManager().createBranch("MyBranch"); sleep(5); // insert some data into the branch tx = db.tx("MyBranch"); tx.put("Math", "Pi", 31415); tx.commit(); long writeTimestamp2 = tx.getTimestamp(); sleep(5); // create a sub-branch db.getBranchManager().createBranch("MyBranch", "MySubBranch"); sleep(5); // commit something in the master branch tx = db.tx(); tx.put("MyAwesomeKeyspace", "third", 789); tx.commit(); // create the temporary file File testDumpFile = this.createTestFile("Test.chronodump"); // create the dump db.writeDump(testDumpFile); String fileContents; try { fileContents = FileUtils.readFileToString(testDumpFile); System.out.println(fileContents); } catch (IOException e) { e.printStackTrace(); } // deserialize the dump ChronoDB db2 = ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER).build(); db2.readDump(testDumpFile); ChronoDBTransaction txAfter1 = db2.tx(writeTimestamp1); assertEquals(Sets.newHashSet("default", "MyKeyspace"), txAfter1.keyspaces()); assertEquals(123, (int) txAfter1.get("first")); assertEquals(456, (int) txAfter1.get("MyKeyspace", "second")); assertNull(db2.tx("MyBranch", writeTimestamp1).get("Math", "Pi")); ChronoDBTransaction txAfter2 = db2.tx("MyBranch", writeTimestamp2); assertEquals(Sets.newHashSet("default", "MyKeyspace"), txAfter1.keyspaces()); assertEquals(123, (int) txAfter2.get("first")); assertEquals(456, (int) txAfter2.get("MyKeyspace", "second")); assertEquals(31415, (int) txAfter2.get("Math", "Pi")); assertEquals(Sets.newHashSet("default", "MyKeyspace", "Math"), txAfter2.keyspaces()); // check that the "MySubBranch" exists assertTrue(db2.getBranchManager().existsBranch("MySubBranch")); assertNotNull(db2.tx("MySubBranch")); assertEquals("MyBranch", db2.getBranchManager().getBranch("MySubBranch").getOrigin().getName()); } @Test public void canExportAndImportDumpOnSameDBType() { ChronoDB db = this.getChronoDB(); // fill the database with some data ChronoDBTransaction tx = db.tx(); tx.put("first", 123); tx.put("MyKeyspace", "second", 456); tx.commit(); sleep(5); // create a branch db.getBranchManager().createBranch("MyBranch"); sleep(5); // insert some data into the branch tx = db.tx("MyBranch"); tx.put("Math", "Pi", 31415); tx.commit(); sleep(5); // create a sub-branch db.getBranchManager().createBranch("MyBranch", "MySubBranch"); sleep(5); // commit something in the master branch tx = db.tx(); tx.put("MyAwesomeKeyspace", "third", 789); tx.commit(); // create the temporary file File testDumpFile = this.createTestFile("Test.chronodump"); // create the dump db.writeDump(testDumpFile); // clear the database db = this.reinstantiateDB(); db.readDump(testDumpFile); // assert that each branch contains the correct information tx = db.tx("MySubBranch"); // Keyspaces in 'MySubBranch': default, MyKeyspace, Math assertEquals(3, tx.keyspaces().size()); assertEquals(31415, (int) tx.get("Math", "Pi")); assertEquals(456, (int) tx.get("MyKeyspace", "second")); assertEquals(123, (int) tx.get("first")); assertEquals(false, tx.keyspaces().contains("MyAwesomeKeyspace")); tx = db.tx(); // Keyspaces in 'Master': default, MyKeyspace, MyAwesomeKeyspace assertEquals(3, tx.keyspaces().size()); assertEquals(789, (int) tx.get("MyAwesomeKeyspace", "third")); } @Test public void canExportAndImportIndexers() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex() .withName("firstname") .withIndexer(new FirstNameIndexer()) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().createIndex() .withName("lastname") .withIndexer(new LastNameIndexer()) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().createIndex() .withName("nickname") .withIndexer(new NicknameIndexer()) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().reindexAll(); long afterFirstCommit = -1L; { // first transaction ChronoDBTransaction tx = db.tx(); tx.put("p1", new Person("John", "Doe", "Johnny", "JD")); tx.put("p2", new Person("Jane", "Doe", "Jenny", "JD")); tx.put("p3", new Person("Jack", "Doe", "Jacky", "JD")); tx.put("p4", new Person("John", "Smith", "Johnny", "JS")); tx.commit(); afterFirstCommit = tx.getTimestamp(); } { // second transaction ChronoDBTransaction tx = db.tx(); tx.remove("p3"); tx.put("p2", new Person("Jane", "Smith", "Jenny", "JS")); tx.commit(); } { // make sure that the indexer state is consistent ChronoDBTransaction tx = db.tx(); Set<String> JDs = tx.find().inDefaultKeyspace().where("nickname").containsIgnoreCase("JD").getKeysAsSet() // transform qualified keys into regular keys, everything resides in the same keyspace .stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1"), JDs); Set<String> johns = tx.find().inDefaultKeyspace().where("firstname").isEqualToIgnoreCase("john") // transform qualified keys into regular keys, everything resides in the same keyspace .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p4"), johns); } // create the dump file File testDumpFile = this.createTestFile("Test.chronodump"); // write the DB contents to the test file db.writeDump(testDumpFile); // print the file contents (for debugging) try { System.out.println(FileUtils.readFileToString(testDumpFile)); } catch (IOException e) { e.printStackTrace(); } // reinstantiate the DB to clear its contents ChronoDB db2 = this.reinstantiateDB(); // read the dump db2.readDump(testDumpFile); {// make sure that the state is consistent after the first commit ChronoDBTransaction tx = db2.tx(afterFirstCommit); Set<String> JDs = tx.find().inDefaultKeyspace().where("nickname").containsIgnoreCase("jd").getKeysAsSet() .stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p2", "p3"), JDs); Set<String> johns = tx.find().inDefaultKeyspace().where("firstname").isEqualToIgnoreCase("john") .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p4"), johns); } } @Test public void canExportInPlainTextFormat() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new ExternalizablePerson("John", "Doe", "Johnny", "JD")); tx.put("p2", new ExternalizablePerson("Jane", "Doe", "Jenny", "JD")); tx.commit(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // write to output db.writeDump(dumpFile); // read the dump into a string String dumpContents = null; try { dumpContents = FileUtils.readFileToString(dumpFile); } catch (IOException e) { e.printStackTrace(); fail(); } // print the file contents (for debugging) System.out.println(dumpContents); // make sure that there are no binary entries in the resulting dump assertFalse(this.containsBinaryEntries(dumpContents)); // read the dump ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile); { // make sure that our data is present and accessible ChronoDBTransaction tx = db2.tx(); ExternalizablePerson john = tx.get("p1"); assertNotNull(john); assertEquals("John", john.getFirstName()); assertEquals("Doe", john.getLastName()); assertEquals(Sets.newHashSet("JD", "Johnny"), john.getNickNames()); ExternalizablePerson jane = tx.get("p2"); assertNotNull(jane); assertEquals("Jane", jane.getFirstName()); assertEquals("Doe", jane.getLastName()); assertEquals(Sets.newHashSet("JD", "Jenny"), jane.getNickNames()); } } @Test public void canReadWriteZippedDump() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("firstname") .withIndexer(new FirstNameIndexer()) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().createIndex().withName("lastname") .withIndexer(new LastNameIndexer()) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().createIndex().withName("nickname") .withIndexer(new NicknameIndexer()) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().reindexAll(); { // add test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new Person("John", "Doe", "Johnny", "JD")); tx.put("p2", new Person("Jane", "Doe", "Jenny", "JD")); tx.commit(); } // create the dump file File dumpFile = this.createTestFile("Test.chronodump.gzip"); // write the dump data db.writeDump(dumpFile, DumpOption.ENABLE_GZIP); // make sure that the produced file is zipped assertTrue(ChronosFileUtils.isGZipped(dumpFile)); // read the dump ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile); { // make sure that our data is present and accessible ChronoDBTransaction tx = db2.tx(); Person john = tx.get("p1"); assertNotNull(john); assertEquals("John", john.getFirstName()); assertEquals("Doe", john.getLastName()); assertEquals(Sets.newHashSet("JD", "Johnny"), john.getNickNames()); Person jane = tx.get("p2"); assertNotNull(jane); assertEquals("Jane", jane.getFirstName()); assertEquals("Doe", jane.getLastName()); assertEquals(Sets.newHashSet("JD", "Jenny"), jane.getNickNames()); } } @Test public void canExportAndImportWellKnownValues() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("set", Sets.newHashSet("Hello", "World")); tx.put("list", Lists.newArrayList(1, 2, 3, 4, 5)); tx.put("enum", DayOfWeek.MONDAY); tx.put("enumList", Lists.newArrayList(DayOfWeek.MONDAY, DayOfWeek.FRIDAY)); Map<String, Integer> map = Maps.newHashMap(); map.put("pi", 31415); map.put("zero", 0); map.put("one", 1); tx.put("map", map); Map<String, Set<String>> multiMap = Maps.newHashMap(); multiMap.put("persons", Sets.newHashSet("John", "Jane", "Jack")); multiMap.put("numbers", Sets.newHashSet("1", "2", "3")); tx.put("multimap", multiMap); tx.commit(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // write to output db.writeDump(dumpFile); // read the dump into a string String dumpContents = null; try { dumpContents = FileUtils.readFileToString(dumpFile); } catch (IOException e) { e.printStackTrace(); fail(); } // print the file contents (for debugging) System.out.println(dumpContents); // make sure that there are no binary entries in the resulting dump assertFalse(this.containsBinaryEntries(dumpContents)); // read the dump ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile); { // make sure that our data is present and accessible ChronoDBTransaction tx = db2.tx(); assertEquals(Sets.newHashSet("Hello", "World"), tx.get("set")); assertEquals(Lists.newArrayList(1, 2, 3, 4, 5), tx.get("list")); assertEquals(DayOfWeek.MONDAY, tx.get("enum")); assertEquals(Lists.newArrayList(DayOfWeek.MONDAY, DayOfWeek.FRIDAY), tx.get("enumList")); Map<String, Integer> map = Maps.newHashMap(); map.put("pi", 31415); map.put("zero", 0); map.put("one", 1); tx.put("map", map); assertEquals(map, tx.get("map")); Map<String, Set<String>> multiMap = Maps.newHashMap(); multiMap.put("persons", Sets.newHashSet("John", "Jane", "Jack")); multiMap.put("numbers", Sets.newHashSet("1", "2", "3")); assertEquals(multiMap, tx.get("multimap")); } } @Test public void canFallBackToBinaryForUnknownValueTypes() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new Person("John", "Doe")); tx.put("p2", new Person("Jane", "Doe")); tx.put("persons", Lists.newArrayList(new Person("John", "Doe"), new Person("Jane", "Doe"))); tx.commit(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // write to output db.writeDump(dumpFile); // read the dump into a string String dumpContents = null; try { dumpContents = FileUtils.readFileToString(dumpFile); } catch (IOException e) { e.printStackTrace(); fail(); } // print the file contents (for debugging) System.out.println(dumpContents); // make sure that there are binary entries (for the persons) in the dump assertTrue(this.containsBinaryEntries(dumpContents)); // read the dump ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile); { // make sure that our data is present and accessible ChronoDBTransaction tx = db2.tx(); assertEquals(new Person("John", "Doe"), tx.get("p1")); assertEquals(new Person("Jane", "Doe"), tx.get("p2")); assertEquals(Lists.newArrayList(new Person("John", "Doe"), new Person("Jane", "Doe")), tx.get("persons")); } } @Test public void canRegisterDefaultConverters() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new Person("John", "Doe")); tx.put("p2", new Person("Jane", "Doe")); tx.commit(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // write to output db.writeDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person"), // use the default converter for persons DumpOption.defaultConverter(Person.class, new PersonDefaultConverter()) // end of dump command ); // read the dump into a string String dumpContents = null; try { dumpContents = FileUtils.readFileToString(dumpFile); } catch (IOException e) { e.printStackTrace(); fail(); } // print the file contents (for debugging) System.out.println(dumpContents); // make sure that there are no binary entries (because our default converter should match) assertFalse(this.containsBinaryEntries(dumpContents)); // make sure that our default converter does not appear in the output assertFalse(dumpContents.contains("PersonDefaultConverter")); // read the dump ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person"), // register the default converter (this time in the other direction DumpOption.defaultConverter(PersonDump.class, new PersonDefaultConverter()) // end of dump read command ); { // make sure that our data is present and accessible ChronoDBTransaction tx = db2.tx(); assertEquals(new Person("John", "Doe"), tx.get("p1")); assertEquals(new Person("Jane", "Doe"), tx.get("p2")); } } @Test public void canOverrideDefaultConverterWithAnnotation() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new ExternalizablePerson("John", "Doe")); tx.put("p2", new ExternalizablePerson("Jane", "Doe")); tx.commit(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // write to output db.writeDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person"), // use the default converter for persons DumpOption.defaultConverter(ExternalizablePerson.class, new PersonDefaultConverter()) // end of dump command ); // read the dump into a string String dumpContents = null; try { dumpContents = FileUtils.readFileToString(dumpFile); } catch (IOException e) { e.printStackTrace(); fail(); } // print the file contents (for debugging) System.out.println(dumpContents); // make sure that there are no binary entries (because our default converter should match) assertFalse(this.containsBinaryEntries(dumpContents)); // make sure that the annotation has overridden the default converter assertTrue(dumpContents.contains("PersonExternalizer")); // read the dump (NOTE: we do not register the default converter anymore, as there are no values for it) ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person") // end of dump read command ); { // make sure that our data is present and accessible ChronoDBTransaction tx = db2.tx(); assertEquals(new ExternalizablePerson("John", "Doe"), tx.get("p1")); assertEquals(new ExternalizablePerson("Jane", "Doe"), tx.get("p2")); } } @Test public void canAccessCommitTimestampsAfterReadingDump() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new ExternalizablePerson("John", "Doe")); tx.put("p2", new ExternalizablePerson("Jane", "Doe")); tx.commit(); tx.put("p3", new ExternalizablePerson("Jack", "Smith")); tx.commit(); db.getBranchManager().createBranch("test"); tx = db.tx("test"); tx.put("p4", new ExternalizablePerson("Sarah", "Doe")); tx.commit(); db.getBranchManager().createBranch("test", "testsub"); tx = db.tx("testsub"); tx.put("p5", new ExternalizablePerson("James", "Smith")); tx.commit(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // write to output db.writeDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person"), // use the default converter for persons DumpOption.defaultConverter(ExternalizablePerson.class, new PersonDefaultConverter()) // end of dump command ); // read the dump ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person") // end of dump read command ); { // assert that the commit history is accessible // there should be two commits on "master" assertEquals(2, db2.tx().countCommitTimestamps()); // there should be one commit on "test" assertEquals(1, db2.tx("test").countCommitTimestamps()); // there should be one commit on "testsub" assertEquals(1, db2.tx("testsub").countCommitTimestamps()); } } @Test public void canAccessCommitMetadataAfterReadingDump() throws Exception { long commit1; long commit2; long commit3; long commit4; ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("p1", new ExternalizablePerson("John", "Doe")); tx.put("p2", new ExternalizablePerson("Jane", "Doe")); tx.commit("first"); commit1 = tx.getTimestamp(); tx.put("p3", new ExternalizablePerson("Jack", "Smith")); tx.commit("second"); commit2 = tx.getTimestamp(); db.getBranchManager().createBranch("test"); tx = db.tx("test"); tx.put("p4", new ExternalizablePerson("Sarah", "Doe")); tx.commit("third"); commit3 = tx.getTimestamp(); db.getBranchManager().createBranch("test", "testsub"); tx = db.tx("testsub"); tx.put("p5", new ExternalizablePerson("James", "Smith")); tx.commit("fourth"); commit4 = tx.getTimestamp(); } // create the file File dumpFile = this.createTestFile("Test.chronodump"); // write to output db.writeDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person"), // use the default converter for persons DumpOption.defaultConverter(ExternalizablePerson.class, new PersonDefaultConverter()) // end of dump command ); // read the dump ChronoDB db2 = this.reinstantiateDB(); db2.readDump(dumpFile, // alias person class with a shorter name DumpOption.aliasHint(PersonDump.class, "person") // end of dump read command ); { // assert that the commit history is accessible // there should be two commits on "master" assertEquals(2, db2.tx().countCommitTimestamps()); // there should be one commit on "test" assertEquals(1, db2.tx("test").countCommitTimestamps()); // there should be one commit on "testsub" assertEquals(1, db2.tx("testsub").countCommitTimestamps()); // assert that the metadata is accessible List<Entry<Long, Object>> commits = db2.tx().getCommitMetadataBefore(System.currentTimeMillis() + 1, 2); assertEquals(commit2, (long) commits.get(0).getKey()); assertEquals("second", commits.get(0).getValue()); assertEquals(commit1, (long) commits.get(1).getKey()); assertEquals("first", commits.get(1).getValue()); commits = db2.tx("test").getCommitMetadataBefore(System.currentTimeMillis() + 1, 1); assertEquals(commit3, (long) commits.get(0).getKey()); assertEquals("third", commits.get(0).getValue()); commits = db2.tx("testsub").getCommitMetadataBefore(System.currentTimeMillis() + 1, 1); assertEquals(commit4, (long) commits.get(0).getKey()); assertEquals("fourth", commits.get(0).getValue()); } } // ===================================================================================================================== // HELPER METHODS // ===================================================================================================================== private File createTestFile(final String filename) { File testDirectory = this.getTestDirectory(); File testFile = new File(testDirectory, filename); try { testFile.createNewFile(); } catch (IOException ioe) { fail(ioe.toString()); } testFile.deleteOnExit(); return testFile; } private boolean containsBinaryEntries(final String dumpContents) { return dumpContents.contains("<" + ChronoDBDumpFormat.ALIAS_NAME__CHRONODB_BINARY_ENTRY + ">"); } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== public static class Person { private String firstName; private String lastName; private Set<String> nickNames = Sets.newHashSet(); public Person() { // serialization constructor } public Person(final String firstName, final String lastName, final String... nicknames) { checkNotNull(firstName, "Precondition violation - argument 'firstName' must not be NULL!"); checkNotNull(lastName, "Precondition violation - argument 'lastName' must not be NULL!"); this.firstName = firstName; this.lastName = lastName; if (nicknames != null && nicknames.length > 0) { for (String nickname : nicknames) { this.nickNames.add(nickname); } } } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public Set<String> getNickNames() { return this.nickNames; } public void setFirstName(final String firstName) { this.firstName = firstName; } public void setLastName(final String lastName) { this.lastName = lastName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.firstName == null ? 0 : this.firstName.hashCode()); result = prime * result + (this.lastName == null ? 0 : this.lastName.hashCode()); result = prime * result + (this.nickNames == null ? 0 : this.nickNames.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Person other = (Person) obj; if (this.firstName == null) { if (other.firstName != null) { return false; } } else if (!this.firstName.equals(other.firstName)) { return false; } if (this.lastName == null) { if (other.lastName != null) { return false; } } else if (!this.lastName.equals(other.lastName)) { return false; } if (this.nickNames == null) { if (other.nickNames != null) { return false; } } else if (!this.nickNames.equals(other.nickNames)) { return false; } return true; } } @ChronosExternalizable(converterClass = PersonExternalizer.class) public static class ExternalizablePerson extends Person { public ExternalizablePerson() { super(); } public ExternalizablePerson(final String firstName, final String lastName, final String... nicknames) { super(firstName, lastName, nicknames); } } // needs to be public; otherwise we can't instantiate it! public static class PersonExternalizer implements ChronoConverter<ExternalizablePerson, PersonDump> { public PersonExternalizer() { } @Override public PersonDump writeToOutput(final ExternalizablePerson person) { PersonDump dump = new PersonDump(); dump.setFirstName(person.getFirstName()); dump.setLastName(person.getLastName()); dump.getNickNames().addAll(person.getNickNames()); return dump; } @Override public ExternalizablePerson readFromInput(final PersonDump dump) { ExternalizablePerson person = new ExternalizablePerson(); person.setFirstName(dump.getFirstName()); person.setLastName(dump.getLastName()); person.getNickNames().addAll(dump.getNickNames()); return person; } } // needs to be public; otherwise we can't instantiate it! public static class PersonDefaultConverter implements ChronoConverter<Person, PersonDump> { public PersonDefaultConverter() { } @Override public PersonDump writeToOutput(final Person person) { PersonDump dump = new PersonDump(); dump.setFirstName(person.getFirstName()); dump.setLastName(person.getLastName()); dump.getNickNames().addAll(person.getNickNames()); return dump; } @Override public Person readFromInput(final PersonDump dump) { Person person = new Person(); person.setFirstName(dump.getFirstName()); person.setLastName(dump.getLastName()); person.getNickNames().addAll(dump.getNickNames()); return person; } } @SuppressWarnings("unused") public static class PersonDump { private String firstName; private String lastName; private Set<String> nickNames = Sets.newHashSet(); public PersonDump() { // serialization constructor } public PersonDump(final String firstName, final String lastName, final String... nicknames) { checkNotNull(firstName, "Precondition violation - argument 'firstName' must not be NULL!"); checkNotNull(lastName, "Precondition violation - argument 'lastName' must not be NULL!"); this.firstName = firstName; this.lastName = lastName; if (nicknames != null && nicknames.length > 0) { for (String nickname : nicknames) { this.nickNames.add(nickname); } } } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } public Set<String> getNickNames() { return this.nickNames; } public void setFirstName(final String firstName) { this.firstName = firstName; } public void setLastName(final String lastName) { this.lastName = lastName; } } public static abstract class PersonIndexer implements StringIndexer { @Override public boolean canIndex(final Object object) { return object != null && object instanceof Person; } @Override public Set<String> getIndexValues(final Object object) { Person person = (Person) object; return this.indexPerson(person); } protected abstract Set<String> indexPerson(Person person); } public static class FirstNameIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public Set<String> indexPerson(final Person person) { return Collections.singleton(person.getFirstName()); } } public static class LastNameIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public Set<String> indexPerson(final Person person) { return Collections.singleton(person.getLastName()); } } public static class NicknameIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override protected Set<String> indexPerson(final Person person) { return Sets.newHashSet(person.getNickNames()); } } }
37,377
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBReopeningTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/reopening/ChronoDBReopeningTest.java
package org.chronos.chronodb.test.cases.engine.reopening; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.test.base.AllBackendsTest.DontRunWithBackend; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.stream.Collectors; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) // these tests do not make sense with non-persistent backends. @DontRunWithBackend({InMemoryChronoDB.BACKEND_NAME}) public class ChronoDBReopeningTest extends AllChronoDBBackendsTest { private static final Logger log = LoggerFactory.getLogger(ChronoDBReopeningTest.class); @Test public void reopeningChronoDbWorks() { ChronoDB db = this.getChronoDB(); assertNotNull(db); ChronoDB db2 = this.closeAndReopenDB(); assertNotNull(db2); assertTrue(db != db2); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10000") public void reopeningChronoDbPreservesConfiguration() { ChronoDB db = this.getChronoDB(); assertNotNull(db); // assert that the settings from the test annotations were applied correctly assertTrue(db.getConfiguration().isCachingEnabled()); assertEquals(10000L, (long) db.getConfiguration().getCacheMaxSize()); // reinstantiate the DB ChronoDB db2 = this.closeAndReopenDB(); assertNotNull(db2); // assert that the settings have carried over assertTrue(db2.getConfiguration().isCachingEnabled()); assertEquals(10000L, (long) db.getConfiguration().getCacheMaxSize()); } @Test public void reopeningChronoDbPreservesContents() { ChronoDB db = this.getChronoDB(); assertNotNull(db); // fill the db with some data ChronoDBTransaction tx = db.tx(); tx.put("k1", "Hello World"); tx.put("k2", "Foo Bar"); tx.put("k3", 42); tx.commit(); // reinstantiate log.info("Reinstantiating DB"); ChronoDB db2 = this.closeAndReopenDB(); // check that the content is still there ChronoDBTransaction tx2 = db2.tx(); Set<String> keySet = tx2.keySet(); assertEquals(3, keySet.size()); assertTrue(keySet.contains("k1")); assertTrue(keySet.contains("k2")); assertTrue(keySet.contains("k3")); assertEquals("Hello World", tx2.get("k1")); assertEquals("Foo Bar", tx2.get("k2")); assertEquals(42, (int) tx2.get("k3")); } @Test public void reopeningChronoDbPreservesIndexers() { ChronoDB db = this.getChronoDB(); assertNotNull(db); // add some indexers db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("test").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); // assert that the indices are present Set<String> indexNames = db.getIndexManager().getIndices().stream().map(SecondaryIndex::getName).collect(Collectors.toSet()); assertTrue(indexNames.contains("name")); assertTrue(indexNames.contains("test")); assertEquals(2, indexNames.size()); // reinstantiate the DB ChronoDB db2 = this.closeAndReopenDB(); // assert that the indices are still present Set<String> indexNames2 = db2.getIndexManager().getIndices().stream().map(SecondaryIndex::getName).collect(Collectors.toSet()); assertTrue(indexNames2.contains("name")); assertTrue(indexNames2.contains("test")); assertEquals(2, indexNames2.size()); } @Test public void reopeningChronoDbPreservesIndexDirtyFlags() { ChronoDB db = this.getChronoDB(); assertNotNull(db); // add some indexers db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); db.getIndexManager().createIndex().withName("test").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); // make sure that 'name' isn't dirty Set<String> dirtyIndexNames = db.getIndexManager().getDirtyIndices().stream().map(SecondaryIndex::getName).collect(Collectors.toSet()); assertFalse(dirtyIndexNames.contains("name")); // ... but the 'test' index should still be dirty assertTrue(dirtyIndexNames.contains("test")); // reopen the db ChronoDB db2 = this.closeAndReopenDB(); // assert that the 'name' index is not dirty, but the 'test' index is Set<String> dirtyIndexNames2 = db2.getIndexManager().getDirtyIndices().stream().map(SecondaryIndex::getName).collect(Collectors.toSet()); assertFalse(dirtyIndexNames2.contains("name")); assertTrue(dirtyIndexNames2.contains("test")); } @Test public void reopeningChronoDbPreservesBranches() { ChronoDB db = this.getChronoDB(); assertNotNull(db); { // insert data into "master" ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(); } db.getBranchManager().createBranch("Test"); { // insert data into "Test" ChronoDBTransaction tx = db.tx("Test"); tx.put("Foo", "Bar"); tx.commit(); } db.getBranchManager().createBranch("Test", "TestSub"); { // insert data into "TestSub" ChronoDBTransaction tx = db.tx("TestSub"); tx.put("Foo", "Baz"); tx.commit(); } // assert that the data is present assertEquals("World", db.tx().get("Hello")); assertEquals("Bar", db.tx("Test").get("Foo")); assertEquals("Baz", db.tx("TestSub").get("Foo")); // close and reopen the db ChronoDB db2 = this.closeAndReopenDB(); // assert that the data is still present assertEquals("World", db2.tx().get("Hello")); assertEquals("Bar", db2.tx("Test").get("Foo")); assertEquals("Baz", db2.tx("TestSub").get("Foo")); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000") public void mosaicCacheWorksWithReopenedRolloverDB() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); this.assumeIsPersistent(db); { // initial commit ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Value", 1); tx.commit(); } { // update... ChronoDBTransaction tx = db.tx(); tx.put("Value", 2); tx.commit(); } long beforeRollover = db.getBranchManager().getMasterBranch().getNow(); // rollover db.getMaintenanceManager().performRolloverOnMaster(); long afterRollover = db.getBranchManager().getMasterBranch().getNow(); assertThat(beforeRollover, is(lessThan(afterRollover))); { // perform another update ChronoDBTransaction tx = db.tx(); tx.put("Value", 3); tx.commit(); } // restart db = this.closeAndReopenDB(); { // query the old state (this will fill the cache with an entry from chunk 0) ChronoDBTransaction tx = db.tx(beforeRollover); Object value = tx.get("Value"); assertThat(value, is(2)); } { // query again at head (which is on chunk 1) ChronoDBTransaction tx = db.tx(); // we should see the HEAD value assertThat(tx.get("Value"), is(3)); } } }
8,687
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RolloverTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/maintenance/rollover/RolloverTest.java
package org.chronos.chronodb.test.cases.engine.maintenance.rollover; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.stream.ChronoDBEntry; import org.chronos.chronodb.internal.api.stream.CloseableIterator; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.model.person.PersonIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.model.person.Person; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class RolloverTest extends AllChronoDBBackendsTest { @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "20") public void basicRolloverWorks() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); // insert a couple of entries { ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("programming", "Foo", "Bar"); tx.put("programming", "Number", "42"); tx.put("person", "John", "Doe"); tx.put("person", "Jane", "Doe"); tx.commit(); } long afterFirstCommit = System.currentTimeMillis(); sleep(5); { ChronoDBTransaction tx = db.tx(); tx.remove("person", "John"); tx.remove("person", "Jane"); tx.remove("programming", "Number"); tx.put("programming", "Foo", "Baz"); tx.put("person", "John", "Smith"); tx.commit(); } long afterSecondCommit = System.currentTimeMillis(); sleep(5); // perform the rollover db.getMaintenanceManager().performRolloverOnMaster(); // make sure that we can access the initial data { ChronoDBTransaction tx = db.tx(afterFirstCommit); assertEquals("World", tx.get("Hello")); assertEquals("Bar", tx.get("programming", "Foo")); assertEquals("42", tx.get("programming", "Number")); assertEquals("Doe", tx.get("person", "John")); assertEquals("Doe", tx.get("person", "Jane")); assertEquals(Sets.newHashSet("default", "programming", "person"), tx.keyspaces()); assertEquals(Sets.newHashSet("Hello"), tx.keySet()); assertEquals(Sets.newHashSet("Foo", "Number"), tx.keySet("programming")); assertEquals(Sets.newHashSet("John", "Jane"), tx.keySet("person")); } // make sure that the data after the second commit is still there { ChronoDBTransaction tx = db.tx(afterSecondCommit); assertEquals("World", tx.get("Hello")); assertEquals("Baz", tx.get("programming", "Foo")); assertEquals("Smith", tx.get("person", "John")); assertEquals(Sets.newHashSet("default", "programming", "person"), tx.keyspaces()); assertEquals(Sets.newHashSet("Hello"), tx.keySet()); assertEquals(Sets.newHashSet("Foo"), tx.keySet("programming")); assertEquals(Sets.newHashSet("John"), tx.keySet("person")); } // make sure that the head revision data is still there { ChronoDBTransaction tx = db.tx(); assertEquals("World", tx.get("Hello")); assertEquals("Baz", tx.get("programming", "Foo")); assertEquals("Smith", tx.get("person", "John")); assertEquals(Sets.newHashSet("default", "programming", "person"), tx.keyspaces()); assertEquals(Sets.newHashSet("Hello"), tx.keySet()); assertEquals(Sets.newHashSet("Foo"), tx.keySet("programming")); assertEquals(Sets.newHashSet("John"), tx.keySet("person")); } // make sure that the rollover did not count as "change" in the history { ChronoDBTransaction tx = db.tx(); assertEquals(1, Iterators.size(tx.history("Hello"))); assertEquals(2, Iterators.size(tx.history("programming", "Foo"))); } } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "20") public void multipleRolloverWork() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); // insert a couple of entries { ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("programming", "Foo", "Bar"); tx.put("programming", "Number", "42"); tx.put("person", "John", "Doe"); tx.put("person", "Jane", "Doe"); tx.commit(); } long afterFirstCommit = System.currentTimeMillis(); sleep(5); { ChronoDBTransaction tx = db.tx(); tx.remove("person", "John"); tx.remove("person", "Jane"); tx.remove("programming", "Number"); tx.put("programming", "Foo", "Baz"); tx.put("person", "John", "Smith"); tx.commit(); } long afterSecondCommit = System.currentTimeMillis(); sleep(5); // perform the rollover db.getMaintenanceManager().performRolloverOnMaster(); // do a commit on the new chunk { ChronoDBTransaction tx = db.tx(); tx.put("math", "pi", "3.1415"); tx.put("math", "e", "2.7182"); tx.put("person", "John", "Johnson"); tx.commit(); } long afterThirdCommit = System.currentTimeMillis(); sleep(5); // do another rollover db.getMaintenanceManager().performRolloverOnMaster(); // make sure that we can access the initial data { ChronoDBTransaction tx = db.tx(afterFirstCommit); assertEquals("World", tx.get("Hello")); assertEquals("Bar", tx.get("programming", "Foo")); assertEquals("42", tx.get("programming", "Number")); assertEquals("Doe", tx.get("person", "John")); assertEquals("Doe", tx.get("person", "Jane")); assertEquals(Sets.newHashSet("default", "programming", "person"), tx.keyspaces()); assertEquals(Sets.newHashSet("Hello"), tx.keySet()); assertEquals(Sets.newHashSet("Foo", "Number"), tx.keySet("programming")); assertEquals(Sets.newHashSet("John", "Jane"), tx.keySet("person")); } // make sure that the data after the second commit is still there { ChronoDBTransaction tx = db.tx(afterSecondCommit); assertEquals("World", tx.get("Hello")); assertEquals("Baz", tx.get("programming", "Foo")); assertEquals("Smith", tx.get("person", "John")); assertEquals(Sets.newHashSet("default", "programming", "person"), tx.keyspaces()); assertEquals(Sets.newHashSet("Hello"), tx.keySet()); assertEquals(Sets.newHashSet("Foo"), tx.keySet("programming")); assertEquals(Sets.newHashSet("John"), tx.keySet("person")); } // make sure that the data after the third is still there { ChronoDBTransaction tx = db.tx(afterThirdCommit); assertEquals("World", tx.get("Hello")); assertEquals("Baz", tx.get("programming", "Foo")); assertEquals("Johnson", tx.get("person", "John")); assertEquals("3.1415", tx.get("math", "pi")); assertEquals("2.7182", tx.get("math", "e")); assertEquals(Sets.newHashSet("default", "programming", "person", "math"), tx.keyspaces()); assertEquals(Sets.newHashSet("Hello"), tx.keySet()); assertEquals(Sets.newHashSet("Foo"), tx.keySet("programming")); assertEquals(Sets.newHashSet("John"), tx.keySet("person")); assertEquals(Sets.newHashSet("pi", "e"), tx.keySet("math")); } // make sure that the head revision data is accessible { ChronoDBTransaction tx = db.tx(); assertEquals("World", tx.get("Hello")); assertEquals("Baz", tx.get("programming", "Foo")); assertEquals("Johnson", tx.get("person", "John")); assertEquals("3.1415", tx.get("math", "pi")); assertEquals("2.7182", tx.get("math", "e")); assertEquals(Sets.newHashSet("default", "programming", "person", "math"), tx.keyspaces()); assertEquals(Sets.newHashSet("Hello"), tx.keySet()); assertEquals(Sets.newHashSet("Foo"), tx.keySet("programming")); assertEquals(Sets.newHashSet("John"), tx.keySet("person")); assertEquals(Sets.newHashSet("pi", "e"), tx.keySet("math")); } // make sure that the rollover did not count as "change" in the history { ChronoDBTransaction tx = db.tx(); assertEquals(1, Iterators.size(tx.history("Hello"))); assertEquals(2, Iterators.size(tx.history("programming", "Foo"))); assertEquals(3, Iterators.size(tx.history("person", "John"))); } } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "20") @InstantiateChronosWith(property = ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, value = "false") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "10") @InstantiateChronosWith(property = ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, value = "off") public void secondaryIndexingWorksWithBasicRollover() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); db.getIndexManager().createIndex().withName("firstName").withIndexer(PersonIndexer.firstName()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("lastName").withIndexer(PersonIndexer.lastName()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("favoriteColor").withIndexer(PersonIndexer.favoriteColor()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("hobbies").withIndexer(PersonIndexer.hobbies()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("pets").withIndexer(PersonIndexer.pets()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // add a couple of persons { ChronoDBTransaction tx = db.tx(); Person johnDoe = new Person("John", "Doe"); johnDoe.setFavoriteColor("red"); johnDoe.setHobbies("swimming", "skiing", "reading"); johnDoe.setPets("cat"); Person janeDoe = new Person("Jane", "Doe"); janeDoe.setFavoriteColor("blue"); janeDoe.setHobbies("skiing", "cinema", "biking"); janeDoe.setPets("cat"); Person sarahDoe = new Person("Sarah", "Doe"); sarahDoe.setFavoriteColor("green"); sarahDoe.setHobbies("swimming", "reading", "cinema"); sarahDoe.setPets("cat"); tx.put("theDoes", "p1", johnDoe); tx.put("theDoes", "p2", janeDoe); tx.put("theDoes", "p3", sarahDoe); Person jackSmith = new Person("Jack", "Smith"); jackSmith.setFavoriteColor("orange"); jackSmith.setHobbies("games"); jackSmith.setPets("cat", "dog", "fish"); Person johnSmith = new Person("John", "Smith"); johnSmith.setFavoriteColor("yellow"); johnSmith.setHobbies("reading"); johnSmith.setPets("cat", "dog"); tx.put("theSmiths", "p1", jackSmith); tx.put("theSmiths", "p2", johnSmith); tx.commit(); } long afterFirstCommit = System.currentTimeMillis(); sleep(5); // make a couple of modifications { ChronoDBTransaction tx = db.tx(); // sarah gets a dog Person sarahDoe = tx.get("theDoes", "p3"); sarahDoe.getPets().add("dog"); tx.put("theDoes", "p3", sarahDoe); // john smith goes on vacation... tx.remove("theSmiths", "p2"); tx.commit(); } long afterSecondCommit = System.currentTimeMillis(); // do the rollover db.getMaintenanceManager().performRolloverOnMaster(); // run a couple of queries on the initial state { ChronoDBTransaction tx = db.tx(afterFirstCommit); Set<String> personsWithJInFirstName = tx.find().inKeyspace("theDoes") // find all persons with a "j" in the first name .where("firstName").containsIgnoreCase("j") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p2"), personsWithJInFirstName); Set<String> personsWhoLikeReading = tx.find().inKeyspace("theDoes") // find all persons that have reading as a hobby .where("hobbies").contains("reading") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p3"), personsWhoLikeReading); } // run a couple of queries after the first commit { ChronoDBTransaction tx = db.tx(afterSecondCommit); Set<String> personsWithJInFirstName = tx.find().inKeyspace("theDoes") // find all persons with a "j" in the first name .where("firstName").containsIgnoreCase("j") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p2"), personsWithJInFirstName); Set<String> personsWhoLikeReading = tx.find().inKeyspace("theDoes") // find all persons that have reading as a hobby .where("hobbies").contains("reading") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p3"), personsWhoLikeReading); Set<String> doesWhoHaveADog = tx.find().inKeyspace("theDoes") // find all persons who have a dog .where("pets").contains("dog") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p3"), doesWhoHaveADog); Set<String> smithsWhoHaveADog = tx.find().inKeyspace("theSmiths") // find all persons who have a dog .where("pets").contains("dog") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1"), smithsWhoHaveADog); } // run a couple of queries on the head revision { ChronoDBTransaction tx = db.tx(); Set<String> personsWithJInFirstName = tx.find().inKeyspace("theDoes") // find all persons with a "j" in the first name .where("firstName").containsIgnoreCase("j") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p2"), personsWithJInFirstName); Set<String> personsWhoLikeReading = tx.find().inKeyspace("theDoes") // find all persons that have reading as a hobby .where("hobbies").contains("reading") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1", "p3"), personsWhoLikeReading); Set<String> doesWhoHaveADog = tx.find().inKeyspace("theDoes") // find all persons who have a dog .where("pets").contains("dog") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p3"), doesWhoHaveADog); Set<String> smithsWhoHaveADog = tx.find().inKeyspace("theSmiths") // find all persons who have a dog .where("pets").contains("dog") // transform to plain key set .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("p1"), smithsWhoHaveADog); } } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100000") public void performingARolloverPreservesEntrySetWithCache() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); this.runPerformingARolloverPerservesEntrySetTest(db); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "false") public void performingARolloverPreservesEntrySetWithoutCache() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); this.runPerformingARolloverPerservesEntrySetTest(db); } @Test public void performingARolloverOnAnEmptyBranchChunkWorks(){ ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); { // base data ChronoDBTransaction tx = db.tx(); tx.put("a", 1); tx.put("b", 2); tx.put("c", 3); tx.commit(); } Branch myBranch = db.getBranchManager().createBranch("my-branch"); { // some more data on the base branch ChronoDBTransaction tx = db.tx(); tx.put("a", 1000); tx.put("b", 2000); tx.put("c", 3000); tx.commit(); } db.getMaintenanceManager().performRolloverOnAllBranches(); assertThat(db.tx("my-branch").get("a"), is(1)); assertThat(db.tx("my-branch").get("b"), is(2)); assertThat(db.tx("my-branch").get("c"), is(3)); try(CloseableIterator<ChronoDBEntry> entryStream = ((ChronoDBInternal)db).entryStream("my-branch", myBranch.getNow(), Long.MAX_VALUE)){ List<ChronoDBEntry> entries = Lists.newArrayList(entryStream.asIterator()); assertThat(entries.size(), is(3)); } } @Test @DontRunWithBackend("chunked") // the chunked backend contains rollover timestamps in the history public void historyAcrossBranchesAndRolloversWorks(){ ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); ChronoDBTransaction tx1 = db.tx(); tx1.put("a", 1); tx1.put("b", 1); long commit1 = tx1.commit(); Branch b1 = db.getBranchManager().createBranch("b1"); System.out.println("B1 branching timestamp: " + b1.getBranchingTimestamp()); ChronoDBTransaction tx2 = db.tx("b1"); tx2.put("a", 2); tx2.put("c", 1); long commit2 = tx2.commit(); db.getMaintenanceManager().performRolloverOnAllBranches(); // do another transaction on master after branching away ChronoDBTransaction tx3 = db.tx(); tx3.put("z", 1); tx3.remove("a"); tx3.commit(); Branch b2 = db.getBranchManager().createBranch("b1", "b2"); System.out.println("B2 branching timestamp: " + b2.getBranchingTimestamp()); ChronoDBTransaction tx4 = db.tx("b2"); tx4.remove("a"); tx4.put("b", 2); tx4.put("d", 1); long commit4 = tx4.commit(); db.getMaintenanceManager().performRolloverOnAllBranches(); // do another transaction on b1 ChronoDBTransaction tx5 = db.tx("b1"); tx5.put("y", 1); tx5.remove("b"); tx5.commit(); db.getMaintenanceManager().performRolloverOnAllBranches(); System.out.println("Commit1: " + commit1); System.out.println("Commit2: " + commit2); System.out.println("Commit4: " + commit4); // create a new branch that contains nothing Branch b3 = db.getBranchManager().createBranch("b2", "b3"); System.out.println("B3 branching timestamp: " + b3.getBranchingTimestamp()); // query the history of "a" on b2 assertThat(Lists.newArrayList(db.tx("b3").history("a")), contains(commit4, commit2, commit1)); // query in ascending order ArrayList<Long> list = Lists.newArrayList(db.tx("b3").history("a", Order.ASCENDING)); assertThat(list, contains(commit1, commit2, commit4)); // query history with bounds assertThat(Lists.newArrayList(db.tx("b3").history("a", commit1, commit2, Order.DESCENDING)), contains(commit2, commit1)); assertThat(Lists.newArrayList(db.tx("b3").history("a", commit1, commit2, Order.ASCENDING)), contains(commit1, commit2)); } private void runPerformingARolloverPerservesEntrySetTest(final ChronoDB db) { // in this test, we work with two keyspaces, each containing four keys: // 1: this key will never be modified and serves as a sanity check. // 2: this key will be overwritten with a new value before the rollover. // 3: this key will be removed before the rollover // 4: this key will first be overwritten and then removed before the rollover. // both keyspaces contain the same keys, except prefixed by 'a' or 'b', respectively. { ChronoDBTransaction tx = db.tx(); // keyspace A tx.put("keyspaceA", "a1", "a"); tx.put("keyspaceA", "a2", "b"); tx.put("keyspaceA", "a3", "c"); tx.put("keyspaceA", "a4", "d"); // keyspace B tx.put("keyspaceB", "b1", "a"); tx.put("keyspaceB", "b2", "b"); tx.put("keyspaceB", "b3", "c"); tx.put("keyspaceB", "b4", "d"); tx.commit(); } // check that the commit worked as intended assertEquals(Sets.newHashSet("a1", "a2", "a3", "a4"), db.tx().keySet("keyspaceA")); assertEquals(Sets.newHashSet("b1", "b2", "b3", "b4"), db.tx().keySet("keyspaceB")); // perform the first set of modifications { ChronoDBTransaction tx = db.tx(); // keyspace A tx.put("keyspaceA", "a2", "modified"); tx.remove("keyspaceA", "a3"); tx.put("keyspaceA", "a4", "modified"); // keyspace B tx.put("keyspaceB", "b2", "modified"); tx.remove("keyspaceB", "b3"); tx.put("keyspaceB", "b4", "modified"); tx.commit(); } // check that the modifications produced the expected result assertEquals(Sets.newHashSet("a1", "a2", "a4"), db.tx().keySet("keyspaceA")); assertEquals(Sets.newHashSet("b1", "b2", "b4"), db.tx().keySet("keyspaceB")); // perform the second set of modifications { ChronoDBTransaction tx = db.tx(); // keyspace A tx.remove("keyspaceA", "a4"); // keyspace B tx.remove("keyspaceB", "b4"); tx.commit(); } // check that the modifications produced the expected result assertEquals(Sets.newHashSet("a1", "a2"), db.tx().keySet("keyspaceA")); assertEquals(Sets.newHashSet("b1", "b2"), db.tx().keySet("keyspaceB")); long beforeRollover = db.getBranchManager().getMasterBranch().getNow(); // perform the rollover db.getMaintenanceManager().performRolloverOnMaster(); // make sure that we can request the same key set before and after the rollover assertEquals(Sets.newHashSet("a1", "a2"), db.tx(beforeRollover).keySet("keyspaceA")); assertEquals(Sets.newHashSet("b1", "b2"), db.tx(beforeRollover).keySet("keyspaceB")); assertEquals(Sets.newHashSet("a1", "a2"), db.tx().keySet("keyspaceA")); assertEquals(Sets.newHashSet("b1", "b2"), db.tx().keySet("keyspaceB")); // assert that the "get" operations deliver the same results // before rollover assertEquals("a", db.tx(beforeRollover).get("keyspaceA", "a1")); assertEquals("modified", db.tx(beforeRollover).get("keyspaceA", "a2")); assertFalse(db.tx(beforeRollover).exists("keyspaceA", "a3")); assertFalse(db.tx(beforeRollover).exists("keyspaceA", "a4")); assertEquals("a", db.tx(beforeRollover).get("keyspaceB", "b1")); assertEquals("modified", db.tx(beforeRollover).get("keyspaceB", "b2")); assertFalse(db.tx(beforeRollover).exists("keyspaceB", "b3")); assertFalse(db.tx(beforeRollover).exists("keyspaceB", "b4")); // after rollover assertEquals("a", db.tx().get("keyspaceA", "a1")); assertEquals("modified", db.tx().get("keyspaceA", "a2")); assertFalse(db.tx().exists("keyspaceA", "a3")); assertFalse(db.tx().exists("keyspaceA", "a4")); assertEquals("a", db.tx().get("keyspaceB", "b1")); assertEquals("modified", db.tx().get("keyspaceB", "b2")); assertFalse(db.tx().exists("keyspaceB", "b3")); assertFalse(db.tx().exists("keyspaceB", "b4")); // perform the third set of changes (after rollover) { ChronoDBTransaction tx = db.tx(); // keyspace A tx.put("keyspaceA", "a2", "modified2"); tx.put("keyspaceA", "a5", "inserted"); // keyspace B tx.put("keyspaceB", "b2", "modified2"); tx.put("keyspaceB", "b5", "inserted"); tx.commit(); } assertEquals(Sets.newHashSet("a1", "a2", "a5"), db.tx().keySet("keyspaceA")); assertEquals(Sets.newHashSet("b1", "b2", "b5"), db.tx().keySet("keyspaceB")); assertEquals("modified2", db.tx().get("keyspaceA", "a2")); assertEquals("modified2", db.tx().get("keyspaceB", "b2")); } }
27,637
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RangedGetTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/versioning/RangedGetTest.java
package org.chronos.chronodb.test.cases.engine.versioning; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class RangedGetTest extends AllChronoDBBackendsTest { @Test public void rangedGetBehavesCorrectlyInMainCase() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Name", "Martin"); tx.put("Number", 123); tx.commit(); long afterFirstCommit = tx.getTimestamp(); this.sleep(10); long betweenCommits = System.currentTimeMillis(); this.sleep(10); tx.put("Hello", "Foo"); tx.put("Name", "John"); tx.put("Number", 456); tx.commit(); long afterSecondCommit = tx.getTimestamp(); this.sleep(10); tx.put("Hello", "Bar"); tx.put("Name", "Jack"); tx.put("Number", 789); tx.commit(); TemporalKeyValueStore tkvs = this.getMasterTkvs(db); ChronoDBTransaction tx2 = db.tx(betweenCommits); // test the ranges in the cases where there is a lower bound and an upper bound GetResult<Object> result1 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Hello")); assertNotNull(result1); assertEquals("World", result1.getValue()); assertEquals(afterFirstCommit, result1.getPeriod().getLowerBound()); assertEquals(afterSecondCommit, result1.getPeriod().getUpperBound()); GetResult<Object> result2 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Name")); assertNotNull(result2); assertEquals("Martin", result2.getValue()); assertEquals(afterFirstCommit, result2.getPeriod().getLowerBound()); assertEquals(afterSecondCommit, result2.getPeriod().getUpperBound()); GetResult<Object> result3 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Number")); assertNotNull(result3); assertEquals(123, result3.getValue()); assertEquals(afterFirstCommit, result3.getPeriod().getLowerBound()); assertEquals(afterSecondCommit, result3.getPeriod().getUpperBound()); } @Test public void rangedGetBehavesCorrectlyInTemporalCornerCases() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Name", "Martin"); tx.put("Number", 123); tx.commit(); long afterFirstCommit = tx.getTimestamp(); this.sleep(10); tx.put("Hello", "Foo"); tx.put("Name", "John"); tx.put("Number", 456); tx.commit(); this.sleep(10); tx.put("Hello", "Bar"); tx.put("Name", "Jack"); tx.put("Number", 789); tx.commit(); long afterThirdCommit = tx.getTimestamp(); TemporalKeyValueStore tkvs = this.getMasterTkvs(db); // test the ranges BEFORE the first commit ChronoDBTransaction tx2 = db.tx(0); GetResult<Object> result1 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Hello")); assertNotNull(result1); assertNull(result1.getValue()); assertEquals(0, result1.getPeriod().getLowerBound()); assertEquals(afterFirstCommit, result1.getPeriod().getUpperBound()); GetResult<Object> result2 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Name")); assertNotNull(result2); assertNull(result2.getValue()); assertEquals(0, result2.getPeriod().getLowerBound()); assertEquals(afterFirstCommit, result2.getPeriod().getUpperBound()); GetResult<Object> result3 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Number")); assertNotNull(result3); assertNull(result3.getValue()); assertEquals(0, result3.getPeriod().getLowerBound()); assertEquals(afterFirstCommit, result3.getPeriod().getUpperBound()); // test the ranges AFTER the third commit ChronoDBTransaction tx3 = db.tx(afterThirdCommit); GetResult<Object> result4 = tkvs.performRangedGet(tx3, QualifiedKey.createInDefaultKeyspace("Hello")); assertNotNull(result4); assertEquals("Bar", result4.getValue()); assertEquals(afterThirdCommit, result4.getPeriod().getLowerBound()); assertEquals(Long.MAX_VALUE, result4.getPeriod().getUpperBound()); GetResult<Object> result5 = tkvs.performRangedGet(tx3, QualifiedKey.createInDefaultKeyspace("Name")); assertNotNull(result5); assertEquals("Jack", result5.getValue()); assertEquals(afterThirdCommit, result5.getPeriod().getLowerBound()); assertEquals(Long.MAX_VALUE, result5.getPeriod().getUpperBound()); GetResult<Object> result6 = tkvs.performRangedGet(tx3, QualifiedKey.createInDefaultKeyspace("Number")); assertNotNull(result6); assertEquals(789, result6.getValue()); assertEquals(afterThirdCommit, result6.getPeriod().getLowerBound()); assertEquals(Long.MAX_VALUE, result6.getPeriod().getUpperBound()); } @Test public void rangedGetBehavesCorrectlyOnNonExistingKeys() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); // make sure that the keyspace exists tx.commit(); TemporalKeyValueStore tkvs = this.getMasterTkvs(db); GetResult<Object> result = tkvs.performRangedGet(tx, QualifiedKey.createInDefaultKeyspace("Fake")); assertNotNull(result); assertNull(result.getValue()); assertEquals(Period.eternal(), result.getPeriod()); } @Test public void rangedGetBehavesCorrectlyOnNonExistingKeyspaces() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); TemporalKeyValueStore tkvs = this.getMasterTkvs(db); GetResult<Object> result = tkvs.performRangedGet(tx, QualifiedKey.createInDefaultKeyspace("Fake")); assertNotNull(result); assertNull(result.getValue()); assertEquals(Period.eternal(), result.getPeriod()); } @Test public void rangedGetBehavesCorrectlyInCombinationWithDeletion() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Name", "Martin"); tx.put("Number", 123); tx.commit(); long afterFirstCommit = tx.getTimestamp(); this.sleep(10); long betweenCommits = System.currentTimeMillis(); this.sleep(10); tx.remove("Hello"); tx.remove("Name"); tx.put("Number", 456); tx.commit(); long afterSecondCommit = tx.getTimestamp(); TemporalKeyValueStore tkvs = this.getMasterTkvs(db); // test the ranges in the cases where there is a lower bound and an upper bound ChronoDBTransaction tx2 = db.tx(betweenCommits); GetResult<Object> result1 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Hello")); assertNotNull(result1); assertEquals("World", result1.getValue()); assertEquals(afterFirstCommit, result1.getPeriod().getLowerBound()); assertEquals(afterSecondCommit, result1.getPeriod().getUpperBound()); GetResult<Object> result2 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Name")); assertNotNull(result2); assertEquals("Martin", result2.getValue()); assertEquals(afterFirstCommit, result2.getPeriod().getLowerBound()); assertEquals(afterSecondCommit, result2.getPeriod().getUpperBound()); GetResult<Object> result3 = tkvs.performRangedGet(tx2, QualifiedKey.createInDefaultKeyspace("Number")); assertNotNull(result3); assertEquals(123, result3.getValue()); assertEquals(afterFirstCommit, result3.getPeriod().getLowerBound()); assertEquals(afterSecondCommit, result3.getPeriod().getUpperBound()); // test the ranges in the cases where there is no upper bound ChronoDBTransaction tx3 = db.tx(afterSecondCommit); GetResult<Object> result4 = tkvs.performRangedGet(tx3, QualifiedKey.createInDefaultKeyspace("Hello")); assertNotNull(result4); assertNull(result4.getValue()); assertEquals(afterSecondCommit, result4.getPeriod().getLowerBound()); assertEquals(Long.MAX_VALUE, result4.getPeriod().getUpperBound()); GetResult<Object> result5 = tkvs.performRangedGet(tx3, QualifiedKey.createInDefaultKeyspace("Name")); assertNotNull(result5); assertNull(result5.getValue()); assertEquals(afterSecondCommit, result5.getPeriod().getLowerBound()); assertEquals(Long.MAX_VALUE, result5.getPeriod().getUpperBound()); GetResult<Object> result6 = tkvs.performRangedGet(tx3, QualifiedKey.createInDefaultKeyspace("Number")); assertNotNull(result6); assertEquals(456, result6.getValue()); assertEquals(afterSecondCommit, result6.getPeriod().getLowerBound()); assertEquals(Long.MAX_VALUE, result6.getPeriod().getUpperBound()); } }
9,697
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetModifiedKeysTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/versioning/GetModifiedKeysTest.java
package org.chronos.chronodb.test.cases.engine.versioning; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.chronos.chronodb.api.*; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Iterator; import java.util.List; import java.util.function.Function; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class GetModifiedKeysTest extends AllChronoDBBackendsTest { @Test public void emptyKeyspaceProducesEmptyIterator() { ChronoDB db = this.getChronoDB(); // create some data, just to ensure that the "now" timestamp is non-zero ChronoDBTransaction tx1 = db.tx(); tx1.put("Hello", "World"); tx1.commit(); // try to retrieve the modified keys from a non-existing keyspace Iterator<TemporalKey> iterator = db.tx().getModificationsInKeyspaceBetween("pseudoKeyspace", 0, db.tx().getTimestamp()); // the iterator must not be null... assertNotNull(iterator); // ... but it must be empty assertFalse(iterator.hasNext()); } @Test public void retrievingSingleCommitAsResultWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("myKeyspace", "Hello", "World"); tx1.commit(); // try to retrieve the timestamp of the commit we just performed Iterator<TemporalKey> iterator = db.tx().getModificationsInKeyspaceBetween("myKeyspace", 0, db.tx().getTimestamp()); assertNotNull(iterator); List<TemporalKey> iteratorContents = Lists.newArrayList(iterator); assertEquals(1, iteratorContents.size()); TemporalKey modifiedKey = Iterables.getOnlyElement(iteratorContents); assertNotNull(modifiedKey); assertEquals(tx1.getTimestamp(), modifiedKey.getTimestamp()); assertEquals("myKeyspace", modifiedKey.getKeyspace()); assertEquals("Hello", modifiedKey.getKey()); } @Test public void retrievingMultipleCommitsWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("myKeyspace", "np1", NamedPayload.create1KB("NP1")); tx1.put("myKeyspace", "np2", NamedPayload.create1KB("NP2")); tx1.put("yourKeyspace", "np1", NamedPayload.create1KB("NP1")); tx1.put("yourKeyspace", "np2", NamedPayload.create1KB("NP2")); tx1.commit(); long afterTx1 = tx1.getTimestamp(); this.sleep(5); ChronoDBTransaction tx2 = db.tx(); tx2.put("myKeyspace", "np1", NamedPayload.create1KB("NP1a")); tx2.put("myKeyspace", "np3", NamedPayload.create1KB("NP3")); tx2.commit(); long afterTx2 = tx2.getTimestamp(); this.sleep(5); ChronoDBTransaction tx3 = db.tx(); tx3.put("myKeyspace", "np1", NamedPayload.create1KB("NP1b")); tx3.put("yourKeyspace", "np3", NamedPayload.create1KB("NP3")); tx3.commit(); long afterTx3 = tx3.getTimestamp(); List<TemporalKey> zeroTo2InMyKeyspace = Lists.newArrayList(db.tx().getModificationsInKeyspaceBetween("myKeyspace", 0, afterTx2)); assertEquals(4, zeroTo2InMyKeyspace.size()); assertTrue(zeroTo2InMyKeyspace.contains(TemporalKey.create(afterTx1, "myKeyspace", "np1"))); assertTrue(zeroTo2InMyKeyspace.contains(TemporalKey.create(afterTx1, "myKeyspace", "np2"))); assertTrue(zeroTo2InMyKeyspace.contains(TemporalKey.create(afterTx2, "myKeyspace", "np1"))); assertTrue(zeroTo2InMyKeyspace.contains(TemporalKey.create(afterTx2, "myKeyspace", "np3"))); List<TemporalKey> zeroTo3InMyKeyspace = Lists.newArrayList(db.tx().getModificationsInKeyspaceBetween("myKeyspace", 0, afterTx3)); assertEquals(5, zeroTo3InMyKeyspace.size()); assertTrue(zeroTo3InMyKeyspace.contains(TemporalKey.create(afterTx1, "myKeyspace", "np1"))); assertTrue(zeroTo3InMyKeyspace.contains(TemporalKey.create(afterTx1, "myKeyspace", "np2"))); assertTrue(zeroTo3InMyKeyspace.contains(TemporalKey.create(afterTx2, "myKeyspace", "np1"))); assertTrue(zeroTo3InMyKeyspace.contains(TemporalKey.create(afterTx2, "myKeyspace", "np3"))); assertTrue(zeroTo3InMyKeyspace.contains(TemporalKey.create(afterTx3, "myKeyspace", "np1"))); List<TemporalKey> twoTo3InMyKeyspace = Lists.newArrayList(db.tx().getModificationsInKeyspaceBetween("myKeyspace", afterTx2, afterTx3)); assertEquals(3, twoTo3InMyKeyspace.size()); assertTrue(twoTo3InMyKeyspace.contains(TemporalKey.create(afterTx2, "myKeyspace", "np1"))); assertTrue(twoTo3InMyKeyspace.contains(TemporalKey.create(afterTx2, "myKeyspace", "np3"))); assertTrue(twoTo3InMyKeyspace.contains(TemporalKey.create(afterTx3, "myKeyspace", "np1"))); List<TemporalKey> exactly3InMyKeyspace = Lists.newArrayList(db.tx().getModificationsInKeyspaceBetween("myKeyspace", afterTx3, afterTx3)); assertEquals(1, exactly3InMyKeyspace.size()); assertTrue(exactly3InMyKeyspace.contains(TemporalKey.create(afterTx3, "myKeyspace", "np1"))); } @Test public void retrievingMultipleCommitsOnMultipleBranchesWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("myKeyspace", "np1", NamedPayload.create1KB("NP1")); tx1.put("myKeyspace", "np2", NamedPayload.create1KB("NP2")); tx1.put("yourKeyspace", "np1", NamedPayload.create1KB("NP1")); tx1.put("yourKeyspace", "np2", NamedPayload.create1KB("NP2")); tx1.commit(); long afterTx1 = tx1.getTimestamp(); this.sleep(5); BranchManager branchManager = db.getBranchManager(); Branch b0 = branchManager.createBranch(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, "b0"); this.sleep(5); ChronoDBTransaction tx2 = db.tx(b0.getName()); tx2.put("myKeyspace", "np1", NamedPayload.create1KB("NP1b0")); tx2.put("myKeyspace", "np3", NamedPayload.create1KB("NP3b0")); tx2.commit(); long afterTx2 = tx2.getTimestamp(); this.sleep(5); Branch b1 = branchManager.createBranch(b0.getName(), "b1"); this.sleep(5); ChronoDBTransaction tx4 = db.tx(b0.getName()); // should not be visible tx4.put("myKeyspace", "np4", NamedPayload.create1KB("NP4b0")); tx4.put("yourKeyspace", "np4", NamedPayload.create1KB("NP4b0")); tx4.commit(); this.sleep(5); ChronoDBTransaction tx3 = db.tx(b1.getName()); tx3.put("myKeyspace", "np1", NamedPayload.create1KB("NP1b1")); tx3.put("yourKeyspace", "np3", NamedPayload.create1KB("NP3b1")); tx3.commit(); long afterTx3 = tx3.getTimestamp(); List<TemporalKey> modificationsBetween = Lists.newArrayList(db.tx(b1.getName()).getModificationsInKeyspaceBetween("myKeyspace", 0, afterTx3)); assertEquals(5, modificationsBetween.size()); assertTrue(modificationsBetween.contains(TemporalKey.create(afterTx1, "myKeyspace", "np1"))); assertTrue(modificationsBetween.contains(TemporalKey.create(afterTx1, "myKeyspace", "np2"))); assertTrue(modificationsBetween.contains(TemporalKey.create(afterTx2, "myKeyspace", "np1"))); assertTrue(modificationsBetween.contains(TemporalKey.create(afterTx2, "myKeyspace", "np3"))); assertTrue(modificationsBetween.contains(TemporalKey.create(afterTx3, "myKeyspace", "np1"))); } }
7,747
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
VersioningTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/versioning/VersioningTest.java
package org.chronos.chronodb.test.cases.engine.versioning; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class VersioningTest extends AllChronoDBBackendsTest { @Test public void testSimpleRW() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("First", 123); tx.put("Second", 456); tx.commit(); long writeTimestamp = tx.getTimestamp(); this.sleep(5); tx.put("Third", 789); tx.commit(); ChronoDBTransaction txBefore = db.tx(0L); assertEquals(false, txBefore.exists("First")); assertEquals(false, txBefore.exists("Second")); assertNull(txBefore.get("First")); assertNull(txBefore.get("Second")); assertEquals(false, txBefore.history("First").hasNext()); assertEquals(false, txBefore.history("Second").hasNext()); assertEquals(true, txBefore.keySet().isEmpty()); ChronoDBTransaction txExact = db.tx(writeTimestamp); assertTrue(txExact.exists("First")); assertTrue(txExact.exists("Second")); assertEquals(123, (int) txExact.get("First")); assertEquals(456, (int) txExact.get("Second")); assertEquals(1, Iterators.size(txExact.history("First"))); assertEquals(1, Iterators.size(txExact.history("Second"))); assertEquals(writeTimestamp, (long) txExact.history("First").next()); assertEquals(writeTimestamp, (long) txExact.history("Second").next()); assertEquals(2, txExact.keySet().size()); ChronoDBTransaction txAfter = db.tx(writeTimestamp + 1); assertTrue(txAfter.exists("First")); assertTrue(txAfter.exists("Second")); assertEquals(123, (int) txAfter.get("First")); assertEquals(456, (int) txAfter.get("Second")); assertEquals(1, Iterators.size(txAfter.history("First"))); assertEquals(1, Iterators.size(txAfter.history("Second"))); assertEquals(writeTimestamp, (long) txAfter.history("First").next()); assertEquals(writeTimestamp, (long) txAfter.history("Second").next()); assertEquals(2, txAfter.keySet().size()); } @Test public void testOverrideOnce() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("First", 123); tx1.put("Second", 456); tx1.commit(); long writeTimestamp1 = tx1.getTimestamp(); this.sleep(5); ChronoDBTransaction tx2 = db.tx(); tx2.put("First", 47); tx2.commit(); long writeTimestamp2 = tx2.getTimestamp(); this.sleep(5); tx2.put("Third", 789); tx2.commit(); { // BEFORE ChronoDBTransaction tx = db.tx(0L); assertEquals(false, tx.exists("First")); assertEquals(false, tx.exists("Second")); assertNull(tx.get("First")); assertNull(tx.get("Second")); assertEquals(false, tx.history("First").hasNext()); assertEquals(false, tx.history("Second").hasNext()); assertEquals(true, tx.keySet().isEmpty()); } { // EXACTLY AT WRITE 1 ChronoDBTransaction tx = db.tx(writeTimestamp1); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(123, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); assertEquals(1, Iterators.size(tx.history("First"))); assertEquals(1, Iterators.size(tx.history("Second"))); assertEquals(writeTimestamp1, (long) tx.history("First").next()); assertEquals(writeTimestamp1, (long) tx.history("Second").next()); assertEquals(2, tx.keySet().size()); } { // BETWEEN WRITES ChronoDBTransaction tx = db.tx(writeTimestamp1 + 1); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(123, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); assertEquals(1, Iterators.size(tx.history("First"))); assertEquals(1, Iterators.size(tx.history("Second"))); assertEquals(writeTimestamp1, (long) tx.history("First").next()); assertEquals(writeTimestamp1, (long) tx.history("Second").next()); assertEquals(2, tx.keySet().size()); } { // EXACTLY AT WRITE 2 ChronoDBTransaction tx = db.tx(writeTimestamp2); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(47, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); assertEquals(2, Iterators.size(tx.history("First"))); assertEquals(1, Iterators.size(tx.history("Second"))); Iterator<Long> iterator = tx.history("First"); List<Long> timestamps = Lists.newArrayList(iterator); assertEquals(2, timestamps.size()); assertTrue(timestamps.contains(writeTimestamp1)); assertTrue(timestamps.contains(writeTimestamp2)); assertEquals(writeTimestamp1, (long) tx.history("Second").next()); assertEquals(2, tx.keySet().size()); } { // AFTER WRITE 2 ChronoDBTransaction tx = db.tx(writeTimestamp2 + 1); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(47, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); Iterator<Long> iterator = tx.history("First"); List<Long> timestamps = Lists.newArrayList(iterator); assertEquals(2, timestamps.size()); assertTrue(timestamps.contains(writeTimestamp1)); assertTrue(timestamps.contains(writeTimestamp2)); assertEquals(writeTimestamp1, (long) tx.history("Second").next()); assertEquals(2, tx.keySet().size()); } // wait for a bit to ensure that the operation is complete this.sleep(5); { // NOW ChronoDBTransaction tx = db.tx(); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(47, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); Iterator<Long> iterator = tx.history("First"); List<Long> timestamps = Lists.newArrayList(iterator); assertEquals(2, timestamps.size()); assertTrue(timestamps.contains(writeTimestamp1)); assertTrue(timestamps.contains(writeTimestamp2)); assertEquals(writeTimestamp1, (long) tx.history("Second").next()); // this includes the "third" key assertEquals(3, tx.keySet().size()); } } @Test public void testOverrideMany() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("First", 123); tx1.put("Second", 456); tx1.commit(); sleep(5); // overwrite "First" value 10 times List<Long> writeTimestamps = Lists.newArrayList(); int value = 123; for (int i = 0; i < 11; i++) { ChronoDBTransaction tx = db.tx(); value++; tx.put("First", value); tx.commit(); writeTimestamps.add(tx.getTimestamp()); sleep(5); } {// BEFORE ChronoDBTransaction tx = db.tx(0L); assertEquals(false, tx.exists("First")); assertEquals(false, tx.exists("Second")); assertNull(tx.get("First")); assertNull(tx.get("Second")); assertEquals(false, tx.history("First").hasNext()); assertEquals(false, tx.history("Second").hasNext()); assertEquals(true, tx.keySet().isEmpty()); } // check the remaining timestamps for (int i = 0; i < 10; i++) { long timestamp = writeTimestamps.get(i); System.out.println("Investigating timestamp #" + i + " (" + timestamp + ")..."); {// BEFORE ChronoDBTransaction tx = db.tx(timestamp - 1); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(123 + i, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); assertEquals(i + 1, Iterators.size(tx.history("First"))); assertEquals(1, Iterators.size(tx.history("Second"))); assertEquals(2, tx.keySet().size()); } {// EXACT ChronoDBTransaction tx = db.tx(timestamp); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(123 + i + 1, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); assertEquals(i + 2, Iterators.size(tx.history("First"))); assertEquals(1, Iterators.size(tx.history("Second"))); assertEquals(2, tx.keySet().size()); } {// AFTER ChronoDBTransaction tx = db.tx(timestamp + 1); assertTrue(tx.exists("First")); assertTrue(tx.exists("Second")); assertEquals(123 + i + 1, (int) tx.get("First")); assertEquals(456, (int) tx.get("Second")); assertEquals(i + 2, Iterators.size(tx.history("First"))); assertEquals(1, Iterators.size(tx.history("Second"))); assertEquals(2, tx.keySet().size()); } } } @Test public void canLimitHistory(){ ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("First", 123); tx1.put("Second", 456); tx1.commit(); sleep(5); // overwrite "First" value 10 times List<Long> writeTimestamps = Lists.newArrayList(); int value = 123; for (int i = 0; i < 11; i++) { ChronoDBTransaction tx = db.tx(); value++; tx.put("First", value); tx.commit(); writeTimestamps.add(tx.getTimestamp()); sleep(5); } assertEquals(9, Iterators.size(db.tx().history("First", 0, writeTimestamps.get(7)))); assertEquals(5, Iterators.size(db.tx().history("First", writeTimestamps.get(3), writeTimestamps.get(7)))); assertEquals(8, Iterators.size(db.tx().history("First", writeTimestamps.get(3), db.tx().getTimestamp()))); assertEquals(10, Iterators.size(db.tx().history("First", writeTimestamps.get(0), writeTimestamps.get(9)))); } @Test public void canChangeHistoryOrdering(){ ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("First", 123); tx1.put("Second", 456); tx1.commit(); sleep(5); // overwrite "First" value 10 times List<Long> writeTimestamps = Lists.newArrayList(); int value = 123; for (int i = 0; i < 11; i++) { ChronoDBTransaction tx = db.tx(); value++; tx.put("First", value); tx.commit(); writeTimestamps.add(tx.getTimestamp()); sleep(5); } assertThat( Lists.newArrayList(db.tx().history("First", writeTimestamps.get(0), writeTimestamps.get(2), Order.ASCENDING)), contains( writeTimestamps.get(0), writeTimestamps.get(1), writeTimestamps.get(2) ) ); assertThat( Lists.newArrayList(db.tx().history("First", writeTimestamps.get(0), writeTimestamps.get(2), Order.DESCENDING)), contains( writeTimestamps.get(2), writeTimestamps.get(1), writeTimestamps.get(0) ) ); } @Test public void canQueryHistoryAcrossBranches(){ ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("a", 1); tx1.put("b", 1); long commit1 = tx1.commit(); db.getBranchManager().createBranch("b1"); ChronoDBTransaction tx2 = db.tx("b1"); tx2.put("a", 2); tx2.put("c", 1); long commit2 = tx2.commit(); // do another transaction on master after branching away ChronoDBTransaction tx3 = db.tx(); tx3.put("z", 1); tx3.remove("a"); tx3.commit(); db.getBranchManager().createBranch("b1", "b2"); ChronoDBTransaction tx4 = db.tx("b2"); tx4.remove("a"); tx4.put("b", 2); tx4.put("d", 1); long commit4 = tx4.commit(); // do another transaction on b1 ChronoDBTransaction tx5 = db.tx("b1"); tx5.put("y", 1); tx5.remove("b"); tx5.commit(); // create a new branch that contains nothing db.getBranchManager().createBranch("b2", "b3"); // query the history of "a" on b2 assertThat(Lists.newArrayList(db.tx("b3").history("a")), contains(commit4, commit2, commit1)); // query in ascending order assertThat(Lists.newArrayList(db.tx("b3").history("a", Order.ASCENDING)), contains(commit1, commit2, commit4)); // query history with bounds assertThat(Lists.newArrayList(db.tx("b3").history("a", commit1, commit2, Order.DESCENDING)), contains(commit2, commit1)); assertThat(Lists.newArrayList(db.tx("b3").history("a", commit1, commit2, Order.ASCENDING)), contains(commit1, commit2)); } }
14,338
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
KeyspaceTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/keyspace/KeyspaceTest.java
package org.chronos.chronodb.test.cases.engine.keyspace; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.List; import java.util.Set; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class KeyspaceTest extends AllChronoDBBackendsTest { @Test public void creatingAndReadingAKeyspaceWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); // initially, only the default keyspace exists assertEquals(1, tx.keyspaces().size()); assertEquals(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, Iterables.getOnlyElement(tx.keyspaces())); // put something into a variety of keyspaces (which dynamically creates them on the fly) tx.put("Programs", "Eclipse", "IBM"); tx.put("Programs", "VisualStudio", "Microsoft"); tx.put("OperatingSystems", "Windows 8", "Microsoft"); tx.put("OperatingSystems", "Windows XP", "Microsoft"); tx.put("OperatingSystems", "Ubuntu", "Canonical"); tx.put("OperatingSystems", "OSX", "Apple"); tx.commit(); // the default keyspace should be empty (we added nothing to it) assertTrue(tx.keySet().isEmpty()); // the "Programs" keyspace should contain 2 entries assertEquals(2, tx.keySet("Programs").size()); // the "OperatingSystems" keyspace should contain 4 entries assertEquals(4, tx.keySet("OperatingSystems").size()); // using the default keyspace, none of our keys works assertNull(tx.get("Eclipse")); assertNull(tx.get("VisualStudio")); assertNull(tx.get("Windows 8")); assertNull(tx.get("Windows XP")); assertNull(tx.get("Ubuntu")); assertNull(tx.get("OSX")); assertEquals(false, tx.exists("Eclipse")); assertEquals(false, tx.exists("VisualStudio")); assertEquals(false, tx.exists("Windows 8")); assertEquals(false, tx.exists("Windows XP")); assertEquals(false, tx.exists("Ubuntu")); assertEquals(false, tx.exists("OSX")); // assert that the "Programs" keyspace contains the correct entries assertEquals("IBM", tx.get("Programs", "Eclipse")); assertEquals("Microsoft", tx.get("Programs", "VisualStudio")); assertNull(tx.get("Programs", "Windows 8")); assertNull(tx.get("Programs", "Windows XP")); assertNull(tx.get("Programs", "Ubuntu")); assertNull(tx.get("Programs", "OSX")); assertEquals(true, tx.exists("Programs", "Eclipse")); assertEquals(true, tx.exists("Programs", "VisualStudio")); assertEquals(false, tx.exists("Programs", "Windows 8")); assertEquals(false, tx.exists("Programs", "Windows XP")); assertEquals(false, tx.exists("Programs", "Ubuntu")); assertEquals(false, tx.exists("Programs", "OSX")); // assert that the "OperatingSystems" keyspace contains the correct entries assertNull(tx.get("OperatingSystems", "Eclipse")); assertNull(tx.get("OperatingSystems", "VisualStudio")); assertEquals("Microsoft", tx.get("OperatingSystems", "Windows 8")); assertEquals("Microsoft", tx.get("OperatingSystems", "Windows XP")); assertEquals("Canonical", tx.get("OperatingSystems", "Ubuntu")); assertEquals("Apple", tx.get("OperatingSystems", "OSX")); assertEquals(false, tx.exists("OperatingSystems", "Eclipse")); assertEquals(false, tx.exists("OperatingSystems", "VisualStudio")); assertEquals(true, tx.exists("OperatingSystems", "Windows 8")); assertEquals(true, tx.exists("OperatingSystems", "Windows XP")); assertEquals(true, tx.exists("OperatingSystems", "Ubuntu")); assertEquals(true, tx.exists("OperatingSystems", "OSX")); } @Test @DontRunWithBackend("jdbc") // H2 sometimes deadlocks here; H2 is at fault here, not chronodb. public void parallelRequestsToKeysetWork() { ChronoDB db = this.getChronoDB(); String keyspace = "myKeyspace"; int datasetSize = 10_000; { // insert test data ChronoDBTransaction tx = db.tx(); for (int i = 0; i < datasetSize; i++) { tx.put(keyspace, "" + i, i); } tx.commit(); } int threadCount = 15; Set<Thread> threads = Sets.newHashSet(); List<Throwable> exceptions = Collections.synchronizedList(Lists.newArrayList()); List<Thread> successfullyTerminatedThreads = Collections.synchronizedList(Lists.newArrayList()); for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(() -> { try { Set<String> keySet = db.tx().keySet(keyspace); assertEquals(datasetSize, keySet.size()); successfullyTerminatedThreads.add(Thread.currentThread()); } catch (Throwable t) { System.err.println("Error in Thread [" + Thread.currentThread().getName() + "]"); t.printStackTrace(); exceptions.add(t); } }); thread.setName("ReadWorker" + i); threads.add(thread); thread.start(); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { throw new RuntimeException("Waiting for thread was interrupted.", e); } } assertTrue(exceptions.isEmpty()); assertEquals(threadCount, successfullyTerminatedThreads.size()); } }
6,088
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CountCommitsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/commitmetadata/CountCommitsTest.java
package org.chronos.chronodb.test.cases.engine.commitmetadata; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.junit.Test; import static org.junit.Assert.*; public class CountCommitsTest extends AllChronoDBBackendsTest { @Test public void retrievingInvalidTimeRangeProducesZero() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(); // check assertEquals(1, tx.countCommitTimestamps()); assertEquals(0, tx.countCommitTimestampsBetween(1, 0)); assertEquals(0, tx.countCommitTimestampsBetween(tx.getTimestamp(), 0)); } @Test public void canCountCommitTimestampWhenNoMetadataIsGiven() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(); // check long now = tx.getTimestamp(); assertEquals(1, tx.countCommitTimestamps()); assertEquals(1, tx.countCommitTimestampsBetween(0L, now)); } @Test public void canCountCommitsWithAndWithoutMetadata() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("Initial Commit"); final long commit1 = tx.getTimestamp(); tx.put("Hello", "Test"); tx.commit(); final long commit2 = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Foobar"); final long commit3 = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit(); final long commit4 = tx.getTimestamp(); assertEquals(4, tx.countCommitTimestamps()); assertEquals(2, tx.countCommitTimestampsBetween(commit2, commit3)); assertEquals(3, tx.countCommitTimestampsBetween(commit1, commit3)); assertEquals(4, tx.countCommitTimestampsBetween(0, commit4)); } @Test public void countingCommitTimestampsIsBranchLocal() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("Initial Commit"); db.getBranchManager().createBranch("Test"); long branchingTimestamp = db.getBranchManager().getBranch("Test").getBranchingTimestamp(); tx = db.tx("Test"); tx.put("Foo", "Bar"); tx.commit("New Branch!"); final long commit2 = tx.getTimestamp(); tx = db.tx(); tx.put("Pi", "3.1415"); tx.commit(); final long commit3 = tx.getTimestamp(); // we should have two commits on 'master' (the first one and the last one) assertEquals(2, db.tx().countCommitTimestamps()); assertEquals(2, db.tx().countCommitTimestampsBetween(0, commit3)); // we should have one commit on 'Test' assertEquals(1, db.tx("Test").countCommitTimestamps()); assertEquals(1, db.tx("Test").countCommitTimestampsBetween(branchingTimestamp, commit2)); } }
3,113
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetCommitsBetweenPagedTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/commitmetadata/GetCommitsBetweenPagedTest.java
package org.chronos.chronodb.test.cases.engine.commitmetadata; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.junit.Test; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Set; import static org.junit.Assert.*; public class GetCommitsBetweenPagedTest extends AllChronoDBBackendsTest { @Test public void retrievingInvalidTimeRangeProducesAnEmptyIterator() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(); // check long now = tx.getTimestamp(); assertEquals(1, Iterators.size(tx.getCommitTimestampsPaged(0, now, 1, 0, Order.ASCENDING))); assertEquals(1, Iterators.size(tx.getCommitMetadataPaged(0, now, 1, 0, Order.ASCENDING))); assertEquals(0, Iterators.size(tx.getCommitTimestampsPaged(now, 0, 1, 0, Order.ASCENDING))); assertEquals(0, Iterators.size(tx.getCommitMetadataPaged(now, 0, 1, 0, Order.ASCENDING))); } @Test public void canRetrieveCommitsWhenNoMetadataWasGiven() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(); long now = tx.getTimestamp(); assertEquals(1, Iterators.size(tx.getCommitTimestampsPaged(0, now, 1, 0, Order.ASCENDING))); assertEquals(1, Iterators.size(tx.getCommitMetadataPaged(0, now, 1, 0, Order.ASCENDING))); } @Test public void canRetrieveCommitsWithAndWithoutMetadata() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("Initial Commit"); final long commit1 = tx.getTimestamp(); tx.put("Hello", "Test"); tx.commit(); final long commit2 = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Foobar"); final long commit3 = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit(); final long commit4 = tx.getTimestamp(); NavigableMap<Long, Object> expectedResult = Maps.newTreeMap(); expectedResult.put(commit1, "Initial Commit"); expectedResult.put(commit2, null); expectedResult.put(commit3, "Foobar"); expectedResult.put(commit4, null); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true).descendingKeySet(), // actual toSet(tx.getCommitTimestampsPaged(commit2, commit4, 4, 0, Order.DESCENDING))); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true).keySet(), // actual toSet(tx.getCommitTimestampsPaged(commit2, commit4, 4, 0, Order.ASCENDING))); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true).descendingMap(), // actual toMap(tx.getCommitMetadataPaged(commit2, commit4, 4, 0, Order.DESCENDING))); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true), // actual toMap(tx.getCommitMetadataPaged(commit2, commit4, 4, 0, Order.ASCENDING))); } @Test public void retrievingCommitTimestampsIsBranchLocal() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("Initial Commit"); db.getBranchManager().createBranch("Test"); long branchingTimestamp = db.getBranchManager().getBranch("Test").getBranchingTimestamp(); tx = db.tx("Test"); tx.put("Foo", "Bar"); tx.commit("New Branch!"); final long commit2 = tx.getTimestamp(); tx = db.tx(); tx.put("Pi", "3.1415"); tx.commit(); final long commit3 = tx.getTimestamp(); // we should have two commits on 'master' (the first one and the last one) assertEquals(2, Iterators.size(db.tx().getCommitTimestampsPaged(0, commit3, 4, 0, Order.ASCENDING))); assertEquals(2, Iterators.size(db.tx().getCommitMetadataPaged(0, commit3, 4, 0, Order.ASCENDING))); // we should have one commit on 'Test' assertEquals(1, Iterators .size(db.tx("Test").getCommitTimestampsPaged(branchingTimestamp, commit2, 4, 0, Order.ASCENDING))); assertEquals(1, Iterators .size(db.tx("Test").getCommitMetadataPaged(branchingTimestamp, commit2, 4, 0, Order.ASCENDING))); } @Test public void ascendingPaginationWorks() { ChronoDB db = this.getChronoDB(); // do 20 commits on the database List<Long> commitTimestamps = Lists.newArrayList(); for (int i = 0; i < 20; i++) { ChronoDBTransaction tx = db.tx(); tx.put("test", i); // attach the iteration as metadata to the commit tx.commit(i); commitTimestamps.add(tx.getTimestamp()); } // query the metadata List<Entry<Long, Object>> entriesPage; List<Long> timestampsPage; // first page entriesPage = toList(db.tx().getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 0, Order.ASCENDING)); timestampsPage = toList(db.tx().getCommitTimestampsPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 0, Order.ASCENDING)); assertEquals(5, entriesPage.size()); for (int i = 0; i < 5; i++) { assertEquals(commitTimestamps.get(2 + i), entriesPage.get(i).getKey()); assertEquals(2 + i, entriesPage.get(i).getValue()); assertEquals(commitTimestamps.get(2 + i), timestampsPage.get(i)); } // page from the middle entriesPage = toList(db.tx().getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 2, Order.ASCENDING)); timestampsPage = toList(db.tx().getCommitTimestampsPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 2, Order.ASCENDING)); assertEquals(5, entriesPage.size()); for (int i = 0; i < 5; i++) { assertEquals(commitTimestamps.get(12 + i), entriesPage.get(i).getKey()); assertEquals(12 + i, entriesPage.get(i).getValue()); assertEquals(commitTimestamps.get(12 + i), timestampsPage.get(i)); } // last page (which is incomplete because there are no 5 entries left) entriesPage = toList(db.tx().getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 3, Order.ASCENDING)); timestampsPage = toList(db.tx().getCommitTimestampsPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 3, Order.ASCENDING)); assertEquals(2, entriesPage.size()); for (int i = 0; i < 2; i++) { assertEquals(commitTimestamps.get(17 + i), entriesPage.get(i).getKey()); assertEquals(17 + i, entriesPage.get(i).getValue()); assertEquals(commitTimestamps.get(17 + i), timestampsPage.get(i)); } } @Test public void descendingPaginationWorks() { ChronoDB db = this.getChronoDB(); // do 20 commits on the database List<Long> commitTimestamps = Lists.newArrayList(); for (int i = 0; i < 20; i++) { ChronoDBTransaction tx = db.tx(); tx.put("test", i); // attach the iteration as metadata to the commit tx.commit(i); commitTimestamps.add(tx.getTimestamp()); } // query the metadata List<Entry<Long, Object>> entriesPage; List<Long> timestampsPage; // first page entriesPage = toList(db.tx().getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 0, Order.DESCENDING)); timestampsPage = toList(db.tx().getCommitTimestampsPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 0, Order.DESCENDING)); assertEquals(5, entriesPage.size()); for (int i = 0; i < 5; i++) { assertEquals(commitTimestamps.get(18 - i), entriesPage.get(i).getKey()); assertEquals(18 - i, entriesPage.get(i).getValue()); assertEquals(commitTimestamps.get(18 - i), timestampsPage.get(i)); } // page from the middle entriesPage = toList(db.tx().getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 2, Order.DESCENDING)); timestampsPage = toList(db.tx().getCommitTimestampsPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 2, Order.DESCENDING)); assertEquals(5, entriesPage.size()); for (int i = 0; i < 5; i++) { assertEquals(commitTimestamps.get(8 - i), entriesPage.get(i).getKey()); assertEquals(8 - i, entriesPage.get(i).getValue()); assertEquals(commitTimestamps.get(8 - i), timestampsPage.get(i)); } // last page (which is incomplete because there are no 5 entries left) entriesPage = toList(db.tx().getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 3, Order.DESCENDING)); timestampsPage = toList(db.tx().getCommitTimestampsPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 3, Order.DESCENDING)); assertEquals(2, entriesPage.size()); for (int i = 0; i < 2; i++) { assertEquals(commitTimestamps.get(3 - i), entriesPage.get(i).getKey()); assertEquals(3 - i, entriesPage.get(i).getValue()); assertEquals(commitTimestamps.get(3 - i), timestampsPage.get(i)); } } // ===================================================================================================================== // HELPER METHODS // ===================================================================================================================== private static <A, B> Map<A, B> toMap(final Iterator<Entry<A, B>> iterator) { Map<A, B> resultMap = new LinkedHashMap<>(); while (iterator.hasNext()) { Entry<A, B> entry = iterator.next(); resultMap.put(entry.getKey(), entry.getValue()); } return resultMap; } private static <A> Set<A> toSet(final Iterator<A> iterator) { Set<A> resultSet = new LinkedHashSet<>(); while (iterator.hasNext()) { resultSet.add(iterator.next()); } return resultSet; } private static <A> List<A> toList(final Iterator<A> iterator) { List<A> resultList = Lists.newArrayList(); iterator.forEachRemaining(element -> resultList.add(element)); return resultList; } }
11,191
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BasicCommitMetadataTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/commitmetadata/BasicCommitMetadataTest.java
package org.chronos.chronodb.test.cases.engine.commitmetadata; import com.google.common.collect.Maps; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Map; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class BasicCommitMetadataTest extends AllChronoDBBackendsTest { @Test public void simpleStoringAndRetrievingMetadataWorks() { ChronoDB db = this.getChronoDB(); // just a message that we can compare later on String commitMessage = "Hey there, Hello World!"; // insert data into the database ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(commitMessage); // record the commit timestamp long timestamp = tx.getTimestamp(); // read the metadata and assert that it's correct assertEquals(commitMessage, db.tx().getCommitMetadata(timestamp)); } @Test public void readingCommitMetadataFromNonExistingCommitTimestampsProducesNull() { ChronoDB db = this.getChronoDB(); // insert data into the database ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("Hello World!"); // read commit metadata from a non-existing (but valid) commit timestamp assertNull(db.tx().getCommitMetadata(0L)); } @Test public void readingCommitMetadataRetrievesCorrectObject() { ChronoDB db = this.getChronoDB(); // the commit messages, as constants to compare with later on final String commitMessage1 = "Hello World!"; final String commitMessage2 = "Foo Bar"; final String commitMessage3 = "Chronos is awesome"; // insert data into the database ChronoDBTransaction tx1 = db.tx(); tx1.put("Hello", "World"); tx1.commit(commitMessage1); // record the commit timestamp long timeCommit1 = tx1.getTimestamp(); this.sleep(5); // ... and another record ChronoDBTransaction tx2 = db.tx(); tx2.put("Foo", "Bar"); tx2.commit(commitMessage2); // record the commit timestamp long timeCommit2 = tx2.getTimestamp(); this.sleep(5); // ... and yet another record ChronoDBTransaction tx3 = db.tx(); tx3.put("Chronos", "IsAwesome"); tx3.commit(commitMessage3); // record the commit timestamp long timeCommit3 = tx3.getTimestamp(); this.sleep(5); // now, retrieve the three messages individually assertEquals(commitMessage1, db.tx().getCommitMetadata(timeCommit1)); assertEquals(commitMessage2, db.tx().getCommitMetadata(timeCommit2)); assertEquals(commitMessage3, db.tx().getCommitMetadata(timeCommit3)); } @Test public void readingCommitMessagesFromOriginBranchWorks() { ChronoDB db = this.getChronoDB(); // the commit messages, as constants to compare with later on final String commitMessage1 = "Hello World!"; final String commitMessage2 = "Foo Bar"; // insert data into the database ChronoDBTransaction tx1 = db.tx(); tx1.put("Hello", "World"); tx1.commit(commitMessage1); // record the commit timestamp long timeCommit1 = tx1.getTimestamp(); this.sleep(5); // create the branch db.getBranchManager().createBranch("MyBranch"); // commit something to the branch ChronoDBTransaction tx2 = db.tx("MyBranch"); tx2.put("Foo", "Bar"); tx2.commit(commitMessage2); // record the commit timestamp long timeCommit2 = tx2.getTimestamp(); // open a transaction on the branch and request the commit message of tx1 assertEquals(commitMessage1, db.tx("MyBranch").getCommitMetadata(timeCommit1)); // also, we should be able to get the commit metadata of the branch assertEquals(commitMessage2, db.tx("MyBranch").getCommitMetadata(timeCommit2)); } @Test public void canUseHashMapAsCommitMetadata() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); Map<String, String> commitMap = Maps.newHashMap(); commitMap.put("User", "Martin"); commitMap.put("Mood", "Good"); commitMap.put("Mail", "martin.haeusler@uibk.ac.at"); tx.commit(commitMap); long timestamp = tx.getTimestamp(); // get the commit map @SuppressWarnings("unchecked") Map<String, String> retrieved = (Map<String, String>) db.tx().getCommitMetadata(timestamp); // assert that the maps are equal assertNotNull(retrieved); assertEquals(commitMap, retrieved); } }
5,009
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetCommitsBetweenTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/commitmetadata/GetCommitsBetweenTest.java
package org.chronos.chronodb.test.cases.engine.commitmetadata; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.junit.Test; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Set; import static org.junit.Assert.*; public class GetCommitsBetweenTest extends AllChronoDBBackendsTest { @Test public void retrievingInvalidTimeRangeProducesAnEmptyIterator() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(); // check long now = tx.getTimestamp(); assertEquals(1, Iterators.size(tx.getCommitTimestampsBetween(0, now))); assertEquals(1, Iterators.size(tx.getCommitMetadataBetween(0, now))); assertEquals(0, Iterators.size(tx.getCommitTimestampsBetween(now, 0))); assertEquals(0, Iterators.size(tx.getCommitMetadataBetween(now, 0))); } @Test public void canRetrieveCommitsWhenNoMetadataWasGiven() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit(); long now = tx.getTimestamp(); assertEquals(1, Iterators.size(tx.getCommitTimestampsBetween(0, now))); assertEquals(1, Iterators.size(tx.getCommitMetadataBetween(0, now))); } @Test public void canRetrieveCommitsWithAndWithoutMetadata() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("Initial Commit"); final long commit1 = tx.getTimestamp(); tx.put("Hello", "Test"); tx.commit(); final long commit2 = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Foobar"); final long commit3 = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit(); final long commit4 = tx.getTimestamp(); NavigableMap<Long, Object> expectedResult = Maps.newTreeMap(); expectedResult.put(commit1, "Initial Commit"); expectedResult.put(commit2, null); expectedResult.put(commit3, "Foobar"); expectedResult.put(commit4, null); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true).descendingKeySet(), // actual toSet(tx.getCommitTimestampsBetween(commit2, commit4, Order.DESCENDING))); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true).keySet(), // actual toSet(tx.getCommitTimestampsBetween(commit2, commit4, Order.ASCENDING))); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true).descendingMap(), // actual toMap(tx.getCommitMetadataBetween(commit2, commit4, Order.DESCENDING))); assertEquals( // expected expectedResult.subMap(commit2, true, commit4, true), // actual toMap(tx.getCommitMetadataBetween(commit2, commit4, Order.ASCENDING))); } @Test public void retrievingCommitTimestampsIsBranchLocal() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("Initial Commit"); db.getBranchManager().createBranch("Test"); long branchingTimestamp = db.getBranchManager().getBranch("Test").getBranchingTimestamp(); tx = db.tx("Test"); tx.put("Foo", "Bar"); tx.commit("New Branch!"); final long commit2 = tx.getTimestamp(); tx = db.tx(); tx.put("Pi", "3.1415"); tx.commit(); final long commit3 = tx.getTimestamp(); // we should have two commits on 'master' (the first one and the last one) assertEquals(2, Iterators.size(db.tx().getCommitTimestampsBetween(0, commit3))); assertEquals(2, Iterators.size(db.tx().getCommitMetadataBetween(0, commit3))); // we should have one commit on 'Test' assertEquals(1, Iterators.size(db.tx("Test").getCommitTimestampsBetween(branchingTimestamp, commit2))); assertEquals(1, Iterators.size(db.tx("Test").getCommitMetadataBetween(branchingTimestamp, commit2))); } // ===================================================================================================================== // HELPER METHODS // ===================================================================================================================== private static <A, B> Map<A, B> toMap(final Iterator<Entry<A, B>> iterator) { Map<A, B> resultMap = new LinkedHashMap<>(); while (iterator.hasNext()) { Entry<A, B> entry = iterator.next(); resultMap.put(entry.getKey(), entry.getValue()); } return resultMap; } private static <A> Set<A> toSet(final Iterator<A> iterator) { Set<A> resultSet = new LinkedHashSet<>(); while (iterator.hasNext()) { resultSet.add(iterator.next()); } return resultSet; } }
5,474
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetCommitsBeforeAfterAroundTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/commitmetadata/GetCommitsBeforeAfterAroundTest.java
package org.chronos.chronodb.test.cases.engine.commitmetadata; import com.google.common.collect.Lists; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import java.util.Map.Entry; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class GetCommitsBeforeAfterAroundTest extends AllChronoDBBackendsTest { // ================================================================================================================= // COMMITS AROUND // ================================================================================================================= @Test public void commitsAroundWorksIfNoCommitsArePresent() { ChronoDB db = this.getChronoDB(); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataAround(0, 10); assertNotNull(commits); assertTrue(commits.isEmpty()); } @Test public void commitsAroundWorksIfNotEnoughCommitsArePresentOnEitherSide() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); List<Entry<Long, Object>> commitsAround = tx.getCommitMetadataAround(afterSecondCommit, 5); assertEquals(3, commitsAround.size()); assertEquals(afterThirdCommit, (long) commitsAround.get(0).getKey()); assertEquals("Third", commitsAround.get(0).getValue()); assertEquals(afterSecondCommit, (long) commitsAround.get(1).getKey()); assertEquals("Second", commitsAround.get(1).getValue()); assertEquals(afterFirstCommit, (long) commitsAround.get(2).getKey()); assertEquals("First", commitsAround.get(2).getValue()); } @Test public void commitsAroundWorksIfExactlyEnoughElementsArePresentOnBothSides() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); List<Entry<Long, Object>> commitsAround = tx.getCommitMetadataAround(afterSecondCommit, 3); assertEquals(3, commitsAround.size()); assertEquals(afterThirdCommit, (long) commitsAround.get(0).getKey()); assertEquals("Third", commitsAround.get(0).getValue()); assertEquals(afterSecondCommit, (long) commitsAround.get(1).getKey()); assertEquals("Second", commitsAround.get(1).getValue()); assertEquals(afterFirstCommit, (long) commitsAround.get(2).getKey()); assertEquals("First", commitsAround.get(2).getValue()); } @Test public void commitsAroundWorksIfNotEnoughElementsArePresentBefore() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterFourthCommit, "Fourth")); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); expected.add(Pair.of(afterFirstCommit, "First")); List<Entry<Long, Object>> commitsAround = tx.getCommitMetadataAround(afterSecondCommit, 4); assertEquals(expected, commitsAround); } @Test public void commitsAroundWorksIfNotEnoughElementsArePresentAfter() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); long afterFifthCommit = tx.getTimestamp(); tx.put("6", "Six"); tx.commit("Sixth"); long afterSixthCommit = tx.getTimestamp(); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterSixthCommit, "Sixth")); expected.add(Pair.of(afterFifthCommit, "Fifth")); expected.add(Pair.of(afterFourthCommit, "Fourth")); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); List<Entry<Long, Object>> commitsAround = tx.getCommitMetadataAround(afterFifthCommit, 5); assertEquals(expected, commitsAround); } @Test public void commitsAroundWorksIfMoreElementsThanNecessaryArePresentOnBothSides() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterFourthCommit, "Fourth")); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); List<Entry<Long, Object>> commitsAround = tx.getCommitMetadataAround(afterThirdCommit, 3); assertEquals(expected, commitsAround); } @Test public void commitsAroundWorksIfTimestampIsNotExactlyMatchingACommit() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); this.sleep(10); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); this.sleep(10); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); this.sleep(10); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); this.sleep(10); long afterFifthCommit = tx.getTimestamp(); tx.put("6", "Six"); tx.commit("Sixth"); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterFifthCommit, "Fifth")); expected.add(Pair.of(afterFourthCommit, "Fourth")); expected.add(Pair.of(afterThirdCommit, "Third")); long requestTimestamp = (afterFourthCommit + afterThirdCommit) / 2; List<Entry<Long, Object>> commitsAround = tx.getCommitMetadataAround(requestTimestamp, 3); assertEquals(expected, commitsAround); } @Test public void commitTimestampsAroundWorksIfNotEnoughCommitsArePresentOnEitherSide() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); List<Long> commitsAround = tx.getCommitTimestampsAround(afterSecondCommit, 5); assertEquals(3, commitsAround.size()); assertEquals(afterThirdCommit, (long) commitsAround.get(0)); assertEquals(afterSecondCommit, (long) commitsAround.get(1)); assertEquals(afterFirstCommit, (long) commitsAround.get(2)); } @Test public void commitTimestampsAroundWorksIfExactlyEnoughElementsArePresentOnBothSides() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); List<Long> commitsAround = tx.getCommitTimestampsAround(afterSecondCommit, 3); assertEquals(3, commitsAround.size()); assertEquals(afterThirdCommit, (long) commitsAround.get(0)); assertEquals(afterSecondCommit, (long) commitsAround.get(1)); assertEquals(afterFirstCommit, (long) commitsAround.get(2)); } @Test public void commitTimestampsAroundWorksIfNotEnoughElementsArePresentBefore() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); List<Long> expected = Lists.newArrayList(); expected.add(afterFourthCommit); expected.add(afterThirdCommit); expected.add(afterSecondCommit); expected.add(afterFirstCommit); List<Long> commitsAround = tx.getCommitTimestampsAround(afterSecondCommit, 4); assertEquals(expected, commitsAround); } @Test public void commitTimestampsAroundWorksIfNotEnoughElementsArePresentAfter() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); long afterFifthCommit = tx.getTimestamp(); tx.put("6", "Six"); tx.commit("Sixth"); long afterSixthCommit = tx.getTimestamp(); List<Long> expected = Lists.newArrayList(); expected.add(afterSixthCommit); expected.add(afterFifthCommit); expected.add(afterFourthCommit); expected.add(afterThirdCommit); expected.add(afterSecondCommit); List<Long> commitsAround = tx.getCommitTimestampsAround(afterFifthCommit, 5); assertEquals(expected, commitsAround); } @Test public void commitTimestampsAroundWorksIfMoreElementsThanNecessaryArePresentOnBothSides() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Long> expected = Lists.newArrayList(); expected.add(afterFourthCommit); expected.add(afterThirdCommit); expected.add(afterSecondCommit); List<Long> commitsAround = tx.getCommitTimestampsAround(afterThirdCommit, 3); assertEquals(expected, commitsAround); } @Test public void commitTimestampsAroundWorksIfTimestampIsNotExactlyMatchingACommit() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); this.sleep(10); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); this.sleep(10); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); this.sleep(10); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); this.sleep(10); long afterFifthCommit = tx.getTimestamp(); tx.put("6", "Six"); tx.commit("Sixth"); List<Long> expected = Lists.newArrayList(); expected.add(afterFifthCommit); expected.add(afterFourthCommit); expected.add(afterThirdCommit); long requestTimestamp = (afterFourthCommit + afterThirdCommit) / 2; List<Long> commitsAround = tx.getCommitTimestampsAround(requestTimestamp, 3); assertEquals(expected, commitsAround); } // ================================================================================================================= // COMMITS BEFORE // ================================================================================================================= @Test public void commitsBeforeWorksIfThereAreNoCommits() { ChronoDB db = this.getChronoDB(); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataBefore(0, 10); assertNotNull(commits); assertTrue(commits.isEmpty()); } @Test public void commitsBeforeWorksIfThereAreNotEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterSecondCommit, "Second")); expected.add(Pair.of(afterFirstCommit, "First")); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataBefore(afterThirdCommit, 3); assertEquals(expected, commits); } @Test public void commitsBeforeWorksIfThereAreExactlyEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); expected.add(Pair.of(afterFirstCommit, "First")); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataBefore(afterFourthCommit, 3); assertEquals(expected, commits); } @Test public void commitsBeforeWorksIfThereAreTooManyCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); long afterFifthCommit = tx.getTimestamp(); tx.put("6", "Six"); tx.commit("Sixth"); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterFourthCommit, "Fourth")); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataBefore(afterFifthCommit, 3); assertEquals(expected, commits); } @Test public void commitTimestampsBeforeWorksIfThereAreNoCommits() { ChronoDB db = this.getChronoDB(); List<Long> commits = db.tx().getCommitTimestampsBefore(0, 10); assertNotNull(commits); assertTrue(commits.isEmpty()); } @Test public void commitTimestampsBeforeWorksIfThereAreNotEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Long> expected = Lists.newArrayList(); expected.add(afterSecondCommit); expected.add(afterFirstCommit); List<Long> commits = db.tx().getCommitTimestampsBefore(afterThirdCommit, 3); assertEquals(expected, commits); } @Test public void commitTimestampsBeforeWorksIfThereAreExactlyEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Long> expected = Lists.newArrayList(); expected.add(afterThirdCommit); expected.add(afterSecondCommit); expected.add(afterFirstCommit); List<Long> commits = db.tx().getCommitTimestampsBefore(afterFourthCommit, 3); assertEquals(expected, commits); } @Test public void commitTimestampsBeforeWorksIfThereAreTooManyCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); long afterFifthCommit = tx.getTimestamp(); tx.put("6", "Six"); tx.commit("Sixth"); List<Long> expected = Lists.newArrayList(); expected.add(afterFourthCommit); expected.add(afterThirdCommit); expected.add(afterSecondCommit); List<Long> commits = db.tx().getCommitTimestampsBefore(afterFifthCommit, 3); assertEquals(expected, commits); } // ================================================================================================================= // COMMITS AFTER // ================================================================================================================= @Test public void commitsAfterWorksIfThereAreNoCommits() { ChronoDB db = this.getChronoDB(); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataAfter(0, 10); assertNotNull(commits); assertTrue(commits.isEmpty()); } @Test public void commitsAfterWorksIfThereAreNotEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataAfter(afterFirstCommit, 3); assertEquals(expected, commits); } @Test public void commitsAfterWorksIfThereAreExactlyEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterFourthCommit, "Fourth")); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataAfter(afterFirstCommit, 3); assertEquals(expected, commits); } @Test public void commitsAfterWorksIfThereAreTooManyCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Entry<Long, Object>> expected = Lists.newArrayList(); expected.add(Pair.of(afterFourthCommit, "Fourth")); expected.add(Pair.of(afterThirdCommit, "Third")); expected.add(Pair.of(afterSecondCommit, "Second")); List<Entry<Long, Object>> commits = db.tx().getCommitMetadataAfter(afterFirstCommit, 3); assertEquals(expected, commits); } @Test public void commitTimestampsAfterWorksIfThereAreNoCommits() { ChronoDB db = this.getChronoDB(); List<Long> commits = db.tx().getCommitTimestampsAfter(0, 10); assertNotNull(commits); assertTrue(commits.isEmpty()); } @Test public void commitTimestampsAfterWorksIfThereAreNotEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); List<Long> expected = Lists.newArrayList(); expected.add(afterThirdCommit); expected.add(afterSecondCommit); List<Long> commits = db.tx().getCommitTimestampsAfter(afterFirstCommit, 3); assertEquals(expected, commits); } @Test public void commitTimestampsAfterWorksIfThereAreExactlyEnoughCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); List<Long> expected = Lists.newArrayList(); expected.add(afterFourthCommit); expected.add(afterThirdCommit); expected.add(afterSecondCommit); List<Long> commits = db.tx().getCommitTimestampsAfter(afterFirstCommit, 3); assertEquals(expected, commits); } @Test public void commitTimestampsAfterWorksIfThereAreTooManyCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); long afterFourthCommit = tx.getTimestamp(); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Long> expected = Lists.newArrayList(); expected.add(afterFourthCommit); expected.add(afterThirdCommit); expected.add(afterSecondCommit); List<Long> commits = db.tx().getCommitTimestampsAfter(afterFirstCommit, 3); assertEquals(expected, commits); } @Test public void commitTimestampsAfterZeroWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.commit("First"); long afterFirstCommit = tx.getTimestamp(); tx.put("Foo", "Bar"); tx.commit("Second"); long afterSecondCommit = tx.getTimestamp(); tx.put("Pi", "3.1415"); tx.commit("Third"); long afterThirdCommit = tx.getTimestamp(); tx.put("Test", "Test"); tx.commit("Fourth"); tx.put("XYZ", "XYZ"); tx.commit("Fifth"); tx.put("6", "Six"); tx.commit("Sixth"); List<Long> expected = Lists.newArrayList(); expected.add(afterThirdCommit); expected.add(afterSecondCommit); expected.add(afterFirstCommit); List<Long> commits = db.tx().getCommitTimestampsAfter(0, 3); assertEquals(expected, commits); } }
28,992
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GetChangesAtCommitTimestampsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/commitmetadata/GetChangesAtCommitTimestampsTest.java
package org.chronos.chronodb.test.cases.engine.commitmetadata; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.File; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class GetChangesAtCommitTimestampsTest extends AllChronoDBBackendsTest { @Test public void canRetrieveChangesFromDefaultKeyspaceWithSpecialDump() { // note: this test is the same as "canRetrieveChangesFromDefaultKeyspace", except // that here we use a dump file which contains the same data as the other test, // but the timestamps were manually adjusted to follow exactly after each other // (i.e. the distance between two commits is exactly 1ms). This was done to test // "off by 1" scenarios when checking the request time boundaries at matrix level. File xmlFile = this.getSrcTestResourcesFile("changesAtCommitTimestampDump.xml"); ChronoDB db = this.getChronoDB(); db.readDump(xmlFile); // these timestamps are contained in the XML dump long timestamp1 = 1536911128414L; long timestamp2 = 1536911128415L; long timestamp3 = 1536911128416L; // make sure that the dump was loaded correctly, i.e. the commit history // reports exactly those three timestamps ChronoDBTransaction tx = db.tx(); List<Long> commitTimestamps = tx.getCommitTimestampsAfter(0, 10); assertThat(commitTimestamps, contains(timestamp3, timestamp2, timestamp1)); {// check timestamp1 Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp1); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("pi", "foo", "hello"), keys); } { // check timestamp2 Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp2); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("foo", "hello"), keys); } { // check timestamp3 Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp3); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("new"), keys); } } @Test public void canRetrieveChangesFromDefaultKeyspace() { ChronoDB db = this.getChronoDB(); long timestamp1; long timestamp2; long timestamp3; { // set up ChronoDBTransaction tx = db.tx(); tx.put("pi", 3.1415); tx.put("hello", "world"); tx.put("foo", "bar"); tx.commit(); timestamp1 = tx.getTimestamp(); tx.put("foo", "baz"); tx.put("hello", "john"); tx.commit(); timestamp2 = tx.getTimestamp(); tx.put("new", "value"); tx.commit(); timestamp3 = tx.getTimestamp(); } {// check timestamp1 Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp1); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("pi", "foo", "hello"), keys); } { // check timestamp2 Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp2); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("foo", "hello"), keys); } { // check timestamp3 Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp3); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("new"), keys); } } @Test public void canRetrieveChangesFromCustomKeyspace() { ChronoDB db = this.getChronoDB(); long timestamp1; long timestamp2; long timestamp3; { // set up ChronoDBTransaction tx = db.tx(); tx.put("math", "pi", 3.1415); tx.put("greeting", "hello", "world"); tx.put("nonsense", "foo", "bar"); tx.commit(); timestamp1 = tx.getTimestamp(); tx.put("nonsense", "foo", "baz"); tx.put("greeting", "hello", "john"); tx.commit(); timestamp2 = tx.getTimestamp(); tx.put("nonsense", "new", "value"); tx.commit(); timestamp3 = tx.getTimestamp(); } {// check timestamp1 (math) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp1, "math"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("pi"), keys); } {// check timestamp1 (greeting) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp1, "greeting"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("hello"), keys); } {// check timestamp1 (nonsense) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp1, "nonsense"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("foo"), keys); } { // check timestamp2 (math) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp2, "math"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Collections.emptySet(), keys); } { // check timestamp2 (greeting) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp2, "greeting"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("hello"), keys); } { // check timestamp2 (nonsense) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp2, "nonsense"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("foo"), keys); } { // check timestamp3 (math) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp3, "math"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Collections.emptySet(), keys); } { // check timestamp3 (greeting) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp3, "greeting"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Collections.emptySet(), keys); } { // check timestamp3 (nonsense) Iterator<String> changedKeys = db.tx().getChangedKeysAtCommit(timestamp3, "nonsense"); Set<String> keys = Sets.newHashSet(changedKeys); assertEquals(Sets.newHashSet("new"), keys); } } @Test public void canRetrieveChangesAtCommitFromBranch() { ChronoDB db = this.getChronoDB(); { // set up master ChronoDBTransaction tx = db.tx(); tx.put("pi", 3.1415); tx.put("hello", "world"); tx.put("foo", "bar"); tx.commit(); } { // set up branch db.getBranchManager().createBranch("test"); ChronoDBTransaction tx = db.tx("test"); tx.put("hello", "john"); tx.put("new", "value"); tx.commit(); } long masterHead = db.tx().getTimestamp(); long testHead = db.tx("test").getTimestamp(); // this is the standard master branch query assertEquals(Sets.newHashSet("pi", "hello", "foo"), Sets.newHashSet(db.tx().getChangedKeysAtCommit(masterHead))); // try to fetch the contents of a commit from the branch assertEquals(Sets.newHashSet("hello", "new"), Sets.newHashSet(db.tx("test").getChangedKeysAtCommit(testHead))); // try to fetch the contents of a commit on a branch that was commited before the branching timestamp assertEquals(Sets.newHashSet("pi", "hello", "foo"), Sets.newHashSet(db.tx("test").getChangedKeysAtCommit(masterHead))); } }
8,557
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryReuseTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/query/QueryReuseTest.java
package org.chronos.chronodb.test.cases.engine.query; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class QueryReuseTest extends AllChronoDBBackendsTest { @Test public void queryReuseWorks() { ChronoDB db = this.getChronoDB(); StringIndexer integerIndexer = new MyStringIndexer(); db.getIndexManager().createIndex().withName("integer").withIndexer(integerIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("First", 123); tx.put("Second", 456); tx.put("Third", 123); tx.commit(); long writeTimestamp = tx.getTimestamp(); this.sleep(5); tx.put("First", 789); tx.commit(); // buildLRU the query ChronoDBQuery query = tx.find().inDefaultKeyspace().where("integer").isEqualTo("123").toQuery(); // check that before the second commit, we get 2 results by running the query { ChronoDBTransaction txBefore = db.tx(writeTimestamp); Iterator<QualifiedKey> keys = txBefore.find(query).getKeys(); Set<String> keySet = Sets.newHashSet(keys).stream().map(qKey -> qKey.getKey()).collect(Collectors.toSet()); assertTrue(keySet.contains("First")); assertTrue(keySet.contains("Third")); assertEquals(2, keySet.size()); } // check that after the second commit, we get 1 result by running the query { ChronoDBTransaction txBefore = db.tx(); Iterator<QualifiedKey> keys = txBefore.find(query).getKeys(); Set<String> keySet = Sets.newHashSet(keys).stream().map(qKey -> qKey.getKey()).collect(Collectors.toSet()); assertFalse(keySet.contains("First")); assertTrue(keySet.contains("Third")); assertEquals(1, keySet.size()); } } private static class MyStringIndexer implements StringIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return object instanceof Integer; } @Override public Set<String> getIndexValues(final Object object) { return Collections.singleton(((Integer) object).toString()); } } }
3,202
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BasicQueryTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/query/BasicQueryTest.java
package org.chronos.chronodb.test.cases.engine.query; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class BasicQueryTest extends AllChronoDBBackendsTest { @Test public void basicQueryingWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); Iterator<QualifiedKey> queryResultIterator = tx.find().inDefaultKeyspace().where("name").contains("Foo").and() .not().where("name").contains("Bar").getKeys(); Set<QualifiedKey> queryResultSet = Sets.newHashSet(queryResultIterator); assertEquals(1, queryResultSet.size()); QualifiedKey singleResult = Iterables.getOnlyElement(queryResultSet); assertEquals("np3", singleResult.getKey()); } @Test public void queryResultSetMethodsWork() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); ChronoDBQuery query = tx.find().inDefaultKeyspace().where("name").contains("Foo").and().not().where("name") .contains("Bar").toQuery(); { // using queryBuilder.getKeys() Iterator<QualifiedKey> keys = tx.find(query).getKeys(); Set<String> keySet = Sets.newHashSet(keys).stream().map(qKey -> qKey.getKey()).collect(Collectors.toSet()); assertTrue(keySet.contains("np3")); assertEquals(1, keySet.size()); } { // using queryBuilder.values() Iterator<Object> values = tx.find(query).getValues(); Set<Object> valueSet = Sets.newHashSet(values); assertEquals(1, valueSet.size()); assertEquals("Foo Baz", ((NamedPayload) Iterables.getOnlyElement(valueSet)).getName()); } { // using queryBuilder.getResult() Iterator<Entry<String, Object>> result = tx.find(query).getResult(); Set<Entry<String, Object>> resultSet = Sets.newHashSet(result); assertEquals(1, resultSet.size()); Entry<String, Object> entry = Iterables.getOnlyElement(resultSet); assertEquals("np3", entry.getKey()); assertEquals("Foo Baz", ((NamedPayload) entry.getValue()).getName()); } { // using queryBuilder.getQualifiedResult() Iterator<Entry<QualifiedKey, Object>> qualifiedResult = tx.find(query).getQualifiedResult(); Entry<QualifiedKey, Object> entry = Iterators.getOnlyElement(qualifiedResult); QualifiedKey qKey = entry.getKey(); String key = qKey.getKey(); String keyspace = qKey.getKeyspace(); NamedPayload value = (NamedPayload) entry.getValue(); assertEquals("np3", key); assertEquals(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, keyspace); assertEquals("Foo Baz", value.getName()); } } @Test public void doubleNegationEliminationWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); Iterator<QualifiedKey> keys = tx.find().inDefaultKeyspace().not().not().not().where("name") .isNotEqualTo("Hello World").getKeys(); Set<String> keySet = Sets.newHashSet(keys).stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(1, keySet.size()); assertTrue(keySet.contains("np1")); } @Test public void multipleAndWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().where("name").contains("o").and().where("name").contains("a").and() .where("name").endsWith("z").count(); assertEquals(1, count); } @Test public void multipleOrWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().where("name").contains("z").or().where("name").contains("ar").or() .where("name").endsWith("oo").count(); assertEquals(2, count); } }
7,949
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ContainmentQueryTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/query/ContainmentQueryTest.java
package org.chronos.chronodb.test.cases.engine.query; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.indexing.DoubleIndexer; import org.chronos.chronodb.api.indexing.LongIndexer; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.query.DoubleContainmentCondition; import org.chronos.chronodb.api.query.LongContainmentCondition; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.internal.impl.query.optimizer.StandardQueryOptimizer; import org.chronos.chronodb.internal.impl.query.parser.ast.BinaryOperatorElement; import org.chronos.chronodb.internal.impl.query.parser.ast.BinaryQueryOperator; import org.chronos.chronodb.internal.impl.query.parser.ast.QueryElement; import org.chronos.chronodb.internal.impl.query.parser.ast.SetDoubleWhereElement; import org.chronos.chronodb.internal.impl.query.parser.ast.SetLongWhereElement; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.chronodb.test.cases.util.model.person.FirstNameIndexer; import org.chronos.chronodb.test.cases.util.model.person.LastNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.chronos.common.test.utils.model.person.Person; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ContainmentQueryTest extends AllChronoDBBackendsTest { @Test public void stringWithinQueryWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); Set<QualifiedKey> keysAsSet = db.tx().find() .inDefaultKeyspace() .where("name").inStrings(Sets.newHashSet("Foo Bar", "Foo Baz")) .getKeysAsSet(); assertThat(keysAsSet, containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("np2"), QualifiedKey.createInDefaultKeyspace("np3") ) ); } @Test public void stringWithoutQueryWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); Set<QualifiedKey> keysAsSet = db.tx().find() .inDefaultKeyspace() .where("name").notInStrings(Sets.newHashSet("Foo Bar", "Foo Baz")) .getKeysAsSet(); assertThat(keysAsSet, containsInAnyOrder(QualifiedKey.createInDefaultKeyspace("np1"))); } @Test public void longWithinQueryWorks() { ChronoDB db = this.getChronoDB(); LongIndexer indexer = new LongBeanIndexer(); db.getIndexManager().createIndex().withName("value").withIndexer(indexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("v1", new LongBean(1L)); tx.put("v2", new LongBean(2L)); tx.put("v3", new LongBean(3L)); tx.put("v4", new LongBean(4L)); tx.put("v5", new LongBean(5L)); tx.commit(); Set<QualifiedKey> keysAsSet = db.tx().find() .inDefaultKeyspace() .where("value").inLongs(Sets.newHashSet(2L, 4L, 5L)) .getKeysAsSet(); assertThat(keysAsSet, containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("v2"), QualifiedKey.createInDefaultKeyspace("v4"), QualifiedKey.createInDefaultKeyspace("v5") )); } @Test public void longWithoutQueryWorks() { ChronoDB db = this.getChronoDB(); LongIndexer indexer = new LongBeanIndexer(); db.getIndexManager().createIndex().withName("value").withIndexer(indexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("v1", new LongBean(1L)); tx.put("v2", new LongBean(2L)); tx.put("v3", new LongBean(3L)); tx.put("v4", new LongBean(4L)); tx.put("v5", new LongBean(5L)); tx.commit(); Set<QualifiedKey> keysAsSet = db.tx().find() .inDefaultKeyspace() .where("value").notInLongs(Sets.newHashSet(2L, 4L, 5L)) .getKeysAsSet(); assertThat(keysAsSet, containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("v1"), QualifiedKey.createInDefaultKeyspace("v3") )); } @Test public void doubleWithinQueryWorks() { ChronoDB db = this.getChronoDB(); DoubleIndexer indexer = new DoubleBeanIndexer(); db.getIndexManager().createIndex().withName("value").withIndexer(indexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("v1", new DoubleBean(1.3)); tx.put("v2", new DoubleBean(2.3)); tx.put("v3", new DoubleBean(3.3)); tx.put("v4", new DoubleBean(4.3)); tx.put("v5", new DoubleBean(5.3)); tx.commit(); Set<QualifiedKey> keysAsSet = db.tx().find() .inDefaultKeyspace() .where("value").inDoubles(Sets.newHashSet(2.0, 4.0, 5.0), 0.4) .getKeysAsSet(); assertThat(keysAsSet, containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("v2"), QualifiedKey.createInDefaultKeyspace("v4"), QualifiedKey.createInDefaultKeyspace("v5") )); } @Test public void doubleWithoutQueryWorks() { ChronoDB db = this.getChronoDB(); DoubleIndexer indexer = new DoubleBeanIndexer(); db.getIndexManager().createIndex().withName("value").withIndexer(indexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("v1", new DoubleBean(1.3)); tx.put("v2", new DoubleBean(2.3)); tx.put("v3", new DoubleBean(3.3)); tx.put("v4", new DoubleBean(4.3)); tx.put("v5", new DoubleBean(5.3)); tx.commit(); Set<QualifiedKey> keysAsSet = db.tx().find() .inDefaultKeyspace() .where("value").notInDoubles(Sets.newHashSet(2.0, 4.0, 5.0), 0.4) .getKeysAsSet(); assertThat(keysAsSet, containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("v1"), QualifiedKey.createInDefaultKeyspace("v3") )); } @Test public void withinAndConnectionQueryWorks() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("first name").withIndexer(new FirstNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("last name").withIndexer(new LastNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("p1", new Person("John", "Doe")); tx.put("p2", new Person("Jane", "Doe")); tx.put("p3", new Person("John", "Sparrow")); tx.put("p4", new Person("John", "Skywalker")); tx.put("p5", new Person("Foo", "Bar")); tx.commit(); Set<QualifiedKey> keysAsSet = db.tx().find() .inDefaultKeyspace() .where("first name").inStrings(Sets.newHashSet("John", "Jane")) .and() .where("last name").notInStringsIgnoreCase(Sets.newHashSet("skywalker", "sparrow")) .getKeysAsSet(); assertThat(keysAsSet, containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("p1"), QualifiedKey.createInDefaultKeyspace("p2") )); } @Test public void canConvertLongOrQueriesIntoContainmentQuery() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("x").withIndexer(new LongBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("y").withIndexer(new LongBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("z").withIndexer(new LongBeanIndexer()).onMaster().acrossAllTimestamps().build(); { // within: merge where clauses with same index ChronoDBQuery query = db.tx().find().inDefaultKeyspace().where("x").isEqualTo(1).or().where("x").isEqualTo(2).or().where("x").isEqualTo(3).toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is(instanceOf(SetLongWhereElement.class))); SetLongWhereElement inClause = (SetLongWhereElement) rootElement; assertThat(inClause.getCondition(), is(LongContainmentCondition.WITHIN)); assertThat(inClause.getIndexName(), is("x")); assertThat(inClause.getComparisonValue(), containsInAnyOrder(1L, 2L, 3L)); } { // within: do not merge where clauses with different indices ChronoDBQuery query = db.tx().find().inDefaultKeyspace().where("x").isEqualTo(1).or().where("y").isEqualTo(2).or().where("z").isEqualTo(3).toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is((instanceOf(BinaryOperatorElement.class)))); } { // without: merge where clauses with same index ChronoDBQuery query = db.tx().find().inDefaultKeyspace() .not().begin() .where("x").isEqualTo(1) .and().where("x").isEqualTo(2) .and().where("x").isEqualTo(3) .end() .toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is(instanceOf(SetLongWhereElement.class))); SetLongWhereElement inClause = (SetLongWhereElement) rootElement; assertThat(inClause.getCondition(), is(LongContainmentCondition.WITHOUT)); assertThat(inClause.getIndexName(), is("x")); assertThat(inClause.getComparisonValue(), containsInAnyOrder(1L, 2L, 3L)); } { // without: merge where clauses with same index ChronoDBQuery query = db.tx().find().inDefaultKeyspace() .not().begin() .where("x").isEqualTo(1) .and().where("y").isEqualTo(2) .and().where("z").isEqualTo(3) .end() .toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is((instanceOf(BinaryOperatorElement.class)))); } } @Test public void canConvertNestedLongOrQueriesIntoContainmentQuery() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("x").withIndexer(new LongBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("y").withIndexer(new LongBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("z").withIndexer(new LongBeanIndexer()).onMaster().acrossAllTimestamps().build(); ChronoDBQuery query = db.tx().find().inDefaultKeyspace() .where("x").isEqualTo(1) .and().begin() .where("y").isEqualTo(2).or().where("y").isEqualTo(3).or().where("y").isEqualTo(4) .end() .toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is(instanceOf(BinaryOperatorElement.class))); BinaryOperatorElement rootBinary = (BinaryOperatorElement) rootElement; assertThat(rootBinary.getOperator(), is(BinaryQueryOperator.AND)); QueryElement rightChild = rootBinary.getRightChild(); assertThat(rightChild, is(instanceOf(SetLongWhereElement.class))); SetLongWhereElement inClause = (SetLongWhereElement) rightChild; assertThat(inClause.getCondition(), is(LongContainmentCondition.WITHIN)); assertThat(inClause.getIndexName(), is("y")); assertThat(inClause.getComparisonValue(), containsInAnyOrder(2L, 3L, 4L)); } @Test public void canConvertDoubleOrQueriesIntoContainmentQuery() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("x").withIndexer(new DoubleBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("y").withIndexer(new DoubleBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("z").withIndexer(new DoubleBeanIndexer()).onMaster().acrossAllTimestamps().build(); { // within: merge where clauses with same index ChronoDBQuery query = db.tx().find().inDefaultKeyspace().where("x").isEqualTo(1.0, 0.01).or().where("x").isEqualTo(2.0, 0.01).or().where("x").isEqualTo(3.0, 0.01).toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is(instanceOf(SetDoubleWhereElement.class))); SetDoubleWhereElement inClause = (SetDoubleWhereElement) rootElement; assertThat(inClause.getCondition(), is(DoubleContainmentCondition.WITHIN)); assertThat(inClause.getIndexName(), is("x")); assertThat(inClause.getComparisonValue(), containsInAnyOrder(1.0, 2.0, 3.0)); assertThat(inClause.getEqualityTolerance(), is(0.01)); } { // within: do not merge where clauses with different indices ChronoDBQuery query = db.tx().find().inDefaultKeyspace().where("x").isEqualTo(1.0, 0.01).or().where("y").isEqualTo(2.0, 0.01).or().where("z").isEqualTo(3.0, 0.01).toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is((instanceOf(BinaryOperatorElement.class)))); } { // within: do not merge where clauses with different tolerances ChronoDBQuery query = db.tx().find().inDefaultKeyspace().where("x").isEqualTo(1.0, 0.01).or().where("x").isEqualTo(2.0, 0.02).or().where("x").isEqualTo(3.0, 0.03).toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is((instanceOf(BinaryOperatorElement.class)))); } { // without: merge where clauses with same index ChronoDBQuery query = db.tx().find().inDefaultKeyspace() .not().begin() .where("x").isEqualTo(1.0, 0.01) .and().where("x").isEqualTo(2.0, 0.01) .and().where("x").isEqualTo(3, 0.01) .end() .toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is(instanceOf(SetDoubleWhereElement.class))); SetDoubleWhereElement inClause = (SetDoubleWhereElement) rootElement; assertThat(inClause.getCondition(), is(DoubleContainmentCondition.WITHOUT)); assertThat(inClause.getIndexName(), is("x")); assertThat(inClause.getComparisonValue(), containsInAnyOrder(1.0, 2.0, 3.0)); assertThat(inClause.getEqualityTolerance(), is(0.01)); } { // without: merge where clauses with same index ChronoDBQuery query = db.tx().find().inDefaultKeyspace() .not().begin() .where("x").isEqualTo(1.0, 0.01) .and().where("y").isEqualTo(2.0, 0.01) .and().where("z").isEqualTo(3.0, 0.01) .end() .toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is((instanceOf(BinaryOperatorElement.class)))); } { // without: do not merge where clauses with different tolerances ChronoDBQuery query = db.tx().find().inDefaultKeyspace() .not().begin() .where("x").isEqualTo(1.0, 0.01) .and().where("x").isEqualTo(2.0, 0.02) .and().where("x").isEqualTo(3.0, 0.03) .end().toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is((instanceOf(BinaryOperatorElement.class)))); } } @Test public void canConvertNestedDoubleOrQueriesIntoContainmentQuery() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("x").withIndexer(new DoubleBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("y").withIndexer(new DoubleBeanIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("z").withIndexer(new DoubleBeanIndexer()).onMaster().acrossAllTimestamps().build(); ChronoDBQuery query = db.tx().find().inDefaultKeyspace() .where("x").isEqualTo(1.0, 0.01) .and().begin() .where("y").isEqualTo(2.0, 0.01).or().where("y").isEqualTo(3.0, 0.01).or().where("y").isEqualTo(4.0, 0.01) .end() .toQuery(); ChronoDBQuery optimedQuery = new StandardQueryOptimizer().optimize(query); QueryElement rootElement = optimedQuery.getRootElement(); assertThat(rootElement, is(instanceOf(BinaryOperatorElement.class))); BinaryOperatorElement rootBinary = (BinaryOperatorElement) rootElement; assertThat(rootBinary.getOperator(), is(BinaryQueryOperator.AND)); QueryElement rightChild = rootBinary.getRightChild(); assertThat(rightChild, is(instanceOf(SetDoubleWhereElement.class))); SetDoubleWhereElement inClause = (SetDoubleWhereElement) rightChild; assertThat(inClause.getCondition(), is(DoubleContainmentCondition.WITHIN)); assertThat(inClause.getIndexName(), is("y")); assertThat(inClause.getComparisonValue(), containsInAnyOrder(2.0, 3.0, 4.0)); } private static class DoubleBean { private double value; @SuppressWarnings("unused") protected DoubleBean() { // kryo } public DoubleBean(double value) { this.value = value; } public double getValue() { return value; } } private static class DoubleBeanIndexer implements DoubleIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return object instanceof DoubleBean; } @Override public Set<Double> getIndexValues(final Object object) { return Collections.singleton(((DoubleBean) object).getValue()); } } private static class LongBean { private long value; @SuppressWarnings("unused") protected LongBean() { // kryo } public LongBean(long value) { this.value = value; } public long getValue() { return value; } } private static class LongBeanIndexer implements LongIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return object instanceof LongBean; } @Override public Set<Long> getIndexValues(final Object object) { return Collections.singleton(((LongBean) object).getValue()); } } }
22,347
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchCreationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/branching/BranchCreationTest.java
package org.chronos.chronodb.test.cases.engine.branching; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.common.test.utils.NamedPayload; import org.chronos.common.test.utils.model.person.Person; import org.chronos.chronodb.test.cases.util.model.person.PersonIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.Set; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class BranchCreationTest extends AllChronoDBBackendsTest { @Test public void basicBranchCreationWorks() { ChronoDB db = this.getChronoDB(); // fill the database with some data ChronoDBTransaction tx = db.tx(); tx.put("first", 123); tx.put("second", 456); tx.commit(); tx.put("first", 789); tx.put("third", 321); tx.commit(); // at this point, our branch should not exist yet assertEquals(false, db.getBranchManager().existsBranch("MyBranch")); // create the branch db.getBranchManager().createBranch("MyBranch"); // make sure that the branch exists now assertTrue(db.getBranchManager().existsBranch("MyBranch")); // access the branch tx = db.tx("MyBranch"); // make sure that the tx has the proper timestamp assertTrue(tx.getTimestamp() > 0); // assert that the data is in the branch assertEquals(3, tx.keySet().size()); assertEquals(789, (int) tx.get("first")); assertEquals(456, (int) tx.get("second")); assertEquals(321, (int) tx.get("third")); } @Test public void branchingAKeyspaceWorks() { ChronoDB db = this.getChronoDB(); // fill the database with some data ChronoDBTransaction tx = db.tx(); tx.put("first", 123); tx.put("MyKeyspace", "second", 456); tx.commit(); tx.put("first", 789); tx.put("MyOtherKeyspace", "third", 321); tx.commit(); // at this point, our branch should not exist yet assertEquals(false, db.getBranchManager().existsBranch("MyBranch")); // create the branch db.getBranchManager().createBranch("MyBranch"); // make sure that the branch exists now assertTrue(db.getBranchManager().existsBranch("MyBranch")); // access the branch tx = db.tx("MyBranch"); // make sure that the tx has the proper timestamp assertTrue(tx.getTimestamp() > 0); // assert that the data is in the branch assertEquals(1, tx.keySet().size()); assertEquals(789, (int) tx.get("first")); assertEquals(456, (int) tx.get("MyKeyspace", "second")); assertEquals(321, (int) tx.get("MyOtherKeyspace", "third")); } @Test public void branchingFromBranchWorks() { ChronoDB db = this.getChronoDB(); // fill the database with some data ChronoDBTransaction tx = db.tx(); tx.put("first", 123); tx.put("MyKeyspace", "second", 456); tx.commit(); // create a branch db.getBranchManager().createBranch("MyBranch"); // insert some data into the branch tx = db.tx("MyBranch"); tx.put("Math", "Pi", 31415); tx.commit(); // create a sub-branch db.getBranchManager().createBranch("MyBranch", "MySubBranch"); // commit something in the master branch tx = db.tx(); tx.put("MyAwesomeKeyspace", "third", 789); tx.commit(); // assert that each branch contains the correct information tx = db.tx("MySubBranch"); // Keyspaces in 'MySubBranch': default, MyKeyspace, Math assertEquals(3, tx.keyspaces().size()); assertEquals(31415, (int) tx.get("Math", "Pi")); assertEquals(456, (int) tx.get("MyKeyspace", "second")); assertEquals(123, (int) tx.get("first")); assertEquals(false, tx.keyspaces().contains("MyAwesomeKeyspace")); tx = db.tx(); // Keyspaces in 'Master': default, MyKeyspace, MyAwesomeKeyspace assertEquals(3, tx.keyspaces().size()); assertEquals(789, (int) tx.get("MyAwesomeKeyspace", "third")); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") public void overridingValuesInBranchWorks() { ChronoDB db = this.getChronoDB(); // create three entries in the master branch ChronoDBTransaction tx = db.tx(); tx.put("np1", NamedPayload.create10KB("NP1")); tx.put("np2", NamedPayload.create10KB("NP2")); tx.put("np3", NamedPayload.create10KB("NP3")); tx.commit(); // remember the timestamp after writing to master long afterWritingToMaster = tx.getTimestamp(); // then, branch from master Branch sub = db.getBranchManager().createBranch("Sub"); assertNotNull(sub); assertEquals(db.getBranchManager().getMasterBranch(), sub.getOrigin()); assertEquals(afterWritingToMaster, sub.getBranchingTimestamp()); // in the new branch, override the value for "np2" ChronoDBTransaction txSub = db.tx("Sub"); txSub.put("np2", NamedPayload.create10KB("NP2_SUB")); txSub.commit(); // remember the timestamp after writing to sub long afterWritingToSub = txSub.getTimestamp(); // create another branch from sub Branch subsub = db.getBranchManager().createBranch("Sub", "SubSub"); assertNotNull(subsub); assertEquals(sub, subsub.getOrigin()); assertEquals(afterWritingToSub, subsub.getBranchingTimestamp()); // override the value for "np3" in subsub ChronoDBTransaction txSubSub = db.tx("SubSub"); txSubSub.put("np3", NamedPayload.create10KB("NP3_SUBSUB")); txSubSub.commit(); // in the master branch, we still want to see our original values assertEquals("NP1", ((NamedPayload) db.tx().get("np1")).getName()); assertEquals("NP2", ((NamedPayload) db.tx().get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx().get("np3")).getName()); // in the sub branch, we want to see our override of np2 assertEquals("NP1", ((NamedPayload) db.tx("Sub").get("np1")).getName()); assertEquals("NP2_SUB", ((NamedPayload) db.tx("Sub").get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx("Sub").get("np3")).getName()); // in the subsub branch, we want to see all of our overrides assertEquals("NP1", ((NamedPayload) db.tx("SubSub").get("np1")).getName()); assertEquals("NP2_SUB", ((NamedPayload) db.tx("SubSub").get("np2")).getName()); assertEquals("NP3_SUBSUB", ((NamedPayload) db.tx("SubSub").get("np3")).getName()); // on ANY branch, if we request the timestamp after committing to master, we want to see our original values assertEquals("NP1", ((NamedPayload) db.tx(afterWritingToMaster).get("np1")).getName()); assertEquals("NP2", ((NamedPayload) db.tx(afterWritingToMaster).get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx(afterWritingToMaster).get("np3")).getName()); assertEquals("NP1", ((NamedPayload) db.tx("Sub", afterWritingToMaster).get("np1")).getName()); assertEquals("NP2", ((NamedPayload) db.tx("Sub", afterWritingToMaster).get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx("Sub", afterWritingToMaster).get("np3")).getName()); assertEquals("NP1", ((NamedPayload) db.tx("SubSub", afterWritingToMaster).get("np1")).getName()); assertEquals("NP2", ((NamedPayload) db.tx("SubSub", afterWritingToMaster).get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx("SubSub", afterWritingToMaster).get("np3")).getName()); // assert that our keyset is the same in all branches, at the timestamp after inserting to master Set<String> keySet = Sets.newHashSet("np1", "np2", "np3"); assertEquals(keySet, db.tx(afterWritingToMaster).keySet()); assertEquals(keySet, db.tx("Sub", afterWritingToMaster).keySet()); assertEquals(keySet, db.tx("SubSub", afterWritingToMaster).keySet()); // in order to assert that we have valid timestamps after our insertions, we insert another pair everywhere ChronoDBTransaction tx2 = db.tx(); tx2.put("np4", NamedPayload.create10KB("NP4")); tx2.commit(); ChronoDBTransaction tx3 = db.tx("Sub"); tx3.put("np4", NamedPayload.create10KB("NP4")); tx3.commit(); ChronoDBTransaction tx4 = db.tx("SubSub"); tx4.put("np4", NamedPayload.create10KB("NP4")); tx4.commit(); // after overriding the entry in "Sub", we want to see the original values in master assertEquals("NP1", ((NamedPayload) db.tx(afterWritingToSub).get("np1")).getName()); assertEquals("NP2", ((NamedPayload) db.tx(afterWritingToSub).get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx(afterWritingToSub).get("np3")).getName()); // ... but we want to see our changes in sub assertEquals("NP1", ((NamedPayload) db.tx("Sub", afterWritingToSub).get("np1")).getName()); assertEquals("NP2_SUB", ((NamedPayload) db.tx("Sub", afterWritingToSub).get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx("Sub", afterWritingToSub).get("np3")).getName()); // ... in SubSub, we don't want to see our change, because it hasn't happened yet assertEquals("NP1", ((NamedPayload) db.tx("SubSub", afterWritingToSub).get("np1")).getName()); assertEquals("NP2_SUB", ((NamedPayload) db.tx("SubSub", afterWritingToSub).get("np2")).getName()); assertEquals("NP3", ((NamedPayload) db.tx("SubSub", afterWritingToSub).get("np3")).getName()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") public void addingValuesInBranchesWorks() { ChronoDB db = this.getChronoDB(); // create three entries in the master branch ChronoDBTransaction tx = db.tx(); tx.put("np1", NamedPayload.create10KB("NP1")); tx.commit(); // remember the timestamp after writing to master long afterWritingToMaster = tx.getTimestamp(); // then, branch from master Branch sub = db.getBranchManager().createBranch("Sub"); assertNotNull(sub); assertEquals(db.getBranchManager().getMasterBranch(), sub.getOrigin()); assertEquals(afterWritingToMaster, sub.getBranchingTimestamp()); // in the new branch, override the value for "np2" ChronoDBTransaction txSub = db.tx("Sub"); txSub.put("np2", NamedPayload.create10KB("NP2_SUB")); txSub.commit(); // remember the timestamp after writing to sub long afterWritingToSub = txSub.getTimestamp(); // create another branch from sub Branch subsub = db.getBranchManager().createBranch("Sub", "SubSub"); assertNotNull(subsub); assertEquals(sub, subsub.getOrigin()); assertEquals(afterWritingToSub, subsub.getBranchingTimestamp()); // override the value for "np3" in subsub ChronoDBTransaction txSubSub = db.tx("SubSub"); txSubSub.put("np3", NamedPayload.create10KB("NP3_SUBSUB")); txSubSub.commit(); // in the master branch, we still want to see our original value, and nothing else assertEquals("NP1", ((NamedPayload) db.tx().get("np1")).getName()); assertNull(db.tx().get("np2")); assertNull(db.tx().get("np3")); // in the sub branch, we want to see our addition of np2 assertEquals("NP1", ((NamedPayload) db.tx("Sub").get("np1")).getName()); assertEquals("NP2_SUB", ((NamedPayload) db.tx("Sub").get("np2")).getName()); assertNull(db.tx("Sub").get("np3")); // in the subsub branch, we want to see all of our additions assertEquals("NP1", ((NamedPayload) db.tx("SubSub").get("np1")).getName()); assertEquals("NP2_SUB", ((NamedPayload) db.tx("SubSub").get("np2")).getName()); assertEquals("NP3_SUBSUB", ((NamedPayload) db.tx("SubSub").get("np3")).getName()); // on ANY branch, if we request the timestamp after committing to master, we want to see our original values assertEquals("NP1", ((NamedPayload) db.tx(afterWritingToMaster).get("np1")).getName()); assertNull(db.tx().get("np2")); assertNull(db.tx().get("np3")); assertEquals("NP1", ((NamedPayload) db.tx("Sub", afterWritingToMaster).get("np1")).getName()); assertNull(db.tx("Sub", afterWritingToMaster).get("np2")); assertNull(db.tx("Sub", afterWritingToMaster).get("np3")); assertEquals("NP1", ((NamedPayload) db.tx("SubSub", afterWritingToMaster).get("np1")).getName()); assertNull(db.tx("SubSub", afterWritingToMaster).get("np2")); assertNull(db.tx("SubSub", afterWritingToMaster).get("np3")); // assert that the key sets are valid assertEquals(Sets.newHashSet("np1"), db.tx().keySet()); assertEquals(Sets.newHashSet("np1", "np2"), db.tx("Sub").keySet()); assertEquals(Sets.newHashSet("np1", "np2", "np3"), db.tx("SubSub").keySet()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") public void removingValuesInBranchWorks() { ChronoDB db = this.getChronoDB(); // create three entries in the master branch ChronoDBTransaction tx = db.tx(); tx.put("np1", NamedPayload.create10KB("NP1")); tx.put("np2", NamedPayload.create10KB("NP2")); tx.put("np3", NamedPayload.create10KB("NP3")); tx.commit(); // remember the timestamp for later use long afterWritingToMaster = tx.getTimestamp(); // create a branch Branch sub = db.getBranchManager().createBranch("Sub"); assertNotNull(sub); assertEquals(db.getBranchManager().getMasterBranch(), sub.getOrigin()); assertEquals(afterWritingToMaster, sub.getBranchingTimestamp()); // remove a value from the branch ChronoDBTransaction txSub = db.tx("Sub"); txSub.remove("np2"); txSub.commit(); long afterWritingToSub = txSub.getTimestamp(); // create another sub-branch Branch subSub = db.getBranchManager().createBranch("Sub", "SubSub"); assertNotNull(subSub); assertEquals(sub, subSub.getOrigin()); assertEquals(afterWritingToSub, subSub.getBranchingTimestamp()); // remove another value in subsub-branch ChronoDBTransaction txSubSub = db.tx("SubSub"); txSubSub.remove("np3"); txSubSub.commit(); // in order to assert that we have valid timestamps after our insertions, we insert another pair everywhere ChronoDBTransaction tx2 = db.tx(); tx2.put("np4", NamedPayload.create10KB("NP4")); tx2.commit(); ChronoDBTransaction tx3 = db.tx("Sub"); tx3.put("np4", NamedPayload.create10KB("NP4")); tx3.commit(); ChronoDBTransaction tx4 = db.tx("SubSub"); tx4.put("np4", NamedPayload.create10KB("NP4")); tx4.commit(); // assert that the values are still present in the master branch assertNotNull(db.tx().get("np1")); assertNotNull(db.tx().get("np2")); assertNotNull(db.tx().get("np3")); assertNotNull(db.tx().get("np4")); assertEquals(Sets.newHashSet("np1", "np2", "np3", "np4"), db.tx().keySet()); // assert that the "np2" value is gone in Sub, but the other values are still present assertNotNull(db.tx("Sub").get("np1")); assertNull(db.tx("Sub").get("np2")); assertNotNull(db.tx("Sub").get("np3")); assertNotNull(db.tx("Sub").get("np4")); assertEquals(Sets.newHashSet("np1", "np3", "np4"), db.tx("Sub").keySet()); // assert that "np2" and "np3" are gone in SubSub, but the other values are still present assertNotNull(db.tx("SubSub").get("np1")); assertNull(db.tx("SubSub").get("np2")); assertNull(db.tx("SubSub").get("np3")); assertNotNull(db.tx("SubSub").get("np4")); assertEquals(Sets.newHashSet("np1", "np4"), db.tx("SubSub").keySet()); } @Test public void canUseBranchNamesWithNonAlphanumericCharacters() { ChronoDB db = this.getChronoDB(); String testBranchName = "#!?$§&:;- `\""; String subBranchName = "*+~.,<>|"; Person john = new Person("John", "Doe"); Person jane = new Person("Jane", "Doe"); db.getIndexManager().createIndex().withName("firstName").withIndexer(PersonIndexer.firstName()).onMaster().acrossAllTimestamps().build(); db.getBranchManager().createBranch(testBranchName); { ChronoDBTransaction tx = db.tx(testBranchName); tx.put("john", john); tx.commit(); } db.getBranchManager().createBranch(testBranchName, subBranchName); { ChronoDBTransaction tx = db.tx(subBranchName); tx.put("jane", jane); tx.commit(); } assertEquals(john, db.tx(testBranchName).get("john")); assertEquals(jane, db.tx(subBranchName).get("jane")); assertEquals(john, db.tx(testBranchName).get("john")); assertNull(db.tx(testBranchName).get("jane")); } }
18,263
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchSecondaryIndexingTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/branching/BranchSecondaryIndexingTest.java
package org.chronos.chronodb.test.cases.engine.branching; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.exceptions.ChronoDBIndexingException; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.model.person.FirstNameIndexer; import org.chronos.chronodb.test.cases.util.model.person.LastNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.model.person.Person; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class BranchSecondaryIndexingTest extends AllChronoDBBackendsTest { @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "20") public void canAddMultiplicityManyValuesInBranch() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new TestObjectNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx1 = db.tx(); tx1.put("one", new TestObject("One", "TO_One")); tx1.put("two", new TestObject("Two", "TO_Two")); tx1.commit(); // assert that we can now find these objects assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("One").count()); assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("TO_One").count()); assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("Two").count()); assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("TO_Two").count()); // create a branch Branch branch = db.getBranchManager().createBranch("MyBranch"); assertNotNull(branch); assertEquals(db.getBranchManager().getMasterBranch(), branch.getOrigin()); assertEquals(tx1.getTimestamp(), branch.getBranchingTimestamp()); // in the branch, add an additional value to "Two" ChronoDBTransaction tx2 = db.tx("MyBranch"); tx2.put("two", new TestObject("Two", "TO_Two", "Hello World")); tx2.commit(); // now, in the branch, we should be able to find the new entry with a query assertEquals(1, db.tx("MyBranch").find().inDefaultKeyspace().where("name").containsIgnoreCase("world").count()); // we still should find the "one" entry assertEquals(1, db.tx("MyBranch").find().inDefaultKeyspace().where("name").containsIgnoreCase("one").count()); // in the master branch, we know nothing about it assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("world").count()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "20") public void canChangeMultiplicityManyValuesInBranch() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new TestObjectNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx1 = db.tx(); tx1.put("one", new TestObject("One", "TO_One")); tx1.put("two", new TestObject("Two", "TO_Two")); tx1.commit(); // assert that we can now find these objects assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("One").count()); assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("TO_One").count()); assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("Two").count()); assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("TO_Two").count()); // create a branch Branch branch = db.getBranchManager().createBranch("MyBranch"); assertNotNull(branch); assertEquals(db.getBranchManager().getMasterBranch(), branch.getOrigin()); assertEquals(tx1.getTimestamp(), branch.getBranchingTimestamp()); // in the branch, add an additional value to "Two" ChronoDBTransaction tx2 = db.tx("MyBranch"); tx2.put("two", new TestObject("Two", "Hello World")); tx2.commit(); // now, in the branch, we should be able to find the new entry with a query assertEquals(1, db.tx("MyBranch").find().inDefaultKeyspace().where("name").containsIgnoreCase("world").count()); // we shouldn't be able to find it under "TO_Two" in the branch assertEquals(0, db.tx("MyBranch").find().inDefaultKeyspace().where("name").isEqualTo("TO_Two").count()); // in the master branch, we know nothing about the change assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("world").count()); // ... but we still find the object under its previous name assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("Two").count()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "20") public void canAddNewIndexedValuesInBranch() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new TestObjectNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx1 = db.tx(); tx1.put("one", new TestObject("One")); tx1.commit(); // assert that we can now find the objects assertEquals(1, tx1.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("One").count()); // create a branch Branch branch = db.getBranchManager().createBranch("MyBranch"); assertNotNull(branch); assertEquals(db.getBranchManager().getMasterBranch(), branch.getOrigin()); assertEquals(tx1.getTimestamp(), branch.getBranchingTimestamp()); // in the branch, add an additional value to "Two" ChronoDBTransaction tx2 = db.tx("MyBranch"); tx2.put("two", new TestObject("Two")); tx2.commit(); // now, in the branch, we should be able to find the new entry with a query assertEquals(1, db.tx("MyBranch").find().inDefaultKeyspace().where("name").containsIgnoreCase("two").count()); // in the master branch, we know nothing about it assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("two").count()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") public void canAddSecondaryIndexOnBranch() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("p1", new Person("John", "Doe")); tx1.put("p2", new Person("Jane", "Doe")); tx1.commit(); db.getBranchManager().createBranch("myBranch"); ChronoDBTransaction tx2 = db.tx("myBranch"); tx2.put("p3", new Person("Jack", "Smith")); long commit2 = tx2.commit(); db.getIndexManager().createIndex() .withName("firstName") .withIndexer(new FirstNameIndexer()) .onBranch("myBranch") .fromTimestamp(commit2) .toInfinity() .build(); db.getIndexManager().reindexAll(); Set<QualifiedKey> queryResult1 = db.tx("myBranch").find() .inDefaultKeyspace() .where("firstName") .startsWith("Ja") .getKeysAsSet(); assertEquals( Sets.newHashSet( QualifiedKey.createInDefaultKeyspace("p2"), // Jane QualifiedKey.createInDefaultKeyspace("p3") // Jack ), queryResult1 ); ChronoDBTransaction tx3 = db.tx("myBranch"); tx3.put("p4", new Person("Janine", "Smith")); tx3.commit(); Set<QualifiedKey> queryResult2 = db.tx("myBranch").find() .inDefaultKeyspace() .where("firstName") .startsWith("Ja") .getKeysAsSet(); assertEquals( Sets.newHashSet( QualifiedKey.createInDefaultKeyspace("p2"), // Jane QualifiedKey.createInDefaultKeyspace("p3"), // Jack QualifiedKey.createInDefaultKeyspace("p4") // Janine ), queryResult2 ); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") public void canAddTimeLimitedIndicesAfterwards() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("p1", new Person("John", "Doe")); tx1.put("p2", new Person("Jane", "Doe")); long commit1 = tx1.commit(); sleep(5); ChronoDBTransaction tx2 = db.tx(); tx2.put("p3", new Person("Jack", "Smith")); long commit2 = tx2.commit(); sleep(5); if (db.getFeatures().isRolloverSupported()) { db.getMaintenanceManager().performRolloverOnMaster(); } sleep(5); ChronoDBTransaction tx3 = db.tx(); tx3.put("p4", new Person("Janine", "Smith")); long commit3 = tx3.commit(); sleep(5); ChronoDBTransaction tx4 = db.tx(); tx4.remove("p1"); long commit4 = tx4.commit(); sleep(5); if (db.getFeatures().isRolloverSupported()) { db.getMaintenanceManager().performRolloverOnMaster(); } sleep(5); ChronoDBTransaction tx5 = db.tx(); tx5.put("p5", new Person("Sarah", "Doe")); long commit5 = tx5.commit(); System.out.println("Commit1:" + commit1); System.out.println("Commit2:" + commit2); System.out.println("Commit3:" + commit3); System.out.println("Commit4:" + commit4); System.out.println("Commit5:" + commit5); db.getIndexManager().createIndex() .withName("firstName") .withIndexer(new FirstNameIndexer()) .onMaster() .fromTimestamp(0).toTimestamp(commit2 + 2) .build(); db.getIndexManager().createIndex() .withName("firstName") .withIndexer(new FirstNameIndexer()) .onMaster() .fromTimestamp(commit4) .toInfinity() .build(); db.getIndexManager().createIndex().withName("lastName").withIndexer(new LastNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // Check index "firstName" which exists in periods assertEquals(0, db.tx(commit1 - 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(2, db.tx(commit1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(2, db.tx(commit1 + 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(2, db.tx(commit2 - 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit2).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit2 + 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); // unavailable on commit3 assertEquals(Sets.newHashSet( "p3", "p2", "p4" ) , db.tx(commit4).find().inDefaultKeyspace().where("firstName").startsWith("J").getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet())); assertEquals(3, db.tx(commit4).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit4 + 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit5 - 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit5).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); // Check index "lastName" which exists on all timestamps assertEquals(0, db.tx(commit1 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit1 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit2 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit2).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit2 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit3 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit3).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit3 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit4 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(1, db.tx(commit4).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(1, db.tx(commit4 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(1, db.tx(commit5 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit5).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") public void canAddIndexOnHead() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("lastName").withIndexer(new LastNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx1 = db.tx(); tx1.put("p1", new Person("John", "Doe")); tx1.put("p2", new Person("Jane", "Doe")); long commit1 = tx1.commit(); sleep(5); ChronoDBTransaction tx2 = db.tx(); tx2.put("p3", new Person("Jack", "Smith")); long commit2 = tx2.commit(); sleep(5); if (db.getFeatures().isRolloverSupported()) { db.getMaintenanceManager().performRolloverOnMaster(); } sleep(5); ChronoDBTransaction tx3 = db.tx(); tx3.put("p4", new Person("Janine", "Smith")); long commit3 = tx3.commit(); sleep(5); db.getIndexManager().createIndex() .withName("firstName") .withIndexer(new FirstNameIndexer()) .onMaster() .fromTimestamp(db.tx().getTimestamp()) .toInfinity() .build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx4 = db.tx(); tx4.remove("p1"); long commit4 = tx4.commit(); sleep(5); if (db.getFeatures().isRolloverSupported()) { db.getMaintenanceManager().performRolloverOnMaster(); } sleep(5); ChronoDBTransaction tx5 = db.tx(); tx5.put("p5", new Person("Sarah", "Doe")); long commit5 = tx5.commit(); System.out.println("Commit1:" + commit1); System.out.println("Commit2:" + commit2); System.out.println("Commit3:" + commit3); System.out.println("Commit4:" + commit4); System.out.println("Commit5:" + commit5); try { db.tx(commit3 - 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count(); fail("Managed to query index outside its validity range"); } catch (ChronoDBIndexingException expected) { // pass } assertEquals( Sets.newHashSet("p3", "p2", "p4"), db.tx(commit4).find().inDefaultKeyspace().where("firstName").startsWith("J").getUnqualifiedKeysAsSet() ); assertEquals(3, db.tx(commit4).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit4 + 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit5 - 1).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); assertEquals(3, db.tx(commit5).find().inDefaultKeyspace().where("firstName").startsWith("J").count()); // Check index "lastName" which exists on all timestamps assertEquals(0, db.tx(commit1 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit1 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit2 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit2).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit2 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit3 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit3).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit3 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit4 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(1, db.tx(commit4).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(1, db.tx(commit4 + 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(1, db.tx(commit5 - 1).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); assertEquals(2, db.tx(commit5).find().inDefaultKeyspace().where("lastName").isEqualTo("Doe").count()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "1000") public void canAddIndexOnDeltaChunk() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("p1", new Person("John", "Doe")); tx1.put("p2", new Person("Jane", "Doe")); tx1.put("p3", new Person("Jack", "Smith")); tx1.put("p4", new Person("Janine", "Smith")); tx1.commit(); ChronoDBTransaction tx2 = db.tx(); tx2.remove("p1"); tx2.commit(); db.getBranchManager().createBranch("myBranch"); ChronoDBTransaction tx3 = db.tx(); tx3.remove("p4"); tx3.put("p5", new Person("Sarah", "Doe")); tx3.commit(); ChronoDBTransaction tx4 = db.tx("myBranch"); tx4.remove("p3"); tx4.put("p2", new Person("NoLongerJane", "Doe")); tx4.put("p6", new Person("Jeanne", "Brancher")); long commit4 = tx4.commit(); db.getIndexManager().createIndex() .withName("firstName") .withIndexer(new FirstNameIndexer()) .onBranch("myBranch") .fromTimestamp(commit4) .toInfinity() .build(); db.getIndexManager().reindexAll(); Set<String> queryResult = db.tx("myBranch").find() .inDefaultKeyspace() .where("firstName") .startsWith("J") .getUnqualifiedKeysAsSet(); assertEquals(Sets.newHashSet("p4", "p6"), queryResult); } private static class TestObject { private Set<String> names; @SuppressWarnings("unused") protected TestObject() { // for serialization } public TestObject(final String... names) { this.names = Sets.newHashSet(names); } public Set<String> getNames() { return this.names; } } private static class TestObjectNameIndexer implements StringIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return object instanceof TestObject; } @Override public Set<String> getIndexValues(final Object object) { TestObject testObject = (TestObject) object; return Sets.newHashSet(testObject.getNames()); } } }
22,669
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchDeletionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/branching/BranchDeletionTest.java
package org.chronos.chronodb.test.cases.engine.branching;//package org.chronos.chronodb.test.cases.engine.branching; // //import org.chronos.chronodb.api.ChronoDB; //import org.chronos.chronodb.api.ChronoDBConstants; //import org.chronos.chronodb.api.ChronoDBTransaction; //import org.chronos.chronodb.api.exceptions.ChronoDBBranchingException; //import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; //import org.chronos.common.test.junit.categories.IntegrationTest; //import org.junit.Test; //import org.junit.experimental.categories.Category; // //@Category(IntegrationTest.class) //public class BranchDeletionTest extends AllChronoDBBackendsTest { // // @Test // public void cannotRemoveMasterBranch() { // ChronoDB db = this.getChronoDB(); // try { // db.getBranchManager().removeBranch(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); // fail("Managed to delete master branch!"); // } catch (ChronoDBBranchingException e) { // // expected // } // // assert that the master branch is still present // assertTrue(db.getBranchManager().existsBranch(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER)); // } // // @Test // public void removingABranchWorks() { // ChronoDB db = this.getChronoDB(); // // assert that the branch initially does not exist // assertEquals(false, db.getBranchManager().existsBranch("MyBranch")); // // create the branch // db.getBranchManager().createBranch("MyBranch"); // // assert that it exists // db.getBranchManager().existsBranch("MyBranch"); // // fill it with some data // ChronoDBTransaction tx = db.tx("MyBranch"); // tx.put("first", 123); // tx.put("second", 456); // tx.commit(); // tx.put("third", 789); // tx.commit(); // // assert that the data is present in the branch // assertEquals(3, tx.keySet().size()); // // assert that the master branch is still empty // tx = db.tx(); // assertTrue(tx.keySet().isEmpty()); // // remove the branch // db.getBranchManager().removeBranch("MyBranch"); // // assert that the branch is gone // assertEquals(false, db.getBranchManager().existsBranch("MyBranch")); // } //}
2,087
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexOverwriteTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/IndexOverwriteTest.java
package org.chronos.chronodb.test.cases.engine.indexing; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class IndexOverwriteTest extends AllChronoDBBackendsTest { @Test public void overwrittenIndexEntryIsNoLongerPresent() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long afterFirstWrite = tx.getTimestamp(); // then, rename np1 and commit it (same key -> second version) np1 = NamedPayload.create1KB("Overwritten"); tx.put("np1", np1); tx.commit(); // open a read transaction after the first write ChronoDBTransaction tx2 = db.tx(afterFirstWrite); // assert that the "hello world" element is there long count = tx2.find().inDefaultKeyspace().where("name").isEqualTo("Hello World").count(); assertEquals(1, count); // open a read transaction on "now" and assert that it is gone ChronoDBTransaction tx3 = db.tx(); long count2 = tx3.find().inDefaultKeyspace().where("name").isEqualTo("Hello World").count(); assertEquals(0, count2); // however, the "overwritten" name should appear long count3 = tx3.find().inDefaultKeyspace().where("name").isEqualTo("Overwritten").count(); assertEquals(1, count3); } }
2,438
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexMatchModesTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/IndexMatchModesTest.java
package org.chronos.chronodb.test.cases.engine.indexing; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class IndexMatchModesTest extends AllChronoDBBackendsTest { @Test public void testEquals() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); // positive test: there must be exactly one key-value pair where "name" is equal to "Foo Bar" long count = tx.find().inDefaultKeyspace().where("name").isEqualTo("Foo Bar").count(); assertEquals(1, count); // negative test: we are performing EQUALS, so no key-value pair with name "Foo" must exist long count2 = tx.find().inDefaultKeyspace().where("name").isEqualTo("Foo").count(); assertEquals(0, count2); } @Test public void testEqualsIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); // positive test: there must be exactly one key-value pair where case-insensitive "name" is equal to "foo bar" long count; count = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("Foo Bar").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("fOO bAR").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("foo bar").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("FOO BAR").count(); assertEquals(1, count); // negative test: we are performing EQUALS, so no key-value pair with case-insensitive name "foo" must exist long count2; count2 = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("Foo").count(); assertEquals(0, count2); count2 = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("fOO").count(); assertEquals(0, count2); count2 = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("foo").count(); assertEquals(0, count2); count2 = tx.find().inDefaultKeyspace().where("name").isEqualToIgnoreCase("FOO").count(); assertEquals(0, count2); } @Test public void testNotEquals() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().not().where("name").isEqualTo("Foo Bar").count(); assertEquals(2, count); long count2 = tx.find().inDefaultKeyspace().not().where("name").isEqualTo("Foo").count(); assertEquals(3, count2); } @Test public void testNotEqualsIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count; count = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("Foo Bar").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("fOO bAR").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("foo bar").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("FOO BAR").count(); assertEquals(2, count); long count2; count2 = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("Foo").count(); assertEquals(3, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("fOO").count(); assertEquals(3, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("foo").count(); assertEquals(3, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").isEqualToIgnoreCase("FOO").count(); assertEquals(3, count2); } @Test public void testContains() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); // whole words long count = tx.find().inDefaultKeyspace().where("name").contains("Foo").count(); assertEquals(2, count); // partial words long count2 = tx.find().inDefaultKeyspace().where("name").contains("oo").count(); assertEquals(2, count2); // at end of word long count3 = tx.find().inDefaultKeyspace().where("name").contains("ld").count(); assertEquals(1, count3); } @Test public void testContainsIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); // whole words long count; count = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("Foo").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("fOO").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("foo").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("FOO").count(); assertEquals(2, count); // partial words long count2; count2 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("oo").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("OO").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("oO").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("Oo").count(); assertEquals(2, count2); // at end of word long count3; count3 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("ld").count(); assertEquals(1, count3); count3 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("LD").count(); assertEquals(1, count3); count3 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("lD").count(); assertEquals(1, count3); count3 = tx.find().inDefaultKeyspace().where("name").containsIgnoreCase("Ld").count(); assertEquals(1, count3); } @Test public void testNotContains() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); // whole words long count = tx.find().inDefaultKeyspace().not().where("name").contains("Foo").count(); assertEquals(1, count); // partial words long count2 = tx.find().inDefaultKeyspace().not().where("name").contains("oo").count(); assertEquals(1, count2); // at end of word long count3 = tx.find().inDefaultKeyspace().not().where("name").contains("ld").count(); assertEquals(2, count3); } @Test public void testNotContainsIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); // whole words long count; count = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("Foo").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("fOO").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("foo").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("FOO").count(); assertEquals(1, count); // partial words long count2; count2 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("oo").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("oO").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("Oo").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("OO").count(); assertEquals(1, count2); // at end of word long count3; count3 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("ld").count(); assertEquals(2, count3); count3 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("LD").count(); assertEquals(2, count3); count3 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("Ld").count(); assertEquals(2, count3); count3 = tx.find().inDefaultKeyspace().not().where("name").containsIgnoreCase("lD").count(); assertEquals(2, count3); } @Test public void testStartsWith() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().where("name").startsWith("Foo").count(); assertEquals(2, count); long count2 = tx.find().inDefaultKeyspace().where("name").startsWith("Hello").count(); assertEquals(1, count2); } @Test public void testStartsWithIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count; count = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("Foo").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("fOO").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("foo").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("FOO").count(); assertEquals(2, count); long count2; count2 = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("Hello").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("hELLO").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("hello").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().where("name").startsWithIgnoreCase("HELLO").count(); assertEquals(1, count2); } @Test public void testNotStartsWith() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().not().where("name").startsWith("Foo").count(); assertEquals(1, count); long count2 = tx.find().inDefaultKeyspace().not().where("name").startsWith("Hello").count(); assertEquals(2, count2); } @Test public void testNotStartsWithIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count; count = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("Foo").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("fOO").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("foo").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("FOO").count(); assertEquals(1, count); long count2; count2 = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("Hello").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("hELLO").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("hello").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").startsWithIgnoreCase("HELLO").count(); assertEquals(2, count2); } @Test public void testEndsWith() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().where("name").endsWith("Bar").count(); assertEquals(1, count); long count2 = tx.find().inDefaultKeyspace().where("name").endsWith("World").count(); assertEquals(1, count2); } @Test public void testEndsWithIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count; count = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("Bar").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("bAR").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("bar").count(); assertEquals(1, count); count = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("BAR").count(); assertEquals(1, count); long count2; count2 = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("World").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("wORLD").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("world").count(); assertEquals(1, count2); count2 = tx.find().inDefaultKeyspace().where("name").endsWithIgnoreCase("WORLD").count(); assertEquals(1, count2); } @Test public void testNotEndsWith() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().not().where("name").endsWith("Bar").count(); assertEquals(2, count); long count2 = tx.find().inDefaultKeyspace().not().where("name").endsWith("World").count(); assertEquals(2, count2); } @Test public void testNotEndsWithIgnoreCase() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count; count = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("Bar").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("bAR").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("bar").count(); assertEquals(2, count); count = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("BAR").count(); assertEquals(2, count); long count2; count2 = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("World").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("wORLD").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("world").count(); assertEquals(2, count2); count2 = tx.find().inDefaultKeyspace().not().where("name").endsWithIgnoreCase("WORLD").count(); assertEquals(2, count2); } @Test public void testMatchesRegex() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().where("name").matchesRegex(".*Ba.").count(); assertEquals(2, count); long count2 = tx.find().inDefaultKeyspace().where("name").matchesRegex("Fo+.*").count(); assertEquals(2, count2); } @Test public void testMatchesRegexCaseInsensitive() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().where("name").matchesRegex("(?i)fo+.*").count(); assertEquals(2, count); } @Test public void testNotMatchesRegex() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long count = tx.find().inDefaultKeyspace().not().where("name").matchesRegex(".*o.*").count(); assertEquals(0, count); long count2 = tx.find().inDefaultKeyspace().not().where("name").matchesRegex("Fo+.*").count(); assertEquals(1, count2); } }
27,899
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericIndexingTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/NumericIndexingTest.java
package org.chronos.chronodb.test.cases.engine.indexing; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.exceptions.InvalidIndexAccessException; import org.chronos.chronodb.api.exceptions.UnknownIndexException; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.ReflectiveDoubleIndexer; import org.chronos.chronodb.test.cases.util.ReflectiveLongIndexer; import org.chronos.chronodb.test.cases.util.ReflectiveStringIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class NumericIndexingTest extends AllChronoDBBackendsTest { // ================================================================================================================= // LONG INDEX TESTS // ================================================================================================================= @Test public void canCreateLongIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveLongIndexer(LongBean.class, "value")).onMaster().acrossAllTimestamps().build(); assertEquals(1, db.getIndexManager().getIndices().size()); } @Test public void canExecuteBasicQueryOnLongIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveLongIndexer(LongBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new LongBean(34)); tx.put("b", new LongBean(27)); tx.commit(); tx.put("c", new LongBean(13)); tx.commit(); } // query the data assertKeysEqual("a", "b", db.tx().find().inDefaultKeyspace().where("value").isGreaterThan(20)); assertKeysEqual("a", db.tx().find().inDefaultKeyspace().where("value").isGreaterThan(27)); assertKeysEqual("a", "b", db.tx().find().inDefaultKeyspace().where("value").isGreaterThanOrEqualTo(27)); assertKeysEqual("c", db.tx().find().inDefaultKeyspace().where("value").isEqualTo(13)); assertKeysEqual("c", db.tx().find().inDefaultKeyspace().where("value").isLessThan(27)); assertKeysEqual("b", "c", db.tx().find().inDefaultKeyspace().where("value").isLessThanOrEqualTo(27)); } // ================================================================================================================= // DOUBLE INDEX TESTS // ================================================================================================================= @Test public void canCreateDoubleIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveDoubleIndexer(DoubleBean.class, "value")).onMaster().acrossAllTimestamps().build(); assertEquals(1, db.getIndexManager().getIndices().size()); } @Test public void canExecuteBasicQueryOnDoubleIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveDoubleIndexer(DoubleBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new DoubleBean(34.1)); tx.put("b", new DoubleBean(27.8)); tx.commit(); tx.put("c", new DoubleBean(13.4)); tx.commit(); } // query the data assertKeysEqual("a", "b", db.tx().find().inDefaultKeyspace().where("value").isGreaterThan(20.4)); assertKeysEqual("a", db.tx().find().inDefaultKeyspace().where("value").isGreaterThan(27.8)); assertKeysEqual("a", "b", db.tx().find().inDefaultKeyspace().where("value").isGreaterThanOrEqualTo(27.8)); assertKeysEqual("c", db.tx().find().inDefaultKeyspace().where("value").isEqualTo(13.4, 0.01)); assertKeysEqual("c", db.tx().find().inDefaultKeyspace().where("value").isLessThan(27.8)); assertKeysEqual("b", "c", db.tx().find().inDefaultKeyspace().where("value").isLessThanOrEqualTo(27.8)); } // ================================================================================================================= // NEGATIVE TESTS // ================================================================================================================= @Test public void cannotSearchForDoubleValueInLongIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveLongIndexer(LongBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new LongBean(34)); tx.put("b", new LongBean(27)); tx.commit(); tx.put("c", new LongBean(13)); tx.commit(); } try { db.tx().find().inDefaultKeyspace().where("value").isEqualTo(34.0, 0.001).getKeysAsSet(); fail("Managed to access index with query of wrong type!"); } catch (InvalidIndexAccessException expected) { // pass } } @Test public void cannotSearchForStringValueInLongIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveLongIndexer(LongBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new LongBean(34)); tx.put("b", new LongBean(27)); tx.commit(); tx.put("c", new LongBean(13)); tx.commit(); } try { db.tx().find().inDefaultKeyspace().where("value").isEqualTo("34").getKeysAsSet(); fail("Managed to access index with query of wrong type!"); } catch (InvalidIndexAccessException expected) { // pass } } @Test public void cannotSearchForLongValueInDoubleIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveDoubleIndexer(DoubleBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new DoubleBean(34.5)); tx.put("b", new DoubleBean(27.8)); tx.commit(); tx.put("c", new DoubleBean(13.4)); tx.commit(); } try { db.tx().find().inDefaultKeyspace().where("value").isEqualTo(34).getKeysAsSet(); fail("Managed to access index with query of wrong type!"); } catch (InvalidIndexAccessException expected) { // pass } } @Test public void cannotSearchForStringValueInDoubleIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveDoubleIndexer(DoubleBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new DoubleBean(34.5)); tx.put("b", new DoubleBean(27.8)); tx.commit(); tx.put("c", new DoubleBean(13.4)); tx.commit(); } try { db.tx().find().inDefaultKeyspace().where("value").isEqualTo("34.0").getKeysAsSet(); fail("Managed to access index with query of wrong type!"); } catch (InvalidIndexAccessException expected) { // pass } } @Test public void cannotSearchForLongValueInStringIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveStringIndexer(StringBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new StringBean("34.5")); tx.put("b", new StringBean("27.8")); tx.commit(); tx.put("c", new StringBean("13.4")); tx.commit(); } try { db.tx().find().inDefaultKeyspace().where("value").isEqualTo(34).getKeysAsSet(); fail("Managed to access index with query of wrong type!"); } catch (InvalidIndexAccessException expected) { // pass } } @Test public void cannotSearchForDoubleValueInStringIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("value").withIndexer(new ReflectiveStringIndexer(StringBean.class, "value")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // insert some data ChronoDBTransaction tx = db.tx(); tx.put("a", new StringBean("34.5")); tx.put("b", new StringBean("27.8")); tx.commit(); tx.put("c", new StringBean("13.4")); tx.commit(); } try { db.tx().find().inDefaultKeyspace().where("value").isEqualTo(34.5, 0.001).getKeysAsSet(); fail("Managed to access index with query of wrong type!"); } catch (InvalidIndexAccessException expected) { // pass } } @Test public void cannotQueryNonExistingIndex() { ChronoDB db = this.getChronoDB(); try { db.tx().find().inDefaultKeyspace().where("hello").isEqualTo("world").getKeysAsSet(); fail("Managed to access non-existent index!"); } catch (UnknownIndexException expected) { // pass } } // ================================================================================================================= // INNER CLASSES // ================================================================================================================= @SuppressWarnings("unused") private static class TestBean<T> { private T value; protected TestBean() { } protected TestBean(final T value) { checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); this.value = value; } public T getValue() { return this.value; } } @SuppressWarnings("unused") private static class LongBean extends TestBean<Long> { protected LongBean() { } public LongBean(final long value) { super(value); } } @SuppressWarnings("unused") private static class DoubleBean extends TestBean<Double> { protected DoubleBean() { } public DoubleBean(final double value) { super(value); } } @SuppressWarnings("unused") private static class StringBean extends TestBean<String> { protected StringBean() { } public StringBean(final String value) { super(value); } } }
11,863
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexingTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/IndexingTest.java
package org.chronos.chronodb.test.cases.engine.indexing; import com.google.common.collect.Sets; import org.chronos.chronodb.api.*; import org.chronos.chronodb.api.exceptions.ChronoDBIndexingException; import org.chronos.chronodb.api.exceptions.UnknownIndexException; import org.chronos.chronodb.api.indexing.DoubleIndexer; import org.chronos.chronodb.api.indexing.Indexer; import org.chronos.chronodb.api.indexing.LongIndexer; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.query.Condition; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.index.IndexManagerInternal; import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification; import org.chronos.chronodb.internal.api.query.searchspec.StringSearchSpecification; import org.chronos.chronodb.internal.impl.index.IndexingOption; import org.chronos.chronodb.internal.impl.index.SecondaryIndexImpl; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import java.lang.reflect.Field; import java.util.Collections; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class IndexingTest extends AllChronoDBBackendsTest { @Test public void indexWritingWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); SecondaryIndex index = db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); Branch masterBranch = db.getBranchManager().getMasterBranch(); String defaultKeyspace = ChronoDBConstants.DEFAULT_KEYSPACE_NAME; // assert that the index is correct SearchSpecification<?, ?> searchSpec = StringSearchSpecification.create( index, Condition.EQUALS, TextMatchMode.STRICT, "Hello World" ); Set<String> r1 = db.getIndexManager().queryIndex( System.currentTimeMillis(), masterBranch, defaultKeyspace, searchSpec ); assertEquals(1, r1.size()); assertEquals("np1", r1.iterator().next()); } @Test public void readingNonExistentIndexFailsGracefully() { ChronoDB db = this.getChronoDB(); String indexId = "dd1f3a91-12d5-47bd-a343-7b15a3475f09"; SecondaryIndex index = new SecondaryIndexImpl( indexId, "shenaningan", new NamedPayloadNameIndexer(), Period.eternal(), ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, null, false, Collections.emptySet() ); try { Branch masterBranch = db.getBranchManager().getMasterBranch(); String defaultKeyspace = ChronoDBConstants.DEFAULT_KEYSPACE_NAME; SearchSpecification<?, ?> searchSpec = StringSearchSpecification.create(index, Condition.EQUALS, TextMatchMode.STRICT, "Hello World"); db.getIndexManager().queryIndex(System.currentTimeMillis(), masterBranch, defaultKeyspace, searchSpec); fail(); } catch (UnknownIndexException e) { // expected } } @Test public void renameTest() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); ChronoDBTransaction tx2 = db.tx(); tx2.put("np1", NamedPayload.create1KB("Renamed")); tx2.commit(); // check that we can find the renamed element by its new name assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").isEqualTo("Renamed").count()); // check that we cannot find the renamed element by its old name anymore assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").isEqualTo("Hello World").count()); // in the past, we should still find the non-renamed version assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("Hello World").count()); // in the past, we should not find the renamed version assertEquals(0, tx.find().inDefaultKeyspace().where("name").isEqualTo("Renamed").count()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "20") public void deleteTest() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("np1"); NamedPayload np2 = NamedPayload.create1KB("np2"); NamedPayload np3 = NamedPayload.create1KB("np3"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); ChronoDBTransaction tx2 = db.tx(); assertEquals(3, db.tx().find().inDefaultKeyspace().where("name").startsWithIgnoreCase("np").count()); tx2.remove("np1"); tx2.remove("np3"); tx2.commit(); assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").startsWithIgnoreCase("np").count()); assertEquals(Collections.singleton("np2"), db.tx().find().inDefaultKeyspace().where("name").startsWithIgnoreCase("np").getKeysAsSet().stream() .map(qKey -> qKey.getKey()).collect(Collectors.toSet())); } @Test public void attemptingToMixIndexerTypesShouldThrowAnException() { ChronoDB db = this.getChronoDB(); this.assertAddingSecondIndexerFails(db, new DummyStringIndexer(), new DummyLongIndexer()); db.getIndexManager().clearAllIndices(); this.assertAddingSecondIndexerFails(db, new DummyStringIndexer(), new DummyDoubleIndexer()); db.getIndexManager().clearAllIndices(); this.assertAddingSecondIndexerFails(db, new DummyLongIndexer(), new DummyStringIndexer()); db.getIndexManager().clearAllIndices(); this.assertAddingSecondIndexerFails(db, new DummyLongIndexer(), new DummyDoubleIndexer()); db.getIndexManager().clearAllIndices(); this.assertAddingSecondIndexerFails(db, new DummyDoubleIndexer(), new DummyStringIndexer()); db.getIndexManager().clearAllIndices(); this.assertAddingSecondIndexerFails(db, new DummyDoubleIndexer(), new DummyLongIndexer()); } @Test public void attemptingToAddTheSameIndexerTwiceShouldThrowAnException() { ChronoDB db = this.getChronoDB(); // this should be okay db.getIndexManager().createIndex().withName("name").withIndexer(new DummyFieldIndexer("name")).onMaster().acrossAllTimestamps().build(); // ... but adding another field indexer of the same name should not be allowed try { db.getIndexManager().createIndex().withName("name").withIndexer(new DummyFieldIndexer("name")).onMaster().acrossAllTimestamps().build(); fail("Managed to add two equal indexers to the same index!"); } catch (ChronoDBIndexingException e) { // pass } } @Test public void attemptingToAddAnIndexerWithoutHashCodeAndEqualsShouldThrowAnException() { ChronoDB db = this.getChronoDB(); try { db.getIndexManager().createIndex().withName("name").withIndexer(new IndexerWithoutHashCode()).onMaster().acrossAllTimestamps().build(); fail("Managed to add indexer that doesn't implement hashCode()"); } catch (ChronoDBIndexingException e) { // pass } try { db.getIndexManager().createIndex().withName("name").withIndexer(new IndexerWithoutEquals()).onMaster().acrossAllTimestamps().build(); fail("Managed to add indexer that doesn't implement equals()"); } catch (ChronoDBIndexingException e) { // pass } } @Test public void canDropAllIndices() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new DummyStringIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("test").withIndexer(new DummyStringIndexer()).onMaster().acrossAllTimestamps().build(); assertEquals(2, db.getIndexManager().getIndices().size()); db.getIndexManager().clearAllIndices(); assertEquals(0, db.getIndexManager().getIndices().size()); } @Test public void canDirtyAllIndices() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new DummyStringIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("foo").withIndexer(new DummyStringIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); assertEquals(Sets.newHashSet("name", "foo"), db.getIndexManager().getIndices().stream().map(SecondaryIndex::getName).collect(Collectors.toSet())); assertEquals(Collections.emptySet(), db.getIndexManager().getDirtyIndices()); // dirty them all ((IndexManagerInternal) db.getIndexManager()).markAllIndicesAsDirty(); assertEquals(Sets.newHashSet("name", "foo"), db.getIndexManager().getDirtyIndices().stream().map(SecondaryIndex::getName).collect(Collectors.toSet())); // after reindexing, they should be clean again db.getIndexManager().reindexAll(); assertEquals(Collections.emptySet(), db.getIndexManager().getDirtyIndices()); } @Test public void assumeNoPriorValuesStartsIndexClean() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex() .withName("name") .withIndexer(new DummyStringIndexer()) .onMaster().acrossAllTimestamps().withOption(IndexingOption.assumeNoPriorValues()).build(); Set<SecondaryIndex> dirtyIndices = db.getIndexManager().getDirtyIndices(); assertEquals(Collections.emptySet(), dirtyIndices); } private void assertAddingSecondIndexerFails(final ChronoDB db, final Indexer<?> indexer1, final Indexer<?> indexer2) { db.getIndexManager().createIndex().withName("test").withIndexer(indexer1).onMaster().acrossAllTimestamps().build(); try { db.getIndexManager().createIndex().withName("test").withIndexer(indexer2).onMaster().acrossAllTimestamps().build(); fail("Managed to mix indexer classes " + indexer1.getClass().getSimpleName() + " and " + indexer2.getClass().getName() + " in same index!"); } catch (ChronoDBIndexingException expected) { // pass } } // ================================================================================================================= // INNER CLASSES // ================================================================================================================= private static class DummyStringIndexer implements StringIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return true; } @Override public Set<String> getIndexValues(final Object object) { return Collections.singleton(String.valueOf(object)); } } private static class DummyLongIndexer implements LongIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return true; } @Override public Set<Long> getIndexValues(final Object object) { return Collections.singleton((long) String.valueOf(object).length()); } } private static class DummyDoubleIndexer implements DoubleIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return true; } @Override public Set<Double> getIndexValues(final Object object) { return Collections.singleton((double) String.valueOf(object).length()); } } private static class DummyFieldIndexer implements StringIndexer { private String fieldName; public DummyFieldIndexer(String fieldName) { checkNotNull(fieldName, "Precondition violation - argument 'fieldName' must not be NULL!"); this.fieldName = fieldName; } @Override public boolean canIndex(final Object object) { return true; } @Override public Set<String> getIndexValues(final Object object) { try { Field field = object.getClass().getDeclaredField(this.fieldName); if (field == null) { return null; } field.setAccessible(true); Object value = field.get(object); if (value == null) { return null; } return Collections.singleton(value.toString()); } catch (Exception e) { return null; } } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DummyFieldIndexer that = (DummyFieldIndexer) o; return Objects.equals(fieldName, that.fieldName); } @Override public int hashCode() { return fieldName != null ? fieldName.hashCode() : 0; } } private static class IndexerWithoutHashCode implements StringIndexer { // no hashCode() method here on purpose! @Override public boolean equals(Object other) { return other == this; } @Override public boolean canIndex(final Object object) { return true; } @Override public Set<String> getIndexValues(final Object object) { return null; } } private static class IndexerWithoutEquals implements StringIndexer { @Override public int hashCode() { return 0; } // no equals() method here on purpose! @Override public boolean canIndex(final Object object) { return true; } @Override public Set<String> getIndexValues(final Object object) { return null; } } }
17,178
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MultiValueIndexingTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/MultiValueIndexingTest.java
package org.chronos.chronodb.test.cases.engine.indexing; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.IndexManager; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class MultiValueIndexingTest extends AllChronoDBBackendsTest { @Test public void multiValuedIndexRetrievalWorks() { ChronoDB db = this.getChronoDB(); IndexManager indexManager = db.getIndexManager(); db.getIndexManager().createIndex().withName("name").withIndexer(new TestBeanIndexer()).onMaster().acrossAllTimestamps().build(); indexManager.reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("tb1", new TestBean("TB1", "First", "Second")); tx.put("tb2", new TestBean("TB2", "Second", "Third")); tx.put("tb3", new TestBean("TB3")); tx.put("tb4", new TestBean("TB4", "First")); tx.commit(); Set<Object> values = tx.find().inDefaultKeyspace().where("name").isEqualTo("First").getValuesAsSet(); // should contain TestBean 1 and TestBean 4 assertEquals(2, values.size()); Set<String> allNames = values.stream().map(tb -> ((TestBean) tb).getNames()).flatMap(Collection::stream).collect(Collectors.toSet()); assertTrue(allNames.contains("TB1")); assertTrue(allNames.contains("TB4")); assertFalse(allNames.contains("TB2")); assertFalse(allNames.contains("TB3")); } @Test public void multiValuedIndexingTemporalAddValueWorks() { ChronoDB db = this.getChronoDB(); IndexManager indexManager = db.getIndexManager(); db.getIndexManager().createIndex().withName("name").withIndexer(new TestBeanIndexer()).onMaster().acrossAllTimestamps().build(); indexManager.reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("tb1", new TestBean("TB1", "First", "Second")); tx.put("tb2", new TestBean("TB2", "Second", "Third")); tx.put("tb3", new TestBean("TB3")); tx.put("tb4", new TestBean("TB4", "First")); tx.commit(); long afterCommit1 = tx.getTimestamp(); // add an index value to TB1 tx.put("tb1", new TestBean("TB1", "First", "Second", "Third")); tx.commit(); // assert that: // - after the first commit, there is only one match for "Third" // - after the second commit, there are two matches for "Third" ChronoDBTransaction txAfter1 = db.tx(afterCommit1); Set<Object> values = txAfter1.find().inDefaultKeyspace().where("name").isEqualTo("Third").getValuesAsSet(); assertEquals(1, values.size()); ChronoDBTransaction txAfter2 = db.tx(); values = txAfter2.find().inDefaultKeyspace().where("name").isEqualTo("Third").getValuesAsSet(); assertEquals(2, values.size()); } @Test public void multiValuedIndexingTemporalRemoveValueWorks() { ChronoDB db = this.getChronoDB(); IndexManager indexManager = db.getIndexManager(); db.getIndexManager().createIndex().withName("name").withIndexer(new TestBeanIndexer()).onMaster().acrossAllTimestamps().build(); indexManager.reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("tb1", new TestBean("TB1", "First", "Second")); tx.put("tb2", new TestBean("TB2", "Second", "Third")); tx.put("tb3", new TestBean("TB3")); tx.put("tb4", new TestBean("TB4", "First")); tx.commit(); long afterCommit1 = tx.getTimestamp(); // remove an index value from TB1 tx.put("tb1", new TestBean("TB1", "Second")); tx.commit(); // assert that: // - after the first commit, there are two matches for "Second" // - after the second commit, there is only one match for "Second" ChronoDBTransaction txAfter1 = db.tx(afterCommit1); Set<Object> values = txAfter1.find().inDefaultKeyspace().where("name").isEqualTo("First").getValuesAsSet(); assertEquals(2, values.size()); ChronoDBTransaction txAfter2 = db.tx(); values = txAfter2.find().inDefaultKeyspace().where("name").isEqualTo("First").getValuesAsSet(); assertEquals(1, values.size()); } public static class TestBean { private final Set<String> names = Sets.newHashSet(); @SuppressWarnings("unused") public TestBean() { // default constructor for serialization } public TestBean(final String... names) { Collections.addAll(this.names, names); } public Set<String> getNames() { return Collections.unmodifiableSet(this.names); } } public static class TestBeanIndexer implements StringIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return object instanceof TestBean; } @Override public Set<String> getIndexValues(final Object object) { TestBean testBean = (TestBean) object; return testBean.getNames(); } } }
5,810
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexDocumentDeleteTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/IndexDocumentDeleteTest.java
package org.chronos.chronodb.test.cases.engine.indexing; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class IndexDocumentDeleteTest extends AllChronoDBBackendsTest { @Test public void testDeletedIndexEntryIsNoLongerPresent() { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex() .withName("name") .withIndexer(nameIndexer) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); long afterFirstWrite = tx.getTimestamp(); // now, delete np2 tx.remove("np2"); tx.commit(); // open a read transaction after the first write ChronoDBTransaction tx2 = db.tx(afterFirstWrite); // assert that the "hello world" element is there long count = tx2.find().inDefaultKeyspace().where("name").isEqualTo("Foo Bar").count(); assertEquals(1, count); // open a read transaction on "now" and assert that it is gone ChronoDBTransaction tx3 = db.tx(); long count2 = tx3.find().inDefaultKeyspace().where("name").isEqualTo("Foo Bar").count(); assertEquals(0, count2); } @Test public void testRecreationViaSaveOfDeletedEntryWorks() throws Exception { ChronoDB db = this.getChronoDB(); StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex() .withName("name") .withIndexer(nameIndexer) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().reindexAll(); final long afterFirstWrite; { // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("A"); NamedPayload np2 = NamedPayload.create1KB("A"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.commit(); afterFirstWrite = tx.getTimestamp(); } final long afterSecondWrite; { // generate and insert test data ChronoDBTransaction tx = db.tx(); tx.remove("np1"); tx.commit(); afterSecondWrite = tx.getTimestamp(); } final long afterThirdWrite; { // generate and insert test data ChronoDBTransaction tx = db.tx(); NamedPayload np1 = NamedPayload.create1KB("A"); tx.put("np1", np1); tx.commit(); afterThirdWrite = tx.getTimestamp(); } final long afterFourthWrite; { // generate and insert test data ChronoDBTransaction tx = db.tx(); tx.remove("np1"); tx.commit(); afterFourthWrite = tx.getTimestamp(); } // two 'A' after first write Set<String> aAfterFirstWrite = db.tx(afterFirstWrite).find().inDefaultKeyspace().where("name") .isEqualTo("A") .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("np1", "np2"), aAfterFirstWrite); // only one 'A' after second write Set<String> aAfterSecondWrite = db.tx(afterSecondWrite).find().inDefaultKeyspace().where("name") .isEqualTo("A") .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("np2"), aAfterSecondWrite); // two 'A' after third write Set<String> aAfterThirdWrite = db.tx(afterThirdWrite).find().inDefaultKeyspace().where("name") .isEqualTo("A") .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("np1", "np2"), aAfterThirdWrite); // only one 'A' after fourth write Set<String> aAfterFourthWrite = db.tx(afterFourthWrite).find().inDefaultKeyspace().where("name") .isEqualTo("A") .getKeysAsSet().stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(Sets.newHashSet("np2"), aAfterFourthWrite); } // private void printIndexState(final ChronoDB db) throws Exception { // // state of secondary index // ChronoChunk chunk = ((ChunkedChronoDB) db).getChunkManager().getChunkManagerForBranch("master") // .getChunkForTimestamp(db.tx().getOperationTimestamp()); // // fetch the index manager for this chunk // ChunkDbIndexManagerBackend indexManagerBackend = ((ChunkDbIndexManager) db.getIndexManager()) // .getIndexManagerBackend(); // Field indexManagerField = ChunkDbIndexManagerBackend.class.getDeclaredField("indexChunkManager"); // indexManagerField.setAccessible(true); // IndexChunkManager indexChunkManager = (IndexChunkManager) indexManagerField.get(indexManagerBackend); // DocumentBasedChunkIndex chunkIndex = indexChunkManager.getIndexForChunk(chunk); // Field indexNameToDocumentField = InMemoryIndexManagerBackend.class.getDeclaredField("indexNameToDocuments"); // indexNameToDocumentField.setAccessible(true); // SetMultimap<String, ChronoIndexDocument> indexNameToDocument = (SetMultimap<String, ChronoIndexDocument>) indexNameToDocumentField // .get(chunkIndex); // // for (ChronoIndexDocument doc : indexNameToDocument.get("name")) { // System.out.println(doc); // } // } }
6,576
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NegatedIndexQueryTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/NegatedIndexQueryTest.java
package org.chronos.chronodb.test.cases.engine.indexing; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.ReflectiveStringIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static com.google.common.base.Preconditions.*; @Category(IntegrationTest.class) public class NegatedIndexQueryTest extends AllChronoDBBackendsTest { @Test public void canEvaluateSimpleNegatedQuery() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new ReflectiveStringIndexer(TestBean.class, "name")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("x").withIndexer(new ReflectiveStringIndexer(TestBeanA.class, "x")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("y").withIndexer(new ReflectiveStringIndexer(TestBeanB.class, "y")).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // add some data ChronoDBTransaction tx = db.tx(); tx.put("a1", new TestBeanA("a", "x1")); tx.put("a2", new TestBeanA("b", "x2")); tx.put("a3", new TestBeanA("c", "x3")); tx.put("a4", new TestBeanA("d", "x4")); tx.put("b1", new TestBeanB("a", "y1")); tx.put("b2", new TestBeanB("b", "y2")); tx.put("b3", new TestBeanB("c", "y3")); tx.put("b4", new TestBeanB("d", "y4")); tx.commit(); } assertKeysEqual("b1", "b2", "b3", "b4", db.tx().find().inDefaultKeyspace().where("x").notStartsWith("x")); assertKeysEqual("a1", "a2", "a3", "a4", "b1", "b2", "b3", "b4", db.tx().find().inDefaultKeyspace().where("x").isNotEqualTo("test")); assertKeysEqual("a2", "a3", "a4", "b1", "b2", "b3", "b4", db.tx().find().inDefaultKeyspace().where("x").notMatchesRegex("x1")); } // ================================================================================================================= // INNER CLASSES // ================================================================================================================= @SuppressWarnings("unused") private static abstract class TestBean { private String name; protected TestBean() { } protected TestBean(final String name) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); this.name = name; } public String getName() { return this.name; } } @SuppressWarnings("unused") private static class TestBeanA extends TestBean { private String x; protected TestBeanA() { } protected TestBeanA(final String name, final String x) { super(name); this.x = x; } public String getX() { return this.x; } } @SuppressWarnings("unused") private static class TestBeanB extends TestBean { private String y; protected TestBeanB() { } public TestBeanB(final String name, final String y) { super(name); this.y = y; } public String getY() { return this.y; } } }
3,588
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MutableIndexValueDiffTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/diff/MutableIndexValueDiffTest.java
package org.chronos.chronodb.test.cases.engine.indexing.diff; import com.google.common.collect.Sets; import org.chronos.chronodb.internal.impl.index.diff.MutableIndexValueDiff; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.chronodb.test.cases.util.model.person.FirstNameIndexer; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import static org.junit.Assert.*; @Category(UnitTest.class) public class MutableIndexValueDiffTest extends ChronoDBUnitTest { @Test public void canCreateEmptyDiff() { MutableIndexValueDiff diff = new MutableIndexValueDiff(null, null); assertNotNull(diff); assertTrue(diff.isEmpty()); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertFalse(diff.isEntryUpdate()); } @Test public void canCreateEmptyAddition() { MutableIndexValueDiff diff = new MutableIndexValueDiff(null, new Object()); assertNotNull(diff); assertTrue(diff.isEmpty()); assertTrue(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertFalse(diff.isEntryUpdate()); } @Test public void canCreateEmptyRemoval() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), null); assertNotNull(diff); assertTrue(diff.isEmpty()); assertFalse(diff.isEntryAddition()); assertTrue(diff.isEntryRemoval()); assertFalse(diff.isEntryUpdate()); } @Test public void canCreateEmtpyUpdate() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); assertNotNull(diff); assertTrue(diff.isEmpty()); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertTrue(diff.isEntryUpdate()); } @Test public void canInsertAdditions() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); assertTrue(diff.isEmpty()); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertTrue(diff.isEntryUpdate()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); DummyIndex testIndex2 = new DummyIndex(new FirstNameIndexer(), "test2"); DummyIndex testIndex3 = new DummyIndex(new FirstNameIndexer(), "test3"); diff.add(testIndex, "Hello World"); diff.add(testIndex, "Foo Bar"); diff.add(testIndex2, "Baz"); assertEquals(Sets.newHashSet(testIndex, testIndex2), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Hello World", "Foo Bar"), diff.getAdditions(testIndex)); assertEquals(Sets.newHashSet("Baz"), diff.getAdditions(testIndex2)); assertEquals(Collections.emptySet(), diff.getRemovals(testIndex)); assertEquals(Collections.emptySet(), diff.getRemovals(testIndex2)); assertTrue(diff.isIndexChanged(testIndex)); assertTrue(diff.isIndexChanged(testIndex2)); assertFalse(diff.isIndexChanged(testIndex3)); } @Test public void canInsertDeletions() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); assertTrue(diff.isEmpty()); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertTrue(diff.isEntryUpdate()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); DummyIndex testIndex2 = new DummyIndex(new FirstNameIndexer(), "test2"); DummyIndex testIndex3 = new DummyIndex(new FirstNameIndexer(), "test3"); diff.removeSingleValue(testIndex, "Hello World"); diff.removeSingleValue(testIndex, "Foo Bar"); diff.removeSingleValue(testIndex2, "Baz"); assertEquals(Sets.newHashSet(testIndex, testIndex2), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Hello World", "Foo Bar"), diff.getRemovals(testIndex)); assertEquals(Sets.newHashSet("Baz"), diff.getRemovals(testIndex2)); assertEquals(Collections.emptySet(), diff.getAdditions(testIndex)); assertEquals(Collections.emptySet(), diff.getAdditions(testIndex2)); assertTrue(diff.isIndexChanged(testIndex)); assertTrue(diff.isIndexChanged(testIndex2)); assertFalse(diff.isIndexChanged(testIndex3)); } @Test public void cannotInsertRemovalsIntoEntryAdditionDiff() { MutableIndexValueDiff diff = new MutableIndexValueDiff(null, new Object()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); try { diff.removeSingleValue(testIndex, "Hello World"); fail("Managed to remove an index value in an entry addition diff!"); } catch (Exception ignored) { // pass } } @Test public void cannotInsertAdditionsIntoEntryRemovalDiff() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), null); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); try { diff.add(testIndex, "Hello World"); fail("Managed to add an index value in an entry removal diff!"); } catch (Exception ignored) { // pass } } @Test public void insertingAnAdditionOverridesARemoval() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); DummyIndex testIndex2 = new DummyIndex(new FirstNameIndexer(), "test2"); diff.removeSingleValue(testIndex, "Hello World"); diff.removeSingleValue(testIndex, "Foo Bar"); assertEquals(Sets.newHashSet(testIndex), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Hello World", "Foo Bar"), diff.getRemovals(testIndex)); assertEquals(Collections.emptySet(), diff.getAdditions(testIndex)); diff.add(testIndex, "Hello World"); assertEquals(Sets.newHashSet(testIndex), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Foo Bar"), diff.getRemovals(testIndex)); assertEquals(Sets.newHashSet("Hello World"), diff.getAdditions(testIndex)); assertTrue(diff.isIndexChanged(testIndex)); assertFalse(diff.isIndexChanged(testIndex2)); } @Test public void insertingARemovalOverridesAnAddition() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); DummyIndex testIndex2 = new DummyIndex(new FirstNameIndexer(), "test2"); diff.add(testIndex, "Hello World"); diff.add(testIndex, "Foo Bar"); assertEquals(Sets.newHashSet(testIndex), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Hello World", "Foo Bar"), diff.getAdditions(testIndex)); assertEquals(Collections.emptySet(), diff.getRemovals(testIndex)); diff.removeSingleValue(testIndex, "Hello World"); assertEquals(Sets.newHashSet(testIndex), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Foo Bar"), diff.getAdditions(testIndex)); assertEquals(Sets.newHashSet("Hello World"), diff.getRemovals(testIndex)); assertTrue(diff.isIndexChanged(testIndex)); assertFalse(diff.isIndexChanged(testIndex2)); } @Test public void canDetectThatDiffisAdditive() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); diff.add(testIndex, "Hello World"); diff.add(testIndex, "Foo Bar"); assertTrue(diff.isAdditive()); assertFalse(diff.isSubtractive()); assertFalse(diff.isMixed()); assertFalse(diff.isEmpty()); } @Test public void canDetectThatDiffIsSubtractive() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); diff.removeSingleValue(testIndex, "Hello World"); diff.removeSingleValue(testIndex, "Foo Bar"); assertFalse(diff.isAdditive()); assertTrue(diff.isSubtractive()); assertFalse(diff.isMixed()); assertFalse(diff.isEmpty()); } @Test public void canDetectThatDiffIsMixed() { MutableIndexValueDiff diff = new MutableIndexValueDiff(new Object(), new Object()); DummyIndex testIndex = new DummyIndex(new FirstNameIndexer(), "test"); diff.add(testIndex, "Hello World"); diff.removeSingleValue(testIndex, "Foo Bar"); assertFalse(diff.isAdditive()); assertFalse(diff.isSubtractive()); assertTrue(diff.isMixed()); assertFalse(diff.isEmpty()); } }
9,010
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DummyIndex.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/diff/DummyIndex.java
package org.chronos.chronodb.test.cases.engine.indexing.diff; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.indexing.Indexer; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.impl.index.IndexingOption; import org.chronos.chronodb.internal.impl.index.diff.IndexingUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class DummyIndex implements SecondaryIndex { private final String id = UUID.randomUUID().toString(); private final String name; private final Indexer<?> indexer; public DummyIndex(Indexer<?> indexer) { this(indexer, null); } public DummyIndex(Indexer<?> indexer, String name){ checkNotNull(indexer, "Precondition violation - argument 'indexer' must not be NULL!"); this.indexer = indexer; if(name == null){ this.name = "Dummy-" + this.id; }else{ this.name = name; } } @NotNull @Override public String getId() { return this.id; } @NotNull @Override public String getName() { return this.name; } @NotNull @Override public Indexer<?> getIndexer() { return this.indexer; } @NotNull @Override public Period getValidPeriod() { return Period.eternal(); } @NotNull @Override public String getBranch() { return ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; } @Nullable @Override public String getParentIndexId() { return null; } @Override public boolean getDirty() { return false; } @NotNull @Override public Class<?> getValueType() { return String.class; } @NotNull @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Set<Comparable<?>> getIndexedValuesForObject(@Nullable final Object value) { if (value == null) { // when the object to index is null, we can't produce any indexed values. // empty set is already unmodifiable, no need to wrap it in Collections.umodifiableSet. return Collections.emptySet(); } if (!this.indexer.canIndex(value)) { return Collections.emptySet(); } Set<?> indexedValues = this.indexer.getIndexValues(value); if (indexedValues == null) { return Collections.emptySet(); } // make sure that there are no NULL values or empty values in the indexed values set return (Set)indexedValues.stream() .filter(IndexingUtils::isValidIndexValue) .collect(Collectors.toSet()); } @NotNull @Override public Set<IndexingOption> getOptions() { return Collections.emptySet(); } @NotNull @Override public Set<IndexingOption> getInheritableOptions() { return Collections.emptySet(); } }
3,477
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexingUtilsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/indexing/diff/IndexingUtilsTest.java
package org.chronos.chronodb.test.cases.engine.indexing.diff; import com.google.common.collect.Sets; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.internal.impl.index.diff.IndexValueDiff; import org.chronos.chronodb.internal.impl.index.diff.IndexingUtils; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.chronodb.test.cases.util.model.person.PersonIndexer; import org.chronos.common.test.junit.categories.UnitTest; import org.chronos.common.test.utils.model.person.Person; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collection; import java.util.Collections; import java.util.Set; import static org.junit.Assert.*; @Category(UnitTest.class) public class IndexingUtilsTest extends ChronoDBUnitTest { // ===================================================================================================================== // GET INDEX VALUES TESTS // ===================================================================================================================== @Test public void canGetIndexValuesForObject() { Person johnDoe = createJohnDoe(); Collection<Object> firstNameValues = IndexingUtils.getIndexedValuesForObject( Collections.singleton(new DummyIndex(PersonIndexer.firstName())), johnDoe ).values(); assertEquals(Sets.newHashSet("John"), Sets.newHashSet(firstNameValues)); Collection<Object> lastNameValues = IndexingUtils.getIndexedValuesForObject( Collections.singleton(new DummyIndex(PersonIndexer.lastName())), johnDoe ).values(); assertEquals(Sets.newHashSet("Doe"), Sets.newHashSet(lastNameValues)); } @Test public void canGetIndexValuesForNullValuedFields() { Person johnDoe = createJohnDoe(); Collection<Object> favoriteColorValues = IndexingUtils.getIndexedValuesForObject( Collections.singleton(new DummyIndex(PersonIndexer.favoriteColor())), johnDoe ).values(); assertEquals(Collections.emptySet(), Sets.newHashSet(favoriteColorValues)); } @Test public void canGetIndexValuesForEmptyCollectionFields() { Person johnDoe = createJohnDoe(); Collection<Object> petsValues = IndexingUtils.getIndexedValuesForObject( Collections.singleton(new DummyIndex(PersonIndexer.pets())), johnDoe ).values(); assertEquals(Collections.emptySet(), Sets.newHashSet(petsValues)); } @Test public void indexedValuesDoNotContainNullOrEmptyString() { Person johnDoe = createJohnDoe(); Collection<Object> hobbiesValues = IndexingUtils.getIndexedValuesForObject( Collections.singleton(new DummyIndex(PersonIndexer.hobbies())), johnDoe ).values(); assertEquals(Sets.newHashSet("Swimming", "Skiing"), Sets.newHashSet(hobbiesValues)); } @Test public void attemptingToGetIndexValuesWithoutIndexerProducesEmptySet() { Person johnDoe = createJohnDoe(); Collection<Object> hobbiesValues2 = IndexingUtils.getIndexedValuesForObject( Collections.emptySet(), johnDoe ).values(); assertEquals(Collections.emptySet(), Sets.newHashSet(hobbiesValues2)); } // ===================================================================================================================== // DIFF CALCULATION TESTS // ===================================================================================================================== @Test public void canCalculateAdditiveDiff() { Person p1 = new Person(); p1.setFirstName("John"); p1.setLastName("Doe"); p1.setHobbies("Swimming", "Skiing"); Person p2 = new Person(); p2.setFirstName("John"); p2.setLastName("Doe"); p2.setHobbies("Swimming", "Skiing", "Cinema", "Reading"); p2.setPets("Cat", "Dog", "Fish"); Set<SecondaryIndex> indices = Sets.newHashSet(); DummyIndex firstNameIndex = new DummyIndex(PersonIndexer.firstName(), "firstName"); DummyIndex lastNameIndex = new DummyIndex(PersonIndexer.lastName(), "lastName"); DummyIndex hobbiesIndex = new DummyIndex(PersonIndexer.hobbies(), "hobbies"); DummyIndex petsIndex = new DummyIndex(PersonIndexer.pets(), "pets"); indices.add(firstNameIndex); indices.add(lastNameIndex); indices.add(hobbiesIndex); indices.add(petsIndex); IndexValueDiff diff = IndexingUtils.calculateDiff(indices, p1, p2); assertNotNull(diff); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertTrue(diff.isEntryUpdate()); assertTrue(diff.isAdditive()); assertFalse(diff.isSubtractive()); assertFalse(diff.isMixed()); assertFalse(diff.isEmpty()); assertEquals(Sets.newHashSet(hobbiesIndex, petsIndex), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Cinema", "Reading"), diff.getAdditions(hobbiesIndex)); assertEquals(Sets.newHashSet("Cat", "Dog", "Fish"), diff.getAdditions(petsIndex)); } @Test public void canCalculateSubtractiveDiff() { Person p1 = new Person(); p1.setFirstName("John"); p1.setLastName("Doe"); p1.setHobbies("Swimming", "Skiing", "Cinema", "Reading"); p1.setPets("Cat", "Dog", "Fish"); Person p2 = new Person(); p2.setFirstName("John"); p2.setLastName("Doe"); p2.setHobbies("Swimming", "Skiing"); Set<SecondaryIndex> indices = Sets.newHashSet(); DummyIndex firstNameIndex = new DummyIndex(PersonIndexer.firstName(), "firstName"); DummyIndex lastNameIndex = new DummyIndex(PersonIndexer.lastName(), "lastName"); DummyIndex hobbiesIndex = new DummyIndex(PersonIndexer.hobbies(), "hobbies"); DummyIndex petsIndex = new DummyIndex(PersonIndexer.pets(), "pets"); indices.add(firstNameIndex); indices.add(lastNameIndex); indices.add(hobbiesIndex); indices.add(petsIndex); IndexValueDiff diff = IndexingUtils.calculateDiff(indices, p1, p2); assertNotNull(diff); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertTrue(diff.isEntryUpdate()); assertFalse(diff.isAdditive()); assertTrue(diff.isSubtractive()); assertFalse(diff.isMixed()); assertFalse(diff.isEmpty()); assertEquals(Sets.newHashSet(hobbiesIndex, petsIndex), diff.getChangedIndices()); assertEquals(Sets.newHashSet("Cinema", "Reading"), diff.getRemovals(hobbiesIndex)); assertEquals(Sets.newHashSet("Cat", "Dog", "Fish"), diff.getRemovals(petsIndex)); } @Test public void canCalculateEntryAdditionDiff() { Person johnDoe = createJohnDoe(); Set<SecondaryIndex> indices = Sets.newHashSet(); DummyIndex firstNameIndex = new DummyIndex(PersonIndexer.firstName(), "firstName"); DummyIndex lastNameIndex = new DummyIndex(PersonIndexer.lastName(), "lastName"); DummyIndex favoriteColorIndex = new DummyIndex(PersonIndexer.favoriteColor(), "favoriteColor"); DummyIndex hobbiesIndex = new DummyIndex(PersonIndexer.hobbies(), "hobbies"); DummyIndex petsIndex = new DummyIndex(PersonIndexer.pets(), "pets"); indices.add(firstNameIndex); indices.add(lastNameIndex); indices.add(favoriteColorIndex); indices.add(hobbiesIndex); indices.add(petsIndex); // simulate the addition of John Doe IndexValueDiff diff = IndexingUtils.calculateDiff(indices, null, johnDoe); assertNotNull(diff); assertTrue(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertFalse(diff.isEntryUpdate()); assertTrue(diff.isAdditive()); assertFalse(diff.isSubtractive()); assertFalse(diff.isMixed()); assertFalse(diff.isEmpty()); assertEquals(Sets.newHashSet(firstNameIndex, lastNameIndex, hobbiesIndex), diff.getChangedIndices()); assertEquals(Sets.newHashSet("John"), diff.getAdditions(firstNameIndex)); assertEquals(Collections.emptySet(), diff.getRemovals(firstNameIndex)); assertEquals(Sets.newHashSet("Doe"), diff.getAdditions(lastNameIndex)); assertEquals(Collections.emptySet(), diff.getRemovals(lastNameIndex)); assertEquals(Sets.newHashSet("Swimming", "Skiing"), diff.getAdditions(hobbiesIndex)); assertEquals(Collections.emptySet(), diff.getRemovals(hobbiesIndex)); } @Test public void canCalculateEntryRemovalDiff() { Person johnDoe = createJohnDoe(); Set<SecondaryIndex> indices = Sets.newHashSet(); DummyIndex firstNameIndex = new DummyIndex(PersonIndexer.firstName(), "firstName"); DummyIndex lastNameIndex = new DummyIndex(PersonIndexer.lastName(), "lastName"); DummyIndex favoriteColorIndex = new DummyIndex(PersonIndexer.favoriteColor(), "favoriteColor"); DummyIndex hobbiesIndex = new DummyIndex(PersonIndexer.hobbies(), "hobbies"); DummyIndex petsIndex = new DummyIndex(PersonIndexer.pets(), "pets"); indices.add(firstNameIndex); indices.add(lastNameIndex); indices.add(favoriteColorIndex); indices.add(hobbiesIndex); indices.add(petsIndex); // simulate the deletion of John Doe IndexValueDiff diff = IndexingUtils.calculateDiff(indices, johnDoe, null); assertNotNull(diff); assertFalse(diff.isEntryAddition()); assertTrue(diff.isEntryRemoval()); assertFalse(diff.isEntryUpdate()); assertFalse(diff.isAdditive()); assertTrue(diff.isSubtractive()); assertFalse(diff.isMixed()); assertFalse(diff.isEmpty()); assertEquals(Sets.newHashSet(firstNameIndex, lastNameIndex, hobbiesIndex), diff.getChangedIndices()); assertEquals(Collections.emptySet(), diff.getAdditions(firstNameIndex)); assertEquals(Sets.newHashSet("John"), diff.getRemovals(firstNameIndex)); assertEquals(Collections.emptySet(), diff.getAdditions(lastNameIndex)); assertEquals(Sets.newHashSet("Doe"), diff.getRemovals(lastNameIndex)); assertEquals(Collections.emptySet(), diff.getAdditions(hobbiesIndex)); assertEquals(Sets.newHashSet("Swimming", "Skiing"), diff.getRemovals(hobbiesIndex)); } @Test public void canCalculateMixedDiff() { Person p1 = new Person(); p1.setFirstName("John"); p1.setLastName("Doe"); p1.setHobbies("Swimming", "Skiing"); Person p2 = new Person(); p2.setFirstName("John"); p2.setLastName("Smith"); p2.setHobbies("Skiing", "Cinema"); Set<SecondaryIndex> indices = Sets.newHashSet(); DummyIndex firstNameIndex = new DummyIndex(PersonIndexer.firstName(), "firstName"); DummyIndex lastNameIndex = new DummyIndex(PersonIndexer.lastName(), "lastName"); DummyIndex hobbiesIndex = new DummyIndex(PersonIndexer.hobbies(), "hobbies"); indices.add(firstNameIndex); indices.add(lastNameIndex); indices.add(hobbiesIndex); IndexValueDiff diff = IndexingUtils.calculateDiff(indices, p1, p2); assertNotNull(diff); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertTrue(diff.isEntryUpdate()); assertFalse(diff.isAdditive()); assertFalse(diff.isSubtractive()); assertTrue(diff.isMixed()); assertFalse(diff.isEmpty()); assertEquals(Collections.emptySet(), diff.getAdditions(firstNameIndex)); assertEquals(Collections.emptySet(), diff.getRemovals(firstNameIndex)); assertFalse(diff.isIndexChanged(firstNameIndex)); assertEquals(Collections.singleton("Smith"), diff.getAdditions(lastNameIndex)); assertEquals(Collections.singleton("Doe"), diff.getRemovals(lastNameIndex)); assertTrue(diff.isIndexChanged(lastNameIndex)); assertEquals(Collections.singleton("Cinema"), diff.getAdditions(hobbiesIndex)); assertEquals(Collections.singleton("Swimming"), diff.getRemovals(hobbiesIndex)); assertTrue(diff.isIndexChanged(hobbiesIndex)); assertEquals(Sets.newHashSet(lastNameIndex, hobbiesIndex), diff.getChangedIndices()); assertFalse(diff.isEntryAddition()); assertFalse(diff.isEntryRemoval()); assertTrue(diff.isEntryUpdate()); } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private static Person createJohnDoe() { Person johnDoe = new Person(); johnDoe.setFirstName("John"); johnDoe.setLastName("Doe"); johnDoe.setFavoriteColor(null); johnDoe.setHobbies(Sets.newHashSet("Swimming", "Skiing", " ", "", null)); johnDoe.setPets(Collections.emptySet()); return johnDoe; } }
13,281
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RolloverDatebackTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/dateback/RolloverDatebackTest.java
package org.chronos.chronodb.test.cases.engine.dateback; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.internal.api.dateback.log.DatebackOperation; import org.chronos.chronodb.internal.api.dateback.log.IPurgeKeyspaceOperation; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class RolloverDatebackTest extends AllChronoDBBackendsTest { @Test public void injectionIsTransferredToFutureChunks() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); List<Long> chunkStartTimestamps = createFourRolloverModel(db); // inject a new key into the second chunk db.getDatebackManager().datebackOnMaster(dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "C", chunkStartTimestamps.get(1) + 1, 1); }); // C should be accessible in HEAD assertEquals(1, (int) db.tx().get("C")); // C should have one history entry (from the inject, rollovers don't count) assertEquals(1, Iterators.size(db.tx().history("C"))); } @Test public void purgedEntriesAreRemovedFromRollover() { ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); List<Long> chunkStartTimestamps = createFourRolloverModel(db); // get the first two commits of A List<Long> commitTimestampsOfA = Lists.reverse(Lists.newArrayList(db.tx().history("A"))); long firstCommitOfA = commitTimestampsOfA.get(0); long secondCommitOfA = commitTimestampsOfA.get(1); assertTrue(firstCommitOfA < secondCommitOfA); assertTrue(secondCommitOfA < chunkStartTimestamps.get(1)); // purge the first two commits of A from the store db.getDatebackManager().datebackOnMaster(dateback -> { dateback.purgeEntry(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "A", firstCommitOfA); dateback.purgeEntry(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "A", secondCommitOfA); }); List<Long> newHistorOfA = Lists.newArrayList(db.tx().history("A")); assertEquals(4, newHistorOfA.size()); } @Test public void canPurgeKeyspace() throws Exception { ChronoDB db = this.getChronoDB(); this.assumeIncrementalBackupIsSupported(db); long commit1; long commit2; long commit3; long commit4; long commit5; { // commit 1 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a1"); tx.put("mykeyspace", "b", "b1"); tx.put("mykeyspace", "c", "c1"); tx.put("test", "x", 1); commit1 = tx.commit(); } Thread.sleep(1); db.getMaintenanceManager().performRolloverOnAllBranches(); Thread.sleep(1); { // commit 2 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a2"); tx.remove("mykeyspace", "c"); tx.put("mykeyspace", "d", "d1"); tx.put("test", "x", 2); commit2 = tx.commit(); } { // commit 3 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a3"); tx.put("mykeyspace", "d", "d2"); tx.put("test", "x", 3); commit3 = tx.commit(); } Thread.sleep(1); db.getMaintenanceManager().performRolloverOnAllBranches(); Thread.sleep(1); { // commit 4 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a4"); tx.put("mykeyspace", "d", "d3"); tx.put("test", "x", 4); commit4 = tx.commit(); } Thread.sleep(1); db.getMaintenanceManager().performRolloverOnAllBranches(); Thread.sleep(1); { // commit 5 ChronoDBTransaction tx = db.tx(); tx.remove("mykeyspace", "a"); tx.put("mykeyspace", "d", "d4"); tx.put("test", "x", 5); commit5 = tx.commit(); } Thread.sleep(1); db.getMaintenanceManager().performRolloverOnAllBranches(); Thread.sleep(1); db.getDatebackManager().datebackOnMaster(dateback -> dateback.purgeKeyspace("mykeyspace", commit2, commit4)); List<DatebackOperation> allOps = db.getDatebackManager().getAllPerformedDatebackOperations(); assertThat(allOps.size(), is(1)); DatebackOperation operation = Iterables.getOnlyElement(allOps); assertThat(operation, is(instanceOf(IPurgeKeyspaceOperation.class))); IPurgeKeyspaceOperation op = (IPurgeKeyspaceOperation) operation; assertThat(op.getFromTimestamp(), is(commit2)); assertThat(op.getToTimestamp(), is(commit4)); assertThat(op.getKeyspace(), is("mykeyspace")); // check that the keyspace "test" was unaffected assertEquals(1, (int) db.tx(commit1).get("test", "x")); assertEquals(2, (int) db.tx(commit2).get("test", "x")); assertEquals(3, (int) db.tx(commit3).get("test", "x")); assertEquals(4, (int) db.tx(commit4).get("test", "x")); assertEquals(5, (int) db.tx(commit5).get("test", "x")); // check that the commits 2 and 3 are indeed gone assertEquals("a1", db.tx(commit1).get("mykeyspace", "a")); assertEquals("a1", db.tx(commit2).get("mykeyspace", "a")); assertEquals("a1", db.tx(commit3).get("mykeyspace", "a")); assertEquals("a1", db.tx(commit4).get("mykeyspace", "a")); assertNull(db.tx(commit5).get("mykeyspace", "a")); // only insertion and deletion of a should remain assertThat(Iterators.size(db.tx().history("mykeyspace", "a")), is(2)); // b should not have been affected assertEquals("b1", db.tx(commit1).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit2).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit3).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit4).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit5).get("mykeyspace", "b")); assertThat(Iterators.size(db.tx().history("mykeyspace", "b")), is(1)); // the deletion of c should be gone as well assertEquals("c1", db.tx(commit1).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit2).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit3).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit4).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit5).get("mykeyspace", "c")); assertThat(Iterators.size(db.tx().history("mykeyspace", "c")), is(1)); // d should first appear on commit 5 assertNull(db.tx(commit1).get("mykeyspace", "d")); assertNull(db.tx(commit2).get("mykeyspace", "d")); assertNull(db.tx(commit3).get("mykeyspace", "d")); assertNull(db.tx(commit4).get("mykeyspace", "d")); assertEquals("d4", db.tx(commit5).get("mykeyspace", "d")); assertThat(Iterators.size(db.tx().history("mykeyspace", "d")), is(1)); } /** * This method creates a very basic test data setup. * * <p> * The setup contains two keys ("A" and "B") which are inserted in the * {@linkplain ChronoDBConstants#DEFAULT_KEYSPACE_NAME default} keyspace on the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch. * * <p> * Here are the values which are associated with the keys, as well as the rollovers which occur: * <ul> * <li>A = 1, B = 1 * <li>A = 2, B = 2 * <li><i>rollover</i> * <li>A = 3, B = 3, * <li>A = 4, B = 4 * <li><i>rollover</i> * <li>A = 5, B = 5 * <li>A = 6, B = 6 * <li><i>rollover</i> * </ul> * * @param db The database to insert the given dataset into. Must not be <code>null</code>. Is assumed to be an * <i>empty</i> database. * @return The list of the 4 timestamps which mark the starting timestamps of each chunk (the first one is always * zero). */ private static List<Long> createFourRolloverModel(final ChronoDB db) { List<Long> timestamps = Lists.newArrayList(); timestamps.add(db.tx().getTimestamp()); // first chunk { ChronoDBTransaction tx = db.tx(); tx.put("A", 1); tx.put("B", 1); tx.commit(); } { ChronoDBTransaction tx = db.tx(); tx.put("A", 2); tx.put("B", 2); tx.commit(); } sleep(2); db.getMaintenanceManager().performRolloverOnMaster(); sleep(2); timestamps.add(db.tx().getTimestamp()); // second chunk { ChronoDBTransaction tx = db.tx(); tx.put("A", 3); tx.put("B", 3); tx.commit(); } { ChronoDBTransaction tx = db.tx(); tx.put("A", 4); tx.put("B", 4); tx.commit(); } sleep(2); db.getMaintenanceManager().performRolloverOnMaster(); sleep(2); timestamps.add(db.tx().getTimestamp()); // third chunk { ChronoDBTransaction tx = db.tx(); tx.put("A", 5); tx.put("B", 5); tx.commit(); } { ChronoDBTransaction tx = db.tx(); tx.put("A", 6); tx.put("B", 6); tx.commit(); } sleep(2); db.getMaintenanceManager().performRolloverOnMaster(); timestamps.add(db.tx().getTimestamp()); return timestamps; } }
10,216
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BasicDatebackTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/dateback/BasicDatebackTest.java
package org.chronos.chronodb.test.cases.engine.dateback; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.BranchManager; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.Dateback; import org.chronos.chronodb.api.DatebackManager; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.dateback.log.DatebackOperation; import org.chronos.chronodb.internal.api.dateback.log.IPurgeKeyspaceOperation; import org.chronos.chronodb.internal.impl.dateback.log.InjectEntriesOperation; import org.chronos.chronodb.internal.impl.dateback.log.PurgeCommitsOperation; import org.chronos.chronodb.internal.impl.dateback.log.PurgeEntryOperation; import org.chronos.chronodb.internal.impl.dateback.log.PurgeKeyOperation; import org.chronos.chronodb.internal.impl.dateback.log.v2.TransformCommitOperation2; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class BasicDatebackTest extends AllChronoDBBackendsTest { @Test public void canAccessDatebackAPI() { ChronoDB db = this.getChronoDB(); assertNotNull(db.getDatebackManager()); } @Test public void canStartDatebackProcess() { ChronoDB db = this.getChronoDB(); AtomicBoolean enteredDateback = new AtomicBoolean(false); db.getDatebackManager().datebackOnMaster(dateback -> { assertNotNull(dateback); enteredDateback.set(true); }); assertTrue(enteredDateback.get()); } @Test public void datebackIsClosedAfterEvaluatingPassedFunction() { ChronoDB db = this.getChronoDB(); // try to "steal" the dateback object Set<Dateback> datebacks = Sets.newHashSet(); db.getDatebackManager().datebackOnMaster(dateback -> { datebacks.add(dateback); }); assertEquals(1, datebacks.size()); // calling ANY method on this dateback should throw an exception Dateback dateback = Iterables.getOnlyElement(datebacks); assertTrue(dateback.isClosed()); try { dateback.inject("default", "test", 123, "Hello world!"); fail("Managed to steal a dateback object and use it arbitrarily outside of the process."); } catch (IllegalStateException expected) { // pass } } @Test public void cannotOpenTransactionsWhileDatebackProcessIsOngoing() { ChronoDB db = this.getChronoDB(); db.getDatebackManager().datebackOnMaster(dateback -> { try { db.tx(); fail("Managed to open a transaction while in dateback!"); } catch (IllegalStateException expected) { // pass } }); } @Test public void canQueryDatabaseWithDatebackObject() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); long afterFirstCommit = tx.commit(); tx.put("Number", 42); tx.remove("Foo"); long afterSecondCommit = tx.commit(); db.getDatebackManager().datebackOnMaster(dateback -> { // we should be able to query HEAD at the moment assertThat(dateback.get(afterSecondCommit, ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Number"), is(42)); assertThat(dateback.get(afterSecondCommit, ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Foo"), is(nullValue())); // now we alter our last commit dateback.transformCommit(afterSecondCommit, originalCommit -> { HashMap<QualifiedKey, Object> newCommit = Maps.newHashMap(); newCommit.put(QualifiedKey.createInDefaultKeyspace("Number"), Dateback.UNCHANGED); newCommit.put(QualifiedKey.createInDefaultKeyspace("Baz"), "Boom"); return newCommit; }); // queries on afterFirstCommit should still be okay assertThat(dateback.get(afterFirstCommit, ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Hello"), is("World")); assertThat(dateback.get(afterFirstCommit, ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Foo"), is("Bar")); // ... but queries after that should throw an exception try { dateback.get(afterSecondCommit, ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Number"); fail("Managed to perform a get() on a potentially dirty timestamp while a dateback was running"); } catch (IllegalArgumentException expected) { // pass } }); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(TransformCommitOperation2.class, op -> { assertThat(op.getCommitTimestamp(), is(afterSecondCommit)); }); } @Test public void canPurgeSingleEntry() { ChronoDB db = this.getChronoDB(); { // insert some test data ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } long timestamp = db.tx().getTimestamp(); // purge an entry db.getDatebackManager().datebackOnMaster(dateback -> { dateback.purgeEntry(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Hello", timestamp); }); // assert that it's gone assertEquals(Collections.singleton("Foo"), db.tx().keySet()); assertNull(db.tx().get("Hello")); // assert that the other entry is left untouched assertEquals("Bar", db.tx().get("Foo")); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(PurgeEntryOperation.class, op -> { assertThat(op.getOperationTimestamp(), is(timestamp)); assertThat(op.getKeyspace(), is(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); assertThat(op.getKey(), is("Hello")); }); } @Test public void timestampNeedsToBePreciseWhenPurgingEntries() { ChronoDB db = this.getChronoDB(); { // insert some test data ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } long timestamp = db.tx().getTimestamp(); // purge an entry db.getDatebackManager().datebackOnMaster(dateback -> { // note that the timestamp is "off by one" here boolean purged = dateback.purgeEntry(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Hello", timestamp + 1); assertFalse(purged); }); // make sure the operation was not logged (because it wasn't successful / didn't change anything) List<DatebackOperation> allOperations = db.getDatebackManager().getAllPerformedDatebackOperations(); assertThat(allOperations.size(), is(0)); } @Test public void canPurgeKey() { ChronoDB db = this.getChronoDB(); { // test data #1 ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } long afterFirstCommit = db.tx().getTimestamp(); { // test data #2 ChronoDBTransaction tx = db.tx(); tx.put("Foo", "Baz"); tx.commit(); } long afterSecondCommit = db.tx().getTimestamp(); { // test data #3 ChronoDBTransaction tx = db.tx(); tx.remove("Foo"); tx.commit(); } long afterThirdCommit = db.tx().getTimestamp(); // purge the "Foo" key db.getDatebackManager().datebackOnMaster(dateback -> { dateback.purgeKey(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Foo"); }); // make sure that it is gone assertNull(db.tx(afterThirdCommit).get("Foo")); assertNull(db.tx(afterSecondCommit).get("Foo")); assertNull(db.tx(afterFirstCommit).get("Foo")); Iterator<Long> history = db.tx().history("Foo"); assertFalse(history.hasNext()); // make sure that the other key still exists assertEquals("World", db.tx().get("Hello")); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(PurgeKeyOperation.class, op -> { assertThat(op.getFromTimestamp(), is(greaterThan(0L))); assertThat(op.getFromTimestamp(), is(lessThan(op.getToTimestamp()))); assertThat(op.getKeyspace(), is(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); assertThat(op.getKey(), is("Foo")); }); } @Test public void canPurgeKeyDeletionWithPredicateOnNullValue() { ChronoDB db = this.getChronoDB(); { // test data #1 ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } { // test data #2 ChronoDBTransaction tx = db.tx(); tx.remove("Foo"); tx.commit(); } { // test data #3 ChronoDBTransaction tx = db.tx(); tx.remove("Hello"); tx.commit(); } assertEquals(Collections.emptySet(), db.tx().keySet()); // purge all deletions on "Hello" db.getDatebackManager().datebackOnMaster(dateback -> { dateback.purgeKey(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Hello", (time, value) -> value == null); }); // make sure that "Hello" exists now (the deletion entry was purged) assertEquals(Collections.singleton("Hello"), db.tx().keySet()); assertEquals("World", db.tx().get("Hello")); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(PurgeKeyOperation.class, op -> { assertThat(op.getFromTimestamp(), is(greaterThan(0L))); assertThat(op.getFromTimestamp(), is(lessThanOrEqualTo(op.getToTimestamp()))); assertThat(op.getKeyspace(), is(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); assertThat(op.getKey(), is("Hello")); }); } @Test public void canPurgeSingleCommit() { ChronoDB db = this.getChronoDB(); { // test data #1 ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit("First"); } { // test data #2 ChronoDBTransaction tx = db.tx(); tx.put("Hello", "Chronos"); tx.remove("Foo"); tx.commit("Second"); } long secondCommitTimestamp = db.tx().getTimestamp(); { // test data #2 ChronoDBTransaction tx = db.tx(); tx.put("John", "Doe"); tx.commit("Third"); } assertEquals("Chronos", db.tx().get("Hello")); assertNull(db.tx().get("Foo")); assertEquals("Doe", db.tx().get("John")); // purge the second commit db.getDatebackManager().datebackOnMaster(dateback -> { dateback.purgeCommit(secondCommitTimestamp); }); // "Hello" should point to "World" again, and "Foo" should not be deleted and point to "Bar" assertEquals("World", db.tx().get("Hello")); assertEquals("Bar", db.tx().get("Foo")); assertEquals("Doe", db.tx().get("John")); // also, we should not have this commit in the commit log anymore assertNull(db.tx().getCommitMetadata(secondCommitTimestamp)); // the keys should not have it in their history anymore either assertEquals(1, Iterators.size(db.tx().history("Hello"))); assertEquals(1, Iterators.size(db.tx().history("Foo"))); assertEquals(1, Iterators.size(db.tx().history("John"))); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(PurgeCommitsOperation.class, op -> { assertThat(op.getCommitTimestamps(), contains(secondCommitTimestamp)); }); } @Test public void canPurgeMultipleCommits() { ChronoDB db = this.getChronoDB(); { // test data #1 ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit("First"); } { // test data #2 ChronoDBTransaction tx = db.tx(); tx.put("Hello", "Chronos"); tx.remove("Foo"); tx.commit("Second"); } long secondCommitTimestamp = db.tx().getTimestamp(); { // test data #2 ChronoDBTransaction tx = db.tx(); tx.put("John", "Doe"); tx.commit("Third"); } long thirdCommitTimestamp = db.tx().getTimestamp(); assertEquals("Chronos", db.tx().get("Hello")); assertNull(db.tx().get("Foo")); assertEquals("Doe", db.tx().get("John")); System.out.println("Second commit timestamp: " + secondCommitTimestamp); System.out.println("Third commit timestamp: " + thirdCommitTimestamp); assertThat(thirdCommitTimestamp, is(greaterThan(secondCommitTimestamp))); // purge the last two commits db.getDatebackManager().datebackOnMaster(dateback -> { dateback.purgeCommits(secondCommitTimestamp, thirdCommitTimestamp); }); // "Hello" should point to "World" again, "Foo should point to "Bar", and "John" should not exist assertEquals("World", db.tx().get("Hello")); assertEquals("Bar", db.tx().get("Foo")); assertNull(db.tx().get("John")); assertEquals(1, Iterators.size(db.tx().getCommitTimestampsBetween(0, thirdCommitTimestamp))); // the keys should not have it in their history anymore either assertEquals(1, Iterators.size(db.tx().history("Hello"))); assertEquals(1, Iterators.size(db.tx().history("Foo"))); assertEquals(0, Iterators.size(db.tx().history("John"))); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(PurgeCommitsOperation.class, op -> { assertThat(op.getCommitTimestamps(), containsInAnyOrder(secondCommitTimestamp, thirdCommitTimestamp)); }); } @Test public void canInjectSingleEntryInThePast() { ChronoDB db = this.getChronoDB(); { // test data ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Baz"); tx.commit(); } long now = db.tx().getTimestamp(); // inject the value db.getDatebackManager().datebackOnMaster(dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Foo", 1234L, "Bar"); }); // make sure that the injected value is present in the history assertEquals(Sets.newHashSet(1234L, now), Sets.newHashSet(db.tx().history("Foo"))); // we should be able to retrieve this value normally assertEquals("Bar", db.tx(1234L).get("Foo")); // we should also see the new commit assertEquals(Collections.singletonList(1234L), db.tx().getCommitTimestampsBefore(1235L, 1)); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(InjectEntriesOperation.class, op -> { assertThat(op.getOperationTimestamp(), is(1234L)); assertThat(op.getInjectedKeys(), hasItems(QualifiedKey.createInDefaultKeyspace("Foo"))); }); } @Test public void cannotInjectIntoTheFuture() { ChronoDB db = this.getChronoDB(); long timestamp = System.currentTimeMillis() + 100000; db.getDatebackManager().datebackOnMaster(dateback -> { try { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Hello", timestamp, "World"); fail("Managed to inject entries into the future!"); } catch (IllegalArgumentException expected) { // pass } }); // make sure the operation was not logged List<DatebackOperation> allOperations = db.getDatebackManager().getAllPerformedDatebackOperations(); assertThat(allOperations.size(), is(0)); } @Test public void canInjectSingleEntryOnAnUnusedKey() { ChronoDB db = this.getChronoDB(); long timestamp = System.currentTimeMillis(); db.getDatebackManager().datebackOnMaster(dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Hello", timestamp, "World"); }); // make sure that the NOW timestamp was advanced assertEquals(timestamp, db.tx().getTimestamp()); // make sure that the entry is now in the database assertEquals("World", db.tx().get("Hello")); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(InjectEntriesOperation.class, op -> { assertThat(op.getInjectedKeys(), hasItems(QualifiedKey.createInDefaultKeyspace("Hello"))); }); } @Test public void canInjectDeletion() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } // make sure that at least 1 millisecond has passed between the commit and our dateback, // otherwise we would override our entry with a deletion (which is not what we want) sleep(1); // inject the deletion db.getDatebackManager().datebackOnMaster(dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Foo", System.currentTimeMillis(), null); }); // make sure that "Foo" is gone in the head revision assertEquals(Collections.singleton("Hello"), db.tx().keySet()); // "Foo" should have 2 history entries (creation + deletion) assertEquals(2, Iterators.size(db.tx().history("Foo"))); // our deletion injection should have created a commit assertEquals(2, db.tx().getCommitTimestampsAfter(0, 10).size()); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(InjectEntriesOperation.class, op -> { assertThat(op.getOperationTimestamp(), is(db.tx().getTimestamp())); assertThat(op.getInjectedKeys(), containsInAnyOrder(QualifiedKey.createInDefaultKeyspace("Foo"))); }); } @Test public void canOverrideEntryWithInjection() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } long now = db.tx().getTimestamp(); // inject an entry exactly at the same coordinates db.getDatebackManager().datebackOnMaster(dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Foo", now, "Baz"); }); // assert that "Foo" has the proper new value assertEquals("Baz", db.tx().get("Foo")); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(InjectEntriesOperation.class, op -> { assertThat(op.getOperationTimestamp(), is(now)); assertThat(op.getInjectedKeys(), contains(QualifiedKey.createInDefaultKeyspace("Foo"))); }); } @Test public void canInjectMultipleEntries() { ChronoDB db = this.getChronoDB(); { // insert test data ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } long latestTimestampBeforeInjection = db.tx().getTimestamp(); // make sure that at least 1 millisecond has passed between the commit and our dateback, // otherwise we would override our entry with a deletion (which is not what we want) sleep(1); // inject new values db.getDatebackManager().datebackOnMaster(dateback -> { String keyspace = ChronoDBConstants.DEFAULT_KEYSPACE_NAME; Map<QualifiedKey, Object> entries = Maps.newHashMap(); entries.put(QualifiedKey.create(keyspace, "Foo"), "Baz"); entries.put(QualifiedKey.create(keyspace, "Hello"), null); // null for deletion entries.put(QualifiedKey.create(keyspace, "John"), "Doe"); dateback.inject(System.currentTimeMillis(), entries, "Injected Commit"); }); long now = db.tx().getTimestamp(); // this injection should have advanced our timestamp assertTrue(now > latestTimestampBeforeInjection); // the new commit should appear in the log assertEquals("Injected Commit", db.tx().getCommitMetadata(now)); // check that the key set is correct assertEquals(Sets.newHashSet("Foo", "John"), db.tx().keySet()); // check that the assigned values are correct assertEquals("Baz", db.tx().get("Foo")); assertEquals("Doe", db.tx().get("John")); // assert that the history lengths are correct assertEquals(2, Iterators.size(db.tx().history("Hello"))); assertEquals(2, Iterators.size(db.tx().history("Foo"))); assertEquals(1, Iterators.size(db.tx().history("John"))); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(InjectEntriesOperation.class, op -> { assertThat(op.getInjectedKeys(), containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("Foo"), QualifiedKey.createInDefaultKeyspace("Hello"), QualifiedKey.createInDefaultKeyspace("John") )); }); } @Test public void cannotInjectEntriesBeforeBranchingTimestamp() { ChronoDB db = this.getChronoDB(); {// insert test data on MASTER ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); } // create the test branch Branch testBranch = db.getBranchManager().createBranch("test"); // start a dateback on the test branch and attempt to inject values before the branching timestamp // (which would make them entries of "master", which is clearly not intended) db.getDatebackManager().dateback(testBranch.getName(), dateback -> { try { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "John", testBranch.getBranchingTimestamp() - 1, "Doe"); fail("Managed to inject data on branch before the branching timestamp!"); } catch (IllegalArgumentException expected) { // pass } }); assertThat(db.getDatebackManager().getAllPerformedDatebackOperations(), is(empty())); } @Test public void canInjectEntryIntoNewKeyspace() { ChronoDB db = this.getChronoDB(); db.getDatebackManager().datebackOnMaster(dateback -> { dateback.inject("people", "John", 1234L, "Doe"); }); assertEquals(Sets.newHashSet(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "people"), db.tx().keyspaces()); assertEquals("Doe", db.tx().get("people", "John")); // make sure the operation was logged this.assertSingleDatebackOperationWasLogged(InjectEntriesOperation.class, op -> { assertThat(op.getOperationTimestamp(), is(1234L)); assertThat(op.getInjectedKeys(), contains(QualifiedKey.create("people", "John"))); }); } @Test public void testDatebackOnBranches() { ChronoDB db = this.getChronoDB(); long commit1; long commit2; long commit3; long commit4; long commit5; long commit6; long commit7; long commit8; long commit9; long commit10; { // first commit on master ChronoDBTransaction tx = db.tx(); tx.put("John", "Doe"); commit1 = tx.commit(); } { // second commit on master ChronoDBTransaction tx = db.tx(); tx.put("Jane", "Doe"); commit2 = tx.commit(); } BranchManager branchManager = db.getBranchManager(); branchManager.createBranch("B1"); { ChronoDBTransaction tx = db.tx("B1"); tx.put("John", "Foo"); commit3 = tx.commit(); } { ChronoDBTransaction tx = db.tx(); tx.remove("John"); commit4 = tx.commit(); } { ChronoDBTransaction tx = db.tx(); tx.put("John", "HereAgain"); commit5 = tx.commit(); } { ChronoDBTransaction tx = db.tx("B1"); tx.put("Isaac", "Newton"); commit6 = tx.commit(); } branchManager.createBranch("B1", "B2"); { ChronoDBTransaction tx = db.tx("B2"); tx.put("John", "Newton"); commit7 = tx.commit(); } { ChronoDBTransaction tx = db.tx("B1"); tx.remove("Jane"); commit8 = tx.commit(); } { ChronoDBTransaction tx = db.tx("B1"); tx.put("Mao", "Almaz"); commit9 = tx.commit(); } { ChronoDBTransaction tx = db.tx(); tx.put("Isaac", "Einstein"); commit10 = tx.commit(); } DatebackManager datebackManager = db.getDatebackManager(); datebackManager.datebackOnMaster(dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Alien", commit1, "E.T."); }); assertThat(db.tx("B2").get("Alien"), is("E.T.")); datebackManager.datebackOnMaster(dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Jane", commit4, null); }); assertThat(db.tx().get("Jane"), is(nullValue())); assertThat(db.tx("B2").get("Jane"), is("Doe")); datebackManager.dateback("B1", dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Foo", commit3, "Bar"); }); assertThat(db.tx().get("Foo"), is(nullValue())); assertThat(db.tx("B1").get("Foo"), is("Bar")); assertThat(db.tx("B2").get("Foo"), is("Bar")); datebackManager.dateback("B1", dateback -> { dateback.purgeEntry(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Jane", commit8); }); assertThat(db.tx("B1").get("Jane"), is("Doe")); datebackManager.dateback("B2", dateback -> { dateback.inject(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, "Jane", commit7, "Newton"); }); assertThat(db.tx("B2").get("Jane"), is("Newton")); assertThat(db.tx("B1").get("Jane"), is("Doe")); assertThat(db.tx().get("Jane"), is(nullValue())); List<DatebackOperation> b2Dateback = datebackManager.getDatebackOperationsAffectingTimestamp("B2", commit7); assertThat(b2Dateback.size(), is(3)); List<DatebackOperation> b1Dateback = datebackManager.getDatebackOperationsAffectingTimestamp("B1", commit9); assertThat(b1Dateback.size(), is(3)); List<DatebackOperation> dateback = datebackManager.getDatebackOperationsAffectingTimestamp(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, commit10); assertThat(dateback.size(), is(2)); } @Test public void canPurgeKeyspace() { ChronoDB db = this.getChronoDB(); long commit1; long commit2; long commit3; long commit4; long commit5; { // commit 1 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a1"); tx.put("mykeyspace", "b", "b1"); tx.put("mykeyspace", "c", "c1"); tx.put("test", "x", 1); commit1 = tx.commit(); } { // commit 2 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a2"); tx.remove("mykeyspace", "c"); tx.put("mykeyspace", "d", "d1"); tx.put("test", "x", 2); commit2 = tx.commit(); } { // commit 3 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a3"); tx.put("mykeyspace", "d", "d2"); tx.put("test", "x", 3); commit3 = tx.commit(); } { // commit 4 ChronoDBTransaction tx = db.tx(); tx.put("mykeyspace", "a", "a4"); tx.put("mykeyspace", "d", "d3"); tx.put("test", "x", 4); commit4 = tx.commit(); } { ChronoDBTransaction tx = db.tx(); tx.remove("mykeyspace", "a"); tx.put("mykeyspace", "d", "d4"); tx.put("test", "x", 5); commit5 = tx.commit(); } db.getDatebackManager().datebackOnMaster(dateback -> dateback.purgeKeyspace("mykeyspace", commit2, commit4)); List<DatebackOperation> allOps = db.getDatebackManager().getAllPerformedDatebackOperations(); assertThat(allOps.size(), is(1)); DatebackOperation operation = Iterables.getOnlyElement(allOps); assertThat(operation, is(instanceOf(IPurgeKeyspaceOperation.class))); IPurgeKeyspaceOperation op = (IPurgeKeyspaceOperation) operation; assertThat(op.getFromTimestamp(), is(commit2)); assertThat(op.getToTimestamp(), is(commit4)); assertThat(op.getKeyspace(), is("mykeyspace")); // check that the keyspace "test" was unaffected assertEquals(1, (int) db.tx(commit1).get("test", "x")); assertEquals(2, (int) db.tx(commit2).get("test", "x")); assertEquals(3, (int) db.tx(commit3).get("test", "x")); assertEquals(4, (int) db.tx(commit4).get("test", "x")); assertEquals(5, (int) db.tx(commit5).get("test", "x")); // check that the commits 2 and 3 are indeed gone assertEquals("a1", db.tx(commit1).get("mykeyspace", "a")); assertEquals("a1", db.tx(commit2).get("mykeyspace", "a")); assertEquals("a1", db.tx(commit3).get("mykeyspace", "a")); assertEquals("a1", db.tx(commit4).get("mykeyspace", "a")); assertNull(db.tx(commit5).get("mykeyspace", "a")); // only insertion and deletion of a should remain assertThat(Iterators.size(db.tx().history("mykeyspace", "a")), is(2)); // b should not have been affected assertEquals("b1", db.tx(commit1).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit2).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit3).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit4).get("mykeyspace", "b")); assertEquals("b1", db.tx(commit5).get("mykeyspace", "b")); assertThat(Iterators.size(db.tx().history("mykeyspace", "b")), is(1)); // the deletion of c should be gone as well assertEquals("c1", db.tx(commit1).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit2).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit3).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit4).get("mykeyspace", "c")); assertEquals("c1", db.tx(commit5).get("mykeyspace", "c")); assertThat(Iterators.size(db.tx().history("mykeyspace", "c")), is(1)); // d should first appear on commit 5 assertNull(db.tx(commit1).get("mykeyspace", "d")); assertNull(db.tx(commit2).get("mykeyspace", "d")); assertNull(db.tx(commit3).get("mykeyspace", "d")); assertNull(db.tx(commit4).get("mykeyspace", "d")); assertEquals("d4", db.tx(commit5).get("mykeyspace", "d")); assertThat(Iterators.size(db.tx().history("mykeyspace", "d")), is(1)); } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= @SuppressWarnings("unchecked") private <T extends DatebackOperation> void assertSingleDatebackOperationWasLogged(Class<T> type, Consumer<T> check) { ChronoDB db = this.getChronoDB(); List<DatebackOperation> allOperations = db.getDatebackManager().getAllPerformedDatebackOperations(); assertThat(allOperations.size(), is(1)); DatebackOperation operation = Iterables.getOnlyElement(allOperations); assertThat(operation, is(instanceOf(type))); assertThat(operation.getBranch(), is(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER)); assertThat(operation.getWallClockTime(), is(greaterThanOrEqualTo(db.tx().getTimestamp()))); T op = (T) operation; check.accept(op); List<DatebackOperation> operationsOnMaster = db.getDatebackManager().getDatebackOperationsAffectingTimestamp(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, System.currentTimeMillis()); assertThat(operationsOnMaster, is(allOperations)); List<DatebackOperation> operationsInRange = db.getDatebackManager().getDatebackOperationsPerformedBetween(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, 0, System.currentTimeMillis()); assertThat(operationsInRange, is(allOperations)); } }
34,333
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DuplicateVersionEliminationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/safetyfeatures/DuplicateVersionEliminationTest.java
package org.chronos.chronodb.test.cases.engine.safetyfeatures; import com.google.common.collect.Lists; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.DuplicateVersionEliminationMode; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class DuplicateVersionEliminationTest extends AllChronoDBBackendsTest { @Test public void duplicateVersionEliminationOnCommitWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.txBuilder() .withDuplicateVersionEliminationMode(DuplicateVersionEliminationMode.ON_COMMIT).build(); // add some data tx.put("first", 123); tx.put("second", 456); tx.commit(); long afterFirstCommit = tx.getTimestamp(); // try to put a duplicate, an update, and an insert tx.put("first", 123); // duplicate tx.put("second", "abc"); // update tx.put("third", Math.PI); // insert tx.commit(); // assert that the key history of "first" only has one entry. // It must have only one, because the second commit on the key was a duplicate and should // have been eliminated. List<Long> historyTimestamps = Lists.newArrayList(tx.history("first")); assertEquals(1, historyTimestamps.size()); assertTrue(historyTimestamps.contains(afterFirstCommit)); // assert that the eliminated duplicate is still available in the head revision assertEquals(123, (int) tx.get("first")); } }
1,819
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RollbackToWALTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/safetyfeatures/RollbackToWALTest.java
package org.chronos.chronodb.test.cases.engine.safetyfeatures; import com.google.common.collect.Sets; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.exceptions.ChronoDBCommitException; import org.chronos.chronodb.internal.api.BranchInternal; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.KillSwitchCollection; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.function.Consumer; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class RollbackToWALTest extends AllChronoDBBackendsTest { // ================================================================================================================= // REGULAR COMMIT TESTS // ================================================================================================================= @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforePrimaryIndexUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforePrimaryIndexUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforePrimaryIndexUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforePrimaryIndexUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeSecondaryIndexUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeSecondaryIndexUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeSecondaryIndexUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeSecondaryIndexUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeMetadataUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeMetadataUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeMetadataUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeMetadataUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeCacheUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeCacheUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeCacheUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeCacheUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeNowTimestampUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeNowTimestampUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeNowTimestampUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeNowTimestampUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeTransactionCommittedUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeTransactionCommitted(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.REGULAR); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingTxTest_BeforeTransactionCommitted_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeTransactionCommitted(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.REGULAR); } // ================================================================================================================= // INCREMENTAL COMMIT TESTS // ================================================================================================================= @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforePrimaryIndexUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforePrimaryIndexUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforePrimaryIndexUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforePrimaryIndexUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeSecondaryIndexUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeSecondaryIndexUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeSecondaryIndexUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeSecondaryIndexUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeMetadataUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeMetadataUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeMetadataUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeMetadataUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeCacheUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeCacheUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeCacheUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeCacheUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeNowTimestampUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeNowTimestampUpdate(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeNowTimestampUpdate_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeNowTimestampUpdate(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeTransactionCommittedUpdate_WithException() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeTransactionCommitted(crashWith(new RuntimeException())); this.runTest(killSwitches, ThreadMode.SINGLE, CommitMode.INCREMENTAL); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void crashingIncTxTest_BeforeTransactionCommitted_WithThreadKill() { KillSwitchCollection killSwitches = new KillSwitchCollection(); killSwitches.setOnBeforeTransactionCommitted(killThread()); this.runTest(killSwitches, ThreadMode.THREAD_PER_COMMIT, CommitMode.INCREMENTAL); } // ================================================================================================================= // ACTUAL TEST METHOD // ================================================================================================================= private void runTest(final KillSwitchCollection callbacks, final ThreadMode threadMode, final CommitMode commitMode) { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { ChronoDBTransaction tx = db.tx(); tx.put("one", NamedPayload.create1KB("Hello World")); tx.put("two", NamedPayload.create1KB("Foo Bar")); tx.put("three", NamedPayload.create1KB("Baz")); tx.commit(); } // check that everything is in the database assertEquals(Sets.newHashSet("one", "two", "three"), db.tx().keySet()); // check that the secondary index is okay assertEquals(2, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("ba").count()); long nowAfterCommit = db.getBranchManager().getMasterBranch().getNow(); Branch branch = db.getBranchManager().getMasterBranch(); TemporalKeyValueStore tkvs = ((BranchInternal) branch).getTemporalKeyValueStore(); // set up the callbacks tkvs.setDebugCallbackBeforePrimaryIndexUpdate(callbacks.getOnBeforePrimaryIndexUpdate()); tkvs.setDebugCallbackBeforeSecondaryIndexUpdate(callbacks.getOnBeforeSecondaryIndexUpdate()); tkvs.setDebugCallbackBeforeMetadataUpdate(callbacks.getOnBeforeMetadataUpdate()); tkvs.setDebugCallbackBeforeCacheUpdate(callbacks.getOnBeforeCacheUpdate()); tkvs.setDebugCallbackBeforeNowTimestampUpdate(callbacks.getOnBeforeNowTimestampUpdate()); tkvs.setDebugCallbackBeforeTransactionCommitted(callbacks.getOnBeforeTransactionCommitted()); { if (ThreadMode.THREAD_PER_COMMIT.equals(threadMode)) { Thread thread = new Thread(() -> { this.doFaultyCommit(db, commitMode); }); thread.start(); try { thread.join(); } catch (InterruptedException e) { } } else { this.doFaultyCommit(db, commitMode); } } // uninstall the kill switch tkvs.setDebugCallbackBeforePrimaryIndexUpdate(null); tkvs.setDebugCallbackBeforeSecondaryIndexUpdate(null); tkvs.setDebugCallbackBeforeMetadataUpdate(null); tkvs.setDebugCallbackBeforeCacheUpdate(null); tkvs.setDebugCallbackBeforeNowTimestampUpdate(null); tkvs.setDebugCallbackBeforeTransactionCommitted(null); // make sure that none of the data managed to get through assertEquals(nowAfterCommit, db.getBranchManager().getMasterBranch().getNow()); // check that everything is in the database assertEquals(Sets.newHashSet("one", "two", "three"), db.tx().keySet()); // check that the secondary index is okay assertEquals(2, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("ba").count()); // make another regular commit { ChronoDBTransaction tx = db.tx(); tx.put("one", NamedPayload.create1KB("42")); tx.put("two", NamedPayload.create1KB("Foo")); // remove the "Bar" tx.put("five", NamedPayload.create1KB("High Five")); tx.commit(); } // make sure that the changes of the last commit are present, but the ones from the failed commit are not assertEquals(Sets.newHashSet("one", "two", "three", "five"), db.tx().keySet()); // check that the secondary index is okay assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("ba").count()); assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("another").count()); assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("five").count()); } private void doFaultyCommit(final ChronoDB db, final CommitMode commitMode) { try { ChronoDBTransaction txFail = db.tx(); if (CommitMode.INCREMENTAL.equals(commitMode)) { txFail.commitIncremental(); } txFail.put("one", NamedPayload.create1KB("Babadu")); txFail.put("four", NamedPayload.create1KB("Another")); if (CommitMode.INCREMENTAL.equals(commitMode)) { txFail.commitIncremental(); } txFail.commit(); fail("Commit was accepted even though kill switch was installed!"); } catch (ChronoDBCommitException exception) { // pass } } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= private static Consumer<ChronoDBTransaction> crashWith(final Throwable t) { return tx -> { sneakyThrow(t); }; } @SuppressWarnings("deprecation") private static Consumer<ChronoDBTransaction> killThread() { return tx -> { Thread.currentThread().stop(); }; } @SuppressWarnings("unchecked") private static <T extends Throwable> void sneakyThrow(final Throwable t) throws T { throw (T) t; } // ================================================================================================================= // INNER CLASSES // ================================================================================================================= private static enum ThreadMode { SINGLE, THREAD_PER_COMMIT } private static enum CommitMode { REGULAR, INCREMENTAL } }
20,063
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BranchHeadStatisticsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/statistics/BranchHeadStatisticsTest.java
package org.chronos.chronodb.test.cases.engine.statistics; import org.chronos.chronodb.api.*; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Assume; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class BranchHeadStatisticsTest extends AllChronoDBBackendsTest { @Test public void canGetBranchHeadStatisticsOnEmptyDatabase(){ ChronoDB db = this.getChronoDB(); BranchHeadStatistics statistics = db.getStatisticsManager().getMasterBranchHeadStatistics(); assertThat(statistics, is(notNullValue())); assertThat(statistics.getNumberOfEntriesInHead(), is(0L)); assertThat(statistics.getNumberOfEntriesInHistory(), is(0L)); assertThat(statistics.getHeadHistoryRatio(), is(1.0)); } @Test public void hhrCalculationOnMasterIsCorrect(){ ChronoDB db = this.getChronoDB(); StatisticsManager statisticsManager = db.getStatisticsManager(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); assertThat(statisticsManager.getMasterBranchHeadStatistics().getNumberOfEntriesInHead(), is(2L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getTotalNumberOfEntries(), is(2L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getNumberOfEntriesInHistory(), is(0L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getHeadHistoryRatio(), is(1.0)); tx.put("Number", 42); tx.put("Foo", "Baz"); tx.remove("Hello"); tx.commit(); assertThat(statisticsManager.getMasterBranchHeadStatistics().getNumberOfEntriesInHead(), is(2L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getTotalNumberOfEntries(), is(5L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getNumberOfEntriesInHistory(), is(3L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getHeadHistoryRatio(), is(2.0/5.0)); } @Test public void hhrCalculationOnBranchIsCorrect(){ ChronoDB db = this.getChronoDB(); StatisticsManager statisticsManager = db.getStatisticsManager(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); db.getBranchManager().createBranch("test"); assertThat(statisticsManager.getBranchHeadStatistics("test"), is(notNullValue())); assertThat(statisticsManager.getBranchHeadStatistics("test").getTotalNumberOfEntries(), is(0L)); assertThat(statisticsManager.getBranchHeadStatistics("test").getNumberOfEntriesInHead(), is(2L)); assertThat(statisticsManager.getBranchHeadStatistics("test").getHeadHistoryRatio(), is(2.0)); tx = db.tx("test"); tx.put("Number", 42); tx.remove("Foo"); tx.commit(); assertThat(statisticsManager.getBranchHeadStatistics("test").getTotalNumberOfEntries(), is(2L)); assertThat(statisticsManager.getBranchHeadStatistics("test").getNumberOfEntriesInHead(), is(2L)); assertThat(statisticsManager.getBranchHeadStatistics("test").getHeadHistoryRatio(), is(1.0)); } @Test public void hhrCalculationAfterRolloverIsCorrect(){ ChronoDB db = this.getChronoDB(); this.assumeRolloverIsSupported(db); StatisticsManager statisticsManager = db.getStatisticsManager(); ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); tx.put("Hello", "Chronos"); tx.remove("Foo"); tx.put("Number", 42); tx.commit(); db.getMaintenanceManager().performRolloverOnMaster(); assertThat(statisticsManager.getMasterBranchHeadStatistics().getNumberOfEntriesInHead(), is(2L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getTotalNumberOfEntries(), is(2L)); assertThat(statisticsManager.getMasterBranchHeadStatistics().getHeadHistoryRatio(), is(1.0)); } }
4,293
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BasicTransactionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/BasicTransactionTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.SerializationManager; import org.chronos.chronodb.api.exceptions.ChronoDBTransactionException; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class BasicTransactionTest extends AllChronoDBBackendsTest { @Test public void basicCommitAndGetWorks() { ChronoDB chronoDB = this.getChronoDB(); ChronoDBTransaction tx = chronoDB.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); assertEquals("World", tx.get("Hello")); assertEquals("Bar", tx.get("Foo")); } @Test public void cantOpenTransactionIntoTheFuture() { ChronoDB chronoDB = this.getChronoDB(); ChronoDBTransaction tx = chronoDB.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); try { tx = chronoDB.tx(System.currentTimeMillis() + 1000); fail("Managed to open a transaction into the future!"); } catch (ChronoDBTransactionException e) { // expected } } @Test public void canRemoveKeys() { ChronoDB chronoDB = this.getChronoDB(); ChronoDBTransaction tx = chronoDB.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); tx.remove("Hello"); tx.commit(); assertEquals(false, tx.exists("Hello")); assertEquals(2, Iterators.size(tx.history("Hello"))); } @Test public void removalOfKeysAffectsKeySet() { ChronoDB chronoDB = this.getChronoDB(); ChronoDBTransaction tx = chronoDB.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); tx.remove("Hello"); tx.commit(); assertFalse(tx.exists("Hello")); assertEquals(1, tx.keySet().size()); } @Test public void removedKeysNoLongerExist() { ChronoDB chronoDB = this.getChronoDB(); ChronoDBTransaction tx = chronoDB.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.commit(); tx.remove("Hello"); tx.commit(); assertTrue(tx.exists("Foo")); assertFalse(tx.exists("Hello")); } @Test public void transactionsAreIsolated() { ChronoDB chronoDB = this.getChronoDB(); ChronoDBTransaction tx = chronoDB.tx(); tx.put("Value1", 1234); tx.put("Value2", 1000); tx.commit(); // Transaction A: read-only; used to check isolation level ChronoDBTransaction txA = chronoDB.tx(); // Transaction B: will set Value1 to 47 ChronoDBTransaction txB = chronoDB.tx(); // Transaction C: will set Value2 to 2000 ChronoDBTransaction txC = chronoDB.tx(); // perform the work in C (while B is open) txC.put("Value2", 2000); txC.commit(); // make sure that isolation level of Transaction A is not violated assertEquals(1234, (int) txA.get("Value1")); assertEquals(1000, (int) txA.get("Value2")); // perform work in B (note that we change different keys than in C) txB.put("Value1", 47); txB.commit(); // make sure that isolation level of Transaction A is not violated assertEquals(1234, (int) txA.get("Value1")); assertEquals(1000, (int) txA.get("Value2")); // Transaction D: read-only; used to check that commits were successful ChronoDBTransaction txD = chronoDB.tx(); // ensure that D sees the results of B and C assertEquals(47, (int) txD.get("Value1")); assertEquals(2000, (int) txD.get("Value2")); } @Test public void canRemoveAndPutInSameTransaction() { ChronoDB chronoDB = this.getChronoDB(); ChronoDBTransaction tx1 = chronoDB.tx(); tx1.put("Hello", "World"); tx1.put("programming", "Foo", "Bar"); tx1.commit(); ChronoDBTransaction tx2 = chronoDB.tx(); tx2.remove("Hello"); tx2.remove("programming", "Foo"); tx2.put("Hello", "ChronoDB"); tx2.put("programming", "Foo", "Baz"); tx2.commit(); ChronoDBTransaction tx3 = chronoDB.tx(); assertEquals("ChronoDB", tx3.get("Hello")); assertEquals("Baz", tx3.get("programming", "Foo")); } @Test public void commitReturnsTheCommitTimestamp() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); tx1.put("Hello", "World"); long time1 = tx1.commit(); assertEquals(db.tx().getTimestamp(), time1); ChronoDBTransaction tx2 = db.tx(); tx2.put("Foo", "Bar"); long time2 = tx2.commit(); assertEquals(db.tx().getTimestamp(), time2); ChronoDBTransaction tx3 = db.tx(); tx3.put("Foo", "Baz"); long time3 = tx3.commit(); assertEquals(db.tx().getTimestamp(), time3); assertTrue(time1 >= 0); assertTrue(time2 >= 0); assertTrue(time3 >= 0); assertTrue(time2 > time1); assertTrue(time3 > time2); ChronoDBTransaction tx = db.tx(); List<Long> timestamps = tx.getCommitTimestampsAfter(0, 3); assertEquals(3, timestamps.size()); assertTrue(timestamps.contains(time1)); assertTrue(timestamps.contains(time2)); assertTrue(timestamps.contains(time3)); } @Test public void canPerformGetBinary(){ ChronoDB db = this.getChronoDB(); { // first commit ChronoDBTransaction tx = db.tx(); tx.put("hello", "world"); tx.put("number", 42); tx.commit(); } { // second commit ChronoDBTransaction tx = db.tx(); tx.put("hello", "chronos"); tx.put("foo", "bar"); tx.commit(); } List<String> allKeys = Lists.newArrayList("hello", "number", "foo"); List<Long> commitTimestamps = db.tx().getCommitTimestampsAfter(0L, 10); SerializationManager serman = db.getSerializationManager(); for(Long commitTimestamp : commitTimestamps){ ChronoDBTransaction tx = db.tx(commitTimestamp); for(String key : allKeys) { Object original = tx.get(key); byte[] binary = tx.getBinary(key); if(original == null){ assertNull(binary); }else{ assertEquals(original, serman.deserialize(binary)); } } } } }
7,029
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IncrementalCommitTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/IncrementalCommitTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.exceptions.ChronoDBCommitException; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class IncrementalCommitTest extends AllChronoDBBackendsTest { private static final Logger log = LoggerFactory.getLogger(IncrementalCommitTest.class); @Test public void canCommitIncrementallyMoreThanTwice() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("a", 1); tx.commitIncremental(); assertEquals(1, (int) tx.get("a")); tx.put("a", 2); tx.commitIncremental(); assertEquals(2, (int) tx.get("a")); tx.put("a", 3); tx.commitIncremental(); assertEquals(3, (int) tx.get("a")); tx.commit(); } finally { tx.rollback(); } assertEquals(3, (int) db.tx().get("a")); } @Test public void canCommitIncrementally() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.commitIncremental(); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.commitIncremental(); tx.put("seven", 7); tx.put("eight", 8); tx.put("nine", 9); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly assertEquals(9, tx.keySet().size()); } @Test public void incrementalCommitTransactionCanReadItsOwnModifications() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.commitIncremental(); assertEquals(3, tx.keySet().size()); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.commitIncremental(); assertEquals(6, tx.keySet().size()); tx.put("seven", 7); tx.put("eight", 8); tx.put("nine", 9); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly Set<String> keySet = tx.keySet(); assertEquals(9, keySet.size()); } @Test public void incrementalCommitTransactionCanReadItsOwnModificationsInIndexer() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); try { tx.put("np1", NamedPayload.create1KB("one")); tx.put("np2", NamedPayload.create1KB("two")); tx.put("np3", NamedPayload.create1KB("three")); tx.commitIncremental(); assertEquals(3, tx.keySet().size()); assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("one").getKeysAsSet().size()); assertEquals(2, tx.find().inDefaultKeyspace().where("name").contains("e").getKeysAsSet().size()); tx.put("np4", NamedPayload.create1KB("four")); tx.put("np5", NamedPayload.create1KB("five")); tx.put("np6", NamedPayload.create1KB("six")); tx.commitIncremental(); assertEquals(6, tx.keySet().size()); assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("one").getKeysAsSet().size()); assertEquals(3, tx.find().inDefaultKeyspace().where("name").contains("e").getKeysAsSet().size()); tx.put("np7", NamedPayload.create1KB("seven")); tx.put("np8", NamedPayload.create1KB("eight")); tx.put("np9", NamedPayload.create1KB("nine")); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly Set<String> keySet = tx.keySet(); assertEquals(9, keySet.size()); assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("one").getKeysAsSet().size()); assertEquals(6, tx.find().inDefaultKeyspace().where("name").contains("e").getKeysAsSet().size()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "20") public void incrementalCommitTransactionCanReadItsOwnModificationsInIndexerWithQueryCaching() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); try { tx.put("np1", NamedPayload.create1KB("one")); tx.put("np2", NamedPayload.create1KB("two")); tx.put("np3", NamedPayload.create1KB("three")); tx.commitIncremental(); assertEquals(3, tx.keySet().size()); assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("one").getKeysAsSet().size()); assertEquals(2, tx.find().inDefaultKeyspace().where("name").contains("e").getKeysAsSet().size()); tx.put("np4", NamedPayload.create1KB("four")); tx.put("np5", NamedPayload.create1KB("five")); tx.put("np6", NamedPayload.create1KB("six")); tx.commitIncremental(); assertEquals(6, tx.keySet().size()); assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("one").getKeysAsSet().size()); assertEquals(3, tx.find().inDefaultKeyspace().where("name").contains("e").getKeysAsSet().size()); tx.put("np7", NamedPayload.create1KB("seven")); tx.put("np8", NamedPayload.create1KB("eight")); tx.put("np9", NamedPayload.create1KB("nine")); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly Set<String> keySet = tx.keySet(); log.debug(keySet.toString()); assertEquals(9, keySet.size()); assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("one").getKeysAsSet().size()); Iterator<Entry<QualifiedKey, Object>> qualifiedResult = tx.find().inDefaultKeyspace().where("name") .contains("e").getQualifiedResult(); qualifiedResult.forEachRemaining(entry -> { log.debug(entry.getKey().toString() + " -> " + entry.getValue()); }); assertEquals(6, tx.find().inDefaultKeyspace().where("name").contains("e").getKeysAsSet().size()); } @Test public void cannotCommitOnOtherTransactionWhileIncrementalCommitProcessIsRunning() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.commitIncremental(); assertEquals(3, tx.keySet().size()); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.commitIncremental(); assertEquals(6, tx.keySet().size()); // simulate a second transaction ChronoDBTransaction tx2 = db.tx(); tx2.put("thirteen", 13); try { tx2.commit(); fail("Managed to commit on other transaction while incremental commit is active!"); } catch (ChronoDBCommitException expected) { // pass } // continue with the incremental commit tx.put("seven", 7); tx.put("eight", 8); tx.put("nine", 9); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly Set<String> keySet = tx.keySet(); assertEquals(9, keySet.size()); } @Test // enable all the caching to make sure that changes are not visible via caching @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "20") public void otherTransactionsCannotSeeChangesPerformedByIncrementalCommits() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.commitIncremental(); assertEquals(3, tx.keySet().size()); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.commitIncremental(); assertEquals(6, tx.keySet().size()); // simulate a second transaction ChronoDBTransaction tx2 = db.tx(); assertFalse(tx2.exists("one")); assertFalse(tx2.exists("six")); assertNull(tx2.get("one")); assertNull(tx2.get("six")); assertEquals(0, tx2.keySet().size()); // continue with the incremental commit tx.put("seven", 7); tx.put("eight", 8); tx.put("nine", 9); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly Set<String> keySet = tx.keySet(); assertEquals(9, keySet.size()); } @Test public void incrementalCommitsAppearAsSingleCommitInHistory() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.put("alpha", 100); tx.commitIncremental(); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.put("alpha", 200); tx.commitIncremental(); tx.put("seven", 7); tx.put("eight", 8); tx.put("nine", 9); tx.put("alpha", 300); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly assertEquals(10, tx.keySet().size()); // assert that alpha was written only once in the versioning history Iterator<Long> historyOfAlpha = tx.history("alpha"); assertEquals(1, Iterators.size(historyOfAlpha)); // assert that all keys have the same timestamp Set<Long> timestamps = Sets.newHashSet(); for (String key : tx.keySet()) { Iterator<Long> history = tx.history(key); timestamps.add(Iterators.getOnlyElement(history)); } assertEquals(1, timestamps.size()); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100") public void rollbackDuringIncrementalCommitWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.commitIncremental(); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.commitIncremental(); // simulate user error throw new RuntimeException("User error"); } catch (RuntimeException expected) { } finally { tx.rollback(); } // assert that the data was rolled back correctly assertEquals(0, tx.keySet().size()); } @Test public void canCommitRegularlyAfterCompletedIncrementalCommitProcess() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.commitIncremental(); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.commitIncremental(); tx.put("seven", 7); tx.put("eight", 8); tx.put("nine", 9); tx.commit(); } finally { tx.rollback(); } // assert that the data was written correctly assertEquals(9, tx.keySet().size()); // can commit on a different transaction ChronoDBTransaction tx2 = db.tx(); tx2.put("fourtytwo", 42); tx2.commit(); // can commit on the same transaction tx.put("fourtyseven", 47); tx.commit(); assertEquals(11, tx.keySet().size()); } @Test public void canCommitRegularlyAfterCanceledIncrementalCommitProcess() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); try { tx.put("one", 1); tx.put("two", 2); tx.put("three", 3); tx.commitIncremental(); tx.put("four", 4); tx.put("five", 5); tx.put("six", 6); tx.commitIncremental(); tx.put("seven", 7); tx.put("eight", 8); tx.put("nine", 9); } finally { tx.rollback(); } // assert that the data was written correctly assertEquals(0, tx.keySet().size()); // can commit on a different transaction ChronoDBTransaction tx2 = db.tx(); tx2.put("fourtytwo", 42); tx2.commit(); // can commit on the same transaction tx.put("fourtyseven", 47); tx.commit(); assertEquals(2, tx.keySet().size()); } @Test public void secondaryIndexingIsCorrectDuringIncrementalCommit() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("firstName").withIndexer(new FirstNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("lastName").withIndexer(new LastNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); try { // add three persons tx.put("p1", new Person("John", "Doe")); tx.put("p2", new Person("John", "Smith")); tx.put("p3", new Person("Jane", "Doe")); // perform the incremental commit tx.commitIncremental(); log.debug("After 1st commitIncremental"); // make sure that we can find them assertEquals(2, tx.find().inDefaultKeyspace().where("firstName").isEqualToIgnoreCase("john").count()); assertEquals(2, tx.find().inDefaultKeyspace().where("lastName").isEqualToIgnoreCase("doe").count()); // change Jane's and John's first names tx.put("p3", new Person("Jayne", "Doe")); tx.put("p1", new Person("Jack", "Doe")); // perform the incremental commit tx.commitIncremental(); log.debug("After 2nd commitIncremental"); // make sure that we can't find John any longer assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualToIgnoreCase("john").count()); assertEquals(2, tx.find().inDefaultKeyspace().where("lastName").isEqualToIgnoreCase("doe").count()); // change Jack's first name (yet again) tx.put("p1", new Person("Joe", "Doe")); // perform the incremental commit tx.commitIncremental(); log.debug("After 3rd commitIncremental"); // make sure that we can't find Jack Doe any longer assertEquals(0, tx.find().inDefaultKeyspace().where("firstName").isEqualToIgnoreCase("jack").count()); // john smith should still be there assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualToIgnoreCase("john").count()); // we still have jayne doe and joe doe assertEquals(2, tx.find().inDefaultKeyspace().where("lastName").isEqualToIgnoreCase("doe").count()); // jayne should be in the first name index as well assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualToIgnoreCase("jayne").count()); // delete Joe tx.remove("p1"); // make sure that joe's gone assertEquals(0, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("joe").count()); // do the full commit tx.commit(); log.debug("After full commit"); } finally { tx.rollback(); } log.debug("TX timestamp is: " + tx.getTimestamp()); // in the end, there should be john smith and jayne doe Set<Object> johns = tx.find().inDefaultKeyspace().where("firstName").isEqualToIgnoreCase("john") .getValuesAsSet(); assertEquals(1, johns.size()); Set<Object> does = tx.find().inDefaultKeyspace().where("lastName").isEqualToIgnoreCase("doe").getValuesAsSet(); assertEquals(1, does.size()); } @Test public void renamingElementsInSecondaryIndexDuringIncrementalCommitWorks() { ChronoDB db = this.getChronoDB(); // set up the "name" index StringIndexer nameIndexer = new NamedPayloadNameIndexer(); db.getIndexManager().createIndex().withName("name").withIndexer(nameIndexer).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // generate and insert test data NamedPayload np1 = NamedPayload.create1KB("Hello World"); NamedPayload np2 = NamedPayload.create1KB("Foo Bar"); NamedPayload np3 = NamedPayload.create1KB("Foo Baz"); ChronoDBTransaction tx = db.tx(); tx.put("np1", np1); tx.put("np2", np2); tx.put("np3", np3); tx.commit(); ChronoDBTransaction tx2 = db.tx(); tx2.commitIncremental(); tx2.put("np1", NamedPayload.create1KB("Renamed")); tx2.commitIncremental(); tx2.commit(); // check that we can find the renamed element by its new name assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").isEqualTo("Renamed").count()); // check that we cannot find the renamed element by its old name anymore assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").isEqualTo("Hello World").count()); // in the past, we should still find the non-renamed version assertEquals(1, tx.find().inDefaultKeyspace().where("name").isEqualTo("Hello World").count()); // in the past, we should not find the renamed version assertEquals(0, tx.find().inDefaultKeyspace().where("name").isEqualTo("Renamed").count()); } @Test public void multipleIncrementalCommitsOnExistingDataWork() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("firstName").withIndexer(new FirstNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("lastName").withIndexer(new LastNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("p1", new Person("John", "Doe")); tx.put("p2", new Person("Jane", "Doe")); tx.commit(); try { // rename "John Doe" to "Jack Doe" tx.put("p1", new Person("Jack", "Doe")); tx.commitIncremental(); // assert that the indexer state is correct assertEquals(0, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("John").count()); assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Jack").count()); assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Jane").count()); // rename "Jack Doe" to "Johnny Doe" tx.put("p1", new Person("Johnny", "Doe")); tx.commitIncremental(); assertEquals(0, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("John").count()); assertEquals(0, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Jack").count()); assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Johnny").count()); assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Jane").count()); // perform the final commit tx.commit(); } finally { tx.rollback(); } // assert that the final result is correct assertEquals(0, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("John").count()); assertEquals(0, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Jack").count()); assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Johnny").count()); assertEquals(1, tx.find().inDefaultKeyspace().where("firstName").isEqualTo("Jane").count()); } @Test public void canInsertAndRemoveDuringIncrementalCommit() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { ChronoDBTransaction tx = db.tx(); tx.put("one", NamedPayload.create1KB("Hello World")); tx.commit(); } // make sure that the commit worked assertEquals(Sets.newHashSet("one"), db.tx().keySet()); assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("hello").count()); // perform incremental commits { ChronoDBTransaction tx = db.tx(); tx.commitIncremental(); tx.put("two", NamedPayload.create1KB("Foo")); tx.put("three", NamedPayload.create1KB("Bar")); tx.commitIncremental(); tx.remove("two"); tx.put("four", NamedPayload.create1KB("Baz")); tx.commitIncremental(); tx.put("five", NamedPayload.create1KB("John Doe")); tx.commit(); } // make sure that the state of the database is consistent assertEquals(Sets.newHashSet("one", "three", "four", "five"), db.tx().keySet()); assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("foo").count()); assertEquals(2, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("ba").count()); } @Test public void canUpdateAndRemoveDuringIncrementalCommit() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { ChronoDBTransaction tx = db.tx(); tx.put("one", NamedPayload.create1KB("Hello World")); tx.put("two", NamedPayload.create1KB("Initial State")); tx.commit(); } // make sure that the commit worked assertEquals(Sets.newHashSet("one", "two"), db.tx().keySet()); assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("hello").count()); assertEquals(1, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("initial").count()); // perform incremental commits { ChronoDBTransaction tx = db.tx(); tx.commitIncremental(); tx.put("two", NamedPayload.create1KB("Foo")); tx.put("three", NamedPayload.create1KB("Bar")); tx.commitIncremental(); tx.remove("two"); tx.put("four", NamedPayload.create1KB("Baz")); tx.commitIncremental(); tx.put("five", NamedPayload.create1KB("John Doe")); tx.commit(); } // make sure that the state of the database is consistent assertEquals(Sets.newHashSet("one", "three", "four", "five"), db.tx().keySet()); assertEquals(0, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("foo").count()); assertEquals(2, db.tx().find().inDefaultKeyspace().where("name").containsIgnoreCase("ba").count()); } @Test public void getAndExistsWorkProperlyAfterDeletionDuringIncrementalCommit() { ChronoDB db = this.getChronoDB(); { // add some base data ChronoDBTransaction tx = db.tx(); tx.put("a", "Hello"); tx.put("b", "World"); tx.commit(); } { // do the incremental commit process ChronoDBTransaction tx = db.tx(); assertEquals("Hello", tx.get("a")); assertEquals("World", tx.get("b")); assertTrue(tx.exists("a")); assertTrue(tx.exists("b")); tx.put("c", "Foo"); tx.put("d", "Bar"); tx.commitIncremental(); assertTrue(tx.exists("a")); assertTrue(tx.exists("b")); assertTrue(tx.exists("c")); assertTrue(tx.exists("d")); tx.remove("a"); tx.commitIncremental(); assertNull(tx.get("a")); assertFalse(tx.exists("a")); tx.commit(); } assertNull(db.tx().get("a")); assertFalse(db.tx().exists("a")); } public static class Person { private String firstName; private String lastName; @SuppressWarnings("unused") public Person() { // default constructor for kryo this(null, null); } public Person(final String firstName, final String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } @Override public String toString() { return "Person[" + this.firstName + " " + this.lastName + "]"; } } public static class FirstNameIndexer implements StringIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return object instanceof Person; } @Override public Set<String> getIndexValues(final Object object) { Person person = (Person) object; return Collections.singleton(person.getFirstName()); } } public static class LastNameIndexer implements StringIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override public boolean canIndex(final Object object) { return object instanceof Person; } @Override public Set<String> getIndexValues(final Object object) { Person person = (Person) object; return Collections.singleton(person.getLastName()); } } }
29,254
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBVersionRetrievalTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/ChronoDBVersionRetrievalTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.version.ChronosVersion; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoDBVersionRetrievalTest extends AllChronoDBBackendsTest { @Test public void canRetrieveChronosVersionFromStrorage() { ChronoDB db = this.getChronoDB(); ChronosVersion storedVersion = db.getStoredChronosVersion(); ChronosVersion currentVersion = db.getCurrentChronosVersion(); assertNotNull(storedVersion); assertNotNull(currentVersion); assertTrue(currentVersion.isGreaterThanOrEqualTo(storedVersion)); } }
911
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SecondaryIndexBranchingTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/SecondaryIndexBranchingTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import org.chronos.chronodb.api.Branch; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.cases.util.model.person.FirstNameIndexer; import org.chronos.chronodb.test.cases.util.model.person.LastNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.model.person.Person; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Set; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; @Category(IntegrationTest.class) public class SecondaryIndexBranchingTest extends AllChronoDBBackendsTest { @Test public void canQuerySecondaryIndexOnBranchBeforeBranchingTimestamp() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("firstName").withIndexer(new FirstNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("lastName").withIndexer(new LastNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); long afterFirstCommit; { // first insert ChronoDBTransaction tx = db.tx(); tx.put("john.doe", new Person("John", "Doe")); tx.put("jane.doe", new Person("Jane", "Doe")); afterFirstCommit = tx.commit(); } // create the branch db.getBranchManager().createBranch("my-branch"); // on both master and my-branch, delete john { ChronoDBTransaction tx = db.tx(); tx.remove("john.doe"); tx.commit(); } { ChronoDBTransaction tx = db.tx("my-branch"); tx.remove("john.doe"); tx.commit(); } { // query on the branch for the first commit Set<QualifiedKey> johns = db.tx("my-branch", afterFirstCommit).find().inDefaultKeyspace().where("firstName").isEqualTo("John").getKeysAsSet(); assertThat(johns, contains(QualifiedKey.createInDefaultKeyspace("john.doe"))); } { // reindex and try again db.getIndexManager().reindexAll(true); Set<QualifiedKey> johns = db.tx("my-branch", afterFirstCommit).find().inDefaultKeyspace().where("firstName").isEqualTo("John").getKeysAsSet(); assertThat(johns, contains(QualifiedKey.createInDefaultKeyspace("john.doe"))); } } @Test public void canDeleteBranchWithSecondaryIndex() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("firstName").withIndexer(new FirstNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().createIndex().withName("lastName").withIndexer(new LastNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); { // first insert ChronoDBTransaction tx = db.tx(); tx.put("john.doe", new Person("John", "Doe")); tx.put("jane.doe", new Person("Jane", "Doe")); } // create the branch Branch branch = db.getBranchManager().createBranch("my-branch"); { ChronoDBTransaction tx = db.tx("my-branch"); tx.remove("john.doe"); tx.commit(); } // create a sub branch db.getBranchManager().createBranch("my-branch", "my-sub-branch"); { ChronoDBTransaction tx = db.tx("my-sub-branch"); tx.put("jack.doe", new Person("Jack", "Doe")); tx.commit(); } // re-index all db.getIndexManager().reindexAll(true); // now delete the branch recursively db.getBranchManager().deleteBranchRecursively(branch.getName()); assertThat(db.getBranchManager().existsBranch("my-branch"), is(false)); assertThat(db.getBranchManager().existsBranch("my-sub-branch"), is(false)); } }
4,177
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
RollbackTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/RollbackTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.internal.api.TemporalKeyValueStore; import org.chronos.chronodb.internal.impl.engines.base.AbstractTemporalKeyValueStore; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.utils.NamedPayload; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class RollbackTest extends AllChronoDBBackendsTest { @Test public void rollbackOnPrimaryIndexWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("np1", NamedPayload.create1KB("np1")); tx.put("np2", NamedPayload.create1KB("np2")); tx.commit(); long timeAfterFirstCommit = tx.getTimestamp(); tx.put("np3", NamedPayload.create1KB("np3")); tx.commit(); assertEquals(3, tx.keySet().size()); // perform a rollback TemporalKeyValueStore tkvs = this.getMasterTkvs(db); AbstractTemporalKeyValueStore aTKVS = (AbstractTemporalKeyValueStore) tkvs; aTKVS.performRollbackToTimestamp(timeAfterFirstCommit, Collections.singleton(ChronoDBConstants.DEFAULT_KEYSPACE_NAME), true); // now, let's open a new transaction ChronoDBTransaction tx2 = db.tx(); // assert that we have indeed performed a rollback assertEquals(timeAfterFirstCommit, tx2.getTimestamp()); // assert that the rolled-back data is now gone assertNull(tx2.get("np3")); } @Test public void rollbackOverriddenEntryWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.tx(); tx.put("np1", NamedPayload.create1KB("np1")); tx.put("np2", NamedPayload.create1KB("np2")); tx.commit(); long timeAfterFirstCommit = tx.getTimestamp(); tx.put("np2", NamedPayload.create1KB("newName")); tx.commit(); assertEquals(2, tx.keySet().size()); // perform a rollback TemporalKeyValueStore tkvs = this.getMasterTkvs(db); AbstractTemporalKeyValueStore aTKVS = (AbstractTemporalKeyValueStore) tkvs; aTKVS.performRollbackToTimestamp(timeAfterFirstCommit, Collections.singleton(ChronoDBConstants.DEFAULT_KEYSPACE_NAME), true); // now, let's open a new transaction ChronoDBTransaction tx2 = db.tx(); // assert that we have indeed performed a rollback assertEquals(timeAfterFirstCommit, tx2.getTimestamp()); // assert that the rolled-back data is now gone assertEquals("np2", ((NamedPayload) tx.get("np2")).getName()); } @Test public void rollbackOnSecondaryIndexWorks() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("np1", NamedPayload.create1KB("np1")); tx.put("np2", NamedPayload.create1KB("np2")); tx.commit(); long timeAfterFirstCommit = tx.getTimestamp(); tx.put("np3", NamedPayload.create1KB("np3")); tx.commit(); assertEquals(3, tx.keySet().size()); // perform a rollback TemporalKeyValueStore tkvs = this.getMasterTkvs(db); AbstractTemporalKeyValueStore aTKVS = (AbstractTemporalKeyValueStore) tkvs; aTKVS.performRollbackToTimestamp(timeAfterFirstCommit, Collections.singleton(ChronoDBConstants.DEFAULT_KEYSPACE_NAME), true); // now, let's open a new transaction ChronoDBTransaction tx2 = db.tx(); // assert that we have indeed performed a rollback assertEquals(timeAfterFirstCommit, tx2.getTimestamp()); // assert that the data is gone from the secondary index assertEquals(2, tx2.find().inDefaultKeyspace().where("name").startsWith("np").count()); } }
4,400
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TransactionConfigurationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/TransactionConfigurationTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.api.exceptions.TransactionIsReadOnlyException; import org.chronos.chronodb.internal.impl.engines.base.ThreadSafeChronoDBTransaction; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class TransactionConfigurationTest extends AllChronoDBBackendsTest { @Test public void threadSafeConfigurationCreatesThreadSafeTransaction() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.txBuilder().threadSafe().build(); assertTrue(tx instanceof ThreadSafeChronoDBTransaction); } @Test public void configuringConflictResolutionWorks() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.txBuilder().withConflictResolutionStrategy(ConflictResolutionStrategy.DO_NOT_MERGE) .build(); assertThat(tx.getConfiguration().getConflictResolutionStrategy(), is(ConflictResolutionStrategy.DO_NOT_MERGE)); ChronoDBTransaction tx2 = db.txBuilder() .withConflictResolutionStrategy(ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE).build(); assertThat(tx2.getConfiguration().getConflictResolutionStrategy(), is(ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE)); } @Test public void cantWriteInReadOnlyTransaction() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx = db.txBuilder().readOnly().build(); try { tx.put("a", 123); fail(); } catch (TransactionIsReadOnlyException expected) { } try { tx.remove("a"); fail(); } catch (TransactionIsReadOnlyException expected) { } } @Test public void branchConfigurationWorks() { ChronoDB db = this.getChronoDB(); db.getBranchManager().createBranch("MyBranch"); ChronoDBTransaction tx = db.txBuilder().onBranch("MyBranch").build(); assertEquals("MyBranch", tx.getBranchName()); } @Test public void transactionsRunOnMasterBranchByDefault() { ChronoDB db = this.getChronoDB(); db.getBranchManager().createBranch("MyBranch"); ChronoDBTransaction tx = db.txBuilder().build(); assertEquals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, tx.getBranchName()); } }
2,867
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PutOptionsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/PutOptionsTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.PutOption; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.utils.NamedPayload; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.junit.Test; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import static org.junit.Assert.*; public class PutOptionsTest extends AllChronoDBBackendsTest { @Test public void noIndexOptionWorks() { ChronoDB db = this.getChronoDB(); // create an indexer db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // assert that the index is empty // NOTE: This will also force lazy-initializing indexing backends to // produce an index. Set<QualifiedKey> keysAsSet = db.tx().find().inDefaultKeyspace().where("name").matchesRegex(".*").getKeysAsSet(); assertTrue(keysAsSet.isEmpty()); // add some data, with and without NO_INDEX option ChronoDBTransaction tx = db.tx(); tx.put("one", NamedPayload.create1KB("one")); tx.put("two", NamedPayload.create1KB("two")); tx.put("three", NamedPayload.create1KB("three"), PutOption.NO_INDEX); tx.put("four", NamedPayload.create1KB("four"), PutOption.NO_INDEX); // commit the changes tx.commit(); // a query on our secondary indexer should only reveal "one" and "two", but not "three" and "four" Set<QualifiedKey> keys = tx.find().inDefaultKeyspace().where("name").matchesRegex(".*").getKeysAsSet(); Set<String> keySet = keys.stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(2, keySet.size()); assertTrue(keySet.contains("one")); assertTrue(keySet.contains("two")); // make sure that our objects still exist outside the secondary indexer assertTrue(tx.exists("three")); assertTrue(tx.exists("four")); assertEquals("three", ((NamedPayload) tx.get("three")).getName()); assertEquals("four", ((NamedPayload) tx.get("four")).getName()); } }
2,506
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CommitMetadataFilterTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/engine/transaction/CommitMetadataFilterTest.java
package org.chronos.chronodb.test.cases.engine.transaction; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.CommitMetadataFilter; import org.chronos.chronodb.api.exceptions.ChronoDBCommitMetadataRejectedException; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.junit.Test; import static org.junit.Assert.*; public class CommitMetadataFilterTest extends AllChronoDBBackendsTest { @Test @InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_METADATA_FILTER_CLASS, value = "org.chronos.chronodb.test.cases.engine.transaction.CommitMetadataFilterTest$MyTestFilter") public void canAttachCommitMetadataFilter() { ChronoDB db = this.getChronoDB(); try { ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); // commit without argument commits a NULL metadata object tx.commit(); fail("Failed to commit NULL metadata object through filter that does not permit NULL values!"); } catch (ChronoDBCommitMetadataRejectedException expected) { // pass } ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); // this should work (because the metadata is not null) tx.commit("I did this!"); } private static class MyTestFilter implements CommitMetadataFilter { public MyTestFilter() { // default constructor for instantiation } @Override public boolean doesAccept(final String branch, final long timestamp, final Object metadata) { // do not permit NULL values return metadata != null; } } }
1,873
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UnqualifiedTemporalKeyTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/temporal/UnqualifiedTemporalKeyTest.java
package org.chronos.chronodb.test.cases.temporal; import com.google.common.collect.Lists; import org.chronos.chronodb.internal.impl.temporal.UnqualifiedTemporalKey; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.*; @Category(UnitTest.class) public class UnqualifiedTemporalKeyTest extends ChronoDBUnitTest { @Test public void testSerializationFormatOrdering() { UnqualifiedTemporalKey k1 = new UnqualifiedTemporalKey("a", 1); UnqualifiedTemporalKey k2 = new UnqualifiedTemporalKey("a", 10); UnqualifiedTemporalKey k3 = new UnqualifiedTemporalKey("aa", 1); UnqualifiedTemporalKey k4 = new UnqualifiedTemporalKey("aaa", 100); UnqualifiedTemporalKey k5 = new UnqualifiedTemporalKey("ab", 1); UnqualifiedTemporalKey k6 = new UnqualifiedTemporalKey("ab", 10); UnqualifiedTemporalKey k7 = new UnqualifiedTemporalKey("b", 1); UnqualifiedTemporalKey k8 = new UnqualifiedTemporalKey("b", 10); List<UnqualifiedTemporalKey> keyList = Lists.newArrayList(k1, k2, k3, k4, k5, k6, k7, k8); List<String> stringList = keyList.stream().map(key -> key.toSerializableFormat()).collect(Collectors.toList()); Collections.sort(keyList); Collections.sort(stringList); System.out.println("Key List:"); for (UnqualifiedTemporalKey key : keyList) { System.out.println("\t" + key.toSerializableFormat()); } System.out.println("String List:"); for (String key : stringList) { System.out.println("\t" + key); } for (int i = 0; i < keyList.size(); i++) { UnqualifiedTemporalKey key = keyList.get(i); String string = stringList.get(i); assertEquals(key.toSerializableFormat(), string); } } @Test public void testParseFromString() { UnqualifiedTemporalKey k1 = new UnqualifiedTemporalKey("a", 1); UnqualifiedTemporalKey k2 = new UnqualifiedTemporalKey("a", 10); UnqualifiedTemporalKey k3 = new UnqualifiedTemporalKey("aa", 1); UnqualifiedTemporalKey k4 = new UnqualifiedTemporalKey("aaa", 100); UnqualifiedTemporalKey k5 = new UnqualifiedTemporalKey("ab", 1); UnqualifiedTemporalKey k6 = new UnqualifiedTemporalKey("ab", 10); UnqualifiedTemporalKey k7 = new UnqualifiedTemporalKey("b", 1); UnqualifiedTemporalKey k8 = new UnqualifiedTemporalKey("b", 10); List<UnqualifiedTemporalKey> keyList = Lists.newArrayList(k1, k2, k3, k4, k5, k6, k7, k8); List<String> stringList = keyList.stream().map(key -> key.toSerializableFormat()).collect(Collectors.toList()); for (int i = 0; i < keyList.size(); i++) { UnqualifiedTemporalKey key = keyList.get(i); String string = stringList.get(i); assertEquals(key, UnqualifiedTemporalKey.parseSerializableFormat(string)); } } @Test public void testSerializationFormatOrdering2() { // This test case originates from a real-world use case where a bug occurred. // That's why the keys and timestamps look so "arbitrary". UnqualifiedTemporalKey k1 = new UnqualifiedTemporalKey("91fa39f4-6bc9-404f-9c90-868c3dcadf7b", 1094050925208L); UnqualifiedTemporalKey k2 = new UnqualifiedTemporalKey("91fa39f4-6bc9-404f-9c90-868c3dcadf7b", 1030144820210L); UnqualifiedTemporalKey k3 = new UnqualifiedTemporalKey("91fa39f4-6bc9-404f-9c90-868c3dcadf7b", 947698459624L); assertTrue(k1.compareTo(k1) == 0); assertTrue(k1.compareTo(k2) > 0); assertTrue(k1.compareTo(k3) > 0); assertTrue(k2.compareTo(k2) == 0); assertTrue(k2.compareTo(k1) < 0); assertTrue(k2.compareTo(k3) > 0); assertTrue(k3.compareTo(k3) == 0); assertTrue(k3.compareTo(k1) < 0); assertTrue(k3.compareTo(k2) < 0); String k1String = k1.toSerializableFormat(); String k2String = k2.toSerializableFormat(); String k3String = k3.toSerializableFormat(); assertTrue(k1String.compareTo(k1String) == 0); assertTrue(k1String.compareTo(k2String) > 0); assertTrue(k1String.compareTo(k3String) > 0); assertTrue(k2String.compareTo(k2String) == 0); assertTrue(k2String.compareTo(k1String) < 0); assertTrue(k2String.compareTo(k3String) > 0); assertTrue(k3String.compareTo(k3String) == 0); assertTrue(k3String.compareTo(k1String) < 0); assertTrue(k3String.compareTo(k2String) < 0); } @Test public void testSerializationFormatOrdering3() { UnqualifiedTemporalKey k1 = new UnqualifiedTemporalKey("a", 109L); UnqualifiedTemporalKey k2 = new UnqualifiedTemporalKey("a", 103L); UnqualifiedTemporalKey k3 = new UnqualifiedTemporalKey("a", 94L); assertEquals(0, k1.compareTo(k1)); assertTrue(k1.compareTo(k2) > 0); assertTrue(k1.compareTo(k3) > 0); assertEquals(0, k2.compareTo(k2)); assertTrue(k2.compareTo(k1) < 0); assertTrue(k2.compareTo(k3) > 0); assertEquals(0, k3.compareTo(k3)); assertTrue(k3.compareTo(k1) < 0); assertTrue(k3.compareTo(k2) < 0); String k1String = k1.toSerializableFormat(); String k2String = k2.toSerializableFormat(); String k3String = k3.toSerializableFormat(); assertEquals(0, k1String.compareTo(k1String)); assertTrue(k1String.compareTo(k2String) > 0); assertTrue(k1String.compareTo(k3String) > 0); assertEquals(0, k2String.compareTo(k2String)); assertTrue(k2String.compareTo(k1String) < 0); assertTrue(k2String.compareTo(k3String) > 0); assertEquals(0, k3String.compareTo(k3String)); assertTrue(k3String.compareTo(k1String) < 0); assertTrue(k3String.compareTo(k2String) < 0); } }
6,122
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TemporalKeyTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/temporal/TemporalKeyTest.java
package org.chronos.chronodb.test.cases.temporal; import com.google.common.collect.Sets; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Set; import static org.junit.Assert.*; @Category(UnitTest.class) public class TemporalKeyTest extends ChronoDBUnitTest { @Test public void canCreateQualifiedKey() { QualifiedKey qKey = QualifiedKey.create("myKeyspace", "hello"); assertNotNull(qKey); assertEquals("hello", qKey.getKey()); assertEquals("myKeyspace", qKey.getKeyspace()); } @Test public void canCreateQualifiedKeyInDefaultKeyspace() { QualifiedKey qKey = QualifiedKey.createInDefaultKeyspace("hello"); assertNotNull(qKey); assertEquals("hello", qKey.getKey()); assertEquals(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, qKey.getKeyspace()); } @Test public void qualifiedKeyImplementsHashCodeAndEqualsCorrectly() { Set<QualifiedKey> set = Sets.newHashSet(); // uniques set.add(QualifiedKey.create("a", "1")); set.add(QualifiedKey.create("a", "2")); set.add(QualifiedKey.create("b", "1")); set.add(QualifiedKey.create("b", "2")); // duplicates set.add(QualifiedKey.create("a", "1")); set.add(QualifiedKey.create("b", "1")); assertEquals(4, set.size()); // containment checks assertTrue(set.contains(QualifiedKey.create("a", "1"))); assertTrue(set.contains(QualifiedKey.create("a", "2"))); assertTrue(set.contains(QualifiedKey.create("b", "1"))); assertTrue(set.contains(QualifiedKey.create("b", "2"))); } @Test public void canCreateTemporalKey() { TemporalKey tKey = TemporalKey.create(1000L, "myKeyspace", "hello"); assertNotNull(tKey); assertEquals(1000L, tKey.getTimestamp()); assertEquals("myKeyspace", tKey.getKeyspace()); assertEquals("hello", tKey.getKey()); } @Test public void canCreateTemporalKeyFromQualifiedKey() { QualifiedKey qKey = QualifiedKey.create("myKeyspace", "hello"); assertNotNull(qKey); TemporalKey tKey = TemporalKey.create(1000L, qKey); assertNotNull(tKey); assertEquals(1000L, tKey.getTimestamp()); assertEquals("myKeyspace", tKey.getKeyspace()); assertEquals("hello", tKey.getKey()); } @Test public void canCreateTemporalKeyAtMinimumTimestamp() { TemporalKey tKey = TemporalKey.createMinTime("myKeyspace", "hello"); assertNotNull(tKey); assertEquals(0L, tKey.getTimestamp()); assertEquals("myKeyspace", tKey.getKeyspace()); assertEquals("hello", tKey.getKey()); } @Test public void canCreateTemporalKeyAtMaximumTimestamp() { TemporalKey tKey = TemporalKey.createMaxTime("myKeyspace", "hello"); assertNotNull(tKey); assertEquals(Long.MAX_VALUE, tKey.getTimestamp()); assertEquals("myKeyspace", tKey.getKeyspace()); assertEquals("hello", tKey.getKey()); } @Test public void canConvertTemporalKeyIntoQualifiedKey() { TemporalKey tKey = TemporalKey.create(1000L, "myKeyspace", "hello"); assertNotNull(tKey); QualifiedKey qKey = tKey.toQualifiedKey(); assertNotNull(qKey); assertEquals("myKeyspace", qKey.getKeyspace()); assertEquals("hello", qKey.getKey()); } @Test public void temporalKeyImplementsHashCodeAndEqualsCorrectly() { Set<TemporalKey> set = Sets.newHashSet(); // uniques set.add(TemporalKey.create(10L, "a", "1")); set.add(TemporalKey.create(10L, "a", "2")); set.add(TemporalKey.create(10L, "b", "1")); set.add(TemporalKey.create(10L, "b", "2")); set.add(TemporalKey.create(100L, "a", "1")); set.add(TemporalKey.create(100L, "a", "2")); set.add(TemporalKey.create(100L, "b", "1")); set.add(TemporalKey.create(100L, "b", "2")); // duplicates set.add(TemporalKey.create(10L, "a", "1")); set.add(TemporalKey.create(10L, "a", "2")); set.add(TemporalKey.create(10L, "b", "1")); set.add(TemporalKey.create(10L, "b", "2")); set.add(TemporalKey.create(100L, "a", "1")); set.add(TemporalKey.create(100L, "a", "2")); set.add(TemporalKey.create(100L, "b", "1")); set.add(TemporalKey.create(100L, "b", "2")); assertEquals(8, set.size()); // containment checks assertTrue(set.contains(TemporalKey.create(10L, "a", "1"))); assertTrue(set.contains(TemporalKey.create(10L, "b", "1"))); assertTrue(set.contains(TemporalKey.create(10L, "a", "2"))); assertTrue(set.contains(TemporalKey.create(10L, "b", "2"))); assertTrue(set.contains(TemporalKey.create(100L, "a", "1"))); assertTrue(set.contains(TemporalKey.create(100L, "b", "1"))); assertTrue(set.contains(TemporalKey.create(100L, "a", "2"))); assertTrue(set.contains(TemporalKey.create(100L, "b", "2"))); } @Test public void canCreateChronoIdentifier() { ChronoIdentifier id = ChronoIdentifier.create("myBranch", 1000L, "myKeyspace", "hello"); assertNotNull(id); assertEquals("myBranch", id.getBranchName()); assertEquals(1000L, id.getTimestamp()); assertEquals("myKeyspace", id.getKeyspace()); assertEquals("hello", id.getKey()); } @Test public void canCreateChronoIdentifierFromTemporalKey() { TemporalKey tKey = TemporalKey.create(1000L, "myKeyspace", "hello"); assertNotNull(tKey); ChronoIdentifier id = ChronoIdentifier.create("myBranch", tKey); assertEquals("myBranch", id.getBranchName()); assertEquals(1000L, id.getTimestamp()); assertEquals("myKeyspace", id.getKeyspace()); assertEquals("hello", id.getKey()); } @Test public void canCreateChronoIdentifierFromQualifiedKey() { QualifiedKey qKey = QualifiedKey.create("myKeyspace", "hello"); assertNotNull(qKey); ChronoIdentifier id = ChronoIdentifier.create("myBranch", 1000L, qKey); assertEquals("myBranch", id.getBranchName()); assertEquals(1000L, id.getTimestamp()); assertEquals("myKeyspace", id.getKeyspace()); assertEquals("hello", id.getKey()); } @Test public void canConvertChronoIdentifierToTemporalKey() { ChronoIdentifier id = ChronoIdentifier.create("myBranch", 1000L, "myKeyspace", "hello"); assertNotNull(id); TemporalKey tKey = id.toTemporalKey(); assertEquals(1000L, tKey.getTimestamp()); assertEquals("myKeyspace", tKey.getKeyspace()); assertEquals("hello", tKey.getKey()); } @Test public void canConvertChronoIdentifierToQualifiedKey() { ChronoIdentifier id = ChronoIdentifier.create("myBranch", 1000L, "myKeyspace", "hello"); assertNotNull(id); QualifiedKey tKey = id.toQualifiedKey(); assertEquals("myKeyspace", tKey.getKeyspace()); assertEquals("hello", tKey.getKey()); } @Test public void chronoIdentifierImplementsHashCodeAndEqualsCorrectly() { Set<ChronoIdentifier> set = Sets.newHashSet(); // uniques set.add(ChronoIdentifier.create("master", 10L, "a", "1")); set.add(ChronoIdentifier.create("master", 10L, "a", "2")); set.add(ChronoIdentifier.create("master", 10L, "b", "1")); set.add(ChronoIdentifier.create("master", 10L, "b", "2")); set.add(ChronoIdentifier.create("master", 100L, "a", "1")); set.add(ChronoIdentifier.create("master", 100L, "a", "2")); set.add(ChronoIdentifier.create("master", 100L, "b", "1")); set.add(ChronoIdentifier.create("master", 100L, "b", "2")); set.add(ChronoIdentifier.create("myBranch", 10L, "a", "1")); set.add(ChronoIdentifier.create("myBranch", 10L, "a", "2")); set.add(ChronoIdentifier.create("myBranch", 10L, "b", "1")); set.add(ChronoIdentifier.create("myBranch", 10L, "b", "2")); set.add(ChronoIdentifier.create("myBranch", 100L, "a", "1")); set.add(ChronoIdentifier.create("myBranch", 100L, "a", "2")); set.add(ChronoIdentifier.create("myBranch", 100L, "b", "1")); set.add(ChronoIdentifier.create("myBranch", 100L, "b", "2")); // duplicates set.add(ChronoIdentifier.create("master", 10L, "a", "1")); set.add(ChronoIdentifier.create("master", 10L, "a", "2")); set.add(ChronoIdentifier.create("master", 10L, "b", "1")); set.add(ChronoIdentifier.create("master", 10L, "b", "2")); set.add(ChronoIdentifier.create("master", 100L, "a", "1")); set.add(ChronoIdentifier.create("master", 100L, "a", "2")); set.add(ChronoIdentifier.create("master", 100L, "b", "1")); set.add(ChronoIdentifier.create("master", 100L, "b", "2")); set.add(ChronoIdentifier.create("myBranch", 10L, "a", "1")); set.add(ChronoIdentifier.create("myBranch", 10L, "a", "2")); set.add(ChronoIdentifier.create("myBranch", 10L, "b", "1")); set.add(ChronoIdentifier.create("myBranch", 10L, "b", "2")); set.add(ChronoIdentifier.create("myBranch", 100L, "a", "1")); set.add(ChronoIdentifier.create("myBranch", 100L, "a", "2")); set.add(ChronoIdentifier.create("myBranch", 100L, "b", "1")); set.add(ChronoIdentifier.create("myBranch", 100L, "b", "2")); assertEquals(16, set.size()); // containment checks assertTrue(set.contains(ChronoIdentifier.create("master", 10L, "a", "1"))); assertTrue(set.contains(ChronoIdentifier.create("master", 10L, "a", "2"))); assertTrue(set.contains(ChronoIdentifier.create("master", 10L, "b", "1"))); assertTrue(set.contains(ChronoIdentifier.create("master", 10L, "b", "2"))); assertTrue(set.contains(ChronoIdentifier.create("master", 100L, "a", "1"))); assertTrue(set.contains(ChronoIdentifier.create("master", 100L, "a", "2"))); assertTrue(set.contains(ChronoIdentifier.create("master", 100L, "b", "1"))); assertTrue(set.contains(ChronoIdentifier.create("master", 100L, "b", "2"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 10L, "a", "1"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 10L, "a", "2"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 10L, "b", "1"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 10L, "b", "2"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 100L, "a", "1"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 100L, "a", "2"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 100L, "b", "1"))); assertTrue(set.contains(ChronoIdentifier.create("myBranch", 100L, "b", "2"))); } }
11,268
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
InverseUnqualifiedTemporalKeyTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/temporal/InverseUnqualifiedTemporalKeyTest.java
package org.chronos.chronodb.test.cases.temporal; import com.google.common.collect.Lists; import org.chronos.chronodb.internal.impl.temporal.InverseUnqualifiedTemporalKey; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.*; @Category(UnitTest.class) public class InverseUnqualifiedTemporalKeyTest extends ChronoDBUnitTest { @Test public void serializationFormatOrderingWorks() { InverseUnqualifiedTemporalKey k1 = new InverseUnqualifiedTemporalKey(1, "a"); InverseUnqualifiedTemporalKey k2 = new InverseUnqualifiedTemporalKey(10, "a"); InverseUnqualifiedTemporalKey k3 = new InverseUnqualifiedTemporalKey(1, "aa"); InverseUnqualifiedTemporalKey k4 = new InverseUnqualifiedTemporalKey(100, "aaa"); InverseUnqualifiedTemporalKey k5 = new InverseUnqualifiedTemporalKey(1, "ab"); InverseUnqualifiedTemporalKey k6 = new InverseUnqualifiedTemporalKey(10, "ab"); InverseUnqualifiedTemporalKey k7 = new InverseUnqualifiedTemporalKey(1, "b"); InverseUnqualifiedTemporalKey k8 = new InverseUnqualifiedTemporalKey(10, "b"); List<InverseUnqualifiedTemporalKey> keyList = Lists.newArrayList(k1, k2, k3, k4, k5, k6, k7, k8); List<String> stringList = keyList.stream().map(key -> key.toSerializableFormat()).collect(Collectors.toList()); Collections.sort(keyList); Collections.sort(stringList); System.out.println("Key List:"); for (InverseUnqualifiedTemporalKey key : keyList) { System.out.println("\t" + key.toSerializableFormat()); } System.out.println("String List:"); for (String key : stringList) { System.out.println("\t" + key); } for (int i = 0; i < keyList.size(); i++) { InverseUnqualifiedTemporalKey key = keyList.get(i); String string = stringList.get(i); assertEquals(key.toSerializableFormat(), string); } } @Test public void parseFromStringWorks() { InverseUnqualifiedTemporalKey k1 = new InverseUnqualifiedTemporalKey(1, "a"); InverseUnqualifiedTemporalKey k2 = new InverseUnqualifiedTemporalKey(10, "a"); InverseUnqualifiedTemporalKey k3 = new InverseUnqualifiedTemporalKey(1, "aa"); InverseUnqualifiedTemporalKey k4 = new InverseUnqualifiedTemporalKey(100, "aaa"); InverseUnqualifiedTemporalKey k5 = new InverseUnqualifiedTemporalKey(1, "ab"); InverseUnqualifiedTemporalKey k6 = new InverseUnqualifiedTemporalKey(10, "ab"); InverseUnqualifiedTemporalKey k7 = new InverseUnqualifiedTemporalKey(1, "b"); InverseUnqualifiedTemporalKey k8 = new InverseUnqualifiedTemporalKey(10, "b"); List<InverseUnqualifiedTemporalKey> keyList = Lists.newArrayList(k1, k2, k3, k4, k5, k6, k7, k8); List<String> stringList = keyList.stream().map(key -> key.toSerializableFormat()).collect(Collectors.toList()); for (int i = 0; i < keyList.size(); i++) { InverseUnqualifiedTemporalKey key = keyList.get(i); String string = stringList.get(i); assertEquals(key, InverseUnqualifiedTemporalKey.parseSerializableFormat(string)); } } @Test public void emptyKeyIsSmallestInOrder() { InverseUnqualifiedTemporalKey k0 = InverseUnqualifiedTemporalKey.createMinInclusive(100); InverseUnqualifiedTemporalKey k1 = InverseUnqualifiedTemporalKey.create(100, "a"); InverseUnqualifiedTemporalKey k2 = InverseUnqualifiedTemporalKey.create(100, "0"); InverseUnqualifiedTemporalKey k3 = InverseUnqualifiedTemporalKey.create(100, "_"); assertTrue(k0.compareTo(k1) < 0); assertTrue(k0.compareTo(k2) < 0); assertTrue(k0.compareTo(k3) < 0); } }
4,017
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PeriodTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/temporal/PeriodTest.java
package org.chronos.chronodb.test.cases.temporal; import com.google.common.collect.Lists; import org.chronos.chronodb.internal.api.Period; import org.chronos.common.test.ChronosUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.List; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(UnitTest.class) public class PeriodTest extends ChronosUnitTest { @Test public void createRangePeriodWorks() { Period range = Period.createRange(0, 100); assertNotNull(range); assertEquals(0, range.getLowerBound()); assertEquals(100, range.getUpperBound()); assertFalse(range.isEmpty()); } @Test public void createOpenEndedRangeWorks() { Period range = Period.createOpenEndedRange(100); assertNotNull(range); assertEquals(100, range.getLowerBound()); assertEquals(Long.MAX_VALUE, range.getUpperBound()); assertFalse(range.isEmpty()); } @Test public void createPointPeriodWorks() { Period point = Period.createPoint(100); assertNotNull(point); assertEquals(100, point.getLowerBound()); assertEquals(101, point.getUpperBound()); assertFalse(point.isEmpty()); } @Test public void createEmptyPeriodWorks() { Period empty = Period.empty(); assertNotNull(empty); assertTrue(empty.isEmpty()); } @Test public void createEternalPeriodWorks() { Period eternal = Period.eternal(); assertNotNull(eternal); assertEquals(0, eternal.getLowerBound()); assertEquals(Long.MAX_VALUE, eternal.getUpperBound()); } @Test public void emptyPeriodIsSingleton() { Period empty1 = Period.empty(); Period empty2 = Period.empty(); assertNotNull(empty1); assertNotNull(empty2); assertTrue(empty1 == empty2); } @Test public void eternalPeriodIsSingleton() { Period eternal1 = Period.eternal(); Period eternal2 = Period.eternal(); assertNotNull(eternal1); assertNotNull(eternal2); assertTrue(eternal1 == eternal2); } @Test public void containsTimestampWorks() { Period p = Period.createRange(10, 100); assertFalse(p.contains(0)); assertFalse(p.contains(9)); assertTrue(p.contains(10)); assertTrue(p.contains(50)); assertTrue(p.contains(99)); assertFalse(p.contains(100)); assertFalse(p.contains(101)); } @Test public void lowerBoundIsInclusive() { Period p = Period.createRange(10, 100); assertFalse(p.contains(9)); assertTrue(p.contains(10)); assertTrue(p.contains(11)); } @Test public void upperBoundIsExclusive() { Period p = Period.createRange(10, 100); assertTrue(p.contains(99)); assertFalse(p.contains(100)); assertFalse(p.contains(101)); } @Test public void orderingWorks() { Period p1 = Period.createRange(1, 5); Period p2 = Period.createRange(5, 7); Period p3 = Period.createPoint(7); List<Period> list = Lists.newArrayList(p3, p1, p2); Collections.sort(list); assertEquals(p1, list.get(0)); assertEquals(p2, list.get(1)); assertEquals(p3, list.get(2)); } @Test public void hashCodeAndEqualsAreConsistent() { Period p1to5 = Period.createRange(1, 5); Period p2to5 = Period.createRange(2, 5); Period p1to6 = Period.createRange(1, 6); assertNotEquals(p1to5, p1to6); assertNotEquals(p1to5, p2to5); Period anotherP1to5 = Period.createRange(1, 5); assertEquals(p1to5, anotherP1to5); assertEquals(p1to5.hashCode(), anotherP1to5.hashCode()); } @Test public void overlapsWorks() { Period p5to10 = Period.createRange(5, 10); Period p1to5 = Period.createRange(1, 5); Period p1to6 = Period.createRange(1, 6); Period p1to11 = Period.createRange(1, 11); Period p7to11 = Period.createRange(7, 11); Period p10to20 = Period.createRange(10, 20); // there is always an overlap with the period itself assertTrue(p5to10.overlaps(p5to10)); // never overlap with empty assertFalse(p5to10.overlaps(Period.empty())); assertFalse(Period.empty().contains(p5to10)); assertFalse(Period.empty().contains(Period.empty())); assertFalse(p1to5.overlaps(p5to10)); assertFalse(p5to10.overlaps(p1to5)); assertTrue(p1to6.overlaps(p5to10)); assertTrue(p5to10.overlaps(p1to6)); assertTrue(p1to11.overlaps(p5to10)); assertTrue(p5to10.overlaps(p1to11)); assertTrue(p7to11.overlaps(p5to10)); assertTrue(p5to10.overlaps(p7to11)); assertFalse(p10to20.overlaps(p5to10)); assertFalse(p5to10.overlaps(p10to20)); } @Test public void containsPeriodWorks() { Period p5to10 = Period.createRange(5, 10); Period p5to9 = Period.createRange(5, 9); Period p6to10 = Period.createRange(6, 10); Period p6to9 = Period.createRange(6, 9); Period p5to11 = Period.createRange(5, 11); Period p4to10 = Period.createRange(4, 10); // a period always contains itself assertTrue(p5to10.contains(p5to10)); // never contain the empty period assertFalse(p5to10.contains(Period.empty())); assertFalse(Period.empty().contains(p5to10)); assertFalse(Period.empty().contains(Period.empty())); assertTrue(p5to10.contains(p5to9)); assertFalse(p5to9.contains(p5to10)); assertTrue(p5to10.contains(p6to10)); assertFalse(p6to10.contains(p5to10)); assertTrue(p5to10.contains(p6to9)); assertFalse(p6to9.contains(p5to10)); assertFalse(p5to10.contains(p5to11)); assertTrue(p5to11.contains(p5to10)); assertFalse(p5to10.contains(p4to10)); assertTrue(p4to10.contains(p5to10)); } @Test public void isAdjacentToWorks() { Period p5to10 = Period.createRange(5, 10); Period p1to5 = Period.createRange(1, 5); Period p10to20 = Period.createRange(10, 20); Period p1to4 = Period.createRange(1, 4); Period p11to20 = Period.createRange(11, 20); Period p1to6 = Period.createRange(1, 6); Period p9to20 = Period.createRange(9, 20); // a period is never adjacent to itself assertFalse(p5to10.isAdjacentTo(p5to10)); // a period is never adjacent to an empty period assertFalse(p5to10.isAdjacentTo(Period.empty())); assertFalse(Period.empty().isAdjacentTo(p5to10)); assertFalse(Period.empty().isAdjacentTo(Period.empty())); assertTrue(p5to10.isAdjacentTo(p1to5)); assertTrue(p1to5.isAdjacentTo(p5to10)); assertTrue(p5to10.isAdjacentTo(p10to20)); assertTrue(p10to20.isAdjacentTo(p5to10)); assertFalse(p5to10.isAdjacentTo(p1to4)); assertFalse(p1to4.isAdjacentTo(p5to10)); assertFalse(p5to10.isAdjacentTo(p11to20)); assertFalse(p11to20.isAdjacentTo(p1to5)); assertFalse(p5to10.isAdjacentTo(p1to6)); assertFalse(p1to6.isAdjacentTo(p5to10)); assertFalse(p5to10.isAdjacentTo(p9to20)); assertFalse(p9to20.isAdjacentTo(p5to10)); } @Test public void isBeforeWorks() { Period p5to10 = Period.createRange(5, 10); Period p1to5 = Period.createRange(1, 5); Period p1to11 = Period.createRange(1, 11); // a period is never before itself assertFalse(p5to10.isBefore(p5to10)); // a period is never before an empty period assertFalse(p5to10.isBefore(Period.empty())); assertFalse(Period.empty().isBefore(p5to10)); assertFalse(Period.empty().isBefore(Period.empty())); assertTrue(p1to5.isBefore(p5to10)); assertFalse(p5to10.isBefore(p1to5)); assertTrue(p1to11.isBefore(p5to10)); assertFalse(p5to10.isBefore(p1to11)); assertFalse(p5to10.isBefore(9)); assertTrue(p5to10.isBefore(10)); assertTrue(p5to10.isBefore(11)); } @Test public void isAfterWorks() { Period p5to10 = Period.createRange(5, 10); Period p1to5 = Period.createRange(1, 5); Period p1to11 = Period.createRange(1, 11); // a period is never after itself assertFalse(p5to10.isAfter(p5to10)); // a period is never after an empty period assertFalse(p5to10.isAfter(Period.empty())); assertFalse(Period.empty().isAfter(p5to10)); assertFalse(Period.empty().isAfter(Period.empty())); assertFalse(p1to5.isAfter(p5to10)); assertTrue(p5to10.isAfter(p1to5)); assertFalse(p1to11.isAfter(p5to10)); assertTrue(p5to10.isAfter(p1to11)); assertTrue(p5to10.isAfter(3)); assertTrue(p5to10.isAfter(4)); assertFalse(p5to10.isAfter(5)); assertFalse(p5to10.isAfter(9)); assertFalse(p5to10.isAfter(10)); assertFalse(p5to10.isAfter(11)); } @Test public void isStrictlyBeforeWorks() { Period p5to10 = Period.createRange(5, 10); Period p1to5 = Period.createRange(1, 5); Period p1to11 = Period.createRange(1, 11); // a period is never strictly before itself assertFalse(p5to10.isStrictlyBefore(p5to10)); // a period is never strictly before an empty period assertFalse(p5to10.isStrictlyBefore(Period.empty())); assertFalse(Period.empty().isStrictlyBefore(p5to10)); assertFalse(Period.empty().isStrictlyBefore(Period.empty())); assertTrue(p1to5.isStrictlyBefore(p5to10)); assertFalse(p5to10.isStrictlyBefore(p1to5)); assertFalse(p1to11.isStrictlyBefore(p5to10)); assertFalse(p5to10.isStrictlyBefore(p1to11)); } @Test public void isStrictlyAfterWorks() { Period p5to10 = Period.createRange(5, 10); Period p1to5 = Period.createRange(1, 5); Period p1to11 = Period.createRange(1, 11); // a period is never strictly after itself assertFalse(p5to10.isStrictlyAfter(p5to10)); // a period is never strictly after an empty period assertFalse(p5to10.isStrictlyAfter(Period.empty())); assertFalse(Period.empty().isStrictlyAfter(p5to10)); assertFalse(Period.empty().isStrictlyAfter(Period.empty())); assertFalse(p1to5.isStrictlyAfter(p5to10)); assertTrue(p5to10.isStrictlyAfter(p1to5)); assertFalse(p1to11.isStrictlyAfter(p5to10)); assertFalse(p5to10.isStrictlyAfter(p1to11)); } @Test public void lengthWorks() { Period p1 = Period.createPoint(1); Period p1to5 = Period.createRange(1, 5); assertEquals(0, Period.empty().length()); assertEquals(1, p1.length()); assertEquals(4, p1to5.length()); } @Test public void isOpenEndedWorks() { Period p1 = Period.createOpenEndedRange(100); Period p2 = Period.createPoint(100); Period p3 = Period.createRange(10, 20); Period p4 = Period.eternal(); Period p5 = Period.empty(); assertTrue(p1.isOpenEnded()); assertFalse(p2.isOpenEnded()); assertFalse(p3.isOpenEnded()); assertTrue(p4.isOpenEnded()); assertFalse(p5.isOpenEnded()); } @Test public void setUpperBoundIsOnlyAllowedOnNonEmptyPeriods() { Period p1 = Period.empty(); try { p1.setUpperBound(1); fail("#setUpperBound() succeeded on empty period!"); } catch (IllegalStateException expected) { // pass } } @Test public void setUpperBoundWorks() { Period p1 = Period.createPoint(100); Period p2 = Period.createRange(10, 100); Period p3 = Period.eternal(); // case of p1 Period p1trim = p1.setUpperBound(150); assertEquals(101, p1.getUpperBound()); assertEquals(150, p1trim.getUpperBound()); assertFalse(p1 == p1trim); assertNotEquals(p1, p1trim); // case of p2 Period p2trim = p2.setUpperBound(200); assertEquals(100, p2.getUpperBound()); assertEquals(200, p2trim.getUpperBound()); assertFalse(p2 == p2trim); assertNotEquals(p2, p2trim); // case of p3 Period p3trim = p3.setUpperBound(200); assertEquals(Long.MAX_VALUE, p3.getUpperBound()); assertEquals(200, p3trim.getUpperBound()); assertFalse(p3 == p3trim); assertNotEquals(p3, p3trim); } @Test public void setUpperBoundCannotCreateEmptyPeriods() { Period p = Period.createRange(50, 100); try { // 49 is illegal, as 49 < 50 p.setUpperBound(49); fail("Managed to create an empty period using #setUpperBound(...)!"); } catch (IllegalArgumentException expected) { // pass } try { // 50 is also illegal because the upper bound is excluded; having a // period from 50 (inclusive) to 50 (exclusive) would result in an empty period p.setUpperBound(50); fail("Managed to create an empty period using #setUpperBound(...)!"); } catch (IllegalArgumentException expected) { // pass } } @Test public void canIntersectPeriods(){ Period p = Period.createRange(50, 100); assertThat(p.intersection(Period.empty()), is(Period.empty())); assertThat(p.intersection(Period.createRange(0, 10)), is(Period.empty())); assertThat(p.intersection(Period.createRange(0, 49)), is(Period.empty())); assertThat(p.intersection(Period.createRange(0, 50)), is(Period.empty())); assertThat(p.intersection(Period.createRange(0, 51)), is(Period.createRange(50,51))); assertThat(p.intersection(Period.createRange(49, 60)), is(Period.createRange(50,60))); assertThat(p.intersection(Period.createRange(60, 70)), is(Period.createRange(60,70))); assertThat(p.intersection(Period.createRange(80, 99)), is(Period.createRange(80,99))); assertThat(p.intersection(Period.createRange(80, 100)), is(Period.createRange(80,100))); assertThat(p.intersection(Period.createRange(80, 101)), is(Period.createRange(80,100))); assertThat(p.intersection(Period.createRange(99, 120)), is(Period.createRange(99,100))); assertThat(p.intersection(Period.createRange(100, 120)), is(Period.empty())); assertThat(p.intersection(Period.createRange(101, 120)), is(Period.empty())); assertThat(p.intersection(Period.createRange(0, 200)), is(Period.createRange(50, 100))); } }
14,942
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationChainTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/migration/MigrationChainTest.java
package org.chronos.chronodb.test.cases.migration; import com.google.common.collect.Lists; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.MigrationChain; import org.chronos.chronodb.test.cases.migration.chainA.MigrationA1; import org.chronos.chronodb.test.cases.migration.chainA.MigrationA2; import org.chronos.chronodb.test.cases.migration.chainA.MigrationA3; import org.chronos.common.test.ChronosUnitTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.version.ChronosVersion; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class MigrationChainTest extends ChronosUnitTest { @Test public void canScanForMigrationChain() { MigrationChain<ChronoDBInternal> chain = MigrationChain.fromPackage("org.chronos.chronodb.test.cases.migration.chainA"); List<Class<? extends ChronosMigration<ChronoDBInternal>>> actualClasses = chain.getMigrationClasses(); List<Class<? extends ChronosMigration<ChronoDBInternal>>> expectedClasses = Lists.newArrayList(); expectedClasses.add(MigrationA1.class); expectedClasses.add(MigrationA2.class); expectedClasses.add(MigrationA3.class); assertEquals(expectedClasses, actualClasses); } @Test public void canLimitMigrationChainArbitrarilyBetweenVersions() { MigrationChain<ChronoDBInternal> chain = MigrationChain.fromPackage("org.chronos.chronodb.test.cases.migration.chainA"); chain = chain.startingAt(ChronosVersion.parse("0.6.0")); List<Class<? extends ChronosMigration<ChronoDBInternal>>> actualClasses = chain.getMigrationClasses(); List<Class<? extends ChronosMigration<ChronoDBInternal>>> expectedClasses = Lists.newArrayList(); expectedClasses.add(MigrationA3.class); assertEquals(expectedClasses, actualClasses); } @Test public void canLimitMigrationChainPreciselyAtVersion() { MigrationChain<ChronoDBInternal> chain = MigrationChain.fromPackage("org.chronos.chronodb.test.cases.migration.chainA"); chain = chain.startingAt(ChronosVersion.parse("0.5.1")); List<Class<? extends ChronosMigration<ChronoDBInternal>>> actualClasses = chain.getMigrationClasses(); List<Class<? extends ChronosMigration<ChronoDBInternal>>> expectedClasses = Lists.newArrayList(); expectedClasses.add(MigrationA2.class); expectedClasses.add(MigrationA3.class); assertEquals(expectedClasses, actualClasses); } @Test public void canDetectOverlappingMigrationChains() { try { MigrationChain.fromPackage("org.chronos.chronodb.test.cases.migration.chainB"); fail("Managed to create a valid migration chain with overlapping migration paths!"); } catch (IllegalStateException expected) { // pass } } }
3,086
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationA1.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/migration/chainA/MigrationA1.java
package org.chronos.chronodb.test.cases.migration.chainA; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.annotations.Migration; @Migration(from = "0.5.0", to = "0.5.1") public class MigrationA1 implements ChronosMigration<ChronoDBInternal> { @Override public void execute(final ChronoDBInternal chronoDB) { } }
460
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationA3.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/migration/chainA/MigrationA3.java
package org.chronos.chronodb.test.cases.migration.chainA; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.annotations.Migration; @Migration(from = "0.6.4", to = "0.7.0") public class MigrationA3 implements ChronosMigration<ChronoDBInternal> { @Override public void execute(final ChronoDBInternal chronoDB) { } }
460
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationA2.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/migration/chainA/MigrationA2.java
package org.chronos.chronodb.test.cases.migration.chainA; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.annotations.Migration; @Migration(from = "0.5.1", to = "0.5.2") public class MigrationA2 implements ChronosMigration<ChronoDBInternal> { @Override public void execute(final ChronoDBInternal chronoDB) { } }
460
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationB2.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/migration/chainB/MigrationB2.java
package org.chronos.chronodb.test.cases.migration.chainB; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.annotations.Migration; @Migration(from = "0.5.1", to = "0.6.0") public class MigrationB2 implements ChronosMigration<ChronoDBInternal> { @Override public void execute(final ChronoDBInternal chronoDB) { } }
459
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MigrationB1.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/migration/chainB/MigrationB1.java
package org.chronos.chronodb.test.cases.migration.chainB; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.migration.ChronosMigration; import org.chronos.chronodb.internal.api.migration.annotations.Migration; @Migration(from = "0.5.3", to = "0.5.4") public class MigrationB1 implements ChronosMigration<ChronoDBInternal> { @Override public void execute(final ChronoDBInternal chronoDB) { } }
458
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBPropertiesFileTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/settings/ChronoDBPropertiesFileTest.java
package org.chronos.chronodb.test.cases.settings; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.File; import java.io.IOException; import java.util.UUID; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoDBPropertiesFileTest extends ChronoDBUnitTest { @Test public void loadingFullChronoConfigFromPropertiesFileWorks() { File testDirectory = tempDir; File dbFile = new File(testDirectory, UUID.randomUUID().toString().replaceAll("-", "") + ".chronodb"); try { dbFile.createNewFile(); } catch (IOException e) { fail(e.toString()); } File propertiesFile = this.getSrcTestResourcesFile("fullChronoConfig.properties"); ChronoDB chronoDB = ChronoDB.FACTORY.create().fromPropertiesFile(propertiesFile).build(); assertNotNull(chronoDB); try { // assert that the correct type of database was instantiated assertTrue(chronoDB instanceof InMemoryChronoDB); // assert that the property in the file was applied ChronoDBInternal chronoDBinternal = (ChronoDBInternal) chronoDB; assertThat(chronoDBinternal.getConfiguration().getConflictResolutionStrategy(), is(ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE)); } finally { chronoDB.close(); } } }
1,815
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBConfigurationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/settings/ChronoDBConfigurationTest.java
package org.chronos.chronodb.test.cases.settings; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.exceptions.TransactionIsReadOnlyException; import org.chronos.chronodb.exodus.configuration.ExodusChronoDBConfiguration; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Assume; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoDBConfigurationTest extends AllChronoDBBackendsTest { @Test public void debugModeIsAlwaysEnabledInTests() { ChronoDB db = this.getChronoDB(); assertTrue(db.getConfiguration().isDebugModeEnabled()); } }
1,021
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardQueryParserTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/query/parser/StandardQueryParserTest.java
package org.chronos.chronodb.test.cases.query.parser; import com.google.common.collect.Lists; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.exceptions.ChronoDBQuerySyntaxException; import org.chronos.chronodb.api.query.Condition; import org.chronos.chronodb.internal.api.query.ChronoDBQuery; import org.chronos.chronodb.internal.api.query.QueryTokenStream; import org.chronos.chronodb.internal.impl.builder.query.StandardQueryTokenStream; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.chronodb.internal.impl.query.parser.StandardQueryParser; import org.chronos.chronodb.internal.impl.query.parser.ast.BinaryOperatorElement; import org.chronos.chronodb.internal.impl.query.parser.ast.BinaryQueryOperator; import org.chronos.chronodb.internal.impl.query.parser.ast.NotElement; import org.chronos.chronodb.internal.impl.query.parser.ast.QueryElement; import org.chronos.chronodb.internal.impl.query.parser.ast.WhereElement; import org.chronos.chronodb.internal.impl.query.parser.token.AndToken; import org.chronos.chronodb.internal.impl.query.parser.token.BeginToken; import org.chronos.chronodb.internal.impl.query.parser.token.EndOfInputToken; import org.chronos.chronodb.internal.impl.query.parser.token.EndToken; import org.chronos.chronodb.internal.impl.query.parser.token.KeyspaceToken; import org.chronos.chronodb.internal.impl.query.parser.token.NotToken; import org.chronos.chronodb.internal.impl.query.parser.token.OrToken; import org.chronos.chronodb.internal.impl.query.parser.token.QueryToken; import org.chronos.chronodb.internal.impl.query.parser.token.WhereToken; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import static org.junit.Assert.*; @Category(UnitTest.class) public class StandardQueryParserTest extends ChronoDBUnitTest { @Test public void basicQueryParsingWorks() { // prepare the list of tokens List<QueryToken> tokens = Lists.newArrayList(); tokens.add(new KeyspaceToken(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); tokens.add(new WhereToken("name", Condition.EQUALS, TextMatchMode.STRICT, "Hello World")); tokens.add(new EndOfInputToken()); // convert the list into a stream QueryTokenStream stream = new StandardQueryTokenStream(tokens); // create the parser StandardQueryParser parser = new StandardQueryParser(); // run it ChronoDBQuery query = null; try { query = parser.parse(stream); } catch (ChronoDBQuerySyntaxException ex) { fail("Parse failed! Exception is: " + ex); } assertNotNull(query); assertEquals(ChronoDBConstants.DEFAULT_KEYSPACE_NAME, query.getKeyspace()); assertTrue(query.getRootElement() instanceof WhereElement); WhereElement<?, ?> where = (WhereElement<?, ?>) query.getRootElement(); assertEquals("name", where.getIndexName()); assertEquals(Condition.EQUALS, where.getCondition()); assertEquals("Hello World", where.getComparisonValue()); } @Test public void missingKeyspaceIsRecognized() { // prepare the list of tokens List<QueryToken> tokens = Lists.newArrayList(); tokens.add(new WhereToken("name", Condition.EQUALS, TextMatchMode.STRICT, "Hello World")); tokens.add(new EndOfInputToken()); // convert the list into a stream QueryTokenStream stream = new StandardQueryTokenStream(tokens); // create the parser StandardQueryParser parser = new StandardQueryParser(); // run it try { parser.parse(stream); fail("Parser did not fail on missing keyspace declaration!"); } catch (ChronoDBQuerySyntaxException ex) { // expected } } @Test public void missingEndOfInputIsRecognized() { // prepare the list of tokens List<QueryToken> tokens = Lists.newArrayList(); tokens.add(new KeyspaceToken(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); tokens.add(new WhereToken("name", Condition.EQUALS, TextMatchMode.STRICT, "Hello World")); // convert the list into a stream QueryTokenStream stream = new StandardQueryTokenStream(tokens); // create the parser StandardQueryParser parser = new StandardQueryParser(); // run it try { parser.parse(stream); fail("Parser did not fail on missing End-Of-Input!"); } catch (ChronoDBQuerySyntaxException ex) { // expected } } @Test public void andBindsStrongerThanOr() { // prepare the list of tokens List<QueryToken> tokens = Lists.newArrayList(); tokens.add(new KeyspaceToken(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); tokens.add(new WhereToken("name", Condition.EQUALS, TextMatchMode.STRICT, "Hello World")); tokens.add(new AndToken()); tokens.add(new WhereToken("foo", Condition.EQUALS, TextMatchMode.STRICT, "Bar")); tokens.add(new OrToken()); tokens.add(new WhereToken("num", Condition.EQUALS, TextMatchMode.STRICT, "42")); tokens.add(new EndOfInputToken()); // convert the list into a stream QueryTokenStream stream = new StandardQueryTokenStream(tokens); // create the parser StandardQueryParser parser = new StandardQueryParser(); // run it ChronoDBQuery query = null; try { query = parser.parse(stream); } catch (ChronoDBQuerySyntaxException ex) { fail("Parse failed! Exception is: " + ex); } assertNotNull(query); System.out.println(query); QueryElement rootElement = query.getRootElement(); assertTrue(rootElement instanceof BinaryOperatorElement); BinaryOperatorElement binaryRoot = (BinaryOperatorElement) rootElement; assertEquals(BinaryQueryOperator.OR, binaryRoot.getOperator()); } @Test public void notBindsStrongerThanAnd() { List<QueryToken> tokens = Lists.newArrayList(); tokens.add(new KeyspaceToken(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); tokens.add(new NotToken()); tokens.add(new WhereToken("name", Condition.EQUALS, TextMatchMode.STRICT, "Hello World")); tokens.add(new AndToken()); tokens.add(new WhereToken("foo", Condition.EQUALS, TextMatchMode.STRICT, "Bar")); tokens.add(new EndOfInputToken()); // convert the list into a stream QueryTokenStream stream = new StandardQueryTokenStream(tokens); // create the parser StandardQueryParser parser = new StandardQueryParser(); // run it ChronoDBQuery query = null; try { query = parser.parse(stream); } catch (ChronoDBQuerySyntaxException ex) { fail("Parse failed! Exception is: " + ex); } assertNotNull(query); System.out.println(query); QueryElement rootElement = query.getRootElement(); assertTrue(rootElement instanceof BinaryOperatorElement); BinaryOperatorElement binaryRoot = (BinaryOperatorElement) rootElement; assertEquals(BinaryQueryOperator.AND, binaryRoot.getOperator()); } @Test public void notBindsStrongerThanOr() { List<QueryToken> tokens = Lists.newArrayList(); tokens.add(new KeyspaceToken(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); tokens.add(new NotToken()); tokens.add(new WhereToken("name", Condition.EQUALS, TextMatchMode.STRICT, "Hello World")); tokens.add(new OrToken()); tokens.add(new WhereToken("foo", Condition.EQUALS, TextMatchMode.STRICT, "Bar")); tokens.add(new EndOfInputToken()); // convert the list into a stream QueryTokenStream stream = new StandardQueryTokenStream(tokens); // create the parser StandardQueryParser parser = new StandardQueryParser(); // run it ChronoDBQuery query = null; try { query = parser.parse(stream); } catch (ChronoDBQuerySyntaxException ex) { fail("Parse failed! Exception is: " + ex); } assertNotNull(query); System.out.println(query); QueryElement rootElement = query.getRootElement(); assertTrue(rootElement instanceof BinaryOperatorElement); BinaryOperatorElement binaryRoot = (BinaryOperatorElement) rootElement; assertEquals(BinaryQueryOperator.OR, binaryRoot.getOperator()); } @Test public void beginEndBindsStrongerThanNot() { List<QueryToken> tokens = Lists.newArrayList(); tokens.add(new KeyspaceToken(ChronoDBConstants.DEFAULT_KEYSPACE_NAME)); tokens.add(new NotToken()); tokens.add(new BeginToken()); tokens.add(new WhereToken("name", Condition.EQUALS, TextMatchMode.STRICT, "Hello World")); tokens.add(new OrToken()); tokens.add(new WhereToken("foo", Condition.EQUALS, TextMatchMode.STRICT, "Bar")); tokens.add(new EndToken()); tokens.add(new EndOfInputToken()); // convert the list into a stream QueryTokenStream stream = new StandardQueryTokenStream(tokens); // create the parser StandardQueryParser parser = new StandardQueryParser(); // run it ChronoDBQuery query = null; try { query = parser.parse(stream); } catch (ChronoDBQuerySyntaxException ex) { fail("Parse failed! Exception is: " + ex); } assertNotNull(query); System.out.println(query); QueryElement rootElement = query.getRootElement(); assertTrue(rootElement instanceof NotElement); } }
9,888
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleQueryConditionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/query/condition/DoubleQueryConditionTest.java
package org.chronos.chronodb.test.cases.query.condition; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.common.test.ChronosUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.chronos.common.util.ReflectionUtils; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.*; @Category(UnitTest.class) @RunWith(Parameterized.class) public class DoubleQueryConditionTest extends ChronosUnitTest { // @formatter:off @Parameters(name = "\"{0}\" {1} \"{2}\" (Should match: {3})") public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { // // PARAMETER ORDER: // {0} : Number to check // {1} : Condition to apply // {2} : Number to compare against // {3} : should match (true or false) // EQUALS { 21, NumberCondition.EQUALS, 21, true }, { 21, NumberCondition.EQUALS, 22, false }, { -13, NumberCondition.EQUALS, -13, true }, { -13, NumberCondition.EQUALS, 13, false }, { -13, NumberCondition.EQUALS, -13, true }, // NOT EQUALS { 21, NumberCondition.NOT_EQUALS, 21, false }, { 21, NumberCondition.NOT_EQUALS, 22, true }, { -13, NumberCondition.NOT_EQUALS, -13, false }, { -13, NumberCondition.NOT_EQUALS, 13, true }, { -13, NumberCondition.NOT_EQUALS, -13, false }, // LESS THAN { 21, NumberCondition.LESS_THAN, 22, true }, { 21, NumberCondition.LESS_THAN, 42, true }, { 21, NumberCondition.LESS_THAN, 21, false }, { 21, NumberCondition.LESS_THAN, -1, false }, // LESS THAN OR EQUAL TO { 21, NumberCondition.LESS_EQUAL, 22, true }, { 21, NumberCondition.LESS_EQUAL, 42, true }, { 21, NumberCondition.LESS_EQUAL, 21, true }, { 21, NumberCondition.LESS_EQUAL, -1, false }, // GREATER THAN { 21, NumberCondition.GREATER_THAN, 20, true }, { 21, NumberCondition.GREATER_THAN, 12, true }, { 21, NumberCondition.GREATER_THAN, 21, false }, { -1, NumberCondition.GREATER_THAN, 21, false }, // GREATER THAN OR EQUAL TO { 21, NumberCondition.GREATER_EQUAL, 20, true }, { 21, NumberCondition.GREATER_EQUAL, 12, true }, { 21, NumberCondition.GREATER_EQUAL, 21, true }, { -1, NumberCondition.GREATER_EQUAL, 21, false }, }); } // @formatter:on @Parameter(0) public Number number; @Parameter(1) public NumberCondition condition; @Parameter(2) public Number search; @Parameter(3) public boolean shouldMatch; @Test public void runTest() { Double a = ReflectionUtils.asDouble(this.number); Double b = ReflectionUtils.asDouble(this.search); if (this.shouldMatch) { assertTrue(this.condition.applies(a, b, 10e-6)); } else { assertFalse(this.condition.applies(a, b, 10e-6)); } } }
3,091
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleQueryConditionEqualityToleranceTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/query/condition/DoubleQueryConditionEqualityToleranceTest.java
package org.chronos.chronodb.test.cases.query.condition; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.common.test.ChronosUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(UnitTest.class) public class DoubleQueryConditionEqualityToleranceTest extends ChronosUnitTest { @Test public void equalityToleranceWorks() { assertFalse(NumberCondition.EQUALS.applies(1, 1.2, 0.1)); assertTrue(NumberCondition.EQUALS.applies(1, 1.2, 0.2)); } @Test public void equalityToleranceWorksInPositiveAndNegativeDirection() { assertTrue(NumberCondition.EQUALS.applies(1, 1.2, 0.2)); assertTrue(NumberCondition.EQUALS.applies(1.2, 1, 0.2)); } }
849
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TextualQueryConditionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/query/condition/TextualQueryConditionTest.java
package org.chronos.chronodb.test.cases.query.condition; import org.chronos.chronodb.api.query.StringCondition; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.common.test.ChronosUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.*; @Category(UnitTest.class) @RunWith(Parameterized.class) public class TextualQueryConditionTest extends ChronosUnitTest { @Parameters(name = "\"{0}\" {1} \"{2}\" (Strict: {3}, CI: {4})") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ // // PARAMETER ORDER: // {0} : Text body to scan // {1} : Condition to apply // {2} : Text to search for in the body // {3} : Should produce strict (case sensitive) match // {4} : Should produce case-insensitive match // // EQUALS // {"Hello World", StringCondition.EQUALS, "Hello World", true, true}, // {"hello world", StringCondition.EQUALS, "Hello World", false, true}, // {"Hello World", StringCondition.EQUALS, "hello world", false, true}, // {"Hello Foo", StringCondition.EQUALS, "Hello World", false, false}, // // NOT EQUALS // {"Hello Foo", StringCondition.NOT_EQUALS, "Hello World", true, true}, // {"Hello World", StringCondition.NOT_EQUALS, "Hello World", false, false}, // {"Hello World", StringCondition.NOT_EQUALS, "hello world", true, false}, // {"hello world", StringCondition.NOT_EQUALS, "Hello World", true, false}, // // CONTAINS // {"Hello World", StringCondition.CONTAINS, "Hello", true, true}, // {"hello world", StringCondition.CONTAINS, "Hello", false, true}, // {"Hello World", StringCondition.CONTAINS, "hello", false, true}, // {"Hello Foo", StringCondition.CONTAINS, "World", false, false}, // // NOT CONTAINS // {"Hello World", StringCondition.NOT_CONTAINS, "Hello", false, false}, // {"hello world", StringCondition.NOT_CONTAINS, "Hello", true, false}, // {"Hello World", StringCondition.NOT_CONTAINS, "hello", true, false}, // {"Hello Foo", StringCondition.NOT_CONTAINS, "World", true, true}, // // STARTS WITH // {"Hello World", StringCondition.STARTS_WITH, "Hello", true, true}, // {"hello world", StringCondition.STARTS_WITH, "Hello", false, true}, // {"Hello World", StringCondition.STARTS_WITH, "hello", false, true}, // {"hello world", StringCondition.STARTS_WITH, "foo", false, false}, // // NOT STARTS WITH // {"Hello World", StringCondition.NOT_STARTS_WITH, "Hello", false, false}, // {"hello world", StringCondition.NOT_STARTS_WITH, "Hello", true, false}, // {"Hello World", StringCondition.NOT_STARTS_WITH, "hello", true, false}, // {"hello world", StringCondition.NOT_STARTS_WITH, "foo", true, true}, // // ENDS WITH // {"Hello World", StringCondition.ENDS_WITH, "World", true, true}, // {"hello world", StringCondition.ENDS_WITH, "World", false, true}, // {"Hello World", StringCondition.ENDS_WITH, "world", false, true}, // {"hello world", StringCondition.ENDS_WITH, "foo", false, false}, // // NOT ENDS WITH // {"Hello World", StringCondition.NOT_ENDS_WITH, "World", false, false}, // {"hello world", StringCondition.NOT_ENDS_WITH, "World", true, false}, // {"Hello World", StringCondition.NOT_ENDS_WITH, "world", true, false}, // {"hello world", StringCondition.NOT_ENDS_WITH, "foo", true, true}, // // MATCHES REGEX // {"Hello World", StringCondition.MATCHES_REGEX, ".*World.*", true, true}, // {"hello world", StringCondition.MATCHES_REGEX, ".*World.*", false, true}, // {"Hello World", StringCondition.MATCHES_REGEX, ".*world.*", false, true}, // {"hello world", StringCondition.MATCHES_REGEX, ".*foo.*", false, false}, // // NOT MATCHES REGEX // {"Hello World", StringCondition.NOT_MATCHES_REGEX, ".*World.*", false, false}, // {"hello world", StringCondition.NOT_MATCHES_REGEX, ".*World.*", true, false}, // {"Hello World", StringCondition.NOT_MATCHES_REGEX, ".*world.*", true, false}, // {"hello world", StringCondition.NOT_MATCHES_REGEX, ".*foo.*", true, true}, }); } @Parameter(0) public String text; @Parameter(1) public StringCondition condition; @Parameter(2) public String search; @Parameter(3) public boolean matchStrict; @Parameter(4) public boolean matchCaseInsensitive; @Test public void runTest() { if (this.matchStrict) { assertTrue(this.condition.applies(this.text, this.search, TextMatchMode.STRICT)); } else { assertFalse(this.condition.applies(this.text, this.search, TextMatchMode.STRICT)); } if (this.matchCaseInsensitive) { assertTrue(this.condition.applies(this.text, this.search, TextMatchMode.CASE_INSENSITIVE)); } else { assertFalse(this.condition.applies(this.text, this.search, TextMatchMode.CASE_INSENSITIVE)); } } }
6,351
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LongQueryConditionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/query/condition/LongQueryConditionTest.java
package org.chronos.chronodb.test.cases.query.condition; import org.chronos.chronodb.api.query.NumberCondition; import org.chronos.common.test.ChronosUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.chronos.common.util.ReflectionUtils; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.*; @Category(UnitTest.class) @RunWith(Parameterized.class) public class LongQueryConditionTest extends ChronosUnitTest { // @formatter:off @Parameters(name = "\"{0}\" {1} \"{2}\" (Should match: {3})") public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { // // PARAMETER ORDER: // {0} : Number to check // {1} : Condition to apply // {2} : Number to compare against // {3} : should match (true or false) // EQUALS { 21, NumberCondition.EQUALS, 21, true }, { 21, NumberCondition.EQUALS, 22, false }, { -13, NumberCondition.EQUALS, -13, true }, { -13, NumberCondition.EQUALS, 13, false }, { -13, NumberCondition.EQUALS, -13, true }, // NOT EQUALS { 21, NumberCondition.NOT_EQUALS, 21, false }, { 21, NumberCondition.NOT_EQUALS, 22, true }, { -13, NumberCondition.NOT_EQUALS, -13, false }, { -13, NumberCondition.NOT_EQUALS, 13, true }, { -13, NumberCondition.NOT_EQUALS, -13, false }, // LESS THAN { 21, NumberCondition.LESS_THAN, 22, true }, { 21, NumberCondition.LESS_THAN, 42, true }, { 21, NumberCondition.LESS_THAN, 21, false }, { 21, NumberCondition.LESS_THAN, -1, false }, // LESS THAN OR EQUAL TO { 21, NumberCondition.LESS_EQUAL, 22, true }, { 21, NumberCondition.LESS_EQUAL, 42, true }, { 21, NumberCondition.LESS_EQUAL, 21, true }, { 21, NumberCondition.LESS_EQUAL, -1, false }, // GREATER THAN { 21, NumberCondition.GREATER_THAN, 20, true }, { 21, NumberCondition.GREATER_THAN, 12, true }, { 21, NumberCondition.GREATER_THAN, 21, false }, { -1, NumberCondition.GREATER_THAN, 21, false }, // GREATER THAN OR EQUAL TO { 21, NumberCondition.GREATER_EQUAL, 20, true }, { 21, NumberCondition.GREATER_EQUAL, 12, true }, { 21, NumberCondition.GREATER_EQUAL, 21, true }, { -1, NumberCondition.GREATER_EQUAL, 21, false }, }); } // @formatter:on @Parameter(0) public Number number; @Parameter(1) public NumberCondition condition; @Parameter(2) public Number search; @Parameter(3) public boolean shouldMatch; @Test public void runTest() { Long a = ReflectionUtils.asLong(this.number); Long b = ReflectionUtils.asLong(this.search); if (this.shouldMatch) { assertTrue(this.condition.applies(a, b)); } else { assertFalse(this.condition.applies(a, b)); } } }
3,067
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ConditionNegationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/query/optimizer/ConditionNegationTest.java
package org.chronos.chronodb.test.cases.query.optimizer; import org.chronos.chronodb.api.query.Condition; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(UnitTest.class) public class ConditionNegationTest extends ChronoDBUnitTest { @Test public void conditionNegationWorks() { for (Condition condition : Condition.values()) { Condition negated = condition.negate(); // every condition can be negated assertNotNull(negated); // the negation of the negation is the original Condition doubleNegated = negated.negate(); assertEquals(condition, doubleNegated); } } }
850
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CommitConflictIntegrationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/conflict/CommitConflictIntegrationTest.java
package org.chronos.chronodb.test.cases.conflict; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.api.exceptions.ChronoDBCommitConflictException; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class CommitConflictIntegrationTest extends AllChronoDBBackendsTest { @Test public void commitConflictDetectionWorks() { ChronoDB db = this.getChronoDB(); // create a transaction at an early timestamp ChronoDBTransaction tx1 = db.txBuilder().build(); // create another transaction and write something ChronoDBTransaction tx2 = db.tx(); tx2.put("key", "value"); tx2.commit(); // attempt to overwrite with tx1 tx1.put("key", 123); try { tx1.commit(); fail(); } catch (ChronoDBCommitConflictException expected) { } } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE") public void overwriteWithSourceStrategyWorks() { ChronoDB db = this.getChronoDB(); // create a transaction at an early timestamp ChronoDBTransaction tx1 = db.txBuilder().build(); // create another transaction and write something ChronoDBTransaction tx2 = db.tx(); tx2.put("key", "value"); tx1.put("other", "hello"); tx2.commit(); // attempt to overwrite with tx1 tx1.put("key", 123); tx1.put("else", "world"); tx1.commit(); // we should have 123 in the store now assertThat(db.tx().get("key"), is(123)); assertThat(db.tx().get("other"), is("hello")); assertThat(db.tx().get("else"), is("world")); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_TARGET") public void overwriteWithTargetStrategyWorks() { ChronoDB db = this.getChronoDB(); // create a transaction at an early timestamp ChronoDBTransaction tx1 = db.txBuilder().build(); // create another transaction and write something ChronoDBTransaction tx2 = db.tx(); tx2.put("key", "value"); tx2.put("other", "hello"); tx2.commit(); // attempt to overwrite with tx1 tx1.put("key", 123); tx1.put("else", "world"); tx1.commit(); // we should have "value" in the store now assertThat(db.tx().get("key"), is("value")); assertThat(db.tx().get("other"), is("hello")); assertThat(db.tx().get("else"), is("world")); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10000") @InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE") public void indexingWorksWithOverwriteWithSource() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // create a transaction at an early timestamp using a different strategy ChronoDBTransaction tx1 = db.tx(); // create another transaction and write something ChronoDBTransaction tx2 = db.tx(); tx2.put("k1", NamedPayload.create1KB("hello")); tx2.put("k2", NamedPayload.create1KB("world")); tx2.commit(); // attempt to overwrite with tx1 tx1.put("k1", NamedPayload.create1KB("foo")); tx1.put("k3", NamedPayload.create1KB("bar")); tx1.commit(); // check the state of the store assertEquals("foo", ((NamedPayload) db.tx().get("k1")).getName()); assertEquals("world", ((NamedPayload) db.tx().get("k2")).getName()); assertEquals("bar", ((NamedPayload) db.tx().get("k3")).getName()); // check the state of the secondary index Set<QualifiedKey> qKeys = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("foo").getKeysAsSet(); assertThat(qKeys.size(), is(1)); assertThat(qKeys, contains(QualifiedKey.createInDefaultKeyspace("k1"))); Set<QualifiedKey> qKeys2 = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("world").getKeysAsSet(); assertThat(qKeys2.size(), is(1)); assertThat(qKeys2, contains(QualifiedKey.createInDefaultKeyspace("k2"))); Set<QualifiedKey> qKeys3 = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("bar").getKeysAsSet(); assertThat(qKeys3.size(), is(1)); assertThat(qKeys3, contains(QualifiedKey.createInDefaultKeyspace("k3"))); Set<QualifiedKey> qKeys4 = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("hello").getKeysAsSet(); assertThat(qKeys4.size(), is(0)); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10000") @InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_TARGET") public void indexingWorksWithOverwriteWithTarget() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); // create a transaction at an early timestamp using a different strategy ChronoDBTransaction tx1 = db.tx(); // create another transaction and write something ChronoDBTransaction tx2 = db.tx(); tx2.put("k1", NamedPayload.create1KB("hello")); tx2.put("k2", NamedPayload.create1KB("world")); tx2.commit(); assertTrue(db.tx().getTimestamp() > 0); // attempt to overwrite with tx1 tx1.put("k1", NamedPayload.create1KB("foo")); tx1.put("k3", NamedPayload.create1KB("bar")); tx1.commit(); // check the state of the store assertThat(((NamedPayload) db.tx().get("k1")).getName(), is("hello")); assertThat(((NamedPayload) db.tx().get("k2")).getName(), is("world")); assertThat(((NamedPayload) db.tx().get("k3")).getName(), is("bar")); // check the state of the secondary index { Set<QualifiedKey> qKeys = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("hello") .getKeysAsSet(); assertThat(qKeys.size(), is(1)); assertThat(qKeys, contains(QualifiedKey.createInDefaultKeyspace("k1"))); } { Set<QualifiedKey> qKeys = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("world") .getKeysAsSet(); assertThat(qKeys.size(), is(1)); assertThat(qKeys, contains(QualifiedKey.createInDefaultKeyspace("k2"))); } { Set<QualifiedKey> qKeys = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("bar").getKeysAsSet(); assertThat(qKeys.size(), is(1)); assertThat(qKeys, contains(QualifiedKey.createInDefaultKeyspace("k3"))); } } @Test public void canOverrideDefaultResolutionStrategyInTransaction() { ChronoDB db = this.getChronoDB(); // by default, we should have DO_NOT_MERGE as our strategy assertThat(db.getConfiguration().getConflictResolutionStrategy(), is(ConflictResolutionStrategy.DO_NOT_MERGE)); // create a transaction at an early timestamp using a different strategy ChronoDBTransaction tx1 = db.txBuilder() .withConflictResolutionStrategy(ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE).build(); // create another transaction and write something ChronoDBTransaction tx2 = db.tx(); tx2.put("key", "value"); tx2.put("other", "hello"); tx2.commit(); // attempt to overwrite with tx1 tx1.put("key", 123); tx1.put("else", "world"); tx1.commit(); // we should have 123 in the store now (because we have chosen "override with source") assertThat(db.tx().get("key"), is(123)); assertThat(db.tx().get("other"), is("hello")); assertThat(db.tx().get("else"), is("world")); } @Test public void canUseCustomConflictResolverClass() { ChronoDB db = this.getChronoDB(); ChronoDBTransaction tx1 = db.tx(); ChronoDBTransaction tx2 = db.txBuilder() .withConflictResolutionStrategy(new TakeHigherNumericValueConflictResolver()).build(); tx1.put("a", 3); tx1.put("b", 25); tx1.put("c", 36); tx1.commit(); tx2.put("a", 15); tx2.put("b", 10); tx2.put("d", 1); tx2.commit(); // assert that the higher value survived in case of conflicts assertThat(db.tx().get("a"), is(15)); assertThat(db.tx().get("b"), is(25)); assertThat(db.tx().get("c"), is(36)); assertThat(db.tx().get("d"), is(1)); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10000") @InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE") public void canConflictResolveDeletions() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex().withName("name").withIndexer(new NamedPayloadNameIndexer()).onMaster().acrossAllTimestamps().build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx0 = db.tx(); tx0.put("k1", "hello"); tx0.commit(); // create a transaction at an early timestamp using a different strategy ChronoDBTransaction tx1 = db.tx(); // create another transaction and write something ChronoDBTransaction tx2 = db.tx(); tx2.put("k1", NamedPayload.create1KB("hello")); tx2.put("k2", NamedPayload.create1KB("world")); tx2.commit(); // attempt to overwrite with tx1 tx1.remove("k1"); tx1.put("k3", NamedPayload.create1KB("bar")); tx1.commit(); // check the state of the store assertThat(db.tx().get("k1"), nullValue()); assertThat(((NamedPayload) db.tx().get("k2")).getName(), is("world")); assertThat(((NamedPayload) db.tx().get("k3")).getName(), is("bar")); Set<QualifiedKey> qKeys = db.tx().find().inDefaultKeyspace().where("name").isEqualTo("hello").getKeysAsSet(); assertThat(qKeys.size(), is(0)); } // ================================================================================================================= // HELPER CLASSES // ================================================================================================================= public static class TakeHigherNumericValueConflictResolver implements ConflictResolutionStrategy { @Override public Object resolve(final AtomicConflict conflict) { Object sourceValue = conflict.getSourceValue(); Object targetValue = conflict.getTargetValue(); if (sourceValue == null) { return targetValue; } if (targetValue == null) { return sourceValue; } if (sourceValue instanceof Number && targetValue instanceof Number) { if (((Number) sourceValue).doubleValue() > ((Number) targetValue).doubleValue()) { return sourceValue; } else { return targetValue; } } else { return sourceValue; } } } }
12,914
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AtomicConflictTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/conflict/AtomicConflictTest.java
package org.chronos.chronodb.test.cases.conflict; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.impl.conflict.AncestorFetcher; import org.chronos.chronodb.internal.impl.conflict.AtomicConflictImpl; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(UnitTest.class) public class AtomicConflictTest extends ChronoDBUnitTest { @Test public void ancestorIsOnlyFetchedOnce() { ChronoIdentifier sourceKey = ChronoIdentifier.create("master", 1000, "default", "hello"); Object sourceValue = "baz"; ChronoIdentifier targetKey = ChronoIdentifier.create("master", 900, "default", "hello"); Object targetValue = "bar"; AncestorFetcher fetcher = (ts, sk, tk) -> { ChronoIdentifier ancestorKey = ChronoIdentifier.create("master", 500, "default", "hello"); Object ancestorValue = "world"; return Pair.of(ancestorKey, ancestorValue); }; AtomicConflict conflict = new AtomicConflictImpl(0, sourceKey, sourceValue, targetKey, targetValue, fetcher); // try to fetch the ancestor twice ChronoIdentifier ancestorKey = conflict.getCommonAncestorKey(); Object ancestorValue = conflict.getCommonAncestorValue(); ChronoIdentifier ancestorKey2 = conflict.getCommonAncestorKey(); Object ancestorValue2 = conflict.getCommonAncestorValue(); // we should get the very SAME objects, even though the ancestor fetcher // produces new instances on every call (because AtomicConflictImpl has a cache) assertTrue(ancestorKey == ancestorKey2); assertTrue(ancestorValue == ancestorValue2); } @Test public void canDealWithDeletions() { // this is a hypothetical case where all values represent deletions. // This would not be an "actual" conflict, but we use it to test NULL handling. ChronoIdentifier sourceKey = ChronoIdentifier.create("master", 1000, "default", "hello"); Object sourceValue = null; ChronoIdentifier targetKey = ChronoIdentifier.create("master", 900, "default", "hello"); Object targetValue = null; AncestorFetcher fetcher = (ts, sk, tk) -> { ChronoIdentifier ancestorKey = ChronoIdentifier.create("master", 500, "default", "hello"); Object ancestorValue = null; return Pair.of(ancestorKey, ancestorValue); }; AtomicConflict conflict = new AtomicConflictImpl(0, sourceKey, sourceValue, targetKey, targetValue, fetcher); assertNull(conflict.getSourceValue()); assertNull(conflict.getTargetValue()); assertNull(conflict.getCommonAncestorValue()); } }
2,990
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ConflictResolutionStrategyLoaderTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/conflict/ConflictResolutionStrategyLoaderTest.java
package org.chronos.chronodb.test.cases.conflict; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.impl.ConflictResolutionStrategyLoader; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(UnitTest.class) public class ConflictResolutionStrategyLoaderTest extends ChronoDBUnitTest { @Test public void canResolveDefaultStrategy() { // null produces the default strategy assertThat(this.load(null), is(ConflictResolutionStrategy.DO_NOT_MERGE)); // empty string produces the default strategy assertThat(this.load(""), is(ConflictResolutionStrategy.DO_NOT_MERGE)); // whitespace string produces the default strategy assertThat(this.load(" \t "), is(ConflictResolutionStrategy.DO_NOT_MERGE)); } @Test public void canResolvePredefinedStrategies() { assertThat(this.load("DO_NOT_MERGE"), is(ConflictResolutionStrategy.DO_NOT_MERGE)); assertThat(this.load("OVERWRITE_WITH_SOURCE"), is(ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE)); assertThat(this.load("OVERWRITE_WITH_TARGET"), is(ConflictResolutionStrategy.OVERWRITE_WITH_TARGET)); } @Test public void canLoadCustomClass() { String className = TestConflictResolutionStrategy.class.getName(); assertThat(this.load(className), instanceOf(TestConflictResolutionStrategy.class)); } @Test public void loadingFailsOnUnknownStrings() { try { this.load("ThisAintNoStrategy"); fail("Managed to load non-existing conflict resolution strategy!"); } catch (IllegalArgumentException expected) { // pass } } @Test public void loadingFailsIfClassDoesNotImplementInterface() { try { this.load(NotAConflictResolutionStrategy.class.getName()); fail("Managed to use a class that does not implement " + ConflictResolutionStrategy.class.getName() + "' as a conflict resolution strategy!"); } catch (IllegalArgumentException expected) { // pass } } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= /** * Just a small syntactic helper that calls {@link ConflictResolutionStrategyLoader#load(String)}. * * @param name the name of the strategy to load. May be <code>null</code>. * @return the loaded strategy instance. */ private ConflictResolutionStrategy load(final String name) { return ConflictResolutionStrategyLoader.load(name); } // ================================================================================================================= // INNER CLASSES // ================================================================================================================= public static class TestConflictResolutionStrategy implements ConflictResolutionStrategy { @Override public Object resolve(final AtomicConflict conflict) { // just for testing... return null; } } public static class NotAConflictResolutionStrategy { } }
3,638
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DefaultCommitConflictStrategiesTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/conflict/DefaultCommitConflictStrategiesTest.java
package org.chronos.chronodb.test.cases.conflict; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronodb.api.conflict.AtomicConflict; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.api.exceptions.ChronoDBCommitConflictException; import org.chronos.chronodb.api.key.ChronoIdentifier; import org.chronos.chronodb.internal.impl.conflict.AncestorFetcher; import org.chronos.chronodb.internal.impl.conflict.AtomicConflictImpl; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(UnitTest.class) public class DefaultCommitConflictStrategiesTest extends ChronoDBUnitTest { @Test public void overwriteWithSourceWorks() { ConflictResolutionStrategy strategy = ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE; AtomicConflict conflict = this.createConflict(); Object resolution = strategy.resolve(conflict); assertEquals(conflict.getSourceValue(), resolution); } @Test public void overwriteWithTargetWorks() { ConflictResolutionStrategy strategy = ConflictResolutionStrategy.OVERWRITE_WITH_TARGET; AtomicConflict conflict = this.createConflict(); Object resolution = strategy.resolve(conflict); assertEquals(conflict.getTargetValue(), resolution); } @Test public void doNotMergeWorks() { ConflictResolutionStrategy strategy = ConflictResolutionStrategy.DO_NOT_MERGE; AtomicConflict conflict = this.createConflict(); try { strategy.resolve(conflict); fail("Managed to merge a conflict with default strategy: DO_NOT_MERGE"); } catch (ChronoDBCommitConflictException expected) { // pass } } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= private AtomicConflict createConflict() { ChronoIdentifier sourceKey = ChronoIdentifier.create("master", 1000, "default", "hello"); Object sourceValue = "baz"; ChronoIdentifier targetKey = ChronoIdentifier.create("master", 900, "default", "hello"); Object targetValue = "bar"; AncestorFetcher fetcher = (ts, sk, tk) -> { ChronoIdentifier ancestorKey = ChronoIdentifier.create("master", 500, "default", "hello"); Object ancestorValue = "world"; return Pair.of(ancestorKey, ancestorValue); }; AtomicConflict conflict = new AtomicConflictImpl(0L, sourceKey, sourceValue, targetKey, targetValue, fetcher); return conflict; } }
2,906
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MutableValuesCacheTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/cache/MutableValuesCacheTest.java
package org.chronos.chronodb.test.cases.cache; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.internal.impl.cache.mosaic.MosaicCache; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class MutableValuesCacheTest extends AllChronoDBBackendsTest { @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100000") @InstantiateChronosWith(property = ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, value = "true") public void passingMutableObjectsToTheCacheAsValuesCanModifyItsState() { // note that we ENABLE the immutability assumption, even though the values we pass into // the cache are NOT immutable. This test case serves as a demonstration that the issue // does indeed exist. ChronoDB db = this.getChronoDB(); assertNotNull(db); try { // assert that we do have a cache ChronoDBCache cache = db.getCache(); assertNotNull(cache); MyMutableObject obj1 = new MyMutableObject(1); MyMutableObject obj2 = new MyMutableObject(2); ChronoDBTransaction tx = db.tx(); tx.put("one", obj1); tx.put("two", obj2); tx.commit(); // assert that a write-through has indeed occurred (i.e. our cache is filled) // 2 entries from our commit + 2 entries with NULL value from the indexing assertEquals(4, cache.size()); // now we change the values (which also reside in the cache) obj1.setNumber(42); // when we now request that element, we should get the (unintentionally) modified version that // was never committed to the database. This is of course wrong, but remember that this test // only demonstrates the existence of the issue, and we deliberately deactivated the safety // measure in the database setup above. assertEquals(42, ((MyMutableObject) tx.get("one")).getNumber()); } finally { db.close(); } } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10000") @InstantiateChronosWith(property = ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, value = "false") public void disablingCachedValuesImmutabilityAssumptionPreventsCacheStateCorruption() { // we disable the assumption that cache values are immutable here. It's actually the default, // but just to make it explicit we do it here, because that's what this test is all about. ChronoDB db = this.getChronoDB(); assertNotNull(db); try { // assert that we do have a cache ChronoDBCache cache = db.getCache(); assertNotNull(cache); MyMutableObject obj1 = new MyMutableObject(1); MyMutableObject obj2 = new MyMutableObject(2); ChronoDBTransaction tx = db.tx(); tx.put("one", obj1); tx.put("two", obj2); tx.commit(); // assert that a write-through has indeed occurred (i.e. our cache is filled) // 2 entries from our commit + 2 entries with NULL value from the indexing assertEquals(4, ((MosaicCache) cache).computedSize()); assertEquals(4, cache.size()); // now we change the values (which should NOT alter our cache state) obj1.setNumber(42); // when we now request that element, we should get the original, ummodified version of the element assertEquals(1, ((MyMutableObject) tx.get("one")).getNumber()); } finally { db.close(); } } private static class MyMutableObject { private int number; @SuppressWarnings("unused") protected MyMutableObject() { // default constructor for serialization purposes this(0); } public MyMutableObject(final int number) { this.number = number; } public int getNumber() { return this.number; } public void setNumber(final int number) { this.number = number; } } }
4,889
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CachedTemporalKeyValueStoreTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/cache/CachedTemporalKeyValueStoreTest.java
package org.chronos.chronodb.test.cases.cache; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class CachedTemporalKeyValueStoreTest extends AllChronoDBBackendsTest { @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000") public void cacheIsFilledByTKVS() { ChronoDB db = this.getChronoDB(); // perform some usual work ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.put("Number", 42); tx.commit(); // the commit should have triggered a write-through, and filled the cache with 3 entries assertTrue(db.getCache().size() >= 3); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000") public void cacheProducesHitsOnGetOperations() { ChronoDB db = this.getChronoDB(); // perform some usual work ChronoDBTransaction tx = db.tx(); tx.put("Hello", "World"); tx.put("Foo", "Bar"); tx.put("Number", 42); tx.commit(); ChronoDBCache cache = db.getCache(); // the commit should have triggered a write-through, and filled the cache with 3 entries assertTrue(cache.size() >= 3); // now, the next requests on "get" should produce cache hits. db.getCache().resetStatistics(); assertEquals("World", tx.get("Hello")); assertEquals("Bar", tx.get("Foo")); assertEquals(42, (int) tx.get("Number")); assertEquals(3, cache.getStatistics().getRequestCount()); assertEquals(3, cache.getStatistics().getCacheHitCount()); assertEquals(0, cache.getStatistics().getCacheMissCount()); assertEquals(1.0, cache.getStatistics().getCacheHitRatio(), 0.001); assertEquals(0.0, cache.getStatistics().getCacheMissRatio(), 0.001); } // @Test // @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") // @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000") // public void performingAGetMayTriggerLruEviction() { // ChronoDB db = this.getChronoDB(); // // perform some usual work // ChronoDBTransaction tx = db.tx(); // tx.put("Hello", "World"); // tx.put("Foo", "Bar"); // tx.put("Number", 42); // tx.commit(); // // ChronoDBCache cache = db.getCache(); // // // we completely reset the cache here, because write-through operations on "tx.commit()" also // // fill the cache. In order to demonstrate that reads will also fill the cache, we need to flush // // it here. // cache.resetStatistics(); // cache.clear(); // // // perform the first two gets // assertEquals("World", tx.get("Hello")); // assertEquals("Bar", tx.get("Foo")); // // // we should have a cache size of 2, 2 misses and 0 hits // assertEquals(2, cache.sizeInElements()); // assertEquals(2, cache.getStatistics().getCacheMissCount()); // assertEquals(0, cache.getStatistics().getCacheHitCount()); // // // now, when performing the "get" on a third key, the LRU eviction should trigger, removing // // the pair "Hello"->"World" // assertEquals(42, (int) tx.get("Number")); // // assertEquals(2, cache.sizeInElements()); // assertEquals(3, cache.getStatistics().getCacheMissCount()); // assertEquals(0, cache.getStatistics().getCacheHitCount()); // // // another call to the (now removed) pair should result in another miss (as it was LRU-evicted) // assertEquals("World", tx.get("Hello")); // assertEquals(2, cache.sizeInElements()); // assertEquals(4, cache.getStatistics().getCacheMissCount()); // assertEquals(0, cache.getStatistics().getCacheHitCount()); // } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000") public void writeThroughWorksCorrectly() { ChronoDB db = this.getChronoDB(); // first, try to get a value for a key that doesn't exist Object value = db.tx().get("mykey"); assertNull(value); // the previous operation should have triggered a cache insert ChronoDBCache cache = db.getCache(); int cacheEntries = cache.size(); assertEquals(1, cacheEntries); // we should have one cache miss (the one we just produced) assertEquals(1, cache.getStatistics().getCacheMissCount()); // now, perform a commit on the same key ChronoDBTransaction tx = db.tx(); tx.put("mykey", "Hello World!"); tx.commit(); // when we now get the value for the key, we should see the real result assertEquals("Hello World!", db.tx().get("mykey")); // this should have been a cache hit due to write-through assertTrue(cache.getStatistics().getCacheHitCount() >= 1); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000") public void writeThroughWorksCorrectlyInIncrementalCommit() { ChronoDB db = this.getChronoDB(); // first, try to get a value for a key that doesn't exist Object value = db.tx().get("mykey"); assertNull(value); // the previous operation should have triggered a cache insert ChronoDBCache cache = db.getCache(); int cacheEntries = cache.size(); assertEquals(1, cacheEntries); // we should have one cache miss (the one we just produced) assertEquals(1, cache.getStatistics().getCacheMissCount()); // now, perform a commit on the same key ChronoDBTransaction tx = db.tx(); tx.put("mykey", "Hello World!"); tx.commitIncremental(); // terminate the incremental commit process tx.commit(); // when we now get the value for the key, we should see the real result assertEquals("Hello World!", db.tx().get("mykey")); } @Test @InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000") public void canWriteThroughCacheSeveralTimesOnSameKeyInIncrementalCommit() { ChronoDB db = this.getChronoDB(); // first, try to get a value for a key that doesn't exist Object value = db.tx().get("mykey"); assertNull(value); // the previous operation should have triggered a cache insert ChronoDBCache cache = db.getCache(); int cacheEntries = cache.size(); assertEquals(1, cacheEntries); // we should have one cache miss (the one we just produced) assertEquals(1, cache.getStatistics().getCacheMissCount()); // now, we perform an incremental commit on that key ChronoDBTransaction tx = db.tx(); tx.put("mykey", "Hello World!"); tx.commitIncremental(); // make sure that the cache contains the correct result assertEquals("Hello World!", tx.get("mykey")); // also make sure that hte previous query was a cache hit assertTrue(cache.getStatistics().getCacheHitCount() >= 1); // now, overwrite with another value tx.put("mykey", "Foo"); tx.commitIncremental(); // make sure that the cache contains the correct result assertEquals("Foo", tx.get("mykey")); // also make sure that hte previous query was a cache hit assertTrue(cache.getStatistics().getCacheHitCount() >= 2); // perform the final commit tx.commit(); // make sure that the cache contains the correct result assertEquals("Foo", tx.get("mykey")); } }
8,636
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
CacheGetResultTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/cache/CacheGetResultTest.java
package org.chronos.chronodb.test.cases.cache; import org.chronos.chronodb.api.exceptions.CacheGetResultNotPresentException; import org.chronos.chronodb.internal.api.cache.CacheGetResult; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(UnitTest.class) public class CacheGetResultTest extends ChronoDBUnitTest { @Test public void canCreateAHit() { CacheGetResult<String> hit = CacheGetResult.hit("180!!!", 180L); assertNotNull(hit); } @Test public void canCreateAMiss() { CacheGetResult<Object> miss = CacheGetResult.miss(); assertNotNull(miss); } @Test public void creatingAMissReturnsASingletonInstance() { CacheGetResult<Object> miss = CacheGetResult.miss(); CacheGetResult<Object> miss2 = CacheGetResult.miss(); assertNotNull(miss); assertTrue(miss == miss2); } @Test public void getValueOnHitReturnsTheCorrectValue() { CacheGetResult<String> hit = CacheGetResult.hit("180!!!", 180L); assertNotNull(hit); assertEquals("180!!!", hit.getValue()); assertEquals(180L, hit.getValidFrom()); } @Test public void getValueOnMissThrowsAnException() { CacheGetResult<?> miss = CacheGetResult.miss(); assertNotNull(miss); try { miss.getValue(); fail("getValue() succeeded on a cache miss!"); } catch (CacheGetResultNotPresentException expected) { // pass } } @Test public void hashCodeAndEqualsWork() { CacheGetResult<String> hit = CacheGetResult.hit("180!!!", 180L); CacheGetResult<String> hit2 = CacheGetResult.hit("Bulls Eye!", 50L); CacheGetResult<String> hit3 = CacheGetResult.hit("Bulls Eye!", 50L); CacheGetResult<String> hit4 = CacheGetResult.hit(null, 0L); CacheGetResult<?> miss = CacheGetResult.miss(); CacheGetResult<?> miss2 = CacheGetResult.miss(); assertNotEquals(hit, hit2); assertEquals(hit2, hit3); assertEquals(hit3, hit2); assertEquals(hit2.hashCode(), hit3.hashCode()); assertNotEquals(hit, miss); assertNotEquals(miss, hit4); assertEquals(miss, miss2); assertEquals(miss.hashCode(), miss2.hashCode()); } }
2,469
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MosaicRowTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/cache/mosaic/MosaicRowTest.java
package org.chronos.chronodb.test.cases.cache.mosaic; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.cache.CacheGetResult; import org.chronos.chronodb.internal.impl.cache.CacheStatisticsImpl; import org.chronos.chronodb.internal.impl.cache.mosaic.MosaicRow; import org.chronos.chronodb.internal.impl.cache.util.lru.FakeUsageRegistry; import org.chronos.chronodb.internal.impl.cache.util.lru.RangedGetResultUsageRegistry; import org.chronos.chronodb.internal.impl.cache.util.lru.UsageRegistry; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Iterator; import java.util.Set; import static org.junit.Assert.*; @Category(UnitTest.class) public class MosaicRowTest extends ChronoDBUnitTest { @Test public void canCreateMosaicRow() { UsageRegistry<GetResult<?>> lruRegistry = FakeUsageRegistry.getInstance(); QualifiedKey rowKey = QualifiedKey.createInDefaultKeyspace("Test"); MosaicRow row = new MosaicRow(rowKey, lruRegistry, new CacheStatisticsImpl(), this::noSizeChangeHandler); assertNotNull(row); } @Test public void putAndGetAreConsistent() { UsageRegistry<GetResult<?>> lruRegistry = FakeUsageRegistry.getInstance(); QualifiedKey rowKey = QualifiedKey.createInDefaultKeyspace("Test"); MosaicRow row = new MosaicRow(rowKey, lruRegistry, new CacheStatisticsImpl(), this::noSizeChangeHandler); GetResult<Object> simulatedGetResult = GetResult.create(rowKey, "Hello", Period.createRange(100, 200)); row.put(simulatedGetResult); assertEquals(1, row.size()); {// get in between the ranges CacheGetResult<Object> cacheGet = row.get(150); assertNotNull(cacheGet); assertTrue(cacheGet.isHit()); assertFalse(cacheGet.isMiss()); assertEquals("Hello", cacheGet.getValue()); } { // get at the lower boundary CacheGetResult<Object> cacheGet = row.get(100); assertNotNull(cacheGet); assertTrue(cacheGet.isHit()); assertFalse(cacheGet.isMiss()); assertEquals("Hello", cacheGet.getValue()); } {// get at the upper boundary CacheGetResult<Object> cacheGet = row.get(199); assertNotNull(cacheGet); assertTrue(cacheGet.isHit()); assertFalse(cacheGet.isMiss()); assertEquals("Hello", cacheGet.getValue()); } {// get below the lower boundary CacheGetResult<Object> cacheGet = row.get(99); assertNotNull(cacheGet); assertTrue(cacheGet.isMiss()); assertFalse(cacheGet.isHit()); } { // get above the upper boundary CacheGetResult<Object> cacheGet = row.get(200); assertNotNull(cacheGet); assertTrue(cacheGet.isMiss()); assertFalse(cacheGet.isHit()); } } @Test public void leastRecentlyUsedEvictionWorks() { UsageRegistry<GetResult<?>> lruRegistry = new RangedGetResultUsageRegistry(); QualifiedKey rowKey = QualifiedKey.createInDefaultKeyspace("Test"); MosaicRow row = new MosaicRow(rowKey, lruRegistry, new CacheStatisticsImpl(), this::noSizeChangeHandler); GetResult<Object> simulatedGetResult1 = GetResult.create(rowKey, "Hello", Period.createRange(100, 200)); row.put(simulatedGetResult1); GetResult<Object> simulatedGetResult2 = GetResult.create(rowKey, "World", Period.createRange(200, 300)); row.put(simulatedGetResult2); assertEquals(2, row.size()); // simulate some gets // Note: to make the outcome of the test deterministic, we insert 'sleep' calls here. In a real-world // scenario, it is of course allowed that several accesses occur on a MosaicRow in the same millisecond, // but the result is hard to perform any checks upon. this.sleep(1); assertEquals("Hello", row.get(150).getValue()); this.sleep(1); assertEquals("World", row.get(250).getValue()); this.sleep(1); assertEquals("Hello", row.get(125).getValue()); // now, remove the least recently used item (which is the 'simulatedGetResult2') lruRegistry.removeLeastRecentlyUsedElement(); // assert that the element is gone from the LRU registry AND from the row assertEquals(1, lruRegistry.sizeInElements()); assertEquals(1, row.size()); // assert that queries on 'simulatedGetResult2' are now cache misses CacheGetResult<Object> result = row.get(250); assertNotNull(result); assertTrue(result.isMiss()); assertFalse(result.isHit()); } @Test public void periodsAreArrangedInDescendingOrder() { UsageRegistry<GetResult<?>> lruRegistry = FakeUsageRegistry.getInstance(); QualifiedKey rowKey = QualifiedKey.createInDefaultKeyspace("Test"); MosaicRowTestSpy row = new MosaicRowTestSpy(rowKey, lruRegistry, new CacheStatisticsImpl(), this::noSizeChangeHandler); GetResult<Object> simulatedGetResult1 = GetResult.create(rowKey, "Hello", Period.createRange(100, 200)); row.put(simulatedGetResult1); GetResult<Object> simulatedGetResult2 = GetResult.create(rowKey, "World", Period.createRange(0, 100)); row.put(simulatedGetResult2); GetResult<Object> simulatedGetResult3 = GetResult.create(rowKey, "Foo", Period.createRange(200, 300)); row.put(simulatedGetResult3); Iterator<GetResult<?>> iterator = row.getContents().iterator(); assertEquals(simulatedGetResult3, iterator.next()); assertEquals(simulatedGetResult1, iterator.next()); assertEquals(simulatedGetResult2, iterator.next()); } @Test public void writeThroughWorks() { RangedGetResultUsageRegistry lruRegistry = new RangedGetResultUsageRegistry(); QualifiedKey rowKey = QualifiedKey.createInDefaultKeyspace("Test"); MosaicRow row = new MosaicRow(rowKey, lruRegistry, new CacheStatisticsImpl(), this::noSizeChangeHandler); GetResult<Object> simulatedGetResult1 = GetResult.create(rowKey, "Hello", Period.createRange(100, 200)); row.put(simulatedGetResult1); GetResult<Object> simulatedGetResult2 = GetResult.create(rowKey, "World", Period.createOpenEndedRange(200)); row.put(simulatedGetResult2); assertEquals(2, row.size()); // assert that the result of a cache get is "World" after 300 assertEquals("World", row.get(350).getValue()); row.writeThrough(300, "Foo"); // assert that we have 3 entries now assertEquals(3, row.size()); System.out.println("Before 'get(350)': " + lruRegistry.toDebugString()); // assert that the result of a cache get is now "Foo" after 300 assertEquals("Foo", row.get(350).getValue()); System.out.println("After 'get(350)' : " + lruRegistry.toDebugString()); // make the "Foo" item the least recently used this.sleep(1); assertEquals("Hello", row.get(150).getValue()); System.out.println("After 'get(150)': " + lruRegistry.toDebugString()); this.sleep(1); assertEquals("World", row.get(250).getValue()); System.out.println("After 'get(250)': " + lruRegistry.toDebugString()); // remove the least recently used items (which is the old unlimited "World" item and the new "Foo" item) lruRegistry.removeLeastRecentlyUsedUntil(() -> row.size() <= 2); System.out.println("After reduce: " + lruRegistry.toDebugString()); System.out.println("Elements in row: " + row.getContents()); // assert that a get after 300 now results in a cache miss assertTrue(row.get(350).isMiss()); } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= private void noSizeChangeHandler(final MosaicRow row, final int sizeDelta) { // nothing to do } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== private static class MosaicRowTestSpy extends MosaicRow { public MosaicRowTestSpy(final QualifiedKey rowKey, final UsageRegistry<GetResult<?>> lruRegistry, final CacheStatisticsImpl statistics, final RowSizeChangeCallback callback) { super(rowKey, lruRegistry, statistics, callback); } @Override public Set<GetResult<?>> getContents() { return super.getContents(); } } }
9,201
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MosaicCacheTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/cache/mosaic/MosaicCacheTest.java
package org.chronos.chronodb.test.cases.cache.mosaic; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.api.cache.CacheGetResult; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.internal.impl.cache.mosaic.MosaicCache; import org.chronos.common.test.utils.TestUtils; import org.chronos.common.test.ChronosUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; @Category(UnitTest.class) public class MosaicCacheTest extends ChronosUnitTest { @Test public void canCreateMosaicCacheInstance() { ChronoDBCache cache = new MosaicCache(); assertNotNull(cache); } @Test public void cacheAndGetAreConsistent() { ChronoDBCache cache = createCacheOfSize(100); String branch = ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; QualifiedKey key = QualifiedKey.createInDefaultKeyspace("Hello"); cache.cache(branch, GetResult.create(key, "World", Period.createRange(100, 200))); cache.cache(branch, GetResult.create(key, "Foo", Period.createRange(200, 500))); { // below lowest entry CacheGetResult<Object> result = cache.get(branch, 99, key); assertNotNull(result); assertTrue(result.isMiss()); } { // at lower bound of lowest entry CacheGetResult<Object> result = cache.get(branch, 100, key); assertNotNull(result); assertTrue(result.isHit()); assertEquals("World", result.getValue()); } { // in between bounds CacheGetResult<Object> result = cache.get(branch, 150, key); assertNotNull(result); assertTrue(result.isHit()); assertEquals("World", result.getValue()); } { // at upper bound of lowest entry CacheGetResult<Object> result = cache.get(branch, 199, key); assertNotNull(result); assertTrue(result.isHit()); assertEquals("World", result.getValue()); } { // at lower bound of upper entry CacheGetResult<Object> result = cache.get(branch, 200, key); assertNotNull(result); assertTrue(result.isHit()); assertEquals("Foo", result.getValue()); } { // in between bounds CacheGetResult<Object> result = cache.get(branch, 300, key); assertNotNull(result); assertTrue(result.isHit()); assertEquals("Foo", result.getValue()); } { // at upper bound of upper entry CacheGetResult<Object> result = cache.get(branch, 499, key); assertNotNull(result); assertTrue(result.isHit()); assertEquals("Foo", result.getValue()); } { // outside of any entry CacheGetResult<Object> result = cache.get(branch, 550, key); assertNotNull(result); assertTrue(result.isMiss()); } } @Test public void cacheGetOnNonExistingRowDoesntCrash() { ChronoDBCache cache = createCacheOfSize(1); String branch = ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; CacheGetResult<Object> result = cache.get(branch, 1234, QualifiedKey.createInDefaultKeyspace("Fake")); assertNotNull(result); assertTrue(result.isMiss()); } @Test public void leastRecentlyUsedShrinkOnCacheBehaviourWorks() { QualifiedKey key = QualifiedKey.createInDefaultKeyspace("Hello"); GetResult<?> result1 = GetResult.create(key, "World", Period.createRange(100, 200)); GetResult<?> result2 = GetResult.create(key, "Foo", Period.createRange(200, 300)); ChronoDBCache cache = createCacheOfSize(1); String branch = ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; cache.cache(branch, result1); cache.cache(branch, result2); assertTrue(cache.get(branch, 250, key).isHit()); assertEquals("Foo", cache.get(branch, 250, key).getValue()); assertFalse(cache.get(branch, 150, key).isHit()); } @Test public void leastRecentlyUsedShrinkOnWriteThroughBehaviourWorks() { QualifiedKey key = QualifiedKey.createInDefaultKeyspace("Hello"); GetResult<?> result1 = GetResult.create(key, "World", Period.createOpenEndedRange(100)); ChronoDBCache cache = createCacheOfSize(1); String branch = ChronoDBConstants.MASTER_BRANCH_IDENTIFIER; cache.cache(branch, result1); cache.writeThrough(branch, 200, key, "Foo"); assertTrue(cache.get(branch, 250, key).isHit()); assertEquals("Foo", cache.get(branch, 250, key).getValue()); assertFalse(cache.get(branch, 150, key).isHit()); } @Test public void cacheSizeIsCorrect() { QualifiedKey qKeyA = QualifiedKey.createInDefaultKeyspace("a"); QualifiedKey qKeyB = QualifiedKey.createInDefaultKeyspace("b"); QualifiedKey qKeyC = QualifiedKey.createInDefaultKeyspace("c"); QualifiedKey qKeyD = QualifiedKey.createInDefaultKeyspace("d"); ChronoDBCache cache = createCacheOfSize(3); cache.cache("master", GetResult.create(qKeyA, "Hello", Period.createRange(100, 200))); cache.cache("master", GetResult.create(qKeyA, "World", Period.createRange(200, 300))); cache.cache("master", GetResult.create(qKeyA, "Foo", Period.createRange(300, 400))); cache.cache("master", GetResult.create(qKeyA, "Bar", Period.createRange(400, 500))); cache.cache("master", GetResult.create(qKeyB, "Hello", Period.createRange(100, 200))); cache.cache("master", GetResult.create(qKeyB, "World", Period.createRange(200, 300))); cache.clear(); assertEquals(0, cache.size()); cache.cache("master", GetResult.create(qKeyA, "Hello", Period.createRange(100, 200))); cache.cache("master", GetResult.create(qKeyA, "World", Period.createRange(200, 300))); cache.cache("master", GetResult.create(qKeyA, "Foo", Period.createRange(300, 400))); cache.writeThrough("master", 400, qKeyA, "Bar"); cache.writeThrough("master", 0, qKeyB, "Hello"); cache.writeThrough("master", 100, qKeyB, "World"); cache.writeThrough("master", 100, qKeyC, "World"); cache.writeThrough("master", 200, qKeyC, "Foo"); cache.cache("master", GetResult.create(qKeyC, "Bar", Period.createRange(300, 400))); cache.writeThrough("master", 100, qKeyD, "World"); cache.writeThrough("master", 200, qKeyD, "Foo"); cache.cache("master", GetResult.create(qKeyD, "Bar", Period.createRange(300, 400))); cache.rollbackToTimestamp(0); } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= private static ChronoDBCache createCacheOfSize(final int size) { checkArgument(size > 0, "Precondition violation - argument 'size' must be > 0!"); final MosaicCache mosaicCache = new MosaicCache(size); // we don't use the mosaic cache directly. Instead, we wrap it in a delegating proxy which will // assert that all cache invariants are valid before and after every method call. ChronoDBCache invariantCheckingProxy = TestUtils.createProxy(ChronoDBCache.class, (self, method, args) -> { System.out.println("Before"); assertCacheInvariants(mosaicCache); Object result = method.invoke(mosaicCache, args); System.out.println("After"); assertCacheInvariants(mosaicCache); return result; }); return invariantCheckingProxy; } private static void assertCacheInvariants(final MosaicCache cache) { System.out.println("CACHE VALIDATION"); System.out.println("\tMax Size: " + cache.maxSize()); System.out.println("\tCurrent Size: " + cache.size()); System.out.println("\tComputed Size: " + cache.computedSize()); System.out.println("\tRow Count: " + cache.rowCount()); System.out.println("\tListener Count: " + cache.lruListenerCount()); int maxSize = cache.maxSize(); int size = cache.size(); int compSize = cache.computedSize(); int rowCount = cache.rowCount(); int listeners = cache.lruListenerCount(); if (maxSize > 0) { assertTrue(size <= maxSize); } assertEquals(compSize, size); assertTrue(rowCount <= compSize); assertEquals(rowCount, listeners); } }
9,037
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryCacheTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/cache/query/QueryCacheTest.java
package org.chronos.chronodb.test.cases.cache.query; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.ChronoDBTransaction; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.index.IndexManagerInternal; import org.chronos.chronodb.internal.impl.index.querycache.ChronoIndexQueryCache; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.chronodb.test.base.InstantiateChronosWith; import org.chronos.chronodb.test.cases.util.model.payload.NamedPayloadNameIndexer; import org.chronos.common.test.junit.categories.IntegrationTest; import org.chronos.common.test.utils.NamedPayload; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class QueryCacheTest extends AllChronoDBBackendsTest { @Test @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true") @InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "10") public void cachingQueriesWorks() { ChronoDB db = this.getChronoDB(); db.getIndexManager().createIndex() .withName("name") .withIndexer(new NamedPayloadNameIndexer()) .onMaster() .acrossAllTimestamps() .build(); db.getIndexManager().reindexAll(); ChronoDBTransaction tx = db.tx(); tx.put("np1", NamedPayload.create1KB("Hello")); tx.put("np2", NamedPayload.create1KB("World")); tx.put("np3", NamedPayload.create1KB("Foo")); tx.put("np4", NamedPayload.create1KB("Bar")); tx.put("np5", NamedPayload.create1KB("Baz")); tx.commit(); // get the query cache instance IndexManagerInternal indexManager = (IndexManagerInternal) db.getIndexManager(); ChronoIndexQueryCache queryCache = indexManager.getIndexQueryCache(); // make sure that the query cache is in place assertNotNull(queryCache); // make sure that the cache is configured to record statistics assertNotNull(queryCache.getStats()); // initially, the cache stats should be empty assertEquals(0, queryCache.getStats().hitCount()); assertEquals(0, queryCache.getStats().missCount()); // run the first query Set<QualifiedKey> set = tx.find().inDefaultKeyspace().where("name").contains("o").getKeysAsSet(); assertThat(set, containsInAnyOrder( QualifiedKey.createInDefaultKeyspace("np1"), QualifiedKey.createInDefaultKeyspace("np2"), QualifiedKey.createInDefaultKeyspace("np3") ) ); // the first query should result in a cache miss assertEquals(0, queryCache.getStats().hitCount()); assertEquals(1, queryCache.getStats().missCount()); // run it again Set<QualifiedKey> set2 = tx.find().inDefaultKeyspace().where("name").contains("o").getKeysAsSet(); // the second query should result in a cache hit assertEquals(1, queryCache.getStats().hitCount()); assertEquals(1, queryCache.getStats().missCount()); // assert that the sets are the same assertEquals(set, set2); Set<String> keys = set.stream().map(QualifiedKey::getKey).collect(Collectors.toSet()); assertEquals(3, keys.size()); assertTrue(keys.contains("np1")); // hell[o] assertTrue(keys.contains("np2")); // w[o]rld assertTrue(keys.contains("np3")); // f[o]o } }
3,831
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UsageRegistryTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/cache/util/lru/UsageRegistryTest.java
package org.chronos.chronodb.test.cases.cache.util.lru; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.chronos.chronodb.api.key.QualifiedKey; import org.chronos.chronodb.internal.api.GetResult; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.impl.cache.util.lru.DefaultUsageRegistry; import org.chronos.chronodb.internal.impl.cache.util.lru.RangedGetResultUsageRegistry; import org.chronos.chronodb.internal.impl.cache.util.lru.UsageRegistry; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; @Category(UnitTest.class) public class UsageRegistryTest extends ChronoDBUnitTest { @Test public void canCreateDefaultUsageRegistry() { UsageRegistry<Integer> registry = new DefaultUsageRegistry<Integer>((e) -> e); assertNotNull(registry); } @Test public void registeringUsagesWorks() { UsageRegistry<Integer> registry = new DefaultUsageRegistry<Integer>((e) -> e); assertNotNull(registry); registry.registerUsage(1); registry.registerUsage(2); registry.registerUsage(3); registry.registerUsage(4); registry.registerUsage(3); registry.registerUsage(2); registry.registerUsage(1); assertEquals(4, registry.sizeInElements()); } @Test public void removingLeastRecentlyUsedElementWorks() { UsageRegistry<Integer> registry = new DefaultUsageRegistry<Integer>((e) -> e); assertNotNull(registry); // do some registration stuff registry.registerUsage(1); this.sleep(1); registry.registerUsage(2); this.sleep(1); registry.registerUsage(3); this.sleep(1); registry.registerUsage(4); this.sleep(1); registry.registerUsage(3); this.sleep(1); registry.registerUsage(2); this.sleep(1); registry.registerUsage(1); // create the evict listener and attach it AssertElementsRemovedListener<Integer> listener = new AssertElementsRemovedListener<>(4, 3, 2, 1); registry.addLeastRecentlyUsedRemoveListenerToAnyTopic(listener); // clear the registry by removing the least recently used element, one at a time while (registry.isEmpty() == false) { registry.removeLeastRecentlyUsedElement(); } // assert that the elements have been removed in the correct order listener.assertAllExpectedElementsRemoved(); } @Test public void removingLeastRecentlyUsedElementsUntilSizeIsReachedWorks() { UsageRegistry<Integer> registry = new DefaultUsageRegistry<Integer>((e) -> e); assertNotNull(registry); // do some registration stuff registry.registerUsage(1); this.sleep(1); registry.registerUsage(2); this.sleep(1); registry.registerUsage(3); this.sleep(1); registry.registerUsage(4); this.sleep(1); registry.registerUsage(3); this.sleep(1); registry.registerUsage(2); this.sleep(1); registry.registerUsage(1); // create the evict listener and attach it AssertElementsRemovedListener<Integer> listener = new AssertElementsRemovedListener<>(4, 3); registry.addLeastRecentlyUsedRemoveListenerToAnyTopic(listener); // clear the registry by removing the least recently used element, one at a time registry.removeLeastRecentlyUsedUntil(() -> registry.sizeInElements() <= 2); // assert that the elements have been removed in the correct order listener.assertAllExpectedElementsRemoved(); } @Test public void removingNonExistingElementsDoesntCrash() { UsageRegistry<Integer> registry = new DefaultUsageRegistry<Integer>((e) -> e); assertNotNull(registry); registry.removeLeastRecentlyUsedElement(); assertEquals(0, registry.sizeInElements()); } @Test public void topicBasedListenersOnlyReceiveNotificationsOnTheirTopic() { UsageRegistry<GetResult<?>> registry = new RangedGetResultUsageRegistry(); assertNotNull(registry); // prepare some keys (= topics) QualifiedKey qKey1 = QualifiedKey.createInDefaultKeyspace("Test1"); QualifiedKey qKey2 = QualifiedKey.createInDefaultKeyspace("Test2"); QualifiedKey qKey3 = QualifiedKey.createInDefaultKeyspace("Test3"); // prepare some values GetResult<?> entry1 = GetResult.create(qKey1, "Hello", Period.createRange(100, 200)); GetResult<?> entry2 = GetResult.create(qKey2, "World", Period.createRange(100, 200)); GetResult<?> entry3 = GetResult.create(qKey3, "Foo", Period.createRange(100, 200)); // add the values to the registry (most recently used = entry1, least recently used = entry3) registry.registerUsage(entry3); registry.registerUsage(entry2); registry.registerUsage(entry1); // add the remove listeners AssertElementsRemovedListener<GetResult<?>> globalListener = new AssertElementsRemovedListener<>(entry3, entry2); AssertElementsRemovedListener<GetResult<?>> qKey2Listener = new AssertElementsRemovedListener<>(entry2); AssertElementsRemovedListener<GetResult<?>> qKey1Listener = new AssertElementsRemovedListener<>(); registry.addLeastRecentlyUsedRemoveListenerToAnyTopic(globalListener); registry.addLeastRecentlyUsedRemoveListener(qKey2, qKey2Listener); registry.addLeastRecentlyUsedRemoveListener(qKey1, qKey1Listener); registry.removeLeastRecentlyUsedUntil(() -> registry.sizeInElements() <= 1); // now, our global listener should have received both remove calls globalListener.assertAllExpectedElementsRemoved(); // in contrast, our "qKey2"-topic listener should have received only one call qKey2Listener.assertAllExpectedElementsRemoved(); // ... and finally, our "qKey1"-topic listener should have received no calls at all qKey1Listener.assertAllExpectedElementsRemoved(); } @Test public void globalListenersReceiveNotificationsOnAllTopics() { } @Test public void concurrentAccessWorks() { UsageRegistry<Integer> registry = new DefaultUsageRegistry<Integer>((e) -> e); assertNotNull(registry); ElementRemoveCountListener<Integer> listener = new ElementRemoveCountListener<>(); registry.addLeastRecentlyUsedRemoveListenerToAnyTopic(listener); int registrationRepeats = 100; Runnable registrationWorker = () -> { int round = 0; while (round < registrationRepeats) { int value = round % 100; registry.registerUsage(value); long wait = Math.round(Math.random() * 5); this.sleep(wait); round++; } }; Runnable lruRemovalWorker = () -> { while (true) { registry.removeLeastRecentlyUsedUntil(() -> registry.sizeInElements() <= 20); try { Thread.sleep(5); } catch (InterruptedException e) { return; } } }; int registrationWorkerThreadCount = 30; Thread lruRemovalWorkerThread = new Thread(lruRemovalWorker); lruRemovalWorkerThread.start(); Set<Thread> registrationWorkerThreads = Sets.newHashSet(); for (int i = 0; i < registrationWorkerThreadCount; i++) { Thread thread = new Thread(registrationWorker); registrationWorkerThreads.add(thread); thread.start(); } // wait until the add workers are done for (Thread worker : registrationWorkerThreads) { try { worker.join(); } catch (InterruptedException e) { e.printStackTrace(); } } // stop the cleanup worker lruRemovalWorkerThread.interrupt(); try { lruRemovalWorkerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } registry.removeLeastRecentlyUsedUntil(() -> registry.sizeInElements() <= 20); // assert that the registry has at most 20 elements assertTrue(20 >= registry.sizeInElements()); // assert that removals indeed have happened assertTrue(listener.getRemoveCallCount() > 0); } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== private static class AssertElementsRemovedListener<T> implements UsageRegistry.RemoveListener<T> { private List<T> elementsToBeRemoved; @SafeVarargs public AssertElementsRemovedListener(final T... elementsToBeRemoved) { this.elementsToBeRemoved = Lists.newArrayList(elementsToBeRemoved); } @Override public void objectRemoved(final Object topic, final T element) { if (this.elementsToBeRemoved.isEmpty()) { fail("No further elements should have been removed, but element '" + element + "' was removed!"); } Object elementToBeRemoved = this.elementsToBeRemoved.get(0); if (elementToBeRemoved.equals(element) == false) { fail("Element '" + elementToBeRemoved + "' should have been removed next, but '" + element + "' was removed instead!"); } this.elementsToBeRemoved.remove(0); } public boolean areAllExpectedElementsRemoved() { return this.elementsToBeRemoved.isEmpty(); } public void assertAllExpectedElementsRemoved() { assertTrue("All elements should have been removed, but '" + this.elementsToBeRemoved + "' have not yet been removed!", this.areAllExpectedElementsRemoved()); } } private static class ElementRemoveCountListener<T> implements UsageRegistry.RemoveListener<T> { private AtomicInteger removeCalls = new AtomicInteger(0); @Override public void objectRemoved(final Object topic, final T element) { this.removeCalls.incrementAndGet(); } public int getRemoveCallCount() { return this.removeCalls.get(); } } }
10,788
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBCreationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/builder/ChronoDBCreationTest.java
package org.chronos.chronodb.test.cases.builder; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.test.base.AllChronoDBBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoDBCreationTest extends AllChronoDBBackendsTest { @Test public void dbCreationWorks() { ChronoDB chronoDB = this.getChronoDB(); assertNotNull("Failed to instantiate ChronoDB on Backend '" + this.getChronoBackendName() + "'!", chronoDB); } }
652
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoDBConfigurationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/builder/ChronoDBConfigurationTest.java
package org.chronos.chronodb.test.cases.builder; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.chronodb.internal.api.cache.ChronoDBCache; import org.chronos.chronodb.internal.impl.cache.bogus.ChronoDBBogusCache; import org.chronos.chronodb.internal.impl.cache.headfirst.HeadFirstCache; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.exceptions.ChronosConfigurationException; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.File; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoDBConfigurationTest extends ChronoDBUnitTest { @Test public void canCreateChronoDbWithBuilder() { ChronoDB db = ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER).build(); assertNotNull(db); } @Test public void canEnableCachingWithInMemoryBuilder() { ChronoDB db = ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER).withLruCacheOfSize(1000).build(); assertNotNull(db); try { this.assertHasCache(db); } finally { db.close(); } } @Test public void canEnableCachingViaPropertiesFile() { File propertiesFile = this.getSrcTestResourcesFile("chronoCacheConfigTest_correct.properties"); ChronoDB chronoDB = ChronoDB.FACTORY.create().fromPropertiesFile(propertiesFile).build(); assertNotNull(chronoDB); try { this.assertHasCache(chronoDB); } finally { chronoDB.close(); } } @Test public void cacheMaxSizeSettingIsRequiredIfCachingIsEnabled() { File propertiesFile = this.getSrcTestResourcesFile("chronoCacheConfigTest_wrong.properties"); try { ChronoDB.FACTORY.create().fromPropertiesFile(propertiesFile).build(); fail("Managed to create cached ChronoDB instance without specifying the Max Cache Size!"); } catch (ChronosConfigurationException expected) { // pass } } @Test public void canConfigureHeadFirstCache() { ChronoDB db = ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER) .withProperty(ChronoDBConfiguration.CACHING_ENABLED,"true") .withProperty(ChronoDBConfiguration.CACHE_TYPE,"head-first") .withProperty(ChronoDBConfiguration.CACHE_MAX_SIZE, "100") .withProperty(ChronoDBConfiguration.CACHE_HEADFIRST_PREFERRED_BRANCH, "master") .withProperty(ChronoDBConfiguration.CACHE_HEADFIRST_PREFERRED_KEYSPACE, "vertex") .build(); ChronoDBCache cache = db.getCache(); assertTrue(cache instanceof HeadFirstCache); HeadFirstCache hfc = (HeadFirstCache) cache; assertEquals("master", hfc.getPreferredBranch()); assertEquals("vertex", hfc.getPreferredKeyspace()); } private void assertHasCache(final ChronoDB db) { // make sure that we have a cache assertNotNull(db.getCache()); // make sure it's not a bogus cache assertFalse(db.getCache() instanceof ChronoDBBogusCache); } }
3,422
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ReflectiveDoubleIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/ReflectiveDoubleIndexer.java
package org.chronos.chronodb.test.cases.util; import com.google.common.collect.Sets; import org.chronos.chronodb.api.indexing.DoubleIndexer; import org.chronos.common.util.ReflectionUtils; import java.util.Set; public class ReflectiveDoubleIndexer extends ReflectiveIndexer<Double> implements DoubleIndexer { public ReflectiveDoubleIndexer() { // default constructor for serialization } public ReflectiveDoubleIndexer(final Class<?> clazz, final String fieldName) { super(clazz, fieldName); } @Override public Set<Double> getIndexValues(final Object object) { Object fieldValue = this.getFieldValue(object); Set<Double> resultSet = Sets.newHashSet(); if (fieldValue instanceof Iterable) { for (Object element : (Iterable<?>) fieldValue) { if (ReflectionUtils.isDoubleCompatible(element)) { resultSet.add(ReflectionUtils.asDouble(element)); } } } else { if (ReflectionUtils.isDoubleCompatible(fieldValue)) { resultSet.add(ReflectionUtils.asDouble(fieldValue)); } } return resultSet; } }
1,200
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ReflectiveStringIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/ReflectiveStringIndexer.java
package org.chronos.chronodb.test.cases.util; import com.google.common.collect.Sets; import org.chronos.chronodb.api.indexing.StringIndexer; import java.util.Set; public class ReflectiveStringIndexer extends ReflectiveIndexer<String> implements StringIndexer { protected ReflectiveStringIndexer() { // default constructor for serialization } public ReflectiveStringIndexer(final Class<?> clazz, final String fieldName) { super(clazz, fieldName); } @Override public Set<String> getIndexValues(final Object object) { Object fieldValue = this.getFieldValue(object); Set<String> resultSet = Sets.newHashSet(); if (fieldValue instanceof Iterable) { for (Object element : (Iterable<?>) fieldValue) { if (element instanceof String) { resultSet.add((String) element); } } } else { if (fieldValue instanceof String) { resultSet.add((String) fieldValue); } } return resultSet; } }
1,085
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IteratorUtilsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/IteratorUtilsTest.java
package org.chronos.chronodb.test.cases.util; import com.google.common.collect.Lists; import org.chronos.chronodb.internal.util.IteratorUtils; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Iterator; import java.util.List; import static org.junit.Assert.*; @Category(UnitTest.class) public class IteratorUtilsTest extends ChronoDBUnitTest { @Test public void uniqueIteratorWorks() { List<Integer> values = Lists.newArrayList(1, 2, 3, 1, 3, 2, 4, 5, 5, 5, 2, 1, 3); Iterator<Integer> iterator = values.iterator(); iterator = IteratorUtils.unique(iterator); List<Integer> newValues = Lists.newArrayList(iterator); assertEquals(5, newValues.size()); assertTrue(newValues.contains(1)); assertTrue(newValues.contains(2)); assertTrue(newValues.contains(3)); assertTrue(newValues.contains(4)); assertTrue(newValues.contains(5)); } }
1,082
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TemporalKeyComparatorsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/TemporalKeyComparatorsTest.java
package org.chronos.chronodb.test.cases.util; import com.google.common.collect.Lists; import org.chronos.chronodb.api.key.TemporalKey; import org.chronos.chronodb.test.base.ChronoDBUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.Collections; import java.util.Comparator; import java.util.List; import static org.junit.Assert.*; @Category(UnitTest.class) public class TemporalKeyComparatorsTest extends ChronoDBUnitTest { @Test public void comparingTemporalKeysByTimestampKeyspaceKeyWorks() { Comparator<TemporalKey> comparator = TemporalKey.Comparators.BY_TIME_KEYSPACE_KEY; TemporalKey tk1 = TemporalKey.create(1000, "default", "test"); TemporalKey tk2 = TemporalKey.create(900, "default", "test"); TemporalKey tk3 = TemporalKey.create(1100, "default", "test"); TemporalKey tk4 = TemporalKey.create(1000, "mykeyspace", "test"); TemporalKey tk5 = TemporalKey.create(900, "mykeyspace", "test"); TemporalKey tk6 = TemporalKey.create(1100, "mykeyspace", "test"); TemporalKey tk7 = TemporalKey.create(1000, "default", "foo"); TemporalKey tk8 = TemporalKey.create(1000, "default", "a"); TemporalKey tk9 = TemporalKey.create(1000, "default", "x"); List<TemporalKey> list = Lists.newArrayList(); list.add(tk1); list.add(tk2); list.add(tk3); list.add(tk4); list.add(tk5); list.add(tk6); list.add(tk7); list.add(tk8); list.add(tk9); Collections.sort(list, comparator); assertEquals(Lists.newArrayList(tk2, tk5, tk8, tk7, tk1, tk9, tk4, tk3, tk6), list); } }
1,755
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
KillSwitchCollection.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/KillSwitchCollection.java
package org.chronos.chronodb.test.cases.util; import org.chronos.chronodb.api.ChronoDBTransaction; import java.util.function.Consumer; public class KillSwitchCollection { private Consumer<ChronoDBTransaction> onBeforePrimaryIndexUpdate; private Consumer<ChronoDBTransaction> onBeforeSecondaryIndexUpdate; private Consumer<ChronoDBTransaction> onBeforeMetadataUpdate; private Consumer<ChronoDBTransaction> onBeforeCacheUpdate; private Consumer<ChronoDBTransaction> onBeforeNowTimestampUpdate; private Consumer<ChronoDBTransaction> onBeforeTransactionCommitted; public Consumer<ChronoDBTransaction> getOnBeforePrimaryIndexUpdate() { return this.onBeforePrimaryIndexUpdate; } public void setOnBeforePrimaryIndexUpdate(final Consumer<ChronoDBTransaction> onBeforePrimaryIndexUpdate) { this.onBeforePrimaryIndexUpdate = onBeforePrimaryIndexUpdate; } public Consumer<ChronoDBTransaction> getOnBeforeSecondaryIndexUpdate() { return this.onBeforeSecondaryIndexUpdate; } public void setOnBeforeSecondaryIndexUpdate(final Consumer<ChronoDBTransaction> onBeforeSecondaryIndexUpdate) { this.onBeforeSecondaryIndexUpdate = onBeforeSecondaryIndexUpdate; } public Consumer<ChronoDBTransaction> getOnBeforeMetadataUpdate() { return this.onBeforeMetadataUpdate; } public void setOnBeforeMetadataUpdate(final Consumer<ChronoDBTransaction> onBeforeMetadataUpdate) { this.onBeforeMetadataUpdate = onBeforeMetadataUpdate; } public Consumer<ChronoDBTransaction> getOnBeforeCacheUpdate() { return this.onBeforeCacheUpdate; } public void setOnBeforeCacheUpdate(final Consumer<ChronoDBTransaction> onBeforeCacheUpdate) { this.onBeforeCacheUpdate = onBeforeCacheUpdate; } public Consumer<ChronoDBTransaction> getOnBeforeNowTimestampUpdate() { return this.onBeforeNowTimestampUpdate; } public void setOnBeforeNowTimestampUpdate(final Consumer<ChronoDBTransaction> onBeforeNowTimestampUpdate) { this.onBeforeNowTimestampUpdate = onBeforeNowTimestampUpdate; } public Consumer<ChronoDBTransaction> getOnBeforeTransactionCommitted() { return this.onBeforeTransactionCommitted; } public void setOnBeforeTransactionCommitted(final Consumer<ChronoDBTransaction> onBeforeTransactionCommitted) { this.onBeforeTransactionCommitted = onBeforeTransactionCommitted; } }
2,462
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ReflectiveIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/ReflectiveIndexer.java
package org.chronos.chronodb.test.cases.util; import org.chronos.chronodb.api.indexing.Indexer; import org.chronos.common.util.ReflectionUtils; import java.lang.reflect.Field; import java.util.Objects; import static com.google.common.base.Preconditions.*; public abstract class ReflectiveIndexer<T> implements Indexer<T> { private Class<?> clazz; private String fieldName; protected ReflectiveIndexer() { // default constructor for serialization } public ReflectiveIndexer(final Class<?> clazz, final String fieldName) { checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!"); checkNotNull(fieldName, "Precondition violation - argument 'fieldName' must not be NULL!"); this.clazz = clazz; this.fieldName = fieldName; } @Override public boolean canIndex(final Object object) { if (object == null) { return false; } return this.clazz.isInstance(object); } protected Object getFieldValue(final Object object) { if (object == null) { return null; } try { Field field = ReflectionUtils.getDeclaredField(object.getClass(), this.fieldName); field.setAccessible(true); return field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException("Failed to access field '" + this.fieldName + "' in instance of class '" + object.getClass().getName() + "'!", e); } } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ReflectiveIndexer<?> that = (ReflectiveIndexer<?>) o; if (!Objects.equals(clazz, that.clazz)) return false; return Objects.equals(fieldName, that.fieldName); } @Override public int hashCode() { int result = clazz != null ? clazz.hashCode() : 0; result = 31 * result + (fieldName != null ? fieldName.hashCode() : 0); return result; } }
2,158
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ReflectiveLongIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/ReflectiveLongIndexer.java
package org.chronos.chronodb.test.cases.util; import com.google.common.collect.Sets; import org.chronos.chronodb.api.indexing.LongIndexer; import org.chronos.common.util.ReflectionUtils; import java.util.Set; public class ReflectiveLongIndexer extends ReflectiveIndexer<Long> implements LongIndexer { public ReflectiveLongIndexer() { // default constructor for serialization } public ReflectiveLongIndexer(final Class<?> clazz, final String fieldName) { super(clazz, fieldName); } @Override public Set<Long> getIndexValues(final Object object) { Object fieldValue = this.getFieldValue(object); Set<Long> resultSet = Sets.newHashSet(); if (fieldValue instanceof Iterable) { for (Object element : (Iterable<?>) fieldValue) { if (ReflectionUtils.isLongCompatible(element)) { resultSet.add(ReflectionUtils.asLong(element)); } } } else { if (ReflectionUtils.isLongCompatible(fieldValue)) { resultSet.add(ReflectionUtils.asLong(fieldValue)); } } return resultSet; } }
1,176
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NamedPayloadNameIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/model/payload/NamedPayloadNameIndexer.java
package org.chronos.chronodb.test.cases.util.model.payload; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.common.test.utils.NamedPayload; import java.util.Collections; import java.util.Set; public class NamedPayloadNameIndexer implements StringIndexer { private final boolean toLowerCase; public NamedPayloadNameIndexer() { this(false); } public NamedPayloadNameIndexer(final boolean toLowerCase) { this.toLowerCase = toLowerCase; } @Override public boolean canIndex(final Object object) { return object != null && object instanceof NamedPayload; } @Override public Set<String> getIndexValues(final Object object) { NamedPayload payload = (NamedPayload) object; String name = payload.getName(); if (this.toLowerCase) { return Collections.singleton(name.toLowerCase()); } else { return Collections.singleton(name); } } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NamedPayloadNameIndexer that = (NamedPayloadNameIndexer) o; return toLowerCase == that.toLowerCase; } @Override public int hashCode() { return (toLowerCase ? 1 : 0); } }
1,385
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
FirstNameIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/model/person/FirstNameIndexer.java
package org.chronos.chronodb.test.cases.util.model.person; import org.chronos.common.test.utils.model.person.Person; import java.util.Collections; import java.util.Set; public class FirstNameIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override protected Set<String> getIndexValuesInternal(final Person person) { return Collections.singleton(person.getFirstName()); } }
566
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PersonIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/model/person/PersonIndexer.java
package org.chronos.chronodb.test.cases.util.model.person; import org.chronos.chronodb.api.indexing.StringIndexer; import org.chronos.common.test.utils.model.person.Person; import java.util.Set; public abstract class PersonIndexer implements StringIndexer { // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== public static FirstNameIndexer firstName() { return new FirstNameIndexer(); } public static LastNameIndexer lastName() { return new LastNameIndexer(); } public static FavoriteColorIndexer favoriteColor() { return new FavoriteColorIndexer(); } public static PetsIndexer pets() { return new PetsIndexer(); } public static HobbiesIndexer hobbies() { return new HobbiesIndexer(); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public boolean canIndex(final Object object) { return object instanceof Person; } @Override public Set<String> getIndexValues(final Object object) { return this.getIndexValuesInternal((Person) object); } // ===================================================================================================================== // ABSTRACT METHOD DECLARATIONS // ===================================================================================================================== protected abstract Set<String> getIndexValuesInternal(Person person); }
1,895
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
HobbiesIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/model/person/HobbiesIndexer.java
package org.chronos.chronodb.test.cases.util.model.person; import org.chronos.common.test.utils.model.person.Person; import java.util.Collections; import java.util.Set; public class HobbiesIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override protected Set<String> getIndexValuesInternal(final Person person) { return Collections.unmodifiableSet(person.getHobbies()); } }
568
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PetsIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/model/person/PetsIndexer.java
package org.chronos.chronodb.test.cases.util.model.person; import org.chronos.common.test.utils.model.person.Person; import java.util.Collections; import java.util.Set; public class PetsIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override protected Set<String> getIndexValuesInternal(final Person person) { return Collections.unmodifiableSet(person.getPets()); } }
561
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
LastNameIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/model/person/LastNameIndexer.java
package org.chronos.chronodb.test.cases.util.model.person; import org.chronos.common.test.utils.model.person.Person; import java.util.Collections; import java.util.Set; public class LastNameIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override protected Set<String> getIndexValuesInternal(final Person person) { return Collections.singleton(person.getLastName()); } }
564
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
FavoriteColorIndexer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/cases/util/model/person/FavoriteColorIndexer.java
package org.chronos.chronodb.test.cases.util.model.person; import org.chronos.common.test.utils.model.person.Person; import java.util.Collections; import java.util.Set; public class FavoriteColorIndexer extends PersonIndexer { @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(final Object obj) { return super.equals(obj); } @Override protected Set<String> getIndexValuesInternal(final Person person) { return Collections.singleton(person.getFavoriteColor()); } }
573
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AllBackendsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/base/AllBackendsTest.java
package org.chronos.chronodb.test.base; import com.google.common.collect.Maps; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.builder.database.spi.ChronoDBBackendProvider; import org.chronos.chronodb.api.builder.database.spi.TestSuitePlugin; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.impl.base.builder.database.service.ChronoDBBackendProviderService; import org.chronos.common.test.ChronosUnitTest; import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; import static org.hamcrest.Matchers.*; import static org.junit.Assume.*; @RunWith(Parameterized.class) public abstract class AllBackendsTest extends ChronosUnitTest { // ===================================================================================================================== // JUNIT PARAMETERIZED TEST DATA // ===================================================================================================================== @Parameters(name = "Using {0}") public static Collection<Object[]> data() { return ChronoDBBackendProviderService.getInstance().getAvailableBuilders().stream() .map(ChronoDBBackendProvider::getBackendName) .map(name -> new Object[]{name}) .collect(Collectors.toSet()); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== @Parameter public String backend; private TestSuitePlugin backendTestSuitePlugin; // ===================================================================================================================== // API // ===================================================================================================================== protected String getChronoBackendName() { return this.backend; } protected TestSuitePlugin getBackendTestSuitePlugin(String backend){ checkNotNull(backend, "Precondition violation - argument 'backend' must not be NULL!"); if(backend.equals(this.backend)){ this.getBackendTestSuitePlugin(); } return this.loadTestSuitePlugin(backend); } protected TestSuitePlugin getBackendTestSuitePlugin(){ if(this.backend == null){ throw new IllegalStateException("There is no current backend! Did the test start?"); } if(this.backendTestSuitePlugin == null){ this.backendTestSuitePlugin = this.loadTestSuitePlugin(this.backend); } return this.backendTestSuitePlugin; } private TestSuitePlugin loadTestSuitePlugin(String backend){ ChronoDBBackendProvider provider = ChronoDBBackendProviderService.getInstance().getBackendProvider(backend); TestSuitePlugin testSuitePlugin = provider.getTestSuitePlugin(); assumeThat("Backend Provider [" + backend + "] does not support the test suite plug-in!", testSuitePlugin, is(notNullValue())); return testSuitePlugin; } protected Configuration createChronosConfiguration(String backend){ checkNotNull(backend, "Precondition violation - argument 'backend' must not be NULL!"); TestSuitePlugin testSuitePlugin = this.getBackendTestSuitePlugin(backend); Configuration configuration = testSuitePlugin.createBasicTestConfiguration(this.getCurrentTestMethod(), this.getTestDirectory()); if(configuration == null){ throw new IllegalStateException("Backend Provider [" + backend + "] failed to create a new configuration!"); } this.applyExtraTestMethodProperties(configuration); return configuration; } // ===================================================================================================================== // JUNIT CONTROL // ===================================================================================================================== @Before public void onBeforeTest() { this.backendTestSuitePlugin = null; checkOptOutFromCurrentTest(); TestSuitePlugin plugin = this.getBackendTestSuitePlugin(); plugin.onBeforeTest(this.getCurrentTestMethod().getDeclaringClass(), this.getCurrentTestMethod(), this.getTestDirectory()); } @After public void onAfterTest(){ this.getBackendTestSuitePlugin().onAfterTest(this.getCurrentTestMethod().getDeclaringClass(), this.getCurrentTestMethod(), this.getTestDirectory()); this.backendTestSuitePlugin = null; this.backend = null; } private void checkOptOutFromCurrentTest() { DontRunWithBackend classAnnotation = this.getClass().getAnnotation(DontRunWithBackend.class); if (classAnnotation != null) { // we skip at least one backend; ensure that we are not running on that particular one for (String backend : classAnnotation.value()) { // "assume" will cause a test to be skipped when the condition applies Assume.assumeFalse(backend.equals(this.backend)); } } // check if the method is annotated Method testMethod = this.getCurrentTestMethod(); DontRunWithBackend methodAnnotation = testMethod.getAnnotation(DontRunWithBackend.class); if(methodAnnotation!= null){ for(String backend : methodAnnotation.value()){ Assume.assumeFalse(backend.equals(this.backend)); } } } // ===================================================================================================================== // INTERNAL HELPER MTHODS // ===================================================================================================================== public Map<String, String> getExtraTestMethodProperties() { Method testMethod = this.getCurrentTestMethod(); Map<String, String> properties = Maps.newHashMap(); if (testMethod == null) { return properties; } InstantiateChronosWith[] annotations = testMethod.getAnnotationsByType(InstantiateChronosWith.class); for (InstantiateChronosWith annotation : annotations) { String property = annotation.property(); String value = annotation.value(); properties.put(property, value); } return properties; } protected void applyExtraTestMethodProperties(final Configuration configuration) { Map<String, String> testMethodProperties = this.getExtraTestMethodProperties(); for (Entry<String, String> entry : testMethodProperties.entrySet()) { String property = entry.getKey(); String value = entry.getValue(); configuration.setProperty(property, value); } // ALWAYS apply the debug property configuration.setProperty(ChronoDBConfiguration.DEBUG, "true"); // ALWAYS disable MBeans for testing configuration.setProperty(ChronoDBConfiguration.MBEANS_ENABLED, "false"); } // ===================================================================================================================== // INNER CLASSES // ===================================================================================================================== @Documented @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public static @interface DontRunWithBackend { public String[] value(); } }
7,599
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TestMethodExtraPropertiesTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.api/src/test/java/org/chronos/chronodb/test/base/TestMethodExtraPropertiesTest.java
package org.chronos.chronodb.test.base; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import org.chronos.chronodb.api.ChronoDB; import org.chronos.chronodb.api.conflict.ConflictResolutionStrategy; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronodb.internal.api.ChronoDBInternal; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; @Category(IntegrationTest.class) public class TestMethodExtraPropertiesTest extends AllChronoDBBackendsTest { @Test @InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE") public void addingExtraPropertiesWorks() { ChronoDB db = this.getChronoDB(); ChronoDBInternal dbInternal = (ChronoDBInternal) db; ChronoDBConfiguration configuration = dbInternal.getConfiguration(); assertThat(configuration.getConflictResolutionStrategy(), is(ConflictResolutionStrategy.OVERWRITE_WITH_SOURCE)); } }
1,066
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z