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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
PersonGenerator.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/utils/model/person/PersonGenerator.java | package org.chronos.common.test.utils.model.person;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.chronos.common.test.utils.TestUtils;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static com.google.common.base.Preconditions.*;
public class PersonGenerator {
private static final List<String> FIRST_NAMES;
private static final List<String> LAST_NAMES;
private static final List<String> COLORS = Lists.newArrayList("red", "green", "blue", "orange", "yellow");
private static final List<String> HOBBIES = Lists.newArrayList("reading", "tv", "cinema", "swimming", "skiing",
"gaming");
private static final List<String> PETS = Lists.newArrayList("cat", "dog", "fish", "horse", "mouse", "rat");
static {
List<String> firstNames = Collections.emptyList();
try {
firstNames = FileUtils.readLines(new File(PersonGenerator.class.getResource("/firstNames.txt").getFile()), Charsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
FIRST_NAMES = Collections.unmodifiableList(firstNames);
List<String> lastNames = Collections.emptyList();
try {
lastNames = FileUtils.readLines(new File(PersonGenerator.class.getResource("/lastNames.txt").getFile()), Charsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
LAST_NAMES = Collections.unmodifiableList(lastNames);
}
public static Person generateRandomPerson() {
Person person = new Person();
person.setFirstName(TestUtils.getRandomEntryOf(FIRST_NAMES));
person.setLastName(TestUtils.getRandomEntryOf(LAST_NAMES));
person.setFavoriteColor(TestUtils.getRandomEntryOf(COLORS));
int numberOfHobbies = TestUtils.randomBetween(0, 3);
int numberOfPets = TestUtils.randomBetween(0, 2);
person.getHobbies().addAll(TestUtils.getRandomUniqueEntriesOf(HOBBIES, numberOfHobbies));
person.getPets().addAll(TestUtils.getRandomUniqueEntriesOf(PETS, numberOfPets));
return person;
}
public static List<Person> generateRandomPersons(final int number) {
checkArgument(number > 0, "Precondition violation - argument 'number' must be positive!");
return IntStream.range(0, number).parallel().mapToObj(i -> generateRandomPerson()).collect(Collectors.toList());
}
}
| 2,559 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ExcludeCategories.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/junit/ExcludeCategories.java | package org.chronos.common.test.junit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcludeCategories {
Class<?>[] value();
}
| 328 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
SuiteIncludes.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/junit/SuiteIncludes.java | package org.chronos.common.test.junit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SuiteIncludes {
public Class<?>[] value();
}
| 333 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
SuitePackages.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/junit/SuitePackages.java | package org.chronos.common.test.junit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SuitePackages {
public String[] value();
}
| 331 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PackageSuite.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.common.testing/src/main/java/org/chronos/common/test/junit/PackageSuite.java | package org.chronos.common.test.junit;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.reflect.ClassPath;
import org.chronos.common.configuration.ChronosConfigurationUtil;
import org.junit.Test;
import org.junit.experimental.categories.Categories.ExcludeCategory;
import org.junit.experimental.categories.Category;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class PackageSuite extends Suite {
private static final Logger log = LoggerFactory.getLogger(PackageSuite.class);
public PackageSuite(final Class<?> suiteClass, final RunnerBuilder builder) throws InitializationError {
super(builder, suiteClass, getSuiteClasses(suiteClass));
}
public static Class<?>[] getSuiteClasses(final Class<?> suiteClass) throws InitializationError {
SuitePackages suitePackages = suiteClass.getAnnotation(SuitePackages.class);
if (suitePackages == null) {
throw new InitializationError(
"PackageSuite class '" + suiteClass.getName() + "' must declare @SuitePackages!");
}
String[] packages = suitePackages.value();
if (packages == null || packages.length == 0) {
throw new InitializationError("PackageSuite class '" + suiteClass.getName()
+ "' must declare at least one package in its @SuitePackages annotation!");
}
Set<Class<?>> allTestClasses = getClassesInPackages(packages);
allTestClasses.addAll(getExplicitSuiteClasses(suiteClass));
allTestClasses.addAll(getClassesFromIncludedSuiteClasses(suiteClass));
applySuiteClassesExcludeFilter(suiteClass, allTestClasses);
List<Class<?>> testClasses = Lists.newArrayList(allTestClasses);
Collections.sort(testClasses, (classA, classB) -> classA.getName().compareTo(classB.getName()));
return testClasses.toArray(new Class<?>[testClasses.size()]);
}
public static Set<Class<?>> getClassesInPackages(final String[] packageNames) {
Set<Class<?>> resultSet = Sets.newHashSet();
for (String packageName : packageNames) {
try {
ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
Set<Class<?>> topLevelClasses = classPath.getTopLevelClassesRecursive(packageName).stream()
.map(ci -> ci.load()).collect(Collectors.toSet());
resultSet.addAll(topLevelClasses);
} catch (IOException e) {
log.error("Failed to scan packages for classes!", e);
}
}
return resultSet;
}
private static Set<Class<?>> getExplicitSuiteClasses(final Class<?> suiteClass) {
Set<Class<?>> resultSet = Sets.newHashSet();
SuiteClasses suiteClasses = suiteClass.getAnnotation(SuiteClasses.class);
if (suiteClasses == null) {
// annotation not given, abort
return resultSet;
}
Class<?>[] explicitSuiteClasses = suiteClasses.value();
if (explicitSuiteClasses == null || explicitSuiteClasses.length < 1) {
// annotation contains no values, abort
return resultSet;
}
for (Class<?> explicitSuiteClass : explicitSuiteClasses) {
resultSet.add(explicitSuiteClass);
}
return resultSet;
}
private static Set<Class<?>> getClassesFromIncludedSuiteClasses(final Class<?> suiteClass)
throws InitializationError {
Set<Class<?>> resultSet = Sets.newHashSet();
SuiteIncludes suiteIncludes = suiteClass.getAnnotation(SuiteIncludes.class);
if (suiteIncludes == null) {
// annotation not present, abort
return resultSet;
}
Class<?>[] includedSuiteClasses = suiteIncludes.value();
if (includedSuiteClasses == null || includedSuiteClasses.length < 1) {
// no value present, abort
return resultSet;
}
for (Class<?> includedSuiteClass : includedSuiteClasses) {
Class<?>[] suiteClasses = getSuiteClasses(includedSuiteClass);
Set<Class<?>> suiteClassesSet = Sets.newHashSet(suiteClasses);
resultSet.addAll(suiteClassesSet);
}
return resultSet;
}
private static void applySuiteClassesExcludeFilter(final Class<?> suiteClass, final Set<Class<?>> testClasses) {
// remove all abstract classes and interfaces
testClasses.removeIf(clazz -> clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()));
// remove all classes that have no test methods
testClasses.removeIf(clazz -> hasTestMethod(clazz) == false);
// apply the categories filter
Set<Class<?>> excludedCategories = getExcludedCategories(suiteClass);
if (excludedCategories.isEmpty()) {
// no classes excluded
return;
}
Map<Class<?>, Set<Class<?>>> testClassesByCategory = getTestClassesByCategory(testClasses);
for (Class<?> excludedCategory : excludedCategories) {
Set<Class<?>> categoryTestClasses = testClassesByCategory.get(excludedCategory);
if (categoryTestClasses != null && categoryTestClasses.isEmpty() == false) {
testClasses.removeAll(categoryTestClasses);
}
}
}
private static Set<Class<?>> getExcludedCategories(final Class<?> suiteClass) {
Set<Class<?>> resultSet = Sets.newHashSet();
Set<Class<?>> excludedCategory = getClassesInExcludeCategoryAnnotation(suiteClass);
if (excludedCategory != null) {
resultSet.addAll(excludedCategory);
}
resultSet.addAll(getClassesInExcludeCategoriesAnnotation(suiteClass));
return resultSet;
}
private static Set<Class<?>> getClassesInExcludeCategoryAnnotation(final Class<?> suiteClass) {
ExcludeCategory excludeCategory = suiteClass.getAnnotation(ExcludeCategory.class);
if (excludeCategory == null) {
// annotation not present, abort
return null;
}
Class<?>[] excludedClasses = excludeCategory.value();
Set<Class<?>> classes = Sets.newHashSet(excludedClasses);
return classes;
}
private static Set<Class<?>> getClassesInExcludeCategoriesAnnotation(final Class<?> suiteClass) {
Set<Class<?>> resultSet = Sets.newHashSet();
ExcludeCategories excludeCategories = suiteClass.getAnnotation(ExcludeCategories.class);
if (excludeCategories == null) {
// annotation not present, abort
return resultSet;
}
Class<?>[] excludedCategories = excludeCategories.value();
if (excludedCategories.length < 1) {
// no annotation value given, abort
return resultSet;
}
resultSet.addAll(Sets.newHashSet(excludedCategories));
return resultSet;
}
private static Map<Class<?>, Set<Class<?>>> getTestClassesByCategory(final Set<Class<?>> testClasses) {
Map<Class<?>, Set<Class<?>>> testClassesByCategory = Maps.newHashMap();
for (Class<?> testClass : testClasses) {
Category categoryAnnotation = testClass.getAnnotation(Category.class);
if (categoryAnnotation == null) {
continue;
}
Class<?>[] testCategoryClasses = categoryAnnotation.value();
for (Class<?> categoryClass : testCategoryClasses) {
Set<Class<?>> categoryMembers = testClassesByCategory.get(categoryClass);
if (categoryMembers == null) {
categoryMembers = Sets.newHashSet();
testClassesByCategory.put(categoryClass, categoryMembers);
}
categoryMembers.add(testClass);
}
}
return testClassesByCategory;
}
private static boolean hasTestMethod(final Class<?> maybeTestClass) {
for (Method method : maybeTestClass.getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
return true;
}
}
return false;
}
}
| 8,581 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTestSuite.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/_suite/ChronoGraphTestSuite.java | package org.chronos.chronograph.test._suite;
import org.chronos.chronodb.test._suite.ChronoDBTestSuite;
import org.chronos.common.test.junit.ExcludeCategories;
import org.chronos.common.test.junit.PackageSuite;
import org.chronos.common.test.junit.SuiteIncludes;
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.chronograph.test.cases")
@SuiteIncludes(ChronoDBTestSuite.class)
@ExcludeCategories({PerformanceTest.class, SlowTest.class})
public class ChronoGraphTestSuite {
} | 799 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
InMemoryChronoGraphProvider.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/_gremlinsuite/InMemoryChronoGraphProvider.java | package org.chronos.chronograph.test._gremlinsuite;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.AbstractGraphProvider;
import org.apache.tinkerpop.gremlin.GraphProvider;
import org.apache.tinkerpop.gremlin.LoadGraphWith.GraphData;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.chronos.chronodb.inmemory.InMemoryChronoDB;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.impl.structure.graph.AbstractChronoElement;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoEdgeImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoGraphVariablesImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoProperty;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexProperty;
import org.chronos.chronograph.internal.impl.structure.graph.StandardChronoGraph;
import org.chronos.chronograph.internal.impl.structure.record2.EdgeRecord2;
import org.chronos.chronograph.internal.impl.structure.record2.EdgeTargetRecord2;
import org.chronos.chronograph.internal.impl.structure.record2.PropertyRecord2;
import org.chronos.chronograph.internal.impl.structure.record3.SimpleVertexPropertyRecord;
import org.chronos.chronograph.internal.impl.structure.record3.VertexPropertyRecord3;
import org.chronos.chronograph.internal.impl.structure.record3.VertexRecord3;
import java.util.Map;
import java.util.Set;
public class InMemoryChronoGraphProvider extends AbstractGraphProvider implements GraphProvider {
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName, final GraphData loadGraphWith) {
Map<String, Object> baseConfig = Maps.newHashMap();
baseConfig.put(Graph.GRAPH, ChronoGraph.class.getName());
baseConfig.put(ChronoDBConfiguration.STORAGE_BACKEND, InMemoryChronoDB.BACKEND_NAME);
baseConfig.put(ChronoDBConfiguration.MBEANS_ENABLED, false);
return baseConfig;
}
@Override
public void clear(final Graph graph, final Configuration configuration) {
if (graph == null) {
return;
}
ChronoGraph chronoGraph = (ChronoGraph) graph;
chronoGraph.close();
}
@Override
@SuppressWarnings("rawtypes")
public Set<Class> getImplementations() {
Set<Class> implementations = Sets.newHashSet();
implementations.add(StandardChronoGraph.class);
implementations.add(ChronoVertexImpl.class);
implementations.add(ChronoEdgeImpl.class);
implementations.add(AbstractChronoElement.class);
implementations.add(ChronoProperty.class);
implementations.add(ChronoVertexProperty.class);
implementations.add(ChronoGraphVariablesImpl.class);
implementations.add(VertexRecord3.class);
implementations.add(EdgeRecord2.class);
implementations.add(VertexPropertyRecord3.class);
implementations.add(SimpleVertexPropertyRecord.class);
implementations.add(PropertyRecord2.class);
implementations.add(EdgeTargetRecord2.class);
return implementations;
}
@Override
public Object convertId(final Object id, final Class<? extends Element> c) {
return String.valueOf(id);
}
}
| 3,627 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
InMemoryChronoGraphProcessStandardTestSuite.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/_gremlinsuite/InMemoryChronoGraphProcessStandardTestSuite.java | package org.chronos.chronograph.test._gremlinsuite;
import org.apache.tinkerpop.gremlin.GraphProviderClass;
import org.apache.tinkerpop.gremlin.process.ProcessStandardSuite;
import org.apache.tinkerpop.gremlin.structure.StructureStandardSuite;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.junit.runner.RunWith;
// note: this class is NOT annotated with @Category(Suite.class) because, even though it technically is a suite,
// we do want Gradle to execute this class (whereas execution of other suites is always redundant). The reason
// is that the tests executed by this suite reside in a JAR file which is not scanned by gradle for test classes.
@RunWith(ProcessStandardSuite.class)
@GraphProviderClass(provider = InMemoryChronoGraphProvider.class, graph = ChronoGraph.class)
public class InMemoryChronoGraphProcessStandardTestSuite {
}
| 867 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
InMemoryChronoGraphStructureStandardTestSuite.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/_gremlinsuite/InMemoryChronoGraphStructureStandardTestSuite.java | package org.chronos.chronograph.test._gremlinsuite;
import org.apache.tinkerpop.gremlin.GraphProviderClass;
import org.apache.tinkerpop.gremlin.structure.StructureStandardSuite;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.junit.runner.RunWith;
// note: this class is NOT annotated with @Category(Suite.class) because, even though it technically is a suite,
// we do want Gradle to execute this class (whereas execution of other suites is always redundant). The reason
// is that the tests executed by this suite reside in a JAR file which is not scanned by gradle for test classes.
@RunWith(StructureStandardSuite.class)
@GraphProviderClass(provider = InMemoryChronoGraphProvider.class, graph = ChronoGraph.class)
public class InMemoryChronoGraphStructureStandardTestSuite {
}
| 805 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphModificationLoggingTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/logging/ChronoGraphModificationLoggingTest.java | package org.chronos.chronograph.test.cases.logging;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
@Category(IntegrationTest.class)
public class ChronoGraphModificationLoggingTest extends AllChronoGraphBackendsTest {
@Test
public void graphModificationLoggingIsDisabledByDefault() {
final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
PrintStream originalSysout = System.out;
System.setOut(new PrintStream(myOut));
try {
ChronoGraph graph = this.getGraph();
graph.tx().open();
graph.addVertex(T.id, "1234");
graph.tx().commit();
} finally {
System.setOut(originalSysout);
}
final String testOutput = myOut.toString();
assertThat(testOutput.toLowerCase(), not(containsString("adding vertex")));
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.GRAPH_MODIFICATION_LOG_LEVEL, value = "info")
public void canEnableGraphModificationLogging() {
final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
PrintStream originalSysout = System.out;
System.setOut(new PrintStream(myOut));
try {
ChronoGraph graph = this.getGraph();
graph.tx().open();
graph.addVertex(T.id, "1234", "firstname", "John", "lastname", "Doe");
graph.tx().commit();
} finally {
System.setOut(originalSysout);
}
final String testOutput = myOut.toString();
System.out.println("<<<< BEGIN TEST OUTPUT >>>>");
System.out.println(testOutput);
System.out.println("<<<< END TEST OUTPUT >>>>");
assertThat(testOutput, not(isEmptyString()));
}
}
| 2,313 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphDumpTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/dump/ChronoGraphDumpTest.java | package org.chronos.chronograph.test.cases.dump;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.chronos.common.util.ClasspathUtils;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class ChronoGraphDumpTest extends AllChronoGraphBackendsTest {
@Test
public void canCreateGraphDump() {
ChronoGraph graph = this.getGraph();
Vertex vJohn = graph.addVertex("firstname", "John", "lastname", "Doe");
Vertex vJane = graph.addVertex("firstname", "Jane", "lastname", "Doe");
Vertex vJack = graph.addVertex("firstname", "Jack", "lastname", "Doe");
vJohn.addEdge("family", vJack, "kind", "brother");
vJohn.addEdge("family", vJane, "kind", "married");
vJane.addEdge("family", vJohn, "kind", "married");
vJane.addEdge("family", vJack, "kind", "brother-in-law");
vJack.addEdge("family", vJohn, "kind", "brohter");
vJack.addEdge("family", vJane, "kind", "sister-in-law");
long commitTimestamp = graph.tx().commitAndReturnTimestamp("blub");
// create the dump file
File dumpFile = this.createTestFile("Test.chronodump");
// write the dump
graph.writeDump(dumpFile);
// print the contents of the file (for debugging)
try {
String contents = FileUtils.readFileToString(dumpFile, Charsets.UTF_8);
System.out.println(contents);
} catch (IOException e) {
e.printStackTrace();
fail();
}
// reinstantiate the DB
ChronoGraph graph2 = this.reinstantiateGraph();
// read the contents of the dump file into the graph
graph2.readDump(dumpFile);
// make sure that the data is still available
Vertex vJohn2 = graph2.vertices(vJohn.id()).next();
Vertex vJane2 = graph2.vertices(vJane.id()).next();
Vertex vJack2 = graph2.vertices(vJack.id()).next();
assertNotNull(vJohn2);
assertNotNull(vJane2);
assertNotNull(vJack2);
// john should be married to jane
assertEquals(vJane2, graph2.traversal().V(vJohn2).outE("family").has("kind", "married").inV().next());
assertEquals(vJohn2, graph2.traversal().V(vJane2).inE("family").has("kind", "married").outV().next());
// jane should be married to john
assertEquals(vJohn2, graph2.traversal().V(vJane2).outE("family").has("kind", "married").inV().next());
assertEquals(vJane2, graph2.traversal().V(vJohn2).inE("family").has("kind", "married").outV().next());
assertEquals(graph2.getCommitMetadata(commitTimestamp), "blub");
List<Long> commitTimestampsAfter = graph2.getCommitTimestampsAfter(0, 100);
Long latestCommit = commitTimestampsAfter.get(0);
ArrayList<String> changedVertices = Lists.newArrayList(graph2.getChangedVerticesAtCommit(latestCommit));
assertThat(changedVertices, containsInAnyOrder(vJohn.id(), vJane.id(), vJack.id()));
}
@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 = "100")
public void canReadDumpWithCaching() throws Exception {
this.canReadDumpTest();
}
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "false")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "false")
public void canCreadDumpWithoutCaching() throws Exception {
this.canReadDumpTest();
}
private void canReadDumpTest() throws Exception {
// get the dump file
File dumpFile = ClasspathUtils.getResourceAsFile("org/chronos/chronograph/dump/dumpReaderTest.xml");
assertNotNull(dumpFile);
assertTrue(dumpFile.exists());
assertTrue(dumpFile.isFile());
// load it into the graph
ChronoGraph graph = this.getGraph();
graph.readDump(dumpFile);
// make sure we have a vertex with "kind" equal to "informationModel"
assertEquals(1, graph.traversal().V().filter(t -> t.get().property("kind").orElse("").equals("informationModel")).toSet().size());
// make sure that the secondary index agrees as well
assertEquals(1, graph.traversal().V().has("kind", "informationModel").toSet().size());
{ // our secondary index should be correct on any timestamp
List<Long> commitTimestamps = graph.getCommitTimestampsBefore(System.currentTimeMillis() + 1, Integer.MAX_VALUE);
for (long timestamp : commitTimestamps) {
try (ChronoGraph txGraph = graph.tx().createThreadedTx(timestamp)) {
System.out.println("Checking timestamp " + timestamp);
assertSameResultFromIndexAndGraph(txGraph, "kind", "entity");
assertSameResultFromIndexAndGraph(txGraph, "kind", "entityClass");
assertSameResultFromIndexAndGraph(txGraph, "kind", "informationModel");
assertSameResultFromIndexAndGraph(txGraph, "kind", "associationClass");
assertSameResultFromIndexAndGraph(txGraph, "kind", "reference");
}
}
}
// reindexing should not affect the correctness of our result
graph.getIndexManagerOnMaster().reindexAll();
// make sure we have a vertex with "kind" equal to "informationModel"
assertEquals(1, graph.traversal().V().filter(t -> t.get().property("kind").orElse("").equals("informationModel")).toSet().size());
// make sure that the secondary index agrees as well
assertEquals(1, graph.traversal().V().has("kind", "informationModel").toSet().size());
// our secondary index should be correct on any timestamp
{
List<Long> commitTimestamps = graph.getCommitTimestampsBefore(System.currentTimeMillis() + 1, Integer.MAX_VALUE);
for (long timestamp : commitTimestamps) {
try (ChronoGraph txGraph = graph.tx().createThreadedTx(timestamp)) {
System.out.println("Checking timestamp " + timestamp);
assertSameResultFromIndexAndGraph(txGraph, "kind", "entity");
}
}
}
}
// =====================================================================================================================
// 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 static Set<String> filterVerticesWithIndex(final ChronoGraph graph, final String property, final String value) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!");
return graph.traversal().V().has(property, value).toStream().map(v -> (String) v.id()).collect(Collectors.toSet());
}
private static Set<String> filterVerticesWithoutIndex(final ChronoGraph graph, final String property, final String value) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!");
return graph.traversal().V().toStream().filter(v -> v.property(property).isPresent()).filter(v -> v.value(property).equals(value)).map(v -> (String) v.id()).collect(Collectors.toSet());
}
private static void assertSameResultFromIndexAndGraph(final ChronoGraph graph, final String property, final String value) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!");
Set<String> idsFromIndex = filterVerticesWithIndex(graph, property, value);
Set<String> idsFromGraph = filterVerticesWithoutIndex(graph, property, value);
assertEquals(idsFromGraph.size(), idsFromIndex.size());
assertEquals(idsFromGraph, idsFromIndex);
}
}
| 9,832 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
SchemaValidationTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/schemavalidation/SchemaValidationTest.java | package org.chronos.chronograph.test.cases.schemavalidation;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.exceptions.ChronoGraphSchemaViolationException;
import org.chronos.chronograph.api.schema.ChronoGraphSchemaManager;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class SchemaValidationTest extends AllChronoGraphBackendsTest {
@Test
public void canDefineSchemaValidator() {
ChronoGraph graph = this.getGraph();
ChronoGraphSchemaManager schemaManager = graph.getSchemaManager();
boolean override = schemaManager.addOrOverrideValidator("validator1", "return;");
assertThat(override, is(false));
boolean override2 = schemaManager.addOrOverrideValidator("validator2", "def x = 1; return;");
assertThat(override2, is(false));
String script = schemaManager.getValidatorScript("validator1");
assertThat(script, is("return;"));
String script2 = schemaManager.getValidatorScript("validator2");
assertThat(script2, is("def x = 1; return;"));
Set<String> allValidatorNames = schemaManager.getAllValidatorNames();
assertThat(allValidatorNames, containsInAnyOrder("validator1", "validator2"));
}
@Test
public void canOverrideSchemaValidator() {
ChronoGraph graph = this.getGraph();
ChronoGraphSchemaManager schemaManager = graph.getSchemaManager();
boolean override = schemaManager.addOrOverrideValidator("validator", "return;");
assertThat(override, is(false));
assertThat(schemaManager.getValidatorScript("validator"), is("return;"));
boolean override2 = schemaManager.addOrOverrideValidator("validator", "def x = 1; return;");
assertThat(override2, is(true));
assertThat(schemaManager.getValidatorScript("validator"), is("def x = 1; return;"));
}
@Test
public void canDeleteSchemaValidator() {
ChronoGraph graph = this.getGraph();
ChronoGraphSchemaManager schemaManager = graph.getSchemaManager();
schemaManager.addOrOverrideValidator("validator", "return");
assertThat(schemaManager.getValidatorScript("validator"), is("return"));
boolean removed = schemaManager.removeValidator("validator");
assertTrue(removed);
assertThat(schemaManager.getValidatorScript("validator"), is(nullValue()));
assertThat(schemaManager.removeValidator("validator"), is(false));
}
@Test
public void invalidGroovyScriptsAreRejectedAsArguments() {
ChronoGraph graph = this.getGraph();
ChronoGraphSchemaManager schemaManager = graph.getSchemaManager();
schemaManager.addOrOverrideValidator("validator", "return");
assertThat(schemaManager.getValidatorScript("validator"), is("return"));
try {
schemaManager.addOrOverrideValidator("validator", "this isn't valid groovy!");
fail("Managed to add schema validator with invalid groovy script body!");
} catch (IllegalArgumentException expected) {
// pass
}
// assert that the previous validator is still present
assertThat(schemaManager.getValidatorScript("validator"), is("return"));
}
@Test
public void canPerformSchemaValidation() {
ChronoGraph graph = this.getGraph();
ChronoGraphSchemaManager schemaManager = graph.getSchemaManager();
String validatorName = "All Vertices must have a name";
schemaManager.addOrOverrideValidator(validatorName, "" +
"if(element instanceof Vertex){ " +
" def v = (Vertex)element; " +
" if(!v.property('name').isPresent()){ " +
" throw new ChronoGraphSchemaViolationException('The Vertex ' + v.id() + ' has no \"name\" property!');" +
" }" +
"}"
);
{ // PART 1: attempt at adding an element that doesn't pass the validator
// try to commit a vertex without a name
graph.tx().open();
graph.addVertex();
try {
graph.tx().commit();
fail("Managed to bypass the graph validator!");
} catch (ChronoGraphSchemaViolationException expected) {
// pass
}
// a failing commit should have performed a rollback
assertThat(graph.tx().isOpen(), is(false));
// ... and no vertices should have been written to disk
graph.tx().open();
assertThat(graph.vertices().hasNext(), is(false));
graph.tx().rollback();
}
{ // PART 2: adding an element which passes the validator
graph.tx().open();
// add a valid vertex
Vertex vertex = graph.addVertex();
vertex.property("name", "John");
// commit it (which should be ok according to the validator)
graph.tx().commit();
}
{ // PART 3: attempt to commit a mixture of valid and invalid elements
graph.tx().open();
Vertex v1 = graph.addVertex();
Vertex v2 = graph.addVertex();
v2.property("name", "Jack");
Vertex v3 = graph.addVertex();
v3.property("name", "Sarah");
try {
graph.tx().commit();
fail("Managed to perform a commit with graph schema validation errors!");
} catch (ChronoGraphSchemaViolationException expected) {
// pass
}
}
{ // PART 4: If we remove the validator again, then we can commit whatever we want
boolean removed = schemaManager.removeValidator(validatorName);
assertThat(removed, is(true));
graph.tx().open();
graph.addVertex();
graph.tx().commit();
}
}
}
| 6,225 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecordValueTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/record/PropertyRecordValueTest.java | package org.chronos.chronograph.test.cases.record;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.chronos.chronograph.internal.impl.structure.record2.valuerecords.*;
import org.chronos.common.test.ChronosUnitTest;
import org.junit.Test;
import java.util.Date;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class PropertyRecordValueTest extends ChronosUnitTest {
@Test
public void canCreatePropertyRecordBooleanValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordBooleanValue.class;
assertPropertyRecordValueIsCorrect(clazz, true, false, Boolean.TRUE, Boolean.FALSE);
}
@Test
public void canCreatePropertyRecordByteValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordByteValue.class;
Byte byteVal1 = (byte) 12;
Byte byteVal2 = (byte) -3;
assertPropertyRecordValueIsCorrect(clazz, (byte) 12, (byte) -3, byteVal1, byteVal2);
}
@Test
public void canCreatePropertyRecordShortValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordShortValue.class;
Short shortVal1 = (short) 12;
Short shortVal2 = (short) -3;
assertPropertyRecordValueIsCorrect(clazz, (short) 12, (short) -3, shortVal1, shortVal2);
}
@Test
public void canCreatePropertyRecordCharValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordCharValue.class;
Character charVal1 = 'a';
Character charVal2 = '\u20ac';
assertPropertyRecordValueIsCorrect(clazz, 'a', '\u20ac', charVal1, charVal2);
}
@Test
public void canCreatePropertyRecordIntegerValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordIntValue.class;
Integer intVal1 = 123;
Integer intVal2 = -344;
assertPropertyRecordValueIsCorrect(clazz, 123, -344, intVal1, intVal2);
}
@Test
public void canCreatePropertyRecordLongValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordLongValue.class;
Long longVal1 = 123L;
Long longVal2 = -344L;
assertPropertyRecordValueIsCorrect(clazz, 123L, -344L, longVal1, longVal2);
}
@Test
public void canCreatePropertyRecordFloatValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordFloatValue.class;
Float floatVal1 = 123.0f;
Float floatVal2 = -344.0f;
assertPropertyRecordValueIsCorrect(clazz, 123.0f, -344.0f, floatVal1, floatVal2);
}
@Test
public void canCreatePropertyRecordDoubleValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDoubleValue.class;
Double doubleVal1 = 123.0d;
Double doubleVal2 = -344.0d;
assertPropertyRecordValueIsCorrect(clazz, 123.0d, -344.0d, doubleVal1, doubleVal2);
}
@Test
public void canCreatePropertyRecordStringValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordStringValue.class;
assertPropertyRecordValueIsCorrect(clazz, "Lorem", "Hello", "World");
}
@Test
public void canCreatePropertyRecordDateValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDateValue.class;
assertPropertyRecordValueIsCorrect(clazz, new Date());
}
@Test
public void canCreatePropertyRecordBooleanArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordBooleanArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new boolean[]{true, true, false});
}
@Test
public void canCreatePropertyRecordBooleanWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordBooleanWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Boolean[]{Boolean.TRUE, Boolean.FALSE});
}
@Test
public void canCreatePropertyRecordBooleanListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordBooleanListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(Boolean.TRUE, null, false));
}
@Test
public void canCreatePropertyRecordBooleanSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordBooleanSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(Boolean.TRUE, null, false));
}
@Test
public void canCreatePropertyRecordByteArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordByteArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new byte[]{12, -3});
}
@Test
public void canCreatePropertyRecordByteWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordByteWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Byte[]{12, -3, null});
}
@Test
public void canCreatePropertyRecordByteListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordByteListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList((byte)12, (byte)-3, null));
}
@Test
public void canCreatePropertyRecordByteSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordByteSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet((byte)12, (byte)-3, null));
}
@Test
public void canCreatePropertyRecordCharArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordCharArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new char[]{'a', '@'});
}
@Test
public void canCreatePropertyRecordCharWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordCharWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Character[]{'a', null, '@'});
}
@Test
public void canCreatePropertyRecordCharListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordCharListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList('a', null, '@'));
}
@Test
public void canCreatePropertyRecordCharSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordCharSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet('a', null, '@'));
}
@Test
public void canCreatePropertyRecordShortArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordShortArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new short[]{12, -3});
}
@Test
public void canCreatePropertyRecordShortWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordShortWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Short[]{(short)12, (short)-3, null});
}
@Test
public void canCreatePropertyRecordShortListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordShortListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList((short)12, (short)-3, null));
}
@Test
public void canCreatePropertyRecordShortSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordShortSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet((short)12, (short)-3, null));
}
@Test
public void canCreatePropertyRecordIntArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordIntArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new int[]{12, -3});
}
@Test
public void canCreatePropertyRecordIntWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordIntWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Integer[]{12, null, -3});
}
@Test
public void canCreatePropertyRecordIntListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordIntListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(12, null, -3));
}
@Test
public void canCreatePropertyRecordIntSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordIntSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(12, null, -3));
}
@Test
public void canCreatePropertyRecordLongArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordLongArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new long[]{12L, -3L});
}
@Test
public void canCreatePropertyRecordLongWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordLongWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Long[]{12L, null, -3L});
}
@Test
public void canCreatePropertyRecordLongListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordLongListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(12L, null, -3L));
}
@Test
public void canCreatePropertyRecordLongSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordLongSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(12L, null, -3L));
}
@Test
public void canCreatePropertyRecordFloatArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordFloatArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new float[]{12.8f, -3f});
}
@Test
public void canCreatePropertyRecordFloatWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordFloatWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Float[]{12.8f, null, -3f});
}
@Test
public void canCreatePropertyRecordFloatListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordFloatListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(12.8f, null, -3f));
}
@Test
public void canCreatePropertyRecordFloatSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordFloatSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(12.8f, null, -3f));
}
@Test
public void canCreatePropertyRecordDoubleArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDoubleArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new double[]{12.8d, -3d});
}
@Test
public void canCreatePropertyRecordDoubleWrapperArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDoubleWrapperArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Double[]{12.8d, null, -3d});
}
@Test
public void canCreatePropertyRecordDoubleListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDoubleListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(12.8d, null, -3d));
}
@Test
public void canCreatePropertyRecordDoubleSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDoubleSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(12.8d, null, -3d));
}
@Test
public void canCreatePropertyRecordStringArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordStringArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new String[]{"Lorem", "Ipsum", null});
}
@Test
public void canCreatePropertyRecordStringListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordStringListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList("Lorem", "Ipsum", null));
}
@Test
public void canCreatePropertyRecordStringSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordStringSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet("Lorem", "Ipsum", null));
}
@Test
public void canCreatePropertyRecordDateArrayValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDateArrayValue.class;
assertPropertyRecordValueIsCorrect(clazz, (Object) new Date[]{new Date(), null});
}
@Test
public void canCreatePropertyRecordDateListValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDateListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(new Date(), null));
}
@Test
public void canCreatePropertyRecordDateSetValues() {
Class<? extends PropertyRecordValue> clazz = PropertyRecordDateSetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(new Date(), null));
}
@Test
public void canCreatePropertyRecordForCustomValue(){
Class<? extends PropertyRecordValue> clazz = PropertyRecordCustomObjectValue.class;
assertPropertyRecordValueIsCorrect(clazz, new MyClass("Hello!"));
}
@Test
public void canCreatePropertyRecordForCustomListValue(){
Class<? extends PropertyRecordValue> clazz = PropertyRecordCustomObjectValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(new MyClass("Hello!")));
}
@Test
public void canCreatePropertyRecordForCustomSetValue(){
Class<? extends PropertyRecordValue> clazz = PropertyRecordCustomObjectValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(new MyClass("Hello!")));
}
@Test
public void canCreatePropertyRecordForListOfNullValues(){
Class<? extends PropertyRecordValue> clazz = PropertyRecordCustomObjectValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList(null, null));
}
@Test
public void canCreatePropertyRecordForSetOfNullValues(){
Class<? extends PropertyRecordValue> clazz = PropertyRecordCustomObjectValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet(null, null));
}
@Test
public void canCreatePropertyRecordForEmptyList(){
Class<? extends PropertyRecordValue> clazz = PropertyRecordEmptyListValue.class;
assertPropertyRecordValueIsCorrect(clazz, Lists.newArrayList());
}
@Test
public void canCreatePropertyRecordForEmptySet(){
Class<? extends PropertyRecordValue> clazz = PropertyRecordEmptySetValue.class;
assertPropertyRecordValueIsCorrect(clazz, Sets.newHashSet());
}
// =================================================================================================================
// INTERNAL HELPER METHODS
// =================================================================================================================
private void assertPropertyRecordValueIsCorrect(Class<?> valueWrapperClass, Object... testValues) {
for (Object testValue : testValues) {
PropertyRecordValue<Object> wrapper = PropertyRecordValue.of(testValue);
assertThat(wrapper, is(instanceOf(valueWrapperClass)));
assertThat(wrapper.getValue(), is(testValue));
}
}
private static class MyClass {
private String name;
public MyClass(String name){
this.name = name;
}
protected MyClass(){
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MyClass myClass = (MyClass) o;
return name != null ? name.equals(myClass.name) : myClass.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
}
}
| 16,343 | 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.chronograph/src/test/java/org/chronos/chronograph/test/cases/commitmetadata/CountCommitsTest.java | package org.chronos.chronograph.test.cases.commitmetadata;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.Test;
import static org.junit.Assert.*;
public class CountCommitsTest extends AllChronoGraphBackendsTest {
@Test
public void retrievingInvalidTimeRangeProducesZero() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit();
// check
assertEquals(1, graph.countCommitTimestamps());
assertEquals(0, graph.countCommitTimestampsBetween(1, 0));
assertEquals(0, graph.countCommitTimestampsBetween(graph.getNow(), 0));
}
@Test
public void canCountCommitTimestampWhenNoMetadataIsGiven() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit();
// check
long now = graph.getNow();
assertEquals(1, graph.countCommitTimestamps());
assertEquals(1, graph.countCommitTimestampsBetween(0L, now));
}
@Test
public void canCountCommitsWithAndWithoutMetadata() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("Initial Commit");
final long commit1 = graph.getNow();
graph.addVertex("Hello", "Test");
graph.tx().commit();
final long commit2 = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Foobar");
final long commit3 = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit();
final long commit4 = graph.getNow();
assertEquals(4, graph.countCommitTimestamps());
assertEquals(2, graph.countCommitTimestampsBetween(commit2, commit3));
assertEquals(3, graph.countCommitTimestampsBetween(commit1, commit3));
assertEquals(4, graph.countCommitTimestampsBetween(0, commit4));
}
@Test
public void countingCommitTimestampsIsBranchLocal() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("Initial Commit");
graph.getBranchManager().createBranch("Test");
long branchingTimestamp = graph.getBranchManager().getBranch("Test").getBranchingTimestamp();
ChronoGraph txGraph = graph.tx().createThreadedTx("Test");
try {
txGraph.addVertex("Foo", "Bar");
txGraph.tx().commit("New Branch!");
} finally {
txGraph.close();
}
final long commit2 = graph.getNow("Test");
graph.addVertex("Pi", "3.1415");
graph.tx().commit();
final long commit3 = graph.getNow();
// we should have two commits on 'master' (the first one and the last one)
assertEquals(2, graph.countCommitTimestamps());
assertEquals(2, graph.countCommitTimestampsBetween(0, commit3));
// we should have one commit on 'Test'
assertEquals(1, graph.countCommitTimestamps("Test"));
assertEquals(1, graph.countCommitTimestampsBetween("Test", branchingTimestamp, commit2));
}
}
| 3,190 | 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.chronograph/src/test/java/org/chronos/chronograph/test/cases/commitmetadata/GetCommitsBetweenPagedTest.java | package org.chronos.chronograph.test.cases.commitmetadata;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.chronos.chronodb.api.Order;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 AllChronoGraphBackendsTest {
@Test
public void retrievingInvalidTimeRangeProducesAnEmptyIterator() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit();
// check
long now = graph.getNow();
assertEquals(1, Iterators.size(graph.getCommitTimestampsPaged(0, now, 1, 0, Order.ASCENDING)));
assertEquals(1, Iterators.size(graph.getCommitMetadataPaged(0, now, 1, 0, Order.ASCENDING)));
assertEquals(0, Iterators.size(graph.getCommitTimestampsPaged(now, 0, 1, 0, Order.ASCENDING)));
assertEquals(0, Iterators.size(graph.getCommitMetadataPaged(now, 0, 1, 0, Order.ASCENDING)));
}
@Test
public void canRetrieveCommitsWhenNoMetadataWasGiven() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit();
long now = graph.getNow();
assertEquals(1, Iterators.size(graph.getCommitTimestampsPaged(0, now, 1, 0, Order.ASCENDING)));
assertEquals(1, Iterators.size(graph.getCommitMetadataPaged(0, now, 1, 0, Order.ASCENDING)));
}
@Test
public void canRetrieveCommitsWithAndWithoutMetadata() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("Initial Commit");
final long commit1 = graph.getNow();
graph.addVertex("Hello", "Test");
graph.tx().commit();
final long commit2 = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Foobar");
final long commit3 = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit();
final long commit4 = graph.getNow();
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(graph.getCommitTimestampsPaged(commit2, commit4, 4, 0, Order.DESCENDING)));
assertEquals(
// expected
expectedResult.subMap(commit2, true, commit4, true).keySet(),
// actual
toSet(graph.getCommitTimestampsPaged(commit2, commit4, 4, 0, Order.ASCENDING)));
assertEquals(
// expected
expectedResult.subMap(commit2, true, commit4, true).descendingMap(),
// actual
toMap(graph.getCommitMetadataPaged(commit2, commit4, 4, 0, Order.DESCENDING)));
assertEquals(
// expected
expectedResult.subMap(commit2, true, commit4, true),
// actual
toMap(graph.getCommitMetadataPaged(commit2, commit4, 4, 0, Order.ASCENDING)));
}
@Test
public void retrievingCommitTimestampsIsBranchLocal() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("Initial Commit");
graph.getBranchManager().createBranch("Test");
long branchingTimestamp = graph.getBranchManager().getBranch("Test").getBranchingTimestamp();
ChronoGraph txGraph = graph.tx().createThreadedTx("Test");
try {
txGraph.addVertex("Foo", "Bar");
txGraph.tx().commit("New Branch!");
} finally {
txGraph.close();
}
final long commit2 = graph.getNow("Test");
graph.addVertex("Pi", "3.1415");
graph.tx().commit();
final long commit3 = graph.getNow();
// we should have two commits on 'master' (the first one and the last one)
assertEquals(2, Iterators.size(graph.getCommitTimestampsPaged(0, commit3, 4, 0, Order.ASCENDING)));
assertEquals(2, Iterators.size(graph.getCommitMetadataPaged(0, commit3, 4, 0, Order.ASCENDING)));
// we should have one commit on 'Test'
assertEquals(1, Iterators
.size(graph.getCommitTimestampsPaged("Test", branchingTimestamp, commit2, 4, 0, Order.ASCENDING)));
assertEquals(1, Iterators
.size(graph.getCommitMetadataPaged("Test", branchingTimestamp, commit2, 4, 0, Order.ASCENDING)));
}
@Test
public void ascendingPaginationWorks() {
ChronoGraph graph = this.getGraph();
// do 20 commits on the database
List<Long> commitTimestamps = Lists.newArrayList();
for (int i = 0; i < 20; i++) {
graph.addVertex("test", i);
// attach the iteration as metadata to the commit
graph.tx().commit(i);
commitTimestamps.add(graph.getNow());
}
// query the metadata
List<Entry<Long, Object>> entriesPage;
List<Long> timestampsPage;
// first page
entriesPage = toList(
graph.getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 0, Order.ASCENDING));
timestampsPage = toList(graph.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(
graph.getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 2, Order.ASCENDING));
timestampsPage = toList(graph.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(
graph.getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 3, Order.ASCENDING));
timestampsPage = toList(graph.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() {
ChronoGraph graph = this.getGraph();
// do 20 commits on the database
List<Long> commitTimestamps = Lists.newArrayList();
for (int i = 0; i < 20; i++) {
graph.addVertex("test", i);
// attach the iteration as metadata to the commit
graph.tx().commit(i);
commitTimestamps.add(graph.getNow());
}
// query the metadata
List<Entry<Long, Object>> entriesPage;
List<Long> timestampsPage;
// first page
entriesPage = toList(graph.getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 0,
Order.DESCENDING));
timestampsPage = toList(graph.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(graph.getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 2,
Order.DESCENDING));
timestampsPage = toList(graph.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(graph.getCommitMetadataPaged(commitTimestamps.get(2), commitTimestamps.get(18), 5, 3,
Order.DESCENDING));
timestampsPage = toList(graph.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,193 | 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.chronograph/src/test/java/org/chronos/chronograph/test/cases/commitmetadata/BasicCommitMetadataTest.java | package org.chronos.chronograph.test.cases.commitmetadata;
import com.google.common.collect.Maps;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 AllChronoGraphBackendsTest {
@Test
public void simpleStoringAndRetrievingMetadataWorks() {
ChronoGraph graph = this.getGraph();
// just a message that we can compare later on
String commitMessage = "Hey there, Hello World!";
// insert data into the database
graph.addVertex("Hello", "World");
graph.tx().commit(commitMessage);
// record the commit timestamp
long timestamp = graph.getNow();
// read the metadata and assert that it's correct
assertEquals(commitMessage, graph.getCommitMetadata(timestamp));
}
@Test
public void readingCommitMetadataFromNonExistingCommitTimestampsProducesNull() {
ChronoGraph graph = this.getGraph();
// insert data into the database
graph.addVertex("Hello", "World");
graph.tx().commit("Hello World!");
// read commit metadata from a non-existing (but valid) commit timestamp
assertNull(graph.getCommitMetadata(0L));
}
@Test
public void readingCommitMetadataRetrievesCorrectObject() {
ChronoGraph graph = this.getGraph();
// 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
graph.addVertex("Hello", "World");
graph.tx().commit(commitMessage1);
// record the commit timestamp
long timeCommit1 = graph.getNow();
this.sleep(5);
// ... and another record
graph.addVertex("Foo", "Bar");
graph.tx().commit(commitMessage2);
// record the commit timestamp
long timeCommit2 = graph.getNow();
this.sleep(5);
// ... and yet another record
graph.addVertex("Chronos", "IsAwesome");
graph.tx().commit(commitMessage3);
// record the commit timestamp
long timeCommit3 = graph.getNow();
this.sleep(5);
// now, retrieve the three messages individually
assertEquals(commitMessage1, graph.getCommitMetadata(timeCommit1));
assertEquals(commitMessage2, graph.getCommitMetadata(timeCommit2));
assertEquals(commitMessage3, graph.getCommitMetadata(timeCommit3));
}
@Test
public void readingCommitMessagesFromOriginBranchWorks() {
ChronoGraph graph = this.getGraph();
// 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
graph.addVertex("Hello", "World");
graph.tx().commit(commitMessage1);
// record the commit timestamp
long timeCommit1 = graph.getNow();
this.sleep(5);
// create the branch
graph.getBranchManager().createBranch("MyBranch");
// commit something to the branch
ChronoGraph txGraph = graph.tx().createThreadedTx("MyBranch");
try {
txGraph.addVertex("Foo", "Bar");
txGraph.tx().commit(commitMessage2);
} finally {
txGraph.close();
}
// record the commit timestamp
long timeCommit2 = graph.getNow("MyBranch");
// open a transaction on the branch and request the commit message of tx1
assertEquals(commitMessage1, graph.getCommitMetadata("MyBranch", timeCommit1));
// also, we should be able to get the commit metadata of the branch
assertEquals(commitMessage2, graph.getCommitMetadata("MyBranch", timeCommit2));
}
@Test
public void canUseHashMapAsCommitMetadata() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
Map<String, String> commitMap = Maps.newHashMap();
commitMap.put("User", "Martin");
commitMap.put("Mood", "Good");
commitMap.put("Mail", "martin.haeusler@uibk.ac.at");
graph.tx().commit(commitMap);
long timestamp = graph.getNow();
// get the commit map
@SuppressWarnings("unchecked")
Map<String, String> retrieved = (Map<String, String>) graph.getCommitMetadata(timestamp);
// assert that the maps are equal
assertNotNull(retrieved);
assertEquals(commitMap, retrieved);
}
}
| 4,898 | 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.chronograph/src/test/java/org/chronos/chronograph/test/cases/commitmetadata/GetCommitsBetweenTest.java | package org.chronos.chronograph.test.cases.commitmetadata;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import org.chronos.chronodb.api.Order;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 AllChronoGraphBackendsTest {
@Test
public void retrievingInvalidTimeRangeProducesAnEmptyIterator() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit();
// check
long now = graph.getNow();
assertEquals(1, Iterators.size(graph.getCommitTimestampsBetween(0, now)));
assertEquals(1, Iterators.size(graph.getCommitMetadataBetween(0, now)));
assertEquals(0, Iterators.size(graph.getCommitTimestampsBetween(now, 0)));
assertEquals(0, Iterators.size(graph.getCommitMetadataBetween(now, 0)));
}
@Test
public void canRetrieveCommitsWhenNoMetadataWasGiven() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit();
long now = graph.getNow();
assertEquals(1, Iterators.size(graph.getCommitTimestampsBetween(0, now)));
assertEquals(1, Iterators.size(graph.getCommitMetadataBetween(0, now)));
}
@Test
public void canRetrieveCommitsWithAndWithoutMetadata() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("Initial Commit");
final long commit1 = graph.getNow();
graph.addVertex("Hello", "Test");
graph.tx().commit();
final long commit2 = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Foobar");
final long commit3 = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit();
final long commit4 = graph.getNow();
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(graph.getCommitTimestampsBetween(commit2, commit4, Order.DESCENDING)));
assertEquals(
// expected
expectedResult.subMap(commit2, true, commit4, true).keySet(),
// actual
toSet(graph.getCommitTimestampsBetween(commit2, commit4, Order.ASCENDING)));
assertEquals(
// expected
expectedResult.subMap(commit2, true, commit4, true).descendingMap(),
// actual
toMap(graph.getCommitMetadataBetween(commit2, commit4, Order.DESCENDING)));
assertEquals(
// expected
expectedResult.subMap(commit2, true, commit4, true),
// actual
toMap(graph.getCommitMetadataBetween(commit2, commit4, Order.ASCENDING)));
}
@Test
public void retrievingCommitTimestampsIsBranchLocal() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("Initial Commit");
graph.getBranchManager().createBranch("Test");
long branchingTimestamp = graph.getBranchManager().getBranch("Test").getBranchingTimestamp();
ChronoGraph txGraph = graph.tx().createThreadedTx("Test");
try {
txGraph.addVertex("Foo", "Bar");
txGraph.tx().commit("New Branch!");
} finally {
txGraph.close();
}
final long commit2 = graph.getNow("Test");
graph.addVertex("Pi", "3.1415");
graph.tx().commit();
final long commit3 = graph.getNow();
// we should have two commits on 'master' (the first one and the last one)
assertEquals(2, Iterators.size(graph.getCommitTimestampsBetween(0, commit3)));
assertEquals(2, Iterators.size(graph.getCommitMetadataBetween(0, commit3)));
// we should have one commit on 'Test'
assertEquals(1, Iterators.size(graph.getCommitTimestampsBetween("Test", branchingTimestamp, commit2)));
assertEquals(1, Iterators.size(graph.getCommitMetadataBetween("Test", 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,555 | 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.chronograph/src/test/java/org/chronos/chronograph/test/cases/commitmetadata/GetCommitsBeforeAfterAroundTest.java | package org.chronos.chronograph.test.cases.commitmetadata;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import org.chronos.chronodb.internal.impl.engines.base.ChronosInternalCommitMetadata;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 java.util.stream.Collectors;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GetCommitsBeforeAfterAroundTest extends AllChronoGraphBackendsTest {
// =================================================================================================================
// COMMITS AROUND
// =================================================================================================================
@Test
public void commitsAroundWorksIfNoCommitsArePresent() {
ChronoGraph graph = this.getGraph();
try (ChronoGraph txGraph = graph.tx().createThreadedTx()) {
List<Entry<Long, Object>> commits = txGraph.getCommitMetadataAround(0, 10).stream().filter(e -> !(e.getValue() instanceof ChronosInternalCommitMetadata)).collect(Collectors.toList());
assertNotNull(commits);
assertTrue(commits.isEmpty());
}
}
@Test
public void commitsAroundWorksIfNotEnoughCommitsArePresentOnEitherSide() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
List<Entry<Long, Object>> commitsAround = graph.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() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
List<Entry<Long, Object>> commitsAround = graph.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() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.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 = graph.getCommitMetadataAround(afterSecondCommit, 4);
assertEquals(expected, commitsAround);
}
@Test
public void commitsAroundWorksIfNotEnoughElementsArePresentAfter() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
long afterFifthCommit = graph.getNow();
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
long afterSixthCommit = graph.getNow();
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 = graph.getCommitMetadataAround(afterFifthCommit, 5);
assertEquals(expected, commitsAround);
}
@Test
public void commitsAroundWorksIfMoreElementsThanNecessaryArePresentOnBothSides() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.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 = graph.getCommitMetadataAround(afterThirdCommit, 3);
assertEquals(expected, commitsAround);
}
@Test
public void commitsAroundWorksIfTimestampIsNotExactlyMatchingACommit() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
this.sleep(10);
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
this.sleep(10);
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
this.sleep(10);
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
this.sleep(10);
long afterFifthCommit = graph.getNow();
graph.addVertex("6", "Six");
graph.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 = graph.getCommitMetadataAround(requestTimestamp, 3);
assertEquals(expected, commitsAround);
}
@Test
public void commitTimestampsAroundWorksIfNotEnoughCommitsArePresentOnEitherSide() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
List<Long> commitsAround = graph.getCommitTimestampsAround(afterSecondCommit, 5, false);
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() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
List<Long> commitsAround = graph.getCommitTimestampsAround(afterSecondCommit, 3, false);
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() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
List<Long> expected = Lists.newArrayList();
expected.add(afterFourthCommit);
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
expected.add(afterFirstCommit);
List<Long> commitsAround = graph.getCommitTimestampsAround(afterSecondCommit, 4, false);
assertEquals(expected, commitsAround);
}
@Test
public void commitTimestampsAroundWorksIfNotEnoughElementsArePresentAfter() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
long afterFifthCommit = graph.getNow();
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
long afterSixthCommit = graph.getNow();
List<Long> expected = Lists.newArrayList();
expected.add(afterSixthCommit);
expected.add(afterFifthCommit);
expected.add(afterFourthCommit);
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
List<Long> commitsAround = graph.getCommitTimestampsAround(afterFifthCommit, 5, false);
assertEquals(expected, commitsAround);
}
@Test
public void commitTimestampsAroundWorksIfMoreElementsThanNecessaryArePresentOnBothSides() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
List<Long> expected = Lists.newArrayList();
expected.add(afterFourthCommit);
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
List<Long> commitsAround = graph.getCommitTimestampsAround(afterThirdCommit, 3, false);
assertEquals(expected, commitsAround);
}
@Test
public void commitTimestampsAroundWorksIfTimestampIsNotExactlyMatchingACommit() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
this.sleep(10);
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
this.sleep(10);
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
this.sleep(10);
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
this.sleep(10);
long afterFifthCommit = graph.getNow();
graph.addVertex("6", "Six");
graph.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 = graph.getCommitTimestampsAround(requestTimestamp, 3, false);
assertEquals(expected, commitsAround);
}
// =================================================================================================================
// COMMITS BEFORE
// =================================================================================================================
@Test
public void commitsBeforeWorksIfThereAreNoCommits() {
ChronoGraph graph = this.getGraph();
List<Entry<Long, Object>> commits = graph.getCommitMetadataBefore(0, 10);
assertNotNull(commits);
assertTrue(commits.isEmpty());
}
@Test
public void commitsBeforeWorksIfThereAreNotEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.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 = graph.getCommitMetadataBefore(afterThirdCommit, 3).stream()
.filter(e -> !(e.getValue() instanceof ChronosInternalCommitMetadata))
.collect(Collectors.toList());
assertEquals(expected, commits);
}
@Test
public void commitsBeforeWorksIfThereAreExactlyEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.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 = graph.getCommitMetadataBefore(afterFourthCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitsBeforeWorksIfThereAreTooManyCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
long afterFifthCommit = graph.getNow();
graph.addVertex("6", "Six");
graph.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 = graph.getCommitMetadataBefore(afterFifthCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitTimestampsBeforeWorksIfThereAreNoCommits() {
ChronoGraph graph = this.getGraph();
List<Long> commits = graph.getCommitTimestampsBefore(0, 10);
assertNotNull(commits);
assertTrue(commits.isEmpty());
}
@Test
public void commitTimestampsBeforeWorksIfThereAreNotEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
List<Long> expected = Lists.newArrayList();
expected.add(afterSecondCommit);
expected.add(afterFirstCommit);
List<Long> commits = graph.getCommitTimestampsBefore(afterThirdCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitTimestampsBeforeWorksIfThereAreExactlyEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
List<Long> expected = Lists.newArrayList();
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
expected.add(afterFirstCommit);
List<Long> commits = graph.getCommitTimestampsBefore(afterFourthCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitTimestampsBeforeWorksIfThereAreTooManyCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
long afterFifthCommit = graph.getNow();
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
List<Long> expected = Lists.newArrayList();
expected.add(afterFourthCommit);
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
List<Long> commits = graph.getCommitTimestampsBefore(afterFifthCommit, 3);
assertEquals(expected, commits);
}
// =================================================================================================================
// COMMITS AFTER
// =================================================================================================================
@Test
public void commitsAfterWorksIfThereAreNoCommits() {
ChronoGraph graph = this.getGraph();
List<Entry<Long, Object>> commits = graph.getCommitMetadataAfter(0, 10).stream()
.filter(e -> !(e.getValue() instanceof ChronosInternalCommitMetadata))
.collect(Collectors.toList());
assertNotNull(commits);
assertTrue(commits.isEmpty());
}
@Test
public void commitsAfterWorksIfThereAreNotEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
List<Entry<Long, Object>> expected = Lists.newArrayList();
expected.add(Pair.of(afterThirdCommit, "Third"));
expected.add(Pair.of(afterSecondCommit, "Second"));
List<Entry<Long, Object>> commits = graph.getCommitMetadataAfter(afterFirstCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitsAfterWorksIfThereAreExactlyEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
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 = graph.getCommitMetadataAfter(afterFirstCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitsAfterWorksIfThereAreTooManyCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.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 = graph.getCommitMetadataAfter(afterFirstCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitTimestampsAfterWorksIfThereAreNoCommits() {
ChronoGraph graph = this.getGraph();
List<Long> commits = graph.getCommitTimestampsAfter(graph.getNow(), 10);
assertNotNull(commits);
assertTrue(commits.isEmpty());
}
@Test
public void commitTimestampsAfterWorksIfThereAreNotEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
List<Long> expected = Lists.newArrayList();
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
List<Long> commits = graph.getCommitTimestampsAfter(afterFirstCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitTimestampsAfterWorksIfThereAreExactlyEnoughCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
List<Long> expected = Lists.newArrayList();
expected.add(afterFourthCommit);
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
List<Long> commits = graph.getCommitTimestampsAfter(afterFirstCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitTimestampsAfterWorksIfThereAreTooManyCommits() {
ChronoGraph graph = this.getGraph();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
long afterFourthCommit = graph.getNow();
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
List<Long> expected = Lists.newArrayList();
expected.add(afterFourthCommit);
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
List<Long> commits = graph.getCommitTimestampsAfter(afterFirstCommit, 3);
assertEquals(expected, commits);
}
@Test
public void commitTimestampsAfterZeroWorks() {
ChronoGraph graph = this.getGraph();
long initTimestamp = graph.getNow();
graph.addVertex("Hello", "World");
graph.tx().commit("First");
long afterFirstCommit = graph.getNow();
graph.addVertex("Foo", "Bar");
graph.tx().commit("Second");
long afterSecondCommit = graph.getNow();
graph.addVertex("Pi", "3.1415");
graph.tx().commit("Third");
long afterThirdCommit = graph.getNow();
graph.addVertex("Test", "Test");
graph.tx().commit("Fourth");
graph.addVertex("XYZ", "XYZ");
graph.tx().commit("Fifth");
graph.addVertex("6", "Six");
graph.tx().commit("Sixth");
List<Long> expected = Lists.newArrayList();
expected.add(afterThirdCommit);
expected.add(afterSecondCommit);
expected.add(afterFirstCommit);
List<Long> commits = graph.getCommitTimestampsAfter(initTimestamp, 3);
assertEquals(expected, commits);
}
}
| 30,579 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GetGraphElementsChangedAtCommitTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/commitmetadata/GetGraphElementsChangedAtCommitTest.java | package org.chronos.chronograph.test.cases.commitmetadata;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 GetGraphElementsChangedAtCommitTest extends AllChronoGraphBackendsTest {
@Test
public void canRetrieveChangesFromMasterBranch() {
ChronoGraph g = this.getGraph();
Vertex vJohn = g.addVertex("name", "John");
String idJohn = (String) vJohn.id();
Vertex vJane = g.addVertex("name", "Jane");
String idJane = (String) vJane.id();
vJohn.addEdge("married", vJane);
g.tx().commit();
long commit1 = g.getNow();
Vertex vSarah = g.addVertex("name", "Sarah");
String idSarah = (String) vSarah.id();
vJohn.addEdge("father", vSarah);
vJane.addEdge("mother", vSarah);
g.tx().commit();
long commit2 = g.getNow();
// removing john will also delete the edges, which will change jane and sarah
vJohn.remove();
g.tx().commit();
long commit3 = g.getNow();
vJane.property("test", "value");
g.tx().commit();
long commit4 = g.getNow();
assertEquals(Sets.newHashSet(idJohn, idJane), Sets.newHashSet(g.getChangedVerticesAtCommit(commit1)));
assertEquals(Sets.newHashSet(idJohn, idJane, idSarah), Sets.newHashSet(g.getChangedVerticesAtCommit(commit2)));
assertEquals(Sets.newHashSet(idJohn, idJane, idSarah), Sets.newHashSet(g.getChangedVerticesAtCommit(commit3)));
assertEquals(Sets.newHashSet(idJane), Sets.newHashSet(g.getChangedVerticesAtCommit(commit4)));
}
@Test
public void canRetrieveChangesFromOtherBranch() {
ChronoGraph g = this.getGraph();
Vertex vJohn = g.addVertex("name", "John");
String idJohn = (String) vJohn.id();
Vertex vJane = g.addVertex("name", "Jane");
String idJane = (String) vJane.id();
vJohn.addEdge("married", vJane);
g.tx().commit();
long commit1 = g.getNow();
g.getBranchManager().createBranch("test");
g.tx().open("test");
Vertex vSarah = g.addVertex("name", "Sarah");
String idSarah = (String) vSarah.id();
vJohn.addEdge("father", vSarah);
vJane.addEdge("mother", vSarah);
g.tx().commit();
long commit2 = g.getNow("test");
g.tx().open("test");
// removing john will also delete the edges, which will change jane and sarah
vJohn.remove();
g.tx().commit();
long commit3 = g.getNow("test");
g.tx().open("test");
vJane.property("test", "value");
g.tx().commit();
long commit4 = g.getNow("test");
assertEquals(Sets.newHashSet(idJohn, idJane), Sets.newHashSet(g.getChangedVerticesAtCommit("test", commit1)));
assertEquals(Sets.newHashSet(idJohn, idJane, idSarah),
Sets.newHashSet(g.getChangedVerticesAtCommit("test", commit2)));
assertEquals(Sets.newHashSet(idJohn, idJane, idSarah),
Sets.newHashSet(g.getChangedVerticesAtCommit("test", commit3)));
assertEquals(Sets.newHashSet(idJane), Sets.newHashSet(g.getChangedVerticesAtCommit("test", commit4)));
}
}
| 3,544 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
CrossCuttingFeaturesTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/system/CrossCuttingFeaturesTest.java | package org.chronos.chronograph.test.cases.system;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.SystemTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import static org.junit.Assert.*;
@Category(SystemTest.class)
public class CrossCuttingFeaturesTest extends AllChronoGraphBackendsTest {
private static final String P_FIRST_NAME = "firstname";
private static final String P_LAST_NAME = "lastname";
private static final String P_NICKNAMES = "nicknames";
private static final String P_GENDER = "gender";
private static final String E_KIND = "kind";
private static final String SCENARIO_A = "Scenario A";
private static final String SCENARIO_A1 = "Scenario A.1";
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "10")
public void phase1Works() {
ChronoGraph graph = this.getGraph();
runPhase1(graph);
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "10")
public void phase2Works() {
ChronoGraph graph = this.getGraph();
runPhase1(graph);
runPhase2(graph);
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "10")
public void phase3Works() {
ChronoGraph graph = this.getGraph();
runPhase1(graph);
runPhase2(graph);
runPhase3(graph);
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "10")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "10")
public void phase4Works() {
ChronoGraph graph = this.getGraph();
runPhase1(graph);
runPhase2(graph);
runPhase3(graph);
runPhase4(graph);
}
// =====================================================================================================================
// RUNNERS
// =====================================================================================================================
/**
* Performs phase 1 of the test.
*
* <p>
* This method will:
* <ul>
* <li>Create indices on {@link #P_FIRST_NAME}, {@link #P_LAST_NAME}, {@link #P_GENDER} and {@link #E_KIND}.
* <li>Create a base graph in a regular commit
* <li>Run queries on and off the indexer, in transient and persistent state
* </ul>
*
* <p>
* <b>INFORMAL SCENARIO DESCRIPTION:</b><br>
* We start off with two persons, John and Jack Doe, who are brothers.
*
* <p>
* <b>RESULTING GRAPH:</b>
* <ul>
* <li><b>v0:</b> First name: "John", Last name: "Doe", Nick names: ["JD", "Johnny"]
* <li><b>v1:</b> First name: "Jack", Last name: "Doe", Nick names: ["JD", "Jacky"]
* </ul>
* <ul>
* <li>John -[family; kind = brother]-> Jack
* <li>Jack -[family; kind = brother]-> John
* </ul>
*
* @param graph The graph to execute the procedure on. Must not be <code>null</code>.
*/
private static void runPhase1(final ChronoGraph graph) {
try {
// create indices
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty(P_FIRST_NAME).acrossAllTimestamps().build();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty(P_LAST_NAME).acrossAllTimestamps().build();
graph.getIndexManagerOnMaster().create().stringIndex().onEdgeProperty(E_KIND).acrossAllTimestamps().build();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty(P_NICKNAMES).acrossAllTimestamps().build();
graph.getIndexManagerOnMaster().reindexAll();
// create the base graph
graph.tx().open();
// add the base graph data
Vertex v0 = graph.addVertex(T.id, "v0", P_FIRST_NAME, "John", P_LAST_NAME, "Doe", P_GENDER, "male");
v0.property(P_NICKNAMES, Sets.newHashSet("JD", "Johnny"));
Vertex v1 = graph.addVertex(T.id, "v1", P_FIRST_NAME, "Jack", P_LAST_NAME, "Doe", P_GENDER, "male");
v1.property(P_NICKNAMES, Sets.newHashSet("JD", "Jacky"));
v0.addEdge("family", v1, E_KIND, "brother");
v1.addEdge("family", v0, E_KIND, "brother");
assertCommitAssertCloseTx(graph,
// assert function
(final ChronoGraph g) -> {
// there should be one john
assertFirstNameCountEquals(graph, "John", 1);
// there should be two does
assertLastNameCountEquals(graph, "Doe", 2);
// there should be 2 persons with a nickname that starts with "J"
assertEquals(2, (long)graph.traversal().V().has(P_NICKNAMES, CP.startsWithIgnoreCase("j")).count().next());
},
// commit function
(final ChronoGraph g) -> {
g.tx().commit();
g.tx().open();
return g;
}
// end of statement
);
} catch (Throwable t) {
throw new AssertionError("Execution of Phase 1 failed! See root cause for details.", t);
}
}
/**
* Performs phase 2 of the test.
*
* <p>
* This method will:
* <ul>
* <li>Expand the base graph with incremental commits (on the thread-local graph)
* <li>Run queries on and off the indexer, in transient and persistent state
* </ul>
*
* <p>
* <b>INFORMAL SCENARIO DESCRIPTION:</b><br>
* This scenario adds two women to the graph, Jane Smith and Jill Johnson. They are friends.
*
* <p>
* <b>RESULTING GRAPH:</b>
* <ul>
* <li><b>v0:</b> First name: "John", Last name: "Doe", Nick names: ["JD", "Johnny"]
* <li><b>v1:</b> First name: "Jack", Last name: "Doe", Nick names: ["JD", "Jacky"]
* <li><b>v2:</b> First name: "Jane", Last name: "Smith", Nick names: ["JS", "Jenny"]
* <li><b>v3:</b> First name: "Jill", Last name: "Johnson", Nick names: ["JJ", "JiJo"]
* </ul>
*
* <ul>
* <li>John -[family; kind = brother]-> Jack
* <li>Jack -[family; kind = brother]-> John
* <li>Jane -[knows; kind = friend]->Jill
* <li>Jill -[knows; kind = friend]->Jane
* </ul>
*
* @param graph The graph to execute the procedure on. Must not be <code>null</code>.
*/
private static void runPhase2(final ChronoGraph graph) {
try {
// open a new graph transaction
graph.tx().open();
// extend the graph
Vertex v2 = graph.addVertex(T.id, "v2", P_FIRST_NAME, "Jane", P_LAST_NAME, "Smith", P_GENDER, "female");
v2.property(P_NICKNAMES, Sets.newHashSet("JS", "Jenny"));
Vertex v3 = graph.addVertex(T.id, "v3", P_FIRST_NAME, "Jill", P_LAST_NAME, "Johnson", P_GENDER, "female");
v3.property(P_NICKNAMES, Sets.newHashSet("JJ", "JiJo"));
// there should be one john
assertFirstNameCountEquals(graph, "John", 1);
// we should have one Jane
assertFirstNameCountEquals(graph, "Jane", 1);
// there should be 4 persons with a nickname that starts with "J"
assertEquals(4, (long)graph.traversal().V().has(P_NICKNAMES, CP.startsWithIgnoreCase("j")).count().next());
// perform the incremental commit
graph.tx().commitIncremental();
// there should be one john
assertFirstNameCountEquals(graph, "John", 1);
// we should have one Jane
assertFirstNameCountEquals(graph, "Jane", 1);
// create the associations
v2.addEdge("knows", v3, E_KIND, "friend");
v3.addEdge("knows", v2, E_KIND, "friend");
assertCommitAssertCloseTx(graph,
// assert function
(final ChronoGraph g) -> {
// jane should know jill
assertEquals(1, g.traversal().V(v2).outE("knows").toSet().size());
assertEquals(1, g.traversal().V(v3).inE("knows").toSet().size());
// jill should know jane
assertEquals(1, g.traversal().V(v3).outE("knows").toSet().size());
assertEquals(1, g.traversal().V(v2).inE("knows").toSet().size());
// there should be one john
assertFirstNameCountEquals(g, "John", 1);
// we should have one Jane
assertFirstNameCountEquals(g, "Jane", 1);
// jane should know jill
assertEquals(1, g.traversal().V(v2).outE("knows").toSet().size());
assertEquals(1, g.traversal().V(v3).inE("knows").toSet().size());
// jill should know jane
assertEquals(1, g.traversal().V(v3).outE("knows").toSet().size());
assertEquals(1, g.traversal().V(v2).inE("knows").toSet().size());
},
// commit function
(final ChronoGraph g) -> {
g.tx().commit();
g.tx().open();
return g;
}
// end of statement
);
} catch (Throwable t) {
throw new AssertionError("Execution of Phase 2 failed! See root cause for details.", t);
}
}
/**
* Performs phase 3 of the test.
*
* <p>
* This method will:
* <ul>
* <li>Create a new branch named "Scenario A"
* <li>Expands the graph data in Scenario A by using threaded transactions
* </ul>
*
* <p>
* <b>INFORMAL SCENARIO DESCRIPTION:</b><br>
* John Doe marries Jane Smith. She takes his last name, becoming "Jane Doe". Of course, her prior nickname, "JS", no longer fits and is replaced by "JD". John and Jane have a daughter, Sarah Doe. Since Jane is married to John, Jane becomes Jack's Sister-in-Law. Jack is also the uncle of Sarah.
*
* <p>
* <b>RESULTING GRAPH:</b>
* <ul>
* <li><b>v0:</b> First name: "John", Last name: "Doe", Nick names: ["JD", "Johnny"]
* <li><b>v1:</b> First name: "Jack", Last name: "Doe", Nick names: ["JD", "Jacky"]
* <li><b>v2:</b> First name: "Jane", Last name: "Doe", Nick names: ["JD", "Jenny"]
* <li><b>v3:</b> First name: "Jill", Last name: "Johnson", Nick names: ["JJ", "JiJo"]
* <li><b>v4:</b> First name: "Sarah", Last name: "Doe", Nick names: ["SD", "Sassie"]
* </ul>
*
* <ul>
* <li>John -[family; kind = brother]-> Jack
* <li>Jack -[family; kind = brother]-> John
* <li>Jane -[knows; kind = friend]->Jill
* <li>Jill -[knows; kind = friend]->Jane
* <li>Jane -[family; kind = married]-> John
* <li>John -[family; kind = married]-> Jane
* <li>Jack -[family; kind = sister-in-law]-> Jane
* <li>Jane -[family; kind = brother-in-law]-> Jack
* <li>John -[family; kind = father]-> Sarah
* <li>Jane -[family; kind = mother]-> Sarah
* <li>Jack -[family; kind = uncle]-> Sarah
* </ul>
*
* @param graph The graph to execute the procedure on. Must not be <code>null</code>.
*/
private static void runPhase3(final ChronoGraph graph) {
try {
// create the branch
graph.getBranchManager().createBranch(SCENARIO_A);
// create the threaded transaction graph
ChronoGraph tx = graph.tx().createThreadedTx(SCENARIO_A);
// fetch john and jane from the graph
Vertex vJohn = tx.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("john")).has(P_LAST_NAME, CP.eqIgnoreCase("doe")).next();
Vertex vJane = tx.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("jane")).has(P_LAST_NAME, CP.eqIgnoreCase("smith")).next();
Vertex vJack = tx.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("jack")).has(P_LAST_NAME, CP.eqIgnoreCase("doe")).next();
assertNotNull(vJohn);
assertNotNull(vJane);
assertNotNull(vJack);
// add the relationship between John and Jane
vJohn.addEdge("family", vJane, E_KIND, "married");
vJane.addEdge("family", vJohn, E_KIND, "married");
// add the relationship between Jack and Jane
vJack.addEdge("family", vJane, E_KIND, "sister-in-law");
vJane.addEdge("family", vJack, E_KIND, "brother-in-law");
// change the nicknames of jane
vJane.property(P_NICKNAMES, Sets.newHashSet("JD", "Jenny"));
// add Sarah
Vertex vSarah = tx.addVertex(T.id, "v4", P_FIRST_NAME, "Sarah", P_LAST_NAME, "Doe", P_GENDER, "female");
vSarah.property(P_NICKNAMES, Sets.newHashSet("SD", "Sassie"));
// link sarah's parents with her
vJohn.addEdge("family", vSarah, E_KIND, "father");
vJane.addEdge("family", vSarah, E_KIND, "mother");
vJack.addEdge("family", vSarah, E_KIND, "uncle");
assertCommitAssertCloseTx(tx,
// assert function
(final ChronoGraph g) -> {
// make sure that sarah is detectable via query on her first name
assertEquals(1, (long)g.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("sarah")).count().next());
// make sure we also find sarah by her nick name
assertEquals(1, (long)g.traversal().V().has(P_NICKNAMES, CP.containsIgnoreCase("sassie")).count().next());
// make sure we no longer find jane by her old nickname "JS"
assertEquals(0, (long)g.traversal().V().has(P_NICKNAMES, CP.eqIgnoreCase("JS")).count().next());
// make sure that sarah has a mother, a father and an uncle
assertEquals(vJane, g.traversal().V(vSarah).inE("family").has(E_KIND, "mother").outV().next());
assertEquals(vJohn, g.traversal().V(vSarah).inE("family").has(E_KIND, "father").outV().next());
assertEquals(vJack, g.traversal().V(vSarah).inE("family").has(E_KIND, "uncle").outV().next());
},
// commit function
(final ChronoGraph g) -> {
// this lambda expression describes how to commit the first tx and open the next
g.tx().commit();
return graph.tx().createThreadedTx("Scenario A");
}
// end of statement
);
// make sure that none of the changes we just performed are visible on the master branch
tx = graph.tx().createThreadedTx(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER);
// we should still find Jane Smith
assertEquals(vJane, tx.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("jane")).has(P_LAST_NAME, CP.eqIgnoreCase("smith")).next());
// there should not be a Jane Doe
assertEquals(0, (long)tx.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("jane")).has(P_LAST_NAME, CP.eqIgnoreCase("doe")).count().next());
// in particular, we shouldn't know sarah
assertEquals(0, (long)tx.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("sarah")).count().next());
// the branch should have a higher "now" timestamp than master
assertTrue(graph.getNow(SCENARIO_A) > graph.getNow());
} catch (Throwable t) {
throw new AssertionError("Execution of Phase 3 failed! See root cause for details.", t);
}
}
/**
* Performs phase 4 of the test.
*
* <p>
* This method will:
* <ul>
* <li>Create a new branch named "Scenario A.1", based on "Scenario A"
* <li>Remove a vertex from the graph during an incremental commit
* </ul>
*
* <p>
* <b>INFORMAL SCENARIO DESCRIPTION:</b><br>
* John dies in an accident. This is modeled as a vertex removal.
*
* <p>
* <b>RESULTING GRAPH:</b>
* <ul>
* <li><b>v1:</b> First name: "Jack", Last name: "Doe", Nick names: ["JD", "Jacky"]
* <li><b>v2:</b> First name: "Jane", Last name: "Doe", Nick names: ["JD", "Jenny"]
* <li><b>v3:</b> First name: "Jill", Last name: "Johnson", Nick names: ["JJ", "JiJo"]
* <li><b>v4:</b> First name: "Sarah", Last name: "Doe", Nick names: ["SD", "Sassie"]
* </ul>
*
* <ul>
* <li>Jane -[knows; kind = friend]->Jill
* <li>Jill -[knows; kind = friend]->Jane
* <li>Jack -[family; kind = sister-in-law]-> Jane
* <li>Jane -[family; kind = brother-in-law]-> Jack
* <li>Jane -[family; kind = mother]-> Sarah
* <li>Jack -[family; kind = uncle]-> Sarah
* </ul>
*
* @param graph The graph to execute the procedure on. Must not be <code>null</code>.
*/
public static void runPhase4(final ChronoGraph graph) {
try {
// create the branch for the scenario
GraphBranch master = graph.getBranchManager().getMasterBranch();
assertNotNull(master);
GraphBranch branchA = graph.getBranchManager().getBranch(SCENARIO_A);
assertNotNull(branchA);
GraphBranch branchA1 = graph.getBranchManager().createBranch(SCENARIO_A, SCENARIO_A1);
assertNotNull(branchA1);
assertEquals(branchA, branchA1.getOrigin());
assertEquals(Lists.newArrayList(master, branchA), branchA1.getOriginsRecursive());
// open a transaction
ChronoGraph txGraph = graph.tx().createThreadedTx(SCENARIO_A1);
// start an incremental commit process
txGraph.tx().commitIncremental();
// find John Doe
Set<Vertex> johns = txGraph.traversal().V().has(P_FIRST_NAME, "John").has(P_LAST_NAME, "Doe").toSet();
Vertex vJohn = Iterables.getOnlyElement(johns);
assertNotNull(vJohn);
// remove John Doe from the graph
vJohn.remove();
assertCommitAssertCloseTx(txGraph,
// assert function
(final ChronoGraph g) -> {
// make sure that we can't find John anymore
assertEquals(0, (long)g.traversal().V().has(P_FIRST_NAME, CP.eqIgnoreCase("john")).count().next());
// find Jack, Jane and Sarah
Vertex vJack = g.traversal().V().has(P_FIRST_NAME, "Jack").next();
Vertex vJane = g.traversal().V().has(P_FIRST_NAME, "Jane").next();
Vertex vSarah = g.traversal().V().has(P_FIRST_NAME, "Sarah").next();
// make sure that Jack has no brother anymore
assertEquals(0, g.traversal().V(vJack).outE("family").has(E_KIND, "brother").inV().toSet().size());
assertEquals(0, g.traversal().V(vJack).inE("family").has(E_KIND, "brother").outV().toSet().size());
// make sure that Jane has no husband anymore
assertEquals(0, g.traversal().V(vJane).outE("family").has(E_KIND, "married").inV().toSet().size());
assertEquals(0, g.traversal().V(vJane).inE("family").has(E_KIND, "married").outV().toSet().size());
// make sure that sarah has no father anymore
assertEquals(0, g.traversal().V(vSarah).inE("family").has(E_KIND, "father").outV().toSet().size());
// assert that we can't find John Doe by his nickname 'JD' anymore
Set<Vertex> JDs = g.traversal().V().has(P_NICKNAMES, "JD").toSet();
// there should be two 'JD's left: Jane Doe and Jack Doe
assertEquals(2, JDs.size());
assertTrue(JDs.contains(vJane));
assertTrue(JDs.contains(vJack));
// ... but John should be missing
assertFalse(JDs.contains(vJohn));
},
// commit function
(final ChronoGraph g) -> {
g.tx().commit();
return graph.tx().createThreadedTx(SCENARIO_A1);
}
// end of statement
);
// make sure that none of our changes are visible in the "Scenario A" base branch
txGraph = graph.tx().createThreadedTx(SCENARIO_A);
// make sure that we can still find John
Vertex vJohn2 = txGraph.traversal().V().has(P_FIRST_NAME, "John").has(P_LAST_NAME, "Doe").next();
assertNotNull(vJohn2);
// make sure that we still find John by his nickname
assertTrue(txGraph.traversal().V().has(P_NICKNAMES, "JD").toSet().contains(vJohn2));
// john should still have a family
Set<Edge> johnsFamilyEdges = txGraph.traversal().V(vJohn2).outE("family").toSet();
// ... he should be the father of a child...
assertEquals(1, johnsFamilyEdges.stream().filter(e -> e.value(E_KIND).equals("father")).count());
// ... there should be one bother...
assertEquals(1, johnsFamilyEdges.stream().filter(e -> e.value(E_KIND).equals("brother")).count());
// ... and he should be married
assertEquals(1, johnsFamilyEdges.stream().filter(e -> e.value(E_KIND).equals("married")).count());
txGraph.tx().close();
} catch (Throwable t) {
throw new AssertionError("Execution of Phase 4 failed! See root cause for details.", t);
}
}
// =====================================================================================================================
// UTILITIES
// =====================================================================================================================
private static void assertFirstNameCountEquals(final ChronoGraph graph, final String firstName, final int count) {
assertEquals(count, (long)graph.traversal().V().has(P_FIRST_NAME, firstName).count().next());
assertEquals(count, graph.traversal().V().has(P_FIRST_NAME, firstName).toSet().size());
}
private static void assertLastNameCountEquals(final ChronoGraph graph, final String lastName, final int count) {
assertEquals(count, (long)graph.traversal().V().has(P_LAST_NAME, lastName).count().next());
assertEquals(count, graph.traversal().V().has(P_LAST_NAME, lastName).toSet().size());
}
@SuppressWarnings("unused")
private static ChronoGraph assertCommitAssert(final ChronoGraph graph, final Consumer<ChronoGraph> assertion,
final Function<ChronoGraph, ChronoGraph> commitFunction) {
assertion.accept(graph);
ChronoGraph newGraph = commitFunction.apply(graph);
assertion.accept(newGraph);
return newGraph;
}
private static void assertCommitAssertCloseTx(final ChronoGraph graph, final Consumer<ChronoGraph> assertion,
final Function<ChronoGraph, ChronoGraph> commitFunction) {
assertion.accept(graph);
ChronoGraph newGraph = commitFunction.apply(graph);
assertion.accept(newGraph);
newGraph.tx().close();
}
}
| 26,232 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphFactoryTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/system/ChronoGraphFactoryTest.java | package org.chronos.chronograph.test.cases.system;
import org.apache.commons.io.FileUtils;
import org.chronos.chronodb.exodus.builder.ExodusChronoDBBuilderImpl;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.junit.Test;
import java.io.File;
import java.nio.file.Files;
import static org.junit.Assert.*;
public class ChronoGraphFactoryTest {
@Test
public void canCreateInMemoryDatabaseEasily() {
// without additional configuration
try (ChronoGraph graph = ChronoGraph.FACTORY.create().inMemoryGraph().build()) {
assertNotNull(graph);
}
// with additional configuration
try (ChronoGraph graph = ChronoGraph.FACTORY.create().inMemoryGraph(config -> config.assumeCachedValuesAreImmutable(true)).build()) {
assertNotNull(graph);
}
}
@Test
public void canCreateExodusDatabaseEasily() throws Exception {
File directory = Files.createTempDirectory("chronodb-test").toFile();
try {
// without additional configuration
try (ChronoGraph graph = ChronoGraph.FACTORY.create().exodusGraph(directory.getAbsolutePath()).build()) {
assertNotNull(graph);
}
// with additional configuration
try (ChronoGraph graph = ChronoGraph.FACTORY.create().exodusGraph(directory.getAbsolutePath(), config -> config.assumeCachedValuesAreImmutable(true)).build()) {
assertNotNull(graph);
}
} finally {
FileUtils.deleteDirectory(directory);
}
}
@Test
public void canCreateCustomDatabaseEasily() throws Exception {
File directory = Files.createTempDirectory("chronodb-test").toFile();
try {
try (ChronoGraph graph = ChronoGraph.FACTORY.create().customGraph(ExodusChronoDBBuilderImpl.class, (ExodusChronoDBBuilderImpl builder) -> builder.onFile(directory)).build()) {
assertNotNull(graph);
}
} finally {
FileUtils.deleteDirectory(directory);
}
}
}
| 2,084 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
MultiEdgeTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/MultiEdgeTest.java | package org.chronos.chronograph.test.cases.structure;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class MultiEdgeTest extends AllChronoGraphBackendsTest {
@Test
public void canHaveMultipleEdgesBetweenTwoVertices() {
ChronoGraph g = this.getGraph();
Vertex v1 = g.addVertex("name", "v1");
Vertex v2 = g.addVertex("name", "v2");
Edge e1 = v1.addEdge("ref", v2);
Edge e2 = v1.addEdge("ref", v2);
this.assertCommitAssert(() -> {
// basic checks
assertNotNull(e1);
assertNotNull(e2);
assertNotEquals(e1, e2);
// check the 'edges' property
Set<Edge> edges = Sets.newHashSet(v1.edges(Direction.OUT, "ref"));
assertEquals(Sets.newHashSet(e1, e2), edges);
// check the 'vertices' property with a list and assert that the duplicate is present
List<Vertex> targetVertices = Lists.newArrayList(v1.vertices(Direction.OUT, "ref"));
assertEquals(2, targetVertices.size());
assertTrue(targetVertices.contains(v2));
assertTrue(targetVertices.indexOf(v2) != targetVertices.lastIndexOf(v2));
// check the 'vertices' property with a set and assert that the duplicate is gone
Set<Vertex> targetVertexSet = Sets.newHashSet(v1.vertices(Direction.OUT, "ref"));
assertEquals(Sets.newHashSet(v2), targetVertexSet);
// check with gremlin
Iterator<Edge> gremlin1 = g.traversal().V(v1).outE("ref");
assertEquals(2, Iterators.size(gremlin1));
Iterator<Vertex> gremlin2 = g.traversal().V(v1).out("ref").dedup();
assertEquals(1, Iterators.size(gremlin2));
});
}
}
| 2,400 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
LifecycleTransitionsTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/LifecycleTransitionsTest.java | package org.chronos.chronograph.test.cases.structure;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import org.chronos.chronograph.internal.impl.structure.graph.ElementLifecycleEvent;
import org.chronos.chronograph.api.structure.ElementLifecycleStatus;
import org.chronos.chronograph.api.structure.ElementLifecycleStatus.IllegalStateTransitionException;
import org.chronos.chronograph.test.base.ChronoGraphUnitTest;
import org.chronos.common.test.junit.categories.UnitTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Map.Entry;
import static com.google.common.base.Preconditions.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(UnitTest.class)
public class LifecycleTransitionsTest extends ChronoGraphUnitTest {
@Test
public void lifecycleStateTransitionsProduceTheExpectedResults() {
// we use variables here to have shorter names (and not having to re-type the enum name in all the places)
ElementLifecycleStatus sNew = ElementLifecycleStatus.NEW;
ElementLifecycleStatus sPersisted = ElementLifecycleStatus.PERSISTED;
ElementLifecycleStatus sObsolete = ElementLifecycleStatus.OBSOLETE;
ElementLifecycleStatus sRemoved = ElementLifecycleStatus.REMOVED;
ElementLifecycleStatus sPropertyChanged = ElementLifecycleStatus.PROPERTY_CHANGED;
ElementLifecycleStatus sEdgeChanged = ElementLifecycleStatus.EDGE_CHANGED;
// we use variables here to have shorter names (and not having to re-type the enum name in all the places)
ElementLifecycleEvent eCreated = ElementLifecycleEvent.CREATED;
ElementLifecycleEvent eRecreatedFromRemoved = ElementLifecycleEvent.RECREATED_FROM_REMOVED;
ElementLifecycleEvent eRecreatedFromObsolete = ElementLifecycleEvent.RECREATED_FROM_OBSOLETE;
ElementLifecycleEvent eSaved = ElementLifecycleEvent.SAVED;
ElementLifecycleEvent eDeleted = ElementLifecycleEvent.DELETED;
ElementLifecycleEvent ePropertyChanged = ElementLifecycleEvent.PROPERTY_CHANGED;
ElementLifecycleEvent eEdgeChanged = ElementLifecycleEvent.ADJACENT_EDGE_ADDED_OR_REMOVED;
ElementLifecycleEvent eReloadedInSync = ElementLifecycleEvent.RELOADED_FROM_DB_AND_IN_SYNC;
ElementLifecycleEvent eReloadedGone = ElementLifecycleEvent.RELOADED_FROM_DB_AND_NO_LONGER_EXISTENT;
TransitionChecker checker = new TransitionChecker();
Object invalid = TransitionChecker.INVALID;
// transitions in state NEW
checker.checkTransition(sNew, eCreated, sNew);
checker.checkTransition(sNew, eDeleted, sObsolete);
checker.checkTransition(sNew, eSaved, sPersisted);
checker.checkTransition(sNew, eEdgeChanged, sNew);
checker.checkTransition(sNew, ePropertyChanged, sNew);
checker.checkTransition(sNew, eRecreatedFromObsolete, sNew);
checker.checkTransition(sNew, eRecreatedFromRemoved, sPropertyChanged);
// transitions in state OBSOLETE
checker.checkTransition(sObsolete, eCreated, invalid);
checker.checkTransition(sObsolete, eDeleted, invalid);
checker.checkTransition(sObsolete, eSaved, invalid);
checker.checkTransition(sObsolete, eEdgeChanged, invalid);
checker.checkTransition(sObsolete, ePropertyChanged, invalid);
checker.checkTransition(sObsolete, eRecreatedFromObsolete, invalid);
checker.checkTransition(sObsolete, eRecreatedFromRemoved, invalid);
// transitions in state PERSISTED
checker.checkTransition(sPersisted, eCreated, invalid);
checker.checkTransition(sPersisted, eDeleted, sRemoved);
checker.checkTransition(sPersisted, eSaved, sPersisted);
checker.checkTransition(sPersisted, eEdgeChanged, sEdgeChanged);
checker.checkTransition(sPersisted, ePropertyChanged, sPropertyChanged);
checker.checkTransition(sPersisted, eRecreatedFromObsolete, invalid);
checker.checkTransition(sPersisted, eRecreatedFromRemoved, invalid);
// transitions in state EDGE_CHANGED
checker.checkTransition(sEdgeChanged, eCreated, invalid);
checker.checkTransition(sEdgeChanged, eDeleted, sRemoved);
checker.checkTransition(sEdgeChanged, eSaved, sPersisted);
checker.checkTransition(sEdgeChanged, eEdgeChanged, sEdgeChanged);
checker.checkTransition(sEdgeChanged, ePropertyChanged, sPropertyChanged);
checker.checkTransition(sEdgeChanged, eRecreatedFromObsolete, invalid);
checker.checkTransition(sEdgeChanged, eRecreatedFromRemoved, invalid);
// transitions in state PROPERTY_CHANGED
checker.checkTransition(sPropertyChanged, eCreated, invalid);
checker.checkTransition(sPropertyChanged, eDeleted, sRemoved);
checker.checkTransition(sPropertyChanged, eSaved, sPersisted);
checker.checkTransition(sPropertyChanged, eEdgeChanged, sPropertyChanged);
checker.checkTransition(sPropertyChanged, ePropertyChanged, sPropertyChanged);
checker.checkTransition(sPropertyChanged, eRecreatedFromObsolete, invalid);
checker.checkTransition(sPropertyChanged, eRecreatedFromRemoved, invalid);
// transitions in state REMOVED
checker.checkTransition(sRemoved, eCreated, invalid);
checker.checkTransition(sRemoved, eDeleted, invalid);
checker.checkTransition(sRemoved, eSaved, invalid);
checker.checkTransition(sRemoved, eEdgeChanged, invalid);
checker.checkTransition(sRemoved, ePropertyChanged, invalid);
checker.checkTransition(sRemoved, eRecreatedFromObsolete, invalid);
checker.checkTransition(sRemoved, eRecreatedFromRemoved, invalid);
// from any state, we should be able to run the reloaded events
for (ElementLifecycleStatus status : ElementLifecycleStatus.values()) {
checker.checkTransition(status, eReloadedInSync, sPersisted);
checker.checkTransition(status, eReloadedGone, sRemoved);
}
checker.assertAllTransitionsWereChecked();
}
private static class TransitionChecker {
public static final Object INVALID = new Object();
private final SetMultimap<ElementLifecycleStatus, ElementLifecycleEvent> testedTransitions = HashMultimap.create();
public void checkTransition(ElementLifecycleStatus status, ElementLifecycleEvent event, Object result) {
checkNotNull(status, "Precondition violation - argument 'status' must not be NULL!");
checkNotNull(event, "Precondition violation - argument 'event' must not be NULL!");
checkNotNull(result, "Precondition violation - argument 'result' must not be NULL!");
if (result.equals(INVALID)) {
this.assertTransitionInvalid(status, event);
} else {
this.checkTransition(status, event, (ElementLifecycleStatus) result);
}
this.testedTransitions.put(status, event);
}
public void checkTransition(ElementLifecycleStatus oldStatus, ElementLifecycleEvent event, ElementLifecycleStatus newStatus) {
checkNotNull(oldStatus, "Precondition violation - argument 'oldStatus' must not be NULL!");
checkNotNull(event, "Precondition violation - argument 'event' must not be NULL!");
checkNotNull(newStatus, "Precondition violation - argument 'newStatus' must not be NULL!");
assertThat(oldStatus.nextState(event), is(newStatus));
this.testedTransitions.put(oldStatus, event);
}
public void assertTransitionInvalid(ElementLifecycleStatus status, ElementLifecycleEvent event) {
checkNotNull(status, "Precondition violation - argument 'status' must not be NULL!");
checkNotNull(event, "Precondition violation - argument 'event' must not be NULL!");
try {
ElementLifecycleStatus newStatus = status.nextState(event);
fail("Managed to transition from state " + status + " to " + newStatus + " with event " + event + " (expected transition to be invalid).");
} catch (IllegalStateTransitionException expected) {
// pass
this.testedTransitions.put(status, event);
}
}
public void assertAllTransitionsWereChecked() {
SetMultimap<ElementLifecycleStatus, ElementLifecycleEvent> untestedTransitions = HashMultimap.create();
for (ElementLifecycleStatus status : ElementLifecycleStatus.values()) {
for (ElementLifecycleEvent event : ElementLifecycleEvent.values()) {
if (!this.testedTransitions.containsEntry(status, event)) {
untestedTransitions.put(status, event);
}
}
}
if (!untestedTransitions.isEmpty()) {
// there were untested transitions, create an error message
StringBuilder msg = new StringBuilder();
msg.append("There were ");
msg.append(untestedTransitions.size());
msg.append(" untested lifecycle state transitions. Please add them to the test. ");
msg.append("The untested transitions are:\n");
for (Entry<ElementLifecycleStatus, ElementLifecycleEvent> entry : untestedTransitions.entries()) {
ElementLifecycleStatus status = entry.getKey();
ElementLifecycleEvent event = entry.getValue();
msg.append("\t");
msg.append(status);
msg.append("->");
msg.append(event);
msg.append("\n");
}
fail(msg.toString());
}
}
}
}
| 9,890 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphIntegrityTortureTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/GraphIntegrityTortureTest.java | package org.chronos.chronograph.test.cases.structure;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.structure.ElementLifecycleStatus;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.utils.TestUtils;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class GraphIntegrityTortureTest extends AllChronoGraphBackendsTest {
// =================================================================================================================
// TESTS
// =================================================================================================================
@Test
public void canAddAndRemoveEdgesWithCustomIDs() {
ChronoGraph g = this.getGraph();
g.tx().open();
int vertexCount = 10;
int edgeCount = 30;
int iterations = 10;
Map<Integer, Vertex> vertexById = Maps.newHashMap();
for (int i = 0; i < vertexCount; i++) {
vertexById.put(i, g.addVertex(T.id, String.valueOf(i)));
}
g.tx().commit();
// start the test
for (int iteration = 0; iteration < iterations; iteration++) {
System.out.println("Iteration #" + (iteration + 1));
g.tx().open();
Set<PlannedEdge> plannedEdges = Sets.newHashSet();
for (int e = 0; e < edgeCount; e++) {
plannedEdges.add(new PlannedEdge(
// from vertex #
TestUtils.randomBetween(0, vertexCount - 1),
// to vertex #
TestUtils.randomBetween(0, vertexCount - 1),
// edge ID
e)
);
}
g.edges().forEachRemaining(Edge::remove);
for (PlannedEdge plannedEdge : plannedEdges) {
Vertex source = Iterators.getOnlyElement(g.vertices(String.valueOf(plannedEdge.getFromId())));
Vertex target = Iterators.getOnlyElement(g.vertices(String.valueOf(plannedEdge.getToId())));
source.addEdge("test", target, T.id, String.valueOf(plannedEdge.edgeId));
}
g.tx().commit();
}
}
@Test
public void cannotAddEdgeToRemovedVertex() {
ChronoGraph g = this.getGraph();
g.addVertex(T.id, "1");
g.tx().commit();
g.tx().open();
Vertex v = Iterators.getOnlyElement(g.vertices("1"));
v.remove();
try {
v.addEdge("test", v);
fail("Managed to add edge to removed vertex!");
} catch (IllegalStateException expected) {
// pass
}
}
@Test
public void rollbackTest() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "123");
g.tx().rollback();
assertThat(g.tx().isOpen(), is(false));
assertThat(g.vertices("123").hasNext(), is(false));
g.tx().commit();
g.tx().open();
assertThat(g.vertices("123").hasNext(), is(false));
}
@Test
public void selfEdgeTest() {
ChronoGraph g = this.getGraph();
g.tx().open();
Vertex v = g.addVertex();
Edge e = v.addEdge("self", v, T.id, "1");
assertThat(((ChronoEdge) e).getStatus(), is(ElementLifecycleStatus.NEW));
g.tx().commit();
g.tx().open();
assertThat(((ChronoEdge) e).getStatus(), is(ElementLifecycleStatus.PERSISTED));
// remove the self-edge
e.remove();
assertThat(((ChronoEdge) e).getStatus(), is(ElementLifecycleStatus.REMOVED));
// add it again (same ID!)
e = v.addEdge("self", v, T.id, "1");
assertThat(((ChronoEdge) e).getStatus(), is(ElementLifecycleStatus.PROPERTY_CHANGED));
// remove it again
e.remove();
assertThat(((ChronoEdge) e).getStatus(), is(ElementLifecycleStatus.REMOVED));
g.tx().commit();
g.tx().open();
// assert that it's gone
assertThat(Iterators.size(g.edges()), is(0));
}
@Test
public void edgeRecreationDropsProperties() {
ChronoGraph g = this.getGraph();
g.tx().open();
Vertex v = g.addVertex();
Edge e = v.addEdge("self", v, T.id, "1");
e.property("foo", "bar");
g.tx().commit();
g.tx().open();
e.remove();
e = v.addEdge("self", v, T.id, "1");
assertThat(e.property("foo").isPresent(), is(false));
assertThat(g.edges("1").next().property("foo").isPresent(), is(false));
assertThat(((ChronoEdge) g.edges("1").next()).getStatus(), is(ElementLifecycleStatus.PROPERTY_CHANGED));
e.remove();
assertThat(g.edges("1").hasNext(), is(false));
g.tx().commit();
g.tx().open();
// assert that it's gone
assertThat(Iterators.size(g.edges()), is(0));
}
@Test
public void canAddAndRemoveVertexWithinSameTransaction() {
ChronoGraph graph = this.getGraph();
graph.tx().open();
Vertex v = graph.addVertex(T.id, "1");
graph.tx().commit();
graph.tx().open();
assertThat(((ChronoVertex) v).getStatus(), is(ElementLifecycleStatus.PERSISTED));
v.remove();
assertThat(((ChronoVertex) v).getStatus(), is(ElementLifecycleStatus.REMOVED));
v = graph.addVertex(T.id, "1");
assertThat(((ChronoVertex) v).getStatus(), is(ElementLifecycleStatus.PROPERTY_CHANGED));
v.remove();
assertThat(((ChronoVertex) v).getStatus(), is(ElementLifecycleStatus.REMOVED));
graph.tx().commit();
graph.tx().open();
assertThat(Iterators.size(graph.vertices()), is(0));
}
@Test
public void edgeProxyRebindingWorks() {
ChronoGraph graph = this.getGraph();
graph.tx().open();
Vertex v = graph.addVertex();
Edge e = v.addEdge("test", v, T.id, "1");
graph.tx().commit();
graph.tx().open();
assertThat(((ChronoEdge) e).isRemoved(), is(false));
e.property("Hello", "World");
assertThat(e.property("Hello").orElse(null), is("World"));
e.remove();
assertThat(((ChronoEdge) e).isRemoved(), is(true));
Vertex v2 = graph.addVertex();
Edge e2 = v2.addEdge("test2", v2, T.id, "1");
e2.property("foo", "bar");
// note that, by adding e2 with the same ID as the deleted e1,
// we re-bind the edge proxy to the new element
assertThat(e, is(sameInstance(e2)));
assertThat(e.property("Hello").isPresent(), is(false));
assertThat(e.property("foo").orElse(null), is("bar"));
graph.tx().commit();
List<Edge> edges = Lists.newArrayList(graph.edges());
assertThat(edges, contains(e));
}
// =================================================================================================================
// INNER CLASSES
// =================================================================================================================
private static class PlannedEdge {
private final int fromId;
private final int toId;
private final int edgeId;
public PlannedEdge(int fromId, int toId, int edgeId) {
this.fromId = fromId;
this.toId = toId;
this.edgeId = edgeId;
}
public int getFromId() {
return this.fromId;
}
public int getToId() {
return this.toId;
}
public int getEdgeId() {
return this.edgeId;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("PlannedEdge{");
sb.append("fromId=").append(this.fromId);
sb.append(", toId=").append(this.toId);
sb.append(", edgeId=").append(this.edgeId);
sb.append('}');
return sb.toString();
}
}
}
| 8,595 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AddEdgeTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/AddEdgeTest.java | package org.chronos.chronograph.test.cases.structure;
import com.google.common.collect.Iterators;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 AddEdgeTest extends AllChronoGraphBackendsTest {
@Test
public void addingEdgesWorks() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "v1");
Vertex v2 = graph.addVertex("name", "v2");
v1.addEdge("test", v2);
graph.tx().commit();
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Vertex v2new = Iterators.getOnlyElement(graph.vertices(v2));
assertNotNull(v2new);
Edge edge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(edge);
assertEquals(v1new, edge.outVertex());
assertEquals(v2new, edge.inVertex());
}
@Test
public void assigningEdgePropertyAfterCreationWorks() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "v1");
Vertex v2 = graph.addVertex("name", "v2");
Edge e = v1.addEdge("test", v2);
e.property("kind", "testificate");
graph.tx().commit();
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Vertex v2new = Iterators.getOnlyElement(graph.vertices(v2));
assertNotNull(v2new);
Edge edge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(edge);
assertEquals(v1new, edge.outVertex());
assertEquals(v2new, edge.inVertex());
assertEquals("testificate", edge.value("kind"));
}
@Test
public void creatingEdgeFromNewToExistingVertexWorks() {
ChronoGraph graph = this.getGraph();
Vertex v2 = graph.addVertex("name", "v2");
graph.tx().commit();
Vertex v1 = graph.addVertex("name", "v2");
Edge e = v1.addEdge("test", v2);
e.property("kind", "testificate");
graph.tx().commit();
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Vertex v2new = Iterators.getOnlyElement(graph.vertices(v2));
assertNotNull(v2new);
Edge edge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(edge);
assertEquals(v1new, edge.outVertex());
assertEquals(v2new, edge.inVertex());
assertEquals("testificate", edge.value("kind"));
}
@Test
public void creatingEdgeFromExistingToNewVertexWorks() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "v1");
graph.tx().commit();
Vertex v2 = graph.addVertex("name", "v2");
Edge e = v1.addEdge("test", v2);
e.property("kind", "testificate");
graph.tx().commit();
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Vertex v2new = Iterators.getOnlyElement(graph.vertices(v2));
assertNotNull(v2new);
Edge edge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(edge);
assertEquals(v1new, edge.outVertex());
assertEquals(v2new, edge.inVertex());
assertEquals("testificate", edge.value("kind"));
}
@Test
public void redirectingEdgeByRemovingAndAddingEdgeFromExistingToNewWorks() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "v1");
Vertex v2 = graph.addVertex("name", "v2");
Edge e = v1.addEdge("test", v2);
e.property("kind", "testificate");
graph.tx().commit();
// create a new vertex, v3
Vertex v3 = graph.addVertex("name", "v3");
// remove the old edge between v1 and v2
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Edge oldEdge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(oldEdge);
assertEquals("testificate", oldEdge.value("kind"));
oldEdge.remove();
// add a new edge from v1 to v3, with the same label and properties
Edge newEdge = v1new.addEdge("test", v3);
newEdge.property("kind", "testificate");
graph.tx().commit();
// load the graph contents again after committing the transaction
v1 = graph.vertices(v1).next();
v2 = graph.vertices(v2).next();
v3 = graph.vertices(v3).next();
// v1 should have 1 outgoing edge (to v3), and none incoming
assertEquals(1, Iterators.size(v1.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v1.edges(Direction.IN)));
assertEquals(v1, Iterators.getOnlyElement(v1.edges(Direction.OUT)).outVertex());
assertEquals(v3, Iterators.getOnlyElement(v1.edges(Direction.OUT)).inVertex());
// v2 should have no incoming or outgoing edges
assertEquals(0, Iterators.size(v2.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v2.edges(Direction.IN)));
// v3 should have one incoming edge (from v1) and no outgoing edges
assertEquals(0, Iterators.size(v3.edges(Direction.OUT)));
assertEquals(1, Iterators.size(v3.edges(Direction.IN)));
assertEquals(v1, Iterators.getOnlyElement(v3.edges(Direction.IN)).outVertex());
assertEquals(v3, Iterators.getOnlyElement(v3.edges(Direction.IN)).inVertex());
// load the edge
Edge edge = v1.edges(Direction.OUT, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
assertEquals(v1, edge.outVertex());
assertEquals(v3, edge.inVertex());
// roll back the transaction and re-load the edge from the "other side"
graph.tx().rollback();
v1 = graph.vertices(v1).next();
v2 = graph.vertices(v2).next();
v3 = graph.vertices(v3).next();
edge = v3.edges(Direction.IN, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
// assert that the edge has the correct neighoring vertices
assertEquals(v1, edge.outVertex());
assertEquals(v3, edge.inVertex());
}
@Test
public void redirectingEdgeByRemovingAndAddingEdgeFromExistingToExistingWorks() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "v1");
Vertex v2 = graph.addVertex("name", "v2");
Vertex v3 = graph.addVertex("name", "v3");
Edge e = v1.addEdge("test", v2);
e.property("kind", "testificate");
graph.tx().commit();
// remove the old edge between v1 and v2
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Edge oldEdge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(oldEdge);
assertEquals("testificate", oldEdge.value("kind"));
oldEdge.remove();
// add a new edge from v1 to v3, with the same label and properties
Edge newEdge = v1new.addEdge("test", v3);
newEdge.property("kind", "testificate");
graph.tx().commit();
// load the graph contents again after committing the transaction
v1 = graph.vertices(v1).next();
v2 = graph.vertices(v2).next();
v3 = graph.vertices(v3).next();
// v1 should have 1 outgoing edge (to v3), and none incoming
assertEquals(1, Iterators.size(v1.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v1.edges(Direction.IN)));
assertEquals(v1, Iterators.getOnlyElement(v1.edges(Direction.OUT)).outVertex());
assertEquals(v3, Iterators.getOnlyElement(v1.edges(Direction.OUT)).inVertex());
// v2 should have no incoming or outgoing edges
assertEquals(0, Iterators.size(v2.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v2.edges(Direction.IN)));
// v3 should have one incoming edge (from v1) and no outgoing edges
assertEquals(0, Iterators.size(v3.edges(Direction.OUT)));
assertEquals(1, Iterators.size(v3.edges(Direction.IN)));
assertEquals(v1, Iterators.getOnlyElement(v3.edges(Direction.IN)).outVertex());
assertEquals(v3, Iterators.getOnlyElement(v3.edges(Direction.IN)).inVertex());
// load the edge
Edge edge = v1.edges(Direction.OUT, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
assertEquals(v1, edge.outVertex());
assertEquals(v3, edge.inVertex());
// roll back the transaction and re-load the edge from the "other side"
graph.tx().rollback();
v1 = graph.vertices(v1).next();
v2 = graph.vertices(v2).next();
v3 = graph.vertices(v3).next();
edge = v3.edges(Direction.IN, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
// assert that the edge has the correct neighoring vertices
assertEquals(v1, edge.outVertex());
assertEquals(v3, edge.inVertex());
}
@Test
public void redirectingEdgeByRemovingAndAddingEdgeFromNewToExistingWorks() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "v1");
Vertex v2 = graph.addVertex("name", "v2");
Edge e = v1.addEdge("test", v2);
e.property("kind", "testificate");
graph.tx().commit();
// create a new vertex, v3
Vertex v3 = graph.addVertex("name", "v3");
// remove the old edge between v1 and v2
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Edge oldEdge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(oldEdge);
assertEquals("testificate", oldEdge.value("kind"));
oldEdge.remove();
// add a new edge from v3 to v1, with the same label and properties
Edge newEdge = v3.addEdge("test", v1);
newEdge.property("kind", "testificate");
graph.tx().commit();
// load the graph contents again after committing the transaction
v1 = graph.vertices(v1).next();
v2 = graph.vertices(v2).next();
v3 = graph.vertices(v3).next();
// v1 should have 0 outgoing edge, and 1 incoming (from v3)
assertEquals(0, Iterators.size(v1.edges(Direction.OUT)));
assertEquals(1, Iterators.size(v1.edges(Direction.IN)));
assertEquals(v3, Iterators.getOnlyElement(v1.edges(Direction.IN)).outVertex());
assertEquals(v1, Iterators.getOnlyElement(v1.edges(Direction.IN)).inVertex());
// v2 should have no incoming or outgoing edges
assertEquals(0, Iterators.size(v2.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v2.edges(Direction.IN)));
// v3 should have one outgoing edge (to v1) and no incoming edges
assertEquals(1, Iterators.size(v3.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v3.edges(Direction.IN)));
assertEquals(v3, Iterators.getOnlyElement(v3.edges(Direction.OUT)).outVertex());
assertEquals(v1, Iterators.getOnlyElement(v3.edges(Direction.OUT)).inVertex());
// load the edge
Edge edge = v3.edges(Direction.OUT, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void removingAndAddingEdgeWithSameIdWorks() {
String edgeID = "e1";
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex(T.id, "v1", "name", "v1");
Vertex v2 = graph.addVertex(T.id, "v2", "name", "v2");
Vertex v3 = graph.addVertex(T.id, "v3", "name", "v3");
Edge e = v1.addEdge("test", v2, T.id, edgeID);
e.property("kind", "testificate");
graph.tx().commit();
// remove the old edge between v1 and v2
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Edge oldEdge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(oldEdge);
assertEquals("testificate", oldEdge.value("kind"));
oldEdge.remove();
// add a new edge from v1 to v3, with the same label and properties
Edge newEdge = v1new.addEdge("test", v3, T.id, edgeID);
newEdge.property("kind", "testificate");
graph.tx().commit();
// load the graph contents again after committing the transaction
v1 = graph.vertices(v1).next();
v2 = graph.vertices(v2).next();
v3 = graph.vertices(v3).next();
// v1 should have 1 outgoing edge (to v3), and none incoming
assertEquals(1, Iterators.size(v1.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v1.edges(Direction.IN)));
assertEquals(v1, Iterators.getOnlyElement(v1.edges(Direction.OUT)).outVertex());
assertEquals(v3, Iterators.getOnlyElement(v1.edges(Direction.OUT)).inVertex());
// v2 should have no incoming or outgoing edges
assertEquals(0, Iterators.size(v2.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v2.edges(Direction.IN)));
// v3 should have one incoming edge (from v1) and no outgoing edges
assertEquals(0, Iterators.size(v3.edges(Direction.OUT)));
assertEquals(1, Iterators.size(v3.edges(Direction.IN)));
assertEquals(v1, Iterators.getOnlyElement(v3.edges(Direction.IN)).outVertex());
assertEquals(v3, Iterators.getOnlyElement(v3.edges(Direction.IN)).inVertex());
// load the edge
Edge edge = v1.edges(Direction.OUT, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
// roll back the transaction and re-load the edge from the "other side"
graph.tx().rollback();
v3 = graph.vertices(v3).next();
edge = v3.edges(Direction.IN, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void removingAndReaddingSameEdgeWithSameIdWorks() {
String edgeID = "MyId";
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "v1");
Vertex v2 = graph.addVertex("name", "v2");
Edge e = v1.addEdge("test", v2, T.id, edgeID);
e.property("kind", "testificate");
graph.tx().commit();
// remove the old edge between v1 and v2
Vertex v1new = Iterators.getOnlyElement(graph.vertices(v1));
assertNotNull(v1new);
Edge oldEdge = Iterators.getOnlyElement(v1new.edges(Direction.OUT, "test"));
assertNotNull(oldEdge);
assertEquals("testificate", oldEdge.value("kind"));
oldEdge.remove();
// add a new edge from v1 to v3, with the same label and properties
Edge newEdge = v1new.addEdge("test", v2, T.id, edgeID);
newEdge.property("kind", "testificate");
graph.tx().commit();
// load the graph contents again after committing the transaction
v1 = graph.vertices(v1).next();
v2 = graph.vertices(v2).next();
// v1 should have 1 outgoing edge (to v3), and none incoming
assertEquals(1, Iterators.size(v1.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v1.edges(Direction.IN)));
// v2 should have 1 incoming and 0 outgoing edges
assertEquals(0, Iterators.size(v2.edges(Direction.OUT)));
assertEquals(1, Iterators.size(v2.edges(Direction.IN)));
// load the edge
Edge edge = v1.edges(Direction.OUT, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
// roll back the transaction and re-load the edge from the "other side"
graph.tx().rollback();
v2 = graph.vertices(v2).next();
edge = v2.edges(Direction.IN, "test").next();
assertNotNull(edge);
assertEquals("testificate", edge.value("kind"));
}
}
| 16,992 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeSymmetryTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/EdgeSymmetryTest.java | package org.chronos.chronograph.test.cases.structure;
import com.google.common.collect.Iterators;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 EdgeSymmetryTest extends AllChronoGraphBackendsTest {
@Test
public void canAssignPropertyToEdgeFromBothSides() {
ChronoGraph g = this.getGraph();
Vertex v1 = g.addVertex();
Vertex v2 = g.addVertex();
v1.addEdge("test", v2);
g.tx().commit();
// fetch the edge twice, once from the left and once from the right
Edge eFromLeft = Iterators.getOnlyElement(v1.edges(Direction.OUT));
Edge eFromRight = Iterators.getOnlyElement(v2.edges(Direction.IN));
assertTrue(eFromLeft.equals(eFromRight));
// the two objects do not necessarily need to be the same (w.r.t. ==), but
// if we change one of them, the other one should change correspondingly.
eFromLeft.property("hello", "world");
assertThat(eFromRight.value("hello"), is("world"));
eFromRight.property("foo", "bar");
assertThat(eFromLeft.value("foo"), is("bar"));
// removing one should remove the other as well
eFromLeft.remove();
assertThat(((ChronoEdge) eFromLeft).isRemoved(), is(true));
assertThat(((ChronoEdge) eFromRight).isRemoved(), is(true));
}
@Test
public void canAssignPropertyToVertexFromBothSides() {
ChronoGraph g = this.getGraph();
{ // insert data
Vertex v1 = g.addVertex(T.id, "v1");
Vertex v2 = g.addVertex(T.id, "v2");
Vertex v3 = g.addVertex(T.id, "v3");
v1.addEdge("test", v2);
v2.addEdge("test", v3);
}
g.tx().commit();
Vertex v1 = Iterators.getOnlyElement(g.vertices("v1"));
Vertex v3 = Iterators.getOnlyElement(g.vertices("v3"));
Edge e1 = Iterators.getOnlyElement(v1.edges(Direction.OUT));
Edge e2 = Iterators.getOnlyElement(v3.edges(Direction.IN));
Vertex v2FromLeft = e1.inVertex();
Vertex v2FromRight = e2.outVertex();
assertTrue(v2FromLeft.equals(v2FromRight));
// changing one should change the other
v2FromLeft.property("hello", "world");
assertThat(v2FromRight.value("hello"), is("world"));
v2FromRight.property("foo", "bar");
assertThat(v2FromLeft.value("foo"), is("bar"));
// removing one should remove the other
v2FromLeft.remove();
assertThat(((ChronoVertex) v2FromRight).isRemoved(), is(true));
}
}
| 3,242 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyLifecycleTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/PropertyLifecycleTest.java | package org.chronos.chronograph.test.cases.structure;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexImpl;
import org.chronos.chronograph.api.structure.PropertyStatus;
import org.chronos.chronograph.internal.impl.structure.graph.proxy.ChronoVertexProxy;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
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 PropertyLifecycleTest extends AllChronoGraphBackendsTest {
@Test
public void nonExistentPropertiesAreUnknown() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
assertThat(propertyStatus(v, "test"), is(PropertyStatus.UNKNOWN));
}
@Test
public void newlyAddedPropertiesAreNew() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.NEW));
}
@Test
public void newPropertiesRemainNewWhenChanged() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
v.property("hello", "foo");
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.NEW));
}
@Test
public void newPropertiesBecomeUnknownWhenRemoved() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
v.property("hello").remove();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.UNKNOWN));
}
@Test
public void newPropertiesBecomePersistedOnCommit() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.NEW));
g.tx().commit();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.PERSISTED));
}
@Test
public void persistedPropertiesBecomeModifiedOnChange() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
g.tx().commit();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.PERSISTED));
v.property("hello", "foo");
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.MODIFIED));
}
@Test
public void canRemovePersistedProperty() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
g.tx().commit();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.PERSISTED));
v.property("hello").remove();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.REMOVED));
}
@Test
public void persistedPropertiesBecomeUnknownAfterRemoveAndCommit() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
g.tx().commit();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.PERSISTED));
v.property("hello").remove();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.REMOVED));
g.tx().commit();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.UNKNOWN));
}
@Test
public void modifiedPropertiesBecomePersistedOnCommit() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex();
v.property("hello", "world");
g.tx().commit();
v.property("hello", "foo");
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.MODIFIED));
g.tx().commit();
assertThat(propertyStatus(v, "hello"), is(PropertyStatus.PERSISTED));
}
// =================================================================================================================
// HELPER METHODS
// =================================================================================================================
private static PropertyStatus propertyStatus(final Vertex vertex, final String key) {
return vertexImpl(vertex).getPropertyStatus(key);
}
private static ChronoVertexImpl vertexImpl(final Vertex vertex) {
ChronoVertex cv = (ChronoVertex) vertex;
if (cv instanceof ChronoVertexProxy) {
ChronoVertexProxy proxy = (ChronoVertexProxy) cv;
return proxy.getElement();
} else {
return (ChronoVertexImpl) cv;
}
}
}
| 4,785 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
RemoveElementsTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/RemoveElementsTest.java | package org.chronos.chronograph.test.cases.structure;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.structure.ElementLifecycleStatus;
import org.chronos.chronograph.api.structure.PropertyStatus;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.ChronoGraphTransactionManager;
import org.chronos.chronograph.api.transaction.GraphTransactionContext;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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.Iterator;
import java.util.Set;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class RemoveElementsTest extends AllChronoGraphBackendsTest {
private static final Logger log = LoggerFactory.getLogger(RemoveElementsTest.class);
@Test
public void removingVerticesWorks() {
Graph g = this.getGraph();
g.addVertex("kind", "person", "name", "martin");
g.addVertex("kind", "person", "name", "john");
g.tx().commit();
// find me
Vertex me = g.traversal().V().has("name", "martin").toSet().iterator().next();
assertNotNull(me);
// remove me and commit
me.remove();
g.tx().commit();
// check that I'm gone
Set<Vertex> persons = g.traversal().V().has("kind", "person").toSet();
assertEquals(1, persons.size());
Vertex person = Iterables.getOnlyElement(persons);
assertEquals("john", person.value("name"));
}
@Test
public void removingEdgesWorks() {
Graph g = this.getGraph();
Vertex me = g.addVertex("kind", "person", "name", "martin");
Vertex john = g.addVertex("kind", "person", "name", "john");
me.addEdge("friend", john, "since", "forever");
g.tx().commit();
// find the edge
Edge friendship = g.traversal().E().has("since", "forever").toSet().iterator().next();
assertNotNull(friendship);
// remove the edge and commit
friendship.remove();
g.tx().commit();
// check that the edge no longer exists in gremlin
Set<Edge> edges = g.traversal().E().has("since", "forever").toSet();
assertTrue(edges.isEmpty());
// check that the edge no longer exists in the adjacent vertices
Vertex me2 = g.traversal().V().has("name", "martin").toSet().iterator().next();
Vertex john2 = g.traversal().V().has("name", "john").toSet().iterator().next();
assertFalse(me2.edges(Direction.BOTH, "friend").hasNext());
assertFalse(john2.edges(Direction.BOTH, "friend").hasNext());
}
@Test
public void removingVertexPropertiesWorks() {
Graph g = this.getGraph();
g.addVertex("kind", "person", "name", "martin");
g.tx().commit();
Vertex me = g.traversal().V().has("name", "martin").toSet().iterator().next();
assertNotNull(me);
me.property("kind").remove();
g.tx().commit();
Vertex me2 = g.traversal().V().has("name", "martin").toSet().iterator().next();
assertNotNull(me2);
assertFalse(me2.property("kind").isPresent());
}
@Test
public void removingVertexMetaPropertiesWorks() {
Graph g = this.getGraph();
Vertex me = g.addVertex("kind", "person", "name", "martin");
me.property("kind").property("job", "researcher");
g.tx().commit();
ChronoVertex me2 = (ChronoVertex) g.traversal().V().has("name", "martin").toSet().iterator().next();
assertNotNull(me2);
assertTrue(me2.property("kind").isPresent());
assertTrue(me2.property("kind").property("job").isPresent());
assertEquals("person", me2.value("kind"));
assertEquals("researcher", me2.property("kind").value("job"));
me2.property("kind").property("job").remove();
assertTrue(me2.property("kind").isPresent());
assertFalse(me2.property("kind").property("job").isPresent());
assertEquals(ElementLifecycleStatus.PROPERTY_CHANGED, me2.getStatus());
assertEquals(PropertyStatus.MODIFIED, me2.getPropertyStatus("kind"));
g.tx().commit();
Vertex me3 = g.traversal().V().has("name", "martin").toSet().iterator().next();
assertNotNull(me3);
assertTrue(me3.property("kind").isPresent());
assertFalse(me3.property("kind").property("job").isPresent());
}
@Test
public void removingEdgePropertiesWorks() {
Graph g = this.getGraph();
Vertex me = g.addVertex("kind", "person", "name", "martin");
Vertex john = g.addVertex("kind", "person", "name", "john");
me.addEdge("friend", john, "since", "forever");
g.tx().commit();
// find the edge
Edge friendship = g.traversal().E().has("since", "forever").toSet().iterator().next();
assertNotNull(friendship);
// remove the edge property and commit
friendship.property("since").remove();
g.tx().commit();
// assert that the property is gone
Vertex me2 = g.traversal().V().has("name", "martin").toSet().iterator().next();
Iterator<Edge> edges = me2.edges(Direction.BOTH, "friend");
assertTrue(edges.hasNext());
Edge friendship2 = Iterators.getOnlyElement(edges);
assertNotNull(friendship2);
assertFalse(friendship2.property("since").isPresent());
}
@Test
public void removingAVertexAlsoRemovesAdjacentEdges() {
Graph g = this.getGraph();
Vertex me = g.addVertex("kind", "person", "name", "martin");
Vertex john = g.addVertex("kind", "person", "name", "john");
me.addEdge("friend", john, "since", "forever");
g.tx().commit();
assertEquals(1, Iterators.size(g.edges()));
me.remove();
g.tx().commit();
assertEquals(0, Iterators.size(g.edges()));
}
@Test
public void removingAllVerticesAlsoRemovesAllEdges() {
// see also: org.apache.tinkerpop.gremlin.structure.VertexTest#shouldNotGetConcurrentModificationException
Graph g = this.getGraph();
Vertex v1 = g.addVertex("name", "one");
Vertex v2 = g.addVertex("name", "two");
Vertex v3 = g.addVertex("name", "three");
log.info("v1 ID: " + v1.id());
log.info("v2 ID: " + v2.id());
log.info("v3 ID: " + v3.id());
log.info("");
log.info("v1->v1: " + v1.addEdge("self", v1).id());
log.info("v1->v2: " + v1.addEdge("knows", v2).id());
log.info("v1->v3: " + v1.addEdge("knows", v3).id());
log.info("");
log.info("v2->v2: " + v2.addEdge("self", v2).id());
log.info("v2->v1: " + v2.addEdge("knows", v1).id());
log.info("v2->v3: " + v2.addEdge("knows", v3).id());
log.info("");
log.info("v3->v3: " + v3.addEdge("self", v3).id());
log.info("v3->v1: " + v3.addEdge("knows", v1).id());
log.info("v3->v2: " + v3.addEdge("knows", v2).id());
assertTrue(Sets.newHashSet(v1.vertices(Direction.OUT)).contains(v1));
assertTrue(Sets.newHashSet(v1.vertices(Direction.OUT)).contains(v2));
assertTrue(Sets.newHashSet(v1.vertices(Direction.OUT)).contains(v3));
assertTrue(Sets.newHashSet(v1.vertices(Direction.IN)).contains(v1));
assertTrue(Sets.newHashSet(v1.vertices(Direction.IN)).contains(v2));
assertTrue(Sets.newHashSet(v1.vertices(Direction.IN)).contains(v3));
assertTrue(Sets.newHashSet(v2.vertices(Direction.OUT)).contains(v1));
assertTrue(Sets.newHashSet(v2.vertices(Direction.OUT)).contains(v2));
assertTrue(Sets.newHashSet(v2.vertices(Direction.OUT)).contains(v3));
assertTrue(Sets.newHashSet(v2.vertices(Direction.IN)).contains(v1));
assertTrue(Sets.newHashSet(v2.vertices(Direction.IN)).contains(v2));
assertTrue(Sets.newHashSet(v2.vertices(Direction.IN)).contains(v3));
assertTrue(Sets.newHashSet(v3.vertices(Direction.OUT)).contains(v1));
assertTrue(Sets.newHashSet(v3.vertices(Direction.OUT)).contains(v2));
assertTrue(Sets.newHashSet(v3.vertices(Direction.OUT)).contains(v3));
assertTrue(Sets.newHashSet(v3.vertices(Direction.IN)).contains(v1));
assertTrue(Sets.newHashSet(v3.vertices(Direction.IN)).contains(v2));
assertTrue(Sets.newHashSet(v3.vertices(Direction.IN)).contains(v3));
g.tx().commit();
ChronoGraphTransactionManager txManager = (ChronoGraphTransactionManager) g.tx();
txManager.open();
ChronoGraphTransaction tx = txManager.getCurrentTransaction();
GraphTransactionContext context = tx.getContext();
assertFalse(context.isDirty());
assertTrue(Sets.newHashSet(v1.vertices(Direction.OUT)).contains(v1));
assertTrue(Sets.newHashSet(v1.vertices(Direction.OUT)).contains(v2));
assertTrue(Sets.newHashSet(v1.vertices(Direction.OUT)).contains(v3));
assertTrue(Sets.newHashSet(v1.vertices(Direction.IN)).contains(v1));
assertTrue(Sets.newHashSet(v1.vertices(Direction.IN)).contains(v2));
assertTrue(Sets.newHashSet(v1.vertices(Direction.IN)).contains(v3));
assertTrue(Sets.newHashSet(v2.vertices(Direction.OUT)).contains(v1));
assertTrue(Sets.newHashSet(v2.vertices(Direction.OUT)).contains(v2));
assertTrue(Sets.newHashSet(v2.vertices(Direction.OUT)).contains(v3));
assertTrue(Sets.newHashSet(v2.vertices(Direction.IN)).contains(v1));
assertTrue(Sets.newHashSet(v2.vertices(Direction.IN)).contains(v2));
assertTrue(Sets.newHashSet(v2.vertices(Direction.IN)).contains(v3));
assertTrue(Sets.newHashSet(v3.vertices(Direction.OUT)).contains(v1));
assertTrue(Sets.newHashSet(v3.vertices(Direction.OUT)).contains(v2));
assertTrue(Sets.newHashSet(v3.vertices(Direction.OUT)).contains(v3));
assertTrue(Sets.newHashSet(v3.vertices(Direction.IN)).contains(v1));
assertTrue(Sets.newHashSet(v3.vertices(Direction.IN)).contains(v2));
assertTrue(Sets.newHashSet(v3.vertices(Direction.IN)).contains(v3));
v3.remove();
assertEquals(5, context.getModifiedEdges().size());
assertEquals(3, context.getModifiedVertices().size());
assertEquals(2, Iterators.size(v2.edges(Direction.OUT)));
assertEquals(2, Iterators.size(v2.edges(Direction.IN)));
assertEquals(2, Iterators.size(v1.edges(Direction.OUT)));
assertEquals(2, Iterators.size(v1.edges(Direction.IN)));
g.tx().commit();
// self-edges count twice when using BOTH, according to gremlin standard.
assertEquals(4, Iterators.size(v2.edges(Direction.BOTH)));
assertEquals(4, Iterators.size(v1.edges(Direction.BOTH)));
v2.remove();
g.tx().commit();
v1.remove();
g.tx().commit();
assertEquals(0, Iterators.size(g.edges()));
}
@Test
public void removingVertexWithSelfEdgeWorks() {
Graph graph = this.getGraph();
Vertex v = graph.addVertex("name", "martin");
v.addEdge("self", v);
graph.tx().commit();
v.remove();
assertEquals(0, Iterators.size(graph.vertices()));
assertEquals(0, Iterators.size(graph.edges()));
graph.tx().commit();
assertEquals(0, Iterators.size(graph.vertices()));
assertEquals(0, Iterators.size(graph.edges()));
}
@Test
public void removingSelfEdgeWorks() {
Graph graph = this.getGraph();
Vertex v = graph.addVertex("name", "martin");
Edge e = v.addEdge("self", v);
graph.tx().commit();
e.remove();
assertEquals(1, Iterators.size(graph.vertices()));
assertEquals(0, Iterators.size(graph.edges()));
assertEquals(0, Iterators.size(v.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v.edges(Direction.IN)));
graph.tx().commit();
assertEquals(1, Iterators.size(graph.vertices()));
assertEquals(0, Iterators.size(graph.edges()));
assertEquals(0, Iterators.size(v.edges(Direction.OUT)));
assertEquals(0, Iterators.size(v.edges(Direction.IN)));
}
@Test
public void removingVerticesFromSingleLinkedCyclicGraphWorks() {
Graph g = this.getGraph();
Vertex a = g.addVertex("name", "a");
Vertex b = g.addVertex("name", "b");
Vertex c = g.addVertex("name", "c");
a.addEdge("knows", b);
b.addEdge("knows", c);
c.addEdge("knows", a);
g.tx().commit();
a.remove();
assertEquals(2, Iterators.size(g.vertices()));
assertEquals(1, Iterators.size(g.edges()));
assertEquals(1, Iterators.size(b.edges(Direction.OUT)));
assertEquals(0, Iterators.size(b.edges(Direction.IN)));
assertEquals(0, Iterators.size(c.edges(Direction.OUT)));
assertEquals(1, Iterators.size(c.edges(Direction.IN)));
g.tx().commit();
assertEquals(2, Iterators.size(g.vertices()));
assertEquals(1, Iterators.size(g.edges()));
assertEquals(1, Iterators.size(b.edges(Direction.OUT)));
assertEquals(0, Iterators.size(b.edges(Direction.IN)));
assertEquals(0, Iterators.size(c.edges(Direction.OUT)));
assertEquals(1, Iterators.size(c.edges(Direction.IN)));
}
@Test
public void removingVerticesFromDoubleLinkedCyclicGraphWorks() {
Graph g = this.getGraph();
Vertex a = g.addVertex("name", "a");
Vertex b = g.addVertex("name", "b");
Vertex c = g.addVertex("name", "c");
a.addEdge("knows", b);
a.addEdge("knows", c);
b.addEdge("knows", a);
b.addEdge("knows", c);
c.addEdge("knows", a);
c.addEdge("knows", b);
g.tx().commit();
a.remove();
assertEquals(2, Iterators.size(g.vertices()));
assertEquals(2, Iterators.size(g.edges()));
assertEquals(1, Iterators.size(b.edges(Direction.OUT)));
assertEquals(1, Iterators.size(b.edges(Direction.IN)));
assertEquals(1, Iterators.size(c.edges(Direction.OUT)));
assertEquals(1, Iterators.size(c.edges(Direction.IN)));
g.tx().commit();
assertEquals(2, Iterators.size(g.vertices()));
assertEquals(2, Iterators.size(g.edges()));
assertEquals(1, Iterators.size(b.edges(Direction.OUT)));
assertEquals(1, Iterators.size(b.edges(Direction.IN)));
assertEquals(1, Iterators.size(c.edges(Direction.OUT)));
assertEquals(1, Iterators.size(c.edges(Direction.IN)));
}
@Test
public void removingVerticesFromMaximallyConnectedGraphOneByOneWorks() {
Graph g = this.getGraph();
g.addVertex("name", "a");
g.addVertex("name", "b");
g.addVertex("name", "c");
g.addVertex("name", "d");
g.addVertex("name", "e");
// for all vertices...
g.vertices().forEachRemaining(v -> {
// ... connect with all other vertices
g.vertices().forEachRemaining(v2 -> {
v.addEdge("knows", v2);
});
});
assertEquals(5, Iterators.size(g.vertices()));
assertEquals(25, Iterators.size(g.edges()));
g.vertices().forEachRemaining(v -> {
assertEquals(5, Iterators.size(v.edges(Direction.OUT)));
assertEquals(5, Iterators.size(v.edges(Direction.IN)));
});
g.tx().commit();
Set<Vertex> vertices = Sets.newHashSet();
g.vertices().forEachRemaining(v -> {
vertices.add(v);
});
for (Vertex vertex : vertices) {
vertex.remove();
g.tx().commit();
}
assertEquals(0, Iterators.size(g.vertices()));
assertEquals(0, Iterators.size(g.edges()));
}
@Test
public void removingVerticesFromMaximallyConnectedGraphInOneGoWorks() {
Graph g = this.getGraph();
g.addVertex("name", "a");
g.addVertex("name", "b");
g.addVertex("name", "c");
g.addVertex("name", "d");
g.addVertex("name", "e");
// for all vertices...
g.vertices().forEachRemaining(v -> {
// ... connect with all other vertices
g.vertices().forEachRemaining(v2 -> {
v.addEdge("knows", v2);
});
});
assertEquals(5, Iterators.size(g.vertices()));
assertEquals(25, Iterators.size(g.edges()));
g.vertices().forEachRemaining(v -> {
assertEquals(5, Iterators.size(v.edges(Direction.OUT)));
assertEquals(5, Iterators.size(v.edges(Direction.IN)));
});
g.tx().commit();
g.vertices().forEachRemaining(v -> {
v.remove();
});
assertEquals(0, Iterators.size(g.vertices()));
assertEquals(0, Iterators.size(g.edges()));
g.tx().commit();
assertEquals(0, Iterators.size(g.vertices()));
assertEquals(0, Iterators.size(g.edges()));
}
@Test
public void removedVerticesDoNotShowUpInIndexQueryResults() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().commit();
Vertex vMartin = g.addVertex("name", "Martin");
Vertex vJoe = g.addVertex("name", "Joe");
g.tx().commit();
// modify the vertex
vMartin.property("name", "Joe");
// remove the vertex
vMartin.remove();
// assert that we don't get the removed vertex in the result set
Set<Vertex> queryResult = g.traversal().V().has("name", CP.eqIgnoreCase("joe")).toSet();
assertEquals(1, queryResult.size());
assertTrue(queryResult.contains(vJoe));
assertFalse(queryResult.contains(vMartin));
// perform a commit and repeat the checks
g.tx().commit();
queryResult = g.traversal().V().has("name", CP.eqIgnoreCase("joe")).toSet();
assertEquals(1, queryResult.size());
assertTrue(queryResult.contains(vJoe));
assertFalse(queryResult.contains(vMartin));
}
@Test
public void removedVertexIsNotReturnedByGdotV() {
final String ID = "1234";
ChronoGraph g = this.getGraph();
g.addVertex(T.id, ID);
assertNotNull(Iterators.getOnlyElement(g.vertices(ID)));
assertFalse(((ChronoVertex) Iterators.getOnlyElement(g.vertices(ID))).isRemoved());
g.tx().commit();
assertNotNull(Iterators.getOnlyElement(g.vertices(ID)));
assertFalse(((ChronoVertex) Iterators.getOnlyElement(g.vertices(ID))).isRemoved());
// remove the vertex transiently in our transaction
Iterators.getOnlyElement(g.vertices(ID)).remove();
// make sure it's not there
assertFalse(g.vertices(ID).hasNext());
// commit and check again
g.tx().commit();
assertFalse(g.vertices(ID).hasNext());
}
}
| 19,726 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ElementLifecycleTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/structure/ElementLifecycleTest.java | package org.chronos.chronograph.test.cases.structure;
import com.google.common.collect.Iterators;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoElement;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.structure.ElementLifecycleStatus;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.NoSuchElementException;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
@Category(IntegrationTest.class)
public class ElementLifecycleTest extends AllChronoGraphBackendsTest {
@Test
public void stateNewIsPreservedDuringEditing() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
// the state should be NEW after creating a vertex
assertThat(v1.getStatus(), is(ElementLifecycleStatus.NEW));
// if we change a property, the state should still be NEW
v1.property("hello", "world");
assertThat(v1.getStatus(), is(ElementLifecycleStatus.NEW));
ChronoVertex v2 = (ChronoVertex) g.addVertex();
// if we add an edge to the vertex, the status should still be NEW
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.NEW));
// if we set a property on the edge, it's state should still be NEW
e1.property("hello", "world");
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
// if we remove the edge, the vertices should still be NEW
e1.remove();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.NEW));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.NEW));
}
@Test
public void removingNewVertexMakesItObsolete() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
// the state should be NEW after creating a vertex
assertThat(v1.getStatus(), is(ElementLifecycleStatus.NEW));
v1.remove();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.OBSOLETE));
}
@Test
public void removingNewEdgeMakesItObsolete() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
e1.remove();
assertThat(e1.getStatus(), is(ElementLifecycleStatus.OBSOLETE));
}
@Test
public void savingAnElementSwitchesStateToPersistent() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
assertThat(v1.getStatus(), is(ElementLifecycleStatus.NEW));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.NEW));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
}
@Test
public void loadingAnElementFromTheStoreSwitchesStateToPersistent() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
assertThat(v1.getStatus(), is(ElementLifecycleStatus.NEW));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.NEW));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
g.tx().commit();
ChronoVertex v1Loaded = (ChronoVertex) Iterators.getOnlyElement(g.vertices(v1.id()));
ChronoVertex v2Loaded = (ChronoVertex) Iterators.getOnlyElement(g.vertices(v2.id()));
ChronoEdge e1Loaded = (ChronoEdge) Iterators.getOnlyElement(g.edges(e1.id()));
assertThat(v1Loaded.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2Loaded.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1Loaded.getStatus(), is(ElementLifecycleStatus.PERSISTED));
}
@Test
public void addingOrRemovingAnEdgeToPersistentVertexSwitchesStateToEdgeChange() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
// adding an edge should switch the vertex state to EDGE_CHANGED
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
assertThat(v1.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
g.tx().commit();
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
// remove the edge, switching the adjacent vertices to EDGE_CHANGED
e1.remove();
assertRemoved(e1);
assertThat(v1.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertRemoved(e1);
}
@Test
public void changingAPropertyOnAPersistentVertexSwitchesStateToPropertyChanged() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
v1.property("hello", "world");
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PROPERTY_CHANGED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
}
@Test
public void changingAPropertyOnAVertexInEdgeChangeStateSwitchesStateToPropertyChange() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
g.tx().commit();
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
assertThat(v1.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
v1.property("hello", "world");
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PROPERTY_CHANGED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.NEW));
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
}
@Test
public void vertexInStatePropertyChangedCannotSwitchBackToEdgeChanged() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
v1.property("hello", "world");
e1.remove();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PROPERTY_CHANGED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertRemoved(e1);
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertRemoved(e1);
}
@Test
public void removingNeighborVertexSwitchesPersistentVertexToStateEdgeChanged() {
ChronoGraph g = this.getGraph();
ChronoVertex v1 = (ChronoVertex) g.addVertex();
ChronoVertex v2 = (ChronoVertex) g.addVertex();
ChronoVertex v3 = (ChronoVertex) g.addVertex();
ChronoEdge e1 = (ChronoEdge) v1.addEdge("test", v2);
ChronoEdge e2 = (ChronoEdge) v2.addEdge("test", v3);
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(v3.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertThat(e2.getStatus(), is(ElementLifecycleStatus.PERSISTED));
v2.remove();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertRemoved(v2);
assertThat(v3.getStatus(), is(ElementLifecycleStatus.EDGE_CHANGED));
assertRemoved(e1);
assertRemoved(e2);
g.tx().commit();
assertThat(v1.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertRemoved(v2);
assertThat(v3.getStatus(), is(ElementLifecycleStatus.PERSISTED));
assertRemoved(e1);
assertRemoved(e2);
}
private static void assertRemoved(final ChronoElement element) {
try {
assertThat(element.getStatus(), is(ElementLifecycleStatus.REMOVED));
} catch (NoSuchElementException expected) {
// pass
}
}
}
| 10,934 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphIteratorsTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/iterators/GraphIteratorsTest.java | package org.chronos.chronograph.test.cases.iterators;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronograph.api.iterators.ChronoGraphIterators;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
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 GraphIteratorsTest extends AllChronoGraphBackendsTest {
@Test
public void canIterateOverAllVerticesAtHead() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex("firstName", "John", "lastName", "Doe");
g.addVertex("firstName", "Jane", "lastName", "Doe");
g.tx().commit();
g.tx().open();
g.addVertex("firstName", "Sarah", "lastName", "Doe");
g.addVertex("firstName", "Jack", "lastName", "Smith");
g.traversal().V().has("firstName", "John").forEachRemaining(Vertex::remove);
g.tx().commit();
Set<String> reportedFirstNames = Sets.newHashSet();
ChronoGraphIterators.createIteratorOn(g)
.overAllBranches()
.atHead()
.overAllVertices(state ->
reportedFirstNames.add(state.getCurrentVertex().value("firstName"))
);
assertThat(reportedFirstNames, containsInAnyOrder("Jane", "Sarah", "Jack"));
}
@Test
public void canIterateOverAllVerticesOnAllTimestamps() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex("firstName", "John", "lastName", "Doe");
g.addVertex("firstName", "Jane", "lastName", "Doe");
g.tx().commit();
g.tx().open();
g.addVertex("firstName", "Sarah", "lastName", "Doe");
g.addVertex("firstName", "Jack", "lastName", "Smith");
g.traversal().V().has("firstName", "John").forEachRemaining(Vertex::remove);
g.tx().commit();
Set<String> reportedFirstNames = Sets.newHashSet();
ChronoGraphIterators.createIteratorOn(g)
.overAllBranches()
.overAllCommitTimestampsDescending()
.overAllVertices(state ->
reportedFirstNames.add(state.getCurrentVertex().value("firstName"))
);
assertThat(reportedFirstNames, containsInAnyOrder("John", "Jane", "Sarah", "Jack"));
}
@Test
public void canIterateOverAllBranches() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex("firstName", "John", "lastName", "Doe");
g.addVertex("firstName", "Jane", "lastName", "Doe");
g.tx().commit();
g.getBranchManager().createBranch("test");
g.tx().open("test");
g.addVertex("firstName", "Sarah", "lastName", "Doe");
g.addVertex("firstName", "Jack", "lastName", "Smith");
g.traversal().V().has("firstName", "John").forEachRemaining(Vertex::remove);
g.tx().commit();
Set<String> reportedFirstNames = Sets.newHashSet();
Set<String> checkedBranchNames = Sets.newHashSet();
ChronoGraphIterators.createIteratorOn(g)
.overAllBranches((oldBranch, newBranch) -> checkedBranchNames.add(newBranch))
.overAllCommitTimestampsDescending()
.overAllVertices(state ->
reportedFirstNames.add(state.getCurrentVertex().value("firstName"))
);
assertThat(reportedFirstNames, containsInAnyOrder("John", "Jane", "Sarah", "Jack"));
assertThat(checkedBranchNames, containsInAnyOrder("test", ChronoDBConstants.MASTER_BRANCH_IDENTIFIER));
}
@Test
public void canVisitChangeTimestampsOnAllBranches() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex("firstName", "John", "lastName", "Doe");
g.addVertex("firstName", "Jane", "lastName", "Doe");
long afterFirstCommit = g.tx().commitAndReturnTimestamp();
g.getBranchManager().createBranch("test");
g.tx().open("test");
g.addVertex("firstName", "Sarah", "lastName", "Doe");
g.addVertex("firstName", "Jack", "lastName", "Smith");
g.traversal().V().has("firstName", "John").forEachRemaining(Vertex::remove);
long afterSecondCommit = g.tx().commitAndReturnTimestamp();
Set<Pair<String, Long>> visitedCoordinates = Sets.newHashSet();
ChronoGraphIterators.createIteratorOn(g)
.overAllBranches()
.overAllCommitTimestampsDescending()
.visitCoordinates(state ->
visitedCoordinates.add(Pair.of(state.getBranch(), state.getTimestamp()))
);
assertThat(visitedCoordinates, containsInAnyOrder(
Pair.of(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, afterFirstCommit),
Pair.of("test", afterSecondCommit))
);
}
@Test
public void canIterateOverHistoryOfVertexOnAllBranches() {
ChronoGraph g = this.getGraph();
String id = "vJohn";
g.tx().open();
g.addVertex(T.id, id, "firstName", "John", "lastName", "Doe");
long afterFirstCommit = g.tx().commitAndReturnTimestamp();
g.getBranchManager().createBranch("test");
g.tx().open("test");
Iterators.getOnlyElement(g.vertices(id)).property("lastName", "Smith");
long afterSecondCommit = g.tx().commitAndReturnTimestamp();
Set<Pair<String, Long>> visitedCoordinates = Sets.newHashSet();
ChronoGraphIterators.createIteratorOn(g)
.overAllBranches()
.overHistoryOfVertex(id)
.visitCoordinates(state -> {
visitedCoordinates.add(Pair.of(state.getBranch(), state.getTimestamp()));
});
assertThat(visitedCoordinates, containsInAnyOrder(
Pair.of(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, afterFirstCommit),
Pair.of("test", afterSecondCommit),
Pair.of("test", afterFirstCommit))
);
}
}
| 6,385 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphConfigurationTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/configuration/ChronoGraphConfigurationTest.java | package org.chronos.chronograph.test.cases.configuration;
import groovy.lang.Script;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.TransactionException;
import org.chronos.chronodb.inmemory.InMemoryChronoDB;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.internal.impl.groovy.StaticGroovyCompilationCache;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class ChronoGraphConfigurationTest extends AllChronoGraphBackendsTest {
@Test
public void chronoGraphConfigurationIsPresent() {
ChronoGraph graph = this.getGraph();
assertNotNull(graph.getChronoGraphConfiguration());
}
@Test
public void idExistenceCheckIsEnabledByDefault() {
ChronoGraph graph = this.getGraph();
assertTrue(graph.getChronoGraphConfiguration().isCheckIdExistenceOnAddEnabled());
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void canDisableIdExistenceCheckWithTestAnnotation() {
ChronoGraph graph = this.getGraph();
assertFalse(graph.getChronoGraphConfiguration().isCheckIdExistenceOnAddEnabled());
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void disablingIdExistenceCheckWorks() {
ChronoGraph graph = this.getGraph();
assertFalse(graph.getChronoGraphConfiguration().isCheckIdExistenceOnAddEnabled());
graph.tx().open();
Vertex v1 = graph.addVertex(T.id, "MyAwesomeId");
graph.tx().commit();
graph.tx().open();
// this should now be okay
Vertex v2 = graph.addVertex(T.id, "MyAwesomeId");
assertThat(v2, is(notNullValue()));
}
@Test
public void enablingIdExistenceCheckThrowsExceptionIfIdIsUsedTwice() {
ChronoGraph graph = this.getGraph();
assertTrue(graph.getChronoGraphConfiguration().isCheckIdExistenceOnAddEnabled());
graph.tx().open();
Vertex v1 = graph.addVertex(T.id, "MyAwesomeId");
assertNotNull(v1);
graph.tx().commit();
graph.tx().open();
try {
graph.addVertex(T.id, "MyAwesomeId");
fail("Managed to use the same ID twice!");
} catch (IllegalArgumentException expected) {
// pass
}
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
public void canDisableAutoStartTransactions() {
ChronoGraph graph = this.getGraph();
assertFalse(graph.getChronoGraphConfiguration().isTransactionAutoOpenEnabled());
try {
graph.addVertex();
fail("Managed to add a vertex to a graph while auto-transactions are disabled!");
} catch (IllegalStateException expected) {
// pass
}
// try in another thread
GraphAccessTestRunnable runnable = new GraphAccessTestRunnable(graph);
Thread worker = new Thread(runnable);
worker.start();
try {
worker.join();
} catch (InterruptedException e) {
// ignored
}
assertFalse(runnable.canAccessGraph());
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
public void canOpenManualTransactionsWhenAutoStartIsDisabled() {
ChronoGraph graph = this.getGraph();
assertFalse(graph.getChronoGraphConfiguration().isTransactionAutoOpenEnabled());
graph.tx().open();
try {
Vertex v = graph.addVertex();
v.property("name", "Martin");
graph.tx().commit();
} finally {
if (graph.tx().isOpen()) {
graph.tx().close();
}
}
}
@Test
@DontRunWithBackend({InMemoryChronoDB.BACKEND_NAME})
public void canStartUpChronoGraphInReadOnlyMode() {
// get the graph in default configuration (let it set up its persistent stores, execute migration chains etc.)
ChronoGraph graph = this.getGraph();
assertNotNull(graph);
// now that the graph has been established on persistent media, close it and reopen as read-only.
Configuration additionalConfig = new BaseConfiguration();
additionalConfig.setProperty(ChronoDBConfiguration.READONLY, true);
ChronoGraph reopenedGraph = this.closeAndReopenGraph(additionalConfig);
// this should be allowed...
reopenedGraph.tx().open();
long vertexCount = reopenedGraph.traversal().V().count().next();
assertEquals(0L, vertexCount);
reopenedGraph.tx().rollback();
// but this should not be allowed... (read-only!)
try {
reopenedGraph.tx().open();
reopenedGraph.addVertex(T.id, "123");
reopenedGraph.tx().commit();
fail("Managed to perform commit() on a read-only graph!");
} catch (TransactionException expected) {
// pass
}
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.USE_STATIC_GROOVY_COMPILATION_CACHE, value = "true")
public void canUseSharedGroovyCache(){
ChronoGraph graph = this.getGraph();
// make sure we have no leftovers from other tests in the static cache
StaticGroovyCompilationCache.getInstance().clear();
String groovyScript = "return;";
boolean added = graph.getSchemaManager().addOrOverrideValidator("dummyValidator", groovyScript);
assertFalse(added);
Class<? extends Script> compiledScript = StaticGroovyCompilationCache.getInstance().get(groovyScript);
assertNotNull(compiledScript);
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.USE_STATIC_GROOVY_COMPILATION_CACHE, value = "false")
public void canUseLocalGroovyCache(){
ChronoGraph graph = this.getGraph();
// make sure we have no leftovers from other tests in the static cache
StaticGroovyCompilationCache.getInstance().clear();
String groovyScript = "return;";
boolean added = graph.getSchemaManager().addOrOverrideValidator("dummyValidator", groovyScript);
assertFalse(added);
Class<? extends Script> compiledScript = StaticGroovyCompilationCache.getInstance().get(groovyScript);
assertNull(compiledScript); // cache miss in the static cache, because we used the local one
}
// =================================================================================================================
// INNER CLASSES
// =================================================================================================================
private static class GraphAccessTestRunnable implements Runnable {
private final ChronoGraph graph;
private boolean canAccessGraph;
public GraphAccessTestRunnable(ChronoGraph graph) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.graph = graph;
}
@Override
public void run() {
try {
this.graph.addVertex();
this.canAccessGraph = true;
} catch (IllegalStateException expected) {
this.canAccessGraph = false;
} finally {
if (this.graph.tx().isOpen()) {
this.graph.tx().rollback();
}
}
}
public boolean canAccessGraph() {
return this.canAccessGraph;
}
}
}
| 8,428 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphElementHashCodeAndEqualsTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/hashcode/GraphElementHashCodeAndEqualsTest.java | package org.chronos.chronograph.test.cases.hashcode;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.Test;
import static org.junit.Assert.*;
public class GraphElementHashCodeAndEqualsTest extends AllChronoGraphBackendsTest {
@Test
public void vertexHashCodeAndEqualsAreConsistent() {
ChronoGraph graph = this.getGraph();
Vertex v = graph.addVertex();
assertEquals(v.hashCode(), v.id().hashCode());
assertEquals(v, v);
assertEquals(v.id(), v.id());
assertNotEquals(v, v.id());
}
@Test
public void edgeHashCodeAndEqualsAreConsistent() {
ChronoGraph graph = this.getGraph();
Vertex v = graph.addVertex();
Edge e = v.addEdge("test", v);
assertEquals(e.hashCode(), e.id().hashCode());
assertEquals(e, e);
assertEquals(e.id(), e.id());
assertNotEquals(e, e.id());
}
}
| 1,098 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinStringMultivalueTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/query/GremlinStringMultivalueTest.java | package org.chronos.chronograph.test.cases.query;
import com.google.common.collect.Lists;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.TextP;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.chronograph.test.base.FailOnAllEdgesQuery;
import org.chronos.chronograph.test.base.FailOnAllVerticesQuery;
import org.junit.Test;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class GremlinStringMultivalueTest extends AllChronoGraphBackendsTest {
@Test
public void canAnswerEqualsQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", "hello").id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerEqualsQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", "hello").id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
public void canAnswerNotEqualsQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.neq("hello")).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotEqualsQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.neq("hello")).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
public void canAnswerWithinQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.within("hello", "bar")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithinQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.within("hello", "bar")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerWithoutQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.without("hello", "bar")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithoutQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.without("hello", "bar")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerStartsWithQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.startingWith("he")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerStartsWithQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.startingWith("he")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerNotStartsWithQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.notStartingWith("he")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotStartsWithQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.notStartingWith("he")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerEndsWithQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.endingWith("lo")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerEndsWithQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.endingWith("lo")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerNotEndsWithQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.notEndingWith("lo")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotEndsWithQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.notEndingWith("lo")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerContainsQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.containing("el")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerContainsQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.containing("el")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerNotContainsQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.notContaining("el")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotContainsQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", TextP.notContaining("el")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerMatchesRegexQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.matchesRegex(".*el.*")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerMatchesRegexQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.matchesRegex(".*el.*")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotMatchesRegexQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notMatchesRegex(".*el.*")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerNotMatchesRegexQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notMatchesRegex(".*el.*")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
// =================================================================================================================
// IGNORE CASE TESTS
// =================================================================================================================
@Test
public void canAnswerEqualsIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.eqIgnoreCase("HELLO")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerEqualsIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.eqIgnoreCase("HELLO")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
public void canAnswerNotEqualsIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.neqIgnoreCase("HELLO")).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotEqualsIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.neqIgnoreCase("HELLO")).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
public void canAnswerWithinIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.withinIgnoreCase(Lists.newArrayList("HELLO", "BAR"))).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithinIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.withinIgnoreCase(Lists.newArrayList("HELLO", "BAR"))).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerWithoutIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.withoutIgnoreCase(Lists.newArrayList("HELLO", "BAR"))).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithoutIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "bar"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.withoutIgnoreCase(Lists.newArrayList("HELLO", "BAR"))).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerStartsWithIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.startsWithIgnoreCase("HE")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerStartsWithIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.startsWithIgnoreCase("HE")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerNotStartsWithIgnoreQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notStartsWithIgnoreCase("HE")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotStartsWithIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "height"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notStartsWithIgnoreCase("HE")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerEndsWithIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.endsWithIgnoreCase("LO")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerEndsWithIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.endsWithIgnoreCase("LO")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerNotEndsWithIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notEndsWithIgnoreCase("LO")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotEndsWithIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yolo"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notEndsWithIgnoreCase("LO")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerContainsIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.containsIgnoreCase("EL")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerContainsIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.containsIgnoreCase("EL")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerNotContainsIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notContainsIgnoreCase("EL")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerMatchesRegexIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.matchesRegexIgnoreCase(".*EL.*")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerMatchesRegexIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.matchesRegexIgnoreCase(".*EL.*")).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotMatchesRegexIgnoreCaseQueryOnIndexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notMatchesRegexIgnoreCase(".*EL.*")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerNotMatchesRegexIgnoreCaseQueryOnUnindexedStringMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", "hello");
g.addVertex(T.id, "3", "p", Lists.newArrayList("hello"));
g.addVertex(T.id, "4", "p", Lists.newArrayList("hello", "world"));
g.addVertex(T.id, "5", "p", "foo");
g.addVertex(T.id, "6", "p", Lists.newArrayList("foo", "yellow"));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", CP.notMatchesRegexIgnoreCase(".*EL.*")).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
// =================================================================================================================
// NEGATIVE TESTS
// =================================================================================================================
@Test
public void cannotUseMultipleStringValuesForEqualityChecking() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
try {
g.traversal().V().has("p", P.eq(Lists.newArrayList("hello"))).id().toSet();
fail("managed to create gremlin query where has(...) EQUALS predicate has multiple values!");
} catch (IllegalArgumentException expected) {
// pass
}
}
@Test
public void cannotUseMultipleStringValuesForInequalityChecking() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
try {
g.traversal().V().has("p", P.neq(Lists.newArrayList("hello"))).id().toSet();
fail("managed to create gremlin query where has(...) NOT EQUALS predicate has multiple values!");
} catch (IllegalArgumentException expected) {
// pass
}
}
}
| 40,426 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinLongMultivalueTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/query/GremlinLongMultivalueTest.java | package org.chronos.chronograph.test.cases.query;
import com.google.common.collect.Lists;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.chronograph.test.base.FailOnAllEdgesQuery;
import org.chronos.chronograph.test.base.FailOnAllVerticesQuery;
import org.junit.Test;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class GremlinLongMultivalueTest extends AllChronoGraphBackendsTest {
@Test
public void canAnswerEqualsQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", 100L).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerEqualsQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", 100L).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
public void canAnswerNotEqualsQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500, 600));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.neq(100L)).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotEqualsQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500, 600));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.neq(100L)).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
public void canAnswerWithinQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.within(100L, 600L)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithinQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.within(100L, 600L)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerWithoutQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.without(100L, 600L)).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithoutQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.without(100L, 600L)).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerLessThanQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.lt(200)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerLessThanQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.lt(200)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
public void canAnswerLessThanOrEqualToQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.lte(100)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerLessThanOrEqualToQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.lte(100)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
public void canAnswerGreaterThanQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.gt(100)).id().toSet();
assertThat(ids, containsInAnyOrder("4", "5", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerGreaterThanQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.gt(100)).id().toSet();
assertThat(ids, containsInAnyOrder("4", "5", "6"));
});
}
@Test
public void canAnswerGreaterThanOrEqualToQueryOnUnindexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.gte(200)).id().toSet();
assertThat(ids, containsInAnyOrder("4", "5", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerGreaterThanOrEqualToQueryOnIndexedLongMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100L);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100L));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100L, 200L));
g.addVertex(T.id, "5", "p", 500);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500L, 600L));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", P.gte(200)).id().toSet();
assertThat(ids, containsInAnyOrder("4", "5", "6"));
});
}
// =================================================================================================================
// NEGATIVE TESTS
// =================================================================================================================
@Test
public void cannotUseMultipleLongValuesForEqualityChecking() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
try {
g.traversal().V().has("p", Lists.newArrayList(100L)).id().toSet();
fail("managed to create gremlin query where has(...) EQUALS predicate has multiple values!");
} catch (IllegalArgumentException expected) {
// pass
expected.printStackTrace();
}
}
}
| 13,770 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphQueryTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/query/GraphQueryTest.java | package org.chronos.chronograph.test.cases.query;
import com.google.common.collect.Iterables;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.chronograph.test.util.ChronoGraphTestUtil;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GraphQueryTest extends AllChronoGraphBackendsTest {
@Test
public void basicQuerySyntaxTest() {
ChronoGraph g = this.getGraph();
Set<Vertex> set = g.traversal().V().has("name", CP.containsIgnoreCase("EVA")).has("kind", "entity").toSet();
assertNotNull(set);
assertTrue(set.isEmpty());
}
@Test
public void queryToGremlinSyntaxTest() {
ChronoGraph g = this.getGraph();
Set<Edge> set = g.traversal().V().has("name", CP.containsIgnoreCase("EVA")).outE().toSet();
assertNotNull(set);
assertTrue(set.isEmpty());
}
@Test
public void simpleVertexQueriesOnPersistentStateWithoutIndexWork() {
this.performSimpleVertexQueries(false, false, true);
}
@Test
public void simpleVertexQueriesOnTransientStateWithoutIndexWork() {
this.performSimpleVertexQueries(false, false, false);
}
@Test
public void simpleVertexQueriesOnPersistentStateWithIndexWork() {
this.performSimpleVertexQueries(true, true, true);
}
@Test
public void simpleVertexQueriesOnTransientStateWithIndexWork() {
this.performSimpleVertexQueries(true, true, false);
}
@Test
public void gremlinQueriesOnPersistentStateWithoutIndexWork() {
this.performVertexToGremlinQueries(false, false, true);
}
@Test
public void gremlinQueriesOnTransientStateWithoutIndexWork() {
this.performVertexToGremlinQueries(false, false, false);
}
@Test
public void gremlinQueriesOnPersistentStateWithIndexWork() {
this.performVertexToGremlinQueries(true, true, true);
}
@Test
public void gremlinQueriesOnTransientStateWithIndexWork() {
this.performVertexToGremlinQueries(true, true, false);
}
@Test
public void canQueryNonStandardObjectTypeInHasClause() {
ChronoGraph graph = this.getGraph();
graph.addVertex("name", new FullName("John", "Doe"));
graph.addVertex("name", new FullName("Jane", "Doe"));
graph.tx().commit();
assertEquals(1, graph.traversal().V().has("name", new FullName("John", "Doe")).toSet().size());
}
@Test
public void canFindStringWithTrailingWhitespace() {
ChronoGraph graph = this.getGraph();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
graph.addVertex("name", "John ");
graph.addVertex("name", "John");
graph.tx().commit();
assertEquals("John ",
Iterables.getOnlyElement(graph.traversal().V().has("name", "John ").toSet()).value("name"));
}
@Test
public void canFindStringWithLeadingWhitespace() {
ChronoGraph graph = this.getGraph();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
graph.addVertex("name", " John");
graph.addVertex("name", "John");
graph.tx().commit();
assertEquals(" John",
Iterables.getOnlyElement(graph.traversal().V().has("name", " John").toSet()).value("name"));
}
@Test
public void indexQueriesAreLazyLoading(){
// IMPORTANT: BE VERY VERY CAREFUL WHEN RUNNING THIS TEST IN THE DEBUGGER!
// The problem is that java debuggers often call the "toString()" method on
// the objects in scope. However, calling "toString()" on a lazy graph element
// proxy leads to the resolution of the proxy. This test ASSERTS that the lazy
// proxies have NOT been resolved yet.
// In short, if this test works when you run it but FAILS when you are debugging
// it, then it is most likely due to "toString()" called by the debugger resolving
// the proxies. It is also not possible for us to change "toString()", because it
// is specified by the TinkerPop standard.
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onEdgeProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
Vertex a = g.addVertex(T.id, "a", "p", "1");
Vertex b = g.addVertex(T.id, "b", "p", "2");
Vertex c = g.addVertex(T.id, "c", "p", "1");
Edge e1 = a.addEdge("l", b, "p", "1");
Edge e2 = a.addEdge("l", c, "p", "2");
Edge e3 = b.addEdge("l", a, "p", "1");
Edge e4 = b.addEdge("l", c, "p", "2");
Edge e5 = c.addEdge("l", a, "p", "1");
Edge e6 = c.addEdge("l", b, "p", "2");
Edge e7 = a.addEdge("l", a, "p", "1");
Edge e8 = b.addEdge("l", b, "p", "2");
Edge e9 = c.addEdge("l", c, "p", "1");
g.tx().commit();
Set<Vertex> vertices = g.traversal().V().has("p", "1").toSet();
assertThat(vertices.size(), is(2));
assertThat(vertices, containsInAnyOrder(a, c));
vertices.forEach(v -> assertThat(ChronoGraphTestUtil.isFullyLoaded(v), is(false)));
Set<Edge> edges = g.traversal().E().has("p", "1").toSet();
assertThat(edges.size(), is(5));
assertThat(edges, containsInAnyOrder(e1, e3, e5, e7, e9));
edges.forEach(e -> assertThat(ChronoGraphTestUtil.isFullyLoaded(e), is(false)));
assertFalse(g.tx().getCurrentTransaction().getContext().isDirty());
}
// =====================================================================================================================
// HELPER METHODS
// =====================================================================================================================
private void performSimpleVertexQueries(final boolean indexName, final boolean indexAge,
final boolean performCommit) {
ChronoGraph g = this.getGraph();
if (indexName) {
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.tx().commit();
}
if (indexAge) {
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.tx().commit();
}
Vertex vMartin = g.addVertex("name", "Martin", "age", 26);
Vertex vJohn = g.addVertex("name", "John", "age", 19);
Vertex vMaria = g.addVertex("name", "Maria", "age", 35);
if (performCommit) {
g.tx().commit();
}
Set<Vertex> set;
set = g.traversal().V().has("name", CP.contains("n")).toSet(); // Marti[n] and Joh[n]
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vMartin));
assertTrue(set.contains(vJohn));
set = g.traversal().V().has("name", CP.containsIgnoreCase("N")).toSet(); // Marti[n] and Joh[n]
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vMartin));
assertTrue(set.contains(vJohn));
set = g.traversal().V().has("name", CP.contains("N")).toSet(); // no capital 'N' to be found in the test data
assertNotNull(set);
assertEquals(0, set.size());
set = g.traversal().V().has("name", CP.startsWith("Mar")).toSet(); // [Mar]tin and [Mar]ia
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vMartin));
assertTrue(set.contains(vMaria));
set = g.traversal().V().has("name", CP.startsWithIgnoreCase("mar")).toSet(); // [Mar]tin and [Mar]ia
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vMartin));
assertTrue(set.contains(vMaria));
set = g.traversal().V().has("name", CP.notContains("t")).toSet(); // all except Mar[t]in
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vJohn));
assertTrue(set.contains(vMaria));
set = g.traversal().V().has("name", CP.matchesRegex(".*r.*i.*")).toSet(); // Ma[r]t[i]n and Ma[r][i]a
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vMartin));
assertTrue(set.contains(vMaria));
set = g.traversal().V().has("name", CP.matchesRegex("(?i).*R.*I.*")).toSet(); // Ma[r]t[i]n and Ma[r][i]a
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vMartin));
assertTrue(set.contains(vMaria));
}
private void performVertexToGremlinQueries(final boolean indexName, final boolean indexAge,
final boolean performCommit) {
ChronoGraph g = this.getGraph();
if (indexName) {
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.tx().commit();
}
if (indexAge) {
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.tx().commit();
}
Vertex vMartin = g.addVertex("name", "Martin", "age", 26);
Vertex vJohn = g.addVertex("name", "John", "age", 19);
Vertex vMaria = g.addVertex("name", "Maria", "age", 35);
vMartin.addEdge("knows", vJohn);
vJohn.addEdge("knows", vMaria);
vMaria.addEdge("knows", vMartin);
if (performCommit) {
g.tx().commit();
}
Set<Vertex> set;
// - The first query (name ends with 'N') delivers Martin and John.
// - Traversing the 'knows' edge on both Martin and John leads to:
// -- John (Martin-knows->John)
// -- Maria (John-knows->Maria)
set = g.traversal().V().has("name", CP.endsWithIgnoreCase("N")).out("knows").toSet();
assertNotNull(set);
assertEquals(2, set.size());
assertTrue(set.contains(vJohn));
assertTrue(set.contains(vMaria));
}
private static class FullName {
private String firstName;
private String lastName;
@SuppressWarnings("unused")
protected FullName() {
// (de-)serialization constructor
}
public FullName(final String firstName, final String lastName) {
this.firstName = firstName;
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());
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;
}
FullName other = (FullName) 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;
}
return true;
}
}
}
| 12,416 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoCompareTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/query/ChronoCompareTest.java | package org.chronos.chronograph.test.cases.query;
import org.chronos.chronograph.internal.impl.query.ChronoStringCompare;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class ChronoCompareTest {
@Test
public void testChronoCompareNegation(){
for(ChronoStringCompare compare : ChronoStringCompare.values()){
assertThat(compare.negate().negate(), is(compare));
}
}
} | 465 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinDoubleMultivalueTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/query/GremlinDoubleMultivalueTest.java | package org.chronos.chronograph.test.cases.query;
import com.google.common.collect.Lists;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.chronograph.test.base.FailOnAllEdgesQuery;
import org.chronos.chronograph.test.base.FailOnAllVerticesQuery;
import org.junit.Test;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class GremlinDoubleMultivalueTest extends AllChronoGraphBackendsTest {
@Test
public void canAnswerEqualsQueryOnUnindexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
this.assertCommitAssert(() -> {
Set<Object> ids = g.traversal().V().has("p", 100.0).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerEqualsQueryOnIndexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", 100.0).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
public void canAnswerNotEqualsQueryOnUnindexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.neq(100.0)).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerNotEqualsQueryOnIndexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.neq(100.0)).id().toSet();
assertThat(ids, containsInAnyOrder("5", "6"));
});
}
@Test
public void canAnswerWithinQueryOnUnindexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.within(100.0, 600.0)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithinQueryOnIndexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.within(100.0, 600.0)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "6"));
});
}
@Test
public void canAnswerWithoutQueryOnUnindexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.without(100.0, 600.0)).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerWithoutQueryOnIndexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.without(100.0, 600.0)).id().toSet();
assertThat(ids, containsInAnyOrder("5"));
});
}
@Test
public void canAnswerLessThanQueryOnUnindexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.lt(500.0)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerLessThanQueryOnIndexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.lt(500.0)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4"));
});
}
@Test
public void canAnswerLessThanOrEqualToQueryOnUnindexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
g.addVertex(T.id, "7", "p", Lists.newArrayList(1000.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.lte(500.0)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "5", "6"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canAnswerLessOrEqualToThanQueryOnIndexedDoubleMultivalues() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
g.addVertex(T.id, "1");
g.addVertex(T.id, "2", "p", 100.0);
g.addVertex(T.id, "3", "p", Lists.newArrayList(100.0));
g.addVertex(T.id, "4", "p", Lists.newArrayList(100.0, 200.0));
g.addVertex(T.id, "5", "p", 500.0);
g.addVertex(T.id, "6", "p", Lists.newArrayList(500.0, 600.0));
g.addVertex(T.id, "7", "p", Lists.newArrayList(1000.0));
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("p", P.lte(500.0)).id().toSet();
assertThat(ids, containsInAnyOrder("2", "3", "4", "5", "6"));
});
}
// =================================================================================================================
// NEGATIVE TESTS
// =================================================================================================================
@Test
public void cannotUseMultipleDoubleValuesForEqualityChecking() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("p").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
try {
g.traversal().V().has("p", Lists.newArrayList(100.0)).id().toSet();
fail("managed to create gremlin query where has(...) EQUALS predicate has multiple values!");
} catch (IllegalArgumentException expected) {
// pass
}
}
}
| 10,880 | 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.chronograph/src/test/java/org/chronos/chronograph/test/cases/index/NumericIndexingTest.java | package org.chronos.chronograph.test.cases.index;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.impl.index.IndexType;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class NumericIndexingTest extends AllChronoGraphBackendsTest {
@Test
public void canAddLongIndex() {
ChronoGraph g = this.getGraph();
ChronoGraphIndex index = g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("number").acrossAllTimestamps().build();
assertNotNull(index);
g.getIndexManagerOnMaster().reindexAll();
assertEquals(IndexType.LONG, index.getIndexType());
assertEquals("number", index.getIndexedProperty());
assertTrue(g.getIndexManagerOnMaster().getIndexedVertexPropertiesAtAnyPointInTime().contains(index));
}
@Test
public void canAddDoubleIndex() {
ChronoGraph g = this.getGraph();
ChronoGraphIndex index = g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("number").acrossAllTimestamps().build();
assertNotNull(index);
g.getIndexManagerOnMaster().reindexAll();
assertEquals(IndexType.DOUBLE, index.getIndexType());
assertEquals("number", index.getIndexedProperty());
assertTrue(g.getIndexManagerOnMaster().getIndexedVertexPropertiesAtAnyPointInTime().contains(index));
}
@Test
public void simpleLongQueryUsingGremlinWorks() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("number").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
{ // insert some data
g.addVertex("name", "a", "number", 24);
g.addVertex("name", "b", "number", 37);
g.addVertex("name", "c", "number", 58);
}
this.assertCommitAssert(() -> {
// query the graph
this.assertNamesEqual("a", g.traversal().V().has("number", P.eq(24)));
this.assertNamesEqual("a", g.traversal().V().has("number", 24));
this.assertNamesEqual("c", g.traversal().V().has("number", P.gt(37)));
this.assertNamesEqual("b", "c", g.traversal().V().has("number", P.gte(37)));
this.assertNamesEqual("a", "b", g.traversal().V().has("number", P.lt(58)));
this.assertNamesEqual("a", "b", g.traversal().V().has("number", P.lte(37)));
});
}
@Test
public void simpleDoubleQueryUsingGremlinWorks() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("number").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
{ // insert some data
g.addVertex("name", "a", "number", 3.1415);
g.addVertex("name", "b", "number", 24.36);
g.addVertex("name", "c", "number", 27.58);
}
this.assertCommitAssert(() -> {
// query the graph
this.assertNamesEqual("a", g.traversal().V().has("number", P.eq(3.1415)));
this.assertNamesEqual("a", g.traversal().V().has("number", 3.1415));
this.assertNamesEqual("c", g.traversal().V().has("number", P.gt(24.36)));
this.assertNamesEqual("b", "c", g.traversal().V().has("number", P.gte(24.36)));
this.assertNamesEqual("a", "b", g.traversal().V().has("number", P.lt(27.58)));
this.assertNamesEqual("a", "b", g.traversal().V().has("number", P.lte(24.36)));
});
}
@SuppressWarnings("unchecked")
private void assertNamesEqual(final Object... objects) {
List<Object> list = Lists.newArrayList(objects);
Object last = list.get(list.size() - 1);
Set<Element> elements = null;
if (last instanceof Iterable) {
elements = Sets.newHashSet((Iterable<Element>) last);
} else if (last instanceof Iterator) {
elements = Sets.newHashSet((Iterator<Element>) last);
} else {
String typeName = "NULL";
if (last != null) {
typeName = last.getClass().getName();
}
fail("Last element of 'assertNamesEqual' varargs must either be a Iterable<Element> or a Iterator<Element> (found: " + typeName + ")");
}
Set<String> elementNames = elements.stream().map(e -> (String) e.value("name")).collect(Collectors.toSet());
Set<String> names = list.subList(0, list.size() - 1).stream().map(k -> (String) k).collect(Collectors.toSet());
assertEquals(names, elementNames);
}
}
| 5,201 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
StringIndexingTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/index/StringIndexingTest.java | package org.chronos.chronograph.test.cases.index;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.chronos.common.test.junit.categories.SlowTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Set;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class StringIndexingTest extends AllChronoGraphBackendsTest {
@Test
public void indexCreationWorks() {
ChronoGraph g = this.getGraph();
ChronoGraphIndex index = g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
assertNotNull(index);
g.getIndexManagerOnMaster().reindexAll();
g.tx().commit();
Vertex v = g.addVertex("name", "Martin");
g.addVertex("name", "John");
g.addVertex("name", "Martina");
g.tx().commit();
// find by case-sensitive search
assertEquals(v, Iterables.getOnlyElement(g.traversal().V().has("name", "Martin").toSet()));
}
@Test
public void canDropIndex() {
ChronoGraph g = this.getGraph();
ChronoGraphIndex index = g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
assertNotNull(index);
g.getIndexManagerOnMaster().reindexAll();
assertTrue(g.getIndexManagerOnMaster().isVertexPropertyIndexedAtAnyPointInTime("name"));
g.getIndexManagerOnMaster().dropIndex(index);
assertFalse(g.getIndexManagerOnMaster().isVertexPropertyIndexedAtAnyPointInTime("name"));
}
@Test
public void canCreateMultipleIndices() {
ChronoGraph g = this.getGraph();
ChronoGraphIndex index = g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
assertNotNull(index);
g.getIndexManagerOnMaster().reindexAll();
Vertex v = g.addVertex("name", "Martin");
Vertex vJohn = g.addVertex("name", "John", "description", "foo");
g.addVertex("name", "Martina", "description", "bar");
g.tx().commit();
assertTrue(g.getIndexManagerOnMaster().isVertexPropertyIndexedAtAnyPointInTime("name"));
// find by case-sensitive search
assertEquals(v, Iterables.getOnlyElement(g.traversal().V().has("name", "Martin").toSet()));
ChronoGraphIndex descriptionIndex = g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("description").acrossAllTimestamps().build();
assertNotNull(descriptionIndex);
g.tx().commit();
assertTrue(g.getIndexManagerOnMaster().isVertexPropertyIndexedAtAnyPointInTime("name"));
assertTrue(g.getIndexManagerOnMaster().isVertexPropertyIndexedAtAnyPointInTime("description"));
assertEquals(v, Iterables.getOnlyElement(g.traversal().V().has("name", "Martin").toSet()));
assertEquals(vJohn, Iterables.getOnlyElement(g.traversal().V().has("description", "foo").toSet()));
}
@Test
public void renamingElementWorks() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
Vertex v1 = g.addVertex("name", "Test");
Vertex v2 = g.addVertex("name", "John");
g.tx().commit();
// assert that we can find the elements
assertEquals(v1, Iterables.getOnlyElement(g.traversal().V().has("name", "Test").toSet()));
assertEquals(v2, Iterables.getOnlyElement(g.traversal().V().has("name", "John").toSet()));
// rename one element
v1.property("name", "Hello");
// assert that we can find the element by its new name
assertEquals(v1, Iterables.getOnlyElement(g.traversal().V().has("name", "Hello").toSet()));
// assert that we cannot find the element by its old name anymore
assertEquals(0, g.traversal().V().has("name", "Test").toSet().size());
// perform the commit
g.tx().commit();
// assert that we can find the element by its new name
assertEquals(v1, Iterables.getOnlyElement(g.traversal().V().has("name", "Hello").toSet()));
// assert that we cannot find the element by its old name anymore
assertEquals(0, g.traversal().V().has("name", "Test").toSet().size());
}
@Test
public void renamingElementInIncrementalCommitWorks() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
Vertex v1 = g.addVertex("name", "Test");
Vertex v2 = g.addVertex("name", "John");
g.tx().commit();
// assert that we can find the elements
assertEquals(v1, Iterables.getOnlyElement(g.traversal().V().has("name", "Test").toSet()));
assertEquals(v2, Iterables.getOnlyElement(g.traversal().V().has("name", "John").toSet()));
g.tx().commitIncremental();
// rename one element
v1.property("name", "Hello");
// assert that we can find the element by its new name
assertEquals(v1, Iterables.getOnlyElement(g.traversal().V().has("name", "Hello").toSet()));
// assert that we cannot find the element by its old name anymore
assertEquals(0, g.traversal().V().has("name", "Test").toSet().size());
g.tx().commitIncremental();
// perform the commit
g.tx().commit();
// assert that we can find the element by its new name
assertEquals(v1, Iterables.getOnlyElement(g.traversal().V().has("name", "Hello").toSet()));
// assert that we cannot find the element by its old name anymore
assertEquals(0, g.traversal().V().has("name", "Test").toSet().size());
}
@Test
@SuppressWarnings("unused")
public void queryingTransientStateWithIndexWorks() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("color").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
Vertex v0 = g.addVertex("color", "red");
Vertex v1 = g.addVertex("color", "green");
Vertex v2 = g.addVertex("color", "blue");
this.assertCommitAssert(() -> {
assertEquals(Sets.newHashSet(v0, v1), g.traversal().V().has("color", CP.contains("r")).toSet());
});
}
@Test
@SuppressWarnings("unused")
public void queryingTransientStateWithoutIndexWorks() {
ChronoGraph g = this.getGraph();
g.tx().open();
Vertex v0 = g.addVertex("color", "red");
Vertex v1 = g.addVertex("color", "green");
Vertex v2 = g.addVertex("color", "blue");
this.assertCommitAssert(() -> {
assertEquals(Sets.newHashSet(v0, v1), g.traversal().V().has("color", CP.contains("r")).toSet());
});
}
@Test
@SuppressWarnings("unused")
public void indexingOfMultiplicityManyValuesWorks() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("colors").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
Vertex v0 = g.addVertex("colors", Sets.newHashSet("red", "green", "blue"));
Vertex v1 = g.addVertex("colors", Sets.newHashSet("red", "black", "white"));
Vertex v2 = g.addVertex("colors", Sets.newHashSet("yellow", "green", "white"));
// try to find all white vertices
this.assertCommitAssert(() -> {
assertEquals(Sets.newHashSet(v1, v2), g.traversal().V().has("colors", CP.eqIgnoreCase("white")).toSet());
});
}
@Test
public void t_EntityTest1() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("Name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("Kind").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.tx().open();
// g.tx().commitIncremental();
Vertex entity1 = g.addVertex(T.id, "id1", "Name", "name1", "Kind", "entity", "Site", "propertyA", "OLA", "Gold");
Vertex entity2 = g.addVertex(T.id, "id2", "Name", "name2", "Kind", "entity", "Site", "propertyB");
// g.tx().commitIncremental();
g.tx().commit();
// assert that we find the entities
assertEquals(entity1, Iterables.getOnlyElement(g.traversal().V().has("Name", "name1").has("Kind", "entity").toSet()));
assertEquals(entity2, Iterables.getOnlyElement(g.traversal().V().has("Name", "name2").has("Kind", "entity").toSet()));
g.tx().rollback();
// perform some modifications on the vertices
g.tx().open();
// g.tx().commitIncremental();
entity1.property("Name", "propertyA");
entity1.property("Site").remove();
entity1.property("OLA").remove();
entity2.property("Name", "propertyB");
entity2.property("Site").remove();
entity2.property("OLA").remove();
// g.tx().commitIncremental();
g.tx().commit();
// assert that we find the entities
assertEquals(entity1, Iterables.getOnlyElement(g.traversal().V().has("Name", "propertyA").has("Kind", "entity").toSet()));
assertEquals(entity2, Iterables.getOnlyElement(g.traversal().V().has("Name", "propertyB").has("Kind", "entity").toSet()));
}
@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() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstName").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastName").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onEdgeProperty("kind").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
Vertex v1 = g.addVertex("firstName", "John", "lastName", "Doe");
Vertex v2 = g.addVertex("firstName", "Jane", "lastName", "Doe");
Vertex v3 = g.addVertex("firstName", "Jack", "lastName", "Johnson");
Vertex v4 = g.addVertex("firstName", "Sarah", "lastName", "Doe");
Set<Vertex> vertices = Sets.newHashSet(v1, v2, v3, v4);
for (Vertex vA : vertices) {
for (Vertex vB : vertices) {
if (vA.equals(vB) == false) {
vA.addEdge("connect", vB, "kind", "connect");
}
}
}
assertEquals(3, (long)g.traversal().V().has("firstName", CP.startsWithIgnoreCase("j")).count().next());
g.tx().commit();
assertEquals(3, (long)g.traversal().V().has("firstName", CP.startsWithIgnoreCase("j")).count().next());
int queryResultSize = 3;
while (vertices.isEmpty() == false) {
Vertex v = vertices.iterator().next();
vertices.remove(v);
if (((String) v.value("firstName")).startsWith("J")) {
v.remove();
queryResultSize--;
assertEquals(queryResultSize, (long)g.traversal().V().has("firstName", CP.startsWithIgnoreCase("j")).count().next());
} else {
v.remove();
assertEquals(queryResultSize, (long)g.traversal().V().has("firstName", CP.startsWithIgnoreCase("j")).count().next());
}
}
assertEquals(0, queryResultSize);
assertEquals(0, (long)g.traversal().V().has("firstName", CP.startsWithIgnoreCase("j")).count().next());
assertEquals(0, (long)g.traversal().V().has("lastName", CP.matchesRegex(".*")).count().next());
assertEquals(0, (long)g.traversal().E().has("kind", CP.matchesRegex(".*")).count().next());
}
@Test
@Category(SlowTest.class)
@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 massiveDeleteTest() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstName").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastName").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
Set<String> vertexIds = Sets.newHashSet();
for (int i = 0; i < 10_000; i++) {
Vertex v = g.addVertex("firstName", "John#" + i, "lastName", "Doe");
vertexIds.add((String) v.id());
if (i % 1_000 == 0) {
g.tx().commitIncremental();
}
}
assertEquals(10_000, (long)g.traversal().V().has("firstName", CP.startsWith("John")).count().next());
g.tx().commit();
assertEquals(10_000, (long)g.traversal().V().has("firstName", CP.startsWith("John")).count().next());
for (int i = 0; i < 10_000; i++) {
Vertex v = Iterators.getOnlyElement(g.vertices(vertexIds.iterator().next()), null);
assertNotNull(v);
vertexIds.remove(v.id());
v.remove();
if (i % 1_000 == 0) {
assertEquals(vertexIds.size(), (long)g.traversal().V().has("firstName", CP.startsWith("John")).count().next());
g.tx().commitIncremental();
assertEquals(vertexIds.size(), (long)g.traversal().V().has("firstName", CP.startsWith("John")).count().next());
}
}
assertEquals(0, (long)g.traversal().V().has("firstName", CP.startsWith("John")).count().next());
g.tx().commit();
assertEquals(0, (long)g.traversal().V().has("firstName", CP.startsWith("John")).count().next());
}
@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 trackingDownTheGhostVertexTest() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("kind").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex("kind", "person", "name", "John");
g.addVertex("kind", "person", "name", "Jane");
g.tx().commit();
g.getBranchManager().createBranch("test");
// perform further inserts on master
g.tx().open();
Object ghostId = g.addVertex("kind", "person", "name", "Ghost").id();
g.tx().commit();
// perform an insert on "test"
g.tx().open("test");
g.addVertex("kind", "person", "name", "Jack");
g.tx().commit();
// delete the ghost on "master"
g.tx().open();
Iterators.getOnlyElement(g.vertices(ghostId)).remove();
g.tx().commit();
// assert that the ghost is not present on "master"
g.tx().open();
assertEquals(0, g.traversal().V().has("name", "Ghost").toSet().size());
assertEquals(0, g.traversal().V().toStream().filter(v -> v.value("name").equals("Ghost")).count());
assertEquals(0, g.traversal().V().has("kind", "person").toStream().filter(v -> v.value("name").equals("Ghost"))
.count());
g.tx().close();
// assert that the ghost is not present on "test"
g.tx().open("test");
assertEquals(0, g.traversal().V().has("name", "Ghost").toSet().size());
assertEquals(0, g.traversal().V().toStream().filter(v -> v.value("name").equals("Ghost")).count());
assertEquals(0, g.traversal().V().has("kind", "person").toStream().filter(v -> v.value("name").equals("Ghost"))
.count());
g.tx().close();
}
@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 secondaryIndexingRemoveTestWithBranching() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("kind").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
Object johnsId = g.addVertex("kind", "person", "name", "John").id();
Object janesId = g.addVertex("kind", "person", "name", "Jane").id();
g.tx().commit();
g.getBranchManager().createBranch("test");
// perform a delete on "master"
g.tx().open();
Iterators.getOnlyElement(g.vertices(johnsId)).remove();
g.tx().commit();
// perform an insert on "test"
g.tx().open("test");
g.addVertex("kind", "person", "name", "Jack");
g.tx().commit();
// delete jane on "master"
g.tx().open();
Iterators.getOnlyElement(g.vertices(janesId)).remove();
g.tx().commit();
// assert that no persons are present on "master" anymore
g.tx().open();
assertEquals(0, g.traversal().V().has("kind", "person").toSet().size());
assertEquals(0, g.traversal().V().toStream().filter(v -> v.value("kind").equals("person")).count());
g.tx().close();
// assert that the persons are still present on "test"
g.tx().open("test");
assertEquals(3, g.traversal().V().has("kind", "person").toSet().size());
assertEquals(3, g.traversal().V().toStream().filter(v -> v.value("kind").equals("person")).count());
g.tx().close();
}
}
| 19,535 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphIndexingUtilsTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/index/GraphIndexingUtilsTest.java | package org.chronos.chronograph.test.cases.index;
import com.google.common.collect.Sets;
import org.chronos.chronograph.internal.impl.index.GraphIndexingUtils;
import org.chronos.chronograph.internal.impl.structure.record2.PropertyRecord2;
import org.chronos.chronograph.test.base.ChronoGraphUnitTest;
import org.junit.Test;
import java.util.Collections;
import static org.junit.Assert.*;
public class GraphIndexingUtilsTest extends ChronoGraphUnitTest {
@Test
public void canIndexSingleStringValue() {
PropertyRecord2 property = new PropertyRecord2("test", "Hello");
assertEquals(Collections.singleton("Hello"), GraphIndexingUtils.getStringIndexValues(property));
}
@Test
public void canIndexMultipleStringValues() {
PropertyRecord2 property = new PropertyRecord2("test", Sets.newHashSet("Hello", "world"));
assertEquals(Sets.newHashSet("Hello", "world"), GraphIndexingUtils.getStringIndexValues(property));
}
@Test
public void canIndexSingleLongValue() {
PropertyRecord2 property = new PropertyRecord2("test", 1234L);
assertEquals(Sets.newHashSet(1234L), GraphIndexingUtils.getLongIndexValues(property));
}
@Test
public void canIndexMultipleLongValues() {
PropertyRecord2 property = new PropertyRecord2("test", Sets.newHashSet(-1234L, 5678L));
assertEquals(Sets.newHashSet(-1234L, 5678L), GraphIndexingUtils.getLongIndexValues(property));
}
@Test
@SuppressWarnings("unchecked")
public void indexingLongValuesWillSkipStrings() {
PropertyRecord2 property = new PropertyRecord2("test", Sets.newHashSet(-1234L, 456L, "-3243", "34"));
assertEquals(Sets.newHashSet(-1234L, 456L), GraphIndexingUtils.getLongIndexValues(property));
}
@Test
public void canIndexSingleDoubleValue() {
double val = 12.34;
PropertyRecord2 property = new PropertyRecord2("test", val);
assertEquals(Sets.newHashSet(val), GraphIndexingUtils.getDoubleIndexValues(property));
}
@Test
public void canIndexMultipleDoubleValues() {
double val1 = -3.1415;
double val2 = 24.36;
PropertyRecord2 property = new PropertyRecord2("test", Sets.newHashSet(val1, val2));
assertEquals(Sets.newHashSet(val1, val2), GraphIndexingUtils.getDoubleIndexValues(property));
}
@Test
@SuppressWarnings("unchecked")
public void indexingDoubleValuesWillSkipStrings() {
PropertyRecord2 property = new PropertyRecord2("test", Sets.newHashSet(-1234.0, 456.0, "-3243.5", "34"));
assertEquals(Sets.newHashSet(-1234.0, 456.0), GraphIndexingUtils.getDoubleIndexValues(property));
}
@Test
public void indexingLongsAlsoAcceptsIntegers() {
PropertyRecord2 property = new PropertyRecord2("test", 123);
assertEquals(Sets.newHashSet(123L), GraphIndexingUtils.getLongIndexValues(property));
}
@Test
public void indexingDoublesAlsoAcceptsIntegers() {
PropertyRecord2 property = new PropertyRecord2("test", 123);
assertEquals(Sets.newHashSet(123.0), GraphIndexingUtils.getDoubleIndexValues(property));
}
@Test
@SuppressWarnings("unchecked")
public void indexingLongValuesIgnoresFloatingPointValues() {
PropertyRecord2 property = new PropertyRecord2("test", Sets.newHashSet(123.4, 24));
assertEquals(Sets.newHashSet(24L), GraphIndexingUtils.getLongIndexValues(property));
}
}
| 3,460 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphBranchTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/branch/GraphBranchTest.java | package org.chronos.chronograph.test.cases.branch;
import com.google.common.collect.Lists;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 GraphBranchTest extends AllChronoGraphBackendsTest {
@Test
public void canRetrieveMasterBranch() {
ChronoGraph graph = this.getGraph();
GraphBranch masterBranch = graph.getBranchManager().getMasterBranch();
checkNotNull(masterBranch, "Precondition violation - argument 'masterBranch' must not be NULL!");
assertEquals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, masterBranch.getName());
assertEquals(0, masterBranch.getBranchingTimestamp());
assertNull(masterBranch.getOrigin());
assertTrue(masterBranch.getOriginsRecursive().isEmpty());
}
@Test
public void canCreateBranch() {
ChronoGraph graph = this.getGraph();
// add some dummy test data
Vertex vJohn = graph.addVertex("firstname", "John", "lastname", "Doe");
graph.tx().commit();
GraphBranch masterBranch = graph.getBranchManager().getMasterBranch();
// create the branch
GraphBranch branchScenarioA = graph.getBranchManager().createBranch("scenarioA");
assertNotNull(branchScenarioA);
assertEquals(masterBranch, branchScenarioA.getOrigin());
assertEquals(Lists.newArrayList(masterBranch), branchScenarioA.getOriginsRecursive());
// add test data to the branch
graph.tx().open(branchScenarioA.getName());
Vertex vJane = graph.addVertex("firstname", "Jane", "lastname", "Doe");
vJohn.addEdge("married", vJane);
vJane.addEdge("married", vJohn);
graph.tx().commit();
// in the master branch, we shouldn't see the change
graph.tx().open();
assertFalse(vJohn.edges(Direction.OUT, "married").hasNext());
graph.tx().close();
// in the scenario branch, we should see the changes
graph.tx().open(branchScenarioA.getName());
assertEquals(vJane, vJohn.edges(Direction.OUT, "married").next().inVertex());
graph.tx().close();
}
}
| 2,665 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
IncrementalGraphCommitTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/IncrementalGraphCommitTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.exceptions.ChronoDBCommitException;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Iterator;
import java.util.Set;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class IncrementalGraphCommitTest extends AllChronoGraphBackendsTest {
@Test
public void canCommitDirectlyAfterIncrementalCommit() {
ChronoGraph g = this.getGraph();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
g.tx().commit();
} finally {
g.tx().rollback();
}
// assert that the data was written correctly
assertEquals(6, Iterators.size(g.vertices()));
}
@Test
public void canCommitIncrementally() {
ChronoGraph g = this.getGraph();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
g.addVertex("name", "seven");
g.addVertex("name", "eight");
g.addVertex("name", "nine");
g.tx().commit();
} finally {
g.tx().rollback();
}
assertEquals(9, Iterators.size(g.vertices()));
}
@Test
public void incrementalCommitTransactionCanReadItsOwnModifications() {
ChronoGraph g = this.getGraph();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
assertEquals(3, Iterators.size(g.vertices()));
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
assertEquals(6, Iterators.size(g.vertices()));
g.addVertex("name", "seven");
g.addVertex("name", "eight");
g.addVertex("name", "nine");
g.tx().commit();
} finally {
g.tx().rollback();
}
// assert that the data was written correctly
assertEquals(9, Iterators.size(g.vertices()));
}
@Test
public void incrementalCommitTransactionCanReadItsOwnModificationsInIndexer() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
assertEquals(3, Iterators.size(g.vertices()));
assertEquals(1, g.traversal().V().has("name", "one").toSet().size());
assertEquals(2, g.traversal().V().has("name", CP.contains("e")).toSet().size());
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
assertEquals(6, Iterators.size(g.vertices()));
assertEquals(1, g.traversal().V().has("name", "one").toSet().size());
assertEquals(3, g.traversal().V().has("name", CP.contains("e")).toSet().size());
g.addVertex("name", "seven");
g.addVertex("name", "eight");
g.addVertex("name", "nine");
g.tx().commit();
} finally {
g.tx().rollback();
}
// assert that the data was written correctly
assertEquals(9, Iterators.size(g.vertices()));
assertEquals(1, g.traversal().V().has("name", "one").toSet().size());
assertEquals(6, g.traversal().V().has("name", CP.contains("e")).toSet().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() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
assertEquals(3, Iterators.size(g.vertices()));
assertEquals(1, g.traversal().V().has("name", "one").toSet().size());
assertEquals(2, g.traversal().V().has("name", CP.contains("e")).toSet().size());
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
assertEquals(6, Iterators.size(g.vertices()));
assertEquals(1, g.traversal().V().has("name", "one").toSet().size());
assertEquals(3, g.traversal().V().has("name", CP.contains("e")).toSet().size());
g.addVertex("name", "seven");
g.addVertex("name", "eight");
g.addVertex("name", "nine");
g.tx().commit();
} finally {
g.tx().rollback();
}
// assert that the data was written correctly
assertEquals(9, Iterators.size(g.vertices()));
assertEquals(1, g.traversal().V().has("name", "one").toSet().size());
assertEquals(6, g.traversal().V().has("name", CP.contains("e")).toSet().size());
}
@Test
public void cannotCommitOnOtherTransactionWhileIncrementalCommitProcessIsRunning() {
ChronoGraph g = this.getGraph();
ChronoGraph tx = g.tx().createThreadedTx();
try {
tx.addVertex("name", "one");
tx.addVertex("name", "two");
tx.addVertex("name", "three");
tx.tx().commitIncremental();
assertEquals(3, Iterators.size(tx.vertices()));
tx.addVertex("name", "four");
tx.addVertex("name", "five");
tx.addVertex("name", "six");
tx.tx().commitIncremental();
// simulate a second transaction
ChronoGraph tx2 = g.tx().createThreadedTx();
tx2.addVertex("name", "thirteen");
try {
tx2.tx().commit();
fail("Managed to commit on other transaction while incremental commit is active!");
} catch (ChronoDBCommitException expected) {
// pass
}
// continue with the incremental commit
assertEquals(6, Iterators.size(tx.vertices()));
tx.addVertex("name", "seven");
tx.addVertex("name", "eight");
tx.addVertex("name", "nine");
tx.tx().commit();
} finally {
tx.tx().rollback();
}
// assert that the data was written correctly
assertEquals(9, Iterators.size(g.vertices()));
}
@Test
public void incrementalCommitsAppearAsSingleCommitInHistory() {
ChronoGraph g = this.getGraph();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
Vertex alpha = g.addVertex("name", "alpha", "value", 100);
g.tx().commitIncremental();
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
// update alpha
alpha.property("value", 200);
g.tx().commitIncremental();
g.addVertex("name", "seven");
g.addVertex("name", "eight");
g.addVertex("name", "nine");
// update alpha
alpha.property("value", 300);
g.tx().commit();
} finally {
g.tx().rollback();
}
// assert that the data was written correctly
assertEquals(10, Iterators.size(g.vertices()));
// find the alpha vertex
Vertex alpha = g.traversal().V().has("name", "alpha").toSet().iterator().next();
// assert that alpha was written only once in the versioning history
Iterator<Long> historyOfAlpha = g.getVertexHistory(alpha);
assertEquals(1, Iterators.size(historyOfAlpha));
// assert that all keys have the same timestamp
Set<Long> timestamps = Sets.newHashSet();
g.vertices().forEachRemaining(vertex -> {
Iterator<Long> history = g.getVertexHistory(vertex);
timestamps.add(Iterators.getOnlyElement(history));
});
assertEquals(1, timestamps.size());
}
@Test
public void rollbackDuringIncrementalCommitWorks() {
ChronoGraph g = this.getGraph();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
// simulate user error
throw new RuntimeException("User error");
} catch (RuntimeException expected) {
} finally {
g.tx().rollback();
}
// assert that the data was rolled back correctly
assertEquals(0, Iterators.size(g.vertices()));
}
@Test
public void canCommitRegularlyAfterCompletedIncrementalCommitProcess() {
ChronoGraph g = this.getGraph();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
g.addVertex("name", "seven");
g.addVertex("name", "eight");
g.addVertex("name", "nine");
g.tx().commit();
} finally {
g.tx().rollback();
}
assertEquals(9, Iterators.size(g.vertices()));
// can commit on a different transaction
ChronoGraph tx2 = g.tx().createThreadedTx();
tx2.addVertex("name", "fourtytwo");
tx2.tx().commit();
// can commit on the same transaction
g.addVertex("name", "fourtyseven");
g.tx().commit();
assertEquals(11, Iterators.size(g.vertices()));
}
@Test
public void canCommitRegularlyAfterCanceledIncrementalCommitProcess() {
ChronoGraph g = this.getGraph();
try {
g.addVertex("name", "one");
g.addVertex("name", "two");
g.addVertex("name", "three");
g.tx().commitIncremental();
g.addVertex("name", "four");
g.addVertex("name", "five");
g.addVertex("name", "six");
g.tx().commitIncremental();
g.addVertex("name", "seven");
g.addVertex("name", "eight");
g.addVertex("name", "nine");
} finally {
g.tx().rollback();
}
assertEquals(0, Iterators.size(g.vertices()));
// can commit on a different transaction
ChronoGraph tx2 = g.tx().createThreadedTx();
tx2.addVertex("name", "fourtytwo");
tx2.tx().commit();
// can commit on the same transaction
g.addVertex("name", "fourtyseven");
g.tx().commit();
assertEquals(2, Iterators.size(g.vertices()));
}
@Test
@SuppressWarnings("unused")
public void secondaryIndexingIsCorrectDuringIncrementalCommit() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstName").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastName").acrossAllTimestamps().build();
g.tx().commit();
try {
// add three persons
Vertex p1 = g.addVertex(T.id, "p1", "firstName", "John", "lastName", "Doe");
Vertex p2 = g.addVertex(T.id, "p2", "firstName", "John", "lastName", "Smith");
Vertex p3 = g.addVertex(T.id, "p3", "firstName", "Jane", "lastName", "Doe");
// perform the incremental commit
g.tx().commitIncremental();
// make sure that we can find them
assertEquals(2, (long)g.traversal().V().has("firstName", CP.eqIgnoreCase("john")).count().next());
assertEquals(2, (long)g.traversal().V().has("lastName", CP.eqIgnoreCase("doe")).count().next());
// change Jane's and John's first names
p3.property("firstName", "Jayne");
p1.property("firstName", "Jack");
// perform the incremental commit
g.tx().commitIncremental();
// make sure that we can't find John any longer
assertEquals(1, (long)g.traversal().V().has("firstName", CP.eqIgnoreCase("john")).count().next());
assertEquals(2, (long)g.traversal().V().has("lastName", CP.eqIgnoreCase("doe")).count().next());
// change Jack's first name (yet again)
p1.property("firstName", "Joe");
// perform the incremental commit
g.tx().commitIncremental();
// make sure that we can't find Jack Doe any longer
assertEquals(0, (long)g.traversal().V().has("firstName", CP.eqIgnoreCase("jack")).count().next());
// john smith should still be there
assertEquals(1, (long)g.traversal().V().has("firstName", CP.eqIgnoreCase("john")).count().next());
// we still have jayne doe and joe doe
assertEquals(2, (long)g.traversal().V().has("lastName", CP.eqIgnoreCase("doe")).count().next());
// jayne should be in the first name index as well
assertEquals(1, (long)g.traversal().V().has("firstName", CP.eqIgnoreCase("jayne")).count().next());
// delete Joe
p1.remove();
// make sure that joe's gone
assertEquals(0, (long)g.traversal().V().has("firstName", "Joe").count().next());
// do the full commit
g.tx().commit();
} finally {
g.tx().rollback();
}
// in the end, there should be john smith and jayne doe
assertEquals(1, (long)g.traversal().V().has("firstName", CP.eqIgnoreCase("john")).count().next());
assertEquals(1, (long)g.traversal().V().has("lastName", CP.eqIgnoreCase("doe")).count().next());
}
@Test
public void getAndExistsWorkProperlyAfterDeletionDuringIncrementalCommit() {
ChronoGraph g = this.getGraph();
{ // add some base data
g.tx().open();
g.addVertex(T.id, "a", "name", "Hello");
g.addVertex(T.id, "b", "name", "World");
g.tx().commit();
}
{ // do the incremental commit process
g.tx().open();
assertTrue(Iterators.getOnlyElement(g.vertices("a"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("b"), null) != null);
assertEquals("Hello", Iterators.getOnlyElement(g.vertices("a")).value("name"));
assertEquals("World", Iterators.getOnlyElement(g.vertices("b")).value("name"));
g.addVertex(T.id, "c", "name", "Foo");
g.addVertex(T.id, "d", "name", "Bar");
g.tx().commitIncremental();
assertTrue(Iterators.getOnlyElement(g.vertices("a"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("b"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("c"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("d"), null) != null);
Iterators.getOnlyElement(g.vertices("a"), null).remove();
g.tx().commitIncremental();
assertNull(Iterators.getOnlyElement(g.vertices("a"), null));
g.tx().commit();
}
g.tx().open();
assertNull(Iterators.getOnlyElement(g.vertices("a"), null));
}
@Test
public void canRecreateVertexDuringIncrementalCommitProcess() {
ChronoGraph g = this.getGraph();
{ // add some base data
g.tx().open();
g.addVertex(T.id, "a", "name", "Hello");
g.addVertex(T.id, "b", "name", "World");
g.tx().commit();
}
{ // do the incremental commit process
g.tx().open();
assertTrue(Iterators.getOnlyElement(g.vertices("a"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("b"), null) != null);
assertEquals("Hello", Iterators.getOnlyElement(g.vertices("a")).value("name"));
assertEquals("World", Iterators.getOnlyElement(g.vertices("b")).value("name"));
g.addVertex(T.id, "c", "name", "Foo");
g.addVertex(T.id, "d", "name", "Bar");
g.tx().commitIncremental();
assertTrue(Iterators.getOnlyElement(g.vertices("a"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("b"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("c"), null) != null);
assertTrue(Iterators.getOnlyElement(g.vertices("d"), null) != null);
Iterators.getOnlyElement(g.vertices("a"), null).remove();
g.tx().commitIncremental();
assertNull(Iterators.getOnlyElement(g.vertices("a"), null));
// recreate a
g.addVertex(T.id, "a", "name", "BornAgain");
g.tx().commitIncremental();
assertTrue(Iterators.getOnlyElement(g.vertices("a"), null) != null);
assertEquals("BornAgain", Iterators.getOnlyElement(g.vertices("a")).value("name"));
g.tx().commit();
}
g.tx().open();
assertTrue(Iterators.getOnlyElement(g.vertices("a"), null) != null);
assertEquals("BornAgain", Iterators.getOnlyElement(g.vertices("a")).value("name"));
}
}
| 19,314 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
TransactionCloseTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/TransactionCloseTest.java | package org.chronos.chronograph.test.cases.transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.Test;
import static org.junit.Assert.*;
public class TransactionCloseTest extends AllChronoGraphBackendsTest {
@Test
public void transactionErrorMessageReportsGraphStatus() {
ChronoGraph graph = this.getGraph();
graph.tx().open();
Vertex v = graph.addVertex("my-id");
graph.close();
try {
v.property("name", "My Vertex");
fail("Managed to operate on a vertex with the transaction already closed!");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("This ChronoGraph instance has already been closed"));
}
}
@Test
public void threadedTransactionErrorMessageReportsGraphStatus1() {
ChronoGraph graph = this.getGraph();
try (ChronoGraph txGraph = graph.tx().createThreadedTx()) {
Vertex v = txGraph.addVertex("my-id");
txGraph.close();
v.property("name", "My Vertex");
fail("Managed to operate on a vertex with the transaction already closed!");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("The ChronoGraph instance is still open"));
}
}
@Test
public void threadedTransactionErrorMessageReportsGraphStatus2() {
ChronoGraph graph = this.getGraph();
try (ChronoGraph txGraph = graph.tx().createThreadedTx()) {
Vertex v = txGraph.addVertex("my-id");
graph.close();
v.property("name", "My Vertex");
fail("Managed to operate on a vertex with the transaction already closed!");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("The ChronoGraph instance has also been closed"));
}
}
}
| 2,023 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ElementHistoryTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/ElementHistoryTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Lists;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.ChronoDBFeatures;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.Assume;
import org.junit.Test;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class ElementHistoryTest extends AllChronoGraphBackendsTest {
@Test
public void canGetVertexHistory(){
ChronoGraph g = this.getGraph();
Vertex a = g.addVertex(T.id, "A", "value", 1);
Vertex b = g.addVertex(T.id, "B", "value", 1);
long afterFirstCommit = g.tx().commitAndReturnTimestamp();
a.property("value", 2);
long afterSecondCommit = g.tx().commitAndReturnTimestamp();
b.property("value", 2);
long afterThirdCommit = g.tx().commitAndReturnTimestamp();
a.property("value", 3);
long afterFourthCommit = g.tx().commitAndReturnTimestamp();
a.addEdge("myLabel", b); // adding an edge should modify both adjacent vertices
long afterFifthCommit = g.tx().commitAndReturnTimestamp();
List<Long> historyOfA = Lists.newArrayList(g.getVertexHistory(a));
assertThat(historyOfA, contains(afterFifthCommit, afterFourthCommit, afterSecondCommit, afterFirstCommit));
List<Long> historyOfB = Lists.newArrayList(g.getVertexHistory(b));
assertThat(historyOfB, contains(afterFifthCommit, afterThirdCommit, afterFirstCommit));
}
@Test
public void canGetEdgeHistory(){
ChronoGraph g = this.getGraph();
Vertex a = g.addVertex(T.id, "A", "value", 1);
Vertex b = g.addVertex(T.id, "B", "value", 1);
Vertex c = g.addVertex(T.id, "C", "value", 1);
Edge e1 = a.addEdge("l", b, T.id, "e1", "value", 1);
Edge e2 = a.addEdge("l", c, T.id, "e2", "value", 1);
long afterFirstCommit = g.tx().commitAndReturnTimestamp();
Edge e3 = b.addEdge("l", c, T.id, "e3");
b.property("value", 2);
long afterSecondCommit = g.tx().commitAndReturnTimestamp();
e1.property("value", 2);
long afterThirdCommit = g.tx().commitAndReturnTimestamp();
b.remove();
long afterFourthCommit = g.tx().commitAndReturnTimestamp();
List<Long> historyOfE1 = Lists.newArrayList(g.getEdgeHistory(e1));
assertThat(historyOfE1, contains(afterFourthCommit, afterThirdCommit, afterFirstCommit));
List<Long> historyOfE2 = Lists.newArrayList(g.getEdgeHistory(e2));
assertThat(historyOfE2, contains(afterFirstCommit));
List<Long> historyOfE3 = Lists.newArrayList(g.getEdgeHistory(e3));
assertThat(historyOfE3, contains(afterFourthCommit, afterSecondCommit));
}
@Test
public void canGetVertexHistoryAcrossRollover(){
ChronoGraph g = this.getGraph();
ChronoDBFeatures features = ((ChronoGraphInternal) g).getBackingDB().getFeatures();
Assume.assumeTrue(features.isPersistent());
Assume.assumeTrue(features.isRolloverSupported());
Vertex a = g.addVertex(T.id, "A", "value", 1);
Vertex b = g.addVertex(T.id, "B", "value", 1);
long afterFirstCommit = g.tx().commitAndReturnTimestamp();
a.property("value", 2);
long afterSecondCommit = g.tx().commitAndReturnTimestamp();
b.property("value", 2);
long afterThirdCommit = g.tx().commitAndReturnTimestamp();
g.getMaintenanceManager().performRolloverOnMaster();
a.property("value", 3);
long afterFourthCommit = g.tx().commitAndReturnTimestamp();
a.addEdge("myLabel", b); // adding an edge should modify both adjacent vertices
long afterFifthCommit = g.tx().commitAndReturnTimestamp();
g = this.closeAndReopenGraph();
// history within chunk 0
g.tx().open(afterThirdCommit);
List<Long> historyOfAInChunk0 = Lists.newArrayList(g.getVertexHistory(a));
assertThat(historyOfAInChunk0, contains(afterSecondCommit, afterFirstCommit));
g.tx().rollback();
// history within entire db
g.tx().open();
List<Long> historyOfA = Lists.newArrayList(g.getVertexHistory(a));
assertThat(historyOfA, contains(afterFifthCommit, afterFourthCommit, afterSecondCommit, afterFirstCommit));
}
@Test
public void canGetEdgeHistoryAcrossRollover(){
ChronoGraph g = this.getGraph();
ChronoDBFeatures features = ((ChronoGraphInternal) g).getBackingDB().getFeatures();
Assume.assumeTrue(features.isPersistent());
Assume.assumeTrue(features.isRolloverSupported());
Vertex a = g.addVertex(T.id, "A", "value", 1);
Vertex b = g.addVertex(T.id, "B", "value", 1);
Vertex c = g.addVertex(T.id, "C", "value", 1);
Edge e1 = a.addEdge("l", b, T.id, "e1", "value", 1);
Edge e2 = a.addEdge("l", c, T.id, "e2", "value", 1);
long afterFirstCommit = g.tx().commitAndReturnTimestamp();
Edge e3 = b.addEdge("l", c, T.id, "e3");
b.property("value", 2);
long afterSecondCommit = g.tx().commitAndReturnTimestamp();
g.getMaintenanceManager().performRolloverOnMaster();
e1.property("value", 2);
long afterThirdCommit = g.tx().commitAndReturnTimestamp();
b.remove();
long afterFourthCommit = g.tx().commitAndReturnTimestamp();
g = this.closeAndReopenGraph();
// history within chunk 0
g.tx().open(afterSecondCommit);
List<Long> historyOfE1InChunk0 = Lists.newArrayList(g.getEdgeHistory(e1));
assertThat(historyOfE1InChunk0, contains(afterFirstCommit));
List<Long> historyOfE2InChunk0 = Lists.newArrayList(g.getEdgeHistory(e2));
assertThat(historyOfE2InChunk0, contains(afterFirstCommit));
List<Long> historyOfE3InChunk0 = Lists.newArrayList(g.getEdgeHistory(e3));
assertThat(historyOfE3InChunk0, contains(afterSecondCommit));
g.tx().rollback();
// history within entire db
g.tx().open();
List<Long> historyOfE1 = Lists.newArrayList(g.getEdgeHistory(e1));
assertThat(historyOfE1, contains(afterFourthCommit, afterThirdCommit, afterFirstCommit));
List<Long> historyOfE2 = Lists.newArrayList(g.getEdgeHistory(e2));
assertThat(historyOfE2, contains(afterFirstCommit));
List<Long> historyOfE3 = Lists.newArrayList(g.getEdgeHistory(e3));
assertThat(historyOfE3, contains(afterFourthCommit, afterSecondCommit));
}
}
| 6,845 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
TransientModificationTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/TransientModificationTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterators;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.structure.PropertyStatus;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.Test;
import java.util.Iterator;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class TransientModificationTest extends AllChronoGraphBackendsTest {
@Test
public void transientPropertiesOnVerticesAreReflectedInGremlinQueries() {
ChronoGraph g = this.getGraph();
g.addVertex("name", "martin");
g.tx().commit();
Vertex me = g.traversal().V().has("name", "martin").toSet().iterator().next();
assertNotNull(me);
// apply the transient change
me.property("name", "john");
{ // test 1: try to retrieve the vertex by the original data state and assert that it's not present
Set<Vertex> vertices = g.traversal().V().has("name", "martin").toSet();
assertTrue("Found vertex 'martin' even though transient context renamed it to 'john'!", vertices.isEmpty());
}
{ // test 2: try to retrieve the vertex by the transient data state and assert that it works
Set<Vertex> vertices = g.traversal().V().has("name", "john").toSet();
assertEquals("Did not find vertex 'john' even though transient context should contain it!", 1,
vertices.size());
}
g.tx().commit();
{ // test 3: try to retrieve the vertex by the new persisted data state and assert that it works
Set<Vertex> vertices = g.traversal().V().has("name", "john").toSet();
assertEquals("Did not find vertex 'john' after commiting the change!", 1, vertices.size());
}
}
@Test
public void transientVertexDeletionsAreReflectedInGremlinQueries() {
ChronoGraph g = this.getGraph();
g.addVertex("name", "martin");
g.addVertex("name", "john");
g.tx().commit();
Vertex me = g.traversal().V().has("name", "martin").toSet().iterator().next();
assertNotNull(me);
me.remove();
// assert that the query no longer returns "me", even before committing the operation
assertTrue("Transient vertex deletions are ignored by gremlin query!",
g.traversal().V().has("name", "martin").toSet().isEmpty());
}
@Test
public void transientEdgeDeletionsAreReflectedInGremlinQueries() {
ChronoGraph g = this.getGraph();
Vertex me = g.addVertex("name", "martin");
Vertex john = g.addVertex("name", "john");
me.addEdge("friend", john, "since", "forever");
g.tx().commit();
Edge e = g.traversal().E().has("since", "forever").toSet().iterator().next();
assertNotNull(e);
e.remove();
// assert that the query no longer returns the edge, even before committing the operation
assertTrue("Transient edge deletions are ignored by gremlin query!",
g.traversal().E().has("since", "forever").toSet().isEmpty());
}
@Test
public void transientAddedVerticesAreReflectedInGremlinQueries() {
ChronoGraph g = this.getGraph();
g.addVertex("name", "martin");
g.addVertex("name", "john");
// note: no commit here! Vertices are transient
Iterator<Vertex> verticesIterator = g.vertices();
assertEquals(2, Iterators.size(verticesIterator));
}
@Test
public void transientGetVertexByIdWorks() {
ChronoGraph g = this.getGraph();
final Vertex v1 = g.addVertex();
final Edge e1 = v1.addEdge("l", v1);
g.tx().commit();
assertEquals(v1.id(), g.vertices(v1.id()).next().id());
assertEquals(e1.id(), g.edges(e1.id()).next().id());
v1.property(VertexProperty.Cardinality.single, "name", "marko");
assertEquals("marko", v1.<String>value("name"));
assertEquals("marko", g.vertices(v1.id()).next().<String>value("name"));
g.tx().commit();
}
@Test
public void canHandleDeletedQueryResultCandidatesInTransientState(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "firstname", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "firstname", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "firstname", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "firstname", "John", "lastname", "Smith");
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("firstname", "John").id().toSet();
assertThat(ids, containsInAnyOrder("1", "4"));
});
// now, delete John Smith...
g.vertex("4").remove();
// ... and add John Norman
g.addVertex(T.id, "5", "firstname", "John", "lastname", "Norman");
this.assertCommitAssert(()->{
Set<Object> ids = g.traversal().V().has("firstname", "John").id().toSet();
assertThat(ids, containsInAnyOrder("1", "5"));
});
}
@Test
public void changingAPropertyBackToItsOriginalValueCausesCommitToBecomeEmpty(){
ChronoGraph g = this.getGraph();
ChronoVertex vJohn = (ChronoVertex) g.addVertex(T.id, "1", "firstName", "John", "lastName", "Doe");
g.tx().commit();
vJohn.property("lastName", "Smith");
// this property is now modified...
assertEquals(PropertyStatus.MODIFIED, vJohn.getPropertyStatus("lastName"));
// ... and now we change it back
vJohn.property("lastName", "Doe");
// the property is still modified according to the transaction...
assertEquals(PropertyStatus.MODIFIED, vJohn.getPropertyStatus("lastName"));
// ... but if we commit now, we don't get a new timestamp,
// because effectively we changed nothing.
long timestamp = g.tx().commitAndReturnTimestamp();
assertThat(timestamp, is(lessThan(0L)));
}
}
| 6,524 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
IncrementalGraphCommitPerformanceTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/IncrementalGraphCommitPerformanceTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
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.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.PerformanceTest;
import org.chronos.common.test.utils.TestUtils;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import static org.junit.Assert.*;
@Category(PerformanceTest.class)
@DontRunWithBackend({InMemoryChronoDB.BACKEND_NAME})
public class IncrementalGraphCommitPerformanceTest extends AllChronoGraphBackendsTest {
// copied from TuplUtils to avoid the project dependency
private static final int BATCH_INSERT_THRESHOLD = 25_000;
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "200000")
public void t_largeStructureTest() {
final int MAX_BATCH_SIZE = 25_000;
ChronoGraph graph = this.getGraph();
// create indices
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("kind").acrossAllTimestamps().build();
// simulate one entity class
Vertex classVertex = graph.addVertex("kind", "class");
graph.tx().commit();
// load largeStructure files
Scanner entitiesScanner = new Scanner(this.getClass().getClassLoader()
.getResourceAsStream("org/chronos/chronograph/testStructures/entities.csv"));
Scanner associationsScanner = new Scanner(this.getClass().getClassLoader()
.getResourceAsStream("org/chronos/chronograph/testStructures/associations.csv"));
// put entities
int batchSize = 0;
while (entitiesScanner.hasNextLine()) {
String line = entitiesScanner.nextLine().trim();
Vertex entityVertex = graph.addVertex(T.id, line, "kind", "entity");
entityVertex.addEdge("classifier", classVertex);
batchSize++;
if (batchSize > MAX_BATCH_SIZE) {
graph.tx().commitIncremental();
batchSize = 0;
}
}
graph.tx().commitIncremental();
// put associations
batchSize = 0;
while (associationsScanner.hasNextLine()) {
String line = associationsScanner.nextLine().trim();
String[] sourceTarget = line.split(",");
String source = sourceTarget[0].trim();
String target = sourceTarget[1].trim();
Vertex v1 = Iterators.getOnlyElement(graph.vertices(source), null);
Vertex v2 = Iterators.getOnlyElement(graph.vertices(target), null);
assertNotNull(v1);
assertNotNull(v2);
v1.addEdge("connected", v2);
batchSize++;
if (batchSize > MAX_BATCH_SIZE) {
graph.tx().commitIncremental();
batchSize = 0;
}
}
// commit and free scanners
graph.tx().commit();
entitiesScanner.close();
associationsScanner.close();
}
@Test
public void massiveIncrementalCommitsProduceConsistentStoreWithBatchInsert() {
this.runMassiveIncrementalCommitTest(true);
}
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10000")
public void massiveIncrementalCommitsProduceConsistentStoreWithBatchInsertAndCache() {
this.runMassiveIncrementalCommitTest(true);
}
@Test
public void massiveIncrementalCommitsProduceConsistentStoreWithRegularInsert() {
this.runMassiveIncrementalCommitTest(false);
}
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "10000")
public void massiveIncrementalCommitsProduceConsistentStoreWithRegularInsertAndCache() {
this.runMassiveIncrementalCommitTest(false);
}
private void runMassiveIncrementalCommitTest(final boolean useBatch) {
ChronoGraph graph = this.getGraph();
// we want at least three batches
final int keyCount = BATCH_INSERT_THRESHOLD * 4;
final int additionalEdgeCount = keyCount * 3;
List<String> keysList = Lists.newArrayList();
for (int i = 0; i < keyCount; i++) {
keysList.add(UUID.randomUUID().toString());
}
keysList = Collections.unmodifiableList(keysList);
final int maxBatchSize;
if (useBatch) {
// we force batch inserts by choosing a size larger than the batch threshold
maxBatchSize = BATCH_INSERT_THRESHOLD + 1;
} else {
// we force normal inserts by choosing a size less than the batch threshold
maxBatchSize = BATCH_INSERT_THRESHOLD - 1;
}
graph.tx().open();
int index = 0;
int batchSize = 0;
int batchCount = 0;
List<String> addedVertexIds = Lists.newArrayList();
while (index < keyCount) {
String uuid = keysList.get(index);
Vertex newVertex = graph.addVertex(T.id, uuid);
if (addedVertexIds.size() > 1) {
// connect to a random vertex (other than self; we add this vertex later)
String randomVertexId = TestUtils.getRandomEntryOf(addedVertexIds);
Vertex randomVertex = Iterators.getOnlyElement(graph.vertices(randomVertexId));
newVertex.addEdge("connected", randomVertex);
}
addedVertexIds.add(uuid);
index++;
batchSize++;
if (batchSize >= maxBatchSize) {
for (int i = 0; i < index; i++) {
String test = keysList.get(i);
try {
Vertex vertex = Iterators.getOnlyElement(graph.vertices(test));
assertNotNull(vertex);
assertEquals(test, vertex.id());
if (i >= 2) {
assertEquals(1, Iterators.size(vertex.edges(Direction.OUT)));
}
} catch (AssertionError e) {
System.out.println("Error occurred on Test\t\tBatch: " + batchCount + "\t\ti: " + i
+ "\t\tmaxIndex: " + index);
throw e;
}
}
graph.tx().commitIncremental();
batchSize = 0;
batchCount++;
for (int i = 0; i < index; i++) {
String test = keysList.get(i);
try {
Vertex vertex = Iterators.getOnlyElement(graph.vertices(test));
assertNotNull(vertex);
assertEquals(test, vertex.id());
if (i >= 2) {
assertEquals(1, Iterators.size(vertex.edges(Direction.OUT)));
}
} catch (AssertionError e) {
System.out.println("Error occurred on Test\t\tBatch: " + batchCount + "\t\ti: " + i
+ "\t\tmaxIndex: " + index);
throw e;
}
}
}
}
// now, do some linking
batchSize = 0;
batchCount = 0;
for (int i = 0; i < additionalEdgeCount; i++) {
String vId1 = TestUtils.getRandomEntryOf(keysList);
String vId2 = TestUtils.getRandomEntryOf(keysList);
Vertex v1 = Iterators.getOnlyElement(graph.vertices(vId1));
Vertex v2 = Iterators.getOnlyElement(graph.vertices(vId2));
v1.addEdge("additional", v2);
batchSize++;
if (batchSize >= maxBatchSize) {
batchSize = 0;
batchCount++;
graph.tx().commitIncremental();
}
}
graph.tx().commit();
graph.tx().open();
// check that all elements are present in the old transaction
int i = 0;
for (String uuid : keysList) {
Vertex vertex = Iterators.getOnlyElement(graph.vertices(uuid));
assertNotNull(vertex);
assertEquals(uuid, vertex.id());
if (i >= 2) {
assertEquals(1, Iterators.size(vertex.edges(Direction.OUT, "connected")));
}
i++;
}
// check that all edges are there
assertEquals(additionalEdgeCount,
Iterators.size(graph.traversal().E().filter(t -> t.get().label().equals("additional"))));
graph.tx().rollback();
}
}
| 9,449 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ElementIdReuseTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/ElementIdReuseTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 ElementIdReuseTest extends AllChronoGraphBackendsTest {
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "true")
public void canCreateDeleteAndReuseEdgeIdInSameTransaction() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex();
Vertex v2 = graph.addVertex();
Vertex v3 = graph.addVertex();
// create an edge with a fixed ID
Edge e1 = v1.addEdge("test", v2, T.id, "1");
assertEquals(1, Iterators.size(graph.edges("1")));
e1.property("hello", "world");
// delete the edge
e1.remove();
// assert that it's gone
assertEquals(0, Iterators.size(graph.edges("1")));
// add another edge with the same ID
Edge e2 = v1.addEdge("test", v3, T.id, "1");
assertNotNull(e2);
e2.property("foo", "bar");
Edge edge = Iterators.getOnlyElement(graph.edges("1"));
assertEquals(null, edge.property("hello").orElse(null));
assertEquals("bar", edge.property("foo").orElse(null));
}
@Test
public void canDeleteAndReuseEdgeIdBetweenDifferentVerticesInSameTransaction(){
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex(T.id, "v1");
Vertex v2 = graph.addVertex(T.id, "v2");
Vertex v3 = graph.addVertex(T.id, "v3");
// create an edge with a fixed ID
Edge e1 = v1.addEdge("test", v2, T.id, "1");
assertEquals(1, Iterators.size(graph.edges("1")));
e1.property("hello", "world");
graph.tx().commit();
// delete the edge
e1.remove();
Edge e2 = v3.addEdge("test", v2, T.id, "1");
assertEquals(v3.id(), e2.outVertex().id());
assertEquals(v2.id(), e2.inVertex().id());
graph.tx().commit();
Edge edgeWithReusedId = Iterables.getOnlyElement(graph.traversal().E("1").toSet());
assertEquals(v3.id(), edgeWithReusedId.outVertex().id());
assertEquals(v2.id(), edgeWithReusedId.inVertex().id());
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "true")
public void canDeleteAndOverridePersistentElement() {
ChronoGraph g = this.getGraph();
Vertex v1 = g.addVertex();
Vertex v2 = g.addVertex();
Vertex v3 = g.addVertex();
Edge e1 = v1.addEdge("test", v2, T.id, "1");
assertNotNull(e1);
g.tx().commit();
e1.remove();
Edge e2 = v1.addEdge("test", v3, T.id, "1");
assertNotNull(e2);
g.tx().commit();
}
}
| 3,452 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ThreadedTransactionTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/ThreadedTransactionTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Set;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class ThreadedTransactionTest extends AllChronoGraphBackendsTest {
@Test
public void canOpenThreadedTransaction() {
ChronoGraph graph = this.getGraph();
ChronoGraph threadedTx = graph.tx().createThreadedTx();
assertNotNull(threadedTx);
}
@Test
public void canAccessGraphElementsInThreadedTransaction() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "Martin");
Vertex v2 = graph.addVertex("name", "John");
Edge e = v1.addEdge("knows", v2);
graph.tx().commit();
// open the threaded transaction
ChronoGraph threadedTx = graph.tx().createThreadedTx();
assertNotNull(threadedTx);
// try to find the elements
Vertex threadedV1 = Iterators.getOnlyElement(threadedTx.vertices(v1));
Vertex threadedV2 = Iterators.getOnlyElement(threadedTx.vertices(v2));
Edge threadedE = Iterators.getOnlyElement(threadedTx.edges(e));
// assert that the elements are equal...
assertEquals(v1, threadedV1);
assertEquals(v2, threadedV2);
assertEquals(e, threadedE);
// ... but not the same w.r.t. ==
assertFalse(v1 == threadedV1);
assertFalse(v2 == threadedV2);
assertFalse(e == threadedE);
}
@Test
public void graphElementsInThreadedTransactionCanBeAccessedInAnyThread() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "Martin");
Vertex v2 = graph.addVertex("name", "John");
Edge e = v1.addEdge("knows", v2);
graph.tx().commit();
// open the threaded transaction
ChronoGraph threadedTx = graph.tx().createThreadedTx();
assertNotNull(threadedTx);
// try to find the elements
Vertex threadedV1 = Iterators.getOnlyElement(threadedTx.vertices(v1));
Vertex threadedV2 = Iterators.getOnlyElement(threadedTx.vertices(v2));
Edge threadedE = Iterators.getOnlyElement(threadedTx.edges(e));
// use a thread (controlled synchronously) to access some vertex data
this.executeSynchronouslyInWorkerThread(() -> {
assertEquals("Martin", threadedV1.value("name"));
assertEquals("John", threadedV2.value("name"));
});
// ... and do the same for edges
this.executeSynchronouslyInWorkerThread(() -> {
assertEquals("knows", threadedE.label());
});
}
@Test
public void canCommitInThreadedTx() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "Martin");
Vertex v2 = graph.addVertex("name", "John");
v1.addEdge("knows", v2);
graph.tx().commit();
// open the threaded transaction
ChronoGraph threadedTx = graph.tx().createThreadedTx();
assertNotNull(threadedTx);
// try to find the elements
Vertex threadedV1 = Iterators.getOnlyElement(threadedTx.vertices(v1));
Vertex threadedV2 = Iterators.getOnlyElement(threadedTx.vertices(v2));
this.executeSynchronouslyInWorkerThread(() -> {
threadedV1.property("age", 26);
threadedV2.property("age", 18);
threadedTx.tx().commit();
});
// close the threaded transaction
threadedTx.close();
// open a new (regular) transaction on the graph
graph.tx().reset();
// make sure that the changes have been applied
assertEquals(26, (int) v1.value("age"));
assertEquals(18, (int) v2.value("age"));
}
@Test
public void elementsFromThreadedTxBecomeUnusableOnceThreadedTxIsClosed() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex("name", "Martin");
Vertex v2 = graph.addVertex("name", "John");
v1.addEdge("knows", v2);
graph.tx().commit();
// open the threaded transaction
ChronoGraph threadedTx = graph.tx().createThreadedTx();
assertNotNull(threadedTx);
// try to find the elements
Vertex threadedV1 = Iterators.getOnlyElement(threadedTx.vertices(v1));
Vertex threadedV2 = Iterators.getOnlyElement(threadedTx.vertices(v2));
// close the threaded tx
threadedTx.close();
// make sure that the elements are no longer accessible
try {
threadedV1.value("name");
threadedV2.value("name");
fail("Managed to access a graph element from a threaded transaction after it was closed!");
} catch (IllegalStateException expected) {
// pass
}
}
@Test
// disable auto-tx for this test to make sure that only the threaded transaction is really open
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
public void canUseIndexManagerFromThreadedTransactionGraph() {
ChronoGraph graph = this.getGraph();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
// work with a threaded graph, add some data
ChronoGraph tGraph = graph.tx().createThreadedTx();
tGraph.addVertex("name", "Martin");
tGraph.addVertex("name", "John");
// try to run a query in "transient" state mode, i.e. without persistence
Set<Vertex> set = tGraph.traversal().V().has("name", CP.eqIgnoreCase("martin")).toSet();
assertEquals(1, set.size());
assertEquals("Martin", Iterables.getOnlyElement(set).value("name"));
// commit the threaded tx
tGraph.tx().commit();
tGraph = null;
// open a new transaction graph and run the query again
ChronoGraph tGraph2 = graph.tx().createThreadedTx();
Set<Vertex> set2 = tGraph2.traversal().V().has("name", CP.eqIgnoreCase("martin")).toSet();
assertEquals(1, set2.size());
assertEquals("Martin", Iterables.getOnlyElement(set2).value("name"));
}
@Test
public void threadBoundTransactionsDoNotInterfereWithThreadedTransactions() {
ChronoGraph graph = this.getGraph();
graph.addVertex("hello", "world");
graph.tx().commit();
long afterFirstCommit = graph.getNow();
graph.addVertex("foo", "bar");
graph.tx().commit();
long afterSecondCommit = graph.getNow();
// open a thread-bound tx on "after first commit"
graph.tx().open(afterFirstCommit);
assertEquals(afterFirstCommit, graph.tx().getCurrentTransaction().getTimestamp());
// open a threaded tx on "now"
try (ChronoGraph txGraph = graph.tx().createThreadedTx()) {
// make sure that "now" is correctly set on the threaded tx, even though
// the graph has a thread-bound tx set to an earlier date
assertEquals(afterSecondCommit, txGraph.getNow());
}
}
@Test
public void threadedTransactionsDoNotInterfereWithThreadBoundTransactions() {
ChronoGraph graph = this.getGraph();
graph.addVertex("hello", "world");
graph.tx().commit();
long afterFirstCommit = graph.getNow();
graph.addVertex("foo", "bar");
graph.tx().commit();
long afterSecondCommit = graph.getNow();
// open a threaded tx on "now"
try (ChronoGraph txGraph = graph.tx().createThreadedTx()) {
// make sure that "now" is correctly set on the threaded tx, even though
// the graph has a thread-bound tx set to an earlier date
assertEquals(afterSecondCommit, txGraph.getNow());
}
// open a thread-bound tx on "after first commit"
graph.tx().open(afterFirstCommit);
assertEquals(afterFirstCommit, graph.tx().getCurrentTransaction().getTimestamp());
}
@Test
public void threadedTransactionIsNotTreatedAsCurrentTransaction() {
ChronoGraph graph = this.getGraph();
graph.addVertex("hello", "world");
graph.tx().commit();
long afterFirstCommit = graph.getNow();
graph.addVertex("foo", "bar");
graph.tx().commit();
long afterSecondCommit = graph.getNow();
try (ChronoGraph txGraph = graph.tx().createThreadedTx(afterFirstCommit)) {
// make sure that "now" is correctly set on the threaded tx, even though
// the graph has a thread-bound tx set to an earlier date
assertEquals(afterSecondCommit, txGraph.getNow());
assertFalse(graph.tx().isOpen());
}
assertFalse(graph.tx().isOpen());
}
// =====================================================================================================================
// HELPER METHODS
// =====================================================================================================================
private void executeSynchronouslyInWorkerThread(final Runnable runnable) {
Thread worker = new Thread(runnable);
// set up a root exception handler in the thread, such that our test
// can fail properly if an error during the access in the other thread occurs
Set<Throwable> workerThreadExceptions = Sets.newConcurrentHashSet();
worker.setUncaughtExceptionHandler((thread, ex) -> {
workerThreadExceptions.add(ex);
});
// run the worker
worker.start();
// wait for the worker to finish
try {
worker.join();
} catch (InterruptedException e) {
fail("Worker was interrupted! Exception: " + e);
}
// assert that there were no errors during the access
assertEquals(0, workerThreadExceptions.size());
}
}
| 10,576 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
CommitMetadataTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/CommitMetadataTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Maps;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 CommitMetadataTest extends AllChronoGraphBackendsTest {
@Test
public void canStoreAndRetrieveCommitMetadata() {
ChronoGraph graph = this.getGraph();
// the message we are going to store as metadata; stored as a variable for later comparison
final String commitMessage = "Committed Hello World!";
// add some data with our commit message
graph.addVertex("message", "Hello World!");
graph.tx().commit(commitMessage);
// the "now" timestamp is pointing to the last commit
long timestamp = graph.getNow();
// read the commit message
Object metadata = graph.getCommitMetadata(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, timestamp);
assertEquals(commitMessage, metadata);
}
@Test
public void readingCommitMetadataFromNonExistingCommitTimestampsProducesNull() {
ChronoGraph graph = this.getGraph();
// the message we are going to store as metadata
final String commitMessage = "Committed Hello World!";
// add some data with our commit message
graph.addVertex("message", "Hello World!");
graph.tx().commit(commitMessage);
// read commit metadata from a non-existing (but valid) commit timestamp
assertNull(graph.getCommitMetadata(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, 0L));
}
@Test
public void canUseHashMapAsCommitMetadata() {
ChronoGraph graph = this.getGraph();
graph.addVertex("message", "Hello World!");
Map<String, String> commitMap = Maps.newHashMap();
commitMap.put("User", "Martin");
commitMap.put("Mood", "Good");
commitMap.put("Mail", "martin.haeusler@uibk.ac.at");
graph.tx().commit(commitMap);
long timestamp = graph.getNow();
// get the commit map
@SuppressWarnings("unchecked")
Map<String, String> retrieved = (Map<String, String>) graph
.getCommitMetadata(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, timestamp);
// assert that the maps are equal
assertNotNull(retrieved);
assertEquals(commitMap, retrieved);
}
}
| 2,661 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphVersioningTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/GraphVersioningTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GraphVersioningTest extends AllChronoGraphBackendsTest {
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "100")
public void graphVersionReadsWork() {
ChronoGraph g = this.getGraph();
// remember the timestamp for later reference
long timestampBeforeTx1 = System.currentTimeMillis();
// make sure that the timestamp really is BEFORE the insert by sleeping a bit
sleep(1);
// create a graph:
//
// (martin)-[worksOn]->(project1)
// -[worksOn]->(project2)
// -[knows]->(John)
// (john)-[worksOn]->(project3)
Vertex vMartin = g.addVertex("name", "Martin", "kind", "person");
Vertex vJohn = g.addVertex("name", "John", "kind", "person");
Vertex vProject1 = g.addVertex("name", "Project 1", "kind", "project");
Vertex vProject2 = g.addVertex("name", "Project 2", "kind", "project");
Vertex vProject3 = g.addVertex("name", "Project 3", "kind", "project");
vMartin.addEdge("knows", vJohn);
vMartin.addEdge("worksOn", vProject1);
vMartin.addEdge("worksOn", vProject2);
vJohn.addEdge("worksOn", vProject3);
String vMartinId = (String) vMartin.id();
String vJohnId = (String) vJohn.id();
String vProject1Id = (String) vProject1.id();
String vProject2Id = (String) vProject2.id();
String vProject3Id = (String) vProject3.id();
g.tx().commit();
// remember the timestamp for later reference
long timestampBeforeTx2 = System.currentTimeMillis();
sleep(1);
// modify the graph to match:
//
// (project2) -> delete
// (martin)-[worksOn]->(project1)
// -[worksOn]->(project3)
// -[worksOn]->(project4)
// -[knows]->(John)
// (john)-[worksOn]->(project3)
vProject2.remove();
Vertex vProject4 = g.addVertex("name", "Project 4", "kind", "project");
vMartin.addEdge("worksOn", vProject3);
vMartin.addEdge("worksOn", vProject4);
String vProject4Id = (String) vProject4.id();
g.tx().commit();
// remember the timestamp for later reference
long timestampBeforeTx3 = System.currentTimeMillis();
sleep(1);
// modify the graph to match:
//
// (martin)-[worksOn]->(project3)
// -[worksOn]->(project4)
// -[knows]->(John)
// (john)-[worksOn]->(project3)
// -[worksOn]->(project1)
Edge eMartinWorksOnProject1 = Iterators.getOnlyElement(Iterators.filter(vMartin.edges(Direction.OUT, "worksOn"), e -> e.inVertex().equals(vProject1)));
eMartinWorksOnProject1.remove();
vJohn.addEdge("worksOn", vProject1);
g.tx().commit();
System.out.println("Before commit #1: " + timestampBeforeTx1);
System.out.println("Before commit #2: " + timestampBeforeTx2);
System.out.println("Before commit #3: " + timestampBeforeTx3);
// open a transaction before the first commit and assert that the graph is empty
{
g.tx().open(timestampBeforeTx1);
assertEquals(timestampBeforeTx1, g.tx().getCurrentTransaction().getTimestamp());
this.assertVertexAndEdgeCountEquals(g, 0, 0);
// assert that the histories are empty
List<Long> historyMartin = Lists.newArrayList(g.getVertexHistory(vMartinId));
List<Long> historyJohn = Lists.newArrayList(g.getVertexHistory(vJohnId));
assertEquals(0, historyMartin.size());
assertEquals(0, historyJohn.size());
// close the transaction again
g.tx().close();
}
// open a second transaction after the first commit and assert graph integrity
{
g.tx().open(timestampBeforeTx2);
assertEquals(timestampBeforeTx2, g.tx().getCurrentTransaction().getTimestamp());
this.assertVertexAndEdgeCountEquals(g, 5, 4);
this.assertVertexExists(g, vMartinId);
this.assertVertexExists(g, vJohnId);
this.assertVertexExists(g, vProject1Id);
this.assertVertexExists(g, vProject2Id);
this.assertVertexExists(g, vProject3Id);
Vertex martin = this.getVertex(g, vMartinId);
Vertex john = this.getVertex(g, vJohnId);
Vertex project1 = this.getVertex(g, vProject1Id);
Vertex project2 = this.getVertex(g, vProject2Id);
Vertex project3 = this.getVertex(g, vProject3Id);
this.assertEdgeExists(martin, john, "knows");
this.assertEdgeExists(martin, project1, "worksOn");
this.assertEdgeExists(martin, project2, "worksOn");
this.assertEdgeExists(john, project3, "worksOn");
// assert that the histories are correct
List<Long> historyMartin = Lists.newArrayList(g.getVertexHistory(vMartin));
List<Long> historyJohn = Lists.newArrayList(g.getVertexHistory(vJohn));
assertEquals(1, historyMartin.size());
assertEquals(1, historyJohn.size());
assertTrue(Iterables.getOnlyElement(historyMartin) > timestampBeforeTx1);
assertTrue(Iterables.getOnlyElement(historyMartin) <= timestampBeforeTx2);
assertTrue(Iterables.getOnlyElement(historyMartin) < timestampBeforeTx3);
assertTrue(Iterables.getOnlyElement(historyJohn) > timestampBeforeTx1);
assertTrue(Iterables.getOnlyElement(historyJohn) <= timestampBeforeTx2);
assertTrue(Iterables.getOnlyElement(historyJohn) < timestampBeforeTx3);
// close the transaction again
g.tx().close();
}
// open a third transaction after the second commit and assert graph integrity
{
g.tx().open(timestampBeforeTx3);
assertEquals(timestampBeforeTx3, g.tx().getCurrentTransaction().getTimestamp());
this.assertVertexAndEdgeCountEquals(g, 5, 5);
this.assertVertexExists(g, vMartinId);
this.assertVertexExists(g, vJohnId);
this.assertVertexExists(g, vProject1Id);
this.assertVertexNotExists(g, vProject2Id);
this.assertVertexExists(g, vProject3Id);
this.assertVertexExists(g, vProject4Id);
Vertex martin = this.getVertex(g, vMartinId);
Vertex john = this.getVertex(g, vJohnId);
Vertex project1 = this.getVertex(g, vProject1Id);
Vertex project3 = this.getVertex(g, vProject3Id);
Vertex project4 = this.getVertex(g, vProject4Id);
this.assertEdgeExists(martin, john, "knows");
this.assertEdgeExists(martin, project1, "worksOn");
this.assertEdgeExists(martin, project3, "worksOn");
this.assertEdgeExists(martin, project4, "worksOn");
this.assertEdgeExists(john, project3, "worksOn");
// assert that the histories are correct
List<Long> historyMartin = Lists.newArrayList(g.getVertexHistory(vMartin));
List<Long> historyJohn = Lists.newArrayList(g.getVertexHistory(vJohn));
assertEquals(2, historyMartin.size());
assertEquals(1, historyJohn.size());
// close the transaction again
g.tx().close();
}
// open one last transaction to verify the final graph state
{
g.tx().open();
this.assertVertexAndEdgeCountEquals(g, 5, 5);
this.assertVertexExists(g, vMartinId);
this.assertVertexExists(g, vJohnId);
this.assertVertexExists(g, vProject1Id);
this.assertVertexNotExists(g, vProject2Id);
this.assertVertexExists(g, vProject3Id);
this.assertVertexExists(g, vProject4Id);
Vertex martin = this.getVertex(g, vMartinId);
Vertex john = this.getVertex(g, vJohnId);
Vertex project1 = this.getVertex(g, vProject1Id);
Vertex project3 = this.getVertex(g, vProject3Id);
Vertex project4 = this.getVertex(g, vProject4Id);
this.assertEdgeExists(martin, john, "knows");
this.assertEdgeExists(martin, project3, "worksOn");
this.assertEdgeExists(martin, project4, "worksOn");
this.assertEdgeExists(john, project1, "worksOn");
this.assertEdgeExists(john, project3, "worksOn");
// assert that the histories are correct
List<Long> historyMartin = Lists.newArrayList(g.getVertexHistory(vMartin));
List<Long> historyJohn = Lists.newArrayList(g.getVertexHistory(vJohn));
assertEquals(3, historyMartin.size());
assertEquals(2, historyJohn.size());
g.tx().close();
}
}
private void assertVertexAndEdgeCountEquals(final Graph g, final int vertexCount, final int edgeCount) {
Set<Vertex> vertices = Sets.newHashSet(g.vertices());
Set<Edge> edges = Sets.newHashSet(g.edges());
assertEquals(vertexCount, vertices.size());
assertEquals(edgeCount, edges.size());
}
private void assertEdgeExists(final Vertex outV, final Vertex inV, final String label) {
Iterator<Edge> iterator = outV.edges(Direction.OUT, label);
Edge edge = Iterators.getOnlyElement(Iterators.filter(iterator, e -> e.inVertex().equals(inV)), null);
assertNotNull(edge);
assertFalse(((ChronoEdge) edge).isRemoved());
iterator = inV.edges(Direction.IN, label);
edge = Iterators.getOnlyElement(Iterators.filter(iterator, e -> e.outVertex().equals(outV)), null);
assertNotNull(edge);
assertFalse(((ChronoEdge) edge).isRemoved());
}
private void assertVertexExists(final Graph g, final String vertexId) {
Vertex vertex = this.getVertex(g, vertexId);
assertNotNull(vertex);
assertFalse(((ChronoVertex) vertex).isRemoved());
}
private void assertVertexNotExists(final Graph g, final String vertexId) {
Vertex vertex = this.getVertex(g, vertexId);
if (vertex == null) {
return;
}
assertTrue(((ChronoVertex) vertex).isRemoved());
}
private Vertex getVertex(final Graph g, final String id) {
return Iterators.getOnlyElement(g.vertices(id), null);
}
}
| 11,623 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
HistoryManagerTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/HistoryManagerTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.history.RestoreResult;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
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 HistoryManagerTest extends AllChronoGraphBackendsTest {
@Test
public void restoringNonExistentVertexHasNoEffect() {
ChronoGraph g = this.getGraph();
g.tx().open();
RestoreResult result = g.getHistoryManager().restoreVertexAsOf(0, "bullshit-id");
assertThat(result.getFailedEdgeIds().isEmpty(), is(true));
assertThat(result.getSuccessfullyRestoredEdgeIds().isEmpty(), is(true));
assertThat(result.getSuccessfullyRestoredVertexIds(), contains("bullshit-id"));
ChronoGraphTransaction tx = g.tx().getCurrentTransaction();
assertThat(tx.getContext().isDirty(), is(false));
}
@Test
public void canRestoreVertexFromNonExistentState() {
ChronoGraph g = this.getGraph();
g.tx().open();
Vertex vertex = g.addVertex("firstName", "John", "lastName", "Doe");
String vertexId = (String) vertex.id();
g.tx().commit();
g.tx().open();
g.getHistoryManager().restoreVertexAsOf(0L, vertexId);
ChronoGraphTransaction tx = g.tx().getCurrentTransaction();
assertThat(tx.getContext().isDirty(), is(true));
assertThat(tx.getContext().getModifiedVertices().size(), is(1));
assertThat(Iterables.getOnlyElement(tx.getContext().getModifiedVertices()).id(), is(vertexId));
// the vertex should not exist anymore, as it has been restored from timestamp 0 (where it did not exist)
assertThat(g.vertices(vertexId).hasNext(), is(false));
}
@Test
public void canRestoreVertexFromExistingState() {
ChronoGraph g = this.getGraph();
g.tx().open();
Vertex vertex = g.addVertex("firstName", "John", "lastName", "Doe");
String vertexId = (String) vertex.id();
g.tx().commit();
long afterFirstCommit = g.getNow();
g.tx().open();
g.vertices(vertexId).next().property("lastName", "Smith");
g.tx().commit();
g.tx().open();
g.getHistoryManager().restoreVertexAsOf(afterFirstCommit, vertexId);
ChronoGraphTransaction tx = g.tx().getCurrentTransaction();
assertThat(tx.getContext().isDirty(), is(true));
assertThat(tx.getContext().getModifiedVertices().size(), is(1));
assertThat(Iterables.getOnlyElement(tx.getContext().getModifiedVertices()).id(), is(vertexId));
Vertex restoredVertex = Iterators.getOnlyElement(g.vertices(vertexId));
assertThat(restoredVertex.value("firstName"), is("John"));
assertThat(restoredVertex.value("lastName"), is("Doe"));
}
@Test
public void restoringAVertexDropsItsCurrentState() {
ChronoGraph g = this.getGraph();
g.tx().open();
Vertex vertex = g.addVertex("firstName", "John", "lastName", "Doe");
String vertexId = (String) vertex.id();
g.tx().commit();
long afterFirstCommit = g.getNow();
g.tx().open();
Vertex v = g.vertices(vertexId).next();
v.property("firstName").remove();
v.property("age", 30);
v.addEdge("self", v);
g.getHistoryManager().restoreVertexAsOf(afterFirstCommit, vertexId);
assertThat(v.value("firstName"), is("John"));
assertThat(v.value("lastName"), is("Doe"));
assertThat(v.edges(Direction.BOTH).hasNext(), is(false));
assertThat(g.edges().hasNext(), is(false));
}
@Test
public void restoringAVertexAlsoRestoresTheEdges() {
ChronoGraph g = this.getGraph();
g.tx().open();
ChronoVertex vJohn = (ChronoVertex) g.addVertex("firstName", "John", "lastName", "Doe");
ChronoVertex vJane = (ChronoVertex) g.addVertex("firstName", "Jane", "lastName", "Doe");
ChronoVertex vJack = (ChronoVertex) g.addVertex("firstName", "Jack", "lastName", "Smith");
vJohn.addEdge("marriedTo", vJane);
vJack.addEdge("friend", vJohn);
g.tx().commit();
long afterFirstCommit = g.getNow();
g.tx().open();
vJohn.remove();
g.tx().commit();
g.tx().open();
assertThat(g.vertices(vJohn).hasNext(), is(false));
RestoreResult restoreResult = g.getHistoryManager().restoreVertexAsOf(afterFirstCommit, vJohn.id());
assertThat(restoreResult.getSuccessfullyRestoredVertexIds(), contains(vJohn.id()));
assertThat(restoreResult.getSuccessfullyRestoredEdgeIds().size(), is(2));
assertThat(restoreResult.getFailedEdgeIds().size(), is(0));
assertThat(vJohn.isRemoved(), is(false));
assertThat(vJack.vertices(Direction.OUT, "friend").next(), is(vJohn));
assertThat(vJane.vertices(Direction.IN, "marriedTo").next(), is(vJohn));
assertThat(vJohn.vertices(Direction.OUT, "marriedTo").next(), is(vJane));
assertThat(vJohn.vertices(Direction.IN, "friend").next(), is(vJack));
}
@Test
public void nonRestorableEdgesAreReported() {
ChronoGraph g = this.getGraph();
g.tx().open();
ChronoVertex vJohn = (ChronoVertex) g.addVertex("firstName", "John", "lastName", "Doe");
ChronoVertex vJane = (ChronoVertex) g.addVertex("firstName", "Jane", "lastName", "Doe");
ChronoVertex vJack = (ChronoVertex) g.addVertex("firstName", "Jack", "lastName", "Smith");
vJohn.addEdge("marriedTo", vJane);
vJack.addEdge("friend", vJohn);
g.tx().commit();
long afterFirstCommit = g.getNow();
g.tx().open();
vJohn.remove();
vJane.remove();
g.tx().commit();
g.tx().open();
assertThat(g.vertices(vJohn).hasNext(), is(false));
RestoreResult restoreResult = g.getHistoryManager().restoreVertexAsOf(afterFirstCommit, vJohn.id());
assertThat(restoreResult.getSuccessfullyRestoredVertexIds(), contains(vJohn.id()));
assertThat(restoreResult.getSuccessfullyRestoredEdgeIds().size(), is(1));
assertThat(restoreResult.getFailedEdgeIds().size(), is(1));
assertThat(vJohn.isRemoved(), is(false));
assertThat(vJack.vertices(Direction.OUT, "friend").next(), is(vJohn));
assertThat(vJohn.vertices(Direction.OUT, "marriedTo").hasNext(), is(false));
assertThat(vJohn.vertices(Direction.IN, "friend").next(), is(vJack));
}
@Test
public void canRestoreGraphStateAsOfTimestamp() {
ChronoGraph g = this.getGraph();
g.tx().open();
ChronoVertex vJohn = (ChronoVertex) g.addVertex("firstName", "John", "lastName", "Doe");
ChronoVertex vJane = (ChronoVertex) g.addVertex("firstName", "Jane", "lastName", "Doe");
ChronoVertex vJack = (ChronoVertex) g.addVertex("firstName", "Jack", "lastName", "Smith");
vJohn.addEdge("marriedTo", vJane);
vJack.addEdge("friend", vJohn);
g.tx().commit();
long afterFirstCommit = g.getNow();
g.tx().open();
vJohn.property("lastName", "Smith");
vJack.remove();
ChronoVertex vSarah = (ChronoVertex) g.addVertex("firstName", "Sarah", "lastName", "Johnson");
vJane.addEdge("friend", vSarah);
g.tx().commit();
g.tx().open();
RestoreResult restoreResult = g.getHistoryManager().restoreGraphStateAsOf(0);
assertThat(restoreResult.getSuccessfullyRestoredVertexIds().size(), is(4));
assertThat(restoreResult.getSuccessfullyRestoredEdgeIds().size(), is(3));
assertThat(restoreResult.getFailedEdgeIds().size(), is(0));
// the graph should now be empty
assertThat(Iterators.size(g.vertices()), is(0));
assertThat(Iterators.size(g.edges()), is(0));
g.tx().rollback();
g.tx().open();
RestoreResult restoreResult2 = g.getHistoryManager().restoreGraphStateAsOf(afterFirstCommit);
assertThat(restoreResult2.getSuccessfullyRestoredVertexIds().size(), is(4));
assertThat(restoreResult2.getSuccessfullyRestoredEdgeIds().size(), is(3));
assertThat(restoreResult2.getFailedEdgeIds().size(), is(0));
assertThat(g.vertices(vSarah.id()).hasNext(), is(false));
assertThat(vJane.edges(Direction.OUT,"friend").hasNext(), is(false));
assertThat(vJohn.value("lastName"), is("Doe"));
assertThat(vJack.isRemoved(), is(false));
g.tx().commit();
g.tx().open();
assertThat(g.vertices(vSarah.id()).hasNext(), is(false));
assertThat(vJane.edges(Direction.OUT,"friend").hasNext(), is(false));
assertThat(vJohn.value("lastName"), is("Doe"));
assertThat(vJack.isRemoved(), is(false));
}
}
| 9,357 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphVariablesTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/ChronoGraphVariablesTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.tuple.Pair;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class ChronoGraphVariablesTest extends AllChronoGraphBackendsTest {
@Test
public void canReadWriteVariablesInCustomKeyspace(){
ChronoGraph g = this.getGraph();
g.variables().set("foo", "bar");
g.variables().set("math", "pi", 3.1415);
g.variables().set("math", "zero", 0);
g.variables().set("math", "one", 1);
g.variables().set("config", "log", "everything");
g.variables().set("config", "awesomeness", "yes");
this.assertCommitAssert(()->{
assertEquals(3.1415, g.variables().get("math", "pi").orElse(null));
assertNull(g.variables().get("pi").orElse(null));
assertNull(g.variables().get("foo", "pi").orElse(null));
assertNull(g.variables().get("config", "pi").orElse(null));
assertEquals(0, g.variables().get("math", "zero").orElse(null));
assertNull(g.variables().get("zero").orElse(null));
assertNull(g.variables().get("foo", "zero").orElse(null));
assertNull(g.variables().get("config", "zero").orElse(null));
assertEquals("everything", g.variables().get("config", "log").orElse(null));
assertEquals("yes", g.variables().get("config", "awesomeness").orElse(null));
assertEquals(Sets.newHashSet("foo"), g.variables().keys());
assertEquals(Sets.newHashSet("pi", "zero", "one"), g.variables().keys("math"));
assertEquals(Sets.newHashSet("log", "awesomeness"), g.variables().keys("config"));
assertEquals(Sets.newHashSet(ChronoGraphConstants.VARIABLES_DEFAULT_KEYSPACE, "math", "config"), g.variables().keyspaces());
Map<String, Object> mathMap = Maps.newHashMap();
mathMap.put("pi", 3.1415);
mathMap.put("zero", 0);
mathMap.put("one", 1);
assertEquals(mathMap, g.variables().asMap("math"));
Map<String, Object> configMap = Maps.newHashMap();
configMap.put("log", "everything");
configMap.put("awesomeness", "yes");
assertEquals(configMap, g.variables().asMap("config"));
Map<String, Object> defaultKeyspaceMap = Maps.newHashMap();
defaultKeyspaceMap.put("foo", "bar");
assertEquals(defaultKeyspaceMap, g.variables().asMap());
});
}
@Test
public void canQueryHistoryOfGraphVariables(){
ChronoGraph g = this.getGraph();
g.variables().set("foo", "bar");
g.variables().set("greeting", "hello", "world");
long commit1 = g.tx().commitAndReturnTimestamp();
assertThat(commit1, is(greaterThan(0L)));
g.variables().set("foo", "baz");
g.variables().set("person", "john", "doe");
long commit2 = g.tx().commitAndReturnTimestamp();
assertThat(commit2, is(greaterThan(commit1)));
g.variables().set("foo", "blub");
g.variables().set("fizz", "buzz");
g.variables().set("greeting", "hello", "chronos");
long commit3 = g.tx().commitAndReturnTimestamp();
assertThat(commit3, is(greaterThan(commit2)));
List<Pair<String, String>> commit2Variables = Lists.newArrayList(g.getChangedGraphVariablesAtCommit(commit2));
assertThat(commit2Variables, containsInAnyOrder(Pair.of(ChronoGraphConstants.VARIABLES_DEFAULT_KEYSPACE, "foo"), Pair.of("person", "john")));
List<String> changedVariablesInDefaultKeyspaceAtCommit3 = Lists.newArrayList(g.getChangedGraphVariablesAtCommitInDefaultKeyspace(commit3));
assertThat(changedVariablesInDefaultKeyspaceAtCommit3, containsInAnyOrder("foo", "fizz"));
List<String> greetingsChangesInCommit3 = Lists.newArrayList(g.getChangedGraphVariablesAtCommitInKeyspace(commit3, "greeting"));
assertThat(greetingsChangesInCommit3, containsInAnyOrder("hello"));
}
@Test
public void nonChangesOnVariablesAreIgnoredInDefaultKeyspace(){
ChronoGraph g = this.getGraph();
g.variables().set("foo", "bar");
assertThat(g.tx().commitAndReturnTimestamp(), is(greaterThan(0L)));
// set the variable to the same value it already has -> non-change
g.variables().set("foo", "bar");
assertEquals(-1, g.tx().commitAndReturnTimestamp());
// set the variable to another value...
g.variables().set("foo", "blub");
// ...and back to the original one
g.variables().set("foo","bar");
assertEquals(-1, g.tx().commitAndReturnTimestamp());
}
@Test
public void nonChangesOnVariablesAreIgnoredInCustomKeyspace(){
ChronoGraph g = this.getGraph();
g.variables().set("custom", "foo", "bar");
g.tx().commit();
// set the variable to the same value it already has -> non-change
g.variables().set("custom", "foo", "bar");
assertEquals(-1, g.tx().commitAndReturnTimestamp());
// set the variable to another value...
g.variables().set("custom", "foo", "blub");
// ...and back to the original one
g.variables().set("custom", "foo","bar");
assertEquals(-1, g.tx().commitAndReturnTimestamp());
}
}
| 5,714 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ElementTransactionTransitionTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/ElementTransactionTransitionTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.GraphTransactionContext;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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.NoSuchElementException;
import java.util.Set;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class ElementTransactionTransitionTest extends AllChronoGraphBackendsTest {
@Test
public void vertexCanBeAccessedAfterCommit() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex("name", "martin");
g.tx().commit();
// now we have a new transaction, but we can still use the vertex
assertEquals("martin", v.value("name"));
}
@Test
public void transientVertexModificationsAreResetOnRollback() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex("name", "martin");
g.tx().commit();
// now modify the vertex
v.property("name", "john");
// assert that the transient modification is applied
assertEquals("john", v.value("name"));
// perform the rollback
g.tx().rollback();
// assert that the vertex is back in its old state
assertEquals("martin", v.value("name"));
}
@Test
public void removedVertexCanBeAccessedAfterCommitButIsInRemovedState() {
ChronoGraph g = this.getGraph();
Vertex v = g.addVertex("name", "martin");
g.tx().commit();
// remove the vertex
v.remove();
g.tx().commit();
// assert that the vertex is still present, but removed
try {
v.value("name");
fail("Removed vertex is still accessible!");
} catch (NoSuchElementException expected) {
// ok
}
}
@Test
public void canReuseVerticesAfterTransactionCommit() {
ChronoGraph g = this.getGraph();
Vertex vMartin1 = g.addVertex("name", "martin", "age", 26);
Vertex vJohn1 = g.addVertex("name", "john", "age", 20);
g.tx().commit();
// now, retrieve the vertices via queries
Vertex vMartin2 = Iterables.getOnlyElement(g.traversal().V().has("name", "martin").toSet());
Vertex vJohn2 = Iterables.getOnlyElement(g.traversal().V().has("name", "john").toSet());
assertNotNull(vMartin2);
assertNotNull(vJohn2);
// they must be equal to their predecessors
assertEquals(vMartin1, vMartin2);
assertEquals(vJohn1, vJohn2);
// changing the successor must update the predecessor
vMartin2.property("age", 30);
assertEquals(30, (int) vMartin1.value("age"));
// changing the predecessor must update the successor
vJohn1.property("age", 21);
assertEquals(21, (int) vJohn2.value("age"));
}
@Test
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, value = "false")
public void canReuseVerticesAfterIncrementalCommit() {
ChronoGraph graph = this.getGraph();
// open a new graph transaction
graph.tx().open();
// extend the graph
Vertex v2 = graph.addVertex(T.id, "v2", "firstname", "Jane", "lastname", "Smith");
Vertex v3 = graph.addVertex(T.id, "v3", "firstname", "Jill", "lastname", "Johnson");
// {
// System.out.println("BEFORE ROLLOVER");
// ChronoVertexProxy v2Proxy = (ChronoVertexProxy) v2;
// ChronoVertexImpl v2Impl = v2Proxy.getElement();
// ChronoVertexProxy v2ProxyReloaded = (ChronoVertexProxy) graph.vertices(v2Proxy).next();
// ChronoVertexImpl v2ImplReloaded = v2ProxyReloaded.getElement();
// System.out.println(
// "Vertex [v2]: ProxyID=" + hexId(v2Proxy) + ", VertexID=" + hexId(v2Impl) + ", Refreshed ProxyID="
// + hexId(v2ProxyReloaded) + ", Refreshed VertexID=" + hexId(v2ImplReloaded));
// ChronoVertexProxy v3Proxy = (ChronoVertexProxy) v3;
// ChronoVertexImpl v3Impl = v3Proxy.getElement();
// ChronoVertexProxy v3ProxyReloaded = (ChronoVertexProxy) graph.vertices(v3Proxy).next();
// ChronoVertexImpl v3ImplReloaded = v3ProxyReloaded.getElement();
// System.out.println(
// "Vertex [v3]: ProxyID=" + hexId(v3Proxy) + ", VertexID=" + hexId(v3Impl) + ", Refreshed ProxyID="
// + hexId(v3ProxyReloaded) + ", Refreshed VertexID=" + hexId(v3ImplReloaded));
// }
assertEquals(1, (long) graph.traversal().V().has("firstname", "Jane").count().next());
// perform the incremental commit
graph.tx().commitIncremental();
// jane should exist
assertEquals(v2, graph.traversal().V(v2).next());
// jill should exist
assertEquals(v3, graph.traversal().V(v3).next());
assertEquals(1, (long)graph.traversal().V().has("firstname", "Jane").count().next());
// {
// System.out.println("AFTER ROLLOVER, BEFORE ADD EDGE");
// ChronoVertexProxy v2Proxy = (ChronoVertexProxy) v2;
// ChronoVertexImpl v2Impl = v2Proxy.getElement();
// ChronoVertexProxy v2ProxyReloaded = (ChronoVertexProxy) graph.vertices(v2Proxy).next();
// ChronoVertexImpl v2ImplReloaded = v2ProxyReloaded.getElement();
// System.out.println(
// "Vertex [v2]: ProxyID=" + hexId(v2Proxy) + ", VertexID=" + hexId(v2Impl) + ", Refreshed ProxyID="
// + hexId(v2ProxyReloaded) + ", Refreshed VertexID=" + hexId(v2ImplReloaded));
// ChronoVertexProxy v3Proxy = (ChronoVertexProxy) v3;
// ChronoVertexImpl v3Impl = v3Proxy.getElement();
// ChronoVertexProxy v3ProxyReloaded = (ChronoVertexProxy) graph.vertices(v3Proxy).next();
// ChronoVertexImpl v3ImplReloaded = v3ProxyReloaded.getElement();
// System.out.println(
// "Vertex [v3]: ProxyID=" + hexId(v3Proxy) + ", VertexID=" + hexId(v3Impl) + ", Refreshed ProxyID="
// + hexId(v3ProxyReloaded) + ", Refreshed VertexID=" + hexId(v3ImplReloaded));
// }
// create some associations
v2.addEdge("knows", v3, "kind", "friend");
v3.addEdge("knows", v2, "kind", "friend");
// {
// System.out.println("AFTER ROLLOVER, AFTER ADD EDGE");
// ChronoVertexProxy v2Proxy = (ChronoVertexProxy) v2;
// ChronoVertexImpl v2Impl = v2Proxy.getElement();
// ChronoVertexProxy v2ProxyReloaded = (ChronoVertexProxy) graph.vertices(v2Proxy).next();
// ChronoVertexImpl v2ImplReloaded = v2ProxyReloaded.getElement();
// System.out.println(
// "Vertex [v2]: ProxyID=" + hexId(v2Proxy) + ", VertexID=" + hexId(v2Impl) + ", Refreshed ProxyID="
// + hexId(v2ProxyReloaded) + ", Refreshed VertexID=" + hexId(v2ImplReloaded));
// ChronoVertexProxy v3Proxy = (ChronoVertexProxy) v3;
// ChronoVertexImpl v3Impl = v3Proxy.getElement();
// ChronoVertexProxy v3ProxyReloaded = (ChronoVertexProxy) graph.vertices(v3Proxy).next();
// ChronoVertexImpl v3ImplReloaded = v3ProxyReloaded.getElement();
// System.out.println(
// "Vertex [v3]: ProxyID=" + hexId(v3Proxy) + ", VertexID=" + hexId(v3Impl) + ", Refreshed ProxyID="
// + hexId(v3ProxyReloaded) + ", Refreshed VertexID=" + hexId(v3ImplReloaded));
// }
// jane and jill should be marked as "dirty" in the transaction context
ChronoGraphTransaction tx = graph.tx().getCurrentTransaction();
GraphTransactionContext context = tx.getContext();
assertEquals(2, context.getModifiedVertices().size());
// jane and jill should have one outgoing edge each
assertEquals(1, Iterators.size(v2.edges(Direction.OUT, "knows")));
assertEquals(1, Iterators.size(v3.edges(Direction.OUT, "knows")));
// even after reloading their elements, jane and jill should STILL have one outgoing edge each
assertEquals(1, Iterators.size(graph.vertices(v2).next().edges(Direction.OUT, "knows")));
assertEquals(1, Iterators.size(graph.vertices(v3).next().edges(Direction.OUT, "knows")));
// jane should know jill
assertEquals(1, graph.traversal().V(v2).outE("knows").toSet().size());
assertEquals(1, graph.traversal().V(v3).inE("knows").toSet().size());
// jill should know jane
assertEquals(1, graph.traversal().V(v3).outE("knows").toSet().size());
assertEquals(1, graph.traversal().V(v2).inE("knows").toSet().size());
graph.tx().commit();
graph.tx().open();
// jane should know jill
assertEquals(1, graph.traversal().V(v2).outE("knows").toSet().size());
assertEquals(1, graph.traversal().V(v3).inE("knows").toSet().size());
// jill should know jane
assertEquals(1, graph.traversal().V(v3).outE("knows").toSet().size());
assertEquals(1, graph.traversal().V(v2).inE("knows").toSet().size());
graph.tx().close();
}
@Test
public void cannotAccessGraphElementFromOtherThread() {
ChronoGraph g = this.getGraph();
Vertex vMartin = g.addVertex("name", "martin", "age", 26);
g.tx().commit();
// use a thread (controlled synchronously) to access some vertex data
Thread worker = new Thread(() -> {
try {
vMartin.value("name");
fail("Managed to access vertex data from other thread!");
} catch (IllegalStateException expected) {
// pass
}
});
// set up a root exception handler in the thread, such that our test
// can fail properly if an error during the access in the other thread occurs
Set<Throwable> workerThreadExceptions = Sets.newConcurrentHashSet();
worker.setUncaughtExceptionHandler((thread, ex) -> {
workerThreadExceptions.add(ex);
});
// run the worker
worker.start();
// wait for the worker to finish
try {
worker.join();
} catch (InterruptedException e) {
fail("Worker was interrupted! Exception: " + e);
}
// assert that there were no errors during the access
assertEquals(Collections.emptySet(), workerThreadExceptions);
}
// private static String hexId(final Object obj) {
// return Integer.toHexString(System.identityHashCode(obj));
// }
}
| 11,120 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ManyChangesOnSamePropertyValueTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/ManyChangesOnSamePropertyValueTest.java | package org.chronos.chronograph.test.cases.transaction;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Table;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoProperty;
import org.chronos.chronograph.internal.impl.transaction.GraphTransactionContextImpl;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class ManyChangesOnSamePropertyValueTest extends AllChronoGraphBackendsTest {
@Test
public void overwriteSamePropertyOneMillionTimes() throws Exception {
ChronoGraph graph = this.getGraph();
graph.tx().open();
Vertex v = graph.addVertex();
for (int i = 0; i < 1_000_000; i++) {
v.property("i").remove();
v.property("i", i);
}
assertThatOnlyOnePropertyIsModified(graph);
graph.tx().commit();
graph.tx().open();
Vertex v1 = Iterators.getOnlyElement(graph.vertices());
for (int i = 0; i < 1_000_000; i++) {
v1.property("i", i);
}
this.assertThatOnlyOnePropertyIsModified(graph);
graph.tx().commit();
}
private void assertThatOnlyOnePropertyIsModified(final ChronoGraph graph) throws NoSuchFieldException, IllegalAccessException {
GraphTransactionContextImpl ctx = (GraphTransactionContextImpl) graph.tx().getCurrentTransaction().getContext();
Field field = ctx.getClass().getDeclaredField("vertexPropertyNameToOwnerIdToModifiedProperty");
field.setAccessible(true);
Table<String, String, ChronoProperty<?>> table = (Table<String, String, ChronoProperty<?>>)field.get(ctx);
assertThat(table.size(), is(1));
}
@Test
public void removingPropertyWorksWithIndexing(){
ChronoGraph graph = this.getGraph();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("p").acrossAllTimestamps().build();
{
graph.tx().open();
Vertex v = graph.addVertex();
v.property("p", "Hello");
graph.tx().commit();
}
{
graph.tx().open();
Set<Vertex> queryResult = graph.traversal().V().has("p", "Hello").toSet();
assertThat(queryResult.size(), is(1));
Vertex v = Iterables.getOnlyElement(queryResult);
v.property("p").remove();
Set<Vertex> queryResult2 = graph.traversal().V().has("p", "Hello").toSet();
assertThat(queryResult2.size(), is(0));
graph.tx().commit();
}
{
graph.tx().open();
Set<Vertex> queryResult = graph.traversal().V().has("p", "Hello").toSet();
assertThat(queryResult.size(), is(0));
}
}
}
| 3,055 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphScriptedTriggerTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/trigger/ChronoGraphScriptedTriggerTest.java | package org.chronos.chronograph.test.cases.transaction.trigger;
import com.google.common.collect.Lists;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPostCommitTrigger;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPostPersistTrigger;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPreCommitTrigger;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPrePersistTrigger;
import org.chronos.chronograph.api.transaction.trigger.GraphTriggerMetadata;
import org.chronos.chronograph.api.transaction.trigger.ScriptedGraphTrigger;
import org.chronos.chronograph.internal.impl.transaction.trigger.script.ScriptedGraphPostCommitTrigger;
import org.chronos.chronograph.internal.impl.transaction.trigger.script.ScriptedGraphPostPersistTrigger;
import org.chronos.chronograph.internal.impl.transaction.trigger.script.ScriptedGraphPreCommitTrigger;
import org.chronos.chronograph.internal.impl.transaction.trigger.script.ScriptedGraphPrePersistTrigger;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class ChronoGraphScriptedTriggerTest extends AllChronoGraphBackendsTest {
@Before
public void prepareTracker() {
ScriptedTriggerTestTracker.getInstance().clearMessages();
}
@After
public void clearTracker() {
ScriptedTriggerTestTracker.getInstance().clearMessages();
}
@Test
public void canUseScriptedGraphTriggers() {
ChronoGraph graph = this.getGraph();
String trigger1Script = ScriptedTriggerTestTracker.class.getName() + ".getInstance().addMessage("
+ "\"PRE COMMIT: v=\" + context.getCurrentState().getModifiedVertices().size() + \", e=\" + context.getCurrentState().getModifiedEdges().size()"
+ ")";
ChronoGraphPreCommitTrigger trigger1 = ScriptedGraphTrigger.createPreCommitTrigger(trigger1Script, 0);
String trigger2Script = ScriptedTriggerTestTracker.class.getName() + ".getInstance().addMessage("
+ "\"PRE PERSIST: v=\" + context.getCurrentState().getModifiedVertices().size() + \", e=\" + context.getCurrentState().getModifiedEdges().size()"
+ ")";
ChronoGraphPrePersistTrigger trigger2 = ScriptedGraphTrigger.createPrePersistTrigger(trigger2Script, 0);
String trigger3Script = ScriptedTriggerTestTracker.class.getName() + ".getInstance().addMessage("
+ "\"POST PERSIST: v=\" + context.getCurrentState().getModifiedVertices().size() + \", e=\" + context.getCurrentState().getModifiedEdges().size()"
+ ")";
ChronoGraphPostPersistTrigger trigger3 = ScriptedGraphTrigger.createPostPersistTrigger(trigger3Script, 0);
String trigger4Script = ScriptedTriggerTestTracker.class.getName() + ".getInstance().addMessage("
+ "\"POST COMMIT: v=\" + context.getCurrentState().getModifiedVertices().size() + \", e=\" + context.getCurrentState().getModifiedEdges().size()"
+ ")";
ChronoGraphPostCommitTrigger trigger4 = ScriptedGraphTrigger.createPostCommitTrigger(trigger4Script, 0);
graph.getTriggerManager().createTrigger("trigger1", trigger1);
graph.getTriggerManager().createTrigger("trigger2", trigger2);
graph.getTriggerManager().createTrigger("trigger3", trigger3);
graph.getTriggerManager().createTrigger("trigger4", trigger4);
graph.tx().open();
try{
Vertex john = graph.addVertex(T.id, "john");
Vertex jane = graph.addVertex(T.id, "jane");
john.addEdge("marriedTo", jane);
graph.tx().commit();
}finally{
if(graph.tx().isOpen()){
graph.tx().rollback();
}
}
// our triggers should have fired and reported to the (static) tracker.
List<String> messages = ScriptedTriggerTestTracker.getInstance().getMessages();
assertThat(messages.size(), is(4));
assertThat(messages.get(0), is("PRE COMMIT: v=2, e=1"));
assertThat(messages.get(1), is("PRE PERSIST: v=2, e=1"));
assertThat(messages.get(2), is("POST PERSIST: v=2, e=1"));
assertThat(messages.get(3), is("POST COMMIT: v=2, e=1"));
// make sure that trigger metadata is accessible
List<GraphTriggerMetadata> triggerMetadata = graph.getTriggerManager().getTriggers();
assertThat(triggerMetadata.size(), is(4));
assertThat(triggerMetadata.get(0).getTriggerName(), is("trigger1"));
assertThat(triggerMetadata.get(0).getTriggerClassName(), is(ScriptedGraphPreCommitTrigger.class.getName()));
assertThat(triggerMetadata.get(0).getPriority(), is(0));
assertThat(triggerMetadata.get(0).getInstantiationException(), is(nullValue()));
assertThat(triggerMetadata.get(0).getUserScriptContent(), is(trigger1Script));
assertThat(triggerMetadata.get(0).isPreCommitTrigger(), is(true));
assertThat(triggerMetadata.get(0).isPrePersistTrigger(), is(false));
assertThat(triggerMetadata.get(0).isPostPersistTrigger(), is(false));
assertThat(triggerMetadata.get(0).isPostCommitTrigger(), is(false));
assertThat(triggerMetadata.get(1).getTriggerName(), is("trigger2"));
assertThat(triggerMetadata.get(1).getTriggerClassName(), is(ScriptedGraphPrePersistTrigger.class.getName()));
assertThat(triggerMetadata.get(1).getPriority(), is(0));
assertThat(triggerMetadata.get(1).getInstantiationException(), is(nullValue()));
assertThat(triggerMetadata.get(1).getUserScriptContent(), is(trigger2Script));
assertThat(triggerMetadata.get(1).isPreCommitTrigger(), is(false));
assertThat(triggerMetadata.get(1).isPrePersistTrigger(), is(true));
assertThat(triggerMetadata.get(1).isPostPersistTrigger(), is(false));
assertThat(triggerMetadata.get(1).isPostCommitTrigger(), is(false));
assertThat(triggerMetadata.get(2).getTriggerName(), is("trigger3"));
assertThat(triggerMetadata.get(2).getTriggerClassName(), is(ScriptedGraphPostPersistTrigger.class.getName()));
assertThat(triggerMetadata.get(2).getPriority(), is(0));
assertThat(triggerMetadata.get(2).getInstantiationException(), is(nullValue()));
assertThat(triggerMetadata.get(2).getUserScriptContent(), is(trigger3Script));
assertThat(triggerMetadata.get(2).isPreCommitTrigger(), is(false));
assertThat(triggerMetadata.get(2).isPrePersistTrigger(), is(false));
assertThat(triggerMetadata.get(2).isPostPersistTrigger(), is(true));
assertThat(triggerMetadata.get(2).isPostCommitTrigger(), is(false));
assertThat(triggerMetadata.get(3).getTriggerName(), is("trigger4"));
assertThat(triggerMetadata.get(3).getTriggerClassName(), is(ScriptedGraphPostCommitTrigger.class.getName()));
assertThat(triggerMetadata.get(3).getPriority(), is(0));
assertThat(triggerMetadata.get(3).getInstantiationException(), is(nullValue()));
assertThat(triggerMetadata.get(3).getUserScriptContent(), is(trigger4Script));
assertThat(triggerMetadata.get(3).isPreCommitTrigger(), is(false));
assertThat(triggerMetadata.get(3).isPrePersistTrigger(), is(false));
assertThat(triggerMetadata.get(3).isPostPersistTrigger(), is(false));
assertThat(triggerMetadata.get(3).isPostCommitTrigger(), is(true));
}
public static class ScriptedTriggerTestTracker {
private static final ScriptedTriggerTestTracker INSTANCE = new ScriptedTriggerTestTracker();
public static ScriptedTriggerTestTracker getInstance() {
return INSTANCE;
}
private final List<String> messages = Lists.newArrayList();
public void addMessage(String message) {
messages.add(message);
}
public List<String> getMessages() {
return Collections.unmodifiableList(this.messages);
}
public void clearMessages() {
this.messages.clear();
}
}
}
| 8,393 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTriggerTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/trigger/ChronoGraphTriggerTest.java | package org.chronos.chronograph.test.cases.transaction.trigger;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.gremlin.structure.Graph.Variables;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronograph.api.exceptions.TriggerAlreadyExistsException;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.structure.ElementLifecycleStatus;
import org.chronos.chronograph.api.transaction.trigger.CancelCommitException;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPostCommitTrigger;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPostPersistTrigger;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPreCommitTrigger;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPrePersistTrigger;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphTrigger;
import org.chronos.chronograph.api.transaction.trigger.GraphTriggerMetadata;
import org.chronos.chronograph.api.transaction.trigger.PostCommitTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.PostPersistTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.PreCommitTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.PrePersistTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.TriggerContext;
import org.chronos.chronograph.api.transaction.trigger.TriggerTiming;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.transaction.trigger.ChronoGraphTriggerManagerInternal;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.AppendPriorityTrigger.AppendPriorityPreCommitTrigger;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.AppendPriorityTrigger.AppendPriorityPrePersistTrigger;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.ChangeSetRecordingTrigger.ChangeSetRecordingPostCommitTrigger;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.ChangeSetRecordingTrigger.ChangeSetRecordingPostPersistTrigger;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.VertexCountTrigger.VertexCountPostCommitTrigger;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.VertexCountTrigger.VertexCountPostPersistTrigger;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.VertexCountTrigger.VertexCountPreCommitTrigger;
import org.chronos.chronograph.test.cases.transaction.trigger.ChronoGraphTriggerTest.VertexCountTrigger.VertexCountPrePersistTrigger;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
public class ChronoGraphTriggerTest extends AllChronoGraphBackendsTest {
@Test
public void cannotAddTriggerWithoutConcreteInterface(){
ChronoGraph graph = this.getGraph();
try{
graph.getTriggerManager().createTrigger("test", new FakeTrigger());
fail("Managed to add a trigger without a concrete interface!");
}catch(IllegalArgumentException expected){
// pass
}
try{
graph.getTriggerManager().createTriggerIfNotPresent("test", FakeTrigger::new);
fail("Managed to add a trigger without a concrete interface!");
}catch(IllegalArgumentException expected){
// pass
}
try{
graph.getTriggerManager().createTriggerAndOverwrite("test", new FakeTrigger());
fail("Managed to add a trigger without a concrete interface!");
}catch(IllegalArgumentException expected){
// pass
}
}
@Test
public void canAddRemoveAndListTriggers() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("foo", new DummyTrigger());
graph.getTriggerManager().createTrigger("bar", new DummyTrigger());
assertThat(graph.getTriggerManager().existsTrigger("foo"), is(true));
assertThat(graph.getTriggerManager().existsTrigger("bar"), is(true));
assertThat(graph.getTriggerManager().getTriggerNames(), containsInAnyOrder("foo", "bar"));
graph.getTriggerManager().dropTrigger("foo");
assertThat(graph.getTriggerManager().existsTrigger("foo"), is(false));
assertThat(graph.getTriggerManager().existsTrigger("bar"), is(true));
assertThat(graph.getTriggerManager().getTriggerNames(), containsInAnyOrder("bar"));
}
@Test
public void cannotAddTwoTriggersWithTheSameName() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("foo", new DummyTrigger());
try {
graph.getTriggerManager().createTrigger("foo", new DummyTrigger());
fail("Managed to add two triggers with the same name!");
} catch (TriggerAlreadyExistsException expected) {
// pass
}
}
@Test
public void canOverrideTriggerByName() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("foo", new DummyTrigger());
graph.getTriggerManager().createTriggerAndOverwrite("foo", new DummyTrigger2());
assertThat(graph.getTriggerManager().existsTrigger("foo"), is(true));
assertThat(graph.getTriggerManager().getTriggerNames(), contains("foo"));
ChronoGraphTriggerManagerInternal triggerManager = (ChronoGraphTriggerManagerInternal) graph.getTriggerManager();
List<Pair<String, ChronoGraphPostCommitTrigger>> triggers = triggerManager.getPostCommitTriggers();
assertThat(triggers.size(), is(1));
Pair<String, ChronoGraphPostCommitTrigger> pair = Iterables.getOnlyElement(triggers);
assertThat(pair, is(notNullValue()));
assertThat(pair.getLeft(), is("foo"));
assertThat(pair.getRight(), is(notNullValue()));
assertThat(pair.getRight(), instanceOf(DummyTrigger2.class));
}
@Test
public void canAddTriggerIfNotPresent() {
ChronoGraph graph = this.getGraph();
boolean added1 = graph.getTriggerManager().createTriggerIfNotPresent("foo", DummyTrigger::new);
boolean added2 = graph.getTriggerManager().createTriggerIfNotPresent("foo", DummyTrigger2::new);
assertThat(added1, is(true));
assertThat(added2, is(false));
assertThat(graph.getTriggerManager().existsTrigger("foo"), is(true));
assertThat(graph.getTriggerManager().getTriggerNames(), contains("foo"));
ChronoGraphTriggerManagerInternal triggerManager = (ChronoGraphTriggerManagerInternal) graph.getTriggerManager();
List<Pair<String, ChronoGraphPostCommitTrigger>> triggers = triggerManager.getPostCommitTriggers();
assertThat(triggers.size(), is(1));
Pair<String, ChronoGraphPostCommitTrigger> pair = Iterables.getOnlyElement(triggers);
assertThat(pair, is(notNullValue()));
assertThat(pair.getLeft(), is("foo"));
assertThat(pair.getRight(), is(notNullValue()));
assertThat(pair.getRight(), instanceOf(DummyTrigger.class));
}
@Test
public void triggersArePersistedAndRemainAfterRestart() {
// don't execute this test on the in-memory backend
assumeThat(((ChronoGraphInternal) this.getGraph()).getBackingDB().getFeatures().isPersistent(), is(true));
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new DummyTrigger());
assertThat(graph.getTriggerManager().getTriggerNames(), contains("test"));
ChronoGraph reloadedGraph = this.closeAndReopenGraph();
assertThat(reloadedGraph.getTriggerManager().getTriggerNames(), contains("test"));
ChronoGraphTriggerManagerInternal triggerManager = (ChronoGraphTriggerManagerInternal) reloadedGraph.getTriggerManager();
List<Pair<String, ChronoGraphPostCommitTrigger>> triggers = triggerManager.getPostCommitTriggers();
assertThat(triggers.size(), is(1));
Pair<String, ChronoGraphPostCommitTrigger> onlyTrigger = Iterables.getOnlyElement(triggers);
assertThat(onlyTrigger.getLeft(), is("test"));
assertThat(onlyTrigger.getRight(), is(notNullValue()));
assertThat(onlyTrigger.getRight(), instanceOf(DummyTrigger.class));
}
@Test
public void triggersAreFiredInCorrectTimingOrder() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new CallTrackingTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.tx().commit();
graph.tx().open();
graph.addVertex(T.id, "456");
graph.tx().commit();
ChronoGraphTriggerManagerInternal triggerManager = (ChronoGraphTriggerManagerInternal) graph.getTriggerManager();
List<Pair<String, ChronoGraphPostCommitTrigger>> triggers = triggerManager.getPostCommitTriggers();
assertThat(triggers.size(), is(1));
Pair<String, ChronoGraphPostCommitTrigger> onlyTrigger = Iterables.getOnlyElement(triggers);
assertThat(onlyTrigger.getLeft(), is("test"));
assertThat(onlyTrigger.getRight(), is(notNullValue()));
assertThat(onlyTrigger.getRight(), instanceOf(CallTrackingTrigger.class));
CallTrackingTrigger trackingTrigger = (CallTrackingTrigger) onlyTrigger.getRight();
assertThat(trackingTrigger.getTrackedTimings(), contains(
// commit 1
TriggerTiming.PRE_COMMIT,
TriggerTiming.PRE_PERSIST,
TriggerTiming.POST_PERSIST,
TriggerTiming.POST_COMMIT,
// commit 2
TriggerTiming.PRE_COMMIT,
TriggerTiming.PRE_PERSIST,
TriggerTiming.POST_PERSIST,
TriggerTiming.POST_COMMIT
));
}
@Test
public void txGraphIsModifiableInPreCommitTriggers() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new VertexCountPreCommitTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.addVertex(T.id, "456");
graph.tx().commit();
{ // check the "count" variable
graph.tx().open();
Optional<Object> variable = graph.variables().get("vertexCount");
assertThat(variable, is(notNullValue()));
assertThat(variable.isPresent(), is(true));
assertThat(variable.get(), is(2));
graph.tx().rollback();
}
// do another commit that deletes a vertex
graph.tx().open();
graph.vertices("123").next().remove();
graph.tx().commit();
{ // check the "count" variable one more time
graph.tx().open();
Optional<Object> variable = graph.variables().get("vertexCount");
assertThat(variable, is(notNullValue()));
assertThat(variable.isPresent(), is(true));
assertThat(variable.get(), is(1));
graph.tx().rollback();
}
}
@Test
public void preCommitTriggerSeesUnmergedState() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new VertexCountPreCommitTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.addVertex(T.id, "456");
graph.tx().commit();
{ // check the "count" variable
graph.tx().open();
Optional<Object> variable = graph.variables().get("vertexCount");
assertThat(variable, is(notNullValue()));
assertThat(variable.isPresent(), is(true));
assertThat(variable.get(), is(2));
graph.tx().rollback();
}
// start two transactions: one deletes a vertex, the other one adds two of them.
// the transaction which deletes the vertex commits first...
// ... and the other one should see 4 vertices (the deletion has not yet been merged)
ChronoGraph graphA = graph.tx().createThreadedTx();
ChronoGraph graphB = graph.tx().createThreadedTx();
graphA.vertices("123").next().remove();
graphA.tx().commit();
graphB.addVertex(T.id, "foo");
graphB.addVertex(T.id, "bar");
graphB.tx().commit();
{ // check the "count" variable one more time
graph.tx().open();
Optional<Object> variable = graph.variables().get("vertexCount");
assertThat(variable, is(notNullValue()));
assertThat(variable.isPresent(), is(true));
assertThat(variable.get(), is(4));
graph.tx().rollback();
// check the actual vertex count (which should be 3)
assertThat(Iterators.size(graph.vertices()), is(3));
}
}
@Test
public void prePersistTriggerSeesMergedState() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new VertexCountPrePersistTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.addVertex(T.id, "456");
graph.tx().commit();
{ // check the "count" variable
graph.tx().open();
Optional<Object> variable = graph.variables().get("vertexCount");
assertThat(variable, is(notNullValue()));
assertThat(variable.isPresent(), is(true));
assertThat(variable.get(), is(2));
graph.tx().rollback();
}
// start two transactions: one deletes a vertex, the other one adds two of them.
// the transaction which deletes the vertex commits first...
// ... and the other one should see 3 vertices (the deletion has been merged in PRE_PERSIST)
ChronoGraph graphA = graph.tx().createThreadedTx();
ChronoGraph graphB = graph.tx().createThreadedTx();
graphA.vertices("123").next().remove();
graphA.tx().commit();
graphB.addVertex(T.id, "foo");
graphB.addVertex(T.id, "bar");
graphB.tx().commit();
{ // check the "count" variable one more time
graph.tx().open();
Optional<Object> variable = graph.variables().get("vertexCount");
assertThat(variable, is(notNullValue()));
assertThat(variable.isPresent(), is(true));
assertThat(variable.get(), is(3));
graph.tx().rollback();
// check the actual vertex count
assertThat(Iterators.size(graph.vertices()), is(3));
}
}
@Test
public void postPersistTriggersHaveAccessToTheChangeSet() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test1", new ChangeSetRecordingPostPersistTrigger());
graph.getTriggerManager().createTrigger("test2", new ChangeSetRecordingPostCommitTrigger());
graph.tx().open();
Vertex v123 = graph.addVertex(T.id, "123");
Vertex v456 = graph.addVertex(T.id, "456");
v123.addEdge("test", v456, T.id, "e1");
graph.variables().set("foo", "bar");
graph.tx().commit();
ChronoGraphTriggerManagerInternal triggerManager = (ChronoGraphTriggerManagerInternal) graph.getTriggerManager();
List<Pair<String, ChronoGraphPostPersistTrigger>> postPersistTriggers = triggerManager.getPostPersistTriggers();
assertThat(postPersistTriggers.size(), is(1));
ChronoGraphTrigger trigger1 = Iterables.getOnlyElement(postPersistTriggers).getRight();
assertThat(trigger1, instanceOf(ChangeSetRecordingTrigger.class));
ChangeSetRecordingTrigger csrTrigger1 = (ChangeSetRecordingTrigger) trigger1;
assertThat(csrTrigger1.observedModifiedVertexIds, contains("123", "456"));
assertThat(csrTrigger1.observedModifiedEdgeIds, contains("e1"));
assertThat(csrTrigger1.observedModifiedGraphVariableKeys, contains("foo"));
List<Pair<String, ChronoGraphPostCommitTrigger>> postCommitTriggers = triggerManager.getPostCommitTriggers();
assertThat(postCommitTriggers.size(), is(1));
ChronoGraphTrigger trigger2 = Iterables.getOnlyElement(postCommitTriggers).getRight();
assertThat(trigger2, instanceOf(ChangeSetRecordingTrigger.class));
ChangeSetRecordingTrigger csrTrigger2 = (ChangeSetRecordingTrigger) trigger2;
assertThat(csrTrigger2.observedModifiedVertexIds, contains("123", "456"));
assertThat(csrTrigger2.observedModifiedEdgeIds, contains("e1"));
assertThat(csrTrigger2.observedModifiedGraphVariableKeys, contains("foo"));
}
@Test
public void postPersistTriggersCannotModifyTheTxGraph() {
// note: this test will produce exception stack traces in the log output. This is expected and intentional,
// as ChronoGraph is set up to complain LOUDLY when a change operation is attempted on a read-only graph.
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new VertexCountPostPersistTrigger());
graph.getTriggerManager().createTrigger("test2", new VertexCountPostCommitTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.addVertex(T.id, "456");
graph.tx().commit();
// make sure that the triggers have been unable to create and/or update the target variable
graph.tx().open();
Optional<Object> vertexCount = graph.variables().get("vertexCount");
assertThat(vertexCount.isPresent(), is(false));
// ... but the commit should be successful, so the vertices should be there
Set<String> vertexIds = Sets.newHashSet(graph.vertices()).stream().map(v -> (String) v.id()).collect(Collectors.toSet());
assertThat(vertexIds, containsInAnyOrder("123", "456"));
}
@Test
public void triggerPriorityIsRespected() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test1", new AppendPriorityPreCommitTrigger(100));
graph.getTriggerManager().createTrigger("test2", new AppendPriorityPreCommitTrigger(50));
graph.getTriggerManager().createTrigger("test3", new AppendPriorityPrePersistTrigger(75));
graph.tx().open();
graph.addVertex(T.id, "123");
graph.tx().commit();
graph.tx().open();
Optional<Object> priority = graph.variables().get("priority");
assertThat(priority, is(notNullValue()));
assertThat(priority.isPresent(), is(true));
assertThat(priority.get(), is("100,50,75"));
}
@Test
public void triggersCanWorkOnAPerBranchBasis() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new OnlyMasterBranchTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.tx().commit();
graph.getBranchManager().createBranch("my-branch");
graph.tx().open("my-branch");
graph.addVertex(T.id, "456");
graph.tx().commit();
graph.tx().open();
graph.addVertex(T.id, "456");
graph.tx().commit();
graph.tx().open("my-branch");
assertThat(graph.variables().get("count").get(), is(1));
graph.tx().rollback();
graph.tx().open();
assertThat(graph.variables().get("count").get(), is(2));
graph.tx().rollback();
}
@Test
public void transactionControlIsLockedInTriggers() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new RollbackTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.tx().commit();
graph.tx().open();
assertThat(Sets.newHashSet(graph.vertices()).stream().map(v -> (String) v.id()).collect(Collectors.toSet()), contains("123"));
graph.tx().close();
}
@Test
public void postPersistTriggersCanDetectDeletions() {
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new OnDeleteTrigger());
graph.tx().open();
graph.addVertex(T.id, "123");
graph.addVertex(T.id, "456");
// this creates an obsolete vertex (added and removed within same TX)
graph.addVertex(T.id, "789").remove();
graph.tx().commit();
graph.tx().open();
graph.vertices("123").next().remove();
graph.addVertex("abc");
graph.vertices("456").next().remove();
graph.tx().commit();
ChronoGraphTriggerManagerInternal triggerManager = (ChronoGraphTriggerManagerInternal) graph.getTriggerManager();
List<Pair<String, ChronoGraphPostPersistTrigger>> triggers = triggerManager.getPostPersistTriggers();
assertThat(triggers.size(), is(1));
OnDeleteTrigger trigger = (OnDeleteTrigger) Iterables.getOnlyElement(triggers).getRight();
assertThat(trigger.deletedVertexIds, containsInAnyOrder("123", "456"));
}
@Test
public void canAccessBranchAndTimestampInTrigger(){
ChronoGraph graph = this.getGraph();
AccessBranchAndTimestampTrigger trigger = new AccessBranchAndTimestampTrigger();
graph.getTriggerManager().createTrigger("test", trigger);
graph.tx().open();
graph.addVertex();
graph.tx().commit();
assertThat(trigger.getExceptions(), is(empty()));
}
@Test
public void canAccessPreCommitStateInPostPersistTrigger(){
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new PreCommitStoreStateChecker());
graph.tx().open();
graph.addVertex(T.id, "hello");
graph.tx().commit();
assertThat(PreCommitStoreStateChecker.RECORDED_VERTEX_IDS, is(empty()));
graph.tx().open();
graph.addVertex(T.id, "world");
graph.tx().commit();
assertThat(PreCommitStoreStateChecker.RECORDED_VERTEX_IDS, contains("hello"));
}
@Test
public void canDetectVertexDeletionsInPostPersistTrigger(){
ChronoGraph graph = this.getGraph();
graph.getTriggerManager().createTrigger("test", new PostPersistDeletionFinder());
graph.tx().open();
graph.addVertex(T.id, "hello");
graph.addVertex(T.id, "world");
graph.tx().commit();
assertThat(PostPersistDeletionFinder.DETECTED_DELETIONS, is(empty()));
graph.tx().open();
graph.vertex("hello").remove();
graph.tx().commit();
assertThat(PostPersistDeletionFinder.DETECTED_DELETIONS, contains("hello"));
}
@Test
public void canGetGraphTriggerMetadata(){
ChronoGraph graph = this.getGraph();
ChronoGraphTrigger trigger = new DummyTrigger();
graph.getTriggerManager().createTrigger("dummy", trigger);
GraphTriggerMetadata metadata = graph.getTriggerManager().getTrigger("dummy");
assertThat(metadata.getTriggerClassName(), is(DummyTrigger.class.getName()));
assertThat(metadata.getUserScriptContent(), is(nullValue()));
assertThat(metadata.getTriggerName(), is("dummy"));
assertThat(metadata.getPriority(), is(0));
assertThat(metadata.isPreCommitTrigger(), is(false));
assertThat(metadata.isPrePersistTrigger(), is(false));
assertThat(metadata.isPostPersistTrigger(), is(false));
assertThat(metadata.isPostCommitTrigger(), is(true));
assertThat(metadata.getInstantiationException(), is(nullValue()));
}
// =================================================================================================================
// INNER CLASSES
// =================================================================================================================
public static class DummyTrigger implements ChronoGraphPostCommitTrigger {
public DummyTrigger() {
// default constructor for kryo
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
// does nothing
}
@Override
public int getPriority() {
return 0;
}
}
public static class DummyTrigger2 implements ChronoGraphPostCommitTrigger {
public DummyTrigger2() {
// default constructor for kryo
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
// does nothing
}
@Override
public int getPriority() {
return 0;
}
}
public static class CallTrackingTrigger implements ChronoGraphPreCommitTrigger, ChronoGraphPrePersistTrigger, ChronoGraphPostPersistTrigger, ChronoGraphPostCommitTrigger {
private final List<TriggerTiming> timings = Lists.newArrayList();
public CallTrackingTrigger() {
}
@Override
public void onPreCommit(final PreCommitTriggerContext context) throws CancelCommitException {
this.timings.add(TriggerTiming.PRE_COMMIT);
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
this.timings.add(TriggerTiming.PRE_PERSIST);
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
this.timings.add(TriggerTiming.POST_PERSIST);
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
this.timings.add(TriggerTiming.POST_COMMIT);
}
@Override
public int getPriority() {
return 0;
}
public List<TriggerTiming> getTrackedTimings() {
return Collections.unmodifiableList(this.timings);
}
public void clearTrackedTimings() {
this.timings.clear();
}
}
public static abstract class VertexCountTrigger implements ChronoGraphTrigger {
private Set<TriggerTiming> timings;
protected VertexCountTrigger() {
// default constructor for kryo
}
public void trigger(final TriggerContext context) {
ChronoGraph graph = context.getCurrentState().getGraph();
long count = graph.traversal().V().count().next();
graph.variables().set("vertexCount", (int) count);
}
@Override
public int getPriority() {
return 0;
}
public static class VertexCountPreCommitTrigger extends VertexCountTrigger implements ChronoGraphPreCommitTrigger {
public VertexCountPreCommitTrigger(){
// default constructor for kryo
}
@Override
public void onPreCommit(final PreCommitTriggerContext context) throws CancelCommitException {
this.trigger(context);
}
}
public static class VertexCountPrePersistTrigger extends VertexCountTrigger implements ChronoGraphPrePersistTrigger {
public VertexCountPrePersistTrigger(){
// default constructor for kryo
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
this.trigger(context);
}
}
public static class VertexCountPostPersistTrigger extends VertexCountTrigger implements ChronoGraphPostPersistTrigger {
public VertexCountPostPersistTrigger(){
// default constructor for kryo
}
@Override
public void onPostPersist(final PostPersistTriggerContext context){
this.trigger(context);
}
}
public static class VertexCountPostCommitTrigger extends VertexCountTrigger implements ChronoGraphPostCommitTrigger {
public VertexCountPostCommitTrigger(){
// default constructor for kryo
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
this.trigger(context);
}
}
}
public static abstract class ChangeSetRecordingTrigger implements ChronoGraphTrigger {
private Set<String> observedModifiedVertexIds = null;
private Set<String> observedModifiedEdgeIds = null;
private Set<String> observedModifiedGraphVariableKeys = null;
protected ChangeSetRecordingTrigger() {
// default constructor for kryo
}
public void trigger(final TriggerContext context) {
this.observedModifiedVertexIds = context.getCurrentState().getModifiedVertices().stream().map(ChronoVertex::id).collect(Collectors.toSet());
this.observedModifiedEdgeIds = context.getCurrentState().getModifiedEdges().stream().map(ChronoEdge::id).collect(Collectors.toSet());
this.observedModifiedGraphVariableKeys = Sets.newHashSet(context.getCurrentState().getModifiedGraphVariables());
}
@Override
public int getPriority() {
return 0;
}
public static class ChangeSetRecordingPostPersistTrigger extends ChangeSetRecordingTrigger implements ChronoGraphPostPersistTrigger {
public ChangeSetRecordingPostPersistTrigger(){
// default constructor for kryo
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
super.trigger(context);
}
}
public static class ChangeSetRecordingPostCommitTrigger extends ChangeSetRecordingTrigger implements ChronoGraphPostCommitTrigger {
public ChangeSetRecordingPostCommitTrigger(){
// default constructor for kryo
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
super.trigger(context);
}
}
}
public static abstract class AppendPriorityTrigger implements ChronoGraphTrigger {
private int priority;
protected AppendPriorityTrigger() {
// default constructor for kryo
}
protected AppendPriorityTrigger(int priority) {
this.priority = priority;
}
public void trigger(final TriggerContext context) {
ChronoGraph graph = context.getCurrentState().getGraph();
Optional<Object> priority = graph.variables().get("priority");
if (priority.isPresent()) {
String value = (String) priority.get();
value += "," + this.priority;
graph.variables().set("priority", value);
} else {
graph.variables().set("priority", "" + this.priority);
}
}
@Override
public int getPriority() {
return this.priority;
}
public static class AppendPriorityPreCommitTrigger extends AppendPriorityTrigger implements ChronoGraphPreCommitTrigger{
protected AppendPriorityPreCommitTrigger() {
// default constructor for kryo
}
public AppendPriorityPreCommitTrigger(int priority) {
super(priority);
}
@Override
public void onPreCommit(final PreCommitTriggerContext context) throws CancelCommitException {
this.trigger(context);
}
}
public static class AppendPriorityPrePersistTrigger extends AppendPriorityTrigger implements ChronoGraphPrePersistTrigger{
protected AppendPriorityPrePersistTrigger() {
// default constructor for kryo
}
public AppendPriorityPrePersistTrigger(int priority) {
super(priority);
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
this.trigger(context);
}
}
public static class AppendPriorityPostPersistTrigger extends AppendPriorityTrigger implements ChronoGraphPostPersistTrigger{
protected AppendPriorityPostPersistTrigger() {
// default constructor for kryo
}
public AppendPriorityPostPersistTrigger(int priority) {
super(priority);
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
this.trigger(context);
}
}
public static class AppendPriorityPostCommitTrigger extends AppendPriorityTrigger implements ChronoGraphPostCommitTrigger{
protected AppendPriorityPostCommitTrigger() {
// default constructor for kryo
}
public AppendPriorityPostCommitTrigger(int priority) {
super(priority);
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
this.trigger(context);
}
}
}
public static class OnlyMasterBranchTrigger implements ChronoGraphPrePersistTrigger {
public OnlyMasterBranchTrigger() {
// default constructor for kryo
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
if (context.getBranch().getName().equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER)) {
Variables variables = context.getCurrentState().getGraph().variables();
Optional<Integer> count = variables.get("count");
if (count.isPresent()) {
Integer value = count.get();
variables.set("count", value + 1);
} else {
variables.set("count", 1);
}
}
}
@Override
public int getPriority() {
return 0;
}
}
public static class RollbackTrigger implements ChronoGraphPrePersistTrigger {
public RollbackTrigger() {
// default constructor for kryo
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
// attempt a rollback (which is prohibited in triggers)
context.getCurrentState().getGraph().tx().rollback();
}
@Override
public int getPriority() {
return 0;
}
}
public static class OnDeleteTrigger implements ChronoGraphPostPersistTrigger {
private Set<String> deletedVertexIds = Sets.newHashSet();
public OnDeleteTrigger() {
// default constructor for kryo
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
Set<ChronoVertex> modifiedVertices = context.getCurrentState().getModifiedVertices();
this.deletedVertexIds.addAll(modifiedVertices.stream().filter(ChronoVertex::isRemoved).filter(v -> v.getStatus() != ElementLifecycleStatus.OBSOLETE).map(ChronoVertex::id).collect(Collectors.toSet()));
}
@Override
public int getPriority() {
return 0;
}
}
public static class FakeTrigger implements ChronoGraphTrigger{
public FakeTrigger(){
}
@Override
public int getPriority() {
return 0;
}
}
public static class AccessBranchAndTimestampTrigger implements ChronoGraphPreCommitTrigger, ChronoGraphPrePersistTrigger, ChronoGraphPostPersistTrigger, ChronoGraphPostCommitTrigger {
private final List<Exception> exceptions = Lists.newArrayList();
public AccessBranchAndTimestampTrigger(){
// default constructor for kryo
}
private void accessBranchAndTimestamp(TriggerContext ctx){
try{
ctx.getCurrentState().getBranch();
ctx.getCurrentState().getTimestamp();
ctx.getAncestorState().getBranch();
ctx.getAncestorState().getTimestamp();
ctx.getStoreState().getBranch();
ctx.getStoreState().getTimestamp();
}catch(Exception e){
this.exceptions.add(e);
}
}
@Override
public void onPreCommit(final PreCommitTriggerContext context) throws CancelCommitException {
this.accessBranchAndTimestamp(context);
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
this.accessBranchAndTimestamp(context);
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
this.accessBranchAndTimestamp(context);
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
this.accessBranchAndTimestamp(context);
}
@Override
public int getPriority() {
return 0;
}
public List<Exception> getExceptions() {
return exceptions;
}
}
public static class PreCommitStoreStateChecker implements ChronoGraphPostPersistTrigger {
public static List<String> RECORDED_VERTEX_IDS = Lists.newArrayList();
public PreCommitStoreStateChecker(){
// default constructor for kryo
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
RECORDED_VERTEX_IDS.clear();
ChronoGraph preCommitStoreState = context.getPreCommitStoreState().getGraph();
List<Vertex> preCommitVertices = Lists.newArrayList(preCommitStoreState.vertices());
preCommitVertices.forEach(v -> RECORDED_VERTEX_IDS.add((String) v.id()));
}
@Override
public int getPriority() {
return 0;
}
}
public static class PostPersistDeletionFinder implements ChronoGraphPostPersistTrigger {
public static List<String> DETECTED_DELETIONS = Lists.newArrayList();
public PostPersistDeletionFinder(){
// default constructor for kryo
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
DETECTED_DELETIONS.clear();
ChronoGraph preCommitGraph = context.getPreCommitStoreState().getGraph();
List<String> detectedVertexDeletions = context.getCurrentState().getModifiedVertices().stream()
// find the vertices which were removed by this transaction
.filter(ChronoVertex::isRemoved)
.map(ChronoVertex::id)
// fetch them from the previous graph state
// (imagine we wanted to access some property, which we can't do in
// our current state since the vertex is removed)
.map(preCommitGraph::vertex)
.filter(Objects::nonNull)
// for illustration purposes, just fetch the ID again
.map(Vertex::id).map(Object::toString)
.collect(Collectors.toList());
DETECTED_DELETIONS.addAll(detectedVertexDeletions);
}
@Override
public int getPriority() {
return 0;
}
}
}
| 40,196 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphConflictMergeUtilsTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/conflict/GraphConflictMergeUtilsTest.java | package org.chronos.chronograph.test.cases.transaction.conflict;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.ChronoDB;
import org.chronos.chronodb.inmemory.InMemoryChronoDB;
import org.chronos.chronograph.api.exceptions.ChronoGraphCommitConflictException;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflictResolutionStrategy;
import org.chronos.chronograph.internal.impl.transaction.merge.GraphConflictMergeUtils;
import org.chronos.chronograph.test.base.ChronoGraphUnitTest;
import org.chronos.common.test.junit.categories.UnitTest;
import org.junit.After;
import org.junit.Before;
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 GraphConflictMergeUtilsTest extends ChronoGraphUnitTest {
// =================================================================================================================
// ENVIRONMENT
// We use an in-memory graph here because we don't want to test the actual graph itself, but only the static
// helper methods in GraphConflictMergeUtils. To do so, we require TinkerPop-compliant instances of Vertex etc.,
// and we only use the in-memory graph to provide those.
// =================================================================================================================
private ChronoGraph g;
@Override
@Before
public void setup() {
super.setup();
this.g = ChronoGraph.FACTORY.create().graphOnChronoDB(
ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER)
).build();
}
@Override
@After
public void tearDown() {
super.tearDown();
this.g.close();
}
// =================================================================================================================
// TESTS
// =================================================================================================================
@Test
public void canAutoMergeNonConflictingCase() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
vertex.property("hello", "world");
storeVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, null, strategy);
assertThat(vertex.property("hello").isPresent(), is(true));
assertThat(vertex.value("hello"), is("world"));
}
@Test
public void canAutoMergePropertyChangeInTransaction() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
vertex.property("hello", "foo");
storeVertex.property("hello", "world");
ancestorVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(true));
assertThat(vertex.value("hello"), is("foo"));
}
@Test
public void canAutoMergePropertyChangeInStore() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
vertex.property("hello", "world");
storeVertex.property("hello", "foo");
ancestorVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(true));
assertThat(vertex.value("hello"), is("foo"));
}
@Test
public void canAutoMergePropertyAddedInTransaction() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
vertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(true));
assertThat(vertex.value("hello"), is("world"));
}
@Test
public void canAutoMergePropertyAddedInStore() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
storeVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(true));
assertThat(vertex.value("hello"), is("world"));
}
@Test
public void canAutoMergePropertyRemovedInTransaction() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
storeVertex.property("hello", "world");
ancestorVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(false));
}
@Test
public void canAutoMergePropertyRemovedInStore() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
vertex.property("hello", "world");
ancestorVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(false));
}
@Test
public void overwriteWithTransactionValueWorks() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
vertex.property("hello", "bar");
storeVertex.property("hello", "foo");
ancestorVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.OVERWRITE_WITH_TRANSACTION_VALUE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(true));
assertThat(vertex.value("hello"), is("bar"));
}
@Test
public void overwriteWithStoreValueWorks() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
vertex.property("hello", "bar");
storeVertex.property("hello", "foo");
ancestorVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.OVERWRITE_WITH_STORE_VALUE;
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
assertThat(vertex.property("hello").isPresent(), is(true));
assertThat(vertex.value("hello"), is("foo"));
}
@Test
public void doNotMergeWorks() {
Vertex vertex = this.g.addVertex();
Vertex storeVertex = this.g.addVertex();
Vertex ancestorVertex = this.g.addVertex();
vertex.property("hello", "bar");
storeVertex.property("hello", "foo");
ancestorVertex.property("hello", "world");
PropertyConflictResolutionStrategy strategy = PropertyConflictResolutionStrategy.DO_NOT_MERGE;
try {
GraphConflictMergeUtils.mergeProperties(vertex, storeVertex, ancestorVertex, strategy);
fail("Failed to trigger commit conflict exception!");
} catch (ChronoGraphCommitConflictException expected) {
// pass
}
}
}
| 8,499 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphTransactionConflictTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/transaction/conflict/GraphTransactionConflictTest.java | package org.chronos.chronograph.test.cases.transaction.conflict;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Iterator;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GraphTransactionConflictTest extends AllChronoGraphBackendsTest {
@Test
public void canMergeNewVertices() {
ChronoGraph g = this.getGraph();
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
g1.addVertex("name", "John");
g1.tx().commit();
g2.addVertex("name", "Jane");
g2.tx().commit();
Set<Vertex> vertices = Sets.newHashSet(g.vertices());
assertThat(vertices.size(), is(2));
Vertex vJohn = vertices.stream().filter(v -> v.value("name").equals("John")).findFirst().orElse(null);
Vertex vJane = vertices.stream().filter(v -> v.value("name").equals("Jane")).findFirst().orElse(null);
assertNotNull(vJohn);
assertNotNull(vJane);
}
@Test
public void canMergeAdditionalEdgesFromStore() {
ChronoGraph g = this.getGraph();
g.addVertex("name", "John");
g.tx().commit();
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
{ // transaction 1
Vertex vJane = g1.addVertex("name", "Jane");
Vertex vJohn = g1.traversal().V().has("name", "John").next();
assertNotNull(vJohn);
vJohn.addEdge("marriedTo", vJane);
g1.tx().commit();
}
{ // transaction 2
Vertex vJack = g2.addVertex("name", "Jack");
Vertex vJohn = g2.traversal().V().has("name", "John").next();
assertNotNull(vJohn);
vJohn.addEdge("friend", vJack);
g2.tx().commit();
}
// now we should have BOTH Jane and Jack in the graph
Vertex vJohn = g.traversal().V().has("name", "John").next();
assertNotNull(vJohn);
assertThat(Iterators.size(vJohn.edges(Direction.OUT)), is(2));
Vertex vJack = Iterators.getOnlyElement(vJohn.vertices(Direction.OUT, "friend"));
assertThat(vJack.value("name"), is("Jack"));
Vertex vJane = Iterators.getOnlyElement(vJohn.vertices(Direction.OUT, "marriedTo"));
assertThat(vJane.value("name"), is("Jane"));
}
@Test
public void canMergeRemovedEdgesFromStore() {
ChronoGraph g = this.getGraph();
{ // initial commit
Vertex vJohn = g.addVertex("name", "John");
Vertex vJane = g.addVertex("name", "Jane");
vJohn.addEdge("marriedTo", vJane);
g.tx().commit();
}
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
{ // transaction 1
Edge edge = g1.traversal().E().hasLabel("marriedTo").next();
edge.remove();
g1.tx().commit();
}
{ // transaction 2
Vertex vJohn = g2.traversal().V().has("name", "John").next();
Vertex vJack = g2.addVertex("name", "Jack");
vJohn.addEdge("knows", vJack);
g2.tx().commit();
}
// the "marriedTo" edge should be gone
Edge marriedToEdge = Iterators.getOnlyElement(g.traversal().E().hasLabel("marriedTo"), null);
assertNull(marriedToEdge);
// the "marriedTo" edge should no longer be listed in vJohn or vJane
Vertex vJohn = g.traversal().V().has("name", "John").next();
Vertex vJane = g.traversal().V().has("name", "Jane").next();
assertThat(vJohn.vertices(Direction.OUT, "marriedTo").hasNext(), is(false));
assertThat(vJohn.edges(Direction.OUT, "marriedTo").hasNext(), is(false));
assertThat(vJane.vertices(Direction.IN, "marriedTo").hasNext(), is(false));
assertThat(vJane.edges(Direction.IN, "marriedTo").hasNext(), is(false));
// the "knows" edge should exist
Vertex vJack = Iterators.getOnlyElement(g.traversal().V().has("name", "Jack"));
assertThat(Iterators.getOnlyElement(vJohn.vertices(Direction.OUT, "knows")), is(vJack));
assertThat(Iterators.getOnlyElement(vJohn.edges(Direction.OUT, "knows")).inVertex(), is(vJack));
}
@Test
public void canMergeEdgeProperties() {
ChronoGraph g = this.getGraph();
{ // initial commit
Vertex vJohn = g.addVertex("name", "John");
Vertex vJane = g.addVertex("name", "Jane");
vJohn.addEdge("marriedTo", vJane);
g.tx().commit();
}
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
{ // transaction 1
Edge edge = g1.traversal().E().next();
edge.property("since", 2003);
edge.property("foo", "bar");
g1.tx().commit();
}
{ // transaction 2
Edge edge = g2.traversal().E().next();
edge.property("foo", "baz");
edge.property("hello", "world");
g2.tx().commit();
}
// now, the edge should have the following property values
Edge edge = g.traversal().E().next();
assertThat(edge.value("foo"), is("baz"));
assertThat(edge.value("hello"), is("world"));
assertThat(edge.value("since"), is(2003));
}
@Test
public void canMergeVertexProperties() {
ChronoGraph g = this.getGraph();
{ // initial commit
g.addVertex("name", "John");
g.tx().commit();
}
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
{ // transaction 1
Vertex vJohn = g1.traversal().V().has("name", "John").next();
vJohn.property("age", 51);
vJohn.property("hello", "world");
g1.tx().commit();
}
{ // transaction 2
Vertex vJohn = g2.traversal().V().has("name", "John").next();
vJohn.property("hello", "foo");
vJohn.property("test", "me");
g2.tx().commit();
}
// now the vertex should have the following property values
Vertex vertex = g.traversal().V().next();
assertThat(vertex.value("age"), is(51));
assertThat(vertex.value("hello"), is("foo"));
assertThat(vertex.value("test"), is("me"));
}
@Test
public void updatesOnExistingVertexAreIgnoredIfVertexWasDeleted() {
ChronoGraph g = this.getGraph();
{ // initial commit
g.addVertex("name", "John");
g.tx().commit();
}
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
{ // transaction 1
Vertex vJohn = g1.traversal().V().has("name", "John").next();
vJohn.remove();
g1.tx().commit();
}
{ // transaction 2
Vertex vJohn = g2.traversal().V().has("name", "John").next();
vJohn.property("hello", "world");
g2.tx().commit();
}
// now the vertex should be gone, and the second update should have been discarded.
Iterator<Vertex> iterator = g.traversal().V().has("name", "John");
assertThat(iterator.hasNext(), is(false));
}
@Test
public void updatesOnExistingEdgesAreIgnoredIfEdgeWasDeleted() {
ChronoGraph g = this.getGraph();
{ // initial commit
Vertex vJohn = g.addVertex("name", "John");
Vertex vJane = g.addVertex("name", "Jane");
vJohn.addEdge("marriedTo", vJane);
g.tx().commit();
}
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
{ // transaction 1
Edge edge = g1.traversal().E().next();
edge.remove();
g1.tx().commit();
}
{ // transaction 2
Edge edge = g2.traversal().E().next();
edge.property("hello", "world");
g2.tx().commit();
}
// now, the edge should have the following property values
Iterator<Edge> iterator = g.traversal().E();
assertThat(iterator.hasNext(), is(false));
}
@Test
public void canMergeConflictingGraphVariables() {
ChronoGraph g = this.getGraph();
{ // initial commit
g.variables().set("hello", "world");
g.variables().set("foo", "bar");
g.tx().commit();
}
ChronoGraph g1 = g.tx().createThreadedTx();
ChronoGraph g2 = g.tx().createThreadedTx();
g1.variables().set("hello", "john");
g1.variables().remove("foo");
g1.variables().set("john", "doe");
g1.tx().commit();
g2.variables().set("hello", "jack");
g2.variables().set("foo", "baz");
g2.variables().set("jane", "doe");
g2.tx().commit();
assertThat(g.variables().get("hello").orElse(null), is("jack"));
assertThat(g.variables().get("foo").orElse(null), is("baz"));
assertThat(g.variables().get("john").orElse(null), is("doe"));
assertThat(g.variables().get("jane").orElse(null), is("doe"));
}
}
| 9,796 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphBuilderTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/builder/GraphBuilderTest.java | package org.chronos.chronograph.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.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.test.base.ChronoGraphUnitTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Properties;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GraphBuilderTest extends ChronoGraphUnitTest {
@Test
public void canCreateGraphOnInMemoryChronoDB(){
ChronoGraphInternal graph = (ChronoGraphInternal) ChronoGraph.FACTORY.create()
.graphOnChronoDB(
ChronoDB.FACTORY.create()
.database(InMemoryChronoDB.BUILDER)
.withLruCacheOfSize(1000)
).withTransactionAutoStart(false).build();
try{
assertThat(graph, is(notNullValue()));
assertThat(graph.getChronoGraphConfiguration().isTransactionAutoOpenEnabled(), is(false));
assertThat(graph.getBackingDB().getConfiguration().isAssumeCachedValuesAreImmutable(), is(true));
assertThat(graph.getBackingDB().getConfiguration().isCachingEnabled(), is(true));
assertThat(graph.getBackingDB().getConfiguration().getCacheMaxSize(), is(1000));
assertThat(graph.getBackingDB().getConfiguration().getBackendType(), is("inmemory"));
}finally{
graph.close();
}
}
@Test
public void canCreateGraphOnProperties(){
Properties properties = new Properties();
properties.put(ChronoDBConfiguration.STORAGE_BACKEND, "inmemory");
properties.put(ChronoDBConfiguration.CACHING_ENABLED, "true");
properties.put(ChronoDBConfiguration.CACHE_MAX_SIZE, "1000");
// note: this is overridden by ChronoGraph default properties.
properties.put(ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, "false");
ChronoGraphInternal graph = (ChronoGraphInternal)ChronoGraph.FACTORY.create()
.fromProperties(properties)
.withTransactionAutoStart(false).build();
try{
assertThat(graph, is(notNullValue()));
assertThat(graph.getBackingDB().getConfiguration().isAssumeCachedValuesAreImmutable(), is(true));
assertThat(graph.getBackingDB().getConfiguration().isAssumeCachedValuesAreImmutable(), is(true));
assertThat(graph.getBackingDB().getConfiguration().isCachingEnabled(), is(true));
assertThat(graph.getBackingDB().getConfiguration().getCacheMaxSize(), is(1000));
assertThat(graph.getBackingDB().getConfiguration().getBackendType(), is("inmemory"));
}finally{
graph.close();
}
}
}
| 3,047 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphCreationTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/builder/ChronoGraphCreationTest.java | package org.chronos.chronograph.test.cases.builder;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 ChronoGraphCreationTest extends AllChronoGraphBackendsTest {
@Test
public void graphCreationWorks() {
ChronoGraph graph = this.getGraph();
assertNotNull("Failed to instantiate ChronoGraph on Backend '" + this.getChronoBackendName() + "'!", graph);
}
}
| 683 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
FetchElementsByIdTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/id/FetchElementsByIdTest.java | package org.chronos.chronograph.test.cases.id;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Iterator;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class FetchElementsByIdTest extends AllChronoGraphBackendsTest {
@Test
public void fetchingUnknownVertexIdReturnsEmptyIterator() {
ChronoGraph graph = this.getGraph();
Iterator<Vertex> vertices = graph.vertices("fake");
assertFalse(vertices.hasNext());
}
@Test
public void fetchingUnknownEdgeIdReturnsEmptyIterator() {
ChronoGraph graph = this.getGraph();
Iterator<Edge> edges = graph.edges("fake");
assertFalse(edges.hasNext());
}
}
| 1,035 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
IdsUniqueTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/id/IdsUniqueTest.java | package org.chronos.chronograph.test.cases.id;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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 IdsUniqueTest extends AllChronoGraphBackendsTest {
@Test
public void shouldHaveExceptionConsistencyWhenAssigningSameIdOnEdge() {
final Vertex v = this.getGraph().addVertex();
final Object o = "1";
v.addEdge("self", v, T.id, o);
try {
v.addEdge("self", v, T.id, o);
fail("Assigning the same ID to an Element should throw an exception");
} catch (IllegalArgumentException expected) {
// pass
}
}
}
| 935 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinPerformanceTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/gremlin/GremlinPerformanceTest.java | package org.chronos.chronograph.test.cases.gremlin;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.PerformanceTest;
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(PerformanceTest.class)
public class GremlinPerformanceTest extends AllChronoGraphBackendsTest {
@Test
public void canExecuteParallelVertexCounts() {
ChronoGraph graph = this.getGraph();
int vertexCount = 100_000;
{ // insert test data
graph.tx().open();
for (int i = 0; i < vertexCount; i++) {
graph.addVertex(T.id, String.valueOf(i));
}
graph.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 {
graph.tx().open();
long count = graph.traversal().V().count().next();
assertEquals(vertexCount, count);
graph.tx().close();
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);
}
}
assertEquals(0, exceptions.size());
assertEquals(threadCount, successfullyTerminatedThreads.size());
}
}
| 2,453 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinContainmentQueryTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/gremlin/GremlinContainmentQueryTest.java | package org.chronos.chronograph.test.cases.gremlin;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GremlinContainmentQueryTest extends AllChronoGraphBackendsTest {
@Test
public void canPerformWithinQueryWithInStringsClause() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "name", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "name", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "name", "Jack", "lastname", "Smith");
g.addVertex(T.id, "5", "name", "John", "lastname", "Smith");
this.assertCommitAssert(() -> {
Set<Object> johnAndJaneIds = g.traversal().V()
.has("name", P.within("John", "Jane"))
.id()
.toSet();
assertThat(johnAndJaneIds, containsInAnyOrder("1", "2", "5"));
});
}
@Test
public void canPerformWithinQueryWithManyInStringsClause() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "name", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "name", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "name", "Jack", "lastname", "Smith");
g.addVertex(T.id, "5", "name", "John", "lastname", "Smith");
this.assertCommitAssert(() -> {
Set<Object> johnAndJaneIds = g.traversal().V()
.has("name", P.within("John", "Jane", "hello", "wold", "foo", "bar", "baz"))
.id()
.toSet();
assertThat(johnAndJaneIds, containsInAnyOrder("1", "2", "5"));
});
}
@Test
public void canPerformWithinQueryWithInLongsClause() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15);
g.addVertex(T.id, "2", "name", "Bob", "age", 23);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58);
this.assertCommitAssert(() -> {
Set<Object> alCeEmIds = g.traversal().V()
.has("age", P.within(15, 58))
.id()
.toSet();
assertThat(alCeEmIds, containsInAnyOrder("1", "3", "5"));
});
}
@Test
public void canPerformWithinQueryWithManyInLongsClause() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15);
g.addVertex(T.id, "2", "name", "Bob", "age", 23);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58);
this.assertCommitAssert(() -> {
Set<Object> alCeEmIds = g.traversal().V()
.has("age", P.within(15, 58, 122, 343432, 32423, 34354, 12231))
.id()
.toSet();
assertThat(alCeEmIds, containsInAnyOrder("1", "3", "5"));
});
}
@Test
public void canPerformWithinQueryWithInDoublesClause() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15.3);
g.addVertex(T.id, "2", "name", "Bob", "age", 23.5);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58.7);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35.9);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58.1);
this.assertCommitAssert(() -> {
Set<Object> aliceAndCeasarIds = g.traversal().V()
.has("age", P.within(15.3, 58.7))
.id()
.toSet();
assertThat(aliceAndCeasarIds, containsInAnyOrder("1", "3"));
});
}
@Test
public void canPerformWithinQueryWithManyInDoublesClause() {
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15.3);
g.addVertex(T.id, "2", "name", "Bob", "age", 23.5);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58.7);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35.9);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58.1);
this.assertCommitAssert(() -> {
Set<Object> aliceAndCeasarIds = g.traversal().V()
.has("age", P.within(15.3, 58.7, 43534.2343, 4545.2234, 56.33324, 5652.334))
.id()
.toSet();
assertThat(aliceAndCeasarIds, containsInAnyOrder("1", "3"));
});
}
@Test
public void canPerformWithoutQueryWithInStringsClause(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "name", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "name", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "name", "Jack", "lastname", "Smith");
g.addVertex(T.id, "5", "name", "John", "lastname", "Smith");
this.assertCommitAssert(()->{
Set<Object> notJohnAndJaneIds = g.traversal().V()
.has("name", P.without("John", "Jane"))
.id()
.toSet();
assertThat(notJohnAndJaneIds, containsInAnyOrder("3", "4"));
});
}
@Test
public void canPerformWithoutQueryWithManyInStringsClause(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "name", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "name", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "name", "Jack", "lastname", "Smith");
g.addVertex(T.id, "5", "name", "John", "lastname", "Smith");
this.assertCommitAssert(()->{
Set<Object> notJohnAndJaneIds = g.traversal().V()
.has("name", P.without("John", "Jane", "foo", "bar", "baz", "hello"))
.id()
.toSet();
assertThat(notJohnAndJaneIds, containsInAnyOrder("3", "4"));
});
}
@Test
public void canPerformWithoutQueryWithInLongsClause(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15);
g.addVertex(T.id, "2", "name", "Bob", "age", 23);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58);
this.assertCommitAssert(()->{
Set<Object> bobAndDorianIds = g.traversal().V()
.has("age", P.without(15, 58))
.id()
.toSet();
assertThat(bobAndDorianIds, containsInAnyOrder("2", "4"));
});
}
@Test
public void canPerformWithoutQueryWithManyInLongsClause(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().longIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15);
g.addVertex(T.id, "2", "name", "Bob", "age", 23);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58);
this.assertCommitAssert(()->{
Set<Object> bobAndDorianIds = g.traversal().V()
.has("age", P.without(15, 58, 123, 456, 789, 222))
.id()
.toSet();
assertThat(bobAndDorianIds, containsInAnyOrder("2", "4"));
});
}
@Test
public void canPerformWithoutQueryWithInDoublesClause(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15.3);
g.addVertex(T.id, "2", "name", "Bob", "age", 23.5);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58.7);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35.9);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58.1);
this.assertCommitAssert(()->{
Set<Object> notAliceAndCeasarIds = g.traversal().V()
.has("age", P.without(15.3, 58.7))
.id()
.toSet();
assertThat(notAliceAndCeasarIds, containsInAnyOrder("2", "4", "5"));
});
}
@Test
public void canPerformWithoutQueryWithManyInDoublesClause(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().doubleIndex().onVertexProperty("age").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "name", "Alice", "age", 15.3);
g.addVertex(T.id, "2", "name", "Bob", "age", 23.5);
g.addVertex(T.id, "3", "name", "Ceasar", "age", 58.7);
g.addVertex(T.id, "4", "name", "Dorian", "age", 35.9);
g.addVertex(T.id, "5", "name", "Emilia", "age", 58.1);
this.assertCommitAssert(()->{
Set<Object> notAliceAndCeasarIds = g.traversal().V()
.has("age", P.without(15.3, 58.7, 3.1415, 423.3423, 34.3456, 66.743))
.id()
.toSet();
assertThat(notAliceAndCeasarIds, containsInAnyOrder("2", "4", "5"));
});
}
}
| 11,486 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/gremlin/GremlinTest.java | package org.chronos.chronograph.test.cases.gremlin;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.api.builder.query.CP;
import org.chronos.chronograph.api.index.ChronoGraphIndexManager;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import java.util.Set;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class GremlinTest extends AllChronoGraphBackendsTest {
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.PERFORMANCE_LOGGING_FOR_COMMITS, value = "true")
public void basicVertexRetrievalWorks() {
ChronoGraph graph = this.getGraph();
graph.addVertex("name", "Martin", "age", 26);
graph.addVertex("name", "Martin", "age", 10);
graph.addVertex("name", "John", "age", 26);
graph.tx().commit();
Set<Vertex> vertices = graph.traversal().V().has("name", "Martin").has("age", 26).toSet();
assertEquals(1, vertices.size());
Vertex vertex = Iterables.getOnlyElement(vertices);
assertEquals("Martin", vertex.value("name"));
assertEquals(26, (int) vertex.value("age"));
}
@Test
public void basicEgdeRetrievalWorks() {
ChronoGraph graph = this.getGraph();
Vertex me = graph.addVertex("kind", "person", "name", "Martin");
Vertex chronos = graph.addVertex("kind", "project", "name", "Chronos");
Vertex otherProject = graph.addVertex("kind", "project", "name", "Other Project");
me.addEdge("worksOn", chronos, "since", "2015-07-30");
me.addEdge("worksOn", otherProject, "since", "2000-01-01");
graph.tx().commit();
Set<Edge> edges = graph.traversal().E().has("since", "2015-07-30").toSet();
assertEquals(1, edges.size());
}
@Test
public void gremlinNavigationWorks() {
ChronoGraph graph = this.getGraph();
Vertex me = graph.addVertex("kind", "person", "name", "Martin");
Vertex chronos = graph.addVertex("kind", "project", "name", "Chronos");
Vertex otherProject = graph.addVertex("kind", "project", "name", "Other Project");
me.addEdge("worksOn", chronos);
me.addEdge("worksOn", otherProject);
graph.tx().commit();
Set<Vertex> vertices = graph.traversal().V().has("kind", "person").has("name", "Martin").out("worksOn")
.has("name", "Chronos").toSet();
assertEquals(1, vertices.size());
Vertex vertex = Iterables.getOnlyElement(vertices);
assertEquals("Chronos", vertex.value("name"));
assertEquals("project", vertex.value("kind"));
}
@Test
public void multipleHasClausesWorksOnIndexedVertexProperty() {
ChronoGraph graph = this.getGraph();
ChronoGraphIndexManager indexManager = graph.getIndexManagerOnMaster();
indexManager.create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
indexManager.create().stringIndex().onVertexProperty("kind").acrossAllTimestamps().build();
indexManager.reindexAll();
Vertex vExpected = graph.addVertex("kind", "person", "name", "Martin");
graph.addVertex("kind", "person", "name", "Thomas");
graph.addVertex("kind", "project", "name", "Chronos");
graph.addVertex("kind", "project", "name", "Martin");
// multiple HAS clauses need to be AND-connected.
Set<Vertex> result = graph.traversal().V().has("name", "Martin").has("kind", "person").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(vExpected));
graph.tx().commit();
result = graph.traversal().V().has("name", "Martin").has("kind", "person").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(vExpected));
}
@Test
public void multipleHasClausesWorksOnNonIndexedVertexProperty() {
ChronoGraph graph = this.getGraph();
Vertex vExpected = graph.addVertex("kind", "person", "name", "Martin");
graph.addVertex("kind", "person", "name", "Thomas");
graph.addVertex("kind", "project", "name", "Chronos");
graph.addVertex("kind", "project", "name", "Martin");
// multiple HAS clauses need to be AND-connected.
Set<Vertex> result = graph.traversal().V().has("name", "Martin").has("kind", "person").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(vExpected));
graph.tx().commit();
result = graph.traversal().V().has("name", "Martin").has("kind", "person").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(vExpected));
}
@Test
public void multipleHasClausesWorksOnMixedIndexedVertexProperty() {
ChronoGraph graph = this.getGraph();
ChronoGraphIndexManager indexManager = graph.getIndexManagerOnMaster();
// do not index 'name', but index 'kind'
indexManager.create().stringIndex().onVertexProperty("kind").acrossAllTimestamps().build();
indexManager.reindexAll();
Vertex vExpected = graph.addVertex("kind", "person", "name", "Martin");
graph.addVertex("kind", "person", "name", "Thomas");
graph.addVertex("kind", "project", "name", "Chronos");
graph.addVertex("kind", "project", "name", "Martin");
// multiple HAS clauses need to be AND-connected.
Set<Vertex> result = graph.traversal().V().has("name", "Martin").has("kind", "person").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(vExpected));
graph.tx().commit();
result = graph.traversal().V().has("name", "Martin").has("kind", "person").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(vExpected));
}
@Test
public void multipleHasClausesWorksOnIndexedEdgeProperty() {
ChronoGraph graph = this.getGraph();
ChronoGraphIndexManager indexManager = graph.getIndexManagerOnMaster();
indexManager.create().stringIndex().onEdgeProperty("a").acrossAllTimestamps().build();
indexManager.create().stringIndex().onEdgeProperty("b").acrossAllTimestamps().build();
indexManager.reindexAll();
Vertex v1 = graph.addVertex();
Vertex v2 = graph.addVertex();
Edge eExpected = v1.addEdge("test1", v2, "a", "yes", "b", "true");
v1.addEdge("test2", v2, "a", "no", "b", "true");
v1.addEdge("test3", v2, "a", "yes", "b", "false");
v1.addEdge("test4", v2, "a", "no", "b", "false");
// multiple HAS clauses need to be AND-connected.
Set<Edge> result = graph.traversal().E().has("a", "yes").has("b", "true").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(eExpected));
graph.tx().commit();
result = graph.traversal().E().has("a", "yes").has("b", "true").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(eExpected));
}
@Test
public void multipleHasClausesWorksOnMixedEdgeProperty() {
ChronoGraph graph = this.getGraph();
ChronoGraphIndexManager indexManager = graph.getIndexManagerOnMaster();
// do not index 'a', but index 'b'
indexManager.create().stringIndex().onEdgeProperty("b").acrossAllTimestamps().build();
indexManager.reindexAll();
Vertex v1 = graph.addVertex();
Vertex v2 = graph.addVertex();
Edge eExpected = v1.addEdge("test1", v2, "a", "yes", "b", "true");
v1.addEdge("test2", v2, "a", "no", "b", "true");
v1.addEdge("test3", v2, "a", "yes", "b", "false");
v1.addEdge("test4", v2, "a", "no", "b", "false");
// multiple HAS clauses need to be AND-connected.
Set<Edge> result = graph.traversal().E().has("a", "yes").has("b", "true").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(eExpected));
graph.tx().commit();
result = graph.traversal().E().has("a", "yes").has("b", "true").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(eExpected));
}
@Test
public void multipleHasClausesWorksOnNonIndexedEdgeProperty() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex();
Vertex v2 = graph.addVertex();
Edge eExpected = v1.addEdge("test1", v2, "a", "yes", "b", "true");
v1.addEdge("test2", v2, "a", "no", "b", "true");
v1.addEdge("test3", v2, "a", "yes", "b", "false");
v1.addEdge("test4", v2, "a", "no", "b", "false");
// multiple HAS clauses need to be AND-connected.
Set<Edge> result = graph.traversal().E().has("a", "yes").has("b", "true").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(eExpected));
graph.tx().commit();
result = graph.traversal().E().has("a", "yes").has("b", "true").toSet();
assertEquals(1, result.size());
assertTrue(result.contains(eExpected));
}
@Test
@SuppressWarnings("unchecked")
public void usingSubqueriesWorks() {
ChronoGraph graph = this.getGraph();
Vertex vMother = graph.addVertex("name", "Eva");
Vertex vFather = graph.addVertex("name", "Adam");
Vertex vSon1 = graph.addVertex("name", "Kain");
Vertex vSon2 = graph.addVertex("name", "Abel");
Vertex vDaughter = graph.addVertex("name", "Sarah");
vMother.addEdge("married", vFather);
vFather.addEdge("married", vMother);
vMother.addEdge("son", vSon1);
vMother.addEdge("son", vSon2);
vMother.addEdge("daughter", vDaughter);
vFather.addEdge("son", vSon1);
vFather.addEdge("son", vSon2);
vFather.addEdge("daughter", vDaughter);
Set<Vertex> vertices = graph.traversal().V(vMother).union(__.out("son"), __.out("daughter")).toSet();
assertEquals(Sets.newHashSet(vSon1, vSon2, vDaughter), vertices);
}
@Test
public void canExecuteGraphEHasLabel() {
ChronoGraph graph = this.getGraph();
Vertex v1 = graph.addVertex();
Vertex v2 = graph.addVertex();
Vertex v3 = graph.addVertex();
v1.addEdge("forward", v2);
v2.addEdge("forward", v3);
v3.addEdge("forward", v1);
v1.addEdge("backward", v3);
v2.addEdge("backward", v2);
v3.addEdge("backward", v2);
assertEquals(3, Iterators.size(graph.traversal().E().hasLabel("forward")));
assertEquals(3, Iterators.size(graph.traversal().E().hasLabel("backward")));
graph.tx().commit();
assertEquals(3, Iterators.size(graph.traversal().E().hasLabel("forward")));
assertEquals(3, Iterators.size(graph.traversal().E().hasLabel("backward")));
}
@Test
public void canExecuteGraphVHasLabel() {
ChronoGraph graph = this.getGraph();
graph.addVertex(T.label, "Person");
graph.addVertex(T.label, "Person");
graph.addVertex(T.label, "Location");
assertEquals(2, Iterators.size(graph.traversal().V().hasLabel("Person")));
assertEquals(1, Iterators.size(graph.traversal().V().hasLabel("Location")));
graph.tx().commit();
assertEquals(2, Iterators.size(graph.traversal().V().hasLabel("Person")));
assertEquals(1, Iterators.size(graph.traversal().V().hasLabel("Location")));
}
@Test
public void canExecuteGraphIndexQueriesWithStringPredicatesWithoutIndices(){
ChronoGraph graph = this.getGraph();
graph.addVertex(T.label, "Person", "firstname", "John", "lastname", "Doe");
graph.addVertex(T.label, "Person", "firstname", "Jane", "lastname", "Doe");
graph.addVertex(T.label, "Person", "firstname", "Jack", "lastname", "Smith");
graph.addVertex(T.label, "Person", "firstname", "Sarah", "lastname", "Doe");
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWith("J")).values("firstname").toSet(), containsInAnyOrder("John","Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWith("J")).values("firstname").toSet(), containsInAnyOrder("Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("John", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWith("n")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("Jack"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWith("n")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("John", "Jane", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.contains("a")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContains("a")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.containsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContainsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("John", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
graph.tx().commit();
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWith("J")).values("firstname").toSet(), containsInAnyOrder("John","Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWith("J")).values("firstname").toSet(), containsInAnyOrder("Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("John", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWith("n")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("Jack"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWith("n")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("John", "Jane", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.contains("a")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContains("a")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.containsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContainsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("John", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
}
@Test
public void canExecuteGraphIndexQueriesWithStringPredicatesWithIndices(){
ChronoGraph graph = this.getGraph();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstname").acrossAllTimestamps().build();
graph.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastname").acrossAllTimestamps().build();
graph.getIndexManagerOnMaster().reindexAll();
graph.addVertex(T.label, "Person", "firstname", "John", "lastname", "Doe");
graph.addVertex(T.label, "Person", "firstname", "Jane", "lastname", "Doe");
graph.addVertex(T.label, "Person", "firstname", "Jack", "lastname", "Smith");
graph.addVertex(T.label, "Person", "firstname", "Sarah", "lastname", "Doe");
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWith("J")).values("firstname").toSet(), containsInAnyOrder("John","Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWith("J")).values("firstname").toSet(), containsInAnyOrder("Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("John", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWith("n")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("Jack"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWith("n")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("John", "Jane", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.contains("a")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContains("a")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.containsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContainsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("John", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
graph.tx().commit();
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWith("J")).values("firstname").toSet(), containsInAnyOrder("John","Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.startsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("Jack", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWith("J")).values("firstname").toSet(), containsInAnyOrder("Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notStartsWithIgnoreCase("ja")).values("firstname").toSet(), containsInAnyOrder("John", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWith("n")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.endsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("Jack"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWith("n")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notEndsWithIgnoreCase("K")).values("firstname").toSet(), containsInAnyOrder("John", "Jane", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.contains("a")).values("firstname").toSet(), containsInAnyOrder("Jane", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContains("a")).values("firstname").toSet(), containsInAnyOrder("John"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.containsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notContainsIgnoreCase("AN")).values("firstname").toSet(), containsInAnyOrder("John", "Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegex("J.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.matchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("John", "Jane"));
MatcherAssert.assertThat(graph.traversal().V().has("firstname", CP.notMatchesRegexIgnoreCase("j.*n.*")).values("firstname").toSet(), containsInAnyOrder("Jack", "Sarah"));
}
}
| 23,858 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinOrTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/gremlin/GremlinOrTest.java | package org.chronos.chronograph.test.cases.gremlin;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
import org.chronos.chronograph.test.base.FailOnAllEdgesQuery;
import org.chronos.chronograph.test.base.FailOnAllVerticesQuery;
import org.chronos.common.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GremlinOrTest extends AllChronoGraphBackendsTest {
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canPerformLeadingOrQuery(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "firstname", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "firstname", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "firstname", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "firstname", "John", "lastname", "Smith");
g.addVertex(T.id, "5", "firstname", "Jack", "lastname", "Jackson");
this.assertCommitAssert(() -> {
// OrStep([[HasStep([firstname.eq(John)])], [HasStep([lastname.eq(Jackson)])]])
Set<Object> queryResult = g.traversal().V()
.or(
has("firstname", "John"),
has("lastname", "Jackson")
).id()
.toSet();
assertThat(queryResult, containsInAnyOrder("1", "4", "5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canPerformOrQueryAfterHas(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "firstname", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "firstname", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "firstname", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "firstname", "John", "lastname", "Smith");
g.addVertex(T.id, "5", "firstname", "Jack", "lastname", "Jackson");
this.assertCommitAssert(() -> {
// OrStep([[HasStep([firstname.eq(John)])], [HasStep([lastname.eq(Jackson)])]])
Set<Object> queryResult = g.traversal().V()
.has("lastname", "Doe")
.or(
has("firstname", "John"),
has("lastname", "Jackson")
).id()
.toSet();
assertThat(queryResult, containsInAnyOrder("1"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canPerformInfixOrQuery(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "firstname", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "firstname", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "firstname", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "firstname", "John", "lastname", "Smith");
g.addVertex(T.id, "5", "firstname", "Jack", "lastname", "Jackson");
g.addVertex(T.id, "6", "firstname", "Max", "lastname", "Mustermann");
this.assertCommitAssert(() -> {
// [ChronoGraphStep(vertex,[]), OrStep([[HasStep([lastname.eq(Doe)])], [HasStep([firstname.eq(John)]), IdStep]])]
Set<String> queryResult = g.traversal().V()
.has("lastname", "Doe")
.or()
.has("firstname", "John")
.or()
.has("lastname", "Jackson")
.toStream()
.map(v -> (String)v.id())
.collect(Collectors.toSet());
assertThat(queryResult, containsInAnyOrder("1", "2", "3", "4", "5"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canPerformOrPredicateQuery(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "firstname", "John", "lastname", "Doe");
g.addVertex(T.id, "2", "firstname", "Jane", "lastname", "Doe");
g.addVertex(T.id, "3", "firstname", "Sarah", "lastname", "Doe");
g.addVertex(T.id, "4", "firstname", "John", "lastname", "Smith");
g.addVertex(T.id, "5", "firstname", "Jack", "lastname", "Jackson");
this.assertCommitAssert(() -> {
// [ChronoGraphStep(vertex,[]), HasStep([lastname.or(eq(Doe), eq(Smith))]), IdStep]
Set<Object> queryResult = g.traversal().V()
.has("lastname", P.eq("Doe").or(P.eq("Smith")))
.id()
.toSet();
assertThat(queryResult, containsInAnyOrder("1", "2", "3", "4"));
});
}
@Test
@FailOnAllVerticesQuery
@FailOnAllEdgesQuery
public void canReorderIndexSearchSteps(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("firstname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("lastname").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
g.addVertex(T.id, "1", "firstname", "John", "lastname", "Doe", "age", 35);
g.addVertex(T.id, "2", "firstname", "Jane", "lastname", "Doe", "age", 32);
g.addVertex(T.id, "3", "firstname", "Sarah", "lastname", "Doe", "age", 18);
g.addVertex(T.id, "4", "firstname", "John", "lastname", "Smith", "age", 37);
g.addVertex(T.id, "5", "firstname", "Jack", "lastname", "Jackson", "age", 38);
this.assertCommitAssert(() -> {
Set<Object> queryResult = g.traversal().V()
// age is not indexed (on purpose)
.has("age", P.gt(20))
// but this OR query is!
.or(
has("lastname", "Doe"),
has("firstname", "John")
).id().toSet();
assertThat(queryResult, containsInAnyOrder("1", "2", "4"));
});
}
@Test
public void canHaveLabelsInQuery(){
ChronoGraph g = this.getGraph();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("name").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onVertexProperty("kind").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onEdgeProperty("associationClass").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().create().stringIndex().onEdgeProperty("kind").acrossAllTimestamps().build();
g.getIndexManagerOnMaster().reindexAll();
Vertex a1 = g.addVertex("name", "A1", "kind", "entity");
Vertex a2 = g.addVertex("name", "A2", "kind", "entity");
Vertex b1 = g.addVertex("name", "B1", "kind", "entity");
Edge a1UsesB1 = a1.addEdge("uses", b1);
a1UsesB1.property("kind", "assocEdge");
a1UsesB1.property("associationClass", "t:dd2da55d-ad7a-4d6a-b382-19eea2581502");
Edge a2UsesB1 = a2.addEdge("uses", b1);
a2UsesB1.property("kind", "assocEdge");
a2UsesB1.property("associationClass", "t:dd2da55d-ad7a-4d6a-b382-19eea2581502");
final String LABEL_ASSET = "ASSET";
final String LABEL_LINK = "LINK";
GraphTraversal<Edge, Map<String, Object>> result = g.traversal().E()
.has("kind", "assocEdge")
.has("associationClass", P.within("t:dd2da55d-ad7a-4d6a-b382-19eea2581502"))
.as(LABEL_LINK)
.inV()
.has("name")
.as(LABEL_ASSET)
.select(LABEL_LINK, LABEL_ASSET);
assertTrue(result.hasNext());
}
} | 9,280 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GremlinTransitiveClosureTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/cases/gremlin/GremlinTransitiveClosureTest.java | package org.chronos.chronograph.test.cases.gremlin;
import com.google.common.base.Objects;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.test.base.AllChronoGraphBackendsTest;
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.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*;
import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class GremlinTransitiveClosureTest extends AllChronoGraphBackendsTest {
@Test
public void runTransitiveClosureTestOnAcyclicGraph() {
ChronoGraph g = this.getGraph();
Vertex vApp = g.addVertex("name", "MyApp", "kind", "Application");
Vertex vVM1 = g.addVertex("name", "VM1", "kind", "VirtualMachine");
Vertex vVM2 = g.addVertex("name", "VM2", "kind", "VirtualMachine");
Vertex vVM3 = g.addVertex("name", "VM3", "kind", "VirtualMachine");
Vertex vVM4 = g.addVertex("name", "VM4", "kind", "VirtualMachine");
Vertex vVM5 = g.addVertex("name", "VM5", "kind", "VirtualMachine");
Vertex vVM6 = g.addVertex("name", "VM6", "kind", "VirtualMachine");
Vertex vVM7 = g.addVertex("name", "VM7", "kind", "VirtualMachine");
Vertex vVM8 = g.addVertex("name", "VM8", "kind", "VirtualMachine");
Vertex vPM1 = g.addVertex("name", "PM1", "kind", "PhysicalMachine");
Vertex vPM2 = g.addVertex("name", "PM2", "kind", "PhysicalMachine");
Vertex vPM3 = g.addVertex("name", "PM3", "kind", "PhysicalMachine");
Vertex vPM4 = g.addVertex("name", "PM4", "kind", "PhysicalMachine");
vApp.addEdge("runsOn", vVM1);
vVM1.addEdge("runsOn", vVM2);
vVM2.addEdge("runsOn", vVM3);
vVM2.addEdge("runsOn", vVM4);
vVM3.addEdge("runsOn", vVM5);
vVM3.addEdge("runsOn", vVM6);
vVM4.addEdge("runsOn", vVM7);
vVM4.addEdge("runsOn", vVM8);
vVM5.addEdge("runsOn", vPM1);
vVM6.addEdge("runsOn", vPM2);
vVM7.addEdge("runsOn", vPM3);
vVM8.addEdge("runsOn", vPM4);
g.tx().commit();
Set<Vertex> physicalMachines = g.traversal()
.V()
.has("name", "MyApp").repeat(out("runsOn")).emit(t -> {
Object value = t.get().property("kind").orElse(null);
return Objects.equal(value, "PhysicalMachine");
})
.until(t -> false)
.toSet();
for (Vertex v : physicalMachines) {
System.out.println(v.id() + ": " + v.value("name") + " (" + v.value("kind") + ")");
}
assertEquals(Sets.newHashSet(vPM1, vPM2, vPM3, vPM4), physicalMachines);
}
@Test
public void runTransitiveClosureTestOnCyclicGraph() {
ChronoGraph g = this.getGraph();
// these four vertices form a circle
Vertex v1 = g.addVertex("name", "V1");
Vertex v2 = g.addVertex("name", "V2");
Vertex v3 = g.addVertex("name", "V3");
Vertex v4 = g.addVertex("name", "V4");
v1.addEdge("connect", v2);
v2.addEdge("connect", v3);
v3.addEdge("connect", v4);
v4.addEdge("connect", v1);
// to each vertex in the circle, we add a vertex to form a 2-step-loop
Vertex v5 = g.addVertex("name", "V5");
Vertex v6 = g.addVertex("name", "V6");
Vertex v7 = g.addVertex("name", "V7");
Vertex v8 = g.addVertex("name", "V8");
v1.addEdge("connect", v5);
v5.addEdge("connect", v1);
v2.addEdge("connect", v6);
v6.addEdge("connect", v2);
v3.addEdge("connect", v7);
v7.addEdge("connect", v3);
v4.addEdge("connect", v8);
v8.addEdge("connect", v4);
g.tx().commit();
// run the query
Collection<Path> paths = g.traversal().V(v1).repeat(out("connect").simplePath()).emit().until(t -> false).path().toList();
// this block is just for debugging, it prints the encountered paths.
paths.forEach(path -> {
String separator = "";
for (Object element : path) {
Vertex v = (Vertex) element;
System.out.print(separator + v.value("name"));
separator = " -> ";
}
System.out.println();
});
List<Vertex> closureVertices = paths.stream().map(Path::head).map(e -> (Vertex) e).collect(Collectors.toList());
// we have 8 vertices in total. The source of the closure is not part of the closure,
// therefore we should have 7 vertices in the closure.
assertEquals(7, closureVertices.size());
assertTrue(closureVertices.contains(v2));
assertTrue(closureVertices.contains(v3));
assertTrue(closureVertices.contains(v4));
assertTrue(closureVertices.contains(v5));
assertTrue(closureVertices.contains(v6));
assertTrue(closureVertices.contains(v7));
}
}
| 5,253 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
FailOnAllVerticesQuery.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/base/FailOnAllVerticesQuery.java | package org.chronos.chronograph.test.base;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FailOnAllVerticesQuery {
}
| 198 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AllChronoGraphBackendsTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/base/AllChronoGraphBackendsTest.java | package org.chronos.chronograph.test.base;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.ConfigurationUtils;
import org.chronos.chronodb.test.base.AllBackendsTest;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.test.util.FailOnAllEdgesIterationHandler;
import org.chronos.chronograph.test.util.FailOnAllVerticesIterationHandler;
import org.junit.After;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import static com.google.common.base.Preconditions.*;
public abstract class AllChronoGraphBackendsTest extends AllBackendsTest {
private static final Logger log = LoggerFactory.getLogger(AllChronoGraphBackendsTest.class);
// =================================================================================================================
// FIELDS
// =================================================================================================================
private ChronoGraph graph;
// =================================================================================================================
// GETTERS & SETTERS
// =================================================================================================================
protected ChronoGraph getGraph() {
if (this.graph == null) {
this.graph = this.instantiateChronoGraph(this.backend);
}
return this.graph;
}
// =================================================================================================================
// JUNIT CONTROL
// =================================================================================================================
@After
public void cleanUp() {
if (this.graph != null && this.graph.isClosed() == false) {
if (this.graph.tx().isOpen()) {
this.graph.tx().rollback();
}
log.debug("Closing ChronoDB on backend '" + this.backend + "'.");
this.graph.close();
}
}
// =================================================================================================================
// UTILITY
// =================================================================================================================
protected ChronoGraph reinstantiateGraph() {
log.debug("Reinstantiating ChronoGraph on backend '" + this.backend + "'.");
this.graph.close();
this.graph = this.instantiateChronoGraph(this.backend);
return this.graph;
}
protected ChronoGraph closeAndReopenGraph(){
return this.closeAndReopenGraph(new BaseConfiguration());
}
protected ChronoGraph closeAndReopenGraph(Configuration additionalConfiguration){
Configuration dbConfig = ((ChronoGraphInternal) this.graph).getBackingDB().getConfiguration().asCommonsConfiguration();
Configuration graphConfig = this.graph.getChronoGraphConfiguration().asCommonsConfiguration();
this.graph.close();
ConfigurationUtils.copy(dbConfig, graphConfig);
ConfigurationUtils.copy(additionalConfiguration, graphConfig);
this.graph = ChronoGraph.FACTORY.create().fromConfiguration(graphConfig).build();
return this.graph;
}
protected ChronoGraph instantiateChronoGraph(final String backend) {
checkNotNull(backend, "Precondition violation - argument 'backend' must not be NULL!");
Configuration configuration = this.createChronosConfiguration(backend);
return this.createGraph(configuration);
}
protected ChronoGraph createGraph(final Configuration configuration) {
checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!");
this.applyExtraTestMethodProperties(configuration);
// always enable graph integrity validation for chronograph tests
configuration.setProperty(ChronoGraphConfiguration.TRANSACTION_CHECK_GRAPH_INVARIANT, "true");
return ChronoGraph.FACTORY.create().fromConfiguration(configuration).build();
}
@Override
protected void applyExtraTestMethodProperties(final Configuration configuration) {
super.applyExtraTestMethodProperties(configuration);
Method currentTestMethod = this.getCurrentTestMethod();
if(currentTestMethod.getAnnotation(FailOnAllVerticesQuery.class) != null){
configuration.setProperty(ChronoGraphConfiguration.ALL_VERTICES_ITERATION_HANDLER_CLASS_NAME, FailOnAllVerticesIterationHandler.class.getName());
}
if(currentTestMethod.getAnnotation(FailOnAllEdgesQuery.class) != null){
configuration.setProperty(ChronoGraphConfiguration.ALL_EDGES_ITERATION_HANDLER_CLASS_NAME, FailOnAllEdgesIterationHandler.class.getName());
}
}
protected void assertCommitAssert(final Runnable assertion) {
assertion.run();
this.getGraph().tx().commit();
assertion.run();
}
}
| 5,272 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphUnitTest.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/base/ChronoGraphUnitTest.java | package org.chronos.chronograph.test.base;
import org.chronos.common.test.ChronosUnitTest;
public abstract class ChronoGraphUnitTest extends ChronosUnitTest {
}
| 164 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
FailOnAllEdgesQuery.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/base/FailOnAllEdgesQuery.java | package org.chronos.chronograph.test.base;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FailOnAllEdgesQuery {
}
| 195 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTestUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/util/ChronoGraphTestUtil.java | package org.chronos.chronograph.test.util;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoEdgeImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexImpl;
import org.chronos.chronograph.internal.impl.structure.graph.proxy.ChronoEdgeProxy;
import org.chronos.chronograph.internal.impl.structure.graph.proxy.ChronoVertexProxy;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphTestUtil {
public static boolean isFullyLoaded(Element element) {
checkNotNull(element, "Precondition violation - argument 'element' must not be NULL!");
if (element instanceof ChronoVertexProxy) {
ChronoVertexProxy vertexProxy = (ChronoVertexProxy) element;
return vertexProxy.isLoaded();
} else if (element instanceof ChronoVertexImpl) {
return true;
} else if (element instanceof ChronoEdgeProxy) {
ChronoEdgeProxy edgeProxy = (ChronoEdgeProxy) element;
return edgeProxy.isLoaded();
} else if (element instanceof ChronoEdgeImpl) {
return true;
} else {
throw new RuntimeException("Could not determine loaded state of element with class [" + element.getClass().getName() + "]");
}
}
}
| 1,343 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
FailOnAllEdgesIterationHandler.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/util/FailOnAllEdgesIterationHandler.java | package org.chronos.chronograph.test.util;
import org.chronos.chronograph.api.transaction.AllEdgesIterationHandler;
import static org.junit.Assert.*;
public class FailOnAllEdgesIterationHandler implements AllEdgesIterationHandler {
@Override
public void onAllEdgesIteration() {
fail("Required iteration over all Edges which is not supposed to happen in this test!");
}
}
| 396 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
FailOnAllVerticesIterationHandler.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/test/java/org/chronos/chronograph/test/util/FailOnAllVerticesIterationHandler.java | package org.chronos.chronograph.test.util;
import org.chronos.chronograph.api.transaction.AllVerticesIterationHandler;
import static org.junit.Assert.*;
public class FailOnAllVerticesIterationHandler implements AllVerticesIterationHandler {
@Override
public void onAllVerticesIteration() {
fail("Required iteration over all Vertices which is not supposed to happen in this test!");
}
}
| 411 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphConstants.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/ChronoGraphConstants.java | package org.chronos.chronograph.internal;
public final class ChronoGraphConstants {
// =====================================================================================================================
// STATIC FIELDS
// =====================================================================================================================
public static final String KEYSPACE_VERTEX = "vertex";
public static final String KEYSPACE_EDGE = "edge";
public static final String KEYSPACE_VARIABLES = "variables";
public static final String KEYSPACE_MANAGEMENT_INDICES = "indices";
public static final String KEYSPACE_TRIGGERS = "triggers";
public static final String KEYSPACE_SCHEMA_VALIDATORS = "schemavalidators";
public static final String KEYSPACE_MANAGEMENT = "org.chronos.chronograph.management";
public static final String KEYSPACE_MANAGEMENT_KEY__CHRONOGRAPH_VERSION = "chronograph.version";
public static final String INDEX_PREFIX_VERTEX = "v_";
public static final String INDEX_PREFIX_EDGE = "e_";
public static final String VARIABLES_DEFAULT_KEYSPACE = "default";
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
private ChronoGraphConstants() {
// do not instantiate
}
}
| 1,479 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
SchemaValidationResultImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/schema/SchemaValidationResultImpl.java | package org.chronos.chronograph.internal.impl.schema;
import com.google.common.collect.*;
import com.google.common.collect.Table.Cell;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.schema.SchemaValidationResult;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class SchemaValidationResultImpl implements SchemaValidationResult {
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final Table<Element, String, Throwable> table = HashBasedTable.create();
// =================================================================================================================
// CONSTRUCTOR
// =================================================================================================================
public SchemaValidationResultImpl() {
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public int getFailureCount() {
return this.table.size();
}
@Override
public Set<String> getFailedValidators() {
return Collections.unmodifiableSet(Sets.newHashSet(this.table.columnKeySet()));
}
@Override
public Map<String, List<Pair<Element, Throwable>>> getViolationsByValidators(){
Map<String, List<Pair<Element, Throwable>>> resultMap = Maps.newHashMap();
for(Cell<Element, String, Throwable> cell : this.table.cellSet()){
List<Pair<Element, Throwable>> list = resultMap.computeIfAbsent(cell.getColumnKey(), k -> Lists.newArrayList());
list.add(Pair.of(cell.getRowKey(), cell.getValue()));
}
return resultMap;
}
@Override
public Map<String, Throwable> getFailedValidatorExceptionsForElement(final Element element) {
return Collections.unmodifiableMap(this.table.row(element));
}
@Override
public String generateErrorMessage() {
if(this.getFailureCount() <= 0){
return "No Graph Schema violations were detected.";
}
int maxViolationsToShowPerValidator = 5;
StringBuilder msg = new StringBuilder();
msg.append("Cannot apply graph commit: ");
msg.append(this.getFailureCount());
msg.append(" Graph Schema violations were detected. ");
msg.append("The transaction will be rolled back, no changes will be applied. ");
msg.append("The following validations were reported:\n");
Map<String, List<Pair<Element, Throwable>>> validatorToViolations = this.getViolationsByValidators();
for (Entry<String, List<Pair<Element, Throwable>>> entry : validatorToViolations.entrySet()) {
String validatorName = entry.getKey();
List<Pair<Element, Throwable>> violations = entry.getValue();
msg.append(" - ");
msg.append(validatorName);
msg.append(" (");
msg.append(violations.size());
msg.append(" violations):\n");
violations.stream().limit(maxViolationsToShowPerValidator).forEach(violation -> {
Element element = violation.getLeft();
Throwable error = violation.getRight();
msg.append("\tat ");
if(element instanceof Vertex){
msg.append("Vertex");
}else if(element instanceof Edge){
msg.append("Edge");
}else {
msg.append(element.getClass().getSimpleName());
}
msg.append("[");
msg.append(element.id());
msg.append("]: ");
msg.append(error.getMessage());
msg.append("\n");
});
if(violations.size() > maxViolationsToShowPerValidator){
int more = violations.size() - maxViolationsToShowPerValidator;
if(more > 0){
msg.append("\t... and ");
msg.append(more);
msg.append(" other elements reported by this validator.");
}
}
}
return msg.toString();
}
@Override
public String toString() {
if (this.isSuccess()) {
return "ValidationResult[SUCCESS]";
} else {
return "ValidationResult[FAILURE: " + this.getFailedValidators().stream().collect(Collectors.joining(", ")) + "]";
}
}
// =================================================================================================================
// INTERNAL API
// =================================================================================================================
public void addIssue(Element graphElement, String validatorName, Throwable issue) {
this.table.put(graphElement, validatorName, issue);
}
}
| 5,387 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphSchemaManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/schema/ChronoGraphSchemaManagerImpl.java | package org.chronos.chronograph.internal.impl.schema;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import groovy.transform.CompileStatic;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronograph.api.exceptions.ChronoGraphSchemaViolationException;
import org.chronos.chronograph.api.schema.ChronoGraphSchemaManager;
import org.chronos.chronograph.api.schema.SchemaValidationResult;
import org.chronos.chronograph.api.structure.ChronoElement;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.groovy.GroovyCompilationCache;
import org.chronos.chronograph.internal.impl.groovy.LocalGroovyCompilationCache;
import org.chronos.chronograph.internal.impl.groovy.StaticGroovyCompilationCache;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphSchemaManagerImpl implements ChronoGraphSchemaManager {
private static final Logger log = LoggerFactory.getLogger(ChronoGraphSchemaManagerImpl.class);
private final ChronoGraphInternal owningGraph;
private final ReadWriteLock validatorsLock;
private final Map<String, String> validatorScriptContentCache = Maps.newHashMap();
private final Map<String, Script> compiledValidatorScriptCache = Maps.newHashMap();
private final GroovyCompilationCache compilationCache;
public ChronoGraphSchemaManagerImpl(ChronoGraphInternal owningGraph) {
checkNotNull(owningGraph, "Precondition violation - argument 'owningGraph' must not be NULL!");
this.owningGraph = owningGraph;
this.validatorsLock = new ReentrantReadWriteLock(true);
if (owningGraph.getChronoGraphConfiguration().isUseStaticGroovyCompilationCache()) {
this.compilationCache = StaticGroovyCompilationCache.getInstance();
} else {
this.compilationCache = new LocalGroovyCompilationCache();
}
this.loadValidatorCaches();
}
@Override
public boolean addOrOverrideValidator(final String validatorName, final String scriptContent) {
return this.addOrOverrideValidator(validatorName, scriptContent, null);
}
@Override
public boolean addOrOverrideValidator(final String validatorName, final String scriptContent, final Object commitMetadata) {
checkNotNull(validatorName, "Precondition violation - argument 'validatorName' must not be NULL!");
checkArgument(!validatorName.isEmpty(), "Precondition violation - argument 'validatorName' must not be empty!");
checkNotNull(scriptContent, "Precondition violation - argument 'scriptContent' must not be NULL!");
checkArgument(!scriptContent.isEmpty(), "Precondition violation - argument 'scriptContent' must not be empty!");
Class<? extends Script> scriptClass;
try {
scriptClass = this.compile(scriptContent);
} catch (Exception e) {
throw new IllegalArgumentException("The given validator script has compilation errors. Please see root cause for details.", e);
}
this.validatorsLock.writeLock().lock();
try {
ChronoDBTransaction tx = this.owningGraph.getBackingDB().tx();
boolean exists = tx.exists(ChronoGraphConstants.KEYSPACE_SCHEMA_VALIDATORS, validatorName);
tx.put(ChronoGraphConstants.KEYSPACE_SCHEMA_VALIDATORS, validatorName, scriptContent);
tx.commit(commitMetadata);
this.addValidatorToCache(validatorName, scriptContent, scriptClass);
return exists;
} finally {
this.validatorsLock.writeLock().unlock();
}
}
@Override
public boolean removeValidator(final String validatorName) {
return this.removeValidator(validatorName, null);
}
@Override
public boolean removeValidator(final String validatorName, Object commitMetadata) {
checkNotNull(validatorName, "Precondition violation - argument 'validatorName' must not be NULL!");
checkArgument(!validatorName.isEmpty(), "Precondition violation - argument 'validatorName' must not be empty!");
this.validatorsLock.writeLock().lock();
try {
ChronoDBTransaction tx = this.owningGraph.getBackingDB().tx();
boolean exists = tx.exists(ChronoGraphConstants.KEYSPACE_SCHEMA_VALIDATORS, validatorName);
tx.remove(ChronoGraphConstants.KEYSPACE_SCHEMA_VALIDATORS, validatorName);
tx.commit(commitMetadata);
this.removeValidatorFromCache(validatorName);
return exists;
} finally {
this.validatorsLock.writeLock().unlock();
}
}
@Override
public String getValidatorScript(final String validatorName) {
checkNotNull(validatorName, "Precondition violation - argument 'validatorName' must not be NULL!");
checkArgument(!validatorName.isEmpty(), "Precondition violation - argument 'validatorName' must not be empty!");
this.validatorsLock.readLock().lock();
try {
return this.validatorScriptContentCache.get(validatorName);
} finally {
this.validatorsLock.readLock().unlock();
}
}
@Override
public Set<String> getAllValidatorNames() {
this.validatorsLock.readLock().lock();
try {
return Collections.unmodifiableSet(Sets.newHashSet(this.validatorScriptContentCache.keySet()));
} finally {
this.validatorsLock.readLock().unlock();
}
}
@Override
public SchemaValidationResult validate(final String branch, final Iterable<? extends ChronoElement> elements) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkNotNull(elements, "Precondition violation - argument 'elements' must not be NULL!");
this.validatorsLock.readLock().lock();
try {
SchemaValidationResultImpl result = new SchemaValidationResultImpl();
if (this.compiledValidatorScriptCache.isEmpty()) {
// no validators given; short-circuit the process
return result;
}
for (Entry<String, Script> entry : this.compiledValidatorScriptCache.entrySet()) {
String validatorName = entry.getKey();
Script script = entry.getValue();
for (ChronoElement element : elements) {
try {
this.executeValidator(script, branch, element);
} catch (Throwable t) {
if (t instanceof ChronoGraphSchemaViolationException == false) {
log.warn("The validator '" + validatorName + "' produced an unexpected exception. " +
"This will be treated as validation failure. The exception is of type '" + t.getClass().getName() +
"' and its message is: " + t.getMessage());
}
// record the issue
result.addIssue(element, validatorName, t);
}
}
}
return result;
} finally {
this.validatorsLock.readLock().unlock();
}
}
// =================================================================================================================
// HELPER METHODS
// =================================================================================================================
private Class<? extends Script> compile(String groovyValidatorScript) throws Exception {
checkNotNull(groovyValidatorScript, "Precondition violation - argument 'groovyValidatorScript' must not be NULL!");
checkArgument(!groovyValidatorScript.isEmpty(), "Precondition violation - argument 'groovyValidatorScript' must not be empty!");
Class<? extends Script> cached = this.compilationCache.get(groovyValidatorScript);
if (cached != null) {
return cached;
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// prepare the default import statements which we are going to use
String imports = "import org.apache.tinkerpop.*; import org.apache.tinkerpop.gremlin.*; import org.apache.tinkerpop.gremlin.structure.*;";
imports += "import org.chronos.chronograph.api.*; import org.chronos.chronograph.api.structure.*; import org.chronos.chronograph.api.exceptions.*;";
// prepare the declaration of the 'element' and 'branch' variables within the script (with the proper variable type)
String varDefs = Element.class.getSimpleName() + " element = (" + Element.class.getSimpleName() + ")this.binding.variables.element; "
+ "String branch = (String)this.binding.variables.branch;\n";
// prepare the compiler configuration to have static type checking
CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(new ASTTransformationCustomizer(CompileStatic.class));
// compile the script into a binary class
try (GroovyClassLoader gcl = new GroovyClassLoader(classLoader, config)) {
Class<?extends Script> compiledScript = gcl.parseClass(imports + varDefs + groovyValidatorScript);
this.compilationCache.put(groovyValidatorScript, compiledScript);
return compiledScript;
}
}
private void loadValidatorCaches() {
ChronoDBTransaction tx = this.owningGraph.getBackingDB().tx();
Set<String> validatorNames = tx.keySet(ChronoGraphConstants.KEYSPACE_SCHEMA_VALIDATORS);
for (String validatorName : validatorNames) {
String validatorScript = tx.get(ChronoGraphConstants.KEYSPACE_SCHEMA_VALIDATORS, validatorName);
try {
Class<? extends Script> compiledScript = this.compile(validatorScript);
this.addValidatorToCache(validatorName, validatorScript, compiledScript);
} catch (Exception e) {
log.warn("The Graph Schema Validator '" + validatorName + "' failed to compile and will be ignored. Root cause: " + e);
}
}
}
private void addValidatorToCache(String validatorName, String validatorScript, Class<? extends Script> scriptClass) {
checkNotNull(validatorName, "Precondition violation - argument 'validatorName' must not be NULL!");
checkArgument(!validatorName.isEmpty(), "Precondition violation - argument 'validatorName' must not be empty!");
checkNotNull(validatorScript, "Precondition violation - argument 'validatorScript' must not be NULL!");
checkArgument(!validatorScript.isEmpty(), "Precondition violation - argument 'validatorScript' must not be empty!");
checkNotNull(scriptClass, "Precondition violation - argument 'scriptClass' must not be NULL!");
this.validatorScriptContentCache.put(validatorName, validatorScript);
try {
Script validatorInstance = scriptClass.getConstructor().newInstance();
this.compiledValidatorScriptCache.put(validatorName, validatorInstance);
} catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {
throw new IllegalArgumentException("Could not create an instance of the given validator script. See root cause for details.", e);
}
}
private void removeValidatorFromCache(String validatorName) {
checkNotNull(validatorName, "Precondition violation - argument 'validatorName' must not be NULL!");
checkArgument(!validatorName.isEmpty(), "Precondition violation - argument 'validatorName' must not be empty!");
this.validatorScriptContentCache.remove(validatorName);
this.compiledValidatorScriptCache.remove(validatorName);
}
private void executeValidator(Script script, String branch, ChronoElement element) throws Exception {
Binding bindings = new Binding();
bindings.setVariable("element", element);
bindings.setVariable("branch", branch);
script.setBinding(bindings);
script.run();
}
}
| 12,896 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphMaintenanceManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/maintenance/ChronoGraphMaintenanceManagerImpl.java | package org.chronos.chronograph.internal.impl.maintenance;
import org.chronos.chronograph.api.maintenance.ChronoGraphMaintenanceManager;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphMaintenanceManagerImpl implements ChronoGraphMaintenanceManager {
private final ChronoGraphInternal graph;
public ChronoGraphMaintenanceManagerImpl(ChronoGraphInternal graph){
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.graph = graph;
}
@Override
public void performRolloverOnBranch(final String branchName, boolean updateIndices) {
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
this.graph.getBackingDB().getMaintenanceManager().performRolloverOnBranch(branchName, updateIndices);
}
@Override
public void performRolloverOnAllBranches(boolean updateIndices) {
this.graph.getBackingDB().getMaintenanceManager().performRolloverOnAllBranches(updateIndices);
}
@Override
public void performRolloverOnAllBranchesWhere(final Predicate<String> branchPredicate, boolean updateIndices) {
checkNotNull(branchPredicate, "Precondition violation - argument 'branchPredicate' must not be NULL!");
this.graph.getBackingDB().getMaintenanceManager().performRolloverOnAllBranchesWhere(branchPredicate, updateIndices);
}
}
| 1,537 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphFactoryImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/factory/ChronoGraphFactoryImpl.java | package org.chronos.chronograph.internal.impl.factory;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.structure.util.GraphFactory;
import org.apache.tinkerpop.gremlin.structure.util.GraphFactoryClass;
import org.chronos.chronograph.api.ChronoGraphFactory;
import org.chronos.chronograph.api.builder.graph.ChronoGraphBaseBuilder;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.impl.builder.graph.ChronoGraphBaseBuilderImpl;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphFactoryImpl implements ChronoGraphFactory {
/**
* This method is <b>required</b> by Apache Tinkerpop. Creates a new graph instance.
*
* <p>
* This is referenced via {@link ChronoGraph}'s <code>@</code>{@link GraphFactoryClass} annotation and is required
* for the {@link GraphFactory} integration. The graph factory will look for this specific method via reflection.
*
* @param configuration
* The configuration to use for the new graph. Must not be <code>null</code>.
*
* @return The new graph instance.
*/
public static ChronoGraph open(final Configuration configuration) {
checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!");
return ChronoGraphFactory.INSTANCE.create().fromConfiguration(configuration).build();
}
@Override
public ChronoGraphBaseBuilder create() {
return new ChronoGraphBaseBuilderImpl();
}
}
| 1,508 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
MutableRestoreResult.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/history/MutableRestoreResult.java | package org.chronos.chronograph.internal.impl.history;
import com.google.common.collect.Sets;
import org.chronos.chronograph.api.history.RestoreResult;
import java.util.Collections;
import java.util.Set;
public class MutableRestoreResult implements RestoreResult {
// =================================================================================================================
// STATIC
// =================================================================================================================
private static final RestoreResult EMPTY = new MutableRestoreResult();
public static RestoreResult empty(){
return EMPTY;
}
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final Set<String> successfullyRestoredVertexIds = Sets.newHashSet();
private final Set<String> successfullyRestoredEdgeIds = Sets.newHashSet();
private final Set<String> failedEdgeIds = Sets.newHashSet();
// =================================================================================================================
// CONSTRUCTOR
// =================================================================================================================
public MutableRestoreResult(){
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public Set<String> getSuccessfullyRestoredVertexIds() {
return Collections.unmodifiableSet(this.successfullyRestoredVertexIds);
}
@Override
public Set<String> getSuccessfullyRestoredEdgeIds() {
return Collections.unmodifiableSet(this.successfullyRestoredEdgeIds);
}
@Override
public Set<String> getFailedEdgeIds() {
return Collections.unmodifiableSet(this.failedEdgeIds);
}
// =================================================================================================================
// INTERNAL API
// =================================================================================================================
public void markVertexAsSuccessfullyRestored(String vertexId){
this.successfullyRestoredVertexIds.add(vertexId);
}
public void markEdgeAsSuccessfullyRestored(String edgeId){
this.failedEdgeIds.remove(edgeId);
this.successfullyRestoredEdgeIds.add(edgeId);
}
public void markEdgeAsFailed(String edgeId){
this.successfullyRestoredEdgeIds.remove(edgeId);
this.failedEdgeIds.add(edgeId);
}
}
| 2,885 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphHistoryManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/history/ChronoGraphHistoryManagerImpl.java | package org.chronos.chronograph.internal.impl.history;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.*;
import org.chronos.chronograph.api.history.ChronoGraphHistoryManager;
import org.chronos.chronograph.api.history.RestoreResult;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphHistoryManagerImpl implements ChronoGraphHistoryManager {
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final ChronoGraphInternal graph;
// =================================================================================================================
// CONSTRUCTOR
// =================================================================================================================
public ChronoGraphHistoryManagerImpl(ChronoGraphInternal graph) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.graph = graph;
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public RestoreResult restoreGraphElementsAsOf(final long timestamp, final Set<String> vertexIds, final Set<String> edgeIds) {
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
ChronoGraphTransaction tx = this.graph.tx().getCurrentTransaction();
if (tx == null) {
throw new IllegalStateException("Restoring graph elements requires an open transaction, but currently no transaction is present. Please open a transaction first.");
}
long now = tx.getTimestamp();
if (timestamp > now) {
throw new IllegalArgumentException("Precondition violation - argument 'timestamp' (value: "
+ timestamp + ") must be less than or equal to the transaction timestamp (value: " + now + ")!");
}
if ((vertexIds == null || vertexIds.isEmpty()) && (edgeIds == null || edgeIds.isEmpty())) {
// nothing to do
return MutableRestoreResult.empty();
}
// prepare the result object
MutableRestoreResult result = new MutableRestoreResult();
// open a second transaction to retrieve the state from
try(ChronoGraph historyGraph = this.graph.tx().createThreadedTx(tx.getBranchName(), timestamp)){
// prepare the set of edges to restore in addition to the given ones (due to vertex restore)
Set<String> allEdgeIds = Sets.newHashSet();
if (edgeIds != null) {
allEdgeIds.addAll(edgeIds);
}
// first restore the vertices (if required)
if (vertexIds != null && !vertexIds.isEmpty()) {
allEdgeIds.addAll(restoreVertices(vertexIds, tx, result, historyGraph));
}
// then restore the edges (if required)
if (!allEdgeIds.isEmpty()) {
restoreEdges(allEdgeIds, tx, result, historyGraph, allEdgeIds);
}
}
return result;
}
@Override
public RestoreResult restoreGraphStateAsOf(final long timestamp) {
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
ChronoGraphTransaction tx = this.graph.tx().getCurrentTransaction();
if (tx == null) {
throw new IllegalStateException("Restoring graph elements requires an open transaction, but currently no transaction is present. Please open a transaction first.");
}
long now = tx.getTimestamp();
if (timestamp > now) {
throw new IllegalArgumentException("Precondition violation - argument 'timestamp' (value: "
+ timestamp + ") must be less than or equal to the transaction timestamp (value: " + now + ")!");
}
Set<String> vertexIds = Sets.newHashSet();
Set<String> edgeIds = Sets.newHashSet();
// collect the differences between the current tx timestamp and the given timestamp
tx.getGraph().getCommitTimestampsBetween(tx.getBranchName(), timestamp, now).forEachRemaining(commit -> {
Iterator<String> changedVerticesAtCommit = tx.getGraph().getChangedVerticesAtCommit(tx.getBranchName(), commit);
Iterators.addAll(vertexIds, changedVerticesAtCommit);
Iterator<String> changedEdgesAtCommit = tx.getGraph().getChangedEdgesAtCommit(tx.getBranchName(), commit);
Iterators.addAll(edgeIds, changedEdgesAtCommit);
});
// restore everything that has changed since the given timestamp
return this.restoreGraphElementsAsOf(timestamp, vertexIds, edgeIds);
}
// =================================================================================================================
// INTERNAL HELPER METHODS
// =================================================================================================================
private Set<String> restoreVertices(final Set<String> vertexIds, final ChronoGraphTransaction tx, final MutableRestoreResult result, final ChronoGraph historyGraph) {
Set<String> additionalEdgeIds = Sets.newHashSet();
Map<String, Vertex> historicalVerticesById = Maps.uniqueIndex(historyGraph.vertices(vertexIds.toArray()), v -> (String) v.id());
for (String vertexId : vertexIds) {
// delete the vertex in our current version if it exists
Vertex currentVertex = Iterators.getOnlyElement(tx.getGraph().vertices(vertexId), null);
if (currentVertex != null) {
currentVertex.remove();
}
Vertex historicalVertex = historicalVerticesById.get(vertexId);
if (historicalVertex == null) {
// vertex did not exist in the previous version, we're done
result.markVertexAsSuccessfullyRestored(vertexId);
continue;
}
// recreate the vertex
Vertex newVertex = tx.getGraph().addVertex(
T.id, historicalVertex.id(),
T.label, historicalVertex.label()
);
historicalVertex.properties().forEachRemaining(vertexProp -> {
VertexProperty<?> newProp = newVertex.property(vertexProp.key(), vertexProp.value());
// transfer the meta-properties
vertexProp.properties().forEachRemaining(metaProp -> newProp.property(metaProp.key(), metaProp.value()));
}
);
// remember to recreate the edges
historicalVertex.edges(Direction.BOTH).forEachRemaining(e -> additionalEdgeIds.add((String) e.id()));
result.markVertexAsSuccessfullyRestored(vertexId);
}
return additionalEdgeIds;
}
private void restoreEdges(final Set<String> edgeIds, final ChronoGraphTransaction tx, final MutableRestoreResult result, final ChronoGraph historyGraph, final Set<String> allEdgeIds) {
Map<String, Edge> historicalEdgesById = Maps.uniqueIndex(historyGraph.edges(allEdgeIds.toArray()), e -> (String) e.id());
for (String edgeId : edgeIds) {
// delete the edge in our current version if it exists
Edge currentEdge = Iterators.getOnlyElement(tx.getGraph().edges(edgeId), null);
if (currentEdge != null) {
currentEdge.remove();
}
Edge historicalEdge = historicalEdgesById.get(edgeId);
if (historicalEdge == null) {
// edge did not exist in the previous version, we're done
result.markEdgeAsSuccessfullyRestored(edgeId);
continue;
}
// get the source and target vertices in the current graph
Vertex inVertex = Iterators.getOnlyElement(tx.getGraph().vertices(historicalEdge.inVertex().id()), null);
Vertex outVertex = Iterators.getOnlyElement(tx.getGraph().vertices(historicalEdge.outVertex().id()), null);
if (inVertex == null || outVertex == null) {
// either source or target does not exist
result.markEdgeAsFailed(edgeId);
continue;
}
// recreate the edge
Edge newEdge = outVertex.addEdge(historicalEdge.label(), inVertex);
// transfer the properties
historicalEdge.properties().forEachRemaining(prop -> newEdge.property(prop.key(), prop.value()));
result.markEdgeAsSuccessfullyRestored(edgeId);
}
}
}
| 9,293 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphMigrationChain.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/migration/ChronoGraphMigrationChain.java | package org.chronos.chronograph.internal.impl.migration;
import com.google.common.collect.Lists;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronodb.api.dump.ChronoDBDumpFormat;
import org.chronos.chronodb.internal.api.stream.ObjectInput;
import org.chronos.chronodb.internal.api.stream.ObjectOutput;
import org.chronos.chronodb.internal.impl.dump.ChronoDBDumpUtil;
import org.chronos.chronodb.internal.impl.dump.DumpOptions;
import org.chronos.chronodb.internal.impl.dump.entry.ChronoDBDumpEntry;
import org.chronos.chronodb.internal.impl.dump.meta.ChronoDBDumpMetadata;
import org.chronos.chronograph.internal.api.migration.ChronoGraphMigration;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.common.exceptions.ChronosIOException;
import org.chronos.common.version.ChronosVersion;
import org.chronos.common.version.VersionKind;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphMigrationChain {
private static final List<Class<? extends ChronoGraphMigration>> ALL_CHRONOGRAPH_MIGRATION_CLASSES = Collections.unmodifiableList(Lists.newArrayList(
ChronoGraphMigration_0_11_1_to_0_11_2.class,
ChronoGraphMigration_0_11_6_to_0_11_7.class
));
private static final List<ChronoGraphMigration> ALL_GRAPH_MIGRATIONS_IN_ORDER;
static {
ALL_GRAPH_MIGRATIONS_IN_ORDER = Collections.unmodifiableList(loadMigrationsInAscendingOrder());
}
public static void executeMigrationChainOnGraph(ChronoGraphInternal graph) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
Optional<ChronosVersion> currentVersion = graph.getStoredChronoGraphVersion();
if (!currentVersion.isPresent()) {
throw new IllegalStateException("Failed to execute ChronoGraph migration chain - current version is unknown!");
}
List<ChronoGraphMigration> migrationsToApply = ALL_GRAPH_MIGRATIONS_IN_ORDER.stream()
.filter(m -> m.getFromVersion().isGreaterThanOrEqualTo(currentVersion.get()))
.collect(Collectors.toList());
if (migrationsToApply.isEmpty()) {
return;
}
// make sure we're not read-only.
if (graph.getBackingDB().getConfiguration().isReadOnly()) {
throw new IllegalStateException("You are trying to open this database in read-only mode with ChronoGraph " + ChronosVersion.getCurrentVersion() + ". " +
"However, this database has been written with an older format (version " + currentVersion.get() + ") and " + migrationsToApply.size() + " data format " +
"migrations needs to be applied in order for this ChronoGraph version to work properly. Please either open the graph in read-write mode to apply the " +
"required data migraitons (breaking compatibility with older ChronoGraph versions), or use an older ChronoGraph binary to access this database.");
}
for (ChronoGraphMigration migration : migrationsToApply) {
migration.execute(graph);
// the migration was executed successfully, write the new
// version to the graph
graph.setStoredChronoGraphVersion(migration.getToVersion());
}
}
public static File executeMigrationChainOnDumpFile(File dumpFile, DumpOptions options) {
checkNotNull(dumpFile, "Precondition violation - argument 'dumpFile' must not be NULL!");
checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!");
try (ObjectInput input = ChronoDBDumpFormat.createInput(dumpFile, options)) {
String extension = FilenameUtils.getExtension(dumpFile.getName());
File outputFile = Files.createTempFile(dumpFile.getName() + "_graphMigrated", "." + extension).toFile();
try (ObjectOutput output = ChronoDBDumpFormat.createOutput(outputFile, options)) {
// the first entry in a dump is always the metadata
ChronoDBDumpMetadata metadata = ChronoDBDumpUtil.readMetadata(input);
ChronosVersion dumpVersion = metadata.getChronosVersion();
// load all existing ChronoGraph migrations and keep the ones which are required for this version
List<ChronoGraphMigration> migrationsToApply = ALL_GRAPH_MIGRATIONS_IN_ORDER.stream()
.filter(m -> m.getFromVersion().isGreaterThanOrEqualTo(dumpVersion))
.collect(Collectors.toList());
// migrate the metadata object
for (ChronoGraphMigration migration : migrationsToApply) {
migration.execute(metadata);
}
// write the metadata into the output
output.write(metadata);
// for the remaining entries, migrate them one by one and write them to the output.
while (input.hasNext()) {
Object entry = input.next();
if (entry instanceof ChronoDBDumpEntry == false) {
// no idea what this is
throw new IllegalStateException("Encountered unknown entry in DB dump of type '" + entry.getClass().getName() + "'.");
}
ChronoDBDumpEntry<?> dumpEntry = (ChronoDBDumpEntry<?>) entry;
for (ChronoGraphMigration migration : migrationsToApply) {
dumpEntry = migration.execute(dumpEntry);
if (dumpEntry == null) {
// migration decided to discard this entry
break;
}
}
if (dumpEntry != null) {
// entry passed all migrations, add to migrated dump
output.write(dumpEntry);
}
}
}
return outputFile;
} catch (IOException ioe) {
throw new ChronosIOException("Could not migrate DB dump due to an I/O error: " + ioe, ioe);
}
}
// =================================================================================================================
// HELPER METHODS
// =================================================================================================================
@SuppressWarnings({"unchecked", "UnstableApiUsage"})
private static List<ChronoGraphMigration> loadMigrationsInAscendingOrder() {
List<ChronoGraphMigration> allMigrations = ALL_CHRONOGRAPH_MIGRATION_CLASSES.stream()
.distinct()
.map(c -> instantiateMigration((Class<? extends ChronoGraphMigration>) c))
.sorted(Comparator.comparing(ChronoGraphMigration::getFromVersion))
.collect(Collectors.toList());
// make sure from and to are strictly monotonically increasing
for (ChronoGraphMigration migration : allMigrations) {
if (!migration.getFromVersion().isSmallerThan(migration.getToVersion())) {
throw new IllegalStateException("ChronoGraph Migration '" + migration.getClass().getName() + "' is invalid: " +
"it specifies a lower 'to' version (" + migration.getToVersion() + ") than " +
"'from' version (" + migration.getFromVersion() + ")!");
}
}
// make sure there are no gaps or overlaps
if (allMigrations.size() >= 2) {
for (int i = 0; i < allMigrations.size() - 1; i++) {
ChronoGraphMigration m = allMigrations.get(i);
ChronoGraphMigration mPlusOne = allMigrations.get(i + 1);
if (!m.getToVersion().isSmallerThan(mPlusOne.getFromVersion())) {
throw new IllegalStateException("ChronoGraph Migration Chain is inconsistent: " +
"migration [" + m.getClass().getName() + "] ends at version " + m.getToVersion() + ", " +
"but the next migration [" + m.getClass().getName() + "] starts at version " + m.getFromVersion() + "!");
}
}
}
// make sure there are only migrations to releases
for (ChronoGraphMigration migration : allMigrations) {
if (migration.getFromVersion().getVersionKind() != VersionKind.RELEASE) {
throw new IllegalStateException("ChronoGraph Migration [" + migration.getClass().getName() + "] " +
"is invalid: it specifies a 'from' version (" + migration.getFromVersion() + ") " +
"which is not a RELEASE!");
}
if (migration.getToVersion().getVersionKind() != VersionKind.RELEASE) {
throw new IllegalStateException("ChronoGraph Migration [" + migration.getClass().getName() + "] " +
"is invalid: it specifies a 'to' version (" + migration.getToVersion() + ") " +
"which is not a RELEASE!");
}
}
return allMigrations;
}
private static <
T extends ChronoGraphMigration> T instantiateMigration(Class<T> migrationClazz) {
try {
Constructor<T> constructor = migrationClazz.getConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (NoSuchMethodException e) {
throw new IllegalStateException("The ChronoGraphMigration class '" + migrationClazz.getName() + "' has no default constructor! Please add a no-argument constructor.", e);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new IllegalStateException("Failed to instantiate ChronoGrpahMigration class '" + migrationClazz.getName() + "'!");
}
}
}
| 10,322 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphMigration_0_11_1_to_0_11_2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/migration/ChronoGraphMigration_0_11_1_to_0_11_2.java | package org.chronos.chronograph.internal.impl.migration;
import org.chronos.chronodb.api.Dateback;
import org.chronos.chronodb.api.key.ChronoIdentifier;
import org.chronos.chronodb.internal.impl.dump.meta.ChronoDBDumpMetadata;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphTrigger;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.migration.ChronoGraphMigration;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.transaction.trigger.ChronoGraphTriggerWrapper;
import org.chronos.common.version.ChronosVersion;
import org.chronos.common.version.VersionKind;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ChronoGraphMigration_0_11_1_to_0_11_2 implements ChronoGraphMigration {
@Override
public ChronosVersion getFromVersion() {
return new ChronosVersion(0, 11, 1, VersionKind.RELEASE);
}
@Override
public ChronosVersion getToVersion() {
return new ChronosVersion(0, 11, 2, VersionKind.RELEASE);
}
@Override
public void execute(final ChronoGraphInternal graph) {
// get the branches, children first
List<GraphBranch> branches = graph.getBranchManager().getBranches().stream()
.sorted(Comparator.comparing(GraphBranch::getBranchingTimestamp).reversed())
.collect(Collectors.toList());
// migrate the old triggers
for(GraphBranch branch : branches){
String branchName = branch.getName();
graph.getBackingDB().getDatebackManager().dateback(branchName, dateback -> {
dateback.transformValuesOfKeyspace(ChronoGraphConstants.KEYSPACE_TRIGGERS, this::transformTrigger);
});
}
}
@Override
public void execute(final ChronoDBDumpMetadata dumpMetadata) {
// nothing to do here
}
@Override
public Object execute(final ChronoIdentifier chronoIdentifier, final Object value) {
if(ChronoGraphConstants.KEYSPACE_TRIGGERS.equals(chronoIdentifier.getKeyspace())){
if(value instanceof ChronoGraphTrigger){
// transform the trigger entry
return this.transformTrigger((ChronoGraphTrigger)value);
}
}
return ChronoGraphMigration.ENTRY_UNCHANGED;
}
// =================================================================================================================
// HELPER METHODS
// =================================================================================================================
private Object transformTrigger(String key, long timestamp, Object oldValue) {
// the old value is an implementation of a ChronoGraph trigger interface.
if(oldValue instanceof ChronoGraphTrigger ){
return transformTrigger((ChronoGraphTrigger)oldValue);
}else{
// whatever it is, don't touch it
return Dateback.UNCHANGED;
}
}
private Object transformTrigger(ChronoGraphTrigger trigger){
if(trigger instanceof ChronoGraphTriggerWrapper){
// this migration has already taken place, nothing to do
return trigger;
}
// wrap the trigger into a wrapper object for safe deserialization handling if the class is absent.
return new ChronoGraphTriggerWrapper(trigger);
}
}
| 3,538 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphMigration_0_11_6_to_0_11_7.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/migration/ChronoGraphMigration_0_11_6_to_0_11_7.java | package org.chronos.chronograph.internal.impl.migration;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.chronos.chronodb.api.Dateback;
import org.chronos.chronodb.api.Order;
import org.chronos.chronodb.api.key.ChronoIdentifier;
import org.chronos.chronodb.api.key.QualifiedKey;
import org.chronos.chronodb.internal.impl.dump.meta.ChronoDBDumpMetadata;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.migration.ChronoGraphMigration;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.structure.record2.VertexRecord2;
import org.chronos.common.version.ChronosVersion;
import org.chronos.common.version.VersionKind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
@SuppressWarnings("deprecation")
public class ChronoGraphMigration_0_11_6_to_0_11_7 implements ChronoGraphMigration {
private static final Logger log = LoggerFactory.getLogger(ChronoGraphMigration_0_11_6_to_0_11_7.class);
@Override
public ChronosVersion getFromVersion() {
return new ChronosVersion(0, 11, 6, VersionKind.RELEASE);
}
@Override
public ChronosVersion getToVersion() {
return new ChronosVersion(0, 11, 7, VersionKind.RELEASE);
}
@Override
public void execute(final ChronoDBDumpMetadata dumpMetadata) {
// nothing to do here
}
@Override
public Object execute(final ChronoIdentifier chronoIdentifier, final Object value) {
return ENTRY_UNCHANGED;
}
@Override
public void execute(final ChronoGraphInternal graph) {
log.info("Migrating ChronoGraph from " + graph.getStoredChronoGraphVersion().map(v -> v.toString()).orElse("<unknown>") + " to " + this.getToVersion() + ". This may take a while.");
// get the branches, children first
List<GraphBranch> branches = graph.getBranchManager().getBranches().stream()
.sorted(Comparator.comparing(GraphBranch::getBranchingTimestamp).reversed())
.collect(Collectors.toList());
int branchIndex = 0;
String logPrefix = "ChronoGraph Migration [" + this.getToVersion() + "]";
// migrate the old triggers
for (GraphBranch branch : branches) {
String branchName = branch.getName();
log.info(logPrefix + ": Starting migration of Branch '" + branchName + "' (" + branchIndex + " of " + branches.size() + ").");
long branchingTimestamp = branch.getBranchingTimestamp();
long branchNow = branch.getNow();
List<Long> commitTimestamps = Lists.newArrayList(graph.getCommitTimestampsBetween(branchName, branchingTimestamp, branchNow, Order.DESCENDING, true));
graph.getBackingDB().getDatebackManager().dateback(branchName, dateback -> {
int commitIndex = 0;
for (long commitTimestamp : commitTimestamps) {
log.info(logPrefix + " on Branch '" + branchName + "': migrating commit " + commitIndex + " of " + commitTimestamps.size() + " (" + new Date(commitTimestamp) + ")");
dateback.transformCommit(commitTimestamp, this::transformCommit);
commitIndex++;
}
log.info(logPrefix + ": Successfully migrated all " + commitTimestamps.size() + " commits on Branch '" + branchName + "', performing branch cleanup...");
});
branchIndex++;
}
log.info(logPrefix + " completed successfully on all " + branches.size() + " Branches");
}
public Map<QualifiedKey, Object> transformCommit(Map<QualifiedKey, Object> commitContents) {
Map<QualifiedKey, Object> resultMap = Maps.newHashMap();
for(Entry<QualifiedKey, Object> entry : commitContents.entrySet()){
QualifiedKey qKey = entry.getKey();
Object value = entry.getValue();
Object newValue = this.transformEntry(qKey, value);
resultMap.put(qKey, newValue);
}
return resultMap;
}
private Object transformEntry(QualifiedKey qKey, Object value){
if(!ChronoGraphConstants.KEYSPACE_VERTEX.equals(qKey.getKeyspace())){
// not in the vertex keyspace -> don't touch this.
return Dateback.UNCHANGED;
}
if(value == null){
// don't touch deletion markers
return Dateback.UNCHANGED;
}
if(value instanceof VertexRecord2 == false){
// not a vertex in the format we're looking for -> don't touch it
return Dateback.UNCHANGED;
}
VertexRecord2 record = (VertexRecord2)value;
// transform into the new format
// (note: the builder always generates the latest format as output).
return IVertexRecord.builder().fromRecord(record).build();
}
}
| 5,190 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecord.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record/VertexRecord.java | package org.chronos.chronograph.internal.impl.structure.record;
import static com.google.common.base.Preconditions.*;
import java.util.*;
import java.util.Map.Entry;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.dump.annotations.ChronosExternalizable;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.record.IEdgeTargetRecord;
import org.chronos.chronograph.api.structure.record.IVertexPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.impl.dumpformat.converter.VertexRecordConverter;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoEdgeImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexProperty;
import org.chronos.chronograph.internal.impl.structure.record2.VertexRecord2;
import org.chronos.chronograph.internal.impl.util.ChronoProxyUtil;
import org.chronos.common.annotation.PersistentClass;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
/**
* A {@link VertexRecord} is the immutable data core of a vertex that has been persisted to the database.
*
* <p>
* This is the class that will actually get serialized as the <code>value</code> in {@link ChronoDBTransaction#put(String, Object)}.
*
* <p>
* It is crucial that all instances of this class are to be treated as immutable after their creation, as these instances are potentially shared among threads due to caching mechanisms.
*
* <p>
* The {@link ChronoVertexImpl} implementation which typically wraps a {@link VertexRecord} is mutable and contains the transient (i.e. not yet persisted) state of the vertex that is specific for the transaction at hand. Upon calling {@link ChronoGraphTransaction#commit()}, the transient state in {@link ChronoVertexImpl} will be written into a new {@link VertexRecord} and persisted to the database with a new timestamp (but the same vertex id), provided that the vertex has indeed been modified by the user.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*
* @deprecated Replaced by {@link VertexRecord2}. We keep this class to be able to read older graphs.
*/
@Deprecated
@PersistentClass("kryo")
@ChronosExternalizable(converterClass = VertexRecordConverter.class)
public final class VertexRecord implements IVertexRecord {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
// note: the only reason why the fields in this class are not declared as "final" is because
// serialization mechanisms struggle with final fields. All fields are effectively final, and
// all of their contents are effectively immutable.
@SuppressWarnings("unused")
/** The id of this record. Unused because new instances are serialized as {@link VertexRecord2}. */
private String recordId;
@SuppressWarnings("unused")
/** The label of the vertex stored in this record. Unused because new instances are serialized as {@link VertexRecord2}. */
private String label;
@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"})
/** Mapping of edge labels to incoming edges, i.e. edges which specify this vertex as their in-vertex. Unused because new instances are serialized as {@link VertexRecord2}. */
private Map<String, Set<EdgeTargetRecord>> incomingEdges;
@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"})
/** Mapping of edge labels to outgoing edges, i.e. edges which specify this vertex as their out-vertex. Unused because new instances are serialized as {@link VertexRecord2}. */
private Map<String, Set<EdgeTargetRecord>> outgoingEdges;
@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"})
/** The set of vertex properties known on this vertex. Unused because new instances are serialized as {@link VertexRecord2}. */
private Set<VertexPropertyRecord> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected VertexRecord() {
// default constructor for serialization mechanism
}
@Override
public String getId() {
return this.recordId;
}
@Override
public String getLabel() {
return this.label;
}
@Override
public List<EdgeTargetRecordWithLabel> getIncomingEdges() {
if (this.incomingEdges == null || this.incomingEdges.isEmpty()) {
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(Entry<String, Set<EdgeTargetRecord>> entry : this.incomingEdges.entrySet()){
String label = entry.getKey();
Set<EdgeTargetRecord> edgeTargetRecords = entry.getValue();
for(EdgeTargetRecord record : edgeTargetRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public List<EdgeTargetRecordWithLabel> getIncomingEdges(String... labels){
if(labels == null || labels.length <= 0){
return getIncomingEdges();
}
if(this.incomingEdges == null || this.incomingEdges.isEmpty()){
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(String label : labels){
Set<EdgeTargetRecord> labelRecords = this.incomingEdges.get(label);
if(labelRecords == null){
continue;
}
for(EdgeTargetRecord record : labelRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public SetMultimap<String, IEdgeTargetRecord> getIncomingEdgesByLabel() {
if (this.incomingEdges == null || this.incomingEdges.isEmpty()) {
// return the empty multimap
return Multimaps.unmodifiableSetMultimap(HashMultimap.create());
}
// transform the internal data structure into a set multimap
SetMultimap<String, IEdgeTargetRecord> multimap = HashMultimap.create();
for (Entry<String, Set<EdgeTargetRecord>> entry : this.incomingEdges.entrySet()) {
String label = entry.getKey();
Set<EdgeTargetRecord> edges = entry.getValue();
for (EdgeTargetRecord edge : edges) {
multimap.put(label, edge);
}
}
return Multimaps.unmodifiableSetMultimap(multimap);
}
@Override
public List<EdgeTargetRecordWithLabel> getOutgoingEdges() {
if (this.outgoingEdges == null || this.outgoingEdges.isEmpty()) {
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(Entry<String, Set<EdgeTargetRecord>> entry : this.outgoingEdges.entrySet()){
String label = entry.getKey();
Set<EdgeTargetRecord> edgeTargetRecords = entry.getValue();
for(EdgeTargetRecord record : edgeTargetRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public List<EdgeTargetRecordWithLabel> getOutgoingEdges(String... labels){
if(labels == null || labels.length <= 0){
return getOutgoingEdges();
}
if(this.outgoingEdges == null || this.outgoingEdges.isEmpty()){
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(String label : labels){
Set<EdgeTargetRecord> labelRecords = this.outgoingEdges.get(label);
if(labelRecords == null){
continue;
}
for(EdgeTargetRecord record : labelRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public SetMultimap<String, IEdgeTargetRecord> getOutgoingEdgesByLabel() {
if (this.outgoingEdges == null || this.outgoingEdges.isEmpty()) {
// return the empty multimap
return Multimaps.unmodifiableSetMultimap(HashMultimap.create());
}
// transform the internal data structure into a set multimap
SetMultimap<String, IEdgeTargetRecord> multimap = HashMultimap.create();
for (Entry<String, Set<EdgeTargetRecord>> entry : this.outgoingEdges.entrySet()) {
String label = entry.getKey();
Set<EdgeTargetRecord> edges = entry.getValue();
for (EdgeTargetRecord edge : edges) {
multimap.put(label, edge);
}
}
return Multimaps.unmodifiableSetMultimap(multimap);
}
@Override
public Set<IVertexPropertyRecord> getProperties() {
if (this.properties == null || this.properties.isEmpty()) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(this.properties);
}
@Override
public VertexPropertyRecord getProperty(final String propertyKey) {
if(propertyKey == null || this.properties == null || this.properties.isEmpty()){
return null;
}
for(VertexPropertyRecord record : this.properties){
if(Objects.equals(record.getKey(), propertyKey)){
return record;
}
}
return null;
}
}
| 9,265 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeTargetRecord.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record/EdgeTargetRecord.java | package org.chronos.chronograph.internal.impl.structure.record;
import org.chronos.chronograph.api.structure.record.IEdgeTargetRecord;
import org.chronos.chronograph.internal.impl.structure.record2.EdgeTargetRecord2;
import org.chronos.common.annotation.PersistentClass;
/**
* @deprecated Use {@link EdgeTargetRecord2} instead. We keep this class to be able to read older graph formats.
*/
@PersistentClass("kryo")
@Deprecated
public class EdgeTargetRecord implements IEdgeTargetRecord {
@SuppressWarnings("unused")
/** The string representation of the {@link ChronoVertexId} of the vertex at the "other end" of the edge. Unused because new instances are of type {@link EdgeTargetRecord2}. */
private String otherEndVertexId;
@SuppressWarnings("unused")
/** The string representation of the {@link ChronoEdgeId} of the edge itself. Unused because new instances are of type {@link EdgeTargetRecord2}.*/
private String edgeId;
protected EdgeTargetRecord() {
// default constructor for serialization
}
@Override
public String getEdgeId() {
return this.edgeId;
}
@Override
public String getOtherEndVertexId() {
return this.otherEndVertexId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.edgeId == null ? 0 : this.edgeId.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;
}
EdgeTargetRecord other = (EdgeTargetRecord) obj;
if (this.edgeId == null) {
if (other.edgeId != null) {
return false;
}
} else if (!this.edgeId.equals(other.edgeId)) {
return false;
}
return true;
}
@Override
public String toString() {
return "EdgeTargetRecord[edgeId='" + this.edgeId + "', otherEndVertexId='" + this.otherEndVertexId + "']";
}
}
| 2,175 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexPropertyRecord.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record/VertexPropertyRecord.java | package org.chronos.chronograph.internal.impl.structure.record;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexPropertyRecord;
import org.chronos.chronograph.internal.impl.structure.record2.VertexPropertyRecord2;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.Map;
/**
* @deprecated Replaced by {@link VertexPropertyRecord2}. We keep this instance to be able to read older graphs.
*/
@Deprecated
@PersistentClass("kryo")
public final class VertexPropertyRecord extends PropertyRecord implements IVertexPropertyRecord {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
@SuppressWarnings("unused")
private String recordId;
@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"})
private Map<String, PropertyRecord> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected VertexPropertyRecord() {
// default constructor for serialization
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
public String getId() {
return this.recordId;
}
@Override
public Map<String, IPropertyRecord> getProperties() {
if (this.properties == null) {
return Collections.emptyMap();
}
return Collections.unmodifiableMap(this.properties);
}
}
| 1,948 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecord.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record/EdgeRecord.java | package org.chronos.chronograph.internal.impl.structure.record;
import static com.google.common.base.Preconditions.*;
import java.util.*;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.dump.annotations.ChronosExternalizable;
import org.chronos.chronograph.api.structure.record.IEdgeRecord;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.impl.dumpformat.converter.EdgeRecordConverter;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoEdgeImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoProperty;
import org.chronos.chronograph.internal.impl.structure.record2.EdgeTargetRecord2;
import org.chronos.common.annotation.PersistentClass;
import com.google.common.collect.Sets;
/**
* An {@link EdgeRecord} is the immutable data core of an edge that has been persisted to the database.
*
* <p>
* This is the class that will actually get serialized as the <code>value</code> in {@link ChronoDBTransaction#put(String, Object)}.
*
* <p>
* It is crucial that all instances of this class are to be treated as immutable after their creation, as these instances are potentially shared among threads due to caching mechanisms.
*
* <p>
* The {@link ChronoEdgeImpl} implementation which typically wraps an {@link EdgeRecord} is mutable and contains the transient (i.e. not yet persisted) state of the edge that is specific for the transaction at hand. Upon calling {@link ChronoGraphTransaction#commit()}, the transient state in {@link ChronoEdgeImpl} will be written into a new {@link EdgeRecord} and persisted to the database with a new timestamp (but the same vertex id), provided that the edge has indeed been modified by the user.
*
*
* <p>
* Note that an {@link EdgeRecord} only contains the id of <b>one</b> end of the edge. The reason is that the edge will always be serialized embedded in an {@link VertexRecord}, and the vertex record keeps track of the incoming and outgoing edges. Therefore, one 'end' of the edge is always given by the containment structure.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*
* @deprecated Replaced by {@link EdgeTargetRecord2}. We keep this class to be able to read older graph formats.
*/
@Deprecated
@PersistentClass("kryo")
@ChronosExternalizable(converterClass = EdgeRecordConverter.class)
public final class EdgeRecord implements IEdgeRecord {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
// note: the only reason why the fields in this class are not declared as "final" is because
// serialization mechanisms struggle with final fields. All fields are effectively final, and
// all of their contents are effectively immutable.
@SuppressWarnings("unused")
/** The id of this record, in string representation. */
private String recordId;
@SuppressWarnings("unused")
/** The label of the edge stored in this record. */
private String label;
@SuppressWarnings("unused")
/** The ID of the "In-Vertex", i.e. the target vertex, in string representation. */
private String inVertexId;
@SuppressWarnings("unused")
/** The ID of the "Out-Vertex", i.e. the source vertex, in string representation. */
private String outVertexId;
@SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"})
/** The set of properties set on this edge. */
private Set<PropertyRecord> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected EdgeRecord() {
// default constructor for serialization
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public String getId() {
return this.recordId;
}
@Override
public String getOutVertexId() {
return this.outVertexId;
}
@Override
public String getInVertexId() {
return this.inVertexId;
}
@Override
public String getLabel() {
return this.label;
}
@Override
public Set<IPropertyRecord> getProperties() {
if (this.properties == null) {
return Collections.emptySet();
} else {
return Collections.unmodifiableSet(this.properties);
}
}
@Override
public IPropertyRecord getProperty(final String propertyKey) {
if(propertyKey == null || this.properties == null || this.properties.isEmpty()){
return null;
}
for(PropertyRecord record : this.properties){
if(Objects.equals(record.getKey(), propertyKey)){
return record;
}
}
return null;
}
}
| 5,172 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeTargetRecordWithLabel.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record/EdgeTargetRecordWithLabel.java | package org.chronos.chronograph.internal.impl.structure.record;
import org.chronos.chronograph.api.structure.record.IEdgeTargetRecord;
import static com.google.common.base.Preconditions.*;
public class EdgeTargetRecordWithLabel {
private final IEdgeTargetRecord record;
private final String label;
public EdgeTargetRecordWithLabel(IEdgeTargetRecord record, String label){
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!");
this.record = record;
this.label = label;
}
public IEdgeTargetRecord getRecord() {
return record;
}
public String getLabel() {
return label;
}
}
| 774 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecord.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record/PropertyRecord.java | package org.chronos.chronograph.internal.impl.structure.record;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.internal.impl.structure.record2.PropertyRecord2;
import org.chronos.common.annotation.PersistentClass;
import org.chronos.common.serialization.KryoManager;
/**
*
* @deprecated Replaced by {@link PropertyRecord2}. We keep this class to be able to read older graphs.
*/
@Deprecated
@PersistentClass("kryo")
public class PropertyRecord implements IPropertyRecord {
@SuppressWarnings("unused")
private String key;
@SuppressWarnings("unused")
private byte[] value;
protected PropertyRecord() {
// default constructor for serialization
}
@Override
public String getKey() {
return this.key;
}
@Override
public Object getValue() {
return KryoManager.deserialize(this.value);
}
@Override
public Object getSerializationSafeValue() {
return this.getValue();
}
}
| 949 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexPropertyRecord2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/VertexPropertyRecord2.java | package org.chronos.chronograph.internal.impl.structure.record2;
import com.google.common.collect.Maps;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexPropertyRecord;
import org.chronos.chronograph.internal.impl.structure.record3.VertexPropertyRecord3;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import static com.google.common.base.Preconditions.*;
/**
* Represents the persistent state of a {@link VertexProperty}.
*
* <p>
* This class has been <b>deprecated</b> because it still uses an explicit {@link #getId() ID} for each
* vertex property, which is costly in practice and unnecessary. This class was replaced by {@link VertexPropertyRecord3}.
* We keep this class around for migration and backwards compatibility purposes.
* </p>
*
* @deprecated Use {@link VertexPropertyRecord3} instead. This class exists solely for migration and backwards compatibility purposes.
*
* @author martin.haeusler@txture io -- Deprecated this class in favour of {@link VertexPropertyRecord3}.
* @author martin.haeusler@txture.io -- Initial contribution and API
*/
@Deprecated
@PersistentClass("kryo")
public final class VertexPropertyRecord2 extends PropertyRecord2 implements IVertexPropertyRecord {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private String recordId;
private Map<String, PropertyRecord2> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected VertexPropertyRecord2() {
// default constructor for serialization
}
public VertexPropertyRecord2(final String recordId, final String key, final Object value, final Iterator<Property<Object>> properties) {
super(key, value);
checkNotNull(recordId, "Precondition violation - argument 'recordId' must not be NULL!");
checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!");
this.recordId = recordId;
if (properties.hasNext()) {
this.properties = Maps.newHashMap();
while (properties.hasNext()) {
Property<?> property = properties.next();
String pKey = property.key();
Object pValue = property.value();
PropertyRecord2 pRecord = new PropertyRecord2(pKey, pValue);
this.properties.put(pKey, pRecord);
}
}
}
public VertexPropertyRecord2(final String recordId, final String key, final Object value, final Map<String, PropertyRecord2> properties) {
super(key, value);
checkNotNull(recordId, "Precondition violation - argument 'recordId' must not be NULL!");
checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!");
this.recordId = recordId;
if (properties.isEmpty() == false) {
this.properties = Maps.newHashMap();
this.properties.putAll(properties);
}
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
public String getId() {
return this.recordId;
}
@Override
public Map<String, IPropertyRecord> getProperties() {
if (this.properties == null) {
return Collections.emptyMap();
}
return Collections.unmodifiableMap(this.properties);
}
}
| 3,903 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeTargetRecord2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/EdgeTargetRecord2.java | package org.chronos.chronograph.internal.impl.structure.record2;
import org.chronos.chronograph.api.structure.record.IEdgeTargetRecord;
import org.chronos.common.annotation.PersistentClass;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public class EdgeTargetRecord2 implements IEdgeTargetRecord {
/** The string representation of the {@link ChronoVertexId} of the vertex at the "other end" of the edge. */
private String otherEndVertexId;
/** The string representation of the {@link ChronoEdgeId} of the edge itself. */
private String edgeId;
protected EdgeTargetRecord2() {
// default constructor for serialization
}
public EdgeTargetRecord2(final String edgeId, final String otherEndVertexId) {
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
checkNotNull(otherEndVertexId, "Precondition violation - argument 'otherEndVertexId' must not be NULL!");
this.edgeId = edgeId;
this.otherEndVertexId = otherEndVertexId;
}
@Override
public String getEdgeId() {
return this.edgeId;
}
@Override
public String getOtherEndVertexId() {
return this.otherEndVertexId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.edgeId == null ? 0 : this.edgeId.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;
}
EdgeTargetRecord2 other = (EdgeTargetRecord2) obj;
if (this.edgeId == null) {
if (other.edgeId != null) {
return false;
}
} else if (!this.edgeId.equals(other.edgeId)) {
return false;
}
return true;
}
@Override
public String toString() {
return "EdgeTargetRecord[edgeId='" + this.edgeId + "', otherEndVertexId='" + this.otherEndVertexId + "']";
}
}
| 1,926 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecord2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/PropertyRecord2.java | package org.chronos.chronograph.internal.impl.structure.record2;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.internal.impl.structure.record2.valuerecords.PropertyRecordValue;
import org.chronos.common.annotation.PersistentClass;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public class PropertyRecord2 implements IPropertyRecord {
private String key;
private PropertyRecordValue<?> value;
protected PropertyRecord2() {
// default constructor for serialization
}
public PropertyRecord2(final String key, final Object value) {
checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!");
checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!");
this.key = key;
this.value = PropertyRecordValue.of(value);
}
@Override
public String getKey() {
return this.key;
}
@Override
public Object getValue() {
return this.value.getValue();
}
@Override
public Object getSerializationSafeValue() {
return this.value.getSerializationSafeValue();
}
}
| 1,111 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecord2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/VertexRecord2.java | package org.chronos.chronograph.internal.impl.structure.record2;
import com.google.common.collect.*;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.dump.annotations.ChronosExternalizable;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.record.IEdgeTargetRecord;
import org.chronos.chronograph.api.structure.record.IVertexPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.impl.dumpformat.converter.VertexRecordConverter;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoEdgeImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexProperty;
import org.chronos.chronograph.internal.impl.structure.record.EdgeTargetRecordWithLabel;
import org.chronos.chronograph.internal.impl.structure.record3.VertexPropertyRecord3;
import org.chronos.chronograph.internal.impl.structure.record3.VertexRecord3;
import org.chronos.chronograph.internal.impl.util.ChronoProxyUtil;
import org.chronos.common.annotation.PersistentClass;
import java.util.*;
import java.util.Map.Entry;
import static com.google.common.base.Preconditions.*;
/**
* A {@link VertexRecord2} is the immutable data core of a vertex that has been persisted to the database.
*
* <p>
* This is the class that will actually get serialized as the <code>value</code> in {@link ChronoDBTransaction#put(String, Object)}.
* </p>
*
* <p>
* It is crucial that all instances of this class are to be treated as immutable after their creation, as these instances are potentially shared among threads due to caching mechanisms.
* </p>
*
* <p>
* The {@link ChronoVertexImpl} implementation which typically wraps a {@link VertexRecord2} is mutable and contains the transient (i.e. not yet persisted) state of the vertex that is specific for the transaction at hand. Upon calling {@link ChronoGraphTransaction#commit()}, the transient state in {@link ChronoVertexImpl} will be written into a new {@link VertexRecord2} and persisted to the database with a new timestamp (but the same vertex id), provided that the vertex has indeed been modified by the user.
* </p>
*
* <p>
* This class has been deprecated in favour of {@link VertexRecord3}, due to the deprecation of {@link VertexPropertyRecord2} in favour of {@link VertexPropertyRecord3}.
* </p>
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
@Deprecated
@PersistentClass("kryo")
@ChronosExternalizable(converterClass = VertexRecordConverter.class)
public final class VertexRecord2 implements IVertexRecord {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
// note: the only reason why the fields in this class are not declared as "final" is because
// serialization mechanisms struggle with final fields. All fields are effectively final, and
// all of their contents are effectively immutable.
/** The id of this record. */
private String recordId;
/** The label of the vertex stored in this record. */
private String label;
/** Mapping of edge labels to incoming edges, i.e. edges which specify this vertex as their in-vertex. */
private Map<String, Set<EdgeTargetRecord2>> incomingEdges;
/** Mapping of edge labels to outgoing edges, i.e. edges which specify this vertex as their out-vertex. */
private Map<String, Set<EdgeTargetRecord2>> outgoingEdges;
/** The set of vertex properties known on this vertex. */
private Set<VertexPropertyRecord2> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected VertexRecord2() {
// default constructor for serialization mechanism
}
public VertexRecord2(final String recordId, final String label, final SetMultimap<String, ChronoEdge> inE,
final SetMultimap<String, ChronoEdge> outE, final Map<String, ChronoVertexProperty<?>> properties) {
checkNotNull(recordId, "Precondition violation - argument 'recordId' must not be NULL!");
checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!");
checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!");
this.recordId = recordId;
this.label = label;
if (inE != null && inE.isEmpty() == false) {
this.incomingEdges = Maps.newHashMap();
Iterator<ChronoEdge> inEIterator = Sets.newHashSet(inE.values()).iterator();
while (inEIterator.hasNext()) {
ChronoEdgeImpl edge = ChronoProxyUtil.resolveEdgeProxy(inEIterator.next());
// create the minimal "edge target" representation for this edge to store in this vertex
EdgeTargetRecord2 edgeTargetRecord = new EdgeTargetRecord2(edge.id(), edge.outVertex().id());
// retrieve the set of edge target records with the label in question
Set<EdgeTargetRecord2> edgeRecordsByLabel = this.incomingEdges.get(edge.label());
if (edgeRecordsByLabel == null) {
// this is the first edge with that label; add a new set to the map
edgeRecordsByLabel = Sets.newHashSet();
this.incomingEdges.put(edge.label(), edgeRecordsByLabel);
}
// store the edge target record by labels
edgeRecordsByLabel.add(edgeTargetRecord);
}
}
if (outE != null && outE.isEmpty() == false) {
this.outgoingEdges = Maps.newHashMap();
Iterator<ChronoEdge> outEIterator = Sets.newHashSet(outE.values()).iterator();
while (outEIterator.hasNext()) {
ChronoEdgeImpl edge = ChronoProxyUtil.resolveEdgeProxy(outEIterator.next());
// create the minimal "edge target" representation for this edge to store in this vertex
EdgeTargetRecord2 edgeTargetRecord = new EdgeTargetRecord2(edge.id(), edge.inVertex().id());
// retrieve the set of edge target records with the label in question
Set<EdgeTargetRecord2> edgeRecordsByLabel = this.outgoingEdges.get(edge.label());
if (edgeRecordsByLabel == null) {
// this is the first edge with that label; add a new set to the map
edgeRecordsByLabel = Sets.newHashSet();
this.outgoingEdges.put(edge.label(), edgeRecordsByLabel);
}
// store the edge target record by labels
edgeRecordsByLabel.add(edgeTargetRecord);
}
}
// create an immutable copy of the vertex properties
Collection<ChronoVertexProperty<?>> props = properties.values();
if (props.isEmpty() == false) {
// we have at least one property
this.properties = Sets.newHashSet();
for (ChronoVertexProperty<?> property : props) {
VertexPropertyRecord2 pRecord = (VertexPropertyRecord2)property.toRecord();
this.properties.add(pRecord);
}
}
}
public VertexRecord2(final String recordId, final String label, final SetMultimap<String, EdgeTargetRecord2> inE,
final SetMultimap<String, EdgeTargetRecord2> outE, final Set<VertexPropertyRecord2> properties) {
checkNotNull(recordId, "Precondition violation - argument 'recordId' must not be NULL!");
checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!");
checkNotNull(inE, "Precondition violation - argument 'inE' must not be NULL!");
checkNotNull(outE, "Precondition violation - argument 'outE' must not be NULL!");
checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!");
this.recordId = recordId;
this.label = label;
// convert incoming edges
if (inE.isEmpty() == false) {
this.incomingEdges = Maps.newHashMap();
for (Entry<String, Collection<EdgeTargetRecord2>> entry : inE.asMap().entrySet()) {
String edgeLabel = entry.getKey();
Collection<EdgeTargetRecord2> edgeRecords = entry.getValue();
if (edgeRecords.isEmpty()) {
continue;
}
Set<EdgeTargetRecord2> edgeRecordsByLabel = this.incomingEdges.get(edgeLabel);
if (edgeRecordsByLabel == null) {
// this is the first edge with that label; add a new set to the map
edgeRecordsByLabel = Sets.newHashSet();
this.incomingEdges.put(edgeLabel, edgeRecordsByLabel);
}
edgeRecordsByLabel.addAll(edgeRecords);
}
}
// convert outgoing edges
if (outE.isEmpty() == false) {
this.outgoingEdges = Maps.newHashMap();
for (Entry<String, Collection<EdgeTargetRecord2>> entry : outE.asMap().entrySet()) {
String edgeLabel = entry.getKey();
Collection<EdgeTargetRecord2> edgeRecords = entry.getValue();
if (edgeRecords.isEmpty()) {
continue;
}
Set<EdgeTargetRecord2> edgeRecordsByLabel = this.outgoingEdges.get(edgeLabel);
if (edgeRecordsByLabel == null) {
// this is the first edge with that label; add a new set to the map
edgeRecordsByLabel = Sets.newHashSet();
this.outgoingEdges.put(edgeLabel, edgeRecordsByLabel);
}
edgeRecordsByLabel.addAll(edgeRecords);
}
}
// convert vertex properties
if (properties.isEmpty() == false) {
this.properties = Sets.newHashSet();
this.properties.addAll(properties);
}
}
@Override
public String getId() {
return this.recordId;
}
@Override
public String getLabel() {
return this.label;
}
@Override
public List<EdgeTargetRecordWithLabel> getIncomingEdges() {
if (this.incomingEdges == null || this.incomingEdges.isEmpty()) {
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(Entry<String, Set<EdgeTargetRecord2>> entry : this.incomingEdges.entrySet()){
String label = entry.getKey();
Set<EdgeTargetRecord2> edgeTargetRecords = entry.getValue();
for(EdgeTargetRecord2 record : edgeTargetRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public List<EdgeTargetRecordWithLabel> getIncomingEdges(String... labels){
if(labels == null || labels.length <= 0){
return getIncomingEdges();
}
if(this.incomingEdges == null || this.incomingEdges.isEmpty()){
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(String label : labels){
Set<EdgeTargetRecord2> labelRecords = this.incomingEdges.get(label);
if(labelRecords == null){
continue;
}
for(EdgeTargetRecord2 record : labelRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public SetMultimap<String, IEdgeTargetRecord> getIncomingEdgesByLabel() {
if (this.incomingEdges == null || this.incomingEdges.isEmpty()) {
// return the empty multimap
return Multimaps.unmodifiableSetMultimap(HashMultimap.create());
}
// transform the internal data structure into a set multimap
SetMultimap<String, IEdgeTargetRecord> multimap = HashMultimap.create();
for (Entry<String, Set<EdgeTargetRecord2>> entry : this.incomingEdges.entrySet()) {
String label = entry.getKey();
Set<EdgeTargetRecord2> edges = entry.getValue();
for (EdgeTargetRecord2 edge : edges) {
multimap.put(label, edge);
}
}
return Multimaps.unmodifiableSetMultimap(multimap);
}
@Override
public List<EdgeTargetRecordWithLabel> getOutgoingEdges() {
if (this.outgoingEdges == null || this.outgoingEdges.isEmpty()) {
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(Entry<String, Set<EdgeTargetRecord2>> entry : this.outgoingEdges.entrySet()){
String label = entry.getKey();
Set<EdgeTargetRecord2> edgeTargetRecords = entry.getValue();
for(EdgeTargetRecord2 record : edgeTargetRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public List<EdgeTargetRecordWithLabel> getOutgoingEdges(String... labels){
if(labels == null || labels.length <= 0){
return getOutgoingEdges();
}
if(this.outgoingEdges == null || this.outgoingEdges.isEmpty()){
return Collections.emptyList();
}
List<EdgeTargetRecordWithLabel> resultList = new ArrayList<>();
for(String label : labels){
Set<EdgeTargetRecord2> labelRecords = this.outgoingEdges.get(label);
if(labelRecords == null){
continue;
}
for(EdgeTargetRecord2 record : labelRecords){
resultList.add(new EdgeTargetRecordWithLabel(record, label));
}
}
return resultList;
}
@Override
public SetMultimap<String, IEdgeTargetRecord> getOutgoingEdgesByLabel() {
if (this.outgoingEdges == null || this.outgoingEdges.isEmpty()) {
// return the empty multimap
return Multimaps.unmodifiableSetMultimap(HashMultimap.create());
}
// transform the internal data structure into a set multimap
SetMultimap<String, IEdgeTargetRecord> multimap = HashMultimap.create();
for (Entry<String, Set<EdgeTargetRecord2>> entry : this.outgoingEdges.entrySet()) {
String label = entry.getKey();
Set<EdgeTargetRecord2> edges = entry.getValue();
for (EdgeTargetRecord2 edge : edges) {
multimap.put(label, edge);
}
}
return Multimaps.unmodifiableSetMultimap(multimap);
}
@Override
public Set<IVertexPropertyRecord> getProperties() {
if (this.properties == null || this.properties.isEmpty()) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(this.properties);
}
@Override
public VertexPropertyRecord2 getProperty(final String propertyKey) {
if(propertyKey == null || this.properties == null || this.properties.isEmpty()){
return null;
}
for(VertexPropertyRecord2 record : this.properties){
if(Objects.equals(record.getKey(), propertyKey)){
return record;
}
}
return null;
}
}
| 13,932 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecord2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/EdgeRecord2.java | package org.chronos.chronograph.internal.impl.structure.record2;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.dump.annotations.ChronosExternalizable;
import org.chronos.chronograph.api.structure.record.IEdgeRecord;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.impl.dumpformat.converter.EdgeRecordConverter;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoEdgeImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoProperty;
import org.chronos.common.annotation.PersistentClass;
import java.util.*;
import static com.google.common.base.Preconditions.*;
/**
* An {@link EdgeRecord2} is the immutable data core of an edge that has been persisted to the database.
*
* <p>
* This is the class that will actually get serialized as the <code>value</code> in {@link ChronoDBTransaction#put(String, Object)}.
*
* <p>
* It is crucial that all instances of this class are to be treated as immutable after their creation, as these instances are potentially shared among threads due to caching mechanisms.
*
* <p>
* The {@link ChronoEdgeImpl} implementation which typically wraps an {@link EdgeRecord2} is mutable and contains the transient (i.e. not yet persisted) state of the edge that is specific for the transaction at hand. Upon calling {@link ChronoGraphTransaction#commit()}, the transient state in {@link ChronoEdgeImpl} will be written into a new {@link EdgeRecord2} and persisted to the database with a new timestamp (but the same vertex id), provided that the edge has indeed been modified by the user.
*
*
* <p>
* Note that an {@link EdgeRecord2} only contains the id of <b>one</b> end of the edge. The reason is that the edge will always be serialized embedded in an {@link VertexRecord2}, and the vertex record keeps track of the incoming and outgoing edges. Therefore, one 'end' of the edge is always given by the containment structure.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*
*/
@PersistentClass("kryo")
@ChronosExternalizable(converterClass = EdgeRecordConverter.class)
public final class EdgeRecord2 implements IEdgeRecord {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
// note: the only reason why the fields in this class are not declared as "final" is because
// serialization mechanisms struggle with final fields. All fields are effectively final, and
// all of their contents are effectively immutable.
/** The id of this record, in string representation. */
private String recordId;
/** The label of the edge stored in this record. */
private String label;
/** The ID of the "In-Vertex", i.e. the target vertex, in string representation. */
private String inVertexId;
/** The ID of the "Out-Vertex", i.e. the source vertex, in string representation. */
private String outVertexId;
/** The set of properties set on this edge. */
private Set<PropertyRecord2> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected EdgeRecord2() {
// default constructor for serialization
}
public EdgeRecord2(final String id, final String outVertexId, final String label, final String inVertexId,
final Map<String, ChronoProperty<?>> properties) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
checkNotNull(outVertexId, "Precondition violation - argument 'outVertexId' must not be NULL!");
ElementHelper.validateLabel(label);
checkNotNull(inVertexId, "Precondition violation - argument 'inVertexId' must not be NULL!");
checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!");
this.recordId = id;
this.outVertexId = outVertexId;
this.label = label;
this.inVertexId = inVertexId;
Collection<ChronoProperty<?>> props = properties.values();
if (props.isEmpty() == false) {
// we have at least one property
this.properties = Sets.newHashSet();
for (ChronoProperty<?> property : props) {
PropertyRecord2 pRecord = new PropertyRecord2(property.key(), property.value());
this.properties.add(pRecord);
}
}
}
public EdgeRecord2(final String id, final String outVertexId, final String label, final String inVertexId,
final Set<PropertyRecord2> properties) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
checkNotNull(outVertexId, "Precondition violation - argument 'outVertexId' must not be NULL!");
ElementHelper.validateLabel(label);
checkNotNull(inVertexId, "Precondition violation - argument 'inVertexId' must not be NULL!");
checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!");
this.recordId = id;
this.outVertexId = outVertexId;
this.label = label;
this.inVertexId = inVertexId;
if (properties.isEmpty() == false) {
this.properties = Sets.newHashSet();
this.properties.addAll(properties);
}
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public String getId() {
return this.recordId;
}
@Override
public String getOutVertexId() {
return this.outVertexId;
}
@Override
public String getInVertexId() {
return this.inVertexId;
}
@Override
public String getLabel() {
return this.label;
}
@Override
public Set<IPropertyRecord> getProperties() {
if (this.properties == null) {
return Collections.emptySet();
} else {
return Collections.unmodifiableSet(this.properties);
}
}
@Override
public IPropertyRecord getProperty(final String propertyKey) {
if(propertyKey == null || this.properties == null || this.properties.isEmpty()){
return null;
}
for(PropertyRecord2 record : this.properties){
if(Objects.equals(record.getKey(), propertyKey)){
return record;
}
}
return null;
}
}
| 6,618 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecordFloatSetValue.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/valuerecords/PropertyRecordFloatSetValue.java | package org.chronos.chronograph.internal.impl.structure.record2.valuerecords;
import com.google.common.collect.Sets;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public class PropertyRecordFloatSetValue implements PropertyRecordValue<Set<Float>> {
private Set<Float> values;
protected PropertyRecordFloatSetValue(){
// default constructor for kryo
}
public PropertyRecordFloatSetValue(Set<Float> values){
checkNotNull(values, "Precondition violation - argument 'values' must not be NULL!");
this.values = Sets.newHashSet(values);
}
@Override
public Set<Float> getValue() {
return Collections.unmodifiableSet(this.values);
}
@Override
public Set<Float> getSerializationSafeValue() {
return Sets.newHashSet(this.values);
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PropertyRecordFloatSetValue that = (PropertyRecordFloatSetValue) o;
return Objects.equals(values, that.values);
}
@Override
public int hashCode() {
return values != null ? values.hashCode() : 0;
}
@Override
public String toString() {
return this.values.toString();
}
}
| 1,499 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecordStringListValue.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/valuerecords/PropertyRecordStringListValue.java | package org.chronos.chronograph.internal.impl.structure.record2.valuerecords;
import com.google.common.collect.Lists;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public class PropertyRecordStringListValue implements PropertyRecordValue<List<String>> {
private List<String> values;
protected PropertyRecordStringListValue(){
// default constructor for kryo
}
public PropertyRecordStringListValue(List<String> values){
checkNotNull(values, "Precondition violation - argument 'values' must not be NULL!");
this.values = Lists.newArrayList(values);
}
@Override
public List<String> getValue() {
return Collections.unmodifiableList(this.values);
}
@Override
public List<String> getSerializationSafeValue() {
return Lists.newArrayList(this.values);
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PropertyRecordStringListValue that = (PropertyRecordStringListValue) o;
return Objects.equals(values, that.values);
}
@Override
public int hashCode() {
return values != null ? values.hashCode() : 0;
}
@Override
public String toString() {
return this.values.toString();
}
}
| 1,528 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecordDoubleListValue.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/valuerecords/PropertyRecordDoubleListValue.java | package org.chronos.chronograph.internal.impl.structure.record2.valuerecords;
import com.google.common.collect.Lists;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public class PropertyRecordDoubleListValue implements PropertyRecordValue<List<Double>> {
private List<Double> values;
protected PropertyRecordDoubleListValue(){
// default constructor for kryo
}
public PropertyRecordDoubleListValue(List<Double> values){
checkNotNull(values, "Precondition violation - argument 'values' must not be NULL!");
this.values = Lists.newArrayList(values);
}
@Override
public List<Double> getValue() {
return Collections.unmodifiableList(this.values);
}
@Override
public List<Double> getSerializationSafeValue() {
return Lists.newArrayList(this.values);
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PropertyRecordDoubleListValue that = (PropertyRecordDoubleListValue) o;
return Objects.equals(values, that.values);
}
@Override
public int hashCode() {
return values != null ? values.hashCode() : 0;
}
@Override
public String toString() {
return this.values.toString();
}
}
| 1,528 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecordShortArrayValue.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/valuerecords/PropertyRecordShortArrayValue.java | package org.chronos.chronograph.internal.impl.structure.record2.valuerecords;
import org.chronos.common.annotation.PersistentClass;
import java.util.Arrays;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public class PropertyRecordShortArrayValue implements PropertyRecordValue<short[]> {
private short[] array;
protected PropertyRecordShortArrayValue(){
// default constructor for kryo
}
public PropertyRecordShortArrayValue(short[] array){
checkNotNull(array, "Precondition violation - argument 'array' must not be NULL!");
this.array = new short[array.length];
System.arraycopy(array, 0, this.array, 0, array.length);
}
@Override
public short[] getValue() {
short[] outArray = new short[this.array.length];
System.arraycopy(this.array, 0, outArray, 0, array.length);
return outArray;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PropertyRecordShortArrayValue that = (PropertyRecordShortArrayValue) o;
return Arrays.equals(array, that.array);
}
@Override
public int hashCode() {
return Arrays.hashCode(array);
}
@Override
public String toString() {
return Arrays.toString(this.array);
}
}
| 1,431 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyRecordLongListValue.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/structure/record2/valuerecords/PropertyRecordLongListValue.java | package org.chronos.chronograph.internal.impl.structure.record2.valuerecords;
import com.google.common.collect.Lists;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public class PropertyRecordLongListValue implements PropertyRecordValue<List<Long>> {
private List<Long> values;
protected PropertyRecordLongListValue(){
// default constructor for kryo
}
public PropertyRecordLongListValue(List<Long> values){
checkNotNull(values, "Precondition violation - argument 'values' must not be NULL!");
this.values = Lists.newArrayList(values);
}
@Override
public List<Long> getValue() {
return Collections.unmodifiableList(this.values);
}
@Override
public List<Long> getSerializationSafeValue() {
return Lists.newArrayList(this.values);
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PropertyRecordLongListValue that = (PropertyRecordLongListValue) o;
return Objects.equals(values, that.values);
}
@Override
public int hashCode() {
return values != null ? values.hashCode() : 0;
}
@Override
public String toString() {
return this.values.toString();
}
}
| 1,508 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.