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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
AllChangedElementIdsAndTheirPreviousNeighborhoodStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/iterators/builder/states/AllChangedElementIdsAndTheirPreviousNeighborhoodStateImpl.java | package org.chronos.chronograph.internal.impl.iterators.builder.states;
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.iterators.states.AllChangedElementIdsAndTheirNeighborhoodState;
import org.chronos.chronograph.api.structure.ChronoGraph;
import java.util.Collections;
import java.util.Set;
public class AllChangedElementIdsAndTheirPreviousNeighborhoodStateImpl extends AllChangedElementIdsStateImpl implements AllChangedElementIdsAndTheirNeighborhoodState {
private Set<String> neighborhoodEdgeIds = null;
private Set<String> neighborhoodVertexIds = null;
public AllChangedElementIdsAndTheirPreviousNeighborhoodStateImpl(final ChronoGraph txGraph, String elementId, Class<? extends Element> elementType) {
super(txGraph, elementId, elementType);
if (this.isCurrentElementAVertex()) {
// a vertex can't have vertices in its direct neighborhood
this.neighborhoodVertexIds = Collections.emptySet();
} else {
// and edge can't have edges in its direct neighborhood
this.neighborhoodEdgeIds = Collections.emptySet();
}
}
@Override
public Set<String> getNeighborhoodVertexIds() {
return null;
}
@Override
public Set<String> getNeighborhoodEdgeIds() {
if (this.neighborhoodEdgeIds == null) {
this.neighborhoodEdgeIds = this.calculatPreviousNeighborhoodEdgeIds(this.getCurrentElementId());
}
return Collections.unmodifiableSet(this.neighborhoodEdgeIds);
}
@Override
public boolean isCurrentElementAVertex() {
return Vertex.class.isAssignableFrom(this.getCurrentElementClass());
}
@Override
public boolean isCurrentElementAnEdge() {
return Edge.class.isAssignableFrom(this.getCurrentElementClass());
}
}
| 1,960 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AllElementsStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/iterators/builder/states/AllElementsStateImpl.java | package org.chronos.chronograph.internal.impl.iterators.builder.states;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.chronos.chronograph.api.iterators.states.AllElementsState;
import org.chronos.chronograph.api.structure.ChronoGraph;
import static com.google.common.base.Preconditions.*;
public class AllElementsStateImpl extends GraphIteratorStateImpl implements AllElementsState {
private final Element element;
public AllElementsStateImpl(final ChronoGraph txGraph, Element element) {
super(txGraph);
checkNotNull(element, "Precondition violation - argument 'element' must not be NULL!");
this.element = element;
}
@Override
public Element getCurrentElement() {
return this.element;
}
}
| 774 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AllChangedVertexIdsAndTheirPreviousNeighborhoodStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/iterators/builder/states/AllChangedVertexIdsAndTheirPreviousNeighborhoodStateImpl.java | package org.chronos.chronograph.internal.impl.iterators.builder.states;
import org.chronos.chronograph.api.iterators.states.AllChangedVertexIdsAndTheirPreviousNeighborhoodState;
import org.chronos.chronograph.api.structure.ChronoGraph;
import java.util.Collections;
import java.util.Set;
public class AllChangedVertexIdsAndTheirPreviousNeighborhoodStateImpl extends AllChangedVertexIdsStateImpl implements AllChangedVertexIdsAndTheirPreviousNeighborhoodState {
private Set<String> neighborhoodEdgeIds = null;
public AllChangedVertexIdsAndTheirPreviousNeighborhoodStateImpl(final ChronoGraph txGraph, String vertexId) {
super(txGraph, vertexId);
}
@Override
public Set<String> getNeighborhoodEdgeIds() {
if (this.neighborhoodEdgeIds == null) {
this.neighborhoodEdgeIds = this.calculatPreviousNeighborhoodEdgeIds(this.getCurrentVertexId());
}
return Collections.unmodifiableSet(this.neighborhoodEdgeIds);
}
}
| 984 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AllChangedEdgeIdsStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/iterators/builder/states/AllChangedEdgeIdsStateImpl.java | package org.chronos.chronograph.internal.impl.iterators.builder.states;
import org.chronos.chronograph.api.iterators.states.AllChangedEdgeIdsState;
import org.chronos.chronograph.api.structure.ChronoGraph;
import static com.google.common.base.Preconditions.*;
public class AllChangedEdgeIdsStateImpl extends GraphIteratorStateImpl implements AllChangedEdgeIdsState {
private final String edgeId;
public AllChangedEdgeIdsStateImpl(final ChronoGraph txGraph, String edgeId) {
super(txGraph);
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
this.edgeId = edgeId;
}
@Override
public String getCurrentEdgeId() {
return this.edgeId;
}
@Override
public boolean isCurrentEdgeRemoved() {
return !this.getEdgeById(this.edgeId).isPresent();
}
}
| 856 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphIteratorStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/iterators/builder/states/GraphIteratorStateImpl.java | package org.chronos.chronograph.internal.impl.iterators.builder.states;
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.Vertex;
import org.chronos.chronograph.api.iterators.states.GraphIteratorState;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.impl.transaction.threaded.ChronoThreadedTransactionGraph;
import java.util.Iterator;
import java.util.Set;
import static com.google.common.base.Preconditions.*;
public class GraphIteratorStateImpl implements GraphIteratorState {
private final ChronoGraph txGraph;
public GraphIteratorStateImpl(ChronoGraph txGraph) {
checkNotNull(txGraph, "Precondition violation - argument 'txGraph' must not be NULL!");
checkArgument(txGraph.tx().isOpen(), "Precondition violation - argument 'txGraph' must have an open transaction!");
this.txGraph = txGraph;
}
@Override
public ChronoGraph getTransactionGraph() {
return this.txGraph;
}
protected Set<String> calculatPreviousNeighborhoodEdgeIds(String vertexId) {
Set<String> resultSet = Sets.newHashSet();
// add the previous neighborhood (if any)
String branch = this.getTransactionGraph().tx().getCurrentTransaction().getBranchName();
Long previousCommit = this.getPreviousCommitOnVertex(this.getTransactionGraph(), vertexId);
if (previousCommit != null) {
try(ChronoGraph previousTxGraph = this.getTransactionGraph().tx().createThreadedTx(branch, previousCommit)) {
Iterator<Vertex> previousVertices = previousTxGraph.vertices(vertexId);
if (previousVertices.hasNext()) {
Vertex previousVertex = Iterators.getOnlyElement(previousVertices);
previousVertex.edges(Direction.BOTH).forEachRemaining(e -> resultSet.add((String) e.id()));
}
}
}
return resultSet;
}
protected Long getPreviousCommitOnVertex(ChronoGraph graph, String vertexId) {
long txTimestamp = graph.tx().getCurrentTransaction().getTimestamp();
Iterator<Long> historyIterator = graph.getVertexHistory(vertexId);
while (historyIterator.hasNext()) {
long timestamp = historyIterator.next();
if (timestamp < txTimestamp) {
return timestamp;
}
}
return null;
}
}
| 2,540 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AllVerticesStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/iterators/builder/states/AllVerticesStateImpl.java | package org.chronos.chronograph.internal.impl.iterators.builder.states;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.iterators.states.AllVerticesState;
import org.chronos.chronograph.api.structure.ChronoGraph;
import static com.google.common.base.Preconditions.*;
public class AllVerticesStateImpl extends GraphIteratorStateImpl implements AllVerticesState {
private final Vertex vertex;
public AllVerticesStateImpl(final ChronoGraph txGraph, Vertex vertex) {
super(txGraph);
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
this.vertex = vertex;
}
@Override
public Vertex getCurrentVertex() {
return this.vertex;
}
}
| 761 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphConfigurationImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/configuration/ChronoGraphConfigurationImpl.java | package org.chronos.chronograph.internal.impl.configuration;
import org.chronos.chronograph.api.transaction.AllEdgesIterationHandler;
import org.chronos.chronograph.api.transaction.AllVerticesIterationHandler;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.common.configuration.AbstractConfiguration;
import org.chronos.common.configuration.annotation.Namespace;
import org.chronos.common.configuration.annotation.Parameter;
import jakarta.annotation.PostConstruct;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
@Namespace(ChronoGraphConfiguration.NAMESPACE)
public class ChronoGraphConfigurationImpl extends AbstractConfiguration implements ChronoGraphConfiguration {
// =================================================================================================================
// FIELDS
// =================================================================================================================
@Parameter(key = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD)
private boolean checkIdExistenceOnAdd = true;
@Parameter(key = ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN)
private boolean txAutoOpenEnabled = true;
@Parameter(key = ChronoGraphConfiguration.TRANSACTION_CHECK_GRAPH_INVARIANT)
private boolean graphInvariantCheckActive = false;
@Parameter(key = ChronoGraphConfiguration.ALL_VERTICES_ITERATION_HANDLER_CLASS_NAME, optional = true)
private String allVerticesIterationHandlerClassName = null;
@Parameter(key = ChronoGraphConfiguration.ALL_EDGES_ITERATION_HANDLER_CLASS_NAME, optional = true)
private String allEdgesIterationHandlerClassName = null;
@Parameter(key = ChronoGraphConfiguration.USE_STATIC_GROOVY_COMPILATION_CACHE, optional = true)
private boolean useStaticGroovyCompilationCache = false;
@Parameter(key = ChronoGraphConfiguration.USE_SECONDARY_INDEX_FOR_VALUE_MAP_STEP, optional = true)
private boolean useSecondaryIndexForGremlinValueMapStep = false;
@Parameter(key = ChronoGraphConfiguration.USE_SECONDARY_INDEX_FOR_VALUES_STEP, optional = true)
private boolean useSecondaryIndexForGremlinValuesStep = false;
// =================================================================================================================
// CACHE
// =================================================================================================================
private AllVerticesIterationHandler allVerticesIterationHandler;
private AllEdgesIterationHandler allEdgesIterationHandler;
// =================================================================================================================
// INIT
// =================================================================================================================
@PostConstruct
private void init() {
if (this.allVerticesIterationHandlerClassName != null && this.allVerticesIterationHandlerClassName.trim().isEmpty() == false) {
Class<?> handlerClass;
try {
handlerClass = Class.forName(this.allVerticesIterationHandlerClassName.trim());
} catch (ClassNotFoundException | NoClassDefFoundError e) {
throw new IllegalArgumentException("Failed to instantiate AllVerticesIterationHandler class '" + this.allVerticesIterationHandlerClassName + "'!", e);
}
if (!AllVerticesIterationHandler.class.isAssignableFrom(handlerClass)) {
throw new IllegalArgumentException("The given AllVerticesIterationHandler class '" + this.allVerticesIterationHandlerClassName + "' is not a subclass of " + AllVerticesIterationHandler.class.getSimpleName() + "!");
}
try {
Constructor<?> constructor = handlerClass.getConstructor();
constructor.setAccessible(true);
this.allVerticesIterationHandler = (AllVerticesIterationHandler) constructor.newInstance();
} catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
throw new IllegalArgumentException("Failed to instantiate AllVerticesIterationHandler class '" + this.allVerticesIterationHandlerClassName + "' - does it have a default constructor?", e);
}
}
if (this.allEdgesIterationHandlerClassName != null && this.allEdgesIterationHandlerClassName.trim().isEmpty() == false) {
Class<?> handlerClass;
try {
handlerClass = Class.forName(this.allEdgesIterationHandlerClassName.trim());
} catch (ClassNotFoundException | NoClassDefFoundError e) {
throw new IllegalArgumentException("Failed to instantiate AllEdgesIterationHandler class '" + this.allEdgesIterationHandlerClassName + "'!", e);
}
if (!AllEdgesIterationHandler.class.isAssignableFrom(handlerClass)) {
throw new IllegalArgumentException("The given AllEdgesIterationHandler class '" + this.allEdgesIterationHandlerClassName + "' is not a subclass of " + AllEdgesIterationHandler.class.getSimpleName() + "!");
}
try {
Constructor<?> constructor = handlerClass.getConstructor();
constructor.setAccessible(true);
this.allEdgesIterationHandler = (AllEdgesIterationHandler) constructor.newInstance();
} catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
throw new IllegalArgumentException("Failed to instantiate AllEdgesIterationHandler class '" + this.allEdgesIterationHandlerClassName + "' - does it have a default constructor?", e);
}
}
}
// =================================================================================================================
// GETTERS
// =================================================================================================================
@Override
public boolean isCheckIdExistenceOnAddEnabled() {
return this.checkIdExistenceOnAdd;
}
@Override
public boolean isTransactionAutoOpenEnabled() {
return this.txAutoOpenEnabled;
}
@Override
public boolean isGraphInvariantCheckActive() {
return this.graphInvariantCheckActive;
}
@Override
public AllVerticesIterationHandler getAllVerticesIterationHandler() {
return this.allVerticesIterationHandler;
}
@Override
public AllEdgesIterationHandler getAllEdgesIterationHandler() {
return this.allEdgesIterationHandler;
}
@Override
public boolean isUseStaticGroovyCompilationCache() {
return this.useStaticGroovyCompilationCache;
}
@Override
public boolean isUseSecondaryIndexForGremlinValueMapStep() {
return this.useSecondaryIndexForGremlinValueMapStep;
}
@Override
public boolean isUseSecondaryIndexForGremlinValuesStep() {
return this.useSecondaryIndexForGremlinValuesStep;
}
}
| 7,171 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoStringCompare.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/query/ChronoStringCompare.java | package org.chronos.chronograph.internal.impl.query;
import java.util.function.BiPredicate;
import java.util.regex.Pattern;
public enum ChronoStringCompare implements BiPredicate<Object, Object> {
STRING_EQUALS_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::compareAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_EQUALS_IGNORE_CASE;
}
private boolean compareAtomic(Object left, Object right) {
if (left instanceof String == false) {
return false;
}
if (right instanceof String == false) {
return false;
}
String sLeft = (String) left;
String sRight = (String) right;
return sLeft.equalsIgnoreCase(sRight);
}
},
STRING_NOT_EQUALS_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_EQUALS_IGNORE_CASE.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_EQUALS_IGNORE_CASE;
}
},
STRING_STARTS_WITH {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_STARTS_WITH;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return string1.startsWith(string2);
}
},
STRING_NOT_STARTS_WITH {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_STARTS_WITH.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_STARTS_WITH;
}
},
STRING_STARTS_WITH_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_STARTS_WITH_IGNORE_CASE;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return string1.toLowerCase().startsWith(string2.toLowerCase());
}
},
STRING_NOT_STARTS_WITH_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_STARTS_WITH_IGNORE_CASE.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_STARTS_WITH_IGNORE_CASE;
}
},
STRING_ENDS_WITH {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_ENDS_WITH;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return string1.endsWith(string2);
}
},
STRING_NOT_ENDS_WITH {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_ENDS_WITH.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_ENDS_WITH;
}
},
STRING_ENDS_WITH_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_ENDS_WITH_IGNORE_CASE;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return string1.toLowerCase().endsWith(string2.toLowerCase());
}
},
STRING_NOT_ENDS_WITH_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_ENDS_WITH_IGNORE_CASE.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_ENDS_WITH_IGNORE_CASE;
}
},
STRING_CONTAINS {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_CONTAINS;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return string1.contains(string2);
}
},
STRING_NOT_CONTAINS {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_CONTAINS.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_CONTAINS;
}
},
STRING_CONTAINS_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_CONTAINS_IGNORE_CASE;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return string1.toLowerCase().contains(string2.toLowerCase());
}
},
STRING_NOT_CONTAINS_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_CONTAINS_IGNORE_CASE.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_CONTAINS_IGNORE_CASE;
}
},
STRING_MATCHES_REGEX {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_MATCHES_REGEX;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return string1.matches(string2);
}
},
STRING_NOT_MATCHES_REGEX {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_MATCHES_REGEX.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_MATCHES_REGEX;
}
},
STRING_MATCHES_REGEX_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::testAtomic);
}
@Override
public ChronoStringCompare negate() {
return STRING_NOT_MATCHES_REGEX_IGNORE_CASE;
}
private boolean testAtomic(final Object o, final Object o2) {
if (o == null || o2 == null) {
return false;
}
if (!(o instanceof String) || !(o2 instanceof String)) {
return false;
}
String string1 = (String) o;
String string2 = (String) o2;
return Pattern.compile(string2, Pattern.CASE_INSENSITIVE).matcher(string1).matches();
}
},
STRING_NOT_MATCHES_REGEX_IGNORE_CASE {
@Override
public boolean test(final Object o, final Object o2) {
return !STRING_MATCHES_REGEX_IGNORE_CASE.test(o, o2);
}
@Override
public ChronoStringCompare negate() {
return STRING_MATCHES_REGEX_IGNORE_CASE;
}
};
public abstract ChronoStringCompare negate();
}
| 9,820 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoCompareUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/query/ChronoCompareUtil.java | package org.chronos.chronograph.internal.impl.query;
import com.google.common.collect.Iterables;
import java.util.Collection;
import java.util.Collections;
import java.util.function.BiPredicate;
public class ChronoCompareUtil {
public static boolean compare(Object left, Object right, BiPredicate<Object, Object> compareAtomic){
Collection<Object> leftCollection = liftToCollection(left);
Collection<Object> rightCollection = liftToCollection(right);
if(leftCollection.isEmpty() || rightCollection.isEmpty()){
// NULLs or empty collections never lead to any matches.
return false;
}
if(leftCollection.size() == 1){
Object onlyLeft = Iterables.getOnlyElement(leftCollection);
if(rightCollection.size() == 1){
// single-vs-single: compare directly
Object onlyRight = Iterables.getOnlyElement(rightCollection);
return compareAtomic.test(onlyLeft, onlyRight);
}else{
// single-vs-multi: never match
return false;
}
}else {
if(rightCollection.size() == 1){
// multi-vs-single: evaluate all entries
Object onlyRight = Iterables.getOnlyElement(rightCollection);
for(Object entry : leftCollection){
if(compareAtomic.test(entry, onlyRight)){
return true;
}
}
return false;
}else{
// multi-vs-multi:
return new MultiCompare(compareAtomic).test(leftCollection, rightCollection);
}
}
}
@SuppressWarnings("unchecked")
public static Collection<Object> liftToCollection(Object value){
if(value == null){
return Collections.emptyList();
}
if(value instanceof Collection){
return (Collection<Object>)value;
}else{
return Collections.singletonList(value);
}
}
private static class MultiCompare implements BiPredicate<Collection<Object>, Collection<Object>> {
private BiPredicate<Object, Object> compareAtomic;
public MultiCompare(BiPredicate<Object, Object> compareAtomic){
this.compareAtomic = compareAtomic;
}
@Override
public boolean test(final Collection<Object> left, final Collection<Object> right) {
for(Object leftElement : left){
if(right.stream().noneMatch(rightElement -> this.compareAtomic.test(leftElement, rightElement))){
return false;
}
}
return true;
}
}
}
| 2,740 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoCompare.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/query/ChronoCompare.java | package org.chronos.chronograph.internal.impl.query;
import org.apache.tinkerpop.gremlin.util.NumberHelper;
import java.util.Collection;
import java.util.Objects;
import java.util.function.BiPredicate;
public enum ChronoCompare implements BiPredicate<Object, Object> {
EQ {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::compareAtomic);
}
@Override
public ChronoCompare negate() {
return NEQ;
}
private boolean compareAtomic(Object left, Object right){
if(left == null || right == null){
return false;
}
return Objects.equals(left, right);
}
},
NEQ {
@Override
public boolean test(final Object o, final Object o2) {
return !EQ.test(o, o2);
}
@Override
public ChronoCompare negate() {
return EQ;
}
},
GT {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::compareAtomic);
}
@Override
public ChronoCompare negate() {
return LTE;
}
@SuppressWarnings({"unchecked"})
private boolean compareAtomic(Object first, Object second){
if(first == null || second == null){
return false;
}
if(first instanceof Number && second instanceof Number){
return NumberHelper.compare((Number) first, (Number) second) > 0;
}
if(first instanceof Comparable){
return ((Comparable<Object>)first).compareTo(second) > 0;
}
return false;
}
},
GTE {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::compareAtomic);
}
@Override
public ChronoCompare negate() {
return LT;
}
@SuppressWarnings({"unchecked"})
private boolean compareAtomic(Object first, Object second){
if(first == null || second == null){
return false;
}
if(first instanceof Number && second instanceof Number){
return NumberHelper.compare((Number) first, (Number) second) >= 0;
}
if(first instanceof Comparable){
return ((Comparable<Object>)first).compareTo(second) >= 0;
}
return false;
}
},
LT {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::compareAtomic);
}
@Override
public ChronoCompare negate() {
return GTE;
}
@SuppressWarnings({"unchecked"})
private boolean compareAtomic(Object first, Object second){
if(first == null || second == null){
return false;
}
if(first instanceof Number && second instanceof Number){
return NumberHelper.compare((Number) first, (Number) second) < 0;
}
if(first instanceof Comparable){
return ((Comparable<Object>)first).compareTo(second) < 0;
}
return false;
}
},
LTE {
@Override
public boolean test(final Object o, final Object o2) {
return ChronoCompareUtil.compare(o, o2, this::compareAtomic);
}
@Override
public ChronoCompare negate() {
return GT;
}
@SuppressWarnings({"unchecked"})
private boolean compareAtomic(Object first, Object second){
if(first == null || second == null){
return false;
}
if(first instanceof Number && second instanceof Number){
return NumberHelper.compare((Number) first, (Number) second) <= 0;
}
if(first instanceof Comparable){
return ((Comparable<Object>)first).compareTo(second) <= 0;
}
return false;
}
},
WITHIN{
@Override
public boolean test(final Object o, final Object o2) {
if(o == null || o2 == null){
return false;
}
Collection<Object> left = ChronoCompareUtil.liftToCollection(o);
Collection<Object> right = ChronoCompareUtil.liftToCollection(o2);
for(Object leftElement : left){
if(right.contains(leftElement)){
return true;
}
}
return false;
}
@Override
public ChronoCompare negate() {
return WITHOUT;
}
},
WITHOUT{
@Override
public boolean test(final Object o, final Object o2) {
return !WITHIN.test(o, o2);
}
@Override
public ChronoCompare negate() {
return WITHIN;
}
};
public abstract ChronoCompare negate();
}
| 5,194 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphStatisticsManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/statistics/ChronoGraphStatisticsManagerImpl.java | package org.chronos.chronograph.internal.impl.statistics;
import org.chronos.chronodb.api.BranchHeadStatistics;
import org.chronos.chronograph.api.statistics.ChronoGraphStatisticsManager;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphStatisticsManagerImpl implements ChronoGraphStatisticsManager {
private final ChronoGraphInternal graph;
public ChronoGraphStatisticsManagerImpl(ChronoGraphInternal graph){
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.graph = graph;
}
@Override
public BranchHeadStatistics getBranchHeadStatistics(final String branchName) {
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
return this.graph.getBackingDB().getStatisticsManager().getBranchHeadStatistics(branchName);
}
}
| 963 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphStep.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/optimizer/step/ChronoGraphStep.java | package org.chronos.chronograph.internal.impl.optimizer.step;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.collect.Streams;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.builder.query.FinalizableQueryBuilder;
import org.chronos.chronodb.api.builder.query.QueryBuilder;
import org.chronos.chronodb.api.key.QualifiedKey;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
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.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.transaction.GraphTransactionContextInternal;
import org.chronos.chronograph.internal.impl.transaction.ElementLoadMode;
import org.chronos.chronograph.internal.impl.util.ChronoGraphStepUtil;
import org.chronos.chronograph.internal.impl.util.ChronoGraphTraversalUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class ChronoGraphStep<S, E extends Element> extends GraphStep<S, E> {
private final List<FilterStep<E>> indexableSubsteps = Lists.newArrayList();
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
public ChronoGraphStep(final GraphStep<S, E> originalStep, final List<FilterStep<E>> indexableSteps) {
super(originalStep.getTraversal(), originalStep.getReturnClass(), originalStep.isStartStep(),
originalStep.getIds());
// copy the labels of the original step
originalStep.getLabels().forEach(this::addLabel);
// add the sub-steps...
this.indexableSubsteps.addAll(indexableSteps);
// ... and copy their labels
indexableSteps.forEach(subStep -> subStep.getLabels().forEach(this::addLabel));
// set the result iterator supplier function (i.e. the function that calculates the result of this step).
// We have to do this computation eagerly here because the step strategy holds the read lock on the index
// while this object is created.
List<E> results = this.getResultList();
this.setIteratorSupplier(results::iterator);
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public String toString() {
// according to TinkerGraph reference implementation
if (this.indexableSubsteps.isEmpty()) {
return super.toString();
} else {
return 0 == this.ids.length
? StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(), this.indexableSubsteps)
: StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(),
Arrays.toString(this.ids), this.indexableSubsteps);
}
}
// =====================================================================================================================
// ITERATION & STEP RESULT CALCULATION
// =====================================================================================================================
@SuppressWarnings("unchecked")
private List<E> getResultList() {
if (Vertex.class.isAssignableFrom(this.returnClass)) {
return (List<E>) this.getResultVertices();
} else {
return (List<E>) this.getResultEdges();
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
private List<Vertex> getResultVertices() {
ChronoGraph graph = ChronoGraphTraversalUtil.getChronoGraph(this.getTraversal());
// ensure that we have an open transaction...
graph.tx().readWrite();
// ... and retrieve it
ChronoGraphTransaction tx = ChronoGraphTraversalUtil.getTransaction(this.getTraversal());
Set<ChronoGraphIndex> cleanIndices = graph.getIndexManagerOnBranch(tx.getBranchName()).getCleanIndicesAtTimestamp(tx.getTimestamp());
// start the query builder
ChronoDBTransaction dbTx = tx.getBackingDBTransaction();
QueryBuilder queryBuilder = dbTx.find().inKeyspace(ChronoGraphConstants.KEYSPACE_VERTEX);
Set<Vertex> verticesFromIndexQuery = getVerticesFromChronoDB(tx, cleanIndices, queryBuilder);
// consider the transaction context
GraphTransactionContextInternal context = (GraphTransactionContextInternal) tx.getContext();
if (!context.isDirty()) {
// return the index query result directly
return Lists.newArrayList(verticesFromIndexQuery);
}
// the context is dirty; we have to run the predicate over all modified vertices as well
Predicate<Vertex> predicate = (Predicate<Vertex>) ChronoGraphTraversalUtil.filterStepsToPredicate(this.indexableSubsteps);
Set<String> queryProperties = ChronoGraphTraversalUtil.getHasPropertyKeys(this.indexableSubsteps);
Set<Vertex> combinedVertices = Sets.newHashSet(verticesFromIndexQuery);
combinedVertices.addAll(context.getVerticesWithModificationsOnProperties(queryProperties));
return combinedVertices.stream()
// eliminate all vertices which have been removed in this transaction
.filter(v -> ((ChronoVertex) v).isRemoved() == false)
.filter(predicate)
.collect(Collectors.toList());
}
@NotNull
@SuppressWarnings("unchecked")
private Set<Vertex> getVerticesFromChronoDB(final ChronoGraphTransaction tx, final Set<ChronoGraphIndex> cleanIndices, final QueryBuilder queryBuilder) {
List<FilterStep<E>> chronoDbFilters = this.indexableSubsteps;
chronoDbFilters = ChronoGraphStepUtil.optimizeFilters(chronoDbFilters);
// for efficiency, it's better NOT to pass any negated filters down to ChronoDB. The reason is
// that ChronoDB needs to perform an intersection with the primary index, as all indices are
// sparse. The better option is to let ChronoDB evaluate the non-negated filters, and we apply
// the rest of the filters in-memory.
List<FilterStep<E>> negatedFilters = chronoDbFilters.stream().filter(ChronoGraphStepUtil::isNegated).collect(Collectors.toList());
List<FilterStep<E>> nonNegatedFilters = chronoDbFilters.stream().filter(step -> !ChronoGraphStepUtil.isNegated(step)).collect(Collectors.toList());
Set<Vertex> verticesFromIndexQuery;
if (nonNegatedFilters.isEmpty()) {
// all filters are negated, this query will be slow
// there's no reason to run ALL negated queries against the index, it will only
// result in needless checks against the primary index, which will slow things down. Only
// run ONE of the negated queries on the index, and the rest in-memory.
FilterStep<E> firstFilter = Iterables.getFirst(negatedFilters, null);
List<FilterStep<E>> indexQueries = Lists.newArrayList();
indexQueries.add(firstFilter);
FinalizableQueryBuilder finalizableQueryBuilder = ChronoGraphTraversalUtil.toChronoDBQuery(
cleanIndices,
indexQueries,
queryBuilder,
ChronoGraphTraversalUtil::createIndexKeyForVertexProperty
);
Iterator<QualifiedKey> keys = finalizableQueryBuilder.getKeys();
verticesFromIndexQuery = Streams.stream(keys)
.map(QualifiedKey::getKey)
.map(id -> tx.getVertexOrNull(id, ElementLoadMode.LAZY))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// there is a slight difference in query semantics between ChronoDB and Gremlin when it comes to NEGATED predicates:
// - In ChronoDB, a key is returned if its value matches the negated predicate. Note that "null" matches many negated predicates.
// - In Gremlin, a graph element is returned if it HAS a value AND that value matches the negated predicate.
// We therefore need to apply a post-processing here, checking that the vertices indeed have the requested property keys.
Predicate<Vertex> predicate = (Predicate<Vertex>) ChronoGraphTraversalUtil.filterStepsToPredicate(negatedFilters);
verticesFromIndexQuery = verticesFromIndexQuery.stream().filter(predicate).collect(Collectors.toSet());
} else {
// run the non-negated filters on ChronoDB, apply the rest in-memory
FinalizableQueryBuilder finalizableQueryBuilder = ChronoGraphTraversalUtil.toChronoDBQuery(
cleanIndices,
nonNegatedFilters,
queryBuilder,
ChronoGraphTraversalUtil::createIndexKeyForVertexProperty
);
Iterator<QualifiedKey> keys = finalizableQueryBuilder.getKeys();
verticesFromIndexQuery = Streams.stream(keys)
.map(QualifiedKey::getKey)
.map(id -> tx.getVertexOrNull(id, ElementLoadMode.LAZY))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// check if we have negated filters
if (!negatedFilters.isEmpty()) {
Predicate<Vertex> predicate = (Predicate<Vertex>) ChronoGraphTraversalUtil.filterStepsToPredicate(negatedFilters);
verticesFromIndexQuery = verticesFromIndexQuery.stream().filter(predicate).collect(Collectors.toSet());
}
}
return verticesFromIndexQuery;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private List<Edge> getResultEdges() {
ChronoGraph graph = ChronoGraphTraversalUtil.getChronoGraph(this.getTraversal());
// ensure that we have an open transaction...
graph.tx().readWrite();
// ... and retrieve it
ChronoGraphTransaction tx = ChronoGraphTraversalUtil.getTransaction(this.getTraversal());
Set<ChronoGraphIndex> cleanIndices = graph.getIndexManagerOnBranch(tx.getBranchName()).getCleanIndicesAtTimestamp(tx.getTimestamp());
// start the query builder
ChronoDBTransaction dbTx = tx.getBackingDBTransaction();
QueryBuilder queryBuilder = dbTx.find().inKeyspace(ChronoGraphConstants.KEYSPACE_EDGE);
Set<Edge> edgesFromIndexQuery = getEdgesFromChronoDB(tx, cleanIndices, queryBuilder);
// consider the transaction context
GraphTransactionContextInternal context = (GraphTransactionContextInternal) tx.getContext();
if (!context.isDirty()) {
// return the index query result directly
return Lists.newArrayList(edgesFromIndexQuery);
}
// the context is dirty; we have to run the predicate over all modified vertices as well
Predicate<Edge> predicate = (Predicate<Edge>) ChronoGraphTraversalUtil.filterStepsToPredicate(this.indexableSubsteps);
Set<String> queryProperties = ChronoGraphTraversalUtil.getHasPropertyKeys(this.indexableSubsteps);
Set<Edge> combinedEdges = Sets.newHashSet(edgesFromIndexQuery);
combinedEdges.addAll(context.getEdgesWithModificationsOnProperties(queryProperties));
return combinedEdges.stream()
// eliminate all vertices which have been removed in this transaction
.filter(v -> ((ChronoEdge) v).isRemoved() == false)
.filter(predicate)
.collect(Collectors.toList());
}
@NotNull
@SuppressWarnings("unchecked")
private Set<Edge> getEdgesFromChronoDB(final ChronoGraphTransaction tx, final Set<ChronoGraphIndex> cleanIndices, final QueryBuilder queryBuilder) {
List<FilterStep<E>> chronoDbFilters = this.indexableSubsteps;
chronoDbFilters = ChronoGraphStepUtil.optimizeFilters(chronoDbFilters);
// for efficiency, it's better NOT to pass any negated filters down to ChronoDB. The reason is
// that ChronoDB needs to perform an intersection with the primary index, as all indices are
// sparse. The better option is to let ChronoDB evaluate the non-negated filters, and we apply
// the rest of the filters in-memory.
List<FilterStep<E>> negatedFilters = chronoDbFilters.stream().filter(ChronoGraphStepUtil::isNegated).collect(Collectors.toList());
List<FilterStep<E>> nonNegatedFilters = chronoDbFilters.stream().filter(step -> !ChronoGraphStepUtil.isNegated(step)).collect(Collectors.toList());
Set<Edge> edgesFromIndexQuery;
if (nonNegatedFilters.isEmpty()) {
// all filters are negated, this query will be slow
// there's no reason to run ALL negated queries against the index, it will only
// result in needless checks against the primary index, which will slow things down. Only
// run ONE of the negated queries on the index, and the rest in-memory.
FilterStep<E> firstFilter = Iterables.getFirst(negatedFilters, null);
List<FilterStep<E>> indexQueries = Lists.newArrayList();
indexQueries.add(firstFilter);
FinalizableQueryBuilder finalizableQueryBuilder = ChronoGraphTraversalUtil.toChronoDBQuery(
cleanIndices,
indexQueries,
queryBuilder,
ChronoGraphTraversalUtil::createIndexKeyForEdgeProperty
);
Iterator<QualifiedKey> keys = finalizableQueryBuilder.getKeys();
edgesFromIndexQuery = Streams.stream(keys)
.map(QualifiedKey::getKey)
.map(id -> tx.getEdgeOrNull(id, ElementLoadMode.LAZY))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// there is a slight difference in query semantics between ChronoDB and Gremlin when it comes to NEGATED predicates:
// - In ChronoDB, a key is returned if its value matches the negated predicate. Note that "null" matches many negated predicates.
// - In Gremlin, a graph element is returned if it HAS a value AND that value matches the negated predicate.
// We therefore need to apply a post-processing here, checking that the vertices indeed have the requested property keys.
Predicate<Edge> predicate = (Predicate<Edge>) ChronoGraphTraversalUtil.filterStepsToPredicate(negatedFilters);
edgesFromIndexQuery = edgesFromIndexQuery.stream().filter(predicate).collect(Collectors.toSet());
} else {
// run the non-negated filters on ChronoDB, apply the rest in-memory
FinalizableQueryBuilder finalizableQueryBuilder = ChronoGraphTraversalUtil.toChronoDBQuery(
cleanIndices,
nonNegatedFilters,
queryBuilder,
ChronoGraphTraversalUtil::createIndexKeyForEdgeProperty
);
Iterator<QualifiedKey> keys = finalizableQueryBuilder.getKeys();
edgesFromIndexQuery = Streams.stream(keys)
.map(QualifiedKey::getKey)
.map(id -> tx.getEdgeOrNull(id, ElementLoadMode.LAZY))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
// check if we have negated filters
if (!negatedFilters.isEmpty()) {
Predicate<Edge> predicate = (Predicate<Edge>) ChronoGraphTraversalUtil.filterStepsToPredicate(negatedFilters);
edgesFromIndexQuery = edgesFromIndexQuery.stream().filter(predicate).collect(Collectors.toSet());
}
}
return edgesFromIndexQuery;
}
}
| 16,640 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
IndexMigrationUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/IndexMigrationUtil.java | package org.chronos.chronograph.internal.impl.index;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
import org.chronos.chronograph.internal.api.index.IChronoGraphEdgeIndex;
import org.chronos.chronograph.internal.api.index.IChronoGraphVertexIndex;
public class IndexMigrationUtil {
@SuppressWarnings("deprecation")
public static IChronoGraphVertexIndex migrate(final IChronoGraphVertexIndex index) {
if (index instanceof ChronoGraphVertexIndex) {
return new ChronoGraphVertexIndex2(index.getIndexedProperty(), index.getIndexType());
}
// no need to migrate
return index;
}
@SuppressWarnings("deprecation")
public static IChronoGraphEdgeIndex migrate(final IChronoGraphEdgeIndex index) {
if (index instanceof ChronoGraphEdgeIndex) {
return new ChronoGraphEdgeIndex2(index.getIndexedProperty(), index.getIndexType());
}
// no need to migrate
return index;
}
public static ChronoGraphIndex migrate(final ChronoGraphIndex index) {
if (index instanceof IChronoGraphVertexIndex) {
return migrate((IChronoGraphVertexIndex) index);
} else if (index instanceof IChronoGraphEdgeIndex) {
return migrate((IChronoGraphEdgeIndex) index);
} else {
throw new IllegalStateException("Unknown subclass of ChronoGraphIndex: '" + index.getClass().getName() + "'!");
}
}
}
| 1,316 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphEdgeIndex.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/ChronoGraphEdgeIndex.java | package org.chronos.chronograph.internal.impl.index;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.chronos.chronodb.api.indexing.Indexer;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.index.IChronoGraphEdgeIndex;
import org.chronos.common.annotation.PersistentClass;
/**
* This class represents the definition of an edge index (index metadata) on disk.
*
* @deprecated Superseded by {@link ChronoGraphEdgeIndex2}.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
@Deprecated
@PersistentClass("kryo")
public class ChronoGraphEdgeIndex extends AbstractChronoGraphIndex implements IChronoGraphEdgeIndex {
protected ChronoGraphEdgeIndex() {
// default constructor for serialization
}
public ChronoGraphEdgeIndex(final String indexedProperty) {
super(indexedProperty);
}
@Override
public String getBackendIndexKey() {
return ChronoGraphConstants.INDEX_PREFIX_EDGE + this.getIndexedProperty();
}
@Override
public Class<Edge> getIndexedElementClass() {
return Edge.class;
}
@Override
public String toString() {
return "Index[Edge, " + this.getIndexedProperty() + "]";
}
}
| 1,204 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphIndexingUtils.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/GraphIndexingUtils.java | package org.chronos.chronograph.internal.impl.index;
import static com.google.common.base.Preconditions.*;
import java.util.Collections;
import java.util.Set;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.util.ReflectionUtils;
import com.google.common.collect.Sets;
public class GraphIndexingUtils {
public static Set<String> getStringIndexValues(final IPropertyRecord record) {
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
Object value = record.getValue();
if (value == null) {
// this should actually never happen, just a safety measure
return Collections.emptySet();
}
if (value instanceof Iterable) {
// multiplicity-many property
Iterable<?> iterable = (Iterable<?>) value;
Set<String> indexedValues = Sets.newHashSet();
for (Object element : iterable) {
indexedValues.add(String.valueOf(element));
}
return Collections.unmodifiableSet(indexedValues);
} else {
// multiplicity-one property
return Collections.singleton(String.valueOf(value));
}
}
public static Set<Long> getLongIndexValues(final IPropertyRecord record) {
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
Object value = record.getValue();
if (value == null) {
// this should actually never happen, just a safety measure
return Collections.emptySet();
}
if (value instanceof Iterable) {
// multiplicity-many property
Iterable<?> iterable = (Iterable<?>) value;
Set<Long> indexedValues = Sets.newHashSet();
for (Object element : iterable) {
Long indexValue = asLongIndexValue(element);
if (indexValue != null) {
indexedValues.add(indexValue);
}
}
return Collections.unmodifiableSet(indexedValues);
} else {
// multiplicity-one property
Long indexValue = asLongIndexValue(value);
if (indexValue != null) {
return Collections.singleton(indexValue);
} else {
return Collections.emptySet();
}
}
}
public static Set<Double> getDoubleIndexValues(final IPropertyRecord record) {
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
Object value = record.getValue();
if (value == null) {
// this should actually never happen, just a safety measure
return Collections.emptySet();
}
if (value instanceof Iterable) {
// multiplicity-many property
Iterable<?> iterable = (Iterable<?>) value;
Set<Double> indexedValues = Sets.newHashSet();
for (Object element : iterable) {
Double indexValue = asDoubleIndexValue(element);
if (indexValue != null) {
indexedValues.add(indexValue);
}
}
return Collections.unmodifiableSet(indexedValues);
} else {
// multiplicity-one property
Double indexValue = asDoubleIndexValue(value);
if (indexValue != null) {
return Collections.singleton(indexValue);
} else {
return Collections.emptySet();
}
}
}
public static Long asLongIndexValue(final Object singleValue) {
if (singleValue == null) {
return null;
}
try {
return ReflectionUtils.asLong(singleValue);
} catch (Exception e) {
// conversion failed
return null;
}
}
public static Double asDoubleIndexValue(final Object singleValue) {
if (singleValue == null) {
return null;
}
try {
return ReflectionUtils.asDouble(singleValue);
} catch (Exception e) {
// conversion failed
return null;
}
}
}
| 3,463 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecordDoubleIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/EdgeRecordDoubleIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Set;
import org.chronos.chronodb.api.indexing.DoubleIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.annotation.PersistentClass;
@PersistentClass("kryo")
public class EdgeRecordDoubleIndexer2 extends EdgeRecordPropertyIndexer2<Double> implements DoubleIndexer {
protected EdgeRecordDoubleIndexer2() {
// default constructor for serialization
}
public EdgeRecordDoubleIndexer2(final String propertyName) {
super(propertyName);
}
@Override
protected Set<Double> getIndexValuesInternal(final IPropertyRecord record) {
return GraphIndexingUtils.getDoubleIndexValues(record);
}
}
| 720 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractChronoGraphIndex2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/AbstractChronoGraphIndex2.java | package org.chronos.chronograph.internal.impl.index;
import static com.google.common.base.Preconditions.*;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronodb.internal.api.Period;
import org.chronos.chronodb.internal.impl.index.IndexingOption;
import org.chronos.chronograph.internal.api.index.ChronoGraphIndexInternal;
import java.util.Collections;
import java.util.Set;
/**
* @deprecated Use {@link ChronoGraphIndex3} instead. This class only exists for backwards compatibility.
*/
@Deprecated
public abstract class AbstractChronoGraphIndex2 implements ChronoGraphIndexInternal {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
protected String indexedProperty;
protected IndexType indexType;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
protected AbstractChronoGraphIndex2() {
// default constructor for serialization
}
public AbstractChronoGraphIndex2(final String indexedProperty, final IndexType indexType) {
checkNotNull(indexedProperty, "Precondition violation - argument 'indexedProperty' must not be NULL!");
checkNotNull(indexType, "Precondition violation - argument 'indexType' must not be NULL!");
this.indexedProperty = indexedProperty;
this.indexType = indexType;
}
@Override
public String getId() {
return this.getBackendIndexKey();
}
@Override
public String getParentIndexId() {
return null;
}
@Override
public boolean isDirty() {
return true;
}
@Override
public String getBranch() {
return ChronoDBConstants.MASTER_BRANCH_IDENTIFIER;
}
@Override
public Period getValidPeriod() {
return Period.eternal();
}
@Override
public String getIndexedProperty() {
return this.indexedProperty;
}
@Override
public IndexType getIndexType() {
return this.indexType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.indexType == null ? 0 : this.indexType.hashCode());
result = prime * result + (this.indexedProperty == null ? 0 : this.indexedProperty.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;
}
AbstractChronoGraphIndex2 other = (AbstractChronoGraphIndex2) obj;
if (this.indexType != other.indexType) {
return false;
}
if (this.indexedProperty == null) {
if (other.indexedProperty != null) {
return false;
}
} else if (!this.indexedProperty.equals(other.indexedProperty)) {
return false;
}
return true;
}
@Override
public Set<IndexingOption> getIndexingOptions() {
return Collections.emptySet();
}
}
| 3,117 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractRecordPropertyIndexer.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/AbstractRecordPropertyIndexer.java | package org.chronos.chronograph.internal.impl.index;
import com.google.common.collect.Sets;
import org.chronos.chronodb.api.indexing.StringIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.Record;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.Preconditions.*;
/**
* A base class for all indexers working on {@link Record}s.
*
* @deprecated Superseded by {@link AbstractRecordPropertyIndexer2}.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
@Deprecated
@PersistentClass("kryo")
public abstract class AbstractRecordPropertyIndexer implements StringIndexer, GraphPropertyIndexer<String> {
protected String propertyName;
protected AbstractRecordPropertyIndexer() {
// default constructor for serialization
}
protected AbstractRecordPropertyIndexer(final String propertyName) {
checkNotNull(propertyName, "Precondition violation - argument 'propertyName' must not be NULL!");
this.propertyName = propertyName;
}
protected Set<String> getIndexValue(final Optional<? extends IPropertyRecord> maybePropertyRecord) {
if (maybePropertyRecord.isPresent() == false) {
// the vertex doesn't have the property; nothing to index
return Collections.emptySet();
} else {
IPropertyRecord property = maybePropertyRecord.get();
Object value = property.getValue();
if (value == null) {
// this should actually never happen, just a safety measure
return Collections.emptySet();
}
if (value instanceof Iterable) {
// multiplicity-many property
Iterable<?> iterable = (Iterable<?>) value;
Set<String> indexedValues = Sets.newHashSet();
for (Object element : iterable) {
indexedValues.add(this.convertToString(element));
}
return Collections.unmodifiableSet(indexedValues);
} else {
// multiplicity-one property
return Collections.singleton(this.convertToString(value));
}
}
}
protected String convertToString(final Object element) {
return String.valueOf(element);
}
@Override
public String getGraphElementPropertyName() {
return this.propertyName;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AbstractRecordPropertyIndexer that = (AbstractRecordPropertyIndexer) o;
return propertyName != null ? propertyName.equals(that.propertyName) : that.propertyName == null;
}
@Override
public int hashCode() {
return propertyName != null ? propertyName.hashCode() : 0;
}
}
| 2,707 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphVertexIndex.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/ChronoGraphVertexIndex.java | package org.chronos.chronograph.internal.impl.index;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.indexing.Indexer;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.index.IChronoGraphVertexIndex;
import org.chronos.common.annotation.PersistentClass;
/**
* This class represents the definition of a vertex index (index metadata) on disk.
*
* @deprecated Superseded by {@link ChronoGraphVertexIndex2}.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
@Deprecated
@PersistentClass("kryo")
public class ChronoGraphVertexIndex extends AbstractChronoGraphIndex implements IChronoGraphVertexIndex {
protected ChronoGraphVertexIndex() {
// default constructor for serialization
}
public ChronoGraphVertexIndex(final String indexedProperty) {
super(indexedProperty);
}
@Override
public String getBackendIndexKey() {
return ChronoGraphConstants.INDEX_PREFIX_VERTEX + this.getIndexedProperty();
}
@Override
public Class<Vertex> getIndexedElementClass() {
return Vertex.class;
}
@Override
public String toString() {
return "Index[Vertex, " + this.getIndexedProperty() + "]";
}
}
| 1,227 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphIndexManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/ChronoGraphIndexManagerImpl.java | package org.chronos.chronograph.internal.impl.index;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.Branch;
import org.chronos.chronodb.api.ChronoDB;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.IndexManager;
import org.chronos.chronodb.api.SecondaryIndex;
import org.chronos.chronodb.api.builder.query.FinalizableQueryBuilder;
import org.chronos.chronodb.api.builder.query.QueryBuilder;
import org.chronos.chronodb.api.builder.query.WhereBuilder;
import org.chronos.chronodb.api.indexing.Indexer;
import org.chronos.chronodb.api.key.QualifiedKey;
import org.chronos.chronodb.api.query.DoubleContainmentCondition;
import org.chronos.chronodb.api.query.LongContainmentCondition;
import org.chronos.chronodb.api.query.NumberCondition;
import org.chronos.chronodb.api.query.StringCondition;
import org.chronos.chronodb.api.query.StringContainmentCondition;
import org.chronos.chronodb.internal.api.index.IndexManagerInternal;
import org.chronos.chronodb.internal.api.query.searchspec.ContainmentDoubleSearchSpecification;
import org.chronos.chronodb.internal.api.query.searchspec.ContainmentLongSearchSpecification;
import org.chronos.chronodb.internal.api.query.searchspec.ContainmentStringSearchSpecification;
import org.chronos.chronodb.internal.api.query.searchspec.DoubleSearchSpecification;
import org.chronos.chronodb.internal.api.query.searchspec.LongSearchSpecification;
import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification;
import org.chronos.chronodb.internal.api.query.searchspec.StringSearchSpecification;
import org.chronos.chronodb.internal.impl.index.IndexingOption;
import org.chronos.chronodb.internal.impl.query.TextMatchMode;
import org.chronos.chronograph.api.builder.index.IndexBuilderStarter;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
import org.chronos.chronograph.api.index.ChronoGraphIndexManager;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.index.ChronoGraphIndexInternal;
import org.chronos.chronograph.internal.api.index.ChronoGraphIndexManagerInternal;
import org.chronos.chronograph.internal.impl.builder.index.ChronoGraphIndexBuilder;
import org.chronos.common.exceptions.UnknownEnumLiteralException;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphIndexManagerImpl implements ChronoGraphIndexManager, ChronoGraphIndexManagerInternal {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private final ChronoDB chronoDB;
private final Branch branch;
public ChronoGraphIndexManagerImpl(final ChronoDB chronoDB, final String branchName) {
checkNotNull(chronoDB, "Precondition violation - argument 'chronoDB' must not be NULL!");
this.chronoDB = chronoDB;
this.branch = this.chronoDB.getBranchManager().getBranch(branchName);
}
// =====================================================================================================================
// INDEX CREATION
// =====================================================================================================================
@Override
public IndexBuilderStarter create() {
return new ChronoGraphIndexBuilder(this);
}
// =====================================================================================================================
// INDEX METADATA QUERYING
// =====================================================================================================================
@Override
public Set<ChronoGraphIndex> getIndexedPropertiesAtTimestamp(final Class<? extends Element> clazz, long timestamp) {
checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
return this.getChronoDBIndexManager().getIndices(this.branch, timestamp).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.filter(idx -> Objects.equals(idx.getIndexedElementClass(), clazz))
.collect(Collectors.toSet());
}
@Override
public Set<ChronoGraphIndex> getIndexedPropertiesAtAnyPointInTime(final Class<? extends Element> clazz) {
checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!");
return this.getChronoDBIndexManager().getIndices(this.branch).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.filter(idx -> Objects.equals(idx.getIndexedElementClass(), clazz))
.collect(Collectors.toSet());
}
@Override
public Set<ChronoGraphIndex> getAllIndicesAtAnyPointInTime() {
return this.getChronoDBIndexManager().getIndices(this.branch).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
@Override
public Set<ChronoGraphIndex> getAllIndicesAtTimestamp(final long timestamp) {
return this.getChronoDBIndexManager().getIndices(this.branch, timestamp).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
@Override
public ChronoGraphIndex getVertexIndexAtTimestamp(final String indexedPropertyName, final long timestamp) {
checkNotNull(indexedPropertyName, "Precondition violation - argument 'indexedPropertyName' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
return this.getChronoDBIndexManager().getIndices(this.branch, timestamp).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.filter(idx -> Vertex.class.equals(idx.getIndexedElementClass()))
.filter(idx -> idx.getValidPeriod().contains(timestamp))
.filter(idx -> idx.getIndexedProperty().equals(indexedPropertyName))
.findFirst().orElse(null);
}
@Override
public Set<ChronoGraphIndex> getVertexIndicesAtAnyPointInTime(final String indexedPropertyName) {
checkNotNull(indexedPropertyName, "Precondition violation - argument 'indexedPropertyName' must not be NULL!");
return this.getChronoDBIndexManager().getIndices(this.branch).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.filter(idx -> Vertex.class.equals(idx.getIndexedElementClass()))
.filter(idx -> idx.getIndexedProperty().equals(indexedPropertyName))
.collect(Collectors.toSet());
}
@Override
public ChronoGraphIndex getEdgeIndexAtTimestamp(final String indexedPropertyName, final long timestamp) {
checkNotNull(indexedPropertyName, "Precondition violation - argument 'indexedPropertyName' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
return this.getChronoDBIndexManager().getIndices(this.branch, timestamp).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.filter(idx -> Edge.class.equals(idx.getIndexedElementClass()))
.filter(idx -> idx.getIndexedProperty().equals(indexedPropertyName))
.filter(idx -> idx.getValidPeriod().contains(timestamp))
.findFirst().orElse(null);
}
@Override
public Set<ChronoGraphIndex> getEdgeIndicesAtAnyPointInTime(final String indexedPropertyName) {
checkNotNull(indexedPropertyName, "Precondition violation - argument 'indexedPropertyName' must not be NULL!");
return this.getChronoDBIndexManager().getIndices(this.branch).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.filter(idx -> Edge.class.equals(idx.getIndexedElementClass()))
.filter(idx -> idx.getIndexedProperty().equals(indexedPropertyName))
.collect(Collectors.toSet());
}
@Override
public boolean isReindexingRequired() {
return this.withIndexReadLock(() -> this.getChronoDBIndexManager().isReindexingRequired());
}
@Override
public Set<ChronoGraphIndex> getDirtyIndicesAtAnyPointInTime() {
return this.getChronoDBIndexManager().getIndices(this.branch).stream()
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.filter(Objects::nonNull)
.filter(ChronoGraphIndex3::isDirty)
.collect(Collectors.toSet());
}
// =====================================================================================================================
// INDEX MANIPULATION
// =====================================================================================================================
@Override
public void reindexAll(boolean force) {
this.getChronoDBIndexManager().reindexAll(force);
}
@Override
public void dropIndex(final ChronoGraphIndex index) {
checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!");
IndexManager indexManager = this.getChronoDBIndexManager();
SecondaryIndex chronoDbIndex = indexManager.getIndexById(index.getId());
if (chronoDbIndex != null) {
indexManager.deleteIndex(chronoDbIndex);
}
}
@Override
public void dropAllIndices() {
this.dropAllIndices(null);
}
@Override
public void dropAllIndices(final Object commitMetadata) {
IndexManager indexManager = this.getChronoDBIndexManager();
indexManager.clearAllIndices();
}
@Override
public ChronoGraphIndex terminateIndex(final ChronoGraphIndex index, final long timestamp) {
checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!");
Preconditions.checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
IndexManager indexManager = this.getChronoDBIndexManager();
SecondaryIndex chronoDBIndex = indexManager.getIndexById(index.getId());
ChronoGraphIndex existingIndex = Optional.ofNullable(chronoDBIndex)
.map(ChronoGraphIndex3::createFromChronoDBIndexOrNull)
.orElse(null);
if (existingIndex == null) {
throw new IllegalArgumentException("The given index '" + index + "' does not exist anymore and cannot be terminated!");
}
if (existingIndex.getValidPeriod().getUpperBound() != Long.MAX_VALUE) {
throw new IllegalStateException("The index '" + index + "' has already been terminated. It cannot be terminated it again!");
}
SecondaryIndex updatedIndex = indexManager.setIndexEndDate(chronoDBIndex, timestamp);
return ChronoGraphIndex3.createFromChronoDBIndexOrNull(updatedIndex);
}
// =====================================================================================================================
// INTERNAL API :: MODIFICATION
// =====================================================================================================================
@Override
public ChronoGraphIndex addIndex(
final Class<? extends Element> elementType,
final IndexType indexType,
final String propertyName,
final long startTimestamp,
final long endTimestamp,
final Set<IndexingOption> indexingOptions
) {
checkNotNull(elementType, "Precondition violation - argument 'elementType' must not be NULL!");
checkNotNull(indexType, "Precondition violation - argument 'indexType' must not be NULL!");
checkNotNull(propertyName, "Precondition violation - argument 'propertyName' must not be NULL!");
checkArgument(!propertyName.isEmpty(), "Precondition violation - argument 'propertyName' must not be empty!");
checkArgument(startTimestamp <= System.currentTimeMillis(), "Precondition violation - argument 'startTimestamp' is in the future!");
checkArgument(startTimestamp >= 0, "Precondition violation - argument 'startTimestamp' must not be negative!");
checkArgument(endTimestamp > startTimestamp, "Precondition violation - argument 'endTimestamp' must be greater than 'startTimestamp'!");
String indexName;
Indexer<?> indexer;
if (Vertex.class.equals(elementType)) {
indexName = ChronoGraphConstants.INDEX_PREFIX_VERTEX + propertyName;
switch (indexType) {
case STRING:
indexer = new VertexRecordStringIndexer2(propertyName);
break;
case LONG:
indexer = new VertexRecordLongIndexer2(propertyName);
break;
case DOUBLE:
indexer = new VertexRecordDoubleIndexer2(propertyName);
break;
default:
throw new UnknownEnumLiteralException(indexType);
}
} else if (Edge.class.equals(elementType)) {
indexName = ChronoGraphConstants.INDEX_PREFIX_EDGE + propertyName;
switch (indexType) {
case STRING:
indexer = new EdgeRecordStringIndexer2(propertyName);
break;
case LONG:
indexer = new EdgeRecordLongIndexer2(propertyName);
break;
case DOUBLE:
indexer = new EdgeRecordDoubleIndexer2(propertyName);
break;
default:
throw new UnknownEnumLiteralException(indexType);
}
} else {
throw new IllegalArgumentException("The elementType '" + elementType.getName() + "' is unknown! Only Vertex and Edge are allowed!");
}
SecondaryIndex dbIndex = this.chronoDB.getIndexManager().createIndex()
.withName(indexName)
.withIndexer(indexer)
.onBranch(this.branch)
.fromTimestamp(startTimestamp)
.toTimestamp(endTimestamp)
.withOptions(indexingOptions)
.build();
return ChronoGraphIndex3.createFromChronoDBIndexOrNull(dbIndex);
}
// =====================================================================================================================
// INTERNAL API :: SEARCH
// =====================================================================================================================
@Override
public Iterator<String> findVertexIdsByIndexedProperties(final ChronoGraphTransaction tx, final Set<SearchSpecification<?, ?>> searchSpecifications) {
checkNotNull(
searchSpecifications,
"Precondition violation - argument 'searchSpecifications' must not be NULL!"
);
return this.findElementsByIndexedProperties(tx, Vertex.class, ChronoGraphConstants.KEYSPACE_VERTEX,
searchSpecifications
);
}
@Override
public Iterator<String> findEdgeIdsByIndexedProperties(final ChronoGraphTransaction tx, final Set<SearchSpecification<?, ?>> searchSpecifications) {
checkNotNull(
searchSpecifications,
"Precondition violation - argument 'searchSpecifications' must not be NULL!"
);
return this.findElementsByIndexedProperties(tx, Edge.class, ChronoGraphConstants.KEYSPACE_EDGE,
searchSpecifications
);
}
private Iterator<String> findElementsByIndexedProperties(final ChronoGraphTransaction tx, final Class<? extends Element> clazz,
final String keyspace, final Set<SearchSpecification<?, ?>> searchSpecifications) {
checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!");
checkNotNull(keyspace, "Precondition violation - argument 'key' must not be NULL!");
checkNotNull(
searchSpecifications,
"Precondition violation - argument 'searchSpecifications' must not be NULL!"
);
// we need to make sure that all given properties are indeed indexed
checkArgument(
searchSpecifications.isEmpty() == false,
"Precondition violation - need at least one search specification to search for!"
);
Set<String> properties = searchSpecifications.stream().map(search -> search.getIndex().getName()).collect(Collectors.toSet());
this.assertAllPropertiesAreIndexed(clazz, properties, tx.getTimestamp());
// build a map from 'backend property key' to 'search specifications'
SetMultimap<String, SearchSpecification<?, ?>> backendPropertyKeyToSearchSpecs = HashMultimap.create();
Set<ChronoGraphIndex> graphIndices = this.getIndexedPropertiesAtTimestamp(clazz, tx.getTimestamp());
for (SearchSpecification<?, ?> searchSpec : searchSpecifications) {
ChronoGraphIndex index = graphIndices.stream()
.filter(idx -> idx.getId().equals(searchSpec.getIndex().getId()))
.findAny()
.orElseThrow(() ->
new IllegalStateException("Unable to find graph index for ID '" + searchSpec.getIndex().getId() + "'!")
);
String backendPropertyKey = ((ChronoGraphIndexInternal) index).getBackendIndexKey();
backendPropertyKeyToSearchSpecs.put(backendPropertyKey, searchSpec);
}
// get the transaction
ChronoDBTransaction backendTransaction = tx.getBackingDBTransaction();
// build the composite query
QueryBuilder builder = backendTransaction.find().inKeyspace(keyspace);
FinalizableQueryBuilder finalizableBuilder = null;
List<String> propertyList = Lists.newArrayList(backendPropertyKeyToSearchSpecs.keySet());
for (int i = 0; i < propertyList.size(); i++) {
String propertyName = propertyList.get(i);
Set<SearchSpecification<?, ?>> searchSpecs = backendPropertyKeyToSearchSpecs.get(propertyName);
FinalizableQueryBuilder innerTempBuilder = null;
for (SearchSpecification<?, ?> searchSpec : searchSpecs) {
WhereBuilder whereBuilder;
if (innerTempBuilder == null) {
whereBuilder = builder.where(propertyName);
} else {
whereBuilder = innerTempBuilder.and().where(propertyName);
}
innerTempBuilder = this.applyCondition(whereBuilder, searchSpec);
}
if (i + 1 < propertyList.size()) {
// continuation
builder = innerTempBuilder.and();
} else {
// done
finalizableBuilder = innerTempBuilder;
}
}
// run the query
Iterator<QualifiedKey> keys = finalizableBuilder.getKeys();
// this is the "raw" iterator over vertex IDs which we obtain from our index.
return Iterators.transform(keys, QualifiedKey::getKey);
}
// =================================================================================================================
// INTERNAL API :: LOCKING
// =================================================================================================================
@Override
public <T> T withIndexReadLock(final Callable<T> action) {
Preconditions.checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
return this.getChronoDBIndexManager().withIndexReadLock(action);
}
@Override
public void withIndexReadLock(final Runnable action) {
Preconditions.checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
this.getChronoDBIndexManager().withIndexReadLock(action);
}
@Override
public <T> T withIndexWriteLock(final Callable<T> action) {
Preconditions.checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
return this.getChronoDBIndexManager().withIndexWriteLock(action);
}
@Override
public void withIndexWriteLock(final Runnable action) {
Preconditions.checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
this.getChronoDBIndexManager().withIndexWriteLock(action);
}
// =====================================================================================================================
// INTERNAL HELPER METHODS
// =====================================================================================================================
private IndexManagerInternal getChronoDBIndexManager() {
return (IndexManagerInternal) this.chronoDB.getIndexManager();
}
private void assertAllPropertiesAreIndexed(final Class<? extends Element> clazz, final Set<String> propertyNames, long timestamp) {
checkNotNull(clazz, "Precondition violation - argument 'clazz' must not be NULL!");
checkNotNull(propertyNames, "Precondition violation - argument 'propertyNames' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
if (Vertex.class.isAssignableFrom(clazz)) {
Set<String> indexedVertexPropertyNames = this.getIndexedVertexPropertyNamesAtTimestamp(timestamp);
Set<String> unindexedProperties = Sets.newHashSet(propertyNames);
unindexedProperties.removeAll(indexedVertexPropertyNames);
if (unindexedProperties.isEmpty() == false) {
throw new IllegalArgumentException(
"Some of the given properties are not indexed on vertices on branch '"
+ this.branch.getName() + "' at timestamp " + timestamp + ": "
+ unindexedProperties
);
}
} else if (Edge.class.isAssignableFrom(clazz)) {
Set<String> indexedEdgePropertyNames = this.getIndexedEdgePropertyNamesAtTimestamp(timestamp);
Set<String> unindexedProperties = Sets.newHashSet(propertyNames);
unindexedProperties.removeAll(indexedEdgePropertyNames);
if (unindexedProperties.isEmpty() == false) {
throw new IllegalArgumentException(
"Some of the given properties are not indexed on edges on branch '"
+ this.branch.getName() + "' at timestamp " + timestamp + ": "
+ unindexedProperties
);
}
} else {
throw new IllegalArgumentException("Unknown graph element class: '" + clazz.getName() + "'!");
}
}
private FinalizableQueryBuilder applyCondition(final WhereBuilder whereBuilder,
final SearchSpecification<?, ?> searchSpec) {
if (searchSpec instanceof StringSearchSpecification) {
return this.applyCondition(whereBuilder, (StringSearchSpecification) searchSpec);
} else if (searchSpec instanceof LongSearchSpecification) {
return this.applyCondition(whereBuilder, (LongSearchSpecification) searchSpec);
} else if (searchSpec instanceof DoubleSearchSpecification) {
return this.applyCondition(whereBuilder, (DoubleSearchSpecification) searchSpec);
} else if (searchSpec instanceof ContainmentStringSearchSpecification) {
return this.applyCondition(whereBuilder, (ContainmentStringSearchSpecification) searchSpec);
} else if (searchSpec instanceof ContainmentLongSearchSpecification) {
return this.applyCondition(whereBuilder, (ContainmentLongSearchSpecification) searchSpec);
} else if (searchSpec instanceof ContainmentDoubleSearchSpecification) {
return this.applyCondition(whereBuilder, (ContainmentDoubleSearchSpecification) searchSpec);
} else {
throw new IllegalStateException(
"Unknown SearchSpecification class: '" + searchSpec.getClass().getName() + "'!");
}
}
private FinalizableQueryBuilder applyCondition(final WhereBuilder whereBuilder,
final StringSearchSpecification searchSpec) {
StringCondition condition = searchSpec.getCondition();
TextMatchMode matchMode = searchSpec.getMatchMode();
String searchText = searchSpec.getSearchValue();
if (condition.equals(StringCondition.CONTAINS)) {
return this.applyContainsCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.ENDS_WITH)) {
return this.applyEndsWithCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.EQUALS)) {
return this.applyEqualsCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.MATCHES_REGEX)) {
return this.applyMatchesRegexCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.NOT_CONTAINS)) {
return this.applyNotContainsCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.NOT_ENDS_WITH)) {
return this.applyNotEndsWithCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.NOT_EQUALS)) {
return this.applyNotEqualsCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.NOT_MATCHES_REGEX)) {
return this.applyNotMatchesRegexCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.NOT_STARTS_WITH)) {
return this.applyNotStartsWithCondition(whereBuilder, matchMode, searchText);
} else if (condition.equals(StringCondition.STARTS_WITH)) {
return this.applyStartsWithCondition(whereBuilder, matchMode, searchText);
} else {
throw new IllegalStateException("Unknown StringCondition: '" + condition.getClass().getName() + "'!");
}
}
private FinalizableQueryBuilder applyStartsWithCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.startsWithIgnoreCase(searchText);
case STRICT:
return whereBuilder.startsWith(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyNotStartsWithCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.notStartsWithIgnoreCase(searchText);
case STRICT:
return whereBuilder.notStartsWith(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyNotEqualsCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.isNotEqualToIgnoreCase(searchText);
case STRICT:
return whereBuilder.isNotEqualTo(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyNotEndsWithCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.notEndsWithIgnoreCase(searchText);
case STRICT:
return whereBuilder.notEndsWith(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyNotContainsCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.notContainsIgnoreCase(searchText);
case STRICT:
return whereBuilder.notContains(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyEqualsCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.isEqualToIgnoreCase(searchText);
case STRICT:
return whereBuilder.isEqualTo(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyEndsWithCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.endsWithIgnoreCase(searchText);
case STRICT:
return whereBuilder.endsWith(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyContainsCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.containsIgnoreCase(searchText);
case STRICT:
return whereBuilder.contains(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyMatchesRegexCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.matchesRegexIgnoreCase(searchText);
case STRICT:
return whereBuilder.matchesRegex(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyNotMatchesRegexCondition(final WhereBuilder whereBuilder, final TextMatchMode matchMode, final String searchText) {
switch (matchMode) {
case CASE_INSENSITIVE:
return whereBuilder.notMatchesRegexIgnoreCase(searchText);
case STRICT:
return whereBuilder.notMatchesRegex(searchText);
default:
throw new UnknownEnumLiteralException(matchMode);
}
}
private FinalizableQueryBuilder applyCondition(final WhereBuilder whereBuilder,
final LongSearchSpecification searchSpec) {
NumberCondition condition = searchSpec.getCondition();
long comparisonValue = searchSpec.getSearchValue();
if (condition.equals(NumberCondition.EQUALS)) {
return whereBuilder.isEqualTo(comparisonValue);
} else if (condition.equals(NumberCondition.NOT_EQUALS)) {
return whereBuilder.isNotEqualTo(comparisonValue);
} else if (condition.equals(NumberCondition.LESS_EQUAL)) {
return whereBuilder.isLessThanOrEqualTo(comparisonValue);
} else if (condition.equals(NumberCondition.LESS_THAN)) {
return whereBuilder.isLessThan(comparisonValue);
} else if (condition.equals(NumberCondition.GREATER_EQUAL)) {
return whereBuilder.isGreaterThanOrEqualTo(comparisonValue);
} else if (condition.equals(NumberCondition.GREATER_THAN)) {
return whereBuilder.isGreaterThan(comparisonValue);
} else {
throw new IllegalStateException("Unknown NumberCondition: '" + condition.getClass().getName() + "'!");
}
}
private FinalizableQueryBuilder applyCondition(final WhereBuilder whereBuilder,
final DoubleSearchSpecification searchSpec) {
NumberCondition condition = searchSpec.getCondition();
double comparisonValue = searchSpec.getSearchValue();
double equalityTolerance = searchSpec.getEqualityTolerance();
if (condition.equals(NumberCondition.EQUALS)) {
return whereBuilder.isEqualTo(comparisonValue, equalityTolerance);
} else if (condition.equals(NumberCondition.NOT_EQUALS)) {
return whereBuilder.isNotEqualTo(comparisonValue, equalityTolerance);
} else if (condition.equals(NumberCondition.LESS_EQUAL)) {
return whereBuilder.isLessThanOrEqualTo(comparisonValue);
} else if (condition.equals(NumberCondition.LESS_THAN)) {
return whereBuilder.isLessThan(comparisonValue);
} else if (condition.equals(NumberCondition.GREATER_EQUAL)) {
return whereBuilder.isGreaterThanOrEqualTo(comparisonValue);
} else if (condition.equals(NumberCondition.GREATER_THAN)) {
return whereBuilder.isGreaterThan(comparisonValue);
} else {
throw new IllegalStateException("Unknown NumberCondition: '" + condition.getClass().getName() + "'!");
}
}
private FinalizableQueryBuilder applyCondition(final WhereBuilder whereBuilder,
final ContainmentStringSearchSpecification searchSpec) {
StringContainmentCondition condition = searchSpec.getCondition();
TextMatchMode matchMode = searchSpec.getMatchMode();
Set<String> searchValue = searchSpec.getSearchValue();
if (condition.equals(StringContainmentCondition.WITHIN)) {
switch (matchMode) {
case STRICT:
return whereBuilder.inStrings(searchValue);
case CASE_INSENSITIVE:
return whereBuilder.inStringsIgnoreCase(searchValue);
default:
throw new UnknownEnumLiteralException(matchMode);
}
} else if (condition.equals(StringContainmentCondition.WITHOUT)) {
switch (matchMode) {
case STRICT:
return whereBuilder.notInStrings(searchValue);
case CASE_INSENSITIVE:
return whereBuilder.notInStringsIgnoreCase(searchValue);
default:
throw new UnknownEnumLiteralException(matchMode);
}
} else {
throw new IllegalStateException("Unknown StringContainmentCondition: '" + condition.getClass().getName() + "'!");
}
}
private FinalizableQueryBuilder applyCondition(final WhereBuilder whereBuilder,
final ContainmentLongSearchSpecification searchSpec) {
LongContainmentCondition condition = searchSpec.getCondition();
Set<Long> searchValue = searchSpec.getSearchValue();
if (condition.equals(LongContainmentCondition.WITHIN)) {
return whereBuilder.inLongs(searchValue);
} else if (condition.equals(LongContainmentCondition.WITHOUT)) {
return whereBuilder.notInLongs(searchValue);
} else {
throw new IllegalStateException("Unknown LongContainmentCondition: '" + condition.getClass().getName() + "'!");
}
}
private FinalizableQueryBuilder applyCondition(final WhereBuilder whereBuilder,
final ContainmentDoubleSearchSpecification searchSpec) {
DoubleContainmentCondition condition = searchSpec.getCondition();
Set<Double> searchValue = searchSpec.getSearchValue();
double equalityTolerance = searchSpec.getEqualityTolerance();
if (condition.equals(DoubleContainmentCondition.WITHIN)) {
return whereBuilder.inDoubles(searchValue, equalityTolerance);
} else if (condition.equals(DoubleContainmentCondition.WITHOUT)) {
return whereBuilder.notInDoubles(searchValue, equalityTolerance);
} else {
throw new IllegalStateException("Unknown DoubleContainmentCondition: '" + condition.getClass().getName() + "'!");
}
}
}
| 37,742 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecordDoubleIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/VertexRecordDoubleIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Set;
import org.chronos.chronodb.api.indexing.DoubleIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.annotation.PersistentClass;
@PersistentClass("kryo")
public class VertexRecordDoubleIndexer2 extends VertexRecordPropertyIndexer2<Double> implements DoubleIndexer {
protected VertexRecordDoubleIndexer2() {
// default constructor for serialization
}
public VertexRecordDoubleIndexer2(final String propertyName) {
super(propertyName);
}
@Override
protected Set<Double> getIndexValuesInternal(final IPropertyRecord record) {
return GraphIndexingUtils.getDoubleIndexValues(record);
}
}
| 728 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphEdgeIndex2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/ChronoGraphEdgeIndex2.java | package org.chronos.chronograph.internal.impl.index;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.chronos.chronodb.api.indexing.Indexer;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.index.IChronoGraphEdgeIndex;
import org.chronos.common.exceptions.UnknownEnumLiteralException;
/**
* @deprecated Use {@link ChronoGraphIndex3} instead. This class only exists for backwards compatibility.
*/
@Deprecated
public class ChronoGraphEdgeIndex2 extends AbstractChronoGraphIndex2 implements IChronoGraphEdgeIndex {
protected ChronoGraphEdgeIndex2() {
// default constructor for serialization
}
public ChronoGraphEdgeIndex2(final String indexedProperty, final IndexType indexType) {
super(indexedProperty, indexType);
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public String getBackendIndexKey() {
return ChronoGraphConstants.INDEX_PREFIX_EDGE + this.getIndexedProperty();
}
@Override
public Class<? extends Element> getIndexedElementClass() {
return Edge.class;
}
@Override
public String toString() {
return "Index[Edge, " + this.getIndexedProperty() + ", " + this.indexType + "]";
}
}
| 1,466 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecordPropertyIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/VertexRecordPropertyIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.internal.impl.structure.record.VertexRecord;
import org.chronos.common.annotation.PersistentClass;
/**
* An indexer working on {@link VertexRecord}s.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
* @param <T>
* The type of the values indexed by this indexer.
*/
@PersistentClass("kryo")
public abstract class VertexRecordPropertyIndexer2<T> extends AbstractRecordPropertyIndexer2<T> {
protected VertexRecordPropertyIndexer2() {
// default constructor for serializer
}
public VertexRecordPropertyIndexer2(final String propertyName) {
super(propertyName);
}
@Override
public boolean canIndex(final Object object) {
return object instanceof IVertexRecord;
}
@Override
public Set<T> getIndexValues(final Object object) {
IVertexRecord vertexRecord = (IVertexRecord) object;
Optional<? extends IPropertyRecord> maybePropertyRecord = vertexRecord.getProperties().stream()
.filter(pRecord -> pRecord.getKey().equals(this.propertyName)).findAny();
return maybePropertyRecord.map(this::getIndexValuesInternal).orElse(Collections.emptySet());
}
protected abstract Set<T> getIndexValuesInternal(IPropertyRecord record);
}
| 1,488 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractChronoGraphIndex.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/AbstractChronoGraphIndex.java | package org.chronos.chronograph.internal.impl.index;
import static com.google.common.base.Preconditions.*;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronodb.internal.api.Period;
import org.chronos.chronodb.internal.impl.index.IndexingOption;
import org.chronos.chronograph.internal.api.index.ChronoGraphIndexInternal;
import org.chronos.common.annotation.PersistentClass;
import java.util.Collections;
import java.util.Set;
/**
* This class represents the definition of a graph index (index metadata) on disk.
*
* @deprecated Superseded by {@link AbstractChronoGraphIndex2}.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
@Deprecated
@PersistentClass("kryo")
public abstract class AbstractChronoGraphIndex implements ChronoGraphIndexInternal {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private String indexedProperty;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
protected AbstractChronoGraphIndex() {
// default constructor for serialization
}
public AbstractChronoGraphIndex(final String indexedProperty) {
checkNotNull(indexedProperty, "Precondition violation - argument 'indexedProperty' must not be NULL!");
this.indexedProperty = indexedProperty;
}
public String getId() {
return this.getBackendIndexKey();
}
@Override
public String getParentIndexId() {
return null;
}
@Override
public boolean isDirty() {
return true;
}
@Override
public String getBranch() {
return ChronoDBConstants.MASTER_BRANCH_IDENTIFIER;
}
@Override
public Period getValidPeriod() {
return Period.eternal();
}
@Override
public String getIndexedProperty() {
return this.indexedProperty;
}
@Override
public IndexType getIndexType() {
// the old version represented by this class only supported strings
return IndexType.STRING;
}
@Override
public Set<IndexingOption> getIndexingOptions() {
return Collections.emptySet();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.indexedProperty == null ? 0 : this.indexedProperty.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;
}
AbstractChronoGraphIndex other = (AbstractChronoGraphIndex) obj;
if (this.indexedProperty == null) {
if (other.indexedProperty != null) {
return false;
}
} else if (!this.indexedProperty.equals(other.indexedProperty)) {
return false;
}
return true;
}
}
| 3,034 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecordLongIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/VertexRecordLongIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Set;
import org.chronos.chronodb.api.indexing.LongIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.annotation.PersistentClass;
@PersistentClass("kryo")
public class VertexRecordLongIndexer2 extends VertexRecordPropertyIndexer2<Long> implements LongIndexer {
protected VertexRecordLongIndexer2() {
// default constructor for serialization
}
public VertexRecordLongIndexer2(final String propertyName) {
super(propertyName);
}
@Override
protected Set<Long> getIndexValuesInternal(final IPropertyRecord record) {
return GraphIndexingUtils.getLongIndexValues(record);
}
}
| 712 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphPropertyIndexer.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/GraphPropertyIndexer.java | package org.chronos.chronograph.internal.impl.index;
import org.chronos.chronodb.api.indexing.Indexer;
public interface GraphPropertyIndexer<T> extends Indexer<T> {
public String getGraphElementPropertyName();
}
| 220 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
IndexType.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/IndexType.java | package org.chronos.chronograph.internal.impl.index;
/**
* An enumeration over index types.
*
* <p>
* This enumeration is used in the construction of a graph index, indicating which values to index.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*
*/
public enum IndexType {
/** Type for indices that store {@link String} values. */
STRING,
/** Type for indices that store {@link Long} values. */
LONG,
/** Type for indices that store {@link Double} values. */
DOUBLE;
}
| 512 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecordLongIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/EdgeRecordLongIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Set;
import org.chronos.chronodb.api.indexing.LongIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.annotation.PersistentClass;
@PersistentClass("kryo")
public class EdgeRecordLongIndexer2 extends EdgeRecordPropertyIndexer2<Long> implements LongIndexer {
protected EdgeRecordLongIndexer2() {
// default constructor for serialization
}
public EdgeRecordLongIndexer2(final String propertyName) {
super(propertyName);
}
@Override
protected Set<Long> getIndexValuesInternal(final IPropertyRecord record) {
return GraphIndexingUtils.getLongIndexValues(record);
}
}
| 704 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecordPropertyIndexer.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/EdgeRecordPropertyIndexer.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Optional;
import java.util.Set;
import org.chronos.chronodb.api.indexing.StringIndexer;
import org.chronos.chronograph.internal.impl.structure.record.EdgeRecord;
import org.chronos.chronograph.api.structure.record.IEdgeRecord;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.annotation.PersistentClass;
/**
* An indexer working on {@link EdgeRecord}s.
*
* @deprecated Superseded by {@link EdgeRecordPropertyIndexer2}.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
@Deprecated
@PersistentClass("kryo")
public class EdgeRecordPropertyIndexer extends AbstractRecordPropertyIndexer implements StringIndexer {
protected EdgeRecordPropertyIndexer() {
// default constructor for serializer
}
public EdgeRecordPropertyIndexer(final String propertyName) {
super(propertyName);
}
@Override
public boolean canIndex(final Object object) {
return object instanceof IEdgeRecord;
}
@Override
public Set<String> getIndexValues(final Object object) {
IEdgeRecord edgeRecord = (IEdgeRecord) object;
Optional<? extends IPropertyRecord> maybePropertyRecord = edgeRecord.getProperties().stream()
.filter(pRecord -> pRecord.getKey().equals(this.propertyName)).findAny();
return this.getIndexValue(maybePropertyRecord);
}
}
| 1,386 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecordStringIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/EdgeRecordStringIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Set;
import org.chronos.chronodb.api.indexing.StringIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
public class EdgeRecordStringIndexer2 extends EdgeRecordPropertyIndexer2<String> implements StringIndexer {
protected EdgeRecordStringIndexer2() {
// default constructor for serialization
}
protected EdgeRecordStringIndexer2(final String propertyName) {
super(propertyName);
}
@Override
protected Set<String> getIndexValuesInternal(final IPropertyRecord record) {
return GraphIndexingUtils.getStringIndexValues(record);
}
}
| 644 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecordStringIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/VertexRecordStringIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Set;
import org.chronos.chronodb.api.indexing.StringIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.annotation.PersistentClass;
@PersistentClass("kryo")
public class VertexRecordStringIndexer2 extends VertexRecordPropertyIndexer2<String> implements StringIndexer {
protected VertexRecordStringIndexer2() {
// default constructor for serialization
}
public VertexRecordStringIndexer2(final String propertyName) {
super(propertyName);
}
@Override
protected Set<String> getIndexValuesInternal(final IPropertyRecord record) {
Set<String> values = GraphIndexingUtils.getStringIndexValues(record);
return values;
}
}
| 759 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecordPropertyIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/EdgeRecordPropertyIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import org.chronos.chronograph.internal.impl.structure.record.EdgeRecord;
import org.chronos.chronograph.api.structure.record.IEdgeRecord;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.annotation.PersistentClass;
/**
* An indexer working on {@link EdgeRecord}s.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
* @param <T>
* The type of values produced by this indexer.
*/
@PersistentClass("kryo")
public abstract class EdgeRecordPropertyIndexer2<T> extends AbstractRecordPropertyIndexer2<T> {
protected EdgeRecordPropertyIndexer2() {
// default constructor for serializer
}
public EdgeRecordPropertyIndexer2(final String propertyName) {
super(propertyName);
}
@Override
public boolean canIndex(final Object object) {
return object instanceof IEdgeRecord;
}
@Override
public Set<T> getIndexValues(final Object object) {
IEdgeRecord vertexRecord = (IEdgeRecord) object;
Optional<? extends IPropertyRecord> maybePropertyRecord = vertexRecord.getProperties().stream()
.filter(pRecord -> pRecord.getKey().equals(this.propertyName)).findAny();
return maybePropertyRecord.map(this::getIndexValuesInternal).orElse(Collections.emptySet());
}
protected abstract Set<T> getIndexValuesInternal(IPropertyRecord record);
}
| 1,467 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphVertexIndex2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/ChronoGraphVertexIndex2.java | package org.chronos.chronograph.internal.impl.index;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.indexing.Indexer;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.index.IChronoGraphVertexIndex;
import org.chronos.common.exceptions.UnknownEnumLiteralException;
/**
* @deprecated Use {@link ChronoGraphIndex3} instead. This class only exists for backwards compatibility.
*/
@Deprecated
public class ChronoGraphVertexIndex2 extends AbstractChronoGraphIndex2 implements IChronoGraphVertexIndex {
protected ChronoGraphVertexIndex2() {
// default constructor for serialization
}
public ChronoGraphVertexIndex2(final String indexedProperty, final IndexType indexType) {
super(indexedProperty, indexType);
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public String getBackendIndexKey() {
return ChronoGraphConstants.INDEX_PREFIX_VERTEX + this.getIndexedProperty();
}
@Override
public Class<? extends Element> getIndexedElementClass() {
return Vertex.class;
}
@Override
public String toString() {
return "Index[Vertex, " + this.getIndexedProperty() + ", " + this.indexType + "]";
}
}
| 1,483 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphIndex3.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/ChronoGraphIndex3.java | package org.chronos.chronograph.internal.impl.index;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.SecondaryIndex;
import org.chronos.chronodb.api.indexing.DoubleIndexer;
import org.chronos.chronodb.api.indexing.Indexer;
import org.chronos.chronodb.api.indexing.LongIndexer;
import org.chronos.chronodb.api.indexing.StringIndexer;
import org.chronos.chronodb.internal.api.Period;
import org.chronos.chronodb.internal.impl.index.IndexingOption;
import org.chronos.chronograph.internal.api.index.ChronoGraphIndexInternal;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphIndex3 implements ChronoGraphIndexInternal {
// =================================================================================================================
// FACTORY
// =================================================================================================================
public static ChronoGraphIndex3 createFromChronoDBIndexOrNull(SecondaryIndex secondaryIndex) {
if (secondaryIndex == null) {
return null;
}
if (secondaryIndex.getIndexer() instanceof GraphPropertyIndexer<?> == false) {
return null;
}
return new ChronoGraphIndex3(secondaryIndex);
}
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
protected SecondaryIndex index;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
protected ChronoGraphIndex3() {
// default constructor for serialization
}
public ChronoGraphIndex3(final SecondaryIndex index) {
checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!");
checkArgument(index.getIndexer() instanceof GraphPropertyIndexer<?>, "The given secondary index is not a graph index.");
this.index = index;
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public String getId() {
return this.index.getId();
}
@Override
public String getParentIndexId() {
return this.index.getParentIndexId();
}
@Override
public String getBackendIndexKey() {
return this.index.getName();
}
@Override
public Set<IndexingOption> getIndexingOptions() {
return Collections.unmodifiableSet(this.index.getOptions());
}
@Override
public String getBranch() {
return this.index.getBranch();
}
@Override
public Period getValidPeriod() {
return this.index.getValidPeriod();
}
@Override
public String getIndexedProperty() {
return this.getIndexer().getGraphElementPropertyName();
}
@Override
public IndexType getIndexType() {
Indexer<?> indexer = this.getIndexer();
if (indexer instanceof StringIndexer) {
return IndexType.STRING;
} else if (indexer instanceof LongIndexer) {
return IndexType.LONG;
} else if (indexer instanceof DoubleIndexer) {
return IndexType.DOUBLE;
} else {
throw new IllegalArgumentException("The given indexer has an unknown index type: '" + indexer.getClass().getName() + "'");
}
}
@Override
public Class<? extends Element> getIndexedElementClass() {
Indexer<?> indexer = this.getIndexer();
if (indexer instanceof VertexRecordPropertyIndexer2 || indexer instanceof VertexRecordPropertyIndexer) {
return Vertex.class;
} else if (indexer instanceof EdgeRecordPropertyIndexer2 || indexer instanceof EdgeRecordPropertyIndexer) {
return Edge.class;
} else {
throw new IllegalArgumentException("The given indexer has an unknown Element type: '" + indexer.getClass().getName() + "'");
}
}
@Override
public boolean isDirty() {
return this.index.getDirty();
}
// =================================================================================================================
// HASH CODE, EQUALS, TOSTRING
// =================================================================================================================
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ChronoGraphIndex3 that = (ChronoGraphIndex3) o;
return Objects.equals(index, that.index);
}
@Override
public int hashCode() {
return Objects.hash(index);
}
@Override
public String toString() {
return "GraphIndex[" +
"id='" + this.getId() + "', " +
"parent='" + this.getParentIndexId() + "', " +
"elementType='" + this.getIndexedElementClass().getSimpleName() + "', " +
"valueType='" + this.getIndexType() + "', " +
"propertyName='" + this.getIndexedProperty() + "', " +
"branch='" + this.getBranch() + "', " +
"validPeriod='" + this.getValidPeriod() + "'" +
"]";
}
// =================================================================================================================
// HELPER METHODS
// =================================================================================================================
private GraphPropertyIndexer<?> getIndexer() {
return (GraphPropertyIndexer<?>)this.index.getIndexer();
}
}
| 6,269 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractRecordPropertyIndexer2.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/AbstractRecordPropertyIndexer2.java | package org.chronos.chronograph.internal.impl.index;
import org.chronos.chronodb.api.indexing.Indexer;
import org.chronos.chronograph.api.structure.record.Record;
import org.chronos.common.annotation.PersistentClass;
import java.util.Objects;
import static com.google.common.base.Preconditions.*;
/**
* A base class for all indexers working on {@link Record}s.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
* @param <T>
* The type of values produced by this indexer.
*/
@PersistentClass("kryo")
public abstract class AbstractRecordPropertyIndexer2<T> implements GraphPropertyIndexer<T> {
protected String propertyName;
protected AbstractRecordPropertyIndexer2() {
// default constructor for serialization
}
protected AbstractRecordPropertyIndexer2(final String propertyName) {
checkNotNull(propertyName, "Precondition violation - argument 'propertyName' must not be NULL!");
this.propertyName = propertyName;
}
public String getPropertyName(){
return this.propertyName;
}
@Override
public String getGraphElementPropertyName() {
return this.propertyName;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AbstractRecordPropertyIndexer2<?> that = (AbstractRecordPropertyIndexer2<?>) o;
return Objects.equals(propertyName, that.propertyName);
}
@Override
public int hashCode() {
return propertyName != null ? propertyName.hashCode() : 0;
}
}
| 1,525 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecordPropertyIndexer.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/VertexRecordPropertyIndexer.java | package org.chronos.chronograph.internal.impl.index;
import java.util.Optional;
import java.util.Set;
import org.chronos.chronodb.api.indexing.StringIndexer;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.internal.impl.structure.record.VertexRecord;
import org.chronos.common.annotation.PersistentClass;
/**
* An indexer working on {@link VertexRecord}s.
*
* @deprecated Superseded by {@link VertexRecordPropertyIndexer2}.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
@Deprecated
@PersistentClass("kryo")
public class VertexRecordPropertyIndexer extends AbstractRecordPropertyIndexer implements StringIndexer {
protected VertexRecordPropertyIndexer() {
// default constructor for serializer
}
public VertexRecordPropertyIndexer(final String propertyName) {
super(propertyName);
}
@Override
public boolean canIndex(final Object object) {
return object instanceof IVertexRecord;
}
@Override
public Set<String> getIndexValues(final Object object) {
IVertexRecord vertexRecord = (IVertexRecord) object;
Optional<? extends IPropertyRecord> maybePropertyRecord = vertexRecord.getProperties().stream()
.filter(pRecord -> pRecord.getKey().equals(this.propertyName)).findAny();
return this.getIndexValue(maybePropertyRecord);
}
}
| 1,410 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphBranchManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/branch/ChronoGraphBranchManagerImpl.java | package org.chronos.chronograph.internal.impl.branch;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import org.chronos.chronodb.api.Branch;
import org.chronos.chronodb.api.BranchManager;
import org.chronos.chronograph.api.branch.ChronoGraphBranchManager;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphBranchManagerImpl implements ChronoGraphBranchManager {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private final ChronoGraphInternal graph;
private final Map<Branch, GraphBranch> backingBranchToGraphBranch;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
public ChronoGraphBranchManagerImpl(final ChronoGraphInternal graph) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.graph = graph;
this.backingBranchToGraphBranch = Maps.newHashMap();
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public GraphBranch createBranch(final String branchName) {
Branch branch = this.getChronoDBBranchManager().createBranch(branchName);
return this.getOrCreateGraphBranch(branch);
}
@Override
public GraphBranch createBranch(final String branchName, final long branchingTimestamp) {
Branch branch = this.getChronoDBBranchManager().createBranch(branchName, branchingTimestamp);
return this.getOrCreateGraphBranch(branch);
}
@Override
public GraphBranch createBranch(final String parentName, final String newBranchName) {
Branch branch = this.getChronoDBBranchManager().createBranch(parentName, newBranchName);
return this.getOrCreateGraphBranch(branch);
}
@Override
public GraphBranch createBranch(final String parentName, final String newBranchName,
final long branchingTimestamp) {
Branch branch = this.getChronoDBBranchManager().createBranch(parentName, newBranchName, branchingTimestamp);
return this.getOrCreateGraphBranch(branch);
}
@Override
public boolean existsBranch(final String branchName) {
return this.getChronoDBBranchManager().existsBranch(branchName);
}
@Override
public GraphBranch getBranch(final String branchName) {
Branch backingBranch = this.getChronoDBBranchManager().getBranch(branchName);
return this.getOrCreateGraphBranch(backingBranch);
}
@Override
public Set<String> getBranchNames() {
return this.getChronoDBBranchManager().getBranchNames();
}
@Override
public Set<GraphBranch> getBranches() {
Set<Branch> branches = this.getChronoDBBranchManager().getBranches();
return branches.stream()
// map each backing branch to a graph branch
.map(this::getOrCreateGraphBranch)
// return the result as a set
.collect(Collectors.toSet());
}
@Override
public List<String> deleteBranchRecursively(final String branchName) {
List<String> deletedBranches = this.getChronoDBBranchManager().deleteBranchRecursively(branchName);
deletedBranches.forEach(deletedBranch -> this.backingBranchToGraphBranch.keySet().removeIf(branch -> Objects.equal(branch.getName(), deletedBranch)));
return deletedBranches;
}
@Override
public GraphBranch getActualBranchForQuerying(final String branchName, final long timestamp) {
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
if(!this.existsBranch(branchName)){
throw new IllegalArgumentException("Precondition violation - there is no branch with name '" + branchName + "'!");
}
GraphBranch currentBranch = this.getBranch(branchName);
while (!currentBranch.isMaster() && currentBranch.getBranchingTimestamp() >= timestamp) {
currentBranch = currentBranch.getOrigin();
}
return currentBranch;
}
// =====================================================================================================================
// INTERNAL HELPER METHODS
// =====================================================================================================================
private BranchManager getChronoDBBranchManager() {
return this.graph.getBackingDB().getBranchManager();
}
private GraphBranch getOrCreateGraphBranch(final Branch backingBranch) {
checkNotNull(backingBranch, "Precondition violation - argument 'backingBranch' must not be NULL!");
// check if we already know that branch...
GraphBranch graphBranch = this.backingBranchToGraphBranch.get(backingBranch);
if (graphBranch != null) {
// use the cached instance
return graphBranch;
}
// we don't know that branch yet; construct it
if (backingBranch.getOrigin() == null) {
// no origin -> we are dealing with the master branch
graphBranch = GraphBranchImpl.createMasterBranch(backingBranch);
} else {
// regular branch
GraphBranch originBranch = this.getOrCreateGraphBranch(backingBranch.getOrigin());
graphBranch = GraphBranchImpl.createBranch(backingBranch, originBranch);
}
// remember the graph branch in our cache
this.backingBranchToGraphBranch.put(backingBranch, graphBranch);
return graphBranch;
}
}
| 6,462 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphBranchImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/branch/GraphBranchImpl.java | package org.chronos.chronograph.internal.impl.branch;
import static com.google.common.base.Preconditions.*;
import java.util.List;
import org.chronos.chronodb.api.Branch;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronograph.api.branch.GraphBranch;
import com.google.common.collect.Lists;
public class GraphBranchImpl implements GraphBranch {
// =====================================================================================================================
// STATIC FACTORY METHODS
// =====================================================================================================================
public static GraphBranchImpl createMasterBranch(final Branch backingMasterBranch) {
checkNotNull(backingMasterBranch, "Precondition violation - argument 'backingMasterBranch' must not be NULL!");
checkArgument(backingMasterBranch.getName().equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER),
"Precondition violation - the backing branch is not the master branch!");
checkArgument(backingMasterBranch.getOrigin() == null,
"Precondition violation - the backing branch is not the master branch!");
return new GraphBranchImpl(backingMasterBranch, null);
}
public static GraphBranchImpl createBranch(final Branch backingBranch, final GraphBranch origin) {
checkNotNull(backingBranch, "Precondition violation - argument 'backingMasterBranch' must not be NULL!");
checkNotNull(origin, "Precondition violation - argument 'origin' must not be NULL!");
checkArgument(backingBranch.getOrigin().getName().equals(origin.getName()),
"Precondition violation - the arguments do not refer to the same branch!");
return new GraphBranchImpl(backingBranch, origin);
}
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private final Branch backingBranch;
private final GraphBranch origin;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
protected GraphBranchImpl(final Branch backingBranch, final GraphBranch origin) {
checkNotNull(backingBranch, "Precondition violation - argument 'backingBranch' must not be NULL!");
this.backingBranch = backingBranch;
this.origin = origin;
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public String getName() {
return this.backingBranch.getName();
}
@Override
public GraphBranch getOrigin() {
return this.origin;
}
@Override
public long getBranchingTimestamp() {
return this.backingBranch.getBranchingTimestamp();
}
@Override
public List<GraphBranch> getOriginsRecursive() {
if (this.origin == null) {
// we are the master branch; by definition, we return an empty list (see JavaDoc).
return Lists.newArrayList();
} else {
// we are not the master branch. Ask the origin to create the list for us
List<GraphBranch> origins = this.getOrigin().getOriginsRecursive();
// ... and add our immediate parent to it.
origins.add(this.getOrigin());
return origins;
}
}
@Override
public long getNow() {
return this.backingBranch.getNow();
}
// =====================================================================================================================
// HASH CODE & EQUALS
// =====================================================================================================================
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.backingBranch == null ? 0 : this.backingBranch.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;
}
GraphBranchImpl other = (GraphBranchImpl) obj;
if (this.backingBranch == null) {
if (other.backingBranch != null) {
return false;
}
} else if (!this.backingBranch.equals(other.backingBranch)) {
return false;
}
return true;
}
}
| 4,557 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphQueryProcessor.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/ChronoGraphQueryProcessor.java | package org.chronos.chronograph.internal.impl.transaction;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.exceptions.UnknownKeyspaceException;
import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoElement;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.transaction.GraphTransactionContext;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.index.ChronoGraphIndexManagerInternal;
import org.chronos.chronograph.internal.impl.util.ChronoGraphQueryUtil;
import org.chronos.chronograph.internal.impl.util.ChronoProxyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphQueryProcessor {
private static final Logger log = LoggerFactory.getLogger(ChronoGraphQueryProcessor.class);
private final StandardChronoGraphTransaction tx;
public ChronoGraphQueryProcessor(final StandardChronoGraphTransaction tx) {
checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!");
this.tx = tx;
}
public Iterator<Vertex> getAllVerticesIterator() {
ChronoDBTransaction tx = this.tx.getBackingDBTransaction();
Set<String> keySet = Sets.newHashSet();
try {
keySet = tx.keySet(ChronoGraphConstants.KEYSPACE_VERTEX);
} catch (UnknownKeyspaceException ignored) {
}
GraphTransactionContext context = this.tx.getContext();
if (context.isDirty() == false) {
// no transient modifications; return the persistent state directly
return new VertexResolvingIterator(keySet.iterator(), ElementLoadMode.LAZY);
}
// our context is dirty, therefore we have to add all new vertices and remove all deleted vertices
Set<String> modifiedKeySet = Sets.newHashSet();
// TODO [Performance] ChronoGraph: refactor this once we have proper "is new" handling for transient vertices
// check for all vertices if they were removed
Set<String> removedVertexIds = Sets.newHashSet();
for (ChronoVertex vertex : context.getModifiedVertices()) {
String id = vertex.id();
if (vertex.isRemoved()) {
removedVertexIds.add(id);
} else {
modifiedKeySet.add(id);
}
}
for (String id : keySet) {
if (removedVertexIds.contains(id) == false) {
modifiedKeySet.add(id);
}
}
Iterator<Vertex> resultIterator = new VertexResolvingIterator(modifiedKeySet.iterator(), ElementLoadMode.LAZY);
return ChronoProxyUtil.replaceVerticesByProxies(resultIterator, this.tx);
}
public Iterator<Vertex> getVerticesIterator(final Iterable<String> chronoVertexIds,
final ElementLoadMode loadMode) {
checkNotNull(chronoVertexIds, "Precondition violation - argument 'chronoVertexIds' must not be NULL!");
checkNotNull(loadMode, "Precondition violation - argument 'loadMode' must not be NULL!");
GraphTransactionContext context = this.tx.getContext();
Set<String> modifiedSet = Sets.newHashSet(chronoVertexIds);
if (context.isDirty()) {
// consider deleted vertices
for (String vertexId : chronoVertexIds) {
if (context.isVertexModified(vertexId) == false) {
// vertex is not modified, keep it
modifiedSet.add(vertexId);
} else {
// vertex may have been removed
ChronoVertex vertex = context.getModifiedVertex(vertexId);
if (vertex.isRemoved() == false) {
// vertex still exists, keep it.
// We have to add it to the set because it may have been
// added during this transaction. If it was just modified,
// it will already be in the set and the 'add' operation
// is a no-op.
modifiedSet.add(vertexId);
} else {
// vertex was removed, drop it
modifiedSet.remove(vertexId);
}
}
}
}
Iterator<Vertex> resultIterator = new VertexResolvingIterator(modifiedSet.iterator(), loadMode);
return ChronoProxyUtil.replaceVerticesByProxies(resultIterator, this.tx);
}
public Iterator<Edge> getAllEdgesIterator() {
ChronoDBTransaction tx = this.tx.getBackingDBTransaction();
Set<String> keySet = Sets.newHashSet();
try {
keySet = tx.keySet(ChronoGraphConstants.KEYSPACE_EDGE);
} catch (UnknownKeyspaceException ignored) {
}
GraphTransactionContext context = this.tx.getContext();
if (context.isDirty() == false) {
// no transient modifications; return the persistent state directly
return new EdgeResolvingIterator(keySet.iterator(), ElementLoadMode.LAZY);
}
// our context is dirty, therefore we have to add all new edges and remove all deleted edges
Set<String> modifiedKeySet = Sets.newHashSet();
// TODO [Performance] ChronoGraph: refactor this once we have proper "is new" handling for transient edges
// check for all edges if they were removed
Set<String> removedEdgeIds = Sets.newHashSet();
for (ChronoEdge edge : context.getModifiedEdges()) {
String id = edge.id();
if (edge.isRemoved()) {
removedEdgeIds.add(id);
} else {
modifiedKeySet.add(id);
}
}
for (String id : keySet) {
if (removedEdgeIds.contains(id) == false) {
modifiedKeySet.add(id);
}
}
Iterator<Edge> edges = new EdgeResolvingIterator(modifiedKeySet.iterator(), ElementLoadMode.LAZY);
return ChronoProxyUtil.replaceEdgesByProxies(edges, this.tx);
}
public Iterator<Edge> getEdgesIterator(final Iterable<String> chronoEdgeIds, ElementLoadMode loadMode) {
checkNotNull(chronoEdgeIds, "Precondition violation - argument 'chronoEdgeIds' must not be NULL!");
checkNotNull(loadMode, "Precondition violation - argument 'loadMode' must not be NULL!");
GraphTransactionContext context = this.tx.getContext();
Set<String> modifiedSet = Sets.newHashSet(chronoEdgeIds);
if (context.isDirty()) {
// consider deleted edges
for (String edgeId : chronoEdgeIds) {
if (context.isEdgeModified(edgeId) == false) {
// edge is not modified, keep it
modifiedSet.add(edgeId);
} else {
// edge may have been removed
ChronoEdge edge = context.getModifiedEdge(edgeId);
if (edge.isRemoved() == false) {
// edge still exists, keep it.
// We have to add it to the set because it may have been
// added during this transaction. If it was just modified,
// it will already be in the set and the 'add' operation
// is a no-op.
modifiedSet.add(edgeId);
} else {
// edge was removed, drop it
modifiedSet.remove(edgeId);
}
}
}
}
Iterator<Edge> edges = new EdgeResolvingIterator(modifiedSet.iterator(), loadMode);
return ChronoProxyUtil.replaceEdgesByProxies(edges, this.tx);
}
// =====================================================================================================================
// INTERNAL HELPER METHODS
// =====================================================================================================================
private ChronoGraphIndexManagerInternal getIndexManager() {
String branchName = this.tx.getBackingDBTransaction().getBranchName();
return (ChronoGraphIndexManagerInternal) this.tx.getGraph().getIndexManagerOnBranch(branchName);
}
// =====================================================================================================================
// INNER CLASSES
// =====================================================================================================================
private class VertexResolvingIterator implements Iterator<Vertex> {
private final ElementLoadMode loadMode;
private final Iterator<?> idIterator;
private Vertex nextVertex;
private VertexResolvingIterator(final Iterator<?> idIterator, final ElementLoadMode loadMode) {
checkNotNull(idIterator, "Precondition violation - argument 'idIterator' must not be NULL!");
checkNotNull(loadMode, "Precondition violation - argument 'loadMode' must not be NULL!");
this.idIterator = idIterator;
this.loadMode = loadMode;
this.tryResolveNextVertex();
}
@Override
public boolean hasNext() {
return this.nextVertex != null;
}
@Override
public Vertex next() {
if (this.nextVertex == null) {
throw new NoSuchElementException();
}
Vertex vertex = this.nextVertex;
this.tryResolveNextVertex();
return vertex;
}
private void tryResolveNextVertex() {
while (this.idIterator.hasNext()) {
// check if we have a vertex for this ID
Object next = this.idIterator.next();
String vertexId;
if (next instanceof String) {
vertexId = (String) next;
} else {
vertexId = String.valueOf(next);
}
Vertex vertex = ChronoGraphQueryProcessor.this.tx.loadVertex(vertexId, this.loadMode);
if (vertex != null) {
this.nextVertex = vertex;
return;
}
}
// we ran out of IDs -> there cannot be a next vertex
this.nextVertex = null;
}
}
private class EdgeResolvingIterator implements Iterator<Edge> {
private final Iterator<?> idIterator;
private final ElementLoadMode loadMode;
private Edge nextEdge;
private EdgeResolvingIterator(final Iterator<?> idIterator, ElementLoadMode loadMode) {
checkNotNull(idIterator, "Precondition violation - argument 'idIterator' must not be NULL!");
checkNotNull(loadMode, "Precondition violation - argument 'loadMode' must not be NULL!");
this.idIterator = idIterator;
this.loadMode = loadMode;
this.tryResolveNextEdge();
}
@Override
public boolean hasNext() {
return this.nextEdge != null;
}
@Override
public Edge next() {
if (this.nextEdge == null) {
throw new NoSuchElementException();
}
Edge edge = this.nextEdge;
this.tryResolveNextEdge();
return edge;
}
private void tryResolveNextEdge() {
while (this.idIterator.hasNext()) {
// check if we have a vertex for this ID
Object next = this.idIterator.next();
String edgeId;
if (next instanceof String) {
edgeId = (String) next;
} else {
edgeId = String.valueOf(next);
}
Edge edge = ChronoGraphQueryProcessor.this.tx.loadEdge(edgeId, this.loadMode);
if (edge != null) {
this.nextEdge = edge;
return;
}
}
// we ran out of IDs -> there cannot be a next edge
this.nextEdge = null;
}
}
private static class PropertyValueFilterPredicate<V extends Element> implements Predicate<V> {
private final Set<SearchSpecification<?, ?>> searchSpecifications;
private PropertyValueFilterPredicate(final Set<SearchSpecification<?, ?>> searchSpecs) {
checkNotNull(searchSpecs, "Precondition violation - argument 'searchSpecs' must not be NULL!");
this.searchSpecifications = Sets.newHashSet(searchSpecs);
}
@Override
public boolean test(final V element) {
ChronoElement chronoElement = (ChronoElement) element;
if (chronoElement.isRemoved()) {
// never consider removed elements
return false;
}
for (SearchSpecification<?, ?> searchSpec : this.searchSpecifications) {
if (element.property(searchSpec.getIndex().getName()).isPresent() == false) {
// the property in question is not present, it is NOT possible to make
// any decision if it matches the given search criterion or not. In particular,
// when the search is negated (e.g. 'not equals'), we decide to have a non-match
// for non-existing properties
return false;
}
Object propertyValue = element.value(searchSpec.getIndex().getName());
boolean searchSpecApplies = ChronoGraphQueryUtil.searchSpecApplies(searchSpec, propertyValue);
if (searchSpecApplies == false) {
// element failed to pass this filter
return false;
}
}
// element passed all filters
return true;
}
}
}
| 14,491 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphTransactionContextImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/GraphTransactionContextImpl.java | package org.chronos.chronograph.internal.impl.transaction;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoElement;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.api.transaction.GraphTransactionContextInternal;
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.graph.ChronoVertexImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoVertexProperty;
import org.chronos.chronograph.internal.impl.structure.graph.proxy.ChronoEdgeProxy;
import org.chronos.chronograph.internal.impl.structure.graph.proxy.ChronoVertexProxy;
import org.chronos.chronograph.internal.impl.util.ChronoGraphQueryUtil;
import org.chronos.common.logging.ChronosLogMarker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.*;
import static org.chronos.common.logging.ChronosLogMarker.*;
/**
* The {@link GraphTransactionContextImpl} keeps track of the elements which have been modified by client code.
* <p>
* <p>
* A TransactionContext is always associated with a {@link ChronoGraphTransaction} that contains the context. The context may be cleared when a {@link ChronoGraphTransaction#rollback()} occurs on the owning transaction.
*
* @author martin.haeusler@uibk.ac.at -- Initial Contribution and API
*/
public class GraphTransactionContextImpl implements GraphTransactionContextInternal {
private static final Logger log = LoggerFactory.getLogger(GraphTransactionContextImpl.class);
private final SetMultimap<String, String> removedVertexPropertyKeyToOwnerId = HashMultimap.create();
private final SetMultimap<String, String> removedEdgePropertyKeyToOwnerId = HashMultimap.create();
private final Table<String, String, ChronoProperty<?>> vertexPropertyNameToOwnerIdToModifiedProperty = HashBasedTable.create();
private final Table<String, String, ChronoProperty<?>> edgePropertyNameToOwnerIdToModifiedProperty = HashBasedTable.create();
private final Map<String, ChronoVertexImpl> modifiedVertices = Maps.newHashMap();
private final Map<String, ChronoEdgeImpl> modifiedEdges = Maps.newHashMap();
private final Map<String, ChronoVertexImpl> loadedVertices = new MapMaker().weakValues().makeMap();
private final Map<String, ChronoEdgeImpl> loadedEdges = new MapMaker().weakValues().makeMap();
private final Map<String, ChronoVertexProxy> idToVertexProxy = new MapMaker().weakValues().makeMap();
private final Map<String, ChronoEdgeProxy> idToEdgeProxy = new MapMaker().weakValues().makeMap();
private final Map<String, Map<String, Object>> keyspaceToModifiedVariables = Maps.newHashMap();
// =====================================================================================================================
// LOADED ELEMENT CACHE API
// =====================================================================================================================
@Override
public Set<String> getLoadedVertexIds(){
return Collections.unmodifiableSet(this.loadedVertices.keySet());
}
@Override
public ChronoVertexImpl getLoadedVertexForId(final String id) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
return this.loadedVertices.get(id);
}
@Override
public void registerLoadedVertex(final ChronoVertexImpl vertex) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
this.loadedVertices.put(vertex.id(), vertex);
ChronoVertexProxy proxy = this.getWeaklyCachedVertexProxy(vertex.id());
if (proxy != null) {
// the proxy already exists; make sure it points to the correct instance
proxy.rebindTo(vertex);
}
}
@Override
public Set<String> getLoadedEdgeIds(){
return Collections.unmodifiableSet(this.loadedEdges.keySet());
}
@Override
public ChronoEdgeImpl getLoadedEdgeForId(final String id) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
return this.loadedEdges.get(id);
}
@Override
public void registerLoadedEdge(final ChronoEdgeImpl edge) {
checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!");
this.loadedEdges.put(edge.id(), edge);
ChronoEdgeProxy proxy = this.getWeaklyCachedEdgeProxy(edge.id());
if (proxy != null) {
// the proxy already exists; make sure it points to the correct instance
proxy.rebindTo(edge);
}
}
@Override
public void registerVertexProxyInCache(final ChronoVertexProxy proxy) {
checkNotNull(proxy, "Precondition violation - argument 'proxy' must not be NULL!");
this.idToVertexProxy.put(proxy.id(), proxy);
}
@Override
public void registerEdgeProxyInCache(final ChronoEdgeProxy proxy) {
checkNotNull(proxy, "Precondition violation - argument 'proxy' must not be NULL!");
this.idToEdgeProxy.put(proxy.id(), proxy);
}
/**
* Returns the {@link ChronoVertexProxy Vertex Proxy} for the {@link Vertex} with the given ID.
* <p>
* <p>
* Bear in mind that proxies are stored in a weak fashion, i.e. they may be garbage collected if they are not referenced anywhere else. This method may and <b>will</b> return <code>null</code> in such cases. Think of this method as a cache.
* <p>
* <p>
* To reliably get a proxy, use {@link #getOrCreateVertexProxy(Vertex)} instead.
*
* @param vertexId The ID of the vertex to get the cached proxy for. Must not be <code>null</code>.
* @return The vertex proxy for the given vertex ID, or <code>null</code> if none is cached.
*/
private ChronoVertexProxy getWeaklyCachedVertexProxy(final String vertexId) {
checkNotNull(vertexId, "Precondition violation - argument 'vertexId' must not be NULL!");
return this.idToVertexProxy.get(vertexId);
}
@Override
public ChronoVertexProxy getOrCreateVertexProxy(final Vertex vertex) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
if (vertex instanceof ChronoVertexProxy) {
// already is a proxy
return (ChronoVertexProxy) vertex;
}
// check if we have a proxy
ChronoVertexProxy proxy = this.getWeaklyCachedVertexProxy((String) vertex.id());
if (proxy != null) {
// we already have a proxy; reuse it
return proxy;
}
// we don't have a proxy yet; create one
proxy = new ChronoVertexProxy((ChronoVertexImpl) vertex);
this.registerVertexProxyInCache(proxy);
return proxy;
}
/**
* Returns the {@link ChronoEdgeProxy Edge Proxy} for the {@link Edge} with the given ID.
* <p>
* <p>
* Bear in mind that proxies are stored in a weak fashion, i.e. they may be garbage collected if they are not referenced anywhere else. This method may and <b>will</b> return <code>null</code> in such cases. Think of this method as a cache.
* <p>
* <p>
* To reliably get a proxy, use {@link #getOrCreateEdgeProxy(Edge)} instead.
*
* @param edgeId The ID of the vertex to get the cached proxy for. Must not be <code>null</code>.
* @return The edge proxy for the given vertex ID, or <code>null</code> if none is cached.
*/
private ChronoEdgeProxy getWeaklyCachedEdgeProxy(final String edgeId) {
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
return this.idToEdgeProxy.get(edgeId);
}
@Override
public ChronoEdgeProxy getOrCreateEdgeProxy(final Edge edge) {
checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!");
if (edge instanceof ChronoEdgeProxy) {
// already is a proxy
return (ChronoEdgeProxy) edge;
}
// check if we have a proxy
ChronoEdgeProxy proxy = this.getWeaklyCachedEdgeProxy((String) edge.id());
if (proxy == null) {
// we don't have a proxy yet; create one
proxy = new ChronoEdgeProxy((ChronoEdgeImpl) edge);
}
this.registerEdgeProxyInCache(proxy);
return proxy;
}
// =====================================================================================================================
// MODIFICATION (IS-DIRTY) API
// =====================================================================================================================
@Override
public Set<ChronoVertex> getModifiedVertices() {
return Collections.unmodifiableSet(Sets.newHashSet(this.modifiedVertices.values()));
}
@Override
public Set<ChronoEdge> getModifiedEdges() {
return Collections.unmodifiableSet(Sets.newHashSet(this.modifiedEdges.values()));
}
@Override
public Set<String> getModifiedVariables(String keyspace) {
Map<String, Object> keyspaceModifications = this.keyspaceToModifiedVariables.get(keyspace);
if (keyspaceModifications == null) {
return Collections.emptySet();
} else {
return Collections.unmodifiableSet(keyspaceModifications.keySet());
}
}
@Override
public Set<ChronoElement> getModifiedElements() {
return Sets.union(this.getModifiedVertices(), this.getModifiedEdges());
}
@Override
public boolean isDirty() {
return this.modifiedVertices.isEmpty() == false || this.modifiedEdges.isEmpty() == false
|| this.vertexPropertyNameToOwnerIdToModifiedProperty.isEmpty() == false
|| this.edgePropertyNameToOwnerIdToModifiedProperty.isEmpty() == false
|| this.removedVertexPropertyKeyToOwnerId.isEmpty() == false
|| this.removedEdgePropertyKeyToOwnerId.isEmpty() == false
|| this.keyspaceToModifiedVariables.values().stream().allMatch(Map::isEmpty) == false;
}
@Override
public boolean isVertexModified(final Vertex vertex) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
String vertexId = (String) vertex.id();
return this.isVertexModified(vertexId);
}
@Override
public boolean isVertexModified(final String vertexId) {
checkNotNull(vertexId, "Precondition violation - argument 'vertexId' must not be NULL!");
return this.modifiedVertices.containsKey(vertexId);
}
@Override
public void markVertexAsModified(final ChronoVertexImpl vertex) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
this.logMarkVertexAsModified(vertex);
this.modifiedVertices.put(vertex.id(), vertex);
}
@Override
public boolean isEdgeModified(final Edge edge) {
checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!");
String edgeId = (String) edge.id();
return this.modifiedEdges.containsKey(edgeId);
}
@Override
public boolean isEdgeModified(final String edgeId) {
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
return this.modifiedEdges.containsKey(edgeId);
}
@Override
public void markEdgeAsModified(final ChronoEdgeImpl edge) {
checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!");
this.logMarkEdgeAsModified(edge);
this.modifiedEdges.put(edge.id(), edge);
}
@Override
public void markPropertyAsModified(final ChronoProperty<?> property) {
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
this.logMarkPropertyAsModified(property);
Element owner = property.element();
String ownerId = (String) owner.id();
if (owner instanceof Vertex) {
// mark the property as "modified"
this.vertexPropertyNameToOwnerIdToModifiedProperty.put(property.key(), ownerId, property);
// the property is no longer "removed"
this.removedVertexPropertyKeyToOwnerId.remove(property.key(), ownerId);
} else if (owner instanceof Edge) {
// mark the property as "modified"
this.edgePropertyNameToOwnerIdToModifiedProperty.put(property.key(), ownerId, property);
// the property is no longer "removed"
this.removedEdgePropertyKeyToOwnerId.remove(property.key(), ownerId);
} else if (owner instanceof ChronoVertexProperty) {
// mark the vertex property itself as modified
ChronoVertexProperty<?> vp = (ChronoVertexProperty<?>) owner;
this.vertexPropertyNameToOwnerIdToModifiedProperty.put(vp.key(), ownerId, vp);
} else {
throw new IllegalArgumentException("Unknown subclass of Element: " + owner.getClass().getName());
}
}
@Override
public void markPropertyAsDeleted(final ChronoProperty<?> property) {
this.logMarkPropertyAsRemoved(property);
Element owner = property.element();
String ownerId = (String) owner.id();
if (owner instanceof Vertex) {
// the property is no longer "modified"
this.vertexPropertyNameToOwnerIdToModifiedProperty.remove(property.key(), ownerId);
// the property now "removed"
this.removedVertexPropertyKeyToOwnerId.put(property.key(), ownerId);
} else if (owner instanceof Edge) {
// the property is no longer "modified"
this.edgePropertyNameToOwnerIdToModifiedProperty.remove(property.key(), ownerId);
// the property is now "removed"
this.removedEdgePropertyKeyToOwnerId.put(property.key(), ownerId);
} else if (owner instanceof ChronoVertexProperty) {
// mark the owning property as modified
ChronoVertexProperty<?> vp = (ChronoVertexProperty<?>) owner;
this.vertexPropertyNameToOwnerIdToModifiedProperty.put(vp.key(), ownerId, vp);
} else {
throw new IllegalArgumentException("Unknown subclass of Element: " + owner.getClass().getName());
}
}
public Set<Vertex> getVerticesWithModificationsOnProperty(String property) {
Set<String> vertexIds = this.vertexPropertyNameToOwnerIdToModifiedProperty.row(property).keySet();
return vertexIds.stream().map(this::getModifiedVertex).collect(Collectors.toSet());
}
public Set<Edge> getEdgesWithModificationsOnProperty(String property) {
Set<String> vertexIds = this.edgePropertyNameToOwnerIdToModifiedProperty.row(property).keySet();
return vertexIds.stream().map(this::getModifiedEdge).collect(Collectors.toSet());
}
@Override
public boolean isVariableModified(final String keyspace, final String variableName) {
checkNotNull(variableName, "Precondition violation - argument 'variableName' must not be NULL!");
Map<String, Object> keyspaceMap = this.keyspaceToModifiedVariables.get(keyspace);
if (keyspaceMap == null) {
return false;
}
return keyspaceMap.containsKey(variableName);
}
@Override
public boolean isVariableRemoved(final String keyspace, final String variableName) {
checkNotNull(variableName, "Precondition violation - argument 'variableName' must not be NULL!");
Map<String, Object> keyspaceMap = this.keyspaceToModifiedVariables.get(keyspace);
if (keyspaceMap == null) {
return false;
}
return keyspaceMap.containsKey(variableName) && keyspaceMap.get(variableName) == null;
}
@Override
public Object getModifiedVariableValue(final String keyspace, final String variableName) {
checkNotNull(variableName, "Precondition violation - argument 'variableName' must not be NULL!");
Map<String, Object> keyspaceMap = this.keyspaceToModifiedVariables.get(keyspace);
if (keyspaceMap == null) {
return null;
}
return keyspaceMap.getOrDefault(variableName, null);
}
// =====================================================================================================================
// GRAPH VARIABLES API
// =====================================================================================================================
@Override
public void removeVariable(final String keyspace, final String variableName) {
checkNotNull(variableName, "Precondition violation - argument 'variableName' must not be NULL!");
Map<String, Object> keyspaceMap = this.keyspaceToModifiedVariables.computeIfAbsent(keyspace, k -> Maps.newHashMap());
keyspaceMap.put(variableName, null);
}
@Override
public void setVariableValue(final String keyspace, final String variableName, final Object value) {
checkNotNull(variableName, "Precondition violation - argument 'variableName' must not be NULL!");
checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!");
Map<String, Object> keyspaceMap = this.keyspaceToModifiedVariables.computeIfAbsent(keyspace, k -> Maps.newHashMap());
keyspaceMap.put(variableName, value);
}
@Override
public Set<String> getRemovedVariables(String keyspace) {
Map<String, Object> keyspaceMap = this.keyspaceToModifiedVariables.get(keyspace);
if (keyspaceMap == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(keyspaceMap.entrySet().stream()
.filter(entry -> entry.getValue() == null)
.map(Entry::getKey)
.collect(Collectors.toSet())
);
}
@Override
public void clear() {
this.modifiedVertices.clear();
this.modifiedEdges.clear();
this.vertexPropertyNameToOwnerIdToModifiedProperty.clear();
this.edgePropertyNameToOwnerIdToModifiedProperty.clear();
this.removedVertexPropertyKeyToOwnerId.clear();
this.removedEdgePropertyKeyToOwnerId.clear();
this.keyspaceToModifiedVariables.clear();
this.loadedVertices.clear();
this.loadedEdges.clear();
this.idToVertexProxy.clear();
this.idToEdgeProxy.clear();
}
@Override
public ChronoVertexImpl getModifiedVertex(final String id) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
return this.modifiedVertices.get(id);
}
@Override
public ChronoEdgeImpl getModifiedEdge(final String id) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
return this.modifiedEdges.get(id);
}
@Override
public Set<String> getModifiedVariableKeyspaces() {
return Collections.unmodifiableSet(this.keyspaceToModifiedVariables.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.filter(entry -> !entry.getValue().isEmpty())
.map(Entry::getKey)
.collect(Collectors.toSet()));
}
// =====================================================================================================================
// DEBUG LOGGING
// =====================================================================================================================
private void logMarkVertexAsModified(final ChronoVertex vertex) {
if(!log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)){
return;
}
// prepare some debug output
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("[GRAPH MODIFICATION] Marking Vertex as modified: ");
messageBuilder.append(vertex.toString());
messageBuilder.append(" (Object ID: '");
messageBuilder.append(System.identityHashCode(vertex));
messageBuilder.append("). ");
if (this.modifiedVertices.containsKey(vertex.id())) {
messageBuilder.append("This Vertex was already marked as modified in this transaction.");
} else {
messageBuilder.append("This Vertex has not yet been marked as modified in this transaction.");
}
log.trace(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS, messageBuilder.toString());
}
private void logMarkEdgeAsModified(final ChronoEdge edge) {
if(!log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)){
return;
}
// prepare some debug output
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("[GRAPH MODIFICATION] Marking Edge as modified: ");
messageBuilder.append(edge.toString());
messageBuilder.append(" (Object ID: '");
messageBuilder.append(System.identityHashCode(edge));
messageBuilder.append("). ");
if (this.modifiedEdges.containsKey(edge.id())) {
messageBuilder.append("This Edge was already marked as modified in this transaction.");
} else {
messageBuilder.append("This Edge has not yet been marked as modified in this transaction.");
}
log.trace(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS, messageBuilder.toString());
}
private void logMarkPropertyAsModified(final ChronoProperty<?> property) {
if(!log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)){
return;
}
// prepare some debug output
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("[GRAPH MODIFICATION] Marking Property as modified: ");
messageBuilder.append(property.toString());
messageBuilder.append(" (Object ID: '");
messageBuilder.append(System.identityHashCode(property));
messageBuilder.append("). ");
if (property.isPresent()) {
ChronoElement owner = property.element();
messageBuilder.append("Property is owned by: ");
messageBuilder.append(owner.toString());
messageBuilder.append(" (Object ID: ");
messageBuilder.append(System.identityHashCode(owner));
messageBuilder.append(")");
}
log.trace(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS, messageBuilder.toString());
}
private void logMarkPropertyAsRemoved(final ChronoProperty<?> property) {
if(!log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)){
return;
}
// prepare some debug output
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append("[GRAPH MODIFICATION] Marking Property as removed: ");
messageBuilder.append(property.toString());
messageBuilder.append(" (Object ID: '");
messageBuilder.append(System.identityHashCode(property));
messageBuilder.append("). ");
if (property.isPresent()) {
ChronoElement owner = property.element();
messageBuilder.append("Property is owned by: ");
messageBuilder.append(owner.toString());
messageBuilder.append(" (Object ID: ");
messageBuilder.append(System.identityHashCode(owner));
messageBuilder.append(")");
}
log.trace(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS, messageBuilder.toString());
}
}
| 24,481 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTransactionManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/ChronoGraphTransactionManagerImpl.java | package org.chronos.chronograph.internal.impl.transaction;
import com.google.common.collect.Maps;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.util.AbstractThreadLocalTransaction;
import org.apache.tinkerpop.gremlin.structure.util.TransactionException;
import org.chronos.chronodb.api.ChronoDB;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.exceptions.ChronoDBBranchingException;
import org.chronos.chronodb.api.exceptions.ChronoDBTransactionException;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.ChronoGraphTransactionManager;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.transaction.threaded.ChronoThreadedTransactionGraph;
import java.util.Date;
import java.util.Map;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphTransactionManagerImpl extends AbstractThreadLocalTransaction
implements ChronoGraphTransactionManager {
private final ChronoGraphInternal chronoGraph;
private final Map<Thread, ChronoGraphTransaction> threadToTx = Maps.newConcurrentMap();
private final boolean allowAutoTx;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
public ChronoGraphTransactionManagerImpl(final ChronoGraphInternal graph) {
super(graph);
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.chronoGraph = graph;
this.allowAutoTx = this.chronoGraph.getChronoGraphConfiguration().isTransactionAutoOpenEnabled();
}
// =====================================================================================================================
// TRANSACTION OPEN METHODS
// =====================================================================================================================
@Override
public boolean isOpen() {
return this.threadToTx.get(Thread.currentThread()) != null;
}
@Override
public void open(final long timestamp) {
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
this.assertNoOpenTransactionExists();
ChronoDB chronoDB = this.chronoGraph.getBackingDB();
ChronoDBTransaction backendTransaction = chronoDB.tx(timestamp);
ChronoGraphTransaction transaction = new StandardChronoGraphTransaction(this.chronoGraph, backendTransaction);
this.threadToTx.put(Thread.currentThread(), transaction);
}
@Override
public void open(final Date date) {
checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!");
this.open(date.getTime());
}
@Override
public void open(final String branch) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
this.assertNoOpenTransactionExists();
ChronoDB chronoDB = this.chronoGraph.getBackingDB();
ChronoDBTransaction backendTransaction = chronoDB.tx(branch);
ChronoGraphTransaction transaction = new StandardChronoGraphTransaction(this.chronoGraph, backendTransaction);
this.threadToTx.put(Thread.currentThread(), transaction);
}
@Override
public void open(final String branch, final Date date) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!");
this.open(branch, date.getTime());
}
@Override
public void open(final String branch, final long timestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
this.assertNoOpenTransactionExists();
ChronoDB chronoDB = this.chronoGraph.getBackingDB();
ChronoDBTransaction backendTransaction = chronoDB.tx(branch, timestamp);
ChronoGraphTransaction transaction = new StandardChronoGraphTransaction(this.chronoGraph, backendTransaction);
this.threadToTx.put(Thread.currentThread(), transaction);
}
@Override
protected void doOpen() {
this.assertNoOpenTransactionExists();
ChronoDB chronoDB = this.chronoGraph.getBackingDB();
ChronoDBTransaction backendTransaction = chronoDB.tx();
ChronoGraphTransaction transaction = new StandardChronoGraphTransaction(this.chronoGraph, backendTransaction);
this.threadToTx.put(Thread.currentThread(), transaction);
}
@Override
protected void doReadWrite() {
if (this.allowAutoTx) {
super.doReadWrite();
} else {
Transaction.READ_WRITE_BEHAVIOR.MANUAL.accept(this);
}
}
@Override
public void reset() {
// make sure that a transaction exists (tx auto), or an exception is thrown if none is open (tx strict)
this.readWrite();
String branchName = this.getCurrentTransaction().getBranchName();
this.doReset(branchName, null);
}
@Override
public void reset(final long timestamp) {
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
// make sure that a transaction exists (tx auto), or an exception is thrown if none is open (tx strict)
this.readWrite();
String branchName = this.getCurrentTransaction().getBranchName();
this.doReset(branchName, timestamp);
}
@Override
public void reset(final Date date) {
checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!");
this.reset(date.getTime());
}
@Override
public void reset(final String branch, final long timestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
// make sure that a transaction exists (tx auto), or an exception is thrown if none is open (tx strict)
this.readWrite();
this.doReset(branch, timestamp);
}
@Override
public void reset(final String branch, final Date date) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!");
this.reset(branch, date.getTime());
}
protected void doReset(final String branch, final Long timestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
// assert that target branch exists
boolean branchExists = this.chronoGraph.getBackingDB().getBranchManager().existsBranch(branch);
if (branchExists == false) {
throw new ChronoDBBranchingException("There is no branch named '" + branch + "'!");
}
// branch exists, perform the rollback on the current transaction
this.rollback();
// decide whether to jump to head revision or to a specific version
if (timestamp == null) {
// jump to head revision
this.open(branch);
} else {
// jump to given revision
this.open(branch, timestamp);
}
}
// =====================================================================================================================
// THREADED TX METHODS
// =====================================================================================================================
@Override
@SuppressWarnings("unchecked")
public ChronoGraph createThreadedTx() {
return new ChronoThreadedTransactionGraph(this.chronoGraph, ChronoDBConstants.MASTER_BRANCH_IDENTIFIER);
}
@Override
public ChronoGraph createThreadedTx(final long timestamp) {
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
return new ChronoThreadedTransactionGraph(this.chronoGraph, ChronoDBConstants.MASTER_BRANCH_IDENTIFIER,
timestamp);
}
@Override
public ChronoGraph createThreadedTx(final Date date) {
checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!");
return this.createThreadedTx(date.getTime());
}
@Override
public ChronoGraph createThreadedTx(final String branchName) {
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
return new ChronoThreadedTransactionGraph(this.chronoGraph, branchName);
}
@Override
public ChronoGraph createThreadedTx(final String branchName, final long timestamp) {
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
return new ChronoThreadedTransactionGraph(this.chronoGraph, branchName, timestamp);
}
@Override
public ChronoGraph createThreadedTx(final String branchName, final Date date) {
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!");
return this.createThreadedTx(branchName, date.getTime());
}
// =====================================================================================================================
// COMMIT & ROLLBACK
// =====================================================================================================================
@Override
protected void doCommit() throws TransactionException {
ChronoGraphTransaction transaction = this.threadToTx.get(Thread.currentThread());
if (transaction == null) {
throw new TransactionException("No Graph Transaction is open on this thread; cannot perform commit!");
}
try {
transaction.commit();
} catch (ChronoDBTransactionException e) {
throw new TransactionException("Commit failed due to exception in ChronoDB: " + e.toString(), e);
} finally {
this.threadToTx.remove(Thread.currentThread());
}
}
@Override
public long commitAndReturnTimestamp() {
return this.commitAndReturnTimestamp(null);
}
@Override
public void commit(final Object metadata) {
// discard the return value to remain compliant with TinkerPop
this.commitAndReturnTimestamp(metadata);
}
@Override
public long commitAndReturnTimestamp(Object metadata) {
readWrite();
ChronoGraphTransaction transaction = this.threadToTx.get(Thread.currentThread());
if (transaction == null) {
throw new RuntimeException("No Graph Transaction is open on this thread; cannot perform commit!");
}
try {
long timestamp = transaction.commit(metadata);
fireOnCommit();
return timestamp;
} catch (ChronoDBTransactionException e) {
throw new RuntimeException("Commit failed due to exception in ChronoDB: " + e.toString(), e);
} finally {
this.threadToTx.remove(Thread.currentThread());
}
}
@Override
public void commitIncremental() {
ChronoGraphTransaction transaction = this.threadToTx.get(Thread.currentThread());
if (transaction == null) {
throw new IllegalStateException("No Graph Transaction is open on this thread; cannot perform commit!");
}
try {
transaction.commitIncremental();
} catch (ChronoDBTransactionException e) {
throw new IllegalStateException("Commit failed due to exception in ChronoDB: " + e.toString(), e);
}
}
@Override
protected void doRollback() throws TransactionException {
ChronoGraphTransaction transaction = this.threadToTx.get(Thread.currentThread());
if (transaction == null) {
throw new TransactionException("No Graph Transaction is open on this thread; cannot perform rollback!");
}
this.threadToTx.remove(Thread.currentThread());
try {
transaction.rollback();
} catch (ChronoDBTransactionException e) {
throw new TransactionException("Rollback failed due to exception in ChronoDB: " + e.toString(), e);
}
}
@Override
public ChronoGraphTransaction getCurrentTransaction() {
ChronoGraphTransaction transaction = this.threadToTx.get(Thread.currentThread());
if (transaction == null) {
throw Transaction.Exceptions.transactionMustBeOpenToReadWrite();
}
return transaction;
}
// =====================================================================================================================
// INTERNAL HELPER METHODS
// =====================================================================================================================
private void assertNoOpenTransactionExists() {
if (this.isOpen()) {
throw Transaction.Exceptions.transactionAlreadyOpen();
}
}
}
| 13,766 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
StandardChronoGraphTransaction.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/StandardChronoGraphTransaction.java | package org.chronos.chronograph.internal.impl.transaction;
import com.google.common.base.Objects;
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.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.Order;
import org.chronos.chronodb.api.PutOption;
import org.chronos.chronodb.api.exceptions.ChronoDBCommitException;
import org.chronos.chronodb.api.key.TemporalKey;
import org.chronos.chronodb.internal.impl.engines.base.StandardChronoDBTransaction;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.exceptions.ChronoGraphCommitConflictException;
import org.chronos.chronograph.api.exceptions.ChronoGraphSchemaViolationException;
import org.chronos.chronograph.api.exceptions.GraphInvariantViolationException;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
import org.chronos.chronograph.api.schema.SchemaValidationResult;
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.ChronoGraphVariables;
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.structure.record.IEdgeRecord;
import org.chronos.chronograph.api.structure.record.IEdgeTargetRecord;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.api.transaction.AllEdgesIterationHandler;
import org.chronos.chronograph.api.transaction.AllVerticesIterationHandler;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.GraphTransactionContext;
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.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.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.internal.api.structure.ChronoElementInternal;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.api.transaction.ChronoGraphTransactionInternal;
import org.chronos.chronograph.internal.api.transaction.GraphTransactionContextInternal;
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.ChronoVertexImpl;
import org.chronos.chronograph.internal.impl.structure.graph.ElementLifecycleEvent;
import org.chronos.chronograph.internal.impl.structure.graph.proxy.ChronoEdgeProxy;
import org.chronos.chronograph.internal.impl.structure.graph.proxy.ChronoVertexProxy;
import org.chronos.chronograph.internal.impl.structure.graph.readonly.ReadOnlyChronoEdge;
import org.chronos.chronograph.internal.impl.structure.graph.readonly.ReadOnlyChronoVertex;
import org.chronos.chronograph.internal.impl.transaction.threaded.ChronoThreadedTransactionGraph;
import org.chronos.chronograph.internal.impl.transaction.trigger.PostTriggerContextImpl;
import org.chronos.chronograph.internal.impl.transaction.trigger.PreTriggerContextImpl;
import org.chronos.chronograph.internal.impl.util.ChronoGraphLoggingUtil;
import org.chronos.chronograph.internal.impl.util.ChronoId;
import org.chronos.chronograph.internal.impl.util.ChronoProxyUtil;
import org.chronos.common.autolock.AutoLock;
import org.chronos.common.exceptions.UnknownEnumLiteralException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.*;
import static org.chronos.common.logging.ChronosLogMarker.*;
public class StandardChronoGraphTransaction implements ChronoGraphTransaction, ChronoGraphTransactionInternal {
private static final Logger log = LoggerFactory.getLogger(StandardChronoGraphTransaction.class);
private final String transactionId;
private final ChronoGraphInternal graph;
private ChronoDBTransaction backendTransaction;
private GraphTransactionContextInternal context;
private final ChronoGraphQueryProcessor queryProcessor;
private long rollbackCount;
public StandardChronoGraphTransaction(final ChronoGraphInternal graph,
final ChronoDBTransaction backendTransaction) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
checkNotNull(backendTransaction, "Precondition violation - argument 'backendTransaction' must not be NULL!");
this.transactionId = UUID.randomUUID().toString();
this.graph = graph;
this.backendTransaction = backendTransaction;
this.context = new GraphTransactionContextImpl();
this.rollbackCount = 0L;
this.queryProcessor = new ChronoGraphQueryProcessor(this);
}
// =====================================================================================================================
// METADATA
// =====================================================================================================================
@Override
public ChronoDBTransaction getBackingDBTransaction() {
this.assertIsOpen();
return this.backendTransaction;
}
@Override
public GraphTransactionContext getContext() {
this.assertIsOpen();
return this.context;
}
@Override
public String getTransactionId() {
return this.transactionId;
}
@Override
public long getRollbackCount() {
return this.rollbackCount;
}
@Override
public ChronoGraph getGraph() {
return this.graph;
}
protected ChronoGraphInternal getGraphInternal() {
return this.graph;
}
@Override
public boolean isThreadedTx() {
// can be overridden in subclasses.
return false;
}
@Override
public boolean isThreadLocalTx() {
// can be overridden in subclasses.
return true;
}
@Override
public boolean isOpen() {
// can be overridden in subclasses.
// by default, the tx is open as long as the graph is open.
return !this.graph.isClosed();
}
// =====================================================================================================================
// COMMIT & ROLLBACK
// =====================================================================================================================
@Override
public long commit() {
return this.commit(null);
}
@Override
public long commit(final Object metadata) {
this.assertIsOpen();
boolean performanceLoggingActive = this.graph.getBackingDB().getConfiguration().isCommitPerformanceLoggingActive();
long timeBeforeGraphCommit = System.currentTimeMillis();
long commitTimestamp = -1;
long beforePreCommitTriggers = System.currentTimeMillis();
this.firePreCommitTriggers(metadata);
String perfLogPrefix = "[PERF ChronoGraph] Graph Commit (" + this.getBranchName() + "@" + this.getTimestamp() + ")";
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Pre-Commit Triggers: " + (System.currentTimeMillis() - beforePreCommitTriggers) + "ms.");
}
long timeBeforeLockAcquisition = System.currentTimeMillis();
try (AutoLock lock = this.graph.commitLock()) {
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Graph Commit Lock Acquisition: " + (System.currentTimeMillis() - timeBeforeLockAcquisition) + "ms.");
}
// only try to merge if not in incremental commit mode
if (this.getBackingDBTransaction().isInIncrementalCommitMode() == false) {
long timeBeforeMerge = System.currentTimeMillis();
this.performGraphLevelMergeWithStoreState();
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Graph-Level Merge With Store: " + (System.currentTimeMillis() - timeBeforeMerge) + "ms.");
}
}
long timeBeforePrePersistTriggers = System.currentTimeMillis();
this.firePrePersistTriggers(metadata);
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Pre-Persist Triggers: " + (System.currentTimeMillis() - timeBeforePrePersistTriggers) + "ms.");
}
ChronoGraphConfiguration config = this.getGraph().getChronoGraphConfiguration();
if (config.isGraphInvariantCheckActive()) {
// validate the graph invariant (each edge points to two existing verticies)
long timeBeforeGraphInvariantCheck = System.currentTimeMillis();
this.validateGraphInvariant();
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Graph Invariant Check: " + (System.currentTimeMillis() - timeBeforeGraphInvariantCheck) + "ms.");
}
}
// perform the schema validation (if any)
long timeBeforeSchemaValidation = System.currentTimeMillis();
SchemaValidationResult schemaValidationResult = this.performGraphSchemaValidation();
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Schema Validation Check: " + (System.currentTimeMillis() - timeBeforeSchemaValidation) + "ms.");
}
if (schemaValidationResult.isFailure()) {
this.rollback();
throw new ChronoGraphSchemaViolationException(schemaValidationResult.generateErrorMessage());
}
// merge not required, commit this transaction
long timeBeforeVertexMap = System.currentTimeMillis();
this.mapModifiedVerticesToChronoDB();
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Mapping Vertices to Key-Value pairs: " + (System.currentTimeMillis() - timeBeforeVertexMap) + "ms.");
}
long timeBeforeEdgesMap = System.currentTimeMillis();
this.mapModifiedEdgesToChronoDB();
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Mapping Edges to Key-Value pairs: " + (System.currentTimeMillis() - timeBeforeEdgesMap) + "ms.");
}
long timeBeforeVariablesMap = System.currentTimeMillis();
this.mapModifiedGraphVariablesToChronoDB();
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Mapping Graph Variables to Key-Value pairs: " + (System.currentTimeMillis() - timeBeforeVariablesMap) + "ms.");
}
if (log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)) {
String header = ChronoGraphLoggingUtil.createLogHeader(this);
log.trace(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS, header + "Committing Transaction.");
}
// commit the transaction
long timeBeforeChronoDBCommit = System.currentTimeMillis();
commitTimestamp = this.getBackingDBTransaction().commit(metadata);
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> ChronoDB commit: " + (System.currentTimeMillis() - timeBeforeChronoDBCommit) + "ms. Commit Timestamp: " + commitTimestamp);
}
// preserve some information for the post-persist triggers (if necessary)
if (commitTimestamp >= 0) {
// only fire post-persist triggers if the transaction actually changed something
long timeBeforePostPersistTriggers = System.currentTimeMillis();
this.firePostPersistTriggers(commitTimestamp, metadata);
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Post Persist Triggers: " + (System.currentTimeMillis() - timeBeforePostPersistTriggers) + "ms.");
}
}
}
if (commitTimestamp >= 0) {
// only fire post-commit triggers if the transaction actually changed something
long timeBeforePostCommitTriggers = System.currentTimeMillis();
this.firePostCommitTriggers(commitTimestamp, metadata);
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + " -> Post Commit Triggers: " + (System.currentTimeMillis() - timeBeforePostCommitTriggers) + "ms.");
}
}
// clear the transaction context
this.context = new GraphTransactionContextImpl();
if (performanceLoggingActive) {
log.info(CHRONOS_LOG_MARKER__PERFORMANCE, perfLogPrefix + ": " + (System.currentTimeMillis() - timeBeforeGraphCommit) + "ms.");
}
return commitTimestamp;
}
@Override
public void commitIncremental() {
this.assertIsOpen();
try (AutoLock lock = this.graph.commitLock()) {
if (this.getBackingDBTransaction().isInIncrementalCommitMode() == false) {
// we're not yet in incremental commit mode, assert that the timestamp is the latest
long now;
try (ChronoGraph currentStateGraph = this.graph.tx().createThreadedTx(this.getBranchName())) {
now = currentStateGraph.getNow(this.getBranchName());
currentStateGraph.tx().rollback();
}
if (now != this.getTimestamp()) {
throw new IllegalStateException("Cannot perform incremental commit: a concurrent transaction has performed a commit since this transaction was opened!");
}
}
ChronoGraphConfiguration config = this.getGraph().getChronoGraphConfiguration();
if (config.isGraphInvariantCheckActive()) {
// validate the graph invariant (each edge points to two existing verticies)
this.validateGraphInvariant();
}
// perform the schema validation (if any)
SchemaValidationResult schemaValidationResult = this.performGraphSchemaValidation();
if (schemaValidationResult.isFailure()) {
this.rollback();
throw new ChronoGraphSchemaViolationException(schemaValidationResult.generateErrorMessage());
}
this.mapModifiedVerticesToChronoDB();
this.mapModifiedEdgesToChronoDB();
this.mapModifiedGraphVariablesToChronoDB();
if (log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)) {
String header = ChronoGraphLoggingUtil.createLogHeader(this);
log.trace(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS, header + "Performing Incremental Commit.");
}
// commit the transaction
this.getBackingDBTransaction().commitIncremental();
// clear the transaction context
this.context.clear();
// we "treat" the incremental commit like a rollback, because
// we want existing proxies to re-register themselves at the
// context (which we just had to clear).
this.rollbackCount++;
}
}
@Override
public void rollback() {
this.context.clear();
this.rollbackCount++;
if (log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)) {
String header = ChronoGraphLoggingUtil.createLogHeader(this);
log.trace(CHRONOS_LOG_MARKER__PERFORMANCE, header + "Rolling back transaction.");
}
this.getBackingDBTransaction().rollback();
}
// =====================================================================================================================
// QUERY METHODS
// =====================================================================================================================
@Override
public Iterator<Vertex> vertices(final Object... vertexIds) {
this.assertIsOpen();
if (vertexIds == null || vertexIds.length <= 0) {
// query all vertices... this is bad.
AllVerticesIterationHandler handler = this.getGraph().getChronoGraphConfiguration().getAllVerticesIterationHandler();
if (handler != null) {
handler.onAllVerticesIteration();
}
Set<ChronoGraphIndex> dirtyIndices = this.getGraph().getIndexManagerOnBranch(this.getBranchName()).getDirtyIndicesAtTimestamp(this.getTimestamp());
if (dirtyIndices.isEmpty()) {
log.warn("Query requires iterating over all vertices."
+ " For better performance, use 'has(...)' clauses in your gremlin that can utilize indices.");
} else {
log.warn(
"Query requires iterating over all vertices which results in reduced performance. " +
"This may be due to the following indices being dirty: " + dirtyIndices
);
}
return this.getAllVerticesIterator();
}
if (this.areAllOfType(String.class, vertexIds)) {
// retrieve some vertices by IDs
List<String> chronoVertexIds = Lists.newArrayList(vertexIds).stream().map(id -> (String) id)
.collect(Collectors.toList());
return this.getVerticesIterator(chronoVertexIds);
}
if (this.areAllOfType(Vertex.class, vertexIds)) {
// vertices were passed as arguments -> extract their IDs and query them
List<String> ids = Lists.newArrayList(vertexIds).stream().map(v -> ((String) ((Vertex) v).id()))
.collect(Collectors.toList());
return this.getVerticesIterator(ids);
}
// in any other case, something wrong was passed as argument...
throw new IllegalArgumentException("The given 'vertexIds' arguments must either be all of type String or all of type Vertex!");
}
@Override
public Iterator<Vertex> getAllVerticesIterator() {
this.assertIsOpen();
return this.queryProcessor.getAllVerticesIterator();
}
@Override
public Iterator<Vertex> getVerticesIterator(final Iterable<String> chronoVertexIds,
final ElementLoadMode loadMode) {
checkNotNull(chronoVertexIds, "Precondition violation - argument 'chronoVertexIds' must not be NULL!");
checkNotNull(loadMode, "Precondition violation - argument 'loadMode' must not be NULL!");
this.assertIsOpen();
return this.queryProcessor.getVerticesIterator(chronoVertexIds, loadMode);
}
@Override
public Iterator<Edge> edges(final Object... edgeIds) {
if (edgeIds == null || edgeIds.length <= 0) {
// query all edges... this is bad.
AllEdgesIterationHandler handler = this.getGraph().getChronoGraphConfiguration().getAllEdgesIterationHandler();
if (handler != null) {
handler.onAllEdgesIteration();
}
Set<ChronoGraphIndex> dirtyIndices = this.getGraph().getIndexManagerOnBranch(this.getBranchName()).getDirtyIndicesAtTimestamp(this.getTimestamp());
if (dirtyIndices.isEmpty()) {
log.warn("Query requires iterating over all edges."
+ " For better performance, use 'has(...)' clauses in your gremlin that can utilize indices.");
} else {
log.warn(
"Query requires iterating over all edges which results in reduced performance. " +
"This may be due to the following indices being dirty: " + dirtyIndices
);
}
return this.getAllEdgesIterator();
}
if (this.areAllOfType(String.class, edgeIds)) {
// retrieve some edges by IDs
List<String> chronoEdgeIds = Lists.newArrayList(edgeIds).stream().map(id -> (String) id)
.collect(Collectors.toList());
return this.getEdgesIterator(chronoEdgeIds);
}
if (this.areAllOfType(Edge.class, edgeIds)) {
// edges were passed as arguments -> extract their IDs and query them
List<String> ids = Lists.newArrayList(edgeIds).stream().map(e -> ((String) ((Edge) e).id()))
.collect(Collectors.toList());
return this.getEdgesIterator(ids);
}
// in any other case, something wrong was passed as argument...
throw new IllegalArgumentException("The given 'vertexIds' arguments must either be all of type String or all of type Edge!");
}
@Override
public Iterator<Edge> getAllEdgesIterator() {
return this.queryProcessor.getAllEdgesIterator();
}
@Override
public Iterator<Edge> getEdgesIterator(final Iterable<String> edgeIds, final ElementLoadMode loadMode) {
checkNotNull(edgeIds, "Precondition violation - argument 'edgeIds' must not be NULL!");
return this.queryProcessor.getEdgesIterator(edgeIds, loadMode);
}
// =====================================================================================================================
// TEMPORAL QUERY METHODS
// =====================================================================================================================
@Override
public Iterator<Long> getVertexHistory(final Object vertexId, final long lowerBound, final long upperBound, final Order order) {
checkNotNull(vertexId, "Precondition violation - argument 'vertexId' must not be NULL!");
checkArgument(lowerBound >= 0, "Precondition violation - argument 'lowerBound' must not be negative!");
checkArgument(upperBound >= 0, "Precondition violation - argument 'upperBound' must not be negative!");
checkArgument(lowerBound <= upperBound, "Precondition violation - argument 'lowerBound' must be less than or equal to argument 'upperBound'!");
checkNotNull(order);
if (vertexId instanceof Vertex) {
return this.getVertexHistory(((Vertex) vertexId).id(), lowerBound, upperBound, order);
}
if (vertexId instanceof String) {
return this.getVertexHistory((String) vertexId, lowerBound, upperBound, order);
}
throw new IllegalArgumentException("The given object is no valid vertex id: " + vertexId);
}
@Override
public Iterator<Long> getEdgeHistory(final Object edgeId, final long lowerBound, final long upperBound, final Order order) {
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
checkArgument(lowerBound >= 0, "Precondition violation - argument 'lowerBound' must not be negative!");
checkArgument(upperBound >= 0, "Precondition violation - argument 'upperBound' must not be negative!");
checkArgument(lowerBound <= upperBound, "Precondition violation - argument 'lowerBound' must be less than or equal to argument 'upperBound'!");
checkNotNull(order);
if (edgeId instanceof Edge) {
return this.getEdgeHistory((Edge) edgeId, lowerBound, upperBound, order);
}
if (edgeId instanceof String) {
return this.getEdgeHistory((String) edgeId, lowerBound, upperBound, order);
}
throw new IllegalArgumentException("The given object is no valid edge id: " + edgeId);
}
@Override
public long getLastModificationTimestampOfVertex(final Vertex vertex) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
return this.getLastModificationTimestampOfVertex(vertex.id());
}
@Override
public long getLastModificationTimestampOfVertex(final Object vertexId) {
checkNotNull(vertexId, "Precondition violation - argument 'vertexId' must not be NULL!");
if (vertexId instanceof Vertex) {
return this.getLastModificationTimestampOfVertex(((Vertex) vertexId).id());
} else if (vertexId instanceof String) {
return this.getBackingDBTransaction().getLastModificationTimestamp(ChronoGraphConstants.KEYSPACE_VERTEX, (String) vertexId);
}
throw new IllegalArgumentException("The given object is no valid vertex id: " + vertexId);
}
@Override
public long getLastModificationTimestampOfEdge(final Edge edge) {
checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!");
return this.getLastModificationTimestampOfEdge(edge.id());
}
@Override
public long getLastModificationTimestampOfEdge(final Object edgeId) {
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
if (edgeId instanceof Edge) {
return this.getLastModificationTimestampOfEdge(((Edge) edgeId).id());
} else if (edgeId instanceof String) {
return this.getBackingDBTransaction().getLastModificationTimestamp(ChronoGraphConstants.KEYSPACE_EDGE, (String) edgeId);
}
throw new IllegalArgumentException("The given object is no valid edge id: " + edgeId);
}
@Override
public Iterator<Long> getEdgeHistory(final Edge edge) {
checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!");
ChronoEdge chronoEdge = (ChronoEdge) edge;
return this.getEdgeHistory(chronoEdge.id());
}
@Override
public Iterator<Pair<Long, String>> getVertexModificationsBetween(final long timestampLowerBound,
final long timestampUpperBound) {
checkArgument(timestampLowerBound >= 0,
"Precondition violation - argument 'timestampLowerBound' must not be negative!");
checkArgument(timestampUpperBound >= 0,
"Precondition violation - argument 'timestampUpperBound' must not be negative!");
checkArgument(timestampLowerBound <= timestampUpperBound,
"Precondition violation - argument 'timestampLowerBound' must be less than or equal to 'timestampUpperBound'!");
checkArgument(timestampLowerBound <= this.getTimestamp(),
"Precondition violation - argument 'timestampLowerBound' must not exceed the transaction timestamp!");
checkArgument(timestampUpperBound <= this.getTimestamp(),
"Precondition violation - argument 'timestampUpperBound' must not exceed the transaction timestamp!");
Iterator<TemporalKey> temporalKeyIterator = this.getBackingDBTransaction().getModificationsInKeyspaceBetween(
ChronoGraphConstants.KEYSPACE_VERTEX, timestampLowerBound, timestampUpperBound);
return Iterators.transform(temporalKeyIterator, tk -> Pair.of(tk.getTimestamp(), tk.getKey()));
}
@Override
public Iterator<Pair<Long, String>> getEdgeModificationsBetween(final long timestampLowerBound,
final long timestampUpperBound) {
checkArgument(timestampLowerBound >= 0,
"Precondition violation - argument 'timestampLowerBound' must not be negative!");
checkArgument(timestampUpperBound >= 0,
"Precondition violation - argument 'timestampUpperBound' must not be negative!");
checkArgument(timestampLowerBound <= timestampUpperBound,
"Precondition violation - argument 'timestampLowerBound' must be less than or equal to 'timestampUpperBound'!");
checkArgument(timestampLowerBound <= this.getTimestamp(),
"Precondition violation - argument 'timestampLowerBound' must not exceed the transaction timestamp!");
checkArgument(timestampUpperBound <= this.getTimestamp(),
"Precondition violation - argument 'timestampUpperBound' must not exceed the transaction timestamp!");
Iterator<TemporalKey> temporalKeyIterator = this.getBackingDBTransaction().getModificationsInKeyspaceBetween(
ChronoGraphConstants.KEYSPACE_EDGE, timestampLowerBound, timestampUpperBound);
return Iterators.transform(temporalKeyIterator, tk -> Pair.of(tk.getTimestamp(), tk.getKey()));
}
@Override
public Object getCommitMetadata(final long commitTimestamp) {
checkArgument(commitTimestamp >= 0,
"Precondition violation - argument 'commitTimestamp' must not be negative!");
checkArgument(commitTimestamp <= this.getTimestamp(),
"Precondition violation - argument 'commitTimestamp' must not be larger than the transaction timestamp!");
return this.getBackingDBTransaction().getCommitMetadata(commitTimestamp);
}
// =================================================================================================================
// ELEMENT CREATION METHODS
// =================================================================================================================
@Override
public ChronoVertex addVertex(final Object... keyValues) {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object id = ElementHelper.getIdValue(keyValues).orElse(null);
boolean userProvidedId = true;
if (id != null && id instanceof String == false) {
throw Vertex.Exceptions.userSuppliedIdsOfThisTypeNotSupported();
}
if (id == null) {
id = ChronoId.random();
// we generated the ID ourselves, it did not come from the user
userProvidedId = false;
}
String vertexId = (String) id;
String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
ChronoVertex removedVertex = null;
if (userProvidedId) {
// assert that we don't already have a graph element with this ID in our transaction cache
ChronoVertex modifiedVertex = this.getContext().getModifiedVertex(vertexId);
if (modifiedVertex != null) {
// re-creating a vertex that has been removed is ok
if (!modifiedVertex.isRemoved()) {
throw Graph.Exceptions.vertexWithIdAlreadyExists(vertexId);
} else {
// the vertex already existed in our transaction context, but was removed. Now
// it is being recreated.
removedVertex = modifiedVertex;
}
} else {
// assert that we don't already have a graph element with this ID in our persistence
if (this.getGraph().getChronoGraphConfiguration().isCheckIdExistenceOnAddEnabled()) {
ChronoDBTransaction backingTx = this.getBackingDBTransaction();
boolean vertexIdAlreadyExists = backingTx.exists(ChronoGraphConstants.KEYSPACE_VERTEX, vertexId);
if (vertexIdAlreadyExists) {
throw Graph.Exceptions.vertexWithIdAlreadyExists(vertexId);
}
}
}
}
this.logAddVertex(vertexId, userProvidedId);
ChronoVertexImpl vertex = new ChronoVertexImpl(vertexId, this.graph, this, label);
if (removedVertex != null) {
// we already have this vertex in our transaction context
if (removedVertex.getStatus() == ElementLifecycleStatus.OBSOLETE) {
vertex.updateLifecycleStatus(ElementLifecycleEvent.RECREATED_FROM_OBSOLETE);
} else if (removedVertex.getStatus() == ElementLifecycleStatus.REMOVED) {
vertex.updateLifecycleStatus(ElementLifecycleEvent.RECREATED_FROM_REMOVED);
} else {
throw new IllegalStateException("Vertex '" + vertex.id() + "' is removed, but is neither " + ElementLifecycleStatus.REMOVED + " nor " + ElementLifecycleStatus.OBSOLETE + "!");
}
} else {
vertex.updateLifecycleStatus(ElementLifecycleEvent.CREATED);
}
ElementHelper.attachProperties(vertex, keyValues);
this.context.registerLoadedVertex(vertex);
return this.context.getOrCreateVertexProxy(vertex);
}
@Override
public ChronoEdge addEdge(final ChronoVertex outVertex, final ChronoVertex inVertex, final String id,
final boolean isUserProvidedId, final String label, final Object... keyValues) {
ChronoEdge removedEdge = null;
if (isUserProvidedId) {
// assert that we don't already have a graph element with this ID in our transaction cache
ChronoEdge modifiedEdge = this.getContext().getModifiedEdge(id);
if (modifiedEdge != null) {
if (modifiedEdge.isRemoved() == false) {
throw Graph.Exceptions.edgeWithIdAlreadyExists(id);
} else {
// the edge was removed in the transaction context and is now created again
removedEdge = modifiedEdge;
}
} else {
// edge is "clean"
if (this.getGraph().getChronoGraphConfiguration().isCheckIdExistenceOnAddEnabled()) {
// assert that we don't already have a graph element with this ID in our persistence
ChronoDBTransaction backingTx = this.getBackingDBTransaction();
boolean edgeIdAlreadyExists = backingTx.exists(ChronoGraphConstants.KEYSPACE_EDGE, id);
if (edgeIdAlreadyExists) {
throw Graph.Exceptions.edgeWithIdAlreadyExists(id);
}
}
}
}
// create the edge
ChronoVertexImpl outV = ChronoProxyUtil.resolveVertexProxy(outVertex);
ChronoVertexImpl inV = ChronoProxyUtil.resolveVertexProxy(inVertex);
ChronoEdgeImpl edge = ChronoEdgeImpl.create(id, outV, label, inV);
// if we have a previous element...
if (removedEdge != null) {
// ... then we are dealing with a recreation
if (removedEdge.getStatus() == ElementLifecycleStatus.OBSOLETE) {
edge.updateLifecycleStatus(ElementLifecycleEvent.RECREATED_FROM_OBSOLETE);
} else if (removedEdge.getStatus() == ElementLifecycleStatus.REMOVED) {
edge.updateLifecycleStatus(ElementLifecycleEvent.RECREATED_FROM_REMOVED);
} else {
throw new IllegalStateException("Edge '" + edge.id() + "' is removed, but is neither " + ElementLifecycleStatus.REMOVED + " nor " + ElementLifecycleStatus.OBSOLETE + "!");
}
}
// set the properties (if any)
ElementHelper.attachProperties(edge, keyValues);
this.context.registerLoadedEdge(edge);
return this.context.getOrCreateEdgeProxy(edge);
}
// =====================================================================================================================
// EQUALS & HASH CODE
// =====================================================================================================================
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.transactionId == null ? 0 : this.transactionId.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;
}
StandardChronoGraphTransaction other = (StandardChronoGraphTransaction) obj;
if (this.transactionId == null) {
if (other.transactionId != null) {
return false;
}
} else if (!this.transactionId.equals(other.transactionId)) {
return false;
}
return true;
}
// =====================================================================================================================
// LOADING METHODS
// =====================================================================================================================
public ChronoVertex loadVertex(final String id, final ElementLoadMode loadMode) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
// first, try to find the vertex in our 'modified vertices' cache
ChronoVertexImpl modifiedVertex = (ChronoVertexImpl) this.context.getModifiedVertex(id);
if (modifiedVertex != null) {
// the given vertex is in our 'modified vertices' cache; reuse it
return modifiedVertex;
}
// then, try to find it in our 'already loaded' cache
ChronoVertexImpl loadedVertex = this.context.getLoadedVertexForId(id);
if (loadedVertex != null) {
// the vertex was already loaded in this transaction; return the same instance
return loadedVertex;
}
ChronoVertexImpl vertex = null;
switch (loadMode) {
case EAGER:
// we are not sure if there is a vertex in the database for the given id. We need
// to make a load attempt to make sure it exists.
ChronoDBTransaction tx = this.getBackingDBTransaction();
IVertexRecord record = tx.get(ChronoGraphConstants.KEYSPACE_VERTEX, id.toString());
// load the vertex from the database
if (record == null) {
return null;
}
vertex = new ChronoVertexImpl(this.graph, this, record);
// register the loaded instance
this.context.registerLoadedVertex(vertex);
return vertex;
case LAZY:
// we can trust that there actually IS a vertex in the database for the given ID,
// but we want to load it lazily when a vertex property is first accessed.
ChronoVertexProxy proxy = new ChronoVertexProxy(this.graph, id);
this.context.registerVertexProxyInCache(proxy);
return proxy;
default:
throw new UnknownEnumLiteralException(loadMode);
}
}
public ChronoEdge loadEdge(final String id, ElementLoadMode loadMode) {
checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!");
checkNotNull(loadMode, "Precondition violation - argument 'loadMode' must not be NULL!");
// first, try to find the edge in our 'modified edges' cache
ChronoEdgeImpl modifiedEdge = (ChronoEdgeImpl) this.context.getModifiedEdge(id);
if (modifiedEdge != null) {
// the given vertex is in our 'modified edges' cache; reuse it
return modifiedEdge;
}
// then, try to find it in our 'already loaded' cache
ChronoEdgeImpl loadedEdge = this.context.getLoadedEdgeForId(id);
if (loadedEdge != null) {
// the edge was already loaded in this transaction; return the same instance
return loadedEdge;
}
switch (loadMode) {
case LAZY:
// we know we can trust that there actually IS an edge with
// the given ID without checking in the store, so we only
// create a proxy here which will lazy-load the edge when required.
// This is important because of queries such as:
//
// graph.traversal().E().has(p, X).count()
//
// ... where "p" is an indexed property. If we did not load lazily,
// then the "count" would require to load all individual edges (!!)
// from disk, which is clearly unnecessary.
ChronoEdgeProxy proxy = new ChronoEdgeProxy(this.graph, id);
this.context.registerEdgeProxyInCache(proxy);
return proxy;
case EAGER:
// load the edge from the database
ChronoDBTransaction tx = this.getBackingDBTransaction();
IEdgeRecord record = tx.get(ChronoGraphConstants.KEYSPACE_EDGE, id);
if (record == null) {
return null;
}
ChronoEdgeImpl edge = ChronoEdgeImpl.create(this.graph, this, record);
// register the loaded edge
this.context.registerLoadedEdge(edge);
return edge;
default:
throw new UnknownEnumLiteralException(loadMode);
}
}
@Override
public ChronoEdge loadOutgoingEdgeFromEdgeTargetRecord(final ChronoVertexImpl sourceVertex, final String label,
final IEdgeTargetRecord record) {
checkNotNull(sourceVertex, "Precondition violation - argument 'sourceVertex' must not be NULL!");
checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!");
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
String id = record.getEdgeId();
// first, try to find the edge in our 'modified edges' cache
ChronoEdge modifiedEdge = this.context.getModifiedEdge(id);
if (modifiedEdge != null) {
// the given vertex is in our 'modified edges' cache; reuse it
return modifiedEdge;
}
// then, try to find it in our 'already loaded' cache
ChronoEdge loadedEdge = this.context.getLoadedEdgeForId(id);
if (loadedEdge != null) {
// the edge was already loaded in this transaction; return the same instance
return loadedEdge;
}
// the edge was not found, create it
ChronoEdgeImpl edge = ChronoEdgeImpl.outgoingEdgeFromRecord(sourceVertex, label, record);
// register the loaded edge
this.context.registerLoadedEdge(edge);
return edge;
}
@Override
public IVertexRecord loadVertexRecord(final String recordId) {
checkNotNull(recordId, "Precondition violation - argument 'recordId' must not be NULL!");
Object value = this.backendTransaction.get(ChronoGraphConstants.KEYSPACE_VERTEX, recordId);
if (value == null) {
throw new IllegalStateException("Received request (branch: '" + this.getBranchName() + "', timestamp: " + this.getTimestamp() + ") to fetch Vertex Record with ID '" + recordId + "', but no record was found!");
}
if (value instanceof IVertexRecord) {
return (IVertexRecord) value;
} else {
throw new IllegalStateException("Received request to fetch Vertex Record with ID '" + recordId + "', but the database returned an object of incompatible type '" + value.getClass().getName() + "' instead! Branch: " + this.getBranchName() + ", timestamp: " + this.getTimestamp());
}
}
@Override
public IEdgeRecord loadEdgeRecord(final String recordId) {
checkNotNull(recordId, "Precondition violation - argument 'recordId' must not be NULL!");
Object value = this.backendTransaction.get(ChronoGraphConstants.KEYSPACE_EDGE, recordId);
if (value == null) {
throw new IllegalStateException("Received request (branch: '" + this.getBranchName() + "', timestamp: " + this.getTimestamp() + ") to fetch Edge Record with ID '" + recordId + "', but no record was found!");
}
if (value instanceof IEdgeRecord) {
return (IEdgeRecord) value;
} else {
throw new IllegalStateException("Received request (branch: '" + this.getBranchName() + "', timestamp: " + this.getTimestamp() + ") to fetch Edge Record with ID '" + recordId + "', but the database returned an object of incompatible type '" + value.getClass().getName() + "'!");
}
}
@Override
public ChronoEdge loadIncomingEdgeFromEdgeTargetRecord(final ChronoVertexImpl targetVertex, final String label,
final IEdgeTargetRecord record) {
checkNotNull(targetVertex, "Precondition violation - argument 'targetVertex' must not be NULL!");
checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!");
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
String id = record.getEdgeId();
// first, try to find the edge in our 'modified edges' cache
ChronoEdge modifiedEdge = this.context.getModifiedEdge(id);
if (modifiedEdge != null) {
// the given vertex is in our 'modified edges' cache; reuse it
return modifiedEdge;
}
// then, try to find it in our 'already loaded' cache
ChronoEdge loadedEdge = this.context.getLoadedEdgeForId(id);
if (loadedEdge != null) {
// the edge was already loaded in this transaction; return the same instance
return loadedEdge;
}
// the edge was not found, create it
ChronoEdgeImpl edge = ChronoEdgeImpl.incomingEdgeFromRecord(targetVertex, label, record);
// register the loaded edge
this.context.registerLoadedEdge(edge);
return edge;
}
// =====================================================================================================================
// INTERNAL HELPER METHODS
// =====================================================================================================================
private boolean areAllOfType(final Class<?> clazz, final Object... objects) {
for (Object object : objects) {
if (clazz.isInstance(object) == false) {
return false;
}
}
return true;
}
private Iterator<Long> getVertexHistory(final String vertexId, long lowerBound, long upperBound, Order order) {
checkNotNull(vertexId, "Precondition violation - argument 'vertexId' must not be NULL!");
ChronoDBTransaction tx = this.getBackingDBTransaction();
return tx.history(ChronoGraphConstants.KEYSPACE_VERTEX, vertexId, lowerBound, upperBound, order);
}
private Iterator<Long> getEdgeHistory(final String edgeId, long lowerBound, long upperBound, Order order) {
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
ChronoDBTransaction tx = this.getBackingDBTransaction();
return tx.history(ChronoGraphConstants.KEYSPACE_EDGE, edgeId, lowerBound, upperBound, order);
}
private void performGraphLevelMergeWithStoreState() {
GraphTransactionContext oldContext = this.context;
// reset the transaction
this.context = new GraphTransactionContextImpl();
((StandardChronoDBTransaction) this.backendTransaction).cancelAndResetToHead();
this.mergeVertexChangesFrom(oldContext);
this.mergeEdgeChangesFrom(oldContext);
this.mergeGraphVariableChangesFrom(oldContext);
}
private void mergeVertexChangesFrom(final GraphTransactionContext oldContext) {
Set<ChronoVertex> verticesToSynchronize = Sets.newHashSet(oldContext.getModifiedVertices());
for (ChronoVertex vertex : verticesToSynchronize) {
ElementLifecycleStatus status = vertex.getStatus();
switch (status) {
case REMOVED: {
Vertex storeVertex = Iterators.getOnlyElement(this.graph.vertices(vertex.id()), null);
if (storeVertex != null) {
// delete the vertex in the store
storeVertex.remove();
}
break;
}
case OBSOLETE:
case PERSISTED: {
// ignore
break;
}
case NEW: {
// the vertex is new in the current transaction
Vertex storeVertex = Iterators.getOnlyElement(this.graph.vertices(vertex.id()), null);
if (storeVertex == null) {
// create the vertex
storeVertex = this.graph.addVertex(T.id, vertex.id(), T.label, vertex.label());
}
// copy the properties from the new vertex to the store vertex
this.copyProperties(vertex, storeVertex);
break;
}
case EDGE_CHANGED: {
// ignore, edges are synchronized in another step
break;
}
case PROPERTY_CHANGED: {
// synchronize the properties
Vertex storeVertex = Iterators.getOnlyElement(this.graph.vertices(vertex.id()), null);
if (storeVertex != null) {
Set<String> propertyKeys = Sets.newHashSet();
propertyKeys.addAll(vertex.keys());
propertyKeys.addAll(storeVertex.keys());
for (String propertyKey : propertyKeys) {
PropertyStatus propertyStatus = vertex.getPropertyStatus(propertyKey);
switch (propertyStatus) {
case NEW:
// FALL THROUGH
case MODIFIED:
VertexProperty<?> txProperty = vertex.property(propertyKey);
VertexProperty<?> storeProperty = storeVertex.property(propertyKey);
// are the properties exactly the same?
if (!arePropertiesTheSame(txProperty, storeProperty)) {
// the properties are different, apply tx changes to store state
storeVertex.property(propertyKey, txProperty.value());
}
if (!areMetaPropertiesTheSame(txProperty, storeProperty)) {
VertexProperty<?> targetProperty = storeVertex.property(propertyKey);
Set<String> allKeys = Sets.union(txProperty.keys(), targetProperty.keys());
for (String metaKey : allKeys) {
Property<Object> txMetaProperty = txProperty.property(metaKey);
if (!txMetaProperty.isPresent()) {
storeProperty.property(metaKey).remove();
} else {
Property<Object> storeMetaProperty = storeProperty.property(metaKey);
if (storeMetaProperty.isPresent()) {
Object txMetaValue = txMetaProperty.value();
Object storeMetaValue = storeMetaProperty.value();
if (!Objects.equal(storeMetaValue, txMetaValue)) {
storeProperty.property(metaKey, txMetaValue);
}
} else {
storeProperty.property(metaKey, txProperty.value(metaKey));
}
}
}
}
break;
case PERSISTED:
// ignore, property is untouched in transaction
break;
case REMOVED:
// remove in store as well
storeVertex.property(propertyKey).remove();
break;
case UNKNOWN:
// ignore, property is unknown in transaction
break;
default:
throw new UnknownEnumLiteralException(propertyStatus);
}
}
}
break;
}
default:
throw new UnknownEnumLiteralException(status);
}
}
}
private boolean arePropertiesTheSame(Property<?> left, Property<?> right) {
boolean leftExists = left.isPresent();
boolean rightExists = right.isPresent();
if (!leftExists && !rightExists) {
// special case: neither of the two properties exists, therefore they are the same.
return true;
}
if (leftExists != rightExists) {
// either one of them does not exist, therefore they are not the same.
return false;
}
// in the remaining case, both properties do exist.
if (!Objects.equal(left.value(), right.value())) {
// values are different
return false;
}
// no changes detected -> the properties are the same.
return true;
}
private boolean areMetaPropertiesTheSame(VertexProperty<?> left, VertexProperty<?> right) {
Set<String> leftKeys = left.keys();
Set<String> rightKeys = right.keys();
if (leftKeys.size() != rightKeys.size()) {
// meta-properties are different -> properties are different.
return false;
}
Set<String> allKeys = Sets.union(leftKeys, rightKeys);
for (String metaPropertyKey : allKeys) {
Property<?> leftMetaProp = left.property(metaPropertyKey);
Property<?> rightMetaProp = right.property(metaPropertyKey);
if (!arePropertiesTheSame(leftMetaProp, rightMetaProp)) {
// meta-properties are different -> properties are different.
return false;
}
}
return true;
}
private void mergeEdgeChangesFrom(final GraphTransactionContext oldContext) {
Set<ChronoEdge> edgesToSynchronize = Sets.newHashSet(oldContext.getModifiedEdges());
for (ChronoEdge edge : edgesToSynchronize) {
ElementLifecycleStatus status = edge.getStatus();
switch (status) {
case NEW: {
// try to get the edge from the store
Edge storeEdge = Iterators.getOnlyElement(this.graph.edges(edge.id()), null);
if (storeEdge == null) {
Vertex outV = Iterators.getOnlyElement(this.graph.vertices(edge.outVertex().id()), null);
Vertex inV = Iterators.getOnlyElement(this.graph.vertices(edge.inVertex().id()), null);
if (outV == null || inV == null) {
// edge can not be created because one of the vertex ends does not exist in merged state
break;
}
storeEdge = outV.addEdge(edge.label(), inV, T.id, edge.id());
} else {
// store edge already exists, check that the neighboring vertices are the same
if (Objects.equal(edge.inVertex().id(), storeEdge.inVertex().id()) == false || Objects.equal(edge.outVertex().id(), storeEdge.outVertex().id()) == false) {
throw new ChronoGraphCommitConflictException("There is an Edge with ID " + edge.id() + " that has been created in this transaction, but the store contains another edge with the same ID that has different neighboring vertices!");
}
}
this.copyProperties(edge, storeEdge);
break;
}
case REMOVED: {
Edge storeEdge = Iterators.getOnlyElement(this.graph.edges(edge.id()), null);
if (storeEdge != null) {
storeEdge.remove();
}
break;
}
case OBSOLETE: {
// ignore
break;
}
case EDGE_CHANGED: {
// can't happen for edges
throw new IllegalStateException("Detected Edge in lifecycle status EDGE_CHANGED!");
}
case PERSISTED: {
// ignore, edge is already in sync with store
break;
}
case PROPERTY_CHANGED: {
Edge storeEdge = Iterators.getOnlyElement(this.graph.edges(edge.id()), null);
if (storeEdge != null) {
// for edges, PROPERTY_CHANGED can also mean that the in/out vertex or label has changed!
if (!storeEdge.inVertex().id().equals(edge.inVertex().id())
|| !storeEdge.outVertex().id().equals(edge.outVertex().id())
|| !storeEdge.label().equals(edge.label())
) {
// recreate the edge in the store
Vertex storeOutV = this.graph.vertex(edge.outVertex().id());
Vertex storeInV = this.graph.vertex(edge.inVertex().id());
storeEdge.remove();
if (storeOutV == null || storeInV == null) {
// cannot recreate edge -> store is lacking one of its adjacent vertices
break;
}
Edge newStoreEdge = storeOutV.addEdge(edge.label(), storeInV, T.id, edge.id());
// copy all property values
Set<String> propertyKeys = edge.keys();
for (String propertyKey : propertyKeys) {
Property<?> prop = edge.property(propertyKey);
if (prop.isPresent()) {
newStoreEdge.property(propertyKey, prop.value());
}
}
} else {
// the edge exists in the store, check the properties
Set<String> propertyKeys = Sets.newHashSet();
propertyKeys.addAll(edge.keys());
propertyKeys.addAll(storeEdge.keys());
for (String propertyKey : propertyKeys) {
PropertyStatus propertyStatus = edge.getPropertyStatus(propertyKey);
switch (propertyStatus) {
case NEW:
// FALL THROUGH
case MODIFIED:
Property<?> txProperty = edge.property(propertyKey);
Property<?> storeProperty = storeEdge.property(propertyKey);
if (!arePropertiesTheSame(txProperty, storeProperty)) {
storeEdge.property(propertyKey, txProperty.value());
}
break;
case PERSISTED:
// ignore, property is untouched in transaction
break;
case REMOVED:
// remove in store as well
storeEdge.property(propertyKey).remove();
break;
case UNKNOWN:
// ignore, property is unknown in transaction
break;
default:
throw new UnknownEnumLiteralException(propertyStatus);
}
}
}
}
break;
}
default:
throw new UnknownEnumLiteralException(status);
}
}
}
private void mergeGraphVariableChangesFrom(final GraphTransactionContext oldContext) {
// get the backing transaction
Set<String> keyspaces = oldContext.getModifiedVariableKeyspaces();
ChronoGraphVariables storeVariables = this.graph.variables();
for (String keyspace : keyspaces) {
// write the modifications of graph variables into the transaction context
for (String variableName : oldContext.getModifiedVariables(keyspace)) {
Optional<Object> storeVariable = storeVariables.get(keyspace, variableName);
Object newValue = oldContext.getModifiedVariableValue(keyspace, variableName);
if (storeVariable.isPresent()) {
if (oldContext.isVariableRemoved(keyspace, variableName)) {
// did exist before, was removed
this.graph.variables().remove(keyspace, variableName);
} else {
// did exist before, still exists. Check if values are identical
if (!Objects.equal(storeVariable.get(), newValue)) {
// value really changed, apply the change
this.graph.variables().set(keyspace, variableName, newValue);
}
// otherwise the value was changed and reverted within the same transaction, e.g. a->b->a.
// we ignore those changes on purpose.
}
} else {
if (!oldContext.isVariableRemoved(keyspace, variableName)) {
// did not exist before, was created
this.graph.variables().set(keyspace, variableName, newValue);
}
// otherwise the variable did not exist before, was created and removed within same transaction -> no-op.
}
}
}
}
private <E extends Element> void copyProperties(final E sourceElement, final E targetElement) {
Iterator<? extends Property<Object>> propertyIterator = sourceElement.properties();
while (propertyIterator.hasNext()) {
Property<?> prop = propertyIterator.next();
Property<?> storeProp = targetElement.property(prop.key(), prop.value());
if (prop instanceof VertexProperty) {
VertexProperty<?> vProp = (VertexProperty<?>) prop;
this.copyMetaProperties(vProp, (VertexProperty<?>) storeProp);
}
}
}
private void copyMetaProperties(final VertexProperty<?> source, final VertexProperty<?> target) {
Iterator<Property<Object>> metaPropertyIterator = source.properties();
while (metaPropertyIterator.hasNext()) {
Property<?> metaProp = metaPropertyIterator.next();
target.property(metaProp.key(), metaProp.value());
}
}
private void validateGraphInvariant() {
try {
this.context.getModifiedVertices().forEach(v -> ((ChronoElementInternal) v).validateGraphInvariant());
this.context.getModifiedEdges().forEach(e -> ((ChronoElementInternal) e).validateGraphInvariant());
} catch (GraphInvariantViolationException e) {
throw new GraphInvariantViolationException("A Graph Invariant Violation has been detected. Transaction details: Coords: [" + this.getBranchName() + "@" + this.getTimestamp() + "] TxID " + this.transactionId, e);
}
}
private SchemaValidationResult performGraphSchemaValidation() {
String branchName = this.getBranchName();
Set<ChronoVertex> modifiedVertices = this.context.getModifiedVertices().stream()
// there is no point in validating deleted elements, so we filter them
.filter(v -> !v.isRemoved())
// we want the validator to work on a read-only version
.map(ReadOnlyChronoVertex::new)
.collect(Collectors.toSet());
Set<ChronoEdge> modifiedEdges = this.context.getModifiedEdges().stream()
// there is no point in validating deleted elements, so we filter them
.filter(e -> !e.isRemoved())
// we want the validator to work on a read-only version
.map(ReadOnlyChronoEdge::new)
.collect(Collectors.toSet());
Set<ChronoElement> modifiedElements = Sets.union(modifiedVertices, modifiedEdges);
return this.getGraph().getSchemaManager().validate(branchName, modifiedElements);
}
private void mapModifiedVerticesToChronoDB() {
// get the backing transaction
ChronoDBTransaction tx = this.getBackingDBTransaction();
// read the set of modified vertices
Set<ChronoVertex> modifiedVertices = this.context.getModifiedVertices();
// write each vertex into a key-value pair in the transaction
for (ChronoVertex vertex : modifiedVertices) {
String vertexId = vertex.id();
ElementLifecycleStatus vertexStatus = vertex.getStatus();
switch (vertexStatus) {
case NEW:
tx.put(ChronoGraphConstants.KEYSPACE_VERTEX, vertexId, ((ChronoVertexImpl) vertex).toRecord());
break;
case OBSOLETE:
// obsolete graph elements are not committed to the store,
// they have been created AND removed in the same transaction
break;
case EDGE_CHANGED:
tx.put(ChronoGraphConstants.KEYSPACE_VERTEX, vertexId, ((ChronoVertexImpl) vertex).toRecord(), PutOption.NO_INDEX);
break;
case PERSISTED:
// this case should actually be unreachable because persisted elements are clean and not dirty
throw new IllegalStateException(
"Unreachable code reached: PERSISTED vertex '" + vertexId + "' is listed as dirty!");
case PROPERTY_CHANGED:
tx.put(ChronoGraphConstants.KEYSPACE_VERTEX, vertexId, ((ChronoVertexImpl) vertex).toRecord());
break;
case REMOVED:
tx.remove(ChronoGraphConstants.KEYSPACE_VERTEX, vertexId);
break;
default:
throw new UnknownEnumLiteralException(vertexStatus);
}
}
}
private void mapModifiedEdgesToChronoDB() {
// get the backing transaction
ChronoDBTransaction tx = this.getBackingDBTransaction();
// read the set of modified edges
Set<ChronoEdge> modifiedEdges = this.context.getModifiedEdges();
// write each edge into a key-value pair in the transaction
for (ChronoEdge edge : modifiedEdges) {
String edgeId = edge.id();
ElementLifecycleStatus edgeStatus = edge.getStatus();
switch (edgeStatus) {
case NEW:
if (log.isTraceEnabled()) {
log.trace("[COMMIT]: Committing Edge '" + edgeId + "' in status NEW");
}
tx.put(ChronoGraphConstants.KEYSPACE_EDGE, edgeId, ((ChronoEdgeImpl) edge).toRecord());
break;
case EDGE_CHANGED:
throw new IllegalStateException(
"Unreachable code reached: Detected edge '" + edgeId + "' in state EDGE_CHANGED!");
case OBSOLETE:
if (log.isTraceEnabled()) {
log.trace("[COMMIT]: Ignoring Edge '" + edgeId + "' in status OBSOLETE");
}
// obsolete graph elements are not committed to the store,
// they have been created AND removed in the same transaction
break;
case PERSISTED:
throw new IllegalStateException(
"Unreachable code reached: PERSISTED edge '" + edgeId + "' is listed as dirty!");
case PROPERTY_CHANGED:
if (log.isTraceEnabled()) {
log.trace("[COMMIT]: Committing Edge '" + edgeId + "' in status PROPERTY_CHANGED");
}
tx.put(ChronoGraphConstants.KEYSPACE_EDGE, edgeId, ((ChronoEdgeImpl) edge).toRecord());
break;
case REMOVED:
if (log.isTraceEnabled()) {
log.trace("[COMMIT]: Removing Edge '" + edgeId + "' in status REMOVED");
}
tx.remove(ChronoGraphConstants.KEYSPACE_EDGE, edgeId);
break;
default:
break;
}
}
}
private void mapModifiedGraphVariablesToChronoDB() {
// get the backing transaction
ChronoDBTransaction tx = this.getBackingDBTransaction();
// read the modified graph variables
Set<String> modifiedVariableKeyspaces = this.context.getModifiedVariableKeyspaces();
for (String keyspace : modifiedVariableKeyspaces) {
String chronoDbKeyspace = ChronoGraphVariablesImpl.createChronoDBVariablesKeyspace(keyspace);
for (String key : this.context.getModifiedVariables(keyspace)) {
if (this.context.isVariableRemoved(keyspace, key)) {
tx.remove(chronoDbKeyspace, key);
} else {
tx.put(chronoDbKeyspace, key, this.context.getModifiedVariableValue(keyspace, key));
}
}
}
}
// =================================================================================================================
// COMMIT TRIGGER METHODS
// =================================================================================================================
private void firePreCommitTriggers(Object commitMetadata) {
List<Pair<String, ChronoGraphPreCommitTrigger>> triggers = this.getGraphInternal().getTriggerManager().getPreCommitTriggers();
if (triggers.isEmpty()) {
return;
}
GraphBranch branch = this.getGraph().getBranchManager().getBranch(this.getBranchName());
try (PreCommitTriggerContext ctx = new PreTriggerContextImpl(branch, commitMetadata, this.graph, this::createAncestorGraph, this::createStoreStateGraph)) {
for (Pair<String, ChronoGraphPreCommitTrigger> nameAndTrigger : triggers) {
String triggerName = nameAndTrigger.getLeft();
ChronoGraphPreCommitTrigger trigger = nameAndTrigger.getRight();
try {
trigger.onPreCommit(ctx);
} catch (CancelCommitException cancelException) {
throw new ChronoDBCommitException("Commit was rejected by Trigger '" + triggerName + "'!");
} catch (Exception otherException) {
log.error("Exception when evaluating Trigger '" + triggerName + "' in PRE COMMIT timing. Commit will continue.", otherException);
}
}
}
}
private void firePrePersistTriggers(Object commitMetadata) {
List<Pair<String, ChronoGraphPrePersistTrigger>> triggers = this.getGraphInternal().getTriggerManager().getPrePersistTriggers();
if (triggers.isEmpty()) {
return;
}
GraphBranch branch = this.getGraph().getBranchManager().getBranch(this.getBranchName());
try (PrePersistTriggerContext ctx = new PreTriggerContextImpl(branch, commitMetadata, this.graph, this::createAncestorGraph, this::createStoreStateGraph)) {
for (Pair<String, ChronoGraphPrePersistTrigger> nameAndTrigger : triggers) {
String triggerName = nameAndTrigger.getLeft();
ChronoGraphPrePersistTrigger trigger = nameAndTrigger.getRight();
try {
trigger.onPrePersist(ctx);
} catch (CancelCommitException cancelException) {
throw new ChronoDBCommitException("Commit was rejected by Trigger '" + triggerName + "'!");
} catch (Exception otherException) {
log.error("Exception when evaluating Trigger '" + triggerName + "' in PRE PERSIST timing. Commit will continue.", otherException);
}
}
}
}
private void firePostPersistTriggers(long commitTimestamp, Object commitMetadata) {
List<Pair<String, ChronoGraphPostPersistTrigger>> triggers = this.getGraphInternal().getTriggerManager().getPostPersistTriggers();
if (triggers.isEmpty()) {
return;
}
GraphBranch branch = this.getGraph().getBranchManager().getBranch(this.getBranchName());
try (PostPersistTriggerContext ctx = new PostTriggerContextImpl(branch, commitTimestamp, commitMetadata, this.graph, this::createAncestorGraph, this::createStoreStateGraph, () -> this.createPreCommitStoreStateGraph(commitTimestamp))) {
for (Pair<String, ChronoGraphPostPersistTrigger> nameAndTrigger : triggers) {
String triggerName = nameAndTrigger.getLeft();
ChronoGraphPostPersistTrigger trigger = nameAndTrigger.getRight();
try {
trigger.onPostPersist(ctx);
} catch (CancelCommitException cancelException) {
throw new ChronoDBCommitException("Commit was rejected by Trigger '" + triggerName + "'!");
} catch (Exception otherException) {
log.error("Exception when evaluating Trigger '" + triggerName + "' in POST PERSIST timing. Commit will continue.", otherException);
}
}
}
}
private void firePostCommitTriggers(long commitTimestamp, Object commitMetadata) {
List<Pair<String, ChronoGraphPostCommitTrigger>> triggers = this.getGraphInternal().getTriggerManager().getPostCommitTriggers();
if (triggers.isEmpty()) {
return;
}
GraphBranch branch = this.getGraph().getBranchManager().getBranch(this.getBranchName());
try (PostCommitTriggerContext ctx = new PostTriggerContextImpl(branch, commitTimestamp, commitMetadata, this.graph, this::createAncestorGraph, this::createStoreStateGraph, () -> this.createPreCommitStoreStateGraph(commitTimestamp))) {
for (Pair<String, ChronoGraphPostCommitTrigger> nameAndTrigger : triggers) {
String triggerName = nameAndTrigger.getLeft();
ChronoGraphPostCommitTrigger trigger = nameAndTrigger.getRight();
try {
trigger.onPostCommit(ctx);
} catch (CancelCommitException cancelException) {
throw new ChronoDBCommitException("Commit was rejected by Trigger '" + triggerName + "'!");
} catch (Exception otherException) {
log.error("Exception when evaluating Trigger '" + triggerName + "' in POST COMMIT timing. Commit will continue.", otherException);
}
}
}
}
private ChronoGraph createAncestorGraph() {
ChronoGraph sourceGraph = this.graph;
if (this.graph instanceof ChronoThreadedTransactionGraph) {
sourceGraph = ((ChronoThreadedTransactionGraph) this.graph).getOriginalGraph();
}
return sourceGraph.tx().createThreadedTx(this.getBranchName(), this.getTimestamp());
}
private ChronoGraph createStoreStateGraph() {
ChronoGraph sourceGraph = this.graph;
if (this.graph instanceof ChronoThreadedTransactionGraph) {
sourceGraph = ((ChronoThreadedTransactionGraph) this.graph).getOriginalGraph();
}
return sourceGraph.tx().createThreadedTx(this.getBranchName());
}
private ChronoGraph createPreCommitStoreStateGraph(long timestamp) {
ChronoGraph sourceGraph = this.graph;
if (this.graph instanceof ChronoThreadedTransactionGraph) {
sourceGraph = ((ChronoThreadedTransactionGraph) this.graph).getOriginalGraph();
}
return sourceGraph.tx().createThreadedTx(this.getBranchName(), timestamp - 1);
}
// =====================================================================================================================
// DEBUG LOGGING
// =====================================================================================================================
private void logAddVertex(final String vertexId, final boolean isUserProvided) {
if (!log.isTraceEnabled(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS)) {
return;
}
// prepare some debug output
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.append(ChronoGraphLoggingUtil.createLogHeader(this));
messageBuilder.append("Adding Vertex with ");
if (isUserProvided) {
messageBuilder.append("user-provided ");
} else {
messageBuilder.append("auto-generated ");
}
messageBuilder.append("ID '");
messageBuilder.append(vertexId);
messageBuilder.append("' to graph.");
log.trace(CHRONOS_LOG_MARKER__GRAPH_MODIFICATIONS, messageBuilder.toString());
}
}
| 80,223 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ThreadedChronoGraphIndexManager.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/threaded/ThreadedChronoGraphIndexManager.java | package org.chronos.chronograph.internal.impl.transaction.threaded;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.chronos.chronodb.internal.api.query.searchspec.SearchSpecification;
import org.chronos.chronodb.internal.impl.index.IndexingOption;
import org.chronos.chronograph.api.builder.index.IndexBuilderStarter;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
import org.chronos.chronograph.api.index.ChronoGraphIndexManager;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.api.index.ChronoGraphIndexManagerInternal;
import org.chronos.chronograph.internal.impl.index.IndexType;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Callable;
import static com.google.common.base.Preconditions.*;
public class ThreadedChronoGraphIndexManager implements ChronoGraphIndexManager, ChronoGraphIndexManagerInternal {
private final ChronoThreadedTransactionGraph graph;
private final ChronoGraphIndexManagerInternal wrappedManager;
public ThreadedChronoGraphIndexManager(final ChronoThreadedTransactionGraph graph, final String branchName) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
this.graph = graph;
this.wrappedManager = (ChronoGraphIndexManagerInternal) this.graph.getOriginalGraph()
.getIndexManagerOnBranch(branchName);
}
@Override
public ChronoGraphIndex addIndex(
final Class<? extends Element> elementType,
final IndexType indexType,
final String propertyName,
final long startTimestamp,
final long endTimestamp,
Set<IndexingOption> options
) {
return this.wrappedManager.addIndex(elementType, indexType, propertyName, startTimestamp, endTimestamp, options);
}
@Override
public Iterator<String> findVertexIdsByIndexedProperties(
final ChronoGraphTransaction tx,
final Set<SearchSpecification<?, ?>> searchSpecifications
) {
return this.wrappedManager.findVertexIdsByIndexedProperties(tx, searchSpecifications);
}
@Override
public Iterator<String> findEdgeIdsByIndexedProperties(
final ChronoGraphTransaction tx,
final Set<SearchSpecification<?, ?>> searchSpecifications
) {
return this.wrappedManager.findEdgeIdsByIndexedProperties(tx, searchSpecifications);
}
@Override
public IndexBuilderStarter create() {
return this.wrappedManager.create();
}
@Override
public Set<ChronoGraphIndex> getIndexedPropertiesAtTimestamp(final Class<? extends Element> clazz, final long timestamp) {
return this.wrappedManager.getIndexedPropertiesAtTimestamp(clazz, timestamp);
}
@Override
public Set<ChronoGraphIndex> getIndexedPropertiesAtAnyPointInTime(final Class<? extends Element> clazz) {
return this.wrappedManager.getIndexedPropertiesAtAnyPointInTime(clazz);
}
@Override
public Set<ChronoGraphIndex> getAllIndicesAtAnyPointInTime() {
return this.wrappedManager.getAllIndicesAtAnyPointInTime();
}
@Override
public Set<ChronoGraphIndex> getAllIndicesAtTimestamp(final long timestamp) {
return this.wrappedManager.getAllIndicesAtTimestamp(timestamp);
}
@Override
public ChronoGraphIndex getVertexIndexAtTimestamp(final String indexedPropertyName, final long timestamp) {
return this.wrappedManager.getVertexIndexAtTimestamp(indexedPropertyName, timestamp);
}
@Override
public Set<ChronoGraphIndex> getVertexIndicesAtAnyPointInTime(final String indexedPropertyName) {
return this.wrappedManager.getVertexIndicesAtAnyPointInTime(indexedPropertyName);
}
@Override
public ChronoGraphIndex getEdgeIndexAtTimestamp(final String indexedPropertyName, final long timestamp) {
return this.wrappedManager.getEdgeIndexAtTimestamp(indexedPropertyName, timestamp);
}
@Override
public Set<ChronoGraphIndex> getEdgeIndicesAtAnyPointInTime(final String indexedPropertyName) {
return this.wrappedManager.getEdgeIndicesAtAnyPointInTime(indexedPropertyName);
}
@Override
public void reindexAll(boolean force) {
this.wrappedManager.reindexAll(force);
}
@Override
public void dropIndex(final ChronoGraphIndex index) {
this.wrappedManager.dropIndex(index);
}
@Override
public void dropAllIndices() {
this.wrappedManager.dropAllIndices();
}
@Override
public void dropAllIndices(Object commitMetadata) {
this.wrappedManager.dropAllIndices(commitMetadata);
}
@Override
public ChronoGraphIndex terminateIndex(final ChronoGraphIndex index, final long timestamp) {
return this.wrappedManager.terminateIndex(index, timestamp);
}
@Override
public boolean isReindexingRequired() {
return this.wrappedManager.isReindexingRequired();
}
@Override
public void withIndexReadLock(final Runnable action) {
checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
this.wrappedManager.withIndexReadLock(action);
}
@Override
public <T> T withIndexReadLock(final Callable<T> action) {
checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
return this.wrappedManager.withIndexReadLock(action);
}
@Override
public void withIndexWriteLock(final Runnable action) {
checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
this.wrappedManager.withIndexWriteLock(action);
}
@Override
public <T> T withIndexWriteLock(final Callable<T> action) {
checkNotNull(action, "Precondition violation - argument 'action' must not be NULL!");
return this.wrappedManager.withIndexWriteLock(action);
}
}
| 6,034 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ThreadedChronoGraphTransactionManager.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/threaded/ThreadedChronoGraphTransactionManager.java | package org.chronos.chronograph.internal.impl.transaction.threaded;
import org.apache.tinkerpop.gremlin.structure.util.AbstractThreadedTransaction;
import org.apache.tinkerpop.gremlin.structure.util.TransactionException;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.ChronoGraphTransactionManager;
import java.util.Date;
public class ThreadedChronoGraphTransactionManager extends AbstractThreadedTransaction
implements ChronoGraphTransactionManager {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private final ChronoThreadedTransactionGraph owningGraph;
private final ThreadedChronoGraphTransaction tx;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
public ThreadedChronoGraphTransactionManager(final ChronoThreadedTransactionGraph g,
final ThreadedChronoGraphTransaction tx) {
super(g);
this.owningGraph = g;
this.tx = tx;
}
// =====================================================================================================================
// TRANSACTION OPENING
// =====================================================================================================================
@Override
public boolean isOpen() {
// this transaction is open for as long as the owning graph is open
return this.owningGraph.isClosed() == false;
}
@Override
public void open(final long timestamp) {
throw new UnsupportedOperationException("Cannot open thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void open(final Date date) {
throw new UnsupportedOperationException("Cannot open thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void open(final String branch) {
throw new UnsupportedOperationException("Cannot open thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void open(final String branch, final long timestamp) {
throw new UnsupportedOperationException("Cannot open thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void open(final String branch, final Date date) {
throw new UnsupportedOperationException("Cannot open thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void reset() {
throw new UnsupportedOperationException("Cannot reset thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void reset(final long timestamp) {
throw new UnsupportedOperationException("Cannot reset thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void reset(final Date date) {
throw new UnsupportedOperationException("Cannot reset thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void reset(final String branch, final long timestamp) {
throw new UnsupportedOperationException("Cannot reset thread-bound transactions from inside a Threaded Transaction!");
}
@Override
public void reset(final String branch, final Date date) {
throw new UnsupportedOperationException("Cannot reset thread-bound transactions from inside a Threaded Transaction!");
}
// =====================================================================================================================
// THREADED TX METHODS
// =====================================================================================================================
@Override
@SuppressWarnings("unchecked")
public ChronoGraph createThreadedTx() {
return this.owningGraph.getOriginalGraph().tx().createThreadedTx();
}
@Override
public ChronoGraph createThreadedTx(final long timestamp) {
return this.owningGraph.getOriginalGraph().tx().createThreadedTx(timestamp);
}
@Override
public ChronoGraph createThreadedTx(final Date date) {
return this.owningGraph.getOriginalGraph().tx().createThreadedTx(date);
}
@Override
public ChronoGraph createThreadedTx(final String branchName) {
return this.owningGraph.getOriginalGraph().tx().createThreadedTx(branchName);
}
@Override
public ChronoGraph createThreadedTx(final String branchName, final long timestamp) {
return this.owningGraph.getOriginalGraph().tx().createThreadedTx(branchName, timestamp);
}
@Override
public ChronoGraph createThreadedTx(final String branchName, final Date date) {
return this.owningGraph.getOriginalGraph().tx().createThreadedTx(branchName, date);
}
// =====================================================================================================================
// CURRENT TRANSACTION
// =====================================================================================================================
@Override
public ChronoGraphTransaction getCurrentTransaction() {
return this.tx;
}
// =====================================================================================================================
// OPENING & CLOSING
// =====================================================================================================================
@Override
protected void doOpen() {
throw new UnsupportedOperationException("Cannot open transactions from inside a Threaded Transaction!");
}
@Override
protected void doCommit() throws TransactionException {
this.tx.commit();
}
@Override
public long commitAndReturnTimestamp() {
return this.commitAndReturnTimestamp(null);
}
@Override
public void commit(final Object metadata) {
this.tx.commit(metadata);
}
@Override
public long commitAndReturnTimestamp(final Object metadata) {
return this.tx.commit(metadata);
}
@Override
public void commitIncremental() {
this.tx.commitIncremental();
}
@Override
protected void doRollback() throws TransactionException {
this.tx.rollback();
this.owningGraph.close();
}
}
| 6,820 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ThreadedChronoGraphTransaction.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/threaded/ThreadedChronoGraphTransaction.java | package org.chronos.chronograph.internal.impl.transaction.threaded;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.transaction.StandardChronoGraphTransaction;
public class ThreadedChronoGraphTransaction extends StandardChronoGraphTransaction {
public ThreadedChronoGraphTransaction(final ChronoGraphInternal graph,
final ChronoDBTransaction backendTransaction) {
super(graph, backendTransaction);
}
// =====================================================================================================================
// METADATA
// =====================================================================================================================
@Override
public boolean isThreadedTx() {
return true;
}
@Override
public boolean isThreadLocalTx() {
return false;
}
@Override
public boolean isOpen() {
// the transaction is open for as long as the graph is open
return this.getGraph().isClosed() == false;
}
}
| 1,076 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoThreadedTransactionGraph.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/threaded/ChronoThreadedTransactionGraph.java | package org.chronos.chronograph.internal.impl.transaction.threaded;
import com.google.common.collect.Maps;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.io.Io;
import org.apache.tinkerpop.gremlin.structure.io.Io.Builder;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.chronos.chronodb.api.ChronoDB;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.DumpOption;
import org.chronos.chronodb.api.Order;
import org.chronos.chronograph.api.branch.ChronoGraphBranchManager;
import org.chronos.chronograph.api.history.ChronoGraphHistoryManager;
import org.chronos.chronograph.api.index.ChronoGraphIndexManager;
import org.chronos.chronograph.api.maintenance.ChronoGraphMaintenanceManager;
import org.chronos.chronograph.api.schema.ChronoGraphSchemaManager;
import org.chronos.chronograph.api.statistics.ChronoGraphStatisticsManager;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.structure.ChronoGraphVariables;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.ChronoGraphTransactionManager;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.structure.graph.ChronoGraphVariablesImpl;
import org.chronos.chronograph.internal.impl.transaction.trigger.ChronoGraphTriggerManagerInternal;
import org.chronos.common.autolock.AutoLock;
import org.chronos.common.version.ChronosVersion;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import static com.google.common.base.Preconditions.*;
public class ChronoThreadedTransactionGraph implements ChronoGraphInternal {
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final ChronoGraphInternal originalGraph;
private final ChronoGraphVariablesImpl variables;
private final ChronoGraphTransactionManager txManager;
private final Map<String, ChronoGraphIndexManager> branchNameToIndexManager;
private boolean isClosed;
// =================================================================================================================
// CONSTRUCTORS
// =================================================================================================================
public ChronoThreadedTransactionGraph(final ChronoGraphInternal originalGraph, final String branchName) {
this(originalGraph, branchName, null);
}
public ChronoThreadedTransactionGraph(final ChronoGraphInternal originalGraph, final String branchName,
final long timestamp) {
this(originalGraph, branchName, Long.valueOf(timestamp));
}
public ChronoThreadedTransactionGraph(final ChronoGraphInternal originalGraph, final String branchName,
final Long timestamp) {
checkNotNull(originalGraph, "Precondition violation - argument 'originalGraph' must not be NULL!");
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
if (timestamp != null) {
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
}
this.originalGraph = originalGraph;
this.isClosed = false;
// initialize the graph transaction which is bound to this graph
ChronoDB db = this.originalGraph.getBackingDB();
ChronoDBTransaction backendTransaction = null;
if (timestamp == null) {
// no timestamp given, use head revision
backendTransaction = db.tx(branchName);
} else {
// timestamp given, use the given revision
backendTransaction = db.tx(branchName, timestamp);
}
ThreadedChronoGraphTransaction graphTx = new ThreadedChronoGraphTransaction(this, backendTransaction);
// build the "pseudo transaction manager" that only returns the just created graph transaction
this.txManager = new ThreadedChronoGraphTransactionManager(this, graphTx);
this.branchNameToIndexManager = Maps.newHashMap();
this.variables = new ChronoGraphVariablesImpl(this);
}
// =================================================================================================================
// GRAPH CLOSING
// =================================================================================================================
@Override
public void close() {
if (this.isClosed) {
return;
}
this.isClosed = true;
// close the singleton transaction
if (this.tx().isOpen()) {
this.tx().rollback();
}
}
@Override
public boolean isClosed() {
return this.isClosed || this.originalGraph.isClosed();
}
public boolean isOriginalGraphClosed(){
return this.originalGraph.isClosed();
}
// =====================================================================================================================
// VERTEX & EDGE HANDLING
// =====================================================================================================================
@Override
public Vertex addVertex(final Object... keyValues) {
this.tx().readWrite();
return this.tx().getCurrentTransaction().addVertex(keyValues);
}
@Override
public Iterator<Vertex> vertices(final Object... vertexIds) {
this.tx().readWrite();
return this.tx().getCurrentTransaction().vertices(vertexIds);
}
@Override
public Iterator<Edge> edges(final Object... edgeIds) {
this.tx().readWrite();
return this.tx().getCurrentTransaction().edges(edgeIds);
}
// =====================================================================================================================
// COMPUTATION API
// =====================================================================================================================
@Override
public <C extends GraphComputer> C compute(final Class<C> graphComputerClass) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
@Override
public GraphComputer compute() throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
// =====================================================================================================================
// TRANSACTION API
// =====================================================================================================================
@Override
public ChronoGraphTransactionManager tx() {
return this.txManager;
}
@Override
public long getNow() {
ChronoGraphTransaction transaction = this.tx().getCurrentTransaction();
if (transaction.isOpen() == false) {
throw new IllegalStateException("This threaded transaction was already closed!");
}
return this.getBackingDB().getBranchManager().getMasterBranch().getNow();
}
@Override
public long getNow(final String branchName) {
ChronoGraphTransaction transaction = this.tx().getCurrentTransaction();
if (transaction.isOpen() == false) {
throw new IllegalStateException("This threaded transaction was already closed!");
}
return this.getBackingDB().getBranchManager().getBranch(branchName).getNow();
}
// =====================================================================================================================
// INDEXING
// =====================================================================================================================
@Override
public ChronoGraphIndexManager getIndexManagerOnMaster() {
return this.getIndexManagerOnBranch(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER);
}
@Override
public ChronoGraphIndexManager getIndexManagerOnBranch(final String branchName) {
checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!");
if (this.getBackingDB().getBranchManager().existsBranch(branchName) == false) {
throw new IllegalArgumentException("There is no branch named '" + branchName + "'!");
}
// try to retrieve a cached copy of the manager
ChronoGraphIndexManager indexManager = this.branchNameToIndexManager.get(branchName);
if (indexManager == null) {
// manager not present in our cache; build it and add it to the cache
indexManager = new ThreadedChronoGraphIndexManager(this, branchName);
this.branchNameToIndexManager.put(branchName, indexManager);
}
return indexManager;
}
// =====================================================================================================================
// BRANCHING
// =====================================================================================================================
@Override
public ChronoGraphBranchManager getBranchManager() {
return this.originalGraph.getBranchManager();
}
// =================================================================================================================
// TRIGGERS
// =================================================================================================================
@Override
public ChronoGraphTriggerManagerInternal getTriggerManager() {
return this.originalGraph.getTriggerManager();
}
@Override
public Optional<ChronosVersion> getStoredChronoGraphVersion() {
return this.originalGraph.getStoredChronoGraphVersion();
}
@Override
public void setStoredChronoGraphVersion(final ChronosVersion version) {
this.originalGraph.setStoredChronoGraphVersion(version);
}
// =================================================================================================================
// SCHEMA VALIDATION
// =================================================================================================================
@Override
public ChronoGraphSchemaManager getSchemaManager() {
return this.originalGraph.getSchemaManager();
}
// =================================================================================================================
// MAINTENANCE
// =================================================================================================================
@Override
public ChronoGraphMaintenanceManager getMaintenanceManager() {
return this.originalGraph.getMaintenanceManager();
}
// =================================================================================================================
// STATISTICS
// =================================================================================================================
@Override
public ChronoGraphStatisticsManager getStatisticsManager() {
return this.originalGraph.getStatisticsManager();
}
// =================================================================================================================
// HISTORY
// =================================================================================================================
@Override
public ChronoGraphHistoryManager getHistoryManager() {
return this.originalGraph.getHistoryManager();
}
// =====================================================================================================================
// VARIABLES & CONFIGURATION
// =====================================================================================================================
@Override
public ChronoGraphVariables variables() {
return this.variables;
}
@Override
public Configuration configuration() {
return this.originalGraph.configuration();
}
@Override
public ChronoGraphConfiguration getChronoGraphConfiguration() {
return this.originalGraph.getChronoGraphConfiguration();
}
// =====================================================================================================================
// TEMPORAL ACTIONS
// =====================================================================================================================
@Override
public Iterator<Long> getVertexHistory(final Object vertexId) {
checkNotNull(vertexId, "Precondition violation - argument 'vertexId' must not be NULL!");
this.tx().readWrite();
return this.tx().getCurrentTransaction().getVertexHistory(vertexId);
}
@Override
public Iterator<Long> getVertexHistory(final Object vertexId, final long lowerBound, final long upperBound, final Order order) {
this.tx().readWrite();
return this.tx().getCurrentTransaction().getVertexHistory(vertexId, lowerBound, upperBound, order);
}
@Override
public Iterator<Long> getEdgeHistory(final Object edgeId, final long lowerBound, final long upperBound, final Order order) {
this.tx().readWrite();
return this.tx().getCurrentTransaction().getEdgeHistory(edgeId, lowerBound, upperBound, order);
}
@Override
public long getLastModificationTimestampOfVertex(final Vertex vertex) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
this.tx().readWrite();
return this.tx().getCurrentTransaction().getLastModificationTimestampOfVertex(vertex);
}
@Override
public long getLastModificationTimestampOfVertex(final Object vertexId) {
checkNotNull(vertexId, "Precondition violation - argument 'vertexId' must not be NULL!");
this.tx().readWrite();
return this.tx().getCurrentTransaction().getLastModificationTimestampOfVertex(vertexId);
}
@Override
public long getLastModificationTimestampOfEdge(final Edge edge) {
checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!");
this.tx().readWrite();
return this.tx().getCurrentTransaction().getLastModificationTimestampOfEdge(edge);
}
@Override
public long getLastModificationTimestampOfEdge(final Object edgeId) {
checkNotNull(edgeId, "Precondition violation - argument 'edgeId' must not be NULL!");
this.tx().readWrite();
return this.tx().getCurrentTransaction().getLastModificationTimestampOfEdge(edgeId);
}
@Override
public Iterator<Pair<Long, String>> getVertexModificationsBetween(final long timestampLowerBound,
final long timestampUpperBound) {
checkArgument(timestampLowerBound >= 0,
"Precondition violation - argument 'timestampLowerBound' must not be negative!");
checkArgument(timestampUpperBound >= 0,
"Precondition violation - argument 'timestampUpperBound' must not be negative!");
checkArgument(timestampLowerBound <= timestampUpperBound,
"Precondition violation - argument 'timestampLowerBound' must be less than or equal to 'timestampUpperBound'!");
this.tx().readWrite();
checkArgument(timestampLowerBound <= this.tx().getCurrentTransaction().getTimestamp(),
"Precondition violation - argument 'timestampLowerBound' must not exceed the transaction timestamp!");
checkArgument(timestampUpperBound <= this.tx().getCurrentTransaction().getTimestamp(),
"Precondition violation - argument 'timestampUpperBound' must not exceed the transaction timestamp!");
return this.tx().getCurrentTransaction().getVertexModificationsBetween(timestampLowerBound,
timestampUpperBound);
}
@Override
public Iterator<Pair<Long, String>> getEdgeModificationsBetween(final long timestampLowerBound,
final long timestampUpperBound) {
checkArgument(timestampLowerBound >= 0,
"Precondition violation - argument 'timestampLowerBound' must not be negative!");
checkArgument(timestampUpperBound >= 0,
"Precondition violation - argument 'timestampUpperBound' must not be negative!");
checkArgument(timestampLowerBound <= timestampUpperBound,
"Precondition violation - argument 'timestampLowerBound' must be less than or equal to 'timestampUpperBound'!");
this.tx().readWrite();
checkArgument(timestampLowerBound <= this.tx().getCurrentTransaction().getTimestamp(),
"Precondition violation - argument 'timestampLowerBound' must not exceed the transaction timestamp!");
checkArgument(timestampUpperBound <= this.tx().getCurrentTransaction().getTimestamp(),
"Precondition violation - argument 'timestampUpperBound' must not exceed the transaction timestamp!");
return this.tx().getCurrentTransaction().getEdgeModificationsBetween(timestampLowerBound, timestampUpperBound);
}
@Override
public Object getCommitMetadata(final String branch, final long timestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
checkArgument(timestamp <= this.getNow(branch),
"Precondition violation - argument 'timestamp' must not be larger than the latest commit timestamp!");
return this.originalGraph.getCommitMetadata(branch, timestamp);
}
@Override
public Iterator<Long> getCommitTimestampsBetween(final String branch, final long from, final long to,
final Order order, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!");
checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!");
checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!");
return this.originalGraph.getCommitTimestampsBetween(branch, from, to, includeSystemInternalCommits);
}
@Override
public Iterator<Entry<Long, Object>> getCommitMetadataBetween(final String branch, final long from, final long to,
final Order order, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!");
checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!");
checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!");
return this.originalGraph.getCommitMetadataBetween(branch, from, to, order, includeSystemInternalCommits);
}
@Override
public Iterator<Long> getCommitTimestampsPaged(final String branch, final long minTimestamp,
final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!");
checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!");
checkArgument(pageSize > 0, "Precondition violation - argument 'pageSize' must be greater than zero!");
checkArgument(pageIndex >= 0, "Precondition violation - argument 'pageIndex' must not be negative!");
checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!");
return this.originalGraph.getCommitTimestampsPaged(branch, minTimestamp, maxTimestamp, pageSize, pageIndex, order, includeSystemInternalCommits);
}
@Override
public Iterator<Entry<Long, Object>> getCommitMetadataPaged(final String branch, final long minTimestamp,
final long maxTimestamp, final int pageSize, final int pageIndex, final Order order, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!");
checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!");
checkArgument(pageSize > 0, "Precondition violation - argument 'pageSize' must be greater than zero!");
checkArgument(pageIndex >= 0, "Precondition violation - argument 'pageIndex' must not be negative!");
checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!");
return this.originalGraph.getCommitMetadataPaged(branch, minTimestamp, maxTimestamp, pageSize, pageIndex, order, includeSystemInternalCommits);
}
@Override
public List<Entry<Long, Object>> getCommitMetadataAround(final String branch, final long timestamp,
final int count, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!");
return this.originalGraph.getCommitMetadataAround(branch, timestamp, count, includeSystemInternalCommits);
}
@Override
public List<Entry<Long, Object>> getCommitMetadataBefore(final String branch, final long timestamp,
final int count, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!");
return this.originalGraph.getCommitMetadataBefore(branch, timestamp, count, includeSystemInternalCommits);
}
@Override
public List<Entry<Long, Object>> getCommitMetadataAfter(final String branch, final long timestamp,
final int count, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!");
return this.originalGraph.getCommitMetadataAfter(branch, timestamp, count, includeSystemInternalCommits);
}
@Override
public List<Long> getCommitTimestampsAround(final String branch, final long timestamp, final int count, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!");
return this.originalGraph.getCommitTimestampsAround(branch, timestamp, count, includeSystemInternalCommits);
}
@Override
public List<Long> getCommitTimestampsBefore(final String branch, final long timestamp, final int count, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!");
return this.originalGraph.getCommitTimestampsBefore(branch, timestamp, count, includeSystemInternalCommits);
}
@Override
public List<Long> getCommitTimestampsAfter(final String branch, final long timestamp, final int count, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
checkArgument(count >= 0, "Precondition violation - argument 'count' must not be negative!");
return this.originalGraph.getCommitTimestampsAfter(branch, timestamp, count, includeSystemInternalCommits);
}
@Override
public int countCommitTimestampsBetween(final String branch, final long from, final long to, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!");
checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!");
return this.originalGraph.countCommitTimestampsBetween(branch, from, to, includeSystemInternalCommits);
}
@Override
public int countCommitTimestamps(final String branch, final boolean includeSystemInternalCommits) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
return this.originalGraph.countCommitTimestamps(branch, includeSystemInternalCommits);
}
@Override
public Iterator<String> getChangedVerticesAtCommit(final String branch, final long commitTimestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
return this.originalGraph.getChangedVerticesAtCommit(branch, commitTimestamp);
}
@Override
public Iterator<String> getChangedEdgesAtCommit(final String branch, final long commitTimestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
return this.originalGraph.getChangedEdgesAtCommit(branch, commitTimestamp);
}
@Override
public Iterator<Pair<String, String>> getChangedGraphVariablesAtCommit(final long commitTimestamp) {
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
return this.originalGraph.getChangedGraphVariablesAtCommit(commitTimestamp);
}
@Override
public Iterator<String> getChangedGraphVariablesAtCommitInDefaultKeyspace(final long commitTimestamp) {
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
return this.originalGraph.getChangedGraphVariablesAtCommitInDefaultKeyspace(commitTimestamp);
}
@Override
public Iterator<String> getChangedGraphVariablesAtCommitInKeyspace(final long commitTimestamp, final String keyspace) {
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!");
return this.originalGraph.getChangedGraphVariablesAtCommitInKeyspace(commitTimestamp, keyspace);
}
@Override
public Iterator<Pair<String, String>> getChangedGraphVariablesAtCommit(final String branch, final long commitTimestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
return this.originalGraph.getChangedGraphVariablesAtCommit(branch, commitTimestamp);
}
@Override
public Iterator<String> getChangedGraphVariablesAtCommitInDefaultKeyspace(final String branch, final long commitTimestamp) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
return this.originalGraph.getChangedGraphVariablesAtCommitInDefaultKeyspace(branch, commitTimestamp);
}
@Override
public Iterator<String> getChangedGraphVariablesAtCommitInKeyspace(final String branch, final long commitTimestamp, final String keyspace) {
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkArgument(commitTimestamp >= 0, "Precondition violation - argument 'commitTimestamp' must not be negative!");
checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!");
return this.originalGraph.getChangedGraphVariablesAtCommitInKeyspace(branch, commitTimestamp, keyspace);
}
// =====================================================================================================================
// SERIALIZATION & DESERIALIZATION (GraphSon, Gyro, ...)
// =====================================================================================================================
@Override
@SuppressWarnings({"rawtypes"})
public <I extends Io> I io(final Builder<I> builder) {
return this.originalGraph.io(builder);
}
// =====================================================================================================================
// DUMP OPERATIONS
// =====================================================================================================================
@Override
public void writeDump(final File dumpFile, final DumpOption... dumpOptions) {
throw new UnsupportedOperationException("createDump(...) is not permitted on threaded transaction graphs. "
+ "Call it on the original graph instead.");
}
@Override
public void readDump(final File dumpFile, final DumpOption... options) {
throw new UnsupportedOperationException("readDump(...) is not permitted on threaded transaction graphs. "
+ "Call it on the original graph instance.");
}
// =====================================================================================================================
// STRING REPRESENTATION
// =====================================================================================================================
@Override
public String toString() {
// according to Tinkerpop specification...
return StringFactory.graphString(this, "");
}
// =================================================================================================================
// INTERNAL API
// =================================================================================================================
@Override
public ChronoDB getBackingDB() {
return this.originalGraph.getBackingDB();
}
@Override
public AutoLock commitLock() {
return this.originalGraph.commitLock();
}
public ChronoGraph getOriginalGraph() {
return this.originalGraph;
}
// =====================================================================================================================
// FEATURES DECLARATION
// =====================================================================================================================
@Override
public Features features() {
return this.originalGraph.features();
}
}
| 33,038 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractTriggerContext.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/AbstractTriggerContext.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.trigger.AncestorState;
import org.chronos.chronograph.api.transaction.trigger.CurrentState;
import org.chronos.chronograph.api.transaction.trigger.StoreState;
import org.chronos.chronograph.api.transaction.trigger.TriggerContext;
import org.chronos.chronograph.internal.impl.structure.graph.readonly.ReadOnlyChronoGraph;
import org.chronos.chronograph.internal.impl.util.CachedSupplier;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.*;
public abstract class AbstractTriggerContext implements TriggerContext {
private final GraphBranch graphBranch;
private final Object commitMetadata;
private final CurrentState currentState;
private final CachedSupplier<ChronoGraph> ancestorStateGraphSupplier;
private final CachedSupplier<ChronoGraph> storeStateGraphSupplier;
private final CachedSupplier<AncestorState> ancestorStateSupplier;
private final CachedSupplier<StoreState> storeStateSupplier;
private String triggerName;
protected boolean closed = false;
protected AbstractTriggerContext(final GraphBranch branch, final Object commitMetadata, ChronoGraph currentStateGraph, Supplier<ChronoGraph> ancestorStateGraphSupplier, Supplier<ChronoGraph> storeStateGraphSupplier){
checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!");
checkNotNull(currentStateGraph, "Precondition violation - argument 'currentStateGraph' must not be NULL!");
checkNotNull(ancestorStateGraphSupplier, "Precondition violation - argument 'ancestorStateGraphSupplier' must not be NULL!");
checkNotNull(storeStateGraphSupplier, "Precondition violation - argument 'storeStateGraphSupplier' must not be NULL!");
this.graphBranch = branch;
this.commitMetadata = commitMetadata;
this.currentState = new CurrentStateImpl(this.wrapCurrentStateGraph(currentStateGraph));
this.ancestorStateGraphSupplier = CachedSupplier.create(() -> this.wrapAncestorStateGraph(ancestorStateGraphSupplier.get()));
this.storeStateGraphSupplier = CachedSupplier.create(() -> this.wrapStoreStateGraph(storeStateGraphSupplier.get()));
this.ancestorStateSupplier = this.ancestorStateGraphSupplier.map(AncestorStateImpl::new);
this.storeStateSupplier = this.storeStateGraphSupplier.map(StoreStateImpl::new);
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public String getTriggerName() {
return triggerName;
}
@Override
public GraphBranch getBranch() {
return this.graphBranch;
}
@Override
public Object getCommitMetadata() {
return this.commitMetadata;
}
@Override
public CurrentState getCurrentState() {
this.assertNotClosed();
return this.currentState;
}
@Override
public AncestorState getAncestorState() {
this.assertNotClosed();
return this.ancestorStateSupplier.get();
}
@Override
public StoreState getStoreState() {
this.assertNotClosed();
return this.storeStateSupplier.get();
}
@Override
public void close() {
if(this.closed){
return;
}
this.ancestorStateGraphSupplier.doIfLoaded(g -> g.tx().rollback());
this.storeStateGraphSupplier.doIfLoaded(g -> g.tx().rollback());
this.closed = true;
}
protected abstract ChronoGraph wrapCurrentStateGraph(ChronoGraph graph);
protected ChronoGraph wrapAncestorStateGraph(ChronoGraph graph){
return new ReadOnlyChronoGraph(graph);
}
protected ChronoGraph wrapStoreStateGraph(ChronoGraph graph){
return new ReadOnlyChronoGraph(graph);
}
// =================================================================================================================
// INTERNAL API
// =================================================================================================================
public void setTriggerName(String triggerName){
checkNotNull(triggerName, "Precondition violation - argument 'triggerName' must not be NULL!");
this.triggerName = triggerName;
}
private void assertNotClosed(){
if(this.closed){
throw new IllegalStateException("Trigger context has already been closed!");
}
}
}
| 4,777 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
StoreStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/StoreStateImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.trigger.StoreState;
import static com.google.common.base.Preconditions.*;
public class StoreStateImpl implements StoreState {
private final ChronoGraph storeStateGraph;
public StoreStateImpl(ChronoGraph storeStateGraph){
checkNotNull(storeStateGraph, "Precondition violation - argument 'storeStateGraph' must not be NULL!");
this.storeStateGraph = storeStateGraph;
}
@Override
public long getTimestamp() {
return this.storeStateGraph.tx().getCurrentTransaction().getTimestamp();
}
@Override
public GraphBranch getBranch() {
ChronoGraph g = this.storeStateGraph;
return g.getBranchManager().getBranch(g.tx().getCurrentTransaction().getBranchName());
}
@Override
public ChronoGraph getGraph() {
return this.storeStateGraph;
}
}
| 1,058 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphTriggerMetadataImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/GraphTriggerMetadataImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.exceptions.GraphTriggerException;
import org.chronos.chronograph.api.transaction.trigger.GraphTriggerMetadata;
public class GraphTriggerMetadataImpl implements GraphTriggerMetadata {
private final String triggerName;
private final String triggerClassName;
private final int priority;
private final boolean isPreCommmitTrigger;
private final boolean isPrePersistTrigger;
private final boolean isPostPersistTrigger;
private final boolean isPostCommitTrigger;
private final String userScriptContent;
private final GraphTriggerException instantiationException;
public GraphTriggerMetadataImpl(
final String triggerName,
final String triggerClassName,
final int priority,
final boolean isPreCommmitTrigger,
final boolean isPrePersistTrigger,
final boolean isPostPersistTrigger,
final boolean isPostCommitTrigger,
final String userScriptContent,
final GraphTriggerException instantiationException
) {
this.triggerName = triggerName;
this.triggerClassName = triggerClassName;
this.priority = priority;
this.isPreCommmitTrigger = isPreCommmitTrigger;
this.isPrePersistTrigger = isPrePersistTrigger;
this.isPostPersistTrigger = isPostPersistTrigger;
this.isPostCommitTrigger = isPostCommitTrigger;
this.userScriptContent = userScriptContent;
this.instantiationException = instantiationException;
}
@Override
public String getTriggerName() {
return this.triggerName;
}
@Override
public String getTriggerClassName() {
return this.triggerClassName;
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public boolean isPreCommitTrigger() {
return this.isPreCommmitTrigger;
}
@Override
public boolean isPrePersistTrigger() {
return this.isPrePersistTrigger;
}
@Override
public boolean isPostPersistTrigger() {
return this.isPostPersistTrigger;
}
@Override
public boolean isPostCommitTrigger() {
return this.isPostCommitTrigger;
}
@Override
public String getUserScriptContent() {
return this.userScriptContent;
}
@Override
public GraphTriggerException getInstantiationException() {
return this.instantiationException;
}
@Override
public String toString() {
return "GraphTriggerMetadataImpl[" +
"triggerName='" + triggerName + '\'' +
", triggerClassName='" + triggerClassName + '\'' +
", priority=" + priority +
"]";
}
}
| 2,782 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PreCommitStoreStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/PreCommitStoreStateImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.trigger.PreCommitStoreState;
import static com.google.common.base.Preconditions.*;
public class PreCommitStoreStateImpl implements PreCommitStoreState {
private final ChronoGraph storeStateGraph;
public PreCommitStoreStateImpl(ChronoGraph storeStateGraph){
checkNotNull(storeStateGraph, "Precondition violation - argument 'storeStateGraph' must not be NULL!");
this.storeStateGraph = storeStateGraph;
}
@Override
public long getTimestamp() {
return this.storeStateGraph.tx().getCurrentTransaction().getTimestamp();
}
@Override
public GraphBranch getBranch() {
ChronoGraph g = this.storeStateGraph;
return g.getBranchManager().getBranch(g.tx().getCurrentTransaction().getBranchName());
}
@Override
public ChronoGraph getGraph() {
return this.storeStateGraph;
}
}
| 1,094 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PrePersistCurrentStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/PrePersistCurrentStateImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
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.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.trigger.CurrentState;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.impl.structure.graph.readonly.NoTransactionControlChronoGraph;
import java.util.Collections;
import java.util.Set;
import static com.google.common.base.Preconditions.*;
public class PrePersistCurrentStateImpl implements CurrentState {
private final ChronoGraph originalGraph;
private final ChronoGraph noTxControlGraph;
public PrePersistCurrentStateImpl(ChronoGraph graph) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.originalGraph = graph;
this.noTxControlGraph = new NoTransactionControlChronoGraph(graph);
}
@Override
public long getTimestamp() {
// we use the original graph here, rather than the wrapped one (the wrapped graph may prevent this call)
return this.originalGraph.tx().getCurrentTransaction().getTimestamp();
}
@Override
public GraphBranch getBranch() {
// we use the original graph here, rather than the wrapped one (the wrapped graph may prevent this call)
ChronoGraph g = this.originalGraph;
return g.getBranchManager().getBranch(g.tx().getCurrentTransaction().getBranchName());
}
@Override
public Set<ChronoVertex> getModifiedVertices() {
ChronoGraphTransaction tx = this.originalGraph.tx().getCurrentTransaction();
return Collections.unmodifiableSet(tx.getContext().getModifiedVertices());
}
@Override
public Set<ChronoEdge> getModifiedEdges() {
ChronoGraphTransaction tx = this.originalGraph.tx().getCurrentTransaction();
return Collections.unmodifiableSet(tx.getContext().getModifiedEdges());
}
@Override
public Set<String> getModifiedGraphVariables() {
return this.getModifiedGraphVariables(ChronoGraphConstants.VARIABLES_DEFAULT_KEYSPACE);
}
@Override
public Set<String> getModifiedGraphVariables(final String keyspace) {
checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!");
ChronoGraphTransaction tx = this.originalGraph.tx().getCurrentTransaction();
return Collections.unmodifiableSet(tx.getContext().getModifiedVariables(keyspace));
}
@Override
public ChronoGraph getGraph() {
return this.noTxControlGraph;
}
}
| 2,811 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AncestorStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/AncestorStateImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.trigger.AncestorState;
import static com.google.common.base.Preconditions.*;
public class AncestorStateImpl implements AncestorState {
private final ChronoGraph ancestorGraph;
public AncestorStateImpl(ChronoGraph ancestorGraph){
checkNotNull(ancestorGraph, "Precondition violation - argument 'ancestorGraph' must not be NULL!");
this.ancestorGraph = ancestorGraph;
}
@Override
public long getTimestamp() {
return this.ancestorGraph.tx().getCurrentTransaction().getTimestamp();
}
@Override
public GraphBranch getBranch() {
ChronoGraph g = this.ancestorGraph;
return g.getBranchManager().getBranch(g.tx().getCurrentTransaction().getBranchName());
}
@Override
public ChronoGraph getGraph() {
return this.ancestorGraph;
}
}
| 1,053 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
NamedTriggerCategoryComparator.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/NamedTriggerCategoryComparator.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.apache.commons.lang3.tuple.Pair;
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.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 java.util.Comparator;
import java.util.Optional;
public class NamedTriggerCategoryComparator implements Comparator<Pair<String, ChronoGraphTrigger>> {
private static final NamedTriggerCategoryComparator INSTANCE = new NamedTriggerCategoryComparator();
public static NamedTriggerCategoryComparator getInstance() {
return INSTANCE;
}
@Override
public int compare(final Pair<String, ChronoGraphTrigger> o1, final Pair<String, ChronoGraphTrigger> o2) {
if(o1 == null && o2 == null){
return 0;
}else if(o1 != null && o2 == null){
return 1;
}else if(o1 == null && o2 != null){
return -1;
}
ChronoGraphTrigger t1 = o1.getRight();
ChronoGraphTrigger t2 = o2.getRight();
if(t1 instanceof ChronoGraphTriggerWrapper){
ChronoGraphTriggerWrapper wrapper = (ChronoGraphTriggerWrapper)t1;
t1 = wrapper.getWrappedTrigger().orElse(null);
}
if(t2 instanceof ChronoGraphTriggerWrapper){
ChronoGraphTriggerWrapper wrapper = (ChronoGraphTriggerWrapper)t2;
t2 = wrapper.getWrappedTrigger().orElse(null);
}
if(t1 == null && t2 == null){
return 0;
}else if(t1 != null && t2 == null){
return 1;
}else if(t1 == null && t2 != null){
return -1;
}
return this.getCategoryPriority(t2) - this.getCategoryPriority(t1);
}
private int getCategoryPriority(ChronoGraphTrigger trigger){
if(trigger instanceof ChronoGraphPreCommitTrigger){
return 1000;
}else if(trigger instanceof ChronoGraphPrePersistTrigger){
return 750;
}else if(trigger instanceof ChronoGraphPostPersistTrigger){
return 500;
} else if(trigger instanceof ChronoGraphPostCommitTrigger){
return 250;
}else{
return -1;
}
}
}
| 2,808 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTriggerManagerInternal.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/ChronoGraphTriggerManagerInternal.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.apache.commons.lang3.tuple.Pair;
import org.chronos.chronograph.api.transaction.trigger.*;
import java.util.List;
public interface ChronoGraphTriggerManagerInternal extends ChronoGraphTriggerManager {
public List<Pair<String, ChronoGraphTrigger>> getAllTriggers();
public List<Pair<String, ChronoGraphPreCommitTrigger>> getPreCommitTriggers();
public List<Pair<String, ChronoGraphPrePersistTrigger>> getPrePersistTriggers();
public List<Pair<String, ChronoGraphPostPersistTrigger>> getPostPersistTriggers();
public List<Pair<String, ChronoGraphPostCommitTrigger>> getPostCommitTriggers();
}
| 698 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
CurrentStateImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/CurrentStateImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
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.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.api.transaction.trigger.CurrentState;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.impl.structure.graph.readonly.NoTransactionControlChronoGraph;
import java.util.Collections;
import java.util.Set;
import static com.google.common.base.Preconditions.*;
public class CurrentStateImpl implements CurrentState {
private final ChronoGraph originalGraph;
private final ChronoGraph noTxControlGraph;
public CurrentStateImpl(ChronoGraph graph) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.originalGraph = graph;
this.noTxControlGraph = new NoTransactionControlChronoGraph(graph);
}
@Override
public long getTimestamp() {
// we use the original graph here, rather than the wrapped one (the wrapped graph may prevent this call)
return this.originalGraph.tx().getCurrentTransaction().getTimestamp();
}
@Override
public GraphBranch getBranch() {
// we use the original graph here, rather than the wrapped one (the wrapped graph may prevent this call)
ChronoGraph g = this.originalGraph;
return g.getBranchManager().getBranch(g.tx().getCurrentTransaction().getBranchName());
}
@Override
public Set<ChronoVertex> getModifiedVertices() {
ChronoGraphTransaction tx = this.originalGraph.tx().getCurrentTransaction();
return Collections.unmodifiableSet(tx.getContext().getModifiedVertices());
}
@Override
public Set<ChronoEdge> getModifiedEdges() {
ChronoGraphTransaction tx = this.originalGraph.tx().getCurrentTransaction();
return Collections.unmodifiableSet(tx.getContext().getModifiedEdges());
}
@Override
public Set<String> getModifiedGraphVariables() {
return this.getModifiedGraphVariables(ChronoGraphConstants.VARIABLES_DEFAULT_KEYSPACE);
}
@Override
public Set<String> getModifiedGraphVariables(final String keyspace) {
checkNotNull(keyspace, "Precondition violation - argument 'keyspace' must not be NULL!");
ChronoGraphTransaction tx = this.originalGraph.tx().getCurrentTransaction();
return Collections.unmodifiableSet(tx.getContext().getModifiedVariables(keyspace));
}
@Override
public ChronoGraph getGraph() {
return this.noTxControlGraph;
}
}
| 2,790 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTriggerWrapper.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/ChronoGraphTriggerWrapper.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.chronos.chronograph.api.transaction.trigger.*;
import org.chronos.common.serialization.KryoManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphTriggerWrapper implements ChronoGraphPreCommitTrigger, ChronoGraphPrePersistTrigger, ChronoGraphPostPersistTrigger, ChronoGraphPostCommitTrigger {
private static final Logger log = LoggerFactory.getLogger(ChronoGraphTriggerWrapper.class);
private byte[] serializedTrigger;
private String triggerClassName;
private transient ChronoGraphTrigger trigger;
private transient boolean deserializationFailed = false;
protected ChronoGraphTriggerWrapper(){
// default constructor for (de-)serialization
}
public ChronoGraphTriggerWrapper(ChronoGraphTrigger trigger){
checkNotNull(trigger, "Precondition violation - argument 'trigger' must not be NULL!");
this.serializedTrigger = KryoManager.serialize(trigger);
this.triggerClassName = trigger.getClass().getName();
// attempt to deserialize the trigger right now
try{
this.trigger = KryoManager.deserialize(this.serializedTrigger);
}catch(Exception e){
// reject this trigger
throw new IllegalArgumentException("The given ChronoGraphTrigger of type '" + trigger.getClass().getName() + "' does not deserialize properly." +
" Please make sure that the class is accessible and has a no-arguments constructor. See root cause for details.", e);
}
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) {
Optional<ChronoGraphTrigger> maybeTrigger = this.getWrappedTrigger();
if(!maybeTrigger.isPresent()){
// trigger didn't deserialize properly
return;
}
ChronoGraphTrigger trigger = maybeTrigger.get();
if(trigger instanceof ChronoGraphPostCommitTrigger){
ChronoGraphPostCommitTrigger postCommitTrigger = (ChronoGraphPostCommitTrigger)trigger;
postCommitTrigger.onPostCommit(context);
}
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) {
Optional<ChronoGraphTrigger> maybeTrigger = this.getWrappedTrigger();
if(!maybeTrigger.isPresent()){
// trigger didn't deserialize properly
return;
}
ChronoGraphTrigger trigger = maybeTrigger.get();
if(trigger instanceof ChronoGraphPostPersistTrigger){
ChronoGraphPostPersistTrigger postPersistTrigger = (ChronoGraphPostPersistTrigger)trigger;
postPersistTrigger.onPostPersist(context);
}
}
@Override
public void onPreCommit(final PreCommitTriggerContext context) throws CancelCommitException {
Optional<ChronoGraphTrigger> maybeTrigger = this.getWrappedTrigger();
if(!maybeTrigger.isPresent()){
// trigger didn't deserialize properly
return;
}
ChronoGraphTrigger trigger = maybeTrigger.get();
if(trigger instanceof ChronoGraphPreCommitTrigger){
ChronoGraphPreCommitTrigger postPersistTrigger = (ChronoGraphPreCommitTrigger)trigger;
postPersistTrigger.onPreCommit(context);
}
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
Optional<ChronoGraphTrigger> maybeTrigger = this.getWrappedTrigger();
if(!maybeTrigger.isPresent()){
// trigger didn't deserialize properly
return;
}
ChronoGraphTrigger trigger = maybeTrigger.get();
if(trigger instanceof ChronoGraphPrePersistTrigger){
ChronoGraphPrePersistTrigger postPersistTrigger = (ChronoGraphPrePersistTrigger)trigger;
postPersistTrigger.onPrePersist(context);
}
}
@Override
public int getPriority() {
return this.getWrappedTrigger().map(ChronoGraphTrigger::getPriority).orElse(0);
}
public String getTriggerClassName() {
return triggerClassName;
}
public synchronized Optional<ChronoGraphTrigger> getWrappedTrigger(){
// if we didn't deserialize the trigger yet, and we didn't encounter any errors in deserialization so far...
if(this.trigger == null && !this.deserializationFailed){
// ... try to deserialize the trigger now.
try{
this.trigger = KryoManager.deserialize(this.serializedTrigger);
}catch(Exception e){
log.warn("Failed to deserialize ChronoGraph Trigger of type [" + this.triggerClassName + "]. This trigger will be ignored!" +
" Cause: " + e + ", Root Cause: " + ExceptionUtils.getRootCause(e)
);
// remember that this trigger cannot be deserialized
this.deserializationFailed = true;
}
}
// at this point, the trigger may or may not be NULL.
return Optional.ofNullable(this.trigger);
}
}
| 5,269 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
NamedTriggerComparator.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/NamedTriggerComparator.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.shaded.jackson.databind.util.Named;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphTrigger;
import java.util.Comparator;
public class NamedTriggerComparator implements Comparator<Pair<String, ChronoGraphTrigger>> {
private static final NamedTriggerComparator INSTANCE = new NamedTriggerComparator();
public static NamedTriggerComparator getInstance() {
return INSTANCE;
}
@Override
public int compare(final Pair<String, ChronoGraphTrigger> o1, final Pair<String, ChronoGraphTrigger> o2) {
if(o1 == null && o2 == null){
return 0;
}
if(o1 == null && o2 != null){
return -1;
}
if(o1 != null && o2 == null){
return 1;
}
int prioLeft = o1.getRight().getPriority();
int prioRight = o2.getRight().getPriority();
if(prioLeft == prioRight){
return 0;
}else if(prioLeft < prioRight){
return -1;
}else{
return 1;
}
}
}
| 1,172 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PreTriggerContextImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/PreTriggerContextImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.trigger.PreCommitTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.PrePersistTriggerContext;
import org.chronos.chronograph.internal.impl.structure.graph.readonly.NoTransactionControlChronoGraph;
import java.util.function.Supplier;
public class PreTriggerContextImpl extends AbstractTriggerContext implements PreCommitTriggerContext, PrePersistTriggerContext {
public PreTriggerContextImpl(final GraphBranch branch, final Object commitMetadata, ChronoGraph currentStateGraph, Supplier<ChronoGraph> ancestorStateGraphSupplier, Supplier<ChronoGraph> storeStateGraphSupplier) {
super(branch, commitMetadata, currentStateGraph, ancestorStateGraphSupplier, storeStateGraphSupplier);
}
@Override
protected ChronoGraph wrapCurrentStateGraph(final ChronoGraph graph) {
return new NoTransactionControlChronoGraph(graph);
}
}
| 1,106 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTriggerManagerImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/ChronoGraphTriggerManagerImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.tuple.Pair;
import org.chronos.chronodb.api.ChronoDBConstants;
import org.chronos.chronodb.api.ChronoDBTransaction;
import org.chronos.chronodb.api.SerializationManager;
import org.chronos.chronograph.api.exceptions.GraphTriggerClassNotFoundException;
import org.chronos.chronograph.api.exceptions.GraphTriggerException;
import org.chronos.chronograph.api.exceptions.TriggerAlreadyExistsException;
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.ChronoGraphTriggerManager;
import org.chronos.chronograph.api.transaction.trigger.GraphTriggerMetadata;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.api.structure.ChronoGraphInternal;
import org.chronos.chronograph.internal.impl.transaction.trigger.script.AbstractScriptedGraphTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphTriggerManagerImpl implements ChronoGraphTriggerManager, ChronoGraphTriggerManagerInternal {
private static final Logger log = LoggerFactory.getLogger(ChronoGraphTriggerManagerImpl.class);
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final ChronoGraphInternal graph;
private List<Pair<String, ChronoGraphTrigger>> triggerCache;
// =================================================================================================================
// CONSTRUCTOR
// =================================================================================================================
public ChronoGraphTriggerManagerImpl(ChronoGraphInternal graph) {
checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!");
this.graph = graph;
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public synchronized boolean existsTrigger(final String triggerName) {
this.validateTriggerName(triggerName);
return this.getAllTriggers().stream().anyMatch(p -> p.getLeft().equals(triggerName));
}
@Override
public synchronized boolean createTriggerIfNotPresent(final String triggerName, final Supplier<ChronoGraphTrigger> triggerSupplier) {
return this.createTriggerIfNotPresent(triggerName, triggerSupplier, null);
}
@Override
public synchronized boolean createTriggerIfNotPresent(final String triggerName, final Supplier<ChronoGraphTrigger> triggerSupplier, final Object commitMetadata) {
this.validateTriggerName(triggerName);
checkNotNull(triggerSupplier, "Precondition violation - argument 'triggerSupplier' must not be NULL!");
if (this.existsTrigger(triggerName)) {
// trigger already exists
return false;
}
ChronoGraphTrigger trigger = triggerSupplier.get();
if (trigger == null) {
throw new IllegalArgumentException("The given trigger supplier has returned NULL!");
}
this.validateIncomingTrigger(trigger);
// wrap the trigger inside a ChronoGraphTrigger to make sure we can always deserialize it properly
ChronoGraphTriggerWrapper wrapper = new ChronoGraphTriggerWrapper(trigger);
ChronoDBTransaction tx = this.backingTx();
tx.put(ChronoGraphConstants.KEYSPACE_TRIGGERS, triggerName, wrapper);
tx.commit(commitMetadata);
this.clearTriggerCache();
return true;
}
@Override
public synchronized boolean createTriggerAndOverwrite(final String triggerName, final ChronoGraphTrigger trigger) {
return this.createTriggerAndOverwrite(triggerName, trigger, null);
}
@Override
public synchronized boolean createTriggerAndOverwrite(final String triggerName, final ChronoGraphTrigger trigger, Object commitMetadata) {
this.validateTriggerName(triggerName);
this.validateIncomingTrigger(trigger);
// wrap the trigger inside a ChronoGraphTrigger to make sure we can always deserialize it properly
ChronoGraphTriggerWrapper wrapper = new ChronoGraphTriggerWrapper(trigger);
ChronoDBTransaction tx = this.backingTx();
boolean result = tx.exists(ChronoGraphConstants.KEYSPACE_TRIGGERS, triggerName);
tx.put(ChronoGraphConstants.KEYSPACE_TRIGGERS, triggerName, wrapper);
tx.commit(commitMetadata);
if (result) {
this.clearTriggerCache();
}
return result;
}
@Override
public synchronized void createTrigger(final String triggerName, final ChronoGraphTrigger trigger) throws TriggerAlreadyExistsException {
this.createTrigger(triggerName, trigger, null);
}
@Override
public synchronized void createTrigger(final String triggerName, final ChronoGraphTrigger trigger, final Object commitMetadata) throws TriggerAlreadyExistsException {
boolean added = this.createTriggerIfNotPresent(triggerName, () -> trigger, commitMetadata);
if (!added) {
throw new TriggerAlreadyExistsException("A trigger with unique name '" + triggerName + "' already exists!");
}
}
@Override
public synchronized boolean dropTrigger(final String triggerName) {
return dropTrigger(triggerName, null);
}
@Override
public synchronized boolean dropTrigger(final String triggerName, final Object commitMetadata) {
this.validateTriggerName(triggerName);
ChronoDBTransaction tx = this.backingTx();
boolean exists = tx.exists(ChronoGraphConstants.KEYSPACE_TRIGGERS, triggerName);
if (!exists) {
// nothing to do
return false;
}
tx.remove(ChronoGraphConstants.KEYSPACE_TRIGGERS, triggerName);
tx.commit(commitMetadata);
this.clearTriggerCache();
return true;
}
@Override
public synchronized Set<String> getTriggerNames() {
return this.getAllTriggers().stream()
// only consider the names (left element of the pair)
.map(Pair::getLeft).collect(Collectors.toSet());
}
@Override
public List<GraphTriggerMetadata> getTriggers() {
ChronoDBTransaction tx = this.backingTx();
Set<String> allTriggerNames = tx.keySet(ChronoGraphConstants.KEYSPACE_TRIGGERS);
return allTriggerNames.stream()
.map(triggerName -> Pair.of(triggerName, (ChronoGraphTrigger)tx.get(ChronoGraphConstants.KEYSPACE_TRIGGERS, triggerName)))
.filter(pair -> pair.getRight() != null)
.sorted(NamedTriggerCategoryComparator.getInstance().thenComparing(NamedTriggerComparator.getInstance().reversed()))
.map(pair -> this.getTriggerMetadata(pair.getLeft(), pair.getRight()))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public GraphTriggerMetadata getTrigger(final String triggerName) {
checkNotNull(triggerName, "Precondition violation - argument 'triggerName' must not be NULL!");
ChronoDBTransaction tx = this.backingTx();
ChronoGraphTrigger trigger = tx.get(ChronoGraphConstants.KEYSPACE_TRIGGERS, triggerName);
return getTriggerMetadata(triggerName, trigger);
}
private GraphTriggerMetadata getTriggerMetadata(final String triggerName, final ChronoGraphTrigger persistedTrigger) {
if (persistedTrigger == null) {
return null;
}
ChronoGraphTrigger trigger = persistedTrigger;
GraphTriggerException loadException = null;
try {
trigger = this.loadPersistedTrigger(triggerName, trigger);
} catch (GraphTriggerException e) {
loadException = e;
}
boolean isPreCommit = trigger instanceof ChronoGraphPreCommitTrigger;
boolean isPrePersist = trigger instanceof ChronoGraphPrePersistTrigger;
boolean isPostPersist = trigger instanceof ChronoGraphPostPersistTrigger;
boolean isPostCommmit = trigger instanceof ChronoGraphPostCommitTrigger;
String userScriptContent = null;
if (trigger instanceof AbstractScriptedGraphTrigger) {
AbstractScriptedGraphTrigger scriptedGraphTrigger = (AbstractScriptedGraphTrigger) trigger;
userScriptContent = scriptedGraphTrigger.getUserScriptContent();
}
String triggerClassName = trigger.getClass().getName();
return new GraphTriggerMetadataImpl(
triggerName,
triggerClassName,
trigger.getPriority(),
isPreCommit,
isPrePersist,
isPostPersist,
isPostCommmit,
userScriptContent,
loadException
);
}
// =================================================================================================================
// INTERNAL METHODS
// =================================================================================================================
public synchronized List<Pair<String, ChronoGraphTrigger>> getAllTriggers() {
if (this.triggerCache == null) {
// load from DB
List<Pair<String, ChronoGraphTrigger>> list = Lists.newArrayList();
ChronoDBTransaction tx = this.backingTx();
Set<String> triggerNames = tx.keySet(ChronoGraphConstants.KEYSPACE_TRIGGERS);
for (String name : triggerNames) {
try {
// load the trigger
ChronoGraphTrigger trigger = tx.get(ChronoGraphConstants.KEYSPACE_TRIGGERS, name);
trigger = this.loadPersistedTrigger(name, trigger);
list.add(Pair.of(name, trigger));
} catch (Exception e) {
log.error("Failed to load Graph Trigger '" + name + "' from persistent store. This trigger will not be executed!", e);
}
}
// sort them
// note: comparators in java sort ascending by default, we want descending priority
// order here, so we reverse the comparator.
list.sort(NamedTriggerComparator.getInstance().reversed());
this.triggerCache = Collections.unmodifiableList(list);
}
return this.triggerCache;
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public List<Pair<String, ChronoGraphPreCommitTrigger>> getPreCommitTriggers() {
return this.getAllTriggers().stream()
.filter(pair -> pair.getRight() instanceof ChronoGraphPreCommitTrigger)
.map(pair -> (Pair<String, ChronoGraphPreCommitTrigger>) (Pair) pair)
.collect(Collectors.toList());
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public List<Pair<String, ChronoGraphPrePersistTrigger>> getPrePersistTriggers() {
return this.getAllTriggers().stream()
.filter(pair -> pair.getRight() instanceof ChronoGraphPrePersistTrigger)
.map(pair -> (Pair<String, ChronoGraphPrePersistTrigger>) (Pair) pair)
.collect(Collectors.toList());
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public List<Pair<String, ChronoGraphPostPersistTrigger>> getPostPersistTriggers() {
return this.getAllTriggers().stream()
.filter(pair -> pair.getRight() instanceof ChronoGraphPostPersistTrigger)
.map(pair -> (Pair<String, ChronoGraphPostPersistTrigger>) (Pair) pair)
.collect(Collectors.toList());
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public List<Pair<String, ChronoGraphPostCommitTrigger>> getPostCommitTriggers() {
return this.getAllTriggers().stream()
.filter(pair -> pair.getRight() instanceof ChronoGraphPostCommitTrigger)
.map(pair -> (Pair<String, ChronoGraphPostCommitTrigger>) (Pair) pair)
.collect(Collectors.toList());
}
// =================================================================================================================
// INTERNAL HELPER METHODS
// =================================================================================================================
private ChronoDBTransaction backingTx() {
return this.graph.getBackingDB().tx(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER);
}
private void validateTriggerName(String triggerName) {
checkNotNull(triggerName, "Precondition violation - argument 'triggerName' must not be NULL!");
checkArgument(triggerName.isEmpty() == false, "Precondition violation - argumen 'triggerName' must not be the empty string!");
}
private void validateIncomingTrigger(ChronoGraphTrigger trigger) {
if (trigger == null) {
throw new NullPointerException("Precondition violation - the given trigger is NULL!");
}
// make sure the trigger implements at least one of our sub-interfaces
boolean atLeastOneInterfaceImplemented = false;
if (trigger instanceof ChronoGraphPreCommitTrigger || trigger instanceof ChronoGraphPrePersistTrigger || trigger instanceof ChronoGraphPostPersistTrigger || trigger instanceof ChronoGraphPostCommitTrigger) {
atLeastOneInterfaceImplemented = true;
}
if (!atLeastOneInterfaceImplemented) {
throw new IllegalArgumentException(
"The given trigger of type '" + trigger.getClass().getName() + "' does not implement any concrete trigger interface." +
" Please implement at least one of: "
+ ChronoGraphPreCommitTrigger.class.getSimpleName() + ", "
+ ChronoGraphPrePersistTrigger.class.getSimpleName() + ", "
+ ChronoGraphPostPersistTrigger.class.getSimpleName() + " or "
+ ChronoGraphPostCommitTrigger.class.getSimpleName()
+ ".");
}
SerializationManager serializationManager = this.graph.getBackingDB().getSerializationManager();
try {
byte[] serialized = serializationManager.serialize(trigger);
serializationManager.deserialize(serialized);
} catch (Exception e) {
throw new IllegalArgumentException("Precondition violation - the given trigger is not serializable! See root cause for details.", e);
}
}
protected ChronoGraphTrigger loadPersistedTrigger(String name, ChronoGraphTrigger persistedTrigger) {
ChronoGraphTrigger trigger = persistedTrigger;
if (trigger instanceof ChronoGraphTriggerWrapper) {
ChronoGraphTriggerWrapper wrapper = (ChronoGraphTriggerWrapper) trigger;
Optional<ChronoGraphTrigger> wrappedTrigger = wrapper.getWrappedTrigger();
if (!wrappedTrigger.isPresent()) {
// failed to deserialize the wrapped trigger, print an error and ignore this trigger
throw new GraphTriggerClassNotFoundException("Failed to load Graph Trigger '" + name + "' from persistent store! Is the required Java Class '" + wrapper.getTriggerClassName() + "' on the classpath? This trigger will not be executed!");
} else {
// wrapper initialized successfully, use the wrapped trigger
trigger = wrappedTrigger.get();
}
}
if (trigger instanceof AbstractScriptedGraphTrigger) {
AbstractScriptedGraphTrigger scriptedTrigger = (AbstractScriptedGraphTrigger) trigger;
// make sure that the trigger compiles and is instantiable
scriptedTrigger.getCompiledScriptInstance();
}
return trigger;
}
private void clearTriggerCache() {
this.triggerCache = null;
}
}
| 16,827 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PostTriggerContextImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/PostTriggerContextImpl.java | package org.chronos.chronograph.internal.impl.transaction.trigger;
import org.chronos.chronograph.api.branch.GraphBranch;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.trigger.*;
import org.chronos.chronograph.internal.impl.structure.graph.readonly.ReadOnlyChronoGraph;
import org.chronos.chronograph.internal.impl.util.CachedSupplier;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.*;
public class PostTriggerContextImpl extends AbstractTriggerContext implements PostCommitTriggerContext, PostPersistTriggerContext {
private final long timestamp;
private final CachedSupplier<ChronoGraph> preCommitStoreStateGraphSupplier;
private final CachedSupplier<PreCommitStoreState> preCommitStoreStateSupplier;
public PostTriggerContextImpl(final GraphBranch branch, long timestamp, final Object commitMetadata, ChronoGraph currentStateGraph, Supplier<ChronoGraph> ancestorStateGraphSupplier, Supplier<ChronoGraph> storeStateGraphSupplier, Supplier<ChronoGraph> preCommitStoreStateGraphSupplier) {
super(branch, commitMetadata, currentStateGraph, ancestorStateGraphSupplier, storeStateGraphSupplier);
checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!");
this.timestamp = timestamp;
this.preCommitStoreStateGraphSupplier = CachedSupplier.create(() -> this.wrapStoreStateGraph(preCommitStoreStateGraphSupplier.get()));
this.preCommitStoreStateSupplier = this.preCommitStoreStateGraphSupplier.map(PreCommitStoreStateImpl::new);
}
@Override
public long getCommitTimestamp() {
return this.timestamp;
}
@Override
public PreCommitStoreState getPreCommitStoreState() {
return this.preCommitStoreStateSupplier.get();
}
@Override
protected ChronoGraph wrapCurrentStateGraph(final ChronoGraph graph) {
return new ReadOnlyChronoGraph(graph);
}
@Override
public void close() {
if(this.closed){
return;
}
super.close();
this.preCommitStoreStateGraphSupplier.doIfLoaded(g -> g.tx().rollback());
}
}
| 2,211 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ScriptedGraphPostPersistTrigger.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/script/ScriptedGraphPostPersistTrigger.java | package org.chronos.chronograph.internal.impl.transaction.trigger.script;
import groovy.lang.Binding;
import groovy.lang.Script;
import org.apache.commons.lang3.StringUtils;
import org.chronos.chronograph.api.transaction.trigger.CancelCommitException;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPostPersistTrigger;
import org.chronos.chronograph.api.transaction.trigger.PostPersistTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.TriggerContext;
import org.chronos.common.annotation.PersistentClass;
import java.util.Arrays;
import java.util.stream.Collectors;
@PersistentClass("kryo")
public class ScriptedGraphPostPersistTrigger extends AbstractScriptedGraphTrigger implements ChronoGraphPostPersistTrigger {
public ScriptedGraphPostPersistTrigger(String userScriptContent, int priority){
super(userScriptContent, priority);
}
protected ScriptedGraphPostPersistTrigger(){
// default constructor for (de-)serialization.
}
@Override
public void onPostPersist(final PostPersistTriggerContext context) throws CancelCommitException {
Binding binding = new Binding();
binding.setVariable("context", context);
Script userScript = this.getCompiledScriptInstance();
userScript.setBinding(binding);
userScript.run();
}
@Override
protected Class<? extends TriggerContext> getTriggerContextClass() {
return PostPersistTriggerContext.class;
}
@Override
public String toString() {
String[] lines = this.getUserScriptContent().split("\\r?\\n");
String userScriptDigest = StringUtils.abbreviate(Arrays.stream(lines).skip(1).collect(Collectors.joining(" ", "", "")), 0, 100);
return "PostPersistGraphScriptTrigger[" + userScriptDigest + "]";
}
}
| 1,825 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ScriptedGraphPostCommitTrigger.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/script/ScriptedGraphPostCommitTrigger.java | package org.chronos.chronograph.internal.impl.transaction.trigger.script;
import groovy.lang.Binding;
import groovy.lang.Script;
import org.apache.commons.lang3.StringUtils;
import org.chronos.chronograph.api.transaction.trigger.CancelCommitException;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPostCommitTrigger;
import org.chronos.chronograph.api.transaction.trigger.PostCommitTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.TriggerContext;
import org.chronos.common.annotation.PersistentClass;
import java.util.Arrays;
import java.util.stream.Collectors;
@PersistentClass("kryo")
public class ScriptedGraphPostCommitTrigger extends AbstractScriptedGraphTrigger implements ChronoGraphPostCommitTrigger {
public ScriptedGraphPostCommitTrigger(String userScriptContent, int priority){
super(userScriptContent, priority);
}
protected ScriptedGraphPostCommitTrigger(){
// default constructor for (de-)serialization.
}
@Override
public void onPostCommit(final PostCommitTriggerContext context) throws CancelCommitException {
Binding binding = new Binding();
binding.setVariable("context", context);
Script userScript = this.getCompiledScriptInstance();
userScript.setBinding(binding);
userScript.run();
}
@Override
protected Class<? extends TriggerContext> getTriggerContextClass() {
return PostCommitTriggerContext.class;
}
@Override
public String toString() {
String[] lines = this.getUserScriptContent().split("\\r?\\n");
String userScriptDigest = StringUtils.abbreviate(Arrays.stream(lines).skip(1).collect(Collectors.joining(" ", "", "")), 0, 100);
return "PostCommitGraphScriptTrigger[" + userScriptDigest + "]";
}
}
| 1,815 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractScriptedGraphTrigger.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/script/AbstractScriptedGraphTrigger.java | package org.chronos.chronograph.internal.impl.transaction.trigger.script;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import groovy.transform.CompileStatic;
import org.chronos.chronograph.api.exceptions.GraphTriggerScriptCompilationException;
import org.chronos.chronograph.api.exceptions.GraphTriggerScriptInstantiationException;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphTrigger;
import org.chronos.chronograph.api.transaction.trigger.TriggerContext;
import org.chronos.common.annotation.PersistentClass;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ExecutionException;
import static com.google.common.base.Preconditions.*;
@PersistentClass("kryo")
public abstract class AbstractScriptedGraphTrigger implements ChronoGraphTrigger {
// =================================================================================================================
// STATIC PART
// =================================================================================================================
private static transient LoadingCache<String, Class<? extends Script>> COMPILED_TRIGGERS_CODE_CACHE =
CacheBuilder.newBuilder()
.maximumSize(1000)
.build(CacheLoader.from(AbstractScriptedGraphTrigger::runGroovyCompile));
@SuppressWarnings("unchecked")
private static Class<? extends Script> runGroovyCompile(String scriptContent) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// prepare the compiler configuration to have static type checking
CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(new ASTTransformationCustomizer(CompileStatic.class));
try (GroovyClassLoader gcl = new GroovyClassLoader(classLoader, config)) {
return (Class<? extends Script>) gcl.parseClass(scriptContent);
} catch (IOException e) {
throw new GraphTriggerScriptCompilationException("Failed to compile Groovy Script for GraphScriptTrigger. See root cause for details.", e);
}
}
// =================================================================================================================
// SERIALIZED FIELDS
// =================================================================================================================
private String userScriptContent;
private int priority;
// =================================================================================================================
// CACHES
// =================================================================================================================
private transient Class<? extends Script> compiledScriptClass;
private transient Script scriptInstance;
// =================================================================================================================
// CONSTRUCTORS
// =================================================================================================================
protected AbstractScriptedGraphTrigger(String userScriptContent, int priority) {
checkNotNull(userScriptContent, "Precondition violation - argument 'userScriptContent' must not be NULL!");
this.userScriptContent = userScriptContent;
this.priority = priority;
// make sure that the script actually compiles
this.getCompiledScriptInstance();
}
protected AbstractScriptedGraphTrigger() {
// default constructor for (de-)serialization.
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public int getPriority() {
return this.priority;
}
public String getUserScriptContent() {
return this.userScriptContent;
}
@SuppressWarnings("unchecked")
public synchronized Class<? extends Script> getCompiledScriptClass() {
if (this.compiledScriptClass != null) {
return this.compiledScriptClass;
}
if (this.userScriptContent == null) {
throw new IllegalStateException("Graph Script Trigger: User Script Content is NULL!");
}
// 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.*;";
imports += "import org.chronos.chronograph.api.transaction.*;import org.chronos.chronograph.api.transaction.trigger.*;";
// prepare the declaration of the 'context' variable within the script (with the proper variable type)
String varDefs = this.getTriggerContextClass().getName() + " context = (" + this.getTriggerContextClass().getName() + ")this.binding.variables.context;\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
String triggerScript = imports + varDefs + this.userScriptContent;
try{
return COMPILED_TRIGGERS_CODE_CACHE.get(triggerScript);
}catch(ExecutionException e){
throw new GraphTriggerScriptCompilationException("Failed to compile Groovy Script for GraphScriptTrigger. See root cause for details.", e);
}
}
public synchronized Script getCompiledScriptInstance() {
if (this.scriptInstance != null) {
return this.scriptInstance;
}
Class<? extends Script> scriptClass = this.getCompiledScriptClass();
try {
this.scriptInstance = scriptClass.getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new GraphTriggerScriptInstantiationException("Failed to instantiate Graph Trigger Script. See root cause for details.", e);
}
return this.scriptInstance;
}
protected abstract Class<? extends TriggerContext> getTriggerContextClass();
}
| 6,862 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ScriptedGraphPrePersistTrigger.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/script/ScriptedGraphPrePersistTrigger.java | package org.chronos.chronograph.internal.impl.transaction.trigger.script;
import groovy.lang.Binding;
import groovy.lang.Script;
import org.apache.commons.lang3.StringUtils;
import org.chronos.chronograph.api.transaction.trigger.CancelCommitException;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPrePersistTrigger;
import org.chronos.chronograph.api.transaction.trigger.PrePersistTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.TriggerContext;
import org.chronos.common.annotation.PersistentClass;
import java.util.Arrays;
import java.util.stream.Collectors;
@PersistentClass("kryo")
public class ScriptedGraphPrePersistTrigger extends AbstractScriptedGraphTrigger implements ChronoGraphPrePersistTrigger {
public ScriptedGraphPrePersistTrigger(String userScriptContent, int priority){
super(userScriptContent, priority);
}
protected ScriptedGraphPrePersistTrigger(){
// default constructor for (de-)serialization.
}
@Override
public void onPrePersist(final PrePersistTriggerContext context) throws CancelCommitException {
Binding binding = new Binding();
binding.setVariable("context", context);
Script userScript = this.getCompiledScriptInstance();
userScript.setBinding(binding);
userScript.run();
}
@Override
protected Class<? extends TriggerContext> getTriggerContextClass() {
return PrePersistTriggerContext.class;
}
@Override
public String toString() {
String[] lines = this.getUserScriptContent().split("\\r?\\n");
String userScriptDigest = StringUtils.abbreviate(Arrays.stream(lines).skip(1).collect(Collectors.joining(" ", "", "")), 0, 100);
return "PrePersistGraphScriptTrigger[" + userScriptDigest + "]";
}
}
| 1,815 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ScriptedGraphPreCommitTrigger.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/trigger/script/ScriptedGraphPreCommitTrigger.java | package org.chronos.chronograph.internal.impl.transaction.trigger.script;
import groovy.lang.Binding;
import groovy.lang.Script;
import org.apache.commons.lang3.StringUtils;
import org.chronos.chronograph.api.transaction.trigger.CancelCommitException;
import org.chronos.chronograph.api.transaction.trigger.ChronoGraphPreCommitTrigger;
import org.chronos.chronograph.api.transaction.trigger.PreCommitTriggerContext;
import org.chronos.chronograph.api.transaction.trigger.TriggerContext;
import org.chronos.common.annotation.PersistentClass;
import java.util.Arrays;
import java.util.stream.Collectors;
@PersistentClass("kryo")
public class ScriptedGraphPreCommitTrigger extends AbstractScriptedGraphTrigger implements ChronoGraphPreCommitTrigger {
public ScriptedGraphPreCommitTrigger(String userScriptContent, int priority){
super(userScriptContent, priority);
}
protected ScriptedGraphPreCommitTrigger(){
// default constructor for (de-)serialization.
}
@Override
public void onPreCommit(final PreCommitTriggerContext context) throws CancelCommitException {
Binding binding = new Binding();
binding.setVariable("context", context);
Script userScript = this.getCompiledScriptInstance();
userScript.setBinding(binding);
userScript.run();
}
@Override
protected Class<? extends TriggerContext> getTriggerContextClass() {
return PreCommitTriggerContext.class;
}
@Override
public String toString() {
String[] lines = this.getUserScriptContent().split("\\r?\\n");
String userScriptDigest = StringUtils.abbreviate(Arrays.stream(lines).skip(1).collect(Collectors.joining(" ", "", "")), 0, 100);
return "PreCommitGraphScriptTrigger[" + userScriptDigest + "]";
}
}
| 1,805 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PropertyConflictImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/conflict/PropertyConflictImpl.java | package org.chronos.chronograph.internal.impl.transaction.conflict;
import static com.google.common.base.Preconditions.*;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflict;
public class PropertyConflictImpl implements PropertyConflict {
private final String propertyKey;
private final Element transactionElement;
private final Property<?> transactionProperty;
private final Element storeElement;
private final Property<?> storeProperty;
private final Element ancestorElement;
private final Property<?> ancestorProperty;
public PropertyConflictImpl(final String propertyKey, final Element transactionElement,
final Property<?> transactionProperty, final Element storeElement, final Property<?> storeProperty,
final Element ancestorElement, final Property<?> ancestorProperty) {
checkNotNull(propertyKey, "Precondition violation - argument 'propertyKey' must not be NULL!");
checkNotNull(ancestorElement, "Precondition violation - argument 'ancestorElement' must not be NULL!");
checkNotNull(transactionProperty, "Precondition violation - argument 'transactionProperty' must not be NULL!");
checkNotNull(storeElement, "Precondition violation - argument 'storeElement' must not be NULL!");
checkNotNull(storeProperty, "Precondition violation - argument 'storeProperty' must not be NULL!");
this.propertyKey = propertyKey;
this.transactionElement = transactionElement;
this.transactionProperty = transactionProperty;
this.storeElement = storeElement;
this.storeProperty = storeProperty;
this.ancestorElement = ancestorElement;
this.ancestorProperty = ancestorProperty;
}
@Override
public String getPropertyKey() {
return this.propertyKey;
}
@Override
public Element getTransactionElement() {
return this.transactionElement;
}
@Override
public Property<?> getTransactionProperty() {
return this.transactionProperty;
}
@Override
public Element getStoreElement() {
return this.storeElement;
}
@Override
public Property<?> getStoreProperty() {
return this.storeProperty;
}
@Override
public Element getAncestorElement() {
return this.ancestorElement;
}
@Override
public Property<?> getAncestorProperty() {
return this.ancestorProperty;
}
}
| 2,352 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
OverwriteWithStoreValueStrategy.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/conflict/strategies/OverwriteWithStoreValueStrategy.java | package org.chronos.chronograph.internal.impl.transaction.conflict.strategies;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflict;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflictResolutionStrategy;
public class OverwriteWithStoreValueStrategy implements PropertyConflictResolutionStrategy {
public static final OverwriteWithStoreValueStrategy INSTANCE = new OverwriteWithStoreValueStrategy();
private OverwriteWithStoreValueStrategy() {
// singleton
}
@Override
public Object resolve(final PropertyConflict conflict) {
Property<?> property = conflict.getStoreProperty();
if (property.isPresent()) {
return property.value();
} else {
return null;
}
}
}
| 849 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
OverwriteWithTransactionValueStrategy.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/conflict/strategies/OverwriteWithTransactionValueStrategy.java | package org.chronos.chronograph.internal.impl.transaction.conflict.strategies;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflict;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflictResolutionStrategy;
public class OverwriteWithTransactionValueStrategy implements PropertyConflictResolutionStrategy {
public static final OverwriteWithTransactionValueStrategy INSTANCE = new OverwriteWithTransactionValueStrategy();
private OverwriteWithTransactionValueStrategy() {
// singleton
}
@Override
public Object resolve(final PropertyConflict conflict) {
Property<?> property = conflict.getTransactionProperty();
if (property.isPresent()) {
return property.value();
} else {
return null;
}
}
}
| 813 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ThrowExceptionStrategy.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/conflict/strategies/ThrowExceptionStrategy.java | package org.chronos.chronograph.internal.impl.transaction.conflict.strategies;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.exceptions.ChronoGraphCommitConflictException;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflict;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflictResolutionStrategy;
public class ThrowExceptionStrategy implements PropertyConflictResolutionStrategy {
public static final ThrowExceptionStrategy INSTANCE = new ThrowExceptionStrategy();
private ThrowExceptionStrategy() {
// singleton
}
@Override
public Object resolve(final PropertyConflict conflict) {
String elementClass = conflict.getTransactionElement() instanceof Vertex ? "Vertex" : "Edge";
throw new ChronoGraphCommitConflictException("Commit conflict on " + elementClass + " ("
+ conflict.getTransactionElement().id() + ") at property '" + conflict.getPropertyKey() + "'!");
}
}
| 972 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphConflictMergeUtils.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/transaction/merge/GraphConflictMergeUtils.java | package org.chronos.chronograph.internal.impl.transaction.merge;
import static com.google.common.base.Preconditions.*;
import java.util.Objects;
import java.util.Set;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflict;
import org.chronos.chronograph.api.transaction.conflict.PropertyConflictResolutionStrategy;
import org.chronos.chronograph.internal.impl.transaction.conflict.PropertyConflictImpl;
import com.google.common.collect.Sets;
public class GraphConflictMergeUtils {
public static void mergeProperties(final Element element, final Element storeElement, final Element ancestorElement,
final PropertyConflictResolutionStrategy strategy) {
checkNotNull(element, "Precondition violation - argument 'element' must not be NULL!");
checkNotNull(storeElement, "Precondition violation - argument 'storeElement' must not be NULL!");
checkNotNull(strategy, "Precondition violation - argument 'strategy' must not be NULL!");
// get all element property keys
Set<String> elementKeys = Sets.newHashSet(element.keys());
Set<String> storeElementKeys = Sets.newHashSet(storeElement.keys());
Set<String> allKeys = Sets.union(elementKeys, storeElementKeys);
for (String propertyKey : allKeys) {
mergeSingleProperty(propertyKey, element, storeElement, ancestorElement, strategy);
}
}
private static void mergeSingleProperty(final String propertyKey, final Element element, final Element storeElement,
final Element ancestorElement, final PropertyConflictResolutionStrategy strategy) {
Property<?> elementProperty = element.property(propertyKey);
Property<?> storeProperty = storeElement.property(propertyKey);
// resolve the ancestor property, if any
Property<?> ancestorProperty = Property.empty();
if (ancestorElement != null) {
ancestorProperty = ancestorElement.property(propertyKey);
}
if (elementProperty.isPresent() && !storeProperty.isPresent()) {
// either the property was added by the transaction, or it was removed in the store.
if (ancestorProperty.isPresent() && Objects.equals(ancestorProperty.value(), elementProperty.value())) {
// property was deleted in the store and is unchanged in our transaction, remove it
elementProperty.remove();
return;
} else if (ancestorProperty.isPresent() == false) {
// property was newly added in the current transaction, keep it
return;
}
}
if (!elementProperty.isPresent() && storeProperty.isPresent()) {
// the property must have either been added in the store, or deleted in our transaction.
// check the common ancestor.
if (ancestorProperty.isPresent() && Objects.equals(ancestorProperty.value(), storeProperty.value())) {
// the property has been removed in this transaction, keep it that way.
return;
} else if (ancestorProperty.isPresent() == false) {
// the property has been added in the store, add it to the transaction
element.property(propertyKey, storeProperty.value());
return;
}
}
if (elementProperty.isPresent() && storeProperty.isPresent()) {
// property is present in transaction and store, compare the values
Object value = elementProperty.value();
Object storeValue = storeProperty.value();
if (Objects.equals(value, storeValue)) {
return;
} else {
// values are conflicting, check if any side is unchanged w.r.t. ancestor
if (ancestorProperty.isPresent()) {
// there is a common ancestor, check if either side is unchanged
Object ancestorValue = ancestorProperty.value();
if (Objects.equals(value, ancestorValue)) {
// transaction property is unchanged, we missed an update in the store.
// use the value from the stored property.
element.property(propertyKey, storeValue);
return;
} else if (Objects.equals(storeValue, ancestorValue)) {
// transaction property has been modified, store is unmodified, keep the change
return;
}
}
}
}
// in any other case, we have a conflict (possibly without common ancestor)
PropertyConflict conflict = new PropertyConflictImpl(propertyKey, element, elementProperty, storeElement,
storeProperty, ancestorElement, ancestorProperty);
resolveConflict(conflict, strategy);
return;
}
private static void resolveConflict(final PropertyConflict conflict,
final PropertyConflictResolutionStrategy strategy) {
Object newValue = strategy.resolve(conflict);
if (newValue == null) {
conflict.getTransactionProperty().remove();
} else {
String key = conflict.getPropertyKey();
conflict.getTransactionElement().property(key, newValue);
}
}
}
| 4,722 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GraphDumpFormat.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/GraphDumpFormat.java | package org.chronos.chronograph.internal.impl.dumpformat;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.chronos.chronodb.api.DumpOption;
import org.chronos.chronodb.api.dump.ChronoConverter;
import org.chronos.chronodb.internal.impl.dump.ChronoDBDumpUtil;
import org.chronos.chronodb.internal.impl.dump.DumpOptions;
import org.chronos.chronograph.api.structure.record.IEdgeRecord;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.internal.impl.dumpformat.converter.EdgeRecordConverter;
import org.chronos.chronograph.internal.impl.dumpformat.converter.VertexRecordConverter;
import org.chronos.chronograph.internal.impl.dumpformat.property.AbstractPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.property.BinaryPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.property.PlainPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.vertexproperty.VertexBinaryPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.vertexproperty.VertexPlainPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.vertexproperty.VertexPropertyDump;
import org.chronos.chronograph.internal.impl.structure.record.*;
import org.chronos.chronograph.internal.impl.structure.record2.EdgeRecord2;
import org.chronos.chronograph.internal.impl.structure.record2.VertexRecord2;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class GraphDumpFormat {
public static AbstractPropertyDump convertPropertyRecordToDumpFormat(final IPropertyRecord record) {
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
Object value = record.getSerializationSafeValue();
if (ChronoDBDumpUtil.isWellKnownObject(value)) {
// it's a well-known type -> use plain text format
return new PlainPropertyDump(record);
}
ChronoConverter<?, ?> converter = ChronoDBDumpUtil.getAnnotatedConverter(value);
if (converter == null) {
// no converter given -> use binary
return new BinaryPropertyDump(record);
} else {
// use the converter for a plain text format
return new PlainPropertyDump(record, converter);
}
}
public static VertexPropertyDump convertVertexPropertyRecordToDumpFormat(final IVertexPropertyRecord record) {
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
Object value = record.getSerializationSafeValue();
if (ChronoDBDumpUtil.isWellKnownObject(value)) {
// it's a well-known type -> use plain text format
return new VertexPlainPropertyDump(record);
}
ChronoConverter<?, ?> converter = ChronoDBDumpUtil.getAnnotatedConverter(value);
if (converter == null) {
// no converter given -> use binary
return new VertexBinaryPropertyDump(record);
} else {
// use the converter for a plain text format
return new VertexPlainPropertyDump(record, converter);
}
}
public static void registerGraphAliases(final DumpOptions options) {
checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!");
options.enable(DumpOption.aliasHint(EdgeDump.class, "cEdge"));
options.enable(DumpOption.aliasHint(VertexDump.class, "cVertex"));
options.enable(DumpOption.aliasHint(PlainPropertyDump.class, "cPropertyPlain"));
options.enable(DumpOption.aliasHint(BinaryPropertyDump.class, "cPropertyBinary"));
options.enable(DumpOption.aliasHint(VertexPlainPropertyDump.class, "cVertexPropertyPlain"));
options.enable(DumpOption.aliasHint(VertexBinaryPropertyDump.class, "cVertexPropertyBinary"));
options.enable(DumpOption.aliasHint(EdgeTargetDump.class, "cEdgeTarget"));
}
public static void registerDefaultConvertersForReading(final DumpOptions options) {
checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!");
options.enable(DumpOption.defaultConverter(VertexDump.class, new VertexRecordConverter()));
options.enable(DumpOption.defaultConverter(EdgeDump.class, new EdgeRecordConverter()));
}
public static void registerDefaultConvertersForWriting(final DumpOptions options) {
checkNotNull(options, "Precondition violation - argument 'options' must not be NULL!");
options.enable(DumpOption.defaultConverter(VertexRecord.class, new VertexRecordConverter()));
options.enable(DumpOption.defaultConverter(VertexRecord2.class, new VertexRecordConverter()));
options.enable(DumpOption.defaultConverter(EdgeRecord.class, new EdgeRecordConverter()));
options.enable(DumpOption.defaultConverter(EdgeRecord2.class, new EdgeRecordConverter()));
}
}
| 4,857 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/EdgeDump.java | package org.chronos.chronograph.internal.impl.dumpformat;
import static com.google.common.base.Preconditions.*;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import org.chronos.chronograph.api.structure.record.IEdgeRecord;
import org.chronos.chronograph.internal.impl.dumpformat.property.AbstractPropertyDump;
import org.chronos.chronograph.internal.impl.structure.record.EdgeRecord;
import org.chronos.chronograph.internal.impl.structure.record.PropertyRecord;
import com.google.common.collect.Sets;
import org.chronos.chronograph.internal.impl.structure.record2.EdgeRecord2;
import org.chronos.chronograph.internal.impl.structure.record2.PropertyRecord2;
public class EdgeDump {
/** The id of this record. */
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. */
private String inVertexId;
/** The ID of the "Out-Vertex", i.e. the source vertex. */
private String outVertexId;
/** The set of properties set on this edge. */
private Set<AbstractPropertyDump> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected EdgeDump() {
// serialization constructor
}
public EdgeDump(final IEdgeRecord record) {
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
this.recordId = record.getId();
this.label = record.getLabel();
this.inVertexId = record.getInVertexId();
this.outVertexId = record.getOutVertexId();
Set<AbstractPropertyDump> props = record.getProperties().stream()
.map(pr -> GraphDumpFormat.convertPropertyRecordToDumpFormat(pr)).collect(Collectors.toSet());
this.properties = Sets.newHashSet();
this.properties.addAll(props);
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
public String getRecordId() {
return this.recordId;
}
public String getInVertexId() {
return this.inVertexId;
}
public String getOutVertexId() {
return this.outVertexId;
}
public String getLabel() {
return this.label;
}
public Set<AbstractPropertyDump> getProperties() {
return Collections.unmodifiableSet(this.properties);
}
public EdgeRecord2 toRecord() {
Set<PropertyRecord2> props = Sets.newHashSet();
for (AbstractPropertyDump propertyDump : this.properties) {
props.add(new PropertyRecord2(propertyDump.getKey(), propertyDump.getValue()));
}
return new EdgeRecord2(this.recordId, this.outVertexId, this.label, this.inVertexId, props);
}
}
| 2,933 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeTargetDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/EdgeTargetDump.java | package org.chronos.chronograph.internal.impl.dumpformat;
import static com.google.common.base.Preconditions.*;
import org.chronos.chronograph.api.structure.record.IEdgeTargetRecord;
public class EdgeTargetDump {
/** The ID of the vertex at the "other end" of the edge. */
private String otherEndVertexId;
/** The ID of the edge itself. */
private String edgeId;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected EdgeTargetDump() {
// serialization constructor
}
public EdgeTargetDump(final IEdgeTargetRecord etr) {
checkNotNull(etr, "Precondition violation - argument 'etr' must not be NULL!");
this.edgeId = etr.getEdgeId();
this.otherEndVertexId = etr.getOtherEndVertexId();
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
public String getEdgeId() {
return this.edgeId;
}
public String getOtherEndVertexId() {
return this.otherEndVertexId;
}
}
| 1,317 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/VertexDump.java | package org.chronos.chronograph.internal.impl.dumpformat;
import static com.google.common.base.Preconditions.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
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.internal.impl.dumpformat.property.AbstractPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.vertexproperty.VertexPropertyDump;
import org.chronos.chronograph.internal.impl.structure.record.*;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
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.record2.VertexPropertyRecord2;
import org.chronos.chronograph.internal.impl.structure.record2.VertexRecord2;
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;
public class VertexDump {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
/** 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<EdgeTargetDump>> incomingEdges;
/** Mapping of edge labels to outgoing edges, i.e. edges which specify this vertex as their out-vertex. */
private Map<String, Set<EdgeTargetDump>> outgoingEdges;
/** The set of vertex properties known on this vertex. */
private Set<VertexPropertyDump> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected VertexDump() {
// serialization constructor
}
public VertexDump(final IVertexRecord record) {
checkNotNull(record, "Precondition violation - argument 'record' must not be NULL!");
// load the basic properties
this.recordId = record.getId();
this.label = record.getLabel();
// load incoming edges
this.incomingEdges = Maps.newHashMap();
for (Entry<String, Collection<IEdgeTargetRecord>> entry : record.getIncomingEdgesByLabel().asMap().entrySet()) {
String label = entry.getKey();
Collection<IEdgeTargetRecord> edgeTargets = entry.getValue();
Set<EdgeTargetDump> targetSet = edgeTargets.stream().map(etr -> new EdgeTargetDump(etr))
.collect(Collectors.toSet());
this.incomingEdges.put(label, targetSet);
}
// load outgoing edges
this.outgoingEdges = Maps.newHashMap();
for (Entry<String, Collection<IEdgeTargetRecord>> entry : record.getOutgoingEdgesByLabel().asMap().entrySet()) {
String label = entry.getKey();
Collection<IEdgeTargetRecord> edgeTargets = entry.getValue();
Set<EdgeTargetDump> targetSet = edgeTargets.stream().map(etr -> new EdgeTargetDump(etr))
.collect(Collectors.toSet());
this.outgoingEdges.put(label, targetSet);
}
// load the vertex properties
Set<VertexPropertyDump> props = record.getProperties().stream()
.map(vpr -> GraphDumpFormat.convertVertexPropertyRecordToDumpFormat(vpr)).collect(Collectors.toSet());
this.properties = Sets.newHashSet();
this.properties.addAll(props);
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
public Map<String, Set<EdgeTargetDump>> getIncomingEdges() {
return Collections.unmodifiableMap(this.incomingEdges);
}
public Map<String, Set<EdgeTargetDump>> getOutgoingEdges() {
return Collections.unmodifiableMap(this.outgoingEdges);
}
public String getLabel() {
return this.label;
}
public String getRecordId() {
return this.recordId;
}
public Set<VertexPropertyDump> getProperties() {
return Collections.unmodifiableSet(this.properties);
}
public VertexRecord3 toRecord() {
// convert incoming edges
SetMultimap<String, EdgeTargetRecord2> inE = HashMultimap.create();
for (Entry<String, Set<EdgeTargetDump>> entry : this.incomingEdges.entrySet()) {
String label = entry.getKey();
for (EdgeTargetDump edgeDump : entry.getValue()) {
EdgeTargetRecord2 edgeRecord = new EdgeTargetRecord2(edgeDump.getEdgeId(),
edgeDump.getOtherEndVertexId());
inE.put(label, edgeRecord);
}
}
// convert outgoing edges
SetMultimap<String, EdgeTargetRecord2> outE = HashMultimap.create();
for (Entry<String, Set<EdgeTargetDump>> entry : this.outgoingEdges.entrySet()) {
String label = entry.getKey();
for (EdgeTargetDump edgeDump : entry.getValue()) {
EdgeTargetRecord2 edgeRecord = new EdgeTargetRecord2(edgeDump.getEdgeId(),
edgeDump.getOtherEndVertexId());
outE.put(label, edgeRecord);
}
}
// convert properties
Set<IVertexPropertyRecord> props = Sets.newHashSet();
for (VertexPropertyDump property : this.properties) {
Map<String, AbstractPropertyDump> metaPropsDump = property.getProperties();
Map<String, PropertyRecord2> metaProps = Maps.newHashMap();
for (Entry<String, AbstractPropertyDump> entry : metaPropsDump.entrySet()) {
String key = entry.getKey();
AbstractPropertyDump propertyDump = entry.getValue();
PropertyRecord2 pRecord = new PropertyRecord2(key, propertyDump.getValue());
metaProps.put(key, pRecord);
}
if(metaProps.isEmpty()){
props.add(new SimpleVertexPropertyRecord(property.getKey(), property.getValue()));
}else{
props.add(new VertexPropertyRecord3(property.getKey(), property.getValue(), metaProps));
}
}
return new VertexRecord3(this.recordId, this.label, inE, outE, props);
}
}
| 6,593 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexPropertyDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/vertexproperty/VertexPropertyDump.java | package org.chronos.chronograph.internal.impl.dumpformat.vertexproperty;
import java.util.Map;
import org.chronos.chronograph.internal.impl.dumpformat.property.AbstractPropertyDump;
public interface VertexPropertyDump {
public String getKey();
public Object getValue();
public Map<String, AbstractPropertyDump> getProperties();
}
| 340 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexBinaryPropertyDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/vertexproperty/VertexBinaryPropertyDump.java | package org.chronos.chronograph.internal.impl.dumpformat.vertexproperty;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import org.chronos.chronograph.internal.impl.dumpformat.GraphDumpFormat;
import org.chronos.chronograph.internal.impl.dumpformat.property.AbstractPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.property.BinaryPropertyDump;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexPropertyRecord;
import com.google.common.collect.Maps;
public class VertexBinaryPropertyDump extends BinaryPropertyDump implements VertexPropertyDump {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
/**
* Used to hold the vertex property ID.
*
* <p>
* This field isn't used anymore and remains for backwards compatibility reasons.
* </p>
*/
@Deprecated
@SuppressWarnings("unused")
private String recordId;
private Map<String, AbstractPropertyDump> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected VertexBinaryPropertyDump() {
// serialization constructor
}
public VertexBinaryPropertyDump(final IVertexPropertyRecord vpr) {
super(vpr);
this.properties = Maps.newHashMap();
for (Entry<String, IPropertyRecord> entry : vpr.getProperties().entrySet()) {
String key = entry.getKey();
IPropertyRecord pRecord = entry.getValue();
AbstractPropertyDump pDump = GraphDumpFormat.convertPropertyRecordToDumpFormat(pRecord);
this.properties.put(key, pDump);
}
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public Map<String, AbstractPropertyDump> getProperties() {
return Collections.unmodifiableMap(this.properties);
}
}
| 2,363 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexPlainPropertyDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/vertexproperty/VertexPlainPropertyDump.java | package org.chronos.chronograph.internal.impl.dumpformat.vertexproperty;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import org.chronos.chronodb.api.dump.ChronoConverter;
import org.chronos.chronograph.internal.impl.dumpformat.GraphDumpFormat;
import org.chronos.chronograph.internal.impl.dumpformat.property.AbstractPropertyDump;
import org.chronos.chronograph.internal.impl.dumpformat.property.PlainPropertyDump;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.chronograph.api.structure.record.IVertexPropertyRecord;
import com.google.common.collect.Maps;
public class VertexPlainPropertyDump extends PlainPropertyDump implements VertexPropertyDump {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
/**
* Used to hold the vertex property ID.
*
* <p>
* This field isn't used anymore and remains for backwards compatibility reasons.
* </p>
*/
@Deprecated
@SuppressWarnings("unused")
private String recordId;
private Map<String, AbstractPropertyDump> properties;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected VertexPlainPropertyDump() {
// serialization constructor
}
public VertexPlainPropertyDump(final IVertexPropertyRecord vpr) {
this(vpr, null);
}
public VertexPlainPropertyDump(final IVertexPropertyRecord vpr, final ChronoConverter<?, ?> converter) {
super(vpr, converter);
this.properties = Maps.newHashMap();
for (Entry<String, IPropertyRecord> entry : vpr.getProperties().entrySet()) {
String key = entry.getKey();
IPropertyRecord pRecord = entry.getValue();
AbstractPropertyDump pDump = GraphDumpFormat.convertPropertyRecordToDumpFormat(pRecord);
this.properties.put(key, pDump);
}
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public Map<String, AbstractPropertyDump> getProperties() {
return Collections.unmodifiableMap(this.properties);
}
}
| 2,551 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractPropertyDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/property/AbstractPropertyDump.java | package org.chronos.chronograph.internal.impl.dumpformat.property;
import static com.google.common.base.Preconditions.*;
public abstract class AbstractPropertyDump {
private String key;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected AbstractPropertyDump() {
// serialization constructor
}
protected AbstractPropertyDump(final String key) {
checkNotNull(key, "Precondition violation - argument 'key' must not be NULL!");
this.key = key;
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
public String getKey() {
return this.key;
}
public abstract Object getValue();
}
| 1,028 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PlainPropertyDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/property/PlainPropertyDump.java | package org.chronos.chronograph.internal.impl.dumpformat.property;
import org.chronos.chronodb.api.dump.ChronoConverter;
import org.chronos.chronodb.api.exceptions.ChronoDBStorageBackendException;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.util.ReflectionUtils;
public class PlainPropertyDump extends AbstractPropertyDump {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private Object value;
private String converterClass;
// =====================================================================================================================
// CONSTRUCTORS
// =====================================================================================================================
protected PlainPropertyDump() {
// serialization constructor
}
public PlainPropertyDump(final IPropertyRecord record) {
this(record, null);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public PlainPropertyDump(final IPropertyRecord record, final ChronoConverter valueConverter) {
super(record.getKey());
if (valueConverter != null) {
this.converterClass = valueConverter.getClass().getName();
this.value = valueConverter.writeToOutput(record.getSerializationSafeValue());
} else {
this.converterClass = null;
this.value = record.getSerializationSafeValue();
}
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object getValue() {
if (this.value == null) {
return null;
}
if (this.converterClass == null) {
// no converter given -> return the object directly
return this.value;
} else {
// instantiate the converter and run it
ChronoConverter converter = null;
try {
Class<?> converterClass = Class.forName(this.converterClass);
converter = (ChronoConverter<?, ?>) ReflectionUtils.instantiate(converterClass);
} catch (Exception e) {
throw new ChronoDBStorageBackendException("Failed to instantiate value converter class '"
+ this.converterClass + "', cannot deserialize value!", e);
}
try {
return converter.readFromInput(this.value);
} catch (Exception e) {
throw new ChronoDBStorageBackendException("Failed to run converter of type '"
+ converter.getClass().getName() + "' on value of type '" + this.value.getClass() + "'!", e);
}
}
}
}
| 2,787 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
BinaryPropertyDump.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/property/BinaryPropertyDump.java | package org.chronos.chronograph.internal.impl.dumpformat.property;
import org.chronos.chronograph.api.structure.record.IPropertyRecord;
import org.chronos.common.serialization.KryoManager;
public class BinaryPropertyDump extends AbstractPropertyDump {
// =====================================================================================================================
// FIELDS
// =====================================================================================================================
private byte[] value;
// =====================================================================================================================
// CONSTRUCTOR
// =====================================================================================================================
protected BinaryPropertyDump() {
// serialization constructor
}
public BinaryPropertyDump(final IPropertyRecord record) {
super(record.getKey());
this.value = KryoManager.serialize(record.getSerializationSafeValue());
}
// =====================================================================================================================
// PUBLIC API
// =====================================================================================================================
@Override
public Object getValue() {
if (this.value == null) {
return null;
}
return KryoManager.deserialize(this.value);
}
}
| 1,427 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
EdgeRecordConverter.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/converter/EdgeRecordConverter.java | package org.chronos.chronograph.internal.impl.dumpformat.converter;
import org.chronos.chronodb.api.dump.ChronoConverter;
import org.chronos.chronograph.api.structure.record.IEdgeRecord;
import org.chronos.chronograph.internal.impl.dumpformat.EdgeDump;
public class EdgeRecordConverter implements ChronoConverter<IEdgeRecord, EdgeDump> {
@Override
public EdgeDump writeToOutput(final IEdgeRecord record) {
if (record == null) {
return null;
}
return new EdgeDump(record);
}
@Override
public IEdgeRecord readFromInput(final EdgeDump dump) {
if (dump == null) {
return null;
}
return dump.toRecord();
}
}
| 632 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
VertexRecordConverter.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/dumpformat/converter/VertexRecordConverter.java | package org.chronos.chronograph.internal.impl.dumpformat.converter;
import org.chronos.chronodb.api.dump.ChronoConverter;
import org.chronos.chronograph.api.structure.record.IVertexRecord;
import org.chronos.chronograph.internal.impl.dumpformat.VertexDump;
public class VertexRecordConverter implements ChronoConverter<IVertexRecord, VertexDump> {
@Override
public VertexDump writeToOutput(final IVertexRecord record) {
if (record == null) {
return null;
}
return new VertexDump(record);
}
@Override
public IVertexRecord readFromInput(final VertexDump dump) {
if (dump == null) {
return null;
}
return dump.toRecord();
}
}
| 652 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractChronoGraphBuilder.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/builder/graph/AbstractChronoGraphBuilder.java | package org.chronos.chronograph.internal.impl.builder.graph;
import org.chronos.common.builder.AbstractChronoBuilder;
import org.chronos.common.builder.ChronoBuilder;
public abstract class AbstractChronoGraphBuilder<SELF extends ChronoBuilder<?>> extends AbstractChronoBuilder<SELF>
implements ChronoBuilder<SELF> {
} | 322 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphDefaultProperties.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/builder/graph/ChronoGraphDefaultProperties.java | package org.chronos.chronograph.internal.impl.builder.graph;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.common.builder.ChronoBuilder;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphDefaultProperties {
public static void applyTo(ChronoBuilder<?> builder){
checkNotNull(builder, "Precondition violation - argument 'builder' must not be NULL!");
// in ChronoGraph, we can ALWAYS ensure immutability of ChronoDB cache values. The reason for this is
// that ChronoGraph only passes records (e.g. VertexRecord) to the underlying ChronoDB, and records
// are always immutable.
builder.withProperty(ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, "true");
}
}
| 784 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
AbstractChronoGraphFinalizableBuilder.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/builder/graph/AbstractChronoGraphFinalizableBuilder.java | package org.chronos.chronograph.internal.impl.builder.graph;
import org.apache.commons.configuration2.Configuration;
import org.chronos.chronodb.api.ChronoDB;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronograph.api.builder.graph.ChronoGraphFinalizableBuilder;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronograph.internal.impl.structure.graph.StandardChronoGraph;
public abstract class AbstractChronoGraphFinalizableBuilder
extends AbstractChronoGraphBuilder<ChronoGraphFinalizableBuilder> implements ChronoGraphFinalizableBuilder {
protected AbstractChronoGraphFinalizableBuilder() {
// default properties for the graph
this.withProperty(ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, "true");
this.withProperty(ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, "false");
}
@Override
public ChronoGraphFinalizableBuilder withIdExistenceCheckOnAdd(final boolean enableIdExistenceCheckOnAdd) {
return this.withProperty(ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD,
String.valueOf(enableIdExistenceCheckOnAdd));
}
@Override
public ChronoGraphFinalizableBuilder withTransactionAutoStart(final boolean enableAutoStartTransactions) {
return this.withProperty(ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN,
String.valueOf(enableAutoStartTransactions));
}
@Override
public ChronoGraphFinalizableBuilder withStaticGroovyCompilationCache(final boolean enableStaticGroovyCompilationCache) {
return this.withProperty(ChronoGraphConfiguration.USE_STATIC_GROOVY_COMPILATION_CACHE, String.valueOf(enableStaticGroovyCompilationCache));
}
@Override
public ChronoGraphFinalizableBuilder withUsingSecondaryIndicesForGremlinValuesStep(final boolean useSecondaryIndexForGremlinValuesStep) {
return this.withProperty(ChronoGraphConfiguration.USE_SECONDARY_INDEX_FOR_VALUES_STEP, String.valueOf(useSecondaryIndexForGremlinValuesStep));
}
@Override
public ChronoGraphFinalizableBuilder withUsingSecondaryIndicesForGremlinValueMapStep(final boolean useSecondaryIndexForGremlinValueMapStep) {
return this.withProperty(ChronoGraphConfiguration.USE_SECONDARY_INDEX_FOR_VALUE_MAP_STEP, String.valueOf(useSecondaryIndexForGremlinValueMapStep));
}
@Override
public ChronoGraph build() {
Configuration config = this.getPropertiesAsConfiguration();
// in ChronoGraph, we can ALWAYS ensure immutability of ChronoDB cache values. The reason for this is
// that ChronoGraph only passes records (e.g. VertexRecord) to the underlying ChronoDB, and records
// are always immutable.
config.setProperty(ChronoDBConfiguration.ASSUME_CACHE_VALUES_ARE_IMMUTABLE, "true");
// ChronoGraph performs its own change tracking, so we never have duplicate versions
config.setProperty(ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, "disabled");
ChronoDB db = ChronoDB.FACTORY.create().fromConfiguration(config).build();
return new StandardChronoGraph(db, config);
}
}
| 3,280 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphPropertyFileBuilderImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/builder/graph/ChronoGraphPropertyFileBuilderImpl.java | package org.chronos.chronograph.internal.impl.builder.graph;
import static com.google.common.base.Preconditions.*;
import java.io.File;
import java.io.FileReader;
import java.util.Set;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.chronos.chronograph.api.exceptions.ChronoGraphConfigurationException;
import com.google.common.collect.Sets;
public class ChronoGraphPropertyFileBuilderImpl extends AbstractChronoGraphFinalizableBuilder {
public ChronoGraphPropertyFileBuilderImpl(final File propertiesFile) {
checkNotNull(propertiesFile, "Precondition violation - argument 'propertiesFile' must not be NULL!");
checkArgument(propertiesFile.exists(),
"Precondition violation - argument 'propertiesFile' must refer to an existing file!");
checkArgument(propertiesFile.isFile(),
"Precondition violation - argument 'propertiesFile' must refer to a file (not a directory)!");
try {
PropertiesConfiguration configuration = new PropertiesConfiguration();
try(FileReader reader = new FileReader(propertiesFile)){
configuration.read(reader);
}
this.applyConfiguration(configuration);
} catch (Exception e) {
throw new ChronoGraphConfigurationException(
"Failed to read properties file '" + propertiesFile.getAbsolutePath() + "'!", e);
}
ChronoGraphDefaultProperties.applyTo(this);
}
public ChronoGraphPropertyFileBuilderImpl(final Configuration configuration) {
checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!");
try {
this.applyConfiguration(configuration);
} catch (Exception e) {
throw new ChronoGraphConfigurationException("Failed to apply the given configuration'!", e);
}
}
private void applyConfiguration(final Configuration configuration) {
Set<String> keys = Sets.newHashSet(configuration.getKeys());
for (String key : keys) {
this.withProperty(key, configuration.getProperty(key).toString());
}
}
}
| 2,086 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphBaseBuilderImpl.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/builder/graph/ChronoGraphBaseBuilderImpl.java | package org.chronos.chronograph.internal.impl.builder.graph;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.MapConfiguration;
import org.chronos.chronodb.api.ChronoDB;
import org.chronos.chronodb.api.builder.database.ChronoDBBackendBuilder;
import org.chronos.chronodb.api.builder.database.ChronoDBFinalizableBuilder;
import org.chronos.chronodb.api.builder.database.spi.ChronoDBBackendProvider;
import org.chronos.chronodb.inmemory.InMemoryChronoDB;
import org.chronos.chronodb.inmemory.builder.ChronoDBInMemoryBuilder;
import org.chronos.chronodb.internal.impl.base.builder.database.service.ChronoDBBackendProviderService;
import org.chronos.chronograph.api.builder.graph.ChronoGraphBaseBuilder;
import org.chronos.chronograph.api.builder.graph.ChronoGraphFinalizableBuilder;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Properties;
import java.util.function.Function;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphBaseBuilderImpl extends AbstractChronoGraphBuilder<ChronoGraphBaseBuilderImpl> implements ChronoGraphBaseBuilder {
@Override
public ChronoGraphFinalizableBuilder graphOnChronoDB(final ChronoDBFinalizableBuilder<?> builder) {
checkNotNull(builder, "Precondition violation - argument 'builder' must not be NULL!");
return new ChronoGraphOnChronoDBBuilder(builder);
}
@Override
public ChronoGraphFinalizableBuilder fromPropertiesFile(final File file) {
checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!");
checkArgument(file.exists(), "Precondition violation - argument 'file' must refer to an existing file!");
checkArgument(file.isFile(), "Precondition violation - argument 'file' must refer to a file (not a directory)!");
return new ChronoGraphPropertyFileBuilderImpl(file);
}
@Override
public ChronoGraphFinalizableBuilder fromConfiguration(final Configuration configuration) {
checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!");
return new ChronoGraphPropertyFileBuilderImpl(configuration);
}
@Override
public ChronoGraphFinalizableBuilder fromProperties(final Properties properties) {
checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!");
Configuration configuration = new MapConfiguration(properties);
return this.fromConfiguration(configuration);
}
@Override
public ChronoGraphFinalizableBuilder inMemoryGraph() {
return this.graphOnChronoDB(ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER));
}
@Override
public ChronoGraphFinalizableBuilder inMemoryGraph(final Function<ChronoDBInMemoryBuilder, ChronoDBFinalizableBuilder<ChronoDBInMemoryBuilder>> configureStore) {
checkNotNull(configureStore, "Precondition violation - argument 'configureStore' must not be NULL!");
ChronoDBInMemoryBuilder dbBuilder = ChronoDB.FACTORY.create().database(InMemoryChronoDB.BUILDER);
ChronoDBFinalizableBuilder<ChronoDBInMemoryBuilder> configuredBuilder = configureStore.apply(dbBuilder);
return this.graphOnChronoDB(configuredBuilder);
}
@Override
public ChronoGraphFinalizableBuilder exodusGraph(final String directoryPath) {
checkNotNull(directoryPath, "Precondition violation - argument 'directoryPath' must not be NULL!");
return this.exodusGraph(new File(directoryPath));
}
@Override
public ChronoGraphFinalizableBuilder exodusGraph(final File directory) {
checkArgument(directory.exists(), "Precondition violation - the given directory does not exist: " + directory.getAbsolutePath());
checkArgument(directory.isDirectory(), "Precondition violation - the given location is not a directory: " + directory.getAbsolutePath());
return this.exodusGraph(directory, Function.identity());
}
@Override
public ChronoGraphFinalizableBuilder exodusGraph(final String directoryPath, final Function<ChronoDBFinalizableBuilder<?>, ChronoDBFinalizableBuilder<?>> configureStore) {
checkNotNull(directoryPath, "Precondition violation - argument 'directoryPath' must not be NULL!");
return this.exodusGraph(new File(directoryPath), configureStore);
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public ChronoGraphFinalizableBuilder exodusGraph(final File directory, final Function<ChronoDBFinalizableBuilder<?>, ChronoDBFinalizableBuilder<?>> configureStore) {
checkArgument(directory.exists(), "Precondition violation - the given directory does not exist: " + directory.getAbsolutePath());
checkArgument(directory.isDirectory(), "Precondition violation - the given location is not a directory: " + directory.getAbsolutePath());
checkNotNull(configureStore, "Precondition violation - argument 'configureStore' must not be NULL!");
// try to access the ChronoDB builder for Exodus. If that fails, it means that it's not on the classpath.
ChronoDBBackendProvider exodusProvider = ChronoDBBackendProviderService.getInstance().getBackendProvider("exodus");
if (exodusProvider == null) {
throw new IllegalStateException("Failed to locate Exodus ChronoDB on classpath. This usually indicates that the" +
" ChronoDB Exodus dependency is either missing on your classpath, or is outdated. Please check your classpath setup.");
}
try {
ChronoDBBackendBuilder builderInstance = exodusProvider.createBuilder();
Method onFileMethod = builderInstance.getClass().getDeclaredMethod("onFile", File.class);
onFileMethod.setAccessible(true);
ChronoDBFinalizableBuilder<?> finalizableBuilder = (ChronoDBFinalizableBuilder) onFileMethod.invoke(builderInstance, directory);
ChronoDBFinalizableBuilder<?> configuredBuilder = configureStore.apply(finalizableBuilder);
return this.graphOnChronoDB(configuredBuilder);
} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassCastException e) {
throw new IllegalStateException("Failed to create Exodus ChronoDB Builder. This usually indicates that the" +
" ChronoDB Exodus dependency is either missing on your classpath, or is outdated. Please check your classpath setup. The cause is: " + e, e);
}
}
@Override
public <T extends ChronoDBBackendBuilder> ChronoGraphFinalizableBuilder customGraph(final Class<T> builderClass, final Function<T, ChronoDBFinalizableBuilder<?>> configureStore) {
checkNotNull(builderClass, "Precondition violation - argument 'builderClass' must not be NULL!");
checkNotNull(configureStore, "Precondition violation - argument 'configureStore' must not be NULL!");
try {
Constructor<T> constructor = builderClass.getConstructor();
T builder = constructor.newInstance();
ChronoDBFinalizableBuilder<?> finalizableBuilder = configureStore.apply(builder);
return this.graphOnChronoDB(finalizableBuilder);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassCastException e) {
throw new IllegalStateException("Failed to create custom ChronoDB Builder of type '" + builderClass.getName() + "'. This usually indicates that the" +
" custom builder does not have a default (no-argument) constructor, or is outdated. Please check your classpath setup. The cause is: " + e, e);
}
}
@Override
public ChronoGraphFinalizableBuilder fromPropertiesFile(final String filePath) {
checkNotNull(filePath, "Precondition violation - argument 'filePath' must not be NULL!");
File file = new File(filePath);
return this.fromPropertiesFile(file);
}
@Override
public Map<String, String> getProperties() {
return null;
}
}
| 8,216 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphOnChronoDBBuilder.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/builder/graph/ChronoGraphOnChronoDBBuilder.java | package org.chronos.chronograph.internal.impl.builder.graph;
import org.chronos.chronodb.api.builder.database.ChronoDBFinalizableBuilder;
import java.util.Map;
import java.util.Map.Entry;
import static com.google.common.base.Preconditions.*;
public class ChronoGraphOnChronoDBBuilder extends AbstractChronoGraphFinalizableBuilder {
public ChronoGraphOnChronoDBBuilder(ChronoDBFinalizableBuilder<?> chronoDBBuilder) {
checkNotNull(chronoDBBuilder, "Precondition violation - argument 'chronoDBBuilder' must not be NULL!");
Map<String, String> properties = chronoDBBuilder.getProperties();
for(Entry<String, String> entry : properties.entrySet()){
this.withProperty(entry.getKey(), entry.getValue());
}
ChronoGraphDefaultProperties.applyTo(this);
}
}
| 808 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphElementUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/ChronoGraphElementUtil.java | package org.chronos.chronograph.internal.impl.util;
import static com.google.common.base.Preconditions.*;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.chronos.chronograph.api.structure.ChronoElement;
import org.chronos.chronograph.api.structure.ChronoVertex;
public class ChronoGraphElementUtil {
private static final String LABEL = Graph.Hidden.hide("label");
private static final String ID = Graph.Hidden.hide("id");
private static final String KEY = Graph.Hidden.hide("key");
private static final String VALUE = Graph.Hidden.hide("value");
public static boolean isHiddenPropertyKey(final String propertyKey) {
checkNotNull(propertyKey, "Precondition violation - argument 'propertyKey' must not be NULL!");
return Graph.Hidden.isHidden(propertyKey);
}
public static boolean isLabelProperty(final String propertyKey) {
checkNotNull(propertyKey, "Precondition violation - argument 'propertyKey' must not be NULL!");
return LABEL.equals(propertyKey);
}
public static boolean isIdProperty(final String propertyKey) {
checkNotNull(propertyKey, "Precondition violation - argument 'propertyKey' must not be NULL!");
return ID.equals(propertyKey);
}
public static boolean isKeyProperty(final String propertyKey) {
checkNotNull(propertyKey, "Precondition violation - argument 'propertyKey' must not be NULL!");
return KEY.equals(propertyKey);
}
public static boolean isValueProperty(final String propertyKey) {
checkNotNull(propertyKey, "Precondition violation - argument 'propertyKey' must not be NULL!");
return VALUE.equals(propertyKey);
}
public static T asSpecialProperty(final String propertyKey) {
if (isHiddenPropertyKey(propertyKey) == false) {
return null;
}
if (isLabelProperty(propertyKey)) {
return T.label;
} else if (isIdProperty(propertyKey)) {
return T.id;
} else if (isKeyProperty(propertyKey)) {
return T.key;
} else if (isValueProperty(propertyKey)) {
return T.value;
} else {
return null;
}
}
public static <E> PredefinedProperty<E> asPredefinedProperty(final ChronoElement element, final String propertyKey) {
T specialProperty = asSpecialProperty(propertyKey);
if (specialProperty == null) {
return null;
}
if (PredefinedProperty.existsOn(element, specialProperty) == false) {
return null;
}
return PredefinedProperty.of(element, specialProperty);
}
public static <E> PredefinedVertexProperty<E> asPredefinedVertexProperty(final ChronoVertex vertex, final String propertyKey) {
T specialProperty = asSpecialProperty(propertyKey);
if (specialProperty == null) {
return null;
}
if (PredefinedVertexProperty.existsOn(vertex, specialProperty) == false) {
return null;
}
return PredefinedVertexProperty.of(vertex, specialProperty);
}
}
| 2,838 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoId.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/ChronoId.java | package org.chronos.chronograph.internal.impl.util;
import java.util.UUID;
public class ChronoId {
public static String random() {
return UUID.randomUUID().toString();
}
}
| 180 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphLoggingUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/ChronoGraphLoggingUtil.java | package org.chronos.chronograph.internal.impl.util;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
public class ChronoGraphLoggingUtil {
public static String createLogHeader(ChronoGraphTransaction tx) {
return "[GRAPH MODIFICATION] :: Coords [" + tx.getBranchName() + "@" + tx.getTimestamp() + "] TxID " + tx.getTransactionId() + " Time " + System.currentTimeMillis() + " :: ";
}
}
| 426 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PredefinedProperty.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/PredefinedProperty.java | package org.chronos.chronograph.internal.impl.util;
import static com.google.common.base.Preconditions.*;
import java.util.NoSuchElementException;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Property;
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.ChronoElement;
import org.chronos.common.exceptions.UnknownEnumLiteralException;
public class PredefinedProperty<E> implements Property<E> {
// =================================================================================================================
// STATIC FACTORY
// =================================================================================================================
public static <E> PredefinedProperty<E> of(final ChronoElement element, final T property) {
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
checkNotNull(element, "Precondition violation - argument 'element' must not be NULL!");
return new PredefinedProperty<>(element, property);
}
public static boolean existsOn(final ChronoElement element, final T property) {
checkNotNull(element, "Precondition violation - argument 'element' must not be NULL!");
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
switch (property) {
case id:
return true;
case label:
return element instanceof Vertex || element instanceof Edge;
case key:
return element instanceof VertexProperty;
case value:
return element instanceof VertexProperty;
default:
throw new UnknownEnumLiteralException(property);
}
}
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final ChronoElement owner;
private final T property;
// =================================================================================================================
// CONSTRUCTOR
// =================================================================================================================
protected PredefinedProperty(final ChronoElement element, final T property) {
this.owner = element;
this.property = property;
}
@Override
public String key() {
return this.property.getAccessor();
}
@Override
@SuppressWarnings("unchecked")
public E value() throws NoSuchElementException {
return (E) this.property.apply(this.owner);
}
@Override
public boolean isPresent() {
return existsOn(this.owner, this.property);
}
@Override
public Element element() {
return this.owner;
}
@Override
public void remove() {
throw new IllegalStateException("Cannot remove the predefined property [" + this.property + "]!");
}
}
| 3,048 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
PredefinedVertexProperty.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/PredefinedVertexProperty.java | package org.chronos.chronograph.internal.impl.util;
import static com.google.common.base.Preconditions.*;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.tinkerpop.gremlin.structure.Property;
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.common.exceptions.UnknownEnumLiteralException;
public class PredefinedVertexProperty<E> implements VertexProperty<E> {
// =================================================================================================================
// STATIC FACTORY METHODS
// =================================================================================================================
public static <E> PredefinedVertexProperty<E> of(final ChronoVertex vertex, final T property) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
return new PredefinedVertexProperty<>(vertex, property);
}
public static boolean existsOn(final ChronoVertex vertex, final T property) {
checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!");
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
switch (property) {
case id:
return true;
case label:
return true;
case key:
return false;
case value:
return false;
default:
throw new UnknownEnumLiteralException(property);
}
}
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final ChronoVertex vertex;
private final T property;
// =================================================================================================================
// CONSTRUCTOR
// =================================================================================================================
protected PredefinedVertexProperty(final ChronoVertex vertex, final T property) {
this.vertex = vertex;
this.property = property;
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public String key() {
return this.property.getAccessor();
}
@Override
@SuppressWarnings("unchecked")
public E value() throws NoSuchElementException {
return (E) this.property.apply(this.vertex);
}
@Override
public boolean isPresent() {
return existsOn(this.vertex, this.property);
}
@Override
public void remove() {
throw new IllegalStateException("Cannot remove predefined Vertex Property '" + this.property.getAccessor() + "'!");
}
@Override
public Object id() {
return null;
}
@Override
public String label() {
return null;
}
@Override
public ChronoGraph graph() {
return this.vertex.graph();
}
@Override
public <V> Property<V> property(final String key, final V value) {
throw new IllegalStateException("Predefined Property '" + this.property.getAccessor() + "' cannot have properties of its own!");
}
@Override
public Vertex element() {
return this.vertex;
}
@Override
public <U> Iterator<Property<U>> properties(final String... propertyKeys) {
return Collections.emptyIterator();
}
}
| 3,775 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphTraversalUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/ChronoGraphTraversalUtil.java | package org.chronos.chronograph.internal.impl.util;
import static com.google.common.base.Preconditions.*;
import java.util.*;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.google.common.collect.*;
import org.apache.tinkerpop.gremlin.process.traversal.*;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal.Admin;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.process.traversal.step.HasContainerHolder;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.*;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.ConnectiveStep.Connective;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.process.traversal.util.AndP;
import org.apache.tinkerpop.gremlin.process.traversal.util.ConnectiveP;
import org.apache.tinkerpop.gremlin.process.traversal.util.OrP;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.chronos.chronodb.api.builder.query.FinalizableQueryBuilder;
import org.chronos.chronodb.api.builder.query.QueryBaseBuilder;
import org.chronos.chronodb.api.builder.query.QueryBuilder;
import org.chronos.chronodb.api.builder.query.WhereBuilder;
import org.chronos.chronodb.internal.impl.query.TextMatchMode;
import org.chronos.chronograph.api.builder.query.*;
import org.chronos.chronograph.api.index.ChronoGraphIndex;
import org.chronos.chronograph.api.structure.ChronoGraph;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.ChronoGraphConstants;
import org.chronos.chronograph.internal.impl.index.IndexType;
import org.chronos.chronograph.internal.impl.query.ChronoCompare;
import org.chronos.chronograph.internal.impl.query.ChronoStringCompare;
import org.chronos.common.exceptions.UnknownEnumLiteralException;
import org.chronos.common.util.ReflectionUtils;
public class ChronoGraphTraversalUtil {
/**
* Returns the {@link ChronoGraph} on which the given {@link Traversal} is executed.
*
* <p>
* This method assumes that the traversal is indeed executed on a ChronoGraph. If that is not the case, an
* {@link IllegalArgumentException} is thrown.
*
* @param traversal The traversal to get the underlying ChronoGraph for. Must not be <code>null</code>.
* @return The ChronoGraph on which the given traversal is executed. Never <code>null</code>.
*/
public static ChronoGraph getChronoGraph(final Traversal<?, ?> traversal) {
checkNotNull(traversal, "Precondition violation - argument 'traversal' must not be NULL!");
Optional<Graph> optGraph = TraversalHelper.getRootTraversal(traversal.asAdmin()).getGraph();
if (optGraph.isPresent() == false) {
throw new IllegalArgumentException("Traversal is not bound to a graph: " + traversal);
}
Graph graph = optGraph.get();
if (graph instanceof ChronoGraph == false) {
throw new IllegalArgumentException(
"Traversal is not bound to a ChronoGraph, but a '" + graph.getClass().getName() + "'!");
}
return (ChronoGraph) graph;
}
/**
* Returns the {@link ChronoGraphTransaction} on which the given {@link Traversal} is executed.
*
* <p>
* This method assumes that the traversal is indeed executed on a ChronoGraph. If that is not the case, an
* {@link IllegalArgumentException} is thrown.
*
* @param traversal The traversal to get the underlying transaction for. Must not be <code>null</code>.
* @return The underlying chrono graph transaction. Never <code>null</code>.
*/
public static ChronoGraphTransaction getTransaction(final Traversal<?, ?> traversal) {
checkNotNull(traversal, "Precondition violation - argument 'traversal' must not be NULL!");
ChronoGraph g = getChronoGraph(traversal);
return g.tx().getCurrentTransaction();
}
public static boolean isCoveredByIndices(Step<?, ?> step, Set<ChronoGraphIndex> indices) {
checkNotNull(step, "Precondition violation - argument 'step' must not be NULL!");
checkNotNull(indices, "Precondition violation - argument 'indices' must not be NULL!");
if (!isChronoGraphIndexable(step, false)) {
// this step contains non-indexable constructs, so it doesn't matter what indices we have available.
return false;
}
ListMultimap<String, ChronoGraphIndex> indicesByProperty = Multimaps.index(indices, ChronoGraphIndex::getIndexedProperty);
if (step instanceof HasContainerHolder) {
List<HasContainer> hasContainers = ((HasContainerHolder) step).getHasContainers();
return hasContainers.stream().allMatch(has -> {
// try to find an index on the given property
List<ChronoGraphIndex> chronoGraphIndices = indicesByProperty.get(has.getKey());
if (indices.isEmpty()) {
return false;
}
// check the predicate
BiPredicate<?, ?> biPredicate = has.getBiPredicate();
if (biPredicate == Compare.eq
|| biPredicate == ChronoCompare.EQ
|| biPredicate == Compare.neq
|| biPredicate == ChronoCompare.NEQ
|| biPredicate instanceof Contains
|| biPredicate == ChronoCompare.WITHIN
|| biPredicate == ChronoCompare.WITHOUT
) {
// all indices support (in)equality, within and without, just assert that we have an index at all
return !chronoGraphIndices.isEmpty();
} else if (biPredicate == Compare.gt
|| biPredicate == ChronoCompare.GT
|| biPredicate == Compare.gte
|| biPredicate == ChronoCompare.GTE
|| biPredicate == Compare.lt
|| biPredicate == ChronoCompare.LT
|| biPredicate == Compare.lte
|| biPredicate == ChronoCompare.LTE
) {
// only numeric indices support those comparison operators
return hasIndexerOfType(chronoGraphIndices, IndexType.LONG, IndexType.DOUBLE);
} else if (biPredicate instanceof DoubleEqualsCP
|| biPredicate instanceof DoubleNotEqualsCP
|| biPredicate instanceof DoubleWithinCP
|| biPredicate instanceof DoubleWithoutCP
) {
return hasIndexerOfType(chronoGraphIndices, IndexType.DOUBLE);
} else if (biPredicate instanceof StringWithinCP || biPredicate instanceof StringWithoutCP) {
return hasIndexerOfType(chronoGraphIndices, IndexType.STRING);
} else if (biPredicate instanceof LongWithinCP || biPredicate instanceof LongWithoutCP) {
return hasIndexerOfType(chronoGraphIndices, IndexType.LONG);
} else if (biPredicate instanceof ChronoStringCompare) {
// only text indices support those comparison operators
return hasIndexerOfType(chronoGraphIndices, IndexType.STRING);
} else {
// unknown predicate...?
return false;
}
});
} else if (step instanceof ConnectiveStep) {
// this case unifies "and" & "or" steps in gremlin (common superclass)
ConnectiveStep<?> connectiveStep = (ConnectiveStep<?>) step;
List<? extends Admin<?, ?>> localChildren = connectiveStep.getLocalChildren();
for (Admin<?, ?> childTraversal : localChildren) {
for (Step<?, ?> childStep : childTraversal.getSteps()) {
if (!isCoveredByIndices(childStep, indices)) {
return false;
}
}
}
return true;
} else if (step instanceof NotStep) {
NotStep<?> notStep = (NotStep<?>) step;
List<? extends Admin<?, ?>> localChildren = notStep.getLocalChildren();
for (Admin<?, ?> childTraversal : localChildren) {
for (Step<?, ?> childStep : childTraversal.getSteps()) {
if (!isCoveredByIndices(childStep, indices)) {
return false;
}
}
}
return true;
} else {
// unknown step?
return false;
}
}
private static boolean hasIndexerOfType(Collection<ChronoGraphIndex> indices, IndexType... indexTypes) {
checkNotNull(indices, "Precondition violation - argument 'indices' must not be NULL!");
checkNotNull(indexTypes, "Precondition violation - argument 'indexTypes' must not be NULL!");
for (ChronoGraphIndex index : indices) {
for (IndexType indexType : indexTypes) {
if (index.getIndexType().equals(indexType)) {
return true;
}
}
}
return false;
}
/**
* Checks if the given step can be answered by ChronoGraph indices.
*
* @param step The step to check. Will return <code>false</code> if <code>null</code> is used.
* @param allowAnyPredicate Whether any predicate (<code>true</code>) is allowed or only predicates supported by ChronoGraph are allowed (<code>false</code>)
* @return <code>true</code> if the given step can be answered by ChronoGraph indices, or <code>false</code> if not.
*/
public static boolean isChronoGraphIndexable(Step<?, ?> step, boolean allowAnyPredicate) {
if (step == null) {
return false;
}
if (step instanceof HasContainerHolder) {
// we've got a "has(x,y)" step, check the condition
List<HasContainer> hasContainers = ((HasContainerHolder) step).getHasContainers();
for (HasContainer hasContainer : hasContainers) {
if (!allowAnyPredicate && !isChronoGraphIndexablePredicate(hasContainer.getPredicate())) {
return false;
}
}
return true;
} else if (step instanceof ConnectiveStep) {
// this case unifies "and" & "or" steps in gremlin (common superclass)
ConnectiveStep<?> connectiveStep = (ConnectiveStep<?>) step;
List<? extends Admin<?, ?>> localChildren = connectiveStep.getLocalChildren();
for (Admin<?, ?> childTraversal : localChildren) {
for (Step<?, ?> childStep : childTraversal.getSteps()) {
if (!isChronoGraphIndexable(childStep, allowAnyPredicate)) {
return false;
}
}
}
return true;
} else if (step instanceof NotStep) {
NotStep<?> notStep = (NotStep<?>) step;
List<? extends Admin<?, ?>> localChildren = notStep.getLocalChildren();
for (Admin<?, ?> childTraversal : localChildren) {
for (Step<?, ?> childStep : childTraversal.getSteps()) {
if (!isChronoGraphIndexable(childStep, allowAnyPredicate)) {
return false;
}
}
}
return true;
}
return false;
}
public static boolean isChronoGraphIndexablePredicate(Predicate<?> predicate) {
if (predicate instanceof CP) {
// we can always deal with our own predicates, since we define them
// ourselves.
return true;
}
if (predicate instanceof ConnectiveP) {
ConnectiveP<?> connective = (ConnectiveP<?>) predicate;
List<? extends P<?>> subPredicates = connective.getPredicates();
for (P<?> subPredicate : subPredicates) {
if (!isChronoGraphIndexablePredicate(subPredicate)) {
return false;
}
}
return true;
}
if (predicate instanceof P) {
P<?> p = (P<?>) predicate;
if (p.getBiPredicate() instanceof Compare) {
// eq, neq, gt, lt, leq, geq
return true;
}
if (p.getBiPredicate() instanceof Contains) {
// within, without
return true;
}
if (p.getBiPredicate() instanceof Text) {
// (native gremlin) starts with, ends with, ...
return true;
}
// note that AndP and OrP are EXCLUDED here! We normalize them in a strategy.
// all other bi-predicates are unknown...
return false;
}
// all other predicates are unknown to the indexer
return false;
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T extends Element> FinalizableQueryBuilder toChronoDBQuery(Set<ChronoGraphIndex> indices, List<FilterStep<T>> indexableSteps, QueryBaseBuilder<?> queryBuilder, Function<String, String> createIndexPropertyKey) {
QueryBaseBuilder<?> currentBuilder = queryBuilder;
currentBuilder = currentBuilder.begin();
boolean firstStep = true;
for (FilterStep<T> step : indexableSteps) {
if (!firstStep) {
// filter steps within a linear sequence are always implicitly AND connected in gremlin
currentBuilder = applyConnective(currentBuilder, Connective.AND);
}
firstStep = false;
if (step instanceof AndStep) {
currentBuilder = currentBuilder.begin();
AndStep<T> andStep = (AndStep<T>) step;
List<Admin<T, ?>> childTraversals = andStep.getLocalChildren();
boolean first = true;
for (Admin<T, ?> childTraversal : childTraversals) {
if (!first) {
currentBuilder = applyConnective(currentBuilder, Connective.AND);
}
first = false;
List<FilterStep<T>> steps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
currentBuilder = toChronoDBQuery(indices, steps, currentBuilder, createIndexPropertyKey);
}
currentBuilder = currentBuilder.end();
} else if (step instanceof OrStep) {
currentBuilder = currentBuilder.begin();
OrStep<T> orStep = (OrStep<T>) step;
List<Admin<T, ?>> childTraversals = orStep.getLocalChildren();
boolean first = true;
for (Admin<T, ?> childTraversal : childTraversals) {
if (!first) {
currentBuilder = applyConnective(currentBuilder, Connective.OR);
}
first = false;
List<FilterStep<T>> steps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
currentBuilder = toChronoDBQuery(indices, steps, currentBuilder, createIndexPropertyKey);
}
currentBuilder = currentBuilder.end();
} else if (step instanceof NotStep) {
currentBuilder = currentBuilder.not().begin();
NotStep<T> notStep = (NotStep<T>) step;
List<Admin<T, ?>> childTraversals = notStep.getLocalChildren();
boolean first = true;
for (Admin<T, ?> childTraversal : childTraversals) {
if (!first) {
currentBuilder = applyConnective(currentBuilder, Connective.AND);
}
first = false;
List<FilterStep<T>> steps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
currentBuilder = toChronoDBQuery(indices, steps, currentBuilder, createIndexPropertyKey);
}
currentBuilder = currentBuilder.end();
} else if (step instanceof HasContainerHolder) {
List<HasContainer> hasContainers = ((HasContainerHolder) step).getHasContainers();
boolean first = true;
for (HasContainer hasContainer : hasContainers) {
if (!first) {
currentBuilder = applyConnective(currentBuilder, Connective.AND);
}
first = false;
Set<IndexType> indexTypes = indices.stream()
.filter(index -> index.getIndexedProperty().equals(hasContainer.getKey()))
.map(ChronoGraphIndex::getIndexType)
.collect(Collectors.toSet());
String gremlinPropertyName = hasContainer.getKey();
String indexPropertyKey = createIndexPropertyKey.apply(gremlinPropertyName);
// String indexPropertyKey = ChronoGraphConstants.INDEX_PREFIX_VERTEX + gremlinPropertyName;
WhereBuilder whereBuilder = ((QueryBuilder) currentBuilder).where(indexPropertyKey);
currentBuilder = applyWhereClause(indexTypes, whereBuilder, hasContainer.getBiPredicate(), hasContainer.getValue());
}
} else {
throw new IllegalStateException("Unexpected step for index query: " + step.getClass().getName());
}
}
currentBuilder = currentBuilder.end();
return (FinalizableQueryBuilder) currentBuilder;
}
private static QueryBaseBuilder<?> applyConnective(QueryBaseBuilder<?> currentBuilder, final Connective connective) {
switch (connective) {
case OR:
return ((FinalizableQueryBuilder) currentBuilder).or();
case AND:
return ((FinalizableQueryBuilder) currentBuilder).and();
default:
throw new UnknownEnumLiteralException(connective);
}
}
private static FinalizableQueryBuilder applyWhereClause(Set<IndexType> indexTypes, WhereBuilder whereBuilder, BiPredicate<?, ?> biPredicate, Object value) {
if (biPredicate.equals(Compare.eq) || biPredicate.equals(ChronoCompare.EQ)) {
if (indexTypes.contains(IndexType.LONG) && ReflectionUtils.isLongCompatible(value)) {
return whereBuilder.isEqualTo(ReflectionUtils.asLong(value));
} else if (indexTypes.contains(IndexType.DOUBLE) && ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isEqualTo(ReflectionUtils.asDouble(value), 0.0);
} else if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.isEqualTo((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(Compare.neq) || biPredicate.equals(ChronoCompare.NEQ)) {
if (indexTypes.contains(IndexType.LONG) && ReflectionUtils.isLongCompatible(value)) {
return whereBuilder.isNotEqualTo(ReflectionUtils.asLong(value));
} else if (indexTypes.contains(IndexType.DOUBLE) && ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isNotEqualTo(ReflectionUtils.asDouble(value), 0.0);
} else if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.isNotEqualTo((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(Compare.lt) || biPredicate.equals(ChronoCompare.LT)) {
if (indexTypes.contains(IndexType.LONG) && ReflectionUtils.isLongCompatible(value)) {
return whereBuilder.isLessThan(ReflectionUtils.asLong(value));
} else if (indexTypes.contains(IndexType.DOUBLE) && ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isLessThan(ReflectionUtils.asDouble(value));
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(Compare.lte) || biPredicate.equals(ChronoCompare.LTE)) {
if (indexTypes.contains(IndexType.LONG) && ReflectionUtils.isLongCompatible(value)) {
return whereBuilder.isLessThanOrEqualTo(ReflectionUtils.asLong(value));
} else if (ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isLessThanOrEqualTo(ReflectionUtils.asDouble(value));
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(Compare.gt) || biPredicate.equals(ChronoCompare.GT)) {
if (indexTypes.contains(IndexType.LONG) && ReflectionUtils.isLongCompatible(value)) {
return whereBuilder.isGreaterThan(ReflectionUtils.asLong(value));
} else if (indexTypes.contains(IndexType.DOUBLE) && ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isGreaterThan(ReflectionUtils.asDouble(value));
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(Compare.gte) || biPredicate.equals(ChronoCompare.GTE)) {
if (indexTypes.contains(IndexType.LONG) && ReflectionUtils.isLongCompatible(value)) {
return whereBuilder.isGreaterThanOrEqualTo(ReflectionUtils.asLong(value));
} else if (indexTypes.contains(IndexType.DOUBLE) && ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isGreaterThanOrEqualTo(ReflectionUtils.asDouble(value));
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(Contains.within) || biPredicate.equals(ChronoCompare.WITHIN)) {
if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
if (indexTypes.contains(IndexType.STRING) && collection.stream().allMatch(String.class::isInstance)) {
Set<String> strings = collection.stream().map(String.class::cast).collect(Collectors.toSet());
return whereBuilder.inStrings(strings);
} else if (indexTypes.contains(IndexType.LONG) && collection.stream().allMatch(ReflectionUtils::isLongCompatible)) {
Set<Long> longs = collection.stream().map(ReflectionUtils::asLong).collect(Collectors.toSet());
return whereBuilder.inLongs(longs);
} else if (indexTypes.contains(IndexType.DOUBLE) && collection.stream().allMatch(ReflectionUtils::isDoubleCompatible)) {
Set<Double> doubles = collection.stream().map(ReflectionUtils::asDouble).collect(Collectors.toSet());
return whereBuilder.inDoubles(doubles, 0.0);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(Contains.without) || biPredicate.equals(ChronoCompare.WITHOUT)) {
if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
if (indexTypes.contains(IndexType.STRING) && collection.stream().allMatch(String.class::isInstance)) {
Set<String> strings = collection.stream().map(String.class::cast).collect(Collectors.toSet());
return whereBuilder.notInStrings(strings);
} else if (indexTypes.contains(IndexType.LONG) && collection.stream().allMatch(ReflectionUtils::isLongCompatible)) {
Set<Long> longs = collection.stream().map(ReflectionUtils::asLong).collect(Collectors.toSet());
return whereBuilder.notInLongs(longs);
} else if (indexTypes.contains(IndexType.DOUBLE) && collection.stream().allMatch(ReflectionUtils::isDoubleCompatible)) {
Set<Double> doubles = collection.stream().map(ReflectionUtils::asDouble).collect(Collectors.toSet());
return whereBuilder.notInDoubles(doubles, 0.0);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate instanceof DoubleWithinCP) {
if (indexTypes.contains(IndexType.DOUBLE) && value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
if (collection.stream().allMatch(ReflectionUtils::isDoubleCompatible)) {
Set<Double> doubles = collection.stream().map(ReflectionUtils::asDouble).collect(Collectors.toSet());
return whereBuilder.notInDoubles(doubles, ((DoubleWithinCP) biPredicate).getTolerance());
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate instanceof DoubleWithoutCP) {
if (indexTypes.contains(IndexType.DOUBLE) && value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
if (collection.stream().allMatch(ReflectionUtils::isDoubleCompatible)) {
Set<Double> doubles = collection.stream().map(ReflectionUtils::asDouble).collect(Collectors.toSet());
return whereBuilder.notInDoubles(doubles, ((DoubleWithoutCP) biPredicate).getTolerance());
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_EQUALS_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.isEqualToIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_EQUALS_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.isNotEqualToIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_CONTAINS) || biPredicate.equals(Text.containing)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.contains((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_CONTAINS_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.containsIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_CONTAINS) || biPredicate.equals(Text.notContaining)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notContains((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_CONTAINS_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notContainsIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_STARTS_WITH) || biPredicate.equals(Text.startingWith)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.startsWith((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_STARTS_WITH_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.startsWithIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_STARTS_WITH) || biPredicate.equals(Text.notStartingWith)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notStartsWith((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_STARTS_WITH_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notStartsWithIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_ENDS_WITH) || biPredicate.equals(Text.endingWith)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.endsWith((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_ENDS_WITH_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.endsWithIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_ENDS_WITH) || biPredicate.equals(Text.notEndingWith)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notEndsWith((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_ENDS_WITH_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notEndsWithIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_MATCHES_REGEX)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.matchesRegex((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_MATCHES_REGEX_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.matchesRegexIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_MATCHES_REGEX)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notMatchesRegex((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate.equals(ChronoStringCompare.STRING_NOT_MATCHES_REGEX_IGNORE_CASE)) {
if (indexTypes.contains(IndexType.STRING) && value instanceof String) {
return whereBuilder.notMatchesRegexIgnoreCase((String) value);
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate instanceof DoubleEqualsCP) {
if (indexTypes.contains(IndexType.DOUBLE) && ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isEqualTo(ReflectionUtils.asDouble(value), ((DoubleEqualsCP) biPredicate).getTolerance());
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else if (biPredicate instanceof DoubleNotEqualsCP) {
if (indexTypes.contains(IndexType.DOUBLE) && ReflectionUtils.isDoubleCompatible(value)) {
return whereBuilder.isEqualTo(ReflectionUtils.asDouble(value), ((DoubleNotEqualsCP) biPredicate).getTolerance());
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
}else if(biPredicate instanceof StringWithinCP) {
if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
if (indexTypes.contains(IndexType.STRING) && collection.stream().allMatch(String.class::isInstance)) {
Set<String> strings = collection.stream().map(String.class::cast).collect(Collectors.toSet());
TextMatchMode matchMode = ((StringWithinCP)biPredicate).getMatchMode();
switch(matchMode){
case STRICT:
return whereBuilder.inStrings(strings);
case CASE_INSENSITIVE:
return whereBuilder.inStringsIgnoreCase(strings);
default:
throw new UnknownEnumLiteralException(matchMode);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
}else if(biPredicate instanceof StringWithoutCP){
if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
if (indexTypes.contains(IndexType.STRING) && collection.stream().allMatch(String.class::isInstance)) {
Set<String> strings = collection.stream().map(String.class::cast).collect(Collectors.toSet());
TextMatchMode matchMode = ((StringWithoutCP)biPredicate).getMatchMode();
switch(matchMode){
case STRICT:
return whereBuilder.notInStrings(strings);
case CASE_INSENSITIVE:
return whereBuilder.notInStringsIgnoreCase(strings);
default:
throw new UnknownEnumLiteralException(matchMode);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else {
throw createInvalidIndexAccessException(indexTypes, biPredicate, value);
}
} else {
throw new IllegalArgumentException("Unknown predicate '" + biPredicate + "'!");
}
}
private static RuntimeException createInvalidIndexAccessException(final Set<IndexType> indexTypes, final BiPredicate<?, ?> biPredicate, final Object value) {
throw new IllegalArgumentException("Cannot construct filter with predicate '" + biPredicate + "' and value '" + value + "' of type " + value.getClass().getName() + " for index type(s) " + indexTypes + "!");
}
public static <T extends Element> Predicate<T> filterStepsToPredicate(List<FilterStep<T>> filterSteps) {
// our base predicate accepts everything
Predicate<T> currentPredicate = (e) -> true;
for (FilterStep<T> filterStep : filterSteps) {
// in gremlin, successive filter steps are implicitly AND connected
currentPredicate = currentPredicate.and(filterStepToPredicate(filterStep));
}
return currentPredicate;
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T extends Element> Predicate<T> filterStepToPredicate(FilterStep<T> filterStep) {
if (filterStep instanceof HasContainerHolder) {
List<HasContainer> hasContainers = ((HasContainerHolder) filterStep).getHasContainers();
return (e) -> HasContainer.testAll(e, hasContainers);
} else if (filterStep instanceof AndStep) {
AndStep<T> andStep = (AndStep<T>) filterStep;
List<Admin<T, ?>> childTraversals = andStep.getLocalChildren();
Predicate<T> currentPredicate = (e) -> true;
for (Admin<T, ?> childTraversal : childTraversals) {
List<FilterStep<T>> childSteps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
currentPredicate = currentPredicate.and(filterStepsToPredicate(childSteps));
}
return currentPredicate;
} else if (filterStep instanceof OrStep) {
OrStep<T> orStep = (OrStep<T>) filterStep;
List<Admin<T, ?>> childTraversals = orStep.getLocalChildren();
// we use FALSE as the default value for this predicate because what follows
// is a sequence of OR-connected predicates.
Predicate<T> currentPredicate = (e) -> false;
for (Admin<T, ?> childTraversal : childTraversals) {
List<FilterStep<T>> childSteps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
currentPredicate = currentPredicate.or(filterStepsToPredicate(childSteps));
}
return currentPredicate;
} else if (filterStep instanceof NotStep) {
NotStep<T> notStep = (NotStep<T>) filterStep;
List<Admin<T, ?>> childTraversals = notStep.getLocalChildren();
Predicate<T> currentPredicate = (e) -> true;
for (Admin<T, ?> childTraversal : childTraversals) {
List<FilterStep<T>> childSteps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
currentPredicate = currentPredicate.and(filterStepsToPredicate(childSteps));
}
return currentPredicate.negate();
} else {
throw new IllegalArgumentException("Unknown filter step: " + filterStep);
}
}
public static <T extends Element> Set<String> getHasPropertyKeys(List<FilterStep<T>> filterSteps) {
return filterSteps.stream().flatMap(step -> getHasPropertyKeys(step).stream()).collect(Collectors.toSet());
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T extends Element> Set<String> getHasPropertyKeys(FilterStep<T> filterStep) {
if (filterStep instanceof HasContainerHolder) {
List<HasContainer> hasContainers = ((HasContainerHolder) filterStep).getHasContainers();
return hasContainers.stream().map(HasContainer::getKey).collect(Collectors.toSet());
} else if (filterStep instanceof AndStep) {
AndStep<T> andStep = (AndStep<T>) filterStep;
List<Admin<T, ?>> childTraversals = andStep.getLocalChildren();
Set<String> resultSet = Sets.newHashSet();
for (Admin<T, ?> childTraversal : childTraversals) {
List<FilterStep<T>> childSteps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
resultSet.addAll(getHasPropertyKeys(childSteps));
}
return resultSet;
} else if (filterStep instanceof OrStep) {
OrStep<T> orStep = (OrStep<T>) filterStep;
List<Admin<T, ?>> childTraversals = orStep.getLocalChildren();
// we use FALSE as the default value for this predicate because what follows
// is a sequence of OR-connected predicates.
Set<String> resultSet = Sets.newHashSet();
for (Admin<T, ?> childTraversal : childTraversals) {
List<FilterStep<T>> childSteps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
resultSet.addAll(getHasPropertyKeys(childSteps));
}
return resultSet;
} else if (filterStep instanceof NotStep) {
NotStep<T> notStep = (NotStep<T>) filterStep;
List<Admin<T, ?>> childTraversals = notStep.getLocalChildren();
Set<String> resultSet = Sets.newHashSet();
for (Admin<T, ?> childTraversal : childTraversals) {
List<FilterStep<T>> childSteps = (List<FilterStep<T>>) (List) childTraversal.getSteps();
resultSet.addAll(getHasPropertyKeys(childSteps));
}
return resultSet;
} else {
throw new IllegalArgumentException("Unknown filter step: " + filterStep);
}
}
public static String createIndexKeyForVertexProperty(String property) {
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
return ChronoGraphConstants.INDEX_PREFIX_VERTEX + property;
}
public static String createIndexKeyForEdgeProperty(String property) {
checkNotNull(property, "Precondition violation - argument 'property' must not be NULL!");
return ChronoGraphConstants.INDEX_PREFIX_EDGE + property;
}
/**
* Normalizes connective (AND & OR) predicates into AND/OR gremlin queries.
*
* <p>
* Example Input:
*
* <pre>
* has("name", P.eq("John").or("Jane").or("Jack").and("Sarah"))
* </pre>
*
* Example Output:
* <pre>
* __.and(
* __.or(
* __.has("name", "Jack"),
* __.or(
* __.has("name", "Jane"),
* __.has("name", "John")
* )
* ),
* __.has("name", "Sarah")
* )
* </pre>
* </p>
*
* @param traversal The original traversal to normalize. Must not be <code>null</code>.
* @param steps The steps of the traversal to analyze. Must not be <code>null</code>.
* @return A map containing the required replacements to perform on the traversal in order to normalize it. Steps which do not occur as keys are already normalized and can stay the same.
*/
@SuppressWarnings("rawtypes")
public static Map<Step, Step> normalizeConnectivePredicates(Traversal.Admin traversal, final List<Step<?, ?>> steps) {
checkNotNull(traversal, "Precondition violation - argument 'traversal' must not be NULL!");
checkNotNull(steps, "Precondition violation - argument 'steps' must not be NULL!");
Map<Step, Step> topLevelReplacements = Maps.newHashMap();
for (Step<?, ?> topLevelStep : steps) {
Step replacementStep = normalizeConnectivePredicates(traversal, topLevelStep);
if (replacementStep != null) {
topLevelReplacements.put(topLevelStep, replacementStep);
}
}
return topLevelReplacements;
}
@SuppressWarnings({"unchecked"})
private static Step normalizeConnectivePredicates(Traversal.Admin traversal, Step topLevelStep) {
if (topLevelStep instanceof HasContainerHolder) {
List<HasContainer> hasContainers = ((HasContainerHolder) topLevelStep).getHasContainers();
List<FilterStep<Element>> filterSteps = hasContainers.stream()
.map(has -> normalizePredicate(traversal, has))
.collect(Collectors.toList());
if (filterSteps.size() == 1) {
// we only have one step, keep it as-is
return Iterables.getOnlyElement(filterSteps);
}
// we have multiple steps, create a wrapping AND step
Traversal[] subTraversals = filterSteps.stream()
.map(ChronoGraphTraversalUtil::createTraversalForStep)
.toArray(Traversal[]::new);
// has-containers are ALWAYS implicitly AND-connected
return new AndStep(traversal, subTraversals);
} else if (topLevelStep instanceof AndStep) {
AndStep<?> andStep = (AndStep<?>) topLevelStep;
List<? extends Admin<?, ?>> childTraversals = andStep.getLocalChildren();
Traversal[] transformedChildTraversals = childTraversals.stream().map(childTraversal -> {
List<FilterStep<?>> childSteps = (List<FilterStep<?>>) (List) childTraversal.getSteps();
List<Step<?, ?>> transformedChildSteps = childSteps.stream()
.map(childStep -> (Step<?, ?>) normalizeConnectivePredicates(traversal, childStep))
.collect(Collectors.toList());
return createTraversalForSteps(transformedChildSteps);
}).toArray(Traversal[]::new);
return new AndStep(traversal, transformedChildTraversals);
} else if (topLevelStep instanceof OrStep) {
OrStep<?> andStep = (OrStep<?>) topLevelStep;
List<? extends Admin<?, ?>> childTraversals = andStep.getLocalChildren();
Traversal[] transformedChildTraversals = childTraversals.stream().map(childTraversal -> {
List<FilterStep<?>> childSteps = (List<FilterStep<?>>) (List) childTraversal.getSteps();
List<Step<?, ?>> transformedChildSteps = childSteps.stream()
.map(childStep -> (Step<?, ?>) normalizeConnectivePredicates(traversal, childStep))
.collect(Collectors.toList());
return createTraversalForSteps(transformedChildSteps);
}).toArray(Traversal[]::new);
return new OrStep(traversal, transformedChildTraversals);
} else if (topLevelStep instanceof NotStep) {
NotStep<?> notStep = (NotStep<?>) topLevelStep;
List<? extends Admin<?, ?>> childTraversals = notStep.getLocalChildren();
// NOT may only have a single child traversal!
Admin<?, ?> childTraversal = Iterables.getOnlyElement(childTraversals);
List<FilterStep<?>> childSteps = (List<FilterStep<?>>) (List) childTraversal.getSteps();
List<Step<?, ?>> transformedChildSteps = childSteps.stream()
.map(childStep -> (Step<?, ?>) normalizeConnectivePredicates(traversal, childStep))
.collect(Collectors.toList());
GraphTraversal.Admin transformedChildTraversal = createTraversalForSteps(transformedChildSteps);
return new NotStep(traversal, transformedChildTraversal);
} else {
// do not modify anything else
return null;
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static <V extends Element> FilterStep<V> normalizePredicate(Traversal.Admin traversal, HasContainer hasContainer) {
P predicate = hasContainer.getPredicate();
return normalizePredicate(traversal, hasContainer.getKey(), (P<V>) predicate);
}
@SuppressWarnings("unchecked")
private static <V extends Element> FilterStep<V> normalizePredicate(Traversal.Admin traversal, String propertyKey, P<V> predicate) {
if (predicate instanceof AndP) {
// replace and-predicate by traversal and steps
AndP<V> orPredicate = (AndP<V>) predicate;
List<P<V>> subPredicates = orPredicate.getPredicates();
Traversal[] transformedChildTraversals = subPredicates.stream()
.map(p -> normalizePredicate(traversal, propertyKey, p))
.map(ChronoGraphTraversalUtil::createTraversalForStep)
.toArray(Traversal[]::new);
return new AndStep(traversal, transformedChildTraversals);
} else if (predicate instanceof OrP) {
// replace or-predicate by traversal or steps
OrP<V> orPredicate = (OrP<V>) predicate;
List<P<V>> subPredicates = orPredicate.getPredicates();
return new OrStep(traversal, subPredicates.stream()
.map(p -> (Step<?, ?>) normalizePredicate(traversal, propertyKey, p))
.map(ChronoGraphTraversalUtil::createTraversalForStep)
.toArray(Traversal[]::new)
);
} else {
// in all other cases, we keep the predicate intact
return new HasStep<>(traversal, new HasContainer(propertyKey, predicate));
}
}
private static <S, E> GraphTraversal.Admin<?, ?> createTraversalForStep(final Step<S, E> step) {
return __.start().asAdmin().addStep(step);
}
private static GraphTraversal.Admin<?, ?> createTraversalForSteps(final List<Step<?, ?>> steps) {
GraphTraversal.Admin<Object, Object> traversal = __.start().asAdmin();
for (Step<?, ?> step : steps) {
traversal.addStep(step);
}
return traversal;
}
}
| 50,692 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
CachedSupplier.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/CachedSupplier.java | package org.chronos.chronograph.internal.impl.util;
import org.apache.tinkerpop.gremlin.structure.T;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class CachedSupplier<T> implements Supplier<T> {
public static <T> CachedSupplier<T> create(Supplier<T> supplier){
if(supplier instanceof CachedSupplier){
return (CachedSupplier<T>)supplier;
}else{
return new CachedSupplier<>(supplier);
}
}
private final Supplier<T> supplier;
private T element;
public CachedSupplier(Supplier<T> supplier){
this.supplier = supplier;
}
public synchronized T get(){
if(this.element == null){
this.element = this.supplier.get();
}
return this.element;
}
public synchronized T getIfLoaded(){
return this.element;
}
public synchronized <R> R mapIfLoaded(Function<T, R> function){
if(this.element != null){
return function.apply(this.element);
}else{
return null;
}
}
public synchronized void doIfLoaded(Consumer<T> function){
if(this.element != null){
function.accept(this.element);
}
}
public <R> CachedSupplier<R> map(Function<T, R> map){
return new CachedSupplier<>(() -> map.apply(CachedSupplier.this.get()));
}
}
| 1,424 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoProxyUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/ChronoProxyUtil.java | package org.chronos.chronograph.internal.impl.util;
import com.google.common.collect.Iterators;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.chronos.chronograph.api.structure.ChronoEdge;
import org.chronos.chronograph.api.structure.ChronoElement;
import org.chronos.chronograph.api.structure.ChronoVertex;
import org.chronos.chronograph.api.transaction.ChronoGraphTransaction;
import org.chronos.chronograph.internal.api.transaction.GraphTransactionContextInternal;
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.AbstractElementProxy;
import java.util.Iterator;
import static com.google.common.base.Preconditions.*;
public class ChronoProxyUtil {
@SuppressWarnings("unchecked")
public static <T extends ChronoElement> T resolveProxy(final T maybeProxy) {
if (maybeProxy == null) {
return null;
}
if (maybeProxy instanceof AbstractElementProxy) {
// proxy, resolve
AbstractElementProxy<?> proxy = (AbstractElementProxy<?>) maybeProxy;
return (T) proxy.getElement();
} else {
// not a proxy
return maybeProxy;
}
}
public static ChronoVertexImpl resolveVertexProxy(final Vertex vertex) {
return (ChronoVertexImpl) resolveProxy((ChronoVertex) vertex);
}
public static ChronoEdgeImpl resolveEdgeProxy(final Edge edge) {
return (ChronoEdgeImpl) resolveProxy((ChronoEdge) edge);
}
public static Iterator<Vertex> replaceVerticesByProxies(final Iterator<Vertex> iterator,
final ChronoGraphTransaction tx) {
checkNotNull(iterator, "Precondition violation - argument 'iterator' must not be NULL!");
checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!");
GraphTransactionContextInternal context = (GraphTransactionContextInternal) tx.getContext();
return Iterators.transform(iterator, v -> context.getOrCreateVertexProxy(v));
}
public static Iterator<Edge> replaceEdgesByProxies(final Iterator<Edge> iterator, final ChronoGraphTransaction tx) {
checkNotNull(iterator, "Precondition violation - argument 'iterator' must not be NULL!");
checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!");
GraphTransactionContextInternal context = (GraphTransactionContextInternal) tx.getContext();
return Iterators.transform(iterator, e -> context.getOrCreateEdgeProxy(e));
}
}
| 2,751 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
ChronoGraphQueryUtil.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/util/ChronoGraphQueryUtil.java | package org.chronos.chronograph.internal.impl.util;
import static com.google.common.base.Preconditions.*;
import java.util.Set;
import org.apache.tinkerpop.gremlin.process.traversal.Compare;
import org.chronos.chronodb.api.query.NumberCondition;
import org.chronos.chronodb.internal.api.query.searchspec.*;
import org.chronos.common.exceptions.UnknownEnumLiteralException;
import org.chronos.common.util.ReflectionUtils;
import com.google.common.collect.Sets;
public class ChronoGraphQueryUtil {
/** The default equality tolerance in graph queries that operate on <code>double</code> values (=10e-6). */
public static final Double DOUBLE_EQUALITY_TOLERANCE = 10e-6;
/**
* Attempts to match the given value against the given search specification.
*
* <p>
* If the value is an {@link Iterable}, each value will be checked individually, and this method will return <code>true</code> if the search specification applies for at least one element of the iterable.
*
* @param searchSpec
* The search spec to test on the given value. Must not be <code>null</code>.
* @param value
* The value to test. May be <code>null</code>. * @param numberIndexingMode The indexing mode to apply. See documentation of enum literals for details. Must not be <code>null</code>.
* @return <code>true</code> if the given search specification applies to the given value, otherwise <code>false</code>.
*/
public static boolean searchSpecApplies(final SearchSpecification<?,?> searchSpec, final Object value) {
checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!");
if (searchSpec instanceof StringSearchSpecification) {
return searchSpecApplies((StringSearchSpecification) searchSpec, value);
} else if (searchSpec instanceof LongSearchSpecification) {
return searchSpecApplies((LongSearchSpecification) searchSpec, value);
} else if (searchSpec instanceof DoubleSearchSpecification) {
return searchSpecApplies((DoubleSearchSpecification) searchSpec, value);
} else if (searchSpec instanceof ContainmentStringSearchSpecification) {
return searchSpecApplies((ContainmentStringSearchSpecification) searchSpec, value);
} else if(searchSpec instanceof ContainmentLongSearchSpecification) {
return searchSpecApplies((ContainmentLongSearchSpecification) searchSpec, value);
}else if(searchSpec instanceof ContainmentDoubleSearchSpecification) {
return searchSpecApplies((ContainmentDoubleSearchSpecification) searchSpec, value);
} else {
throw new IllegalStateException("Unknown SearchSpecification class: '" + searchSpec.getClass().getName() + "'!");
}
}
/**
* Attempts to match the given value against the given search specification.
*
* <p>
* If the value is an {@link Iterable}, each value will be checked individually, and this method will return <code>true</code> if the search specification applies for at least one element of the iterable.
*
* @param searchSpec
* The search spec to test on the given value. Must not be <code>null</code>.
* @param value
* The value to test. May be <code>null</code>.
* @return <code>true</code> if the given search specification applies to the given value, otherwise <code>false</code>.
*/
public static boolean searchSpecApplies(final StringSearchSpecification searchSpec, final Object value) {
checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!");
if (value == null) {
return false;
}
Set<Object> extractedValues = extractValues(value);
for (Object element : extractedValues) {
if (element instanceof String == false) {
continue;
}
String stringVal = (String) element;
if (searchSpec.matches(stringVal)) {
return true;
}
}
return false;
}
/**
* Attempts to match the given value against the given search specification.
*
* <p>
* If the value is an {@link Iterable}, each value will be checked individually, and this method will return <code>true</code> if the search specification applies for at least one element of the iterable.
*
* @param searchSpec
* The search spec to test on the given value. Must not be <code>null</code>.
* @param value
* The value to test. May be <code>null</code>.
* @return <code>true</code> if the given search specification applies to the given value, otherwise <code>false</code>.
*/
public static boolean searchSpecApplies(final LongSearchSpecification searchSpec, final Object value) {
checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!");
if (value == null) {
return false;
}
Set<Object> extractedValues = extractValues(value);
for (Object element : extractedValues) {
if (ReflectionUtils.isLongCompatible(element) == false) {
continue;
}
long longVal = ReflectionUtils.asLong(value);
if (searchSpec.matches(longVal)) {
return true;
}
}
return false;
}
/**
* Attempts to match the given value against the given search specification.
*
* <p>
* If the value is an {@link Iterable}, each value will be checked individually, and this method will return <code>true</code> if the search specification applies for at least one element of the iterable.
*
* @param searchSpec
* The search spec to test on the given value. Must not be <code>null</code>.
* @param value
* The value to test. May be <code>null</code>.
*
* @return <code>true</code> if the given search specification applies to the given value, otherwise <code>false</code>.
*/
public static boolean searchSpecApplies(final DoubleSearchSpecification searchSpec, final Object value) {
checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!");
if (value == null) {
return false;
}
Set<Object> extractedValues = extractValues(value);
for (Object element : extractedValues) {
if (ReflectionUtils.isDoubleCompatible(element) == false) {
continue;
}
double doubleVal = ReflectionUtils.asDouble(value);
if (searchSpec.matches(doubleVal)) {
return true;
}
}
return false;
}
/**
* Attempts to match the given value against the given search specification.
*
* <p>
* If the value is an {@link Iterable}, each value will be checked individually, and this method will return <code>true</code> if the search specification applies for at least one element of the iterable.
*
* @param searchSpec
* The search spec to test on the given value. Must not be <code>null</code>.
* @param value
* The value to test. May be <code>null</code>.
*
* @return <code>true</code> if the given search specification applies to the given value, otherwise <code>false</code>.
*/
public static boolean searchSpecApplies(final ContainmentStringSearchSpecification searchSpec, final Object value) {
checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!");
if (value == null) {
return false;
}
Set<Object> extractedValues = extractValues(value);
for (Object element : extractedValues) {
if (element instanceof String == false) {
continue;
}
String stringVal = (String) element;
if (searchSpec.matches(stringVal)) {
return true;
}
}
return false;
}
/**
* Attempts to match the given value against the given search specification.
*
* <p>
* If the value is an {@link Iterable}, each value will be checked individually, and this method will return <code>true</code> if the search specification applies for at least one element of the iterable.
*
* @param searchSpec
* The search spec to test on the given value. Must not be <code>null</code>.
* @param value
* The value to test. May be <code>null</code>.
* @return <code>true</code> if the given search specification applies to the given value, otherwise <code>false</code>.
*/
public static boolean searchSpecApplies(final ContainmentLongSearchSpecification searchSpec, final Object value) {
checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!");
if (value == null) {
return false;
}
Set<Object> extractedValues = extractValues(value);
for (Object element : extractedValues) {
if (ReflectionUtils.isLongCompatible(element) == false) {
continue;
}
long longVal = ReflectionUtils.asLong(value);
if (searchSpec.matches(longVal)) {
return true;
}
}
return false;
}
/**
* Attempts to match the given value against the given search specification.
*
* <p>
* If the value is an {@link Iterable}, each value will be checked individually, and this method will return <code>true</code> if the search specification applies for at least one element of the iterable.
*
* @param searchSpec
* The search spec to test on the given value. Must not be <code>null</code>.
* @param value
* The value to test. May be <code>null</code>.
*
* @return <code>true</code> if the given search specification applies to the given value, otherwise <code>false</code>.
*/
public static boolean searchSpecApplies(final ContainmentDoubleSearchSpecification searchSpec, final Object value) {
checkNotNull(searchSpec, "Precondition violation - argument 'searchSpec' must not be NULL!");
if (value == null) {
return false;
}
Set<Object> extractedValues = extractValues(value);
for (Object element : extractedValues) {
if (ReflectionUtils.isDoubleCompatible(element) == false) {
continue;
}
double doubleVal = ReflectionUtils.asDouble(value);
if (searchSpec.matches(doubleVal)) {
return true;
}
}
return false;
}
private static Set<Object> extractValues(final Object value) {
Set<Object> resultSet = Sets.newHashSet();
if (value == null) {
return resultSet;
}
if (value instanceof Iterable == false) {
// just use the string reperesentation of the value
resultSet.add(value);
return resultSet;
}
// iterate over the values and put everything in a collection
@SuppressWarnings("unchecked")
Iterable<? extends Object> iterable = (Iterable<? extends Object>) value;
for (Object element : iterable) {
resultSet.add(element);
}
return resultSet;
}
public static NumberCondition gremlinCompareToNumberCondition(final Compare compare) {
switch (compare) {
case eq:
return NumberCondition.EQUALS;
case neq:
return NumberCondition.NOT_EQUALS;
case gt:
return NumberCondition.GREATER_THAN;
case gte:
return NumberCondition.GREATER_EQUAL;
case lt:
return NumberCondition.LESS_THAN;
case lte:
return NumberCondition.LESS_EQUAL;
default:
throw new UnknownEnumLiteralException(compare);
}
}
}
| 10,788 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
GroovyCompilationCache.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/groovy/GroovyCompilationCache.java | package org.chronos.chronograph.internal.impl.groovy;
import groovy.lang.Script;
public interface GroovyCompilationCache {
public void put(String scriptContent, Class<? extends Script> compiledScript);
public Class<? extends Script> get(String scriptContent);
public void clear();
}
| 301 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
LocalGroovyCompilationCache.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/groovy/LocalGroovyCompilationCache.java | package org.chronos.chronograph.internal.impl.groovy;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import groovy.lang.Script;
import static com.google.common.base.Preconditions.*;
public class LocalGroovyCompilationCache implements GroovyCompilationCache {
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final Cache<String, Class<?extends Script>> localScriptCache = CacheBuilder.newBuilder().maximumSize(255).build();
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public void put(final String scriptContent, final Class<? extends Script> compiledScript) {
checkNotNull(scriptContent, "Precondition violation - argument 'scriptContent' must not be NULL!");
checkNotNull(compiledScript, "Precondition violation - argument 'compiledScript' must not be NULL!");
localScriptCache.put(scriptContent, compiledScript);
}
@Override
public Class<? extends Script> get(final String scriptContent) {
checkNotNull(scriptContent, "Precondition violation - argument 'scriptContent' must not be NULL!");
return localScriptCache.getIfPresent(scriptContent);
}
@Override
public void clear() {
this.localScriptCache.invalidateAll();
}
}
| 1,695 | Java | .java | Txture/chronos | 26 | 3 | 0 | 2020-05-19T17:35:13Z | 2023-03-10T16:19:01Z |
StaticGroovyCompilationCache.java | /FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/groovy/StaticGroovyCompilationCache.java | package org.chronos.chronograph.internal.impl.groovy;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import groovy.lang.Script;
import static com.google.common.base.Preconditions.*;
public class StaticGroovyCompilationCache implements GroovyCompilationCache {
// =================================================================================================================
// STATIC
// =================================================================================================================
private static final StaticGroovyCompilationCache INSTANCE = new StaticGroovyCompilationCache();
public static GroovyCompilationCache getInstance(){
return INSTANCE;
}
// =================================================================================================================
// FIELDS
// =================================================================================================================
private final Cache<String, Class<?extends Script>> scriptCache = CacheBuilder.newBuilder().maximumSize(255).build();
// =================================================================================================================
// CONSTRUCTOR
// =================================================================================================================
private StaticGroovyCompilationCache(){
}
// =================================================================================================================
// PUBLIC API
// =================================================================================================================
@Override
public void put(final String scriptContent, final Class<? extends Script> compiledScript) {
checkNotNull(scriptContent, "Precondition violation - argument 'scriptContent' must not be NULL!");
checkNotNull(compiledScript, "Precondition violation - argument 'compiledScript' must not be NULL!");
scriptCache.put(scriptContent, compiledScript);
}
@Override
public Class<? extends Script> get(final String scriptContent) {
checkNotNull(scriptContent, "Precondition violation - argument 'scriptContent' must not be NULL!");
return scriptCache.getIfPresent(scriptContent);
}
@Override
public void clear() {
this.scriptCache.invalidateAll();
}
}
| 2,438 | 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.