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
EObjectQueryNotStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryNotStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.api.query.EObjectQueryStepBuilder; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.api.query.QueryStepBuilderInternal; import org.chronos.chronosphere.impl.query.EObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.steps.object.ObjectQueryEObjectReifyStepBuilder; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.impl.query.traversal.TraversalSource; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.eclipse.emf.ecore.EObject; import static com.google.common.base.Preconditions.*; import static org.chronos.chronosphere.impl.query.QueryUtils.*; public class EObjectQueryNotStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final QueryStepBuilder<EObject, ?> subquery; public EObjectQueryNotStepBuilder(final TraversalChainElement previous, final QueryStepBuilder<EObject, ?> subquery) { super(previous); checkNotNull(subquery, "Precondition violation - argument 'subquery' must not be NULL!"); this.subquery = subquery; QueryStepBuilderInternal<?, ?> firstBuilderInChain = QueryUtils.getFirstBuilderInChain(subquery); if (firstBuilderInChain instanceof EObjectQueryStepBuilder == false) { // prepend a "reify" step to make the subqueries compatible with this query TraversalSource<?, ?> source = (TraversalSource<?, ?>) firstBuilderInChain.getPrevious(); firstBuilderInChain.setPrevious(new ObjectQueryEObjectReifyStepBuilder<>(source)); } } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { // apply the transforms on the subquery. We can hand over the vertex // representations here directly because we made sure above that the // incoming chain has an EObject query step as its first step. GraphTraversal innerTraversal = resolveTraversalChain(this.subquery, tx, false); return traversal.not(innerTraversal); } }
2,434
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryInstanceOfEClassStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryInstanceOfEClassStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.EObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import static com.google.common.base.Preconditions.*; public class EObjectQueryInstanceOfEClassStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final EClass eClass; private final boolean allowSubclasses; public EObjectQueryInstanceOfEClassStepBuilder(final TraversalChainElement previous, EClass eClass, boolean allowSubclasses) { super(previous); checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); this.eClass = eClass; this.allowSubclasses = allowSubclasses; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { if (this.allowSubclasses == false) { String eClassID = tx.getEPackageRegistry().getEClassID(this.eClass); String key = ChronoSphereGraphFormat.V_PROP__ECLASS_ID; return traversal.has(key, eClassID); } else { // we want to include subclasses, we don't have much choice other // than resolving the EObjects and using the Ecore API. Optimization? return traversal .map(t -> QueryUtils.mapVertexToEObject(tx, t)) .filter(this::filterEObject) .map(t -> QueryUtils.mapEObjectToVertex(tx.getGraph(), t.get())); } } private boolean filterEObject(Traverser<EObject> traverser) { EObject eObject = traverser.get(); if (eObject == null) { return false; } return this.eClass.isSuperTypeOf(eObject.eClass()); } }
2,321
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryEAllContentsStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryEAllContentsStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.EObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; public class EObjectQueryEAllContentsStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { public EObjectQueryEAllContentsStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal .repeat( // walk the incoming EContainer edges __.in(ChronoSphereGraphFormat.E_LABEL__ECONTAINER)) // emit every step .emit() // don't quit until the last possible vertex was reached in the loop .until(t -> false); } }
1,282
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryAllReferencingEObjectsQueryStep.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryAllReferencingEObjectsQueryStep.java
package org.chronos.chronosphere.impl.query.steps.eobject; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.EObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.chronos.chronosphere.internal.ogm.api.VertexKind; public class EObjectQueryAllReferencingEObjectsQueryStep<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { public EObjectQueryAllReferencingEObjectsQueryStep(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.in().has(ChronoSphereGraphFormat.V_PROP__KIND, VertexKind.EOBJECT.toString()); } }
1,062
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryFlatMapStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryFlatMapStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import java.util.Iterator; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class ObjectQueryFlatMapStepBuilder<S, I, E> extends ObjectQueryStepBuilderImpl<S, I, E> { private final Function<I, Iterator<E>> function; public ObjectQueryFlatMapStepBuilder(final TraversalChainElement previous, Function<I, Iterator<E>> function) { super(previous); checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); this.function = function; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, I> traversal) { return traversal.flatMap(t -> this.function.apply((t.get()))); } }
1,143
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryEGetAttributeStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryEGetAttributeStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import com.google.common.collect.Iterators; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.eclipse.emf.ecore.EAttribute; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class ObjectQueryEGetAttributeStepBuilder<S> extends ObjectQueryStepBuilderImpl<S, Vertex, Object> { private final EAttribute eAttribute; public ObjectQueryEGetAttributeStepBuilder(final TraversalChainElement previous, final EAttribute eAttribute) { super(previous); checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); this.eAttribute = eAttribute; } @Override public GraphTraversal<S, Object> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { ChronoEPackageRegistry registry = tx.getEPackageRegistry(); return traversal.flatMap(this.eGetByEAttribute(this.eAttribute, registry)); } @SuppressWarnings("unchecked") private <E2> Function<Traverser<Vertex>, Iterator<E2>> eGetByEAttribute(final EAttribute eAttribute, final ChronoEPackageRegistry registry) { return traverser -> { if (traverser == null || traverser.get() == null) { // skip NULL objects return Collections.emptyIterator(); } Vertex vertex = traverser.get(); String key = ChronoSphereGraphFormat.createVertexPropertyKey(registry, eAttribute); Object value = vertex.property(key).orElse(null); if (value == null) { return Collections.emptyIterator(); } else if (value instanceof Collection) { return ((Collection<E2>) value).iterator(); } else { return Iterators.singletonIterator((E2) value); } }; } }
2,548
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryEGetByNameStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryEGetByNameStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import com.google.common.collect.Iterators; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.eclipse.emf.ecore.*; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class ObjectQueryEGetByNameStepBuilder<S> extends ObjectQueryStepBuilderImpl<S, Vertex, Object> { private final String eStructuralFeatureName; public ObjectQueryEGetByNameStepBuilder(final TraversalChainElement previous, String eStructuralFeatureName) { super(previous); checkNotNull(eStructuralFeatureName, "Precondition violation - argument 'eStructuralFeatureName' must not be NULL!"); this.eStructuralFeatureName = eStructuralFeatureName; } @Override public GraphTraversal<S, Object> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.flatMap(this.eGetByName(this.eStructuralFeatureName, tx)); } @SuppressWarnings("unchecked") private <E2> Function<Traverser<Vertex>, Iterator<E2>> eGetByName(final String eStructuralFeatureName, final ChronoSphereTransactionInternal tx) { return traverser -> { if (traverser == null || traverser.get() == null) { // skip NULL objects return Collections.emptyIterator(); } Vertex vertex = traverser.get(); String eClassID = (String) vertex.property(ChronoSphereGraphFormat.V_PROP__ECLASS_ID).orElse(null); if (eClassID == null) { // EClass is unknown? Can this even happen? return Collections.emptyIterator(); } ChronoEPackageRegistry registry = tx.getEPackageRegistry(); EClass eClass = registry.getEClassByID(eClassID); if (eClass == null) { // EClass with the given ID doesn't exist... return Collections.emptyIterator(); } EStructuralFeature feature = eClass.getEStructuralFeature(eStructuralFeatureName); if (feature == null) { return Collections.emptyIterator(); } if (feature instanceof EAttribute) { // the feature we deal with is an EAttribute EAttribute eAttribute = (EAttribute) feature; String key = ChronoSphereGraphFormat.createVertexPropertyKey(registry, eAttribute); Object value = vertex.property(key).orElse(null); if (value == null) { return Collections.emptyIterator(); } else if (value instanceof Collection) { return ((Collection<E2>) value).iterator(); } else { return Iterators.singletonIterator((E2) value); } } else if (feature instanceof EReference) { // the feature we deal with is an EReference EReference eReference = (EReference) feature; String label = ChronoSphereGraphFormat.createReferenceEdgeLabel(registry, eReference); Iterator<Vertex> targets = vertex.vertices(org.apache.tinkerpop.gremlin.structure.Direction.OUT, label); // the next step in the query is certainly not an EObjectQueryStepBuilder, so // we have to reify the EObjects. Iterator<EObject> eObjectIterator = Iterators.transform(targets, v -> QueryUtils.mapVertexToEObject(tx, v)); return (Iterator<E2>) eObjectIterator; } else { throw new IllegalStateException("Unknown subclass of EStructuralFeature: " + feature.getClass().getName()); } }; } }
4,442
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryLimitStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryLimitStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class ObjectQueryLimitStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final long limit; public ObjectQueryLimitStepBuilder(final TraversalChainElement previous, long limit) { super(previous); this.limit = limit; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.limit(this.limit); } }
840
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryExceptSetStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryExceptSetStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import com.google.common.collect.Sets; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import java.util.Set; import static com.google.common.base.Preconditions.*; public class ObjectQueryExceptSetStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final Set<?> set; public ObjectQueryExceptSetStepBuilder(final TraversalChainElement previous, Set<?> set) { super(previous); checkNotNull(set, "Precondition violation - argument 'set' must not be NULL!"); this.set = Sets.newHashSet(set); } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.filter(t -> this.set.contains(t.get()) == false); } }
1,098
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryNamedStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryNamedStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; public class ObjectQueryNamedStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final String name; public ObjectQueryNamedStepBuilder(final TraversalChainElement previous, String name) { super(previous); checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); this.name = name; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.as(this.name); } }
981
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryExceptNamedStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryExceptNamedStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; public class ObjectQueryExceptNamedStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final String stepName; public ObjectQueryExceptNamedStepBuilder(final TraversalChainElement previous, final String stepName) { super(previous); checkNotNull(stepName, "Precondition violation - argument 'stepName' must not be NULL!"); this.stepName = stepName; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { // syntax according to: https://groups.google.com/d/msg/gremlin-users/EZUU00UEdoY/nX11hMu4AgAJ return traversal.where(P.neq(this.stepName)); } }
1,197
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryEObjectBackStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryEObjectBackStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; public class ObjectQueryEObjectBackStepBuilder<S> extends ObjectQueryStepBuilderImpl<S, Vertex, Object> { private final String stepName; public ObjectQueryEObjectBackStepBuilder(final TraversalChainElement previous, final String stepName) { super(previous); checkNotNull(stepName, "Precondition violation - argument 'stepName' must not be NULL!"); this.stepName = stepName; } @Override public GraphTraversal<S, Object> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.select(this.stepName); } }
1,102
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryMapStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryMapStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class ObjectQueryMapStepBuilder<S, I, E> extends ObjectQueryStepBuilderImpl<S, I, E> { private final Function<I, E> function; public ObjectQueryMapStepBuilder(final TraversalChainElement previous, final Function<I, E> function) { super(previous); checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); this.function = function; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, I> traversal) { return traversal.map(t -> this.function.apply(t.get())); } }
1,088
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryFilterStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryFilterStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import java.util.function.Predicate; import static com.google.common.base.Preconditions.*; public class ObjectQueryFilterStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final Predicate<E> predicate; public ObjectQueryFilterStepBuilder(final TraversalChainElement previous, Predicate<E> predicate) { super(previous); checkNotNull(predicate, "Precondition violation - argument 'predicate' must not be NULL!"); this.predicate = predicate; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.filter(traverser -> { E object = traverser.get(); return this.predicate.test(object); }); } }
1,171
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryBackStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryBackStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; public class ObjectQueryBackStepBuilder<S, I> extends ObjectQueryStepBuilderImpl<S, I, Object> { private final String name; public ObjectQueryBackStepBuilder(final TraversalChainElement previous, String name) { super(previous); checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); this.name = name; } @Override public GraphTraversal<S, Object> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, I> traversal) { return traversal.select(this.name); } }
993
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryNotStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryNotStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; import static org.chronos.chronosphere.impl.query.QueryUtils.*; public class ObjectQueryNotStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final QueryStepBuilder<E, ?> subquery; public ObjectQueryNotStepBuilder(final TraversalChainElement previous, final QueryStepBuilder<E, ?> subquery) { super(previous); checkNotNull(subquery, "Precondition violation - argument 'subquery' must not be NULL!"); this.subquery = subquery; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { GraphTraversal innerTraversal = resolveTraversalChain(this.subquery, tx, false); return traversal.not(innerTraversal); } }
1,258
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryEObjectUnionStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryEObjectUnionStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.eclipse.emf.ecore.EObject; import static com.google.common.base.Preconditions.*; import static org.chronos.chronosphere.impl.query.QueryUtils.*; public class ObjectQueryEObjectUnionStepBuilder<S> extends ObjectQueryStepBuilderImpl<S, Vertex, Object> { private final QueryStepBuilder<EObject, ?>[] subqueries; public ObjectQueryEObjectUnionStepBuilder(final TraversalChainElement previous, final QueryStepBuilder<EObject, ?>... subqueries) { super(previous); checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); this.subqueries = subqueries; } @Override public GraphTraversal<S, Object> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.union(subQueriesToObjectTraversals(tx, this.subqueries, true)); } }
1,368
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryOrStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryOrStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; import static org.chronos.chronosphere.impl.query.QueryUtils.*; public class ObjectQueryOrStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final QueryStepBuilder<E, ?>[] subqueries; public ObjectQueryOrStepBuilder(final TraversalChainElement previous, final QueryStepBuilder<E, ?>... subqueries) { super(previous); checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); this.subqueries = subqueries; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.or(subQueriesToObjectTraversals(tx, this.subqueries, false)); } }
1,225
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryAndStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryAndStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; import static org.chronos.chronosphere.impl.query.QueryUtils.*; public class ObjectQueryAndStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final QueryStepBuilder<E, ?>[] subqueries; @SafeVarargs public ObjectQueryAndStepBuilder(final TraversalChainElement previous, final QueryStepBuilder<E, ?>... subqueries) { super(previous); checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); this.subqueries = subqueries; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.and(subQueriesToObjectTraversals(tx, this.subqueries, false)); } }
1,245
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryAsBooleanStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryAsBooleanStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class ObjectQueryAsBooleanStepBuilder<S> extends ObjectQueryStepBuilderImpl<S, Object, Boolean> { public ObjectQueryAsBooleanStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Boolean> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalTo(traversal, Boolean.class); } }
876
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryDistinctStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryDistinctStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class ObjectQueryDistinctStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { public ObjectQueryDistinctStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.dedup(); } }
765
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryUnionStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryUnionStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import static com.google.common.base.Preconditions.*; import static org.chronos.chronosphere.impl.query.QueryUtils.*; public class ObjectQueryUnionStepBuilder<S, I> extends ObjectQueryStepBuilderImpl<S, I, Object> { private final QueryStepBuilder<I, ?>[] subqueries; @SafeVarargs public ObjectQueryUnionStepBuilder(final TraversalChainElement previous, final QueryStepBuilder<I, ?>... subqueries) { super(previous); checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); this.subqueries = subqueries; } @Override public GraphTraversal<S, Object> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, I> traversal) { return traversal.union(subQueriesToObjectTraversals(tx, this.subqueries, true)); } }
1,260
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryEObjectReifyStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryEObjectReifyStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.eclipse.emf.ecore.EObject; public class ObjectQueryEObjectReifyStepBuilder<S> extends ObjectQueryStepBuilderImpl<S, Vertex, EObject> { public ObjectQueryEObjectReifyStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, EObject> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.map(t -> QueryUtils.mapVertexToEObject(tx, t)); } }
980
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryAsCharacterStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryAsCharacterStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class ObjectQueryAsCharacterStepBuilder<S> extends ObjectQueryStepBuilderImpl<S, Object, Character> { public ObjectQueryAsCharacterStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Character> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalTo(traversal, Character.class); } }
886
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryTerminalConverterStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryTerminalConverterStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class ObjectQueryTerminalConverterStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, Object, E> { public ObjectQueryTerminalConverterStepBuilder(final TraversalChainElement previous) { super(previous); } @Override @SuppressWarnings("unchecked") public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { // convert all vertices to EObjects, but leave everything else alone. GraphTraversal<S, Object> newTraversal = traversal.map(traverser -> { Object element = traverser.get(); if (element instanceof Vertex == false) { return element; } Vertex vertex = (Vertex) element; return QueryUtils.mapVertexToEObject(tx, vertex); }); return (GraphTraversal<S, E>) newTraversal; } }
1,377
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryOrderByStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/object/ObjectQueryOrderByStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.object; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.ObjectQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import java.util.Comparator; import static com.google.common.base.Preconditions.*; public class ObjectQueryOrderByStepBuilder<S, E> extends ObjectQueryStepBuilderImpl<S, E, E> { private final Comparator<E> comparator; public ObjectQueryOrderByStepBuilder(final TraversalChainElement previous, final Comparator<E> comparator) { super(previous); checkNotNull(comparator, "Precondition violation - argument 'comparator' must not be NULL!"); this.comparator = comparator; } @Override public GraphTraversal<S, E> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, E> traversal) { return traversal.order().by(this.comparator); } }
1,085
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ModelEvolutionContextImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/evolution/ModelEvolutionContextImpl.java
package org.chronos.chronosphere.impl.evolution; import static com.google.common.base.Preconditions.*; import java.util.Set; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.api.MetaModelEvolutionContext; import org.chronos.chronosphere.api.SphereBranch; import org.chronos.chronosphere.api.query.QueryStepBuilderStarter; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; public class ModelEvolutionContextImpl implements MetaModelEvolutionContext { // ===================================================================================================================== // FIELDS // ===================================================================================================================== protected final ChronoSphere repository; protected final SphereBranch branch; protected final ChronoSphereTransactionInternal oldTx; protected final ChronoSphereTransactionInternal newTx; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public ModelEvolutionContextImpl(final ChronoSphere repository, final String branch, final ChronoSphereTransaction oldTx, final ChronoSphereTransaction newTx) { checkNotNull(repository, "Precondition violation - argument 'repository' must not be NULL!"); checkNotNull(oldTx, "Precondition violation - argument 'oldTx' must not be NULL!"); checkNotNull(newTx, "Precondition violation - argument 'newTx' must not be NULL!"); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); this.repository = repository; this.branch = repository.getBranchManager().getBranch(branch); this.oldTx = (ChronoSphereTransactionInternal) oldTx; this.newTx = (ChronoSphereTransactionInternal) newTx; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public EPackage getOldEPackage(final String namespaceURI) { checkNotNull(namespaceURI, "Precondition violation - argument 'namespaceURI' must not be NULL!"); return this.oldTx.getEPackageByNsURI(namespaceURI); } @Override public EPackage getNewEPackage(final String namespaceURI) { checkNotNull(namespaceURI, "Precondition violation - argument 'namespaceURI' must not be NULL!"); return this.newTx.getEPackageByNsURI(namespaceURI); } @Override public Set<EPackage> getOldEPackages() { return this.oldTx.getEPackages(); } @Override public Set<EPackage> getNewEPackages() { return this.newTx.getEPackages(); } @Override public SphereBranch getMigrationBranch() { return this.branch; } @Override public QueryStepBuilderStarter findInOldModel() { return this.oldTx.find(); } @Override public QueryStepBuilderStarter findInNewModel() { return this.newTx.find(); } @Override public void flush() { this.newTx.commitIncremental(); } @Override public EObject createAndAttachEvolvedEObject(final EObject oldObject, final EClass newClass) { checkNotNull(oldObject, "Precondition violation - argument 'oldObject' must not be NULL!"); checkNotNull(newClass, "Precondition violation - argument 'newClass' must not be NULL!"); return this.newTx.createAndAttach(newClass, ((ChronoEObject) oldObject).getId()); } @Override public EObject getCorrespondingEObjectInOldModel(final EObject newEObject) { checkNotNull(newEObject, "Precondition violation - argument 'newEObject' must not be NULL!"); return this.oldTx.getEObjectById(((ChronoEObject) newEObject).getId()); } @Override public EObject getCorrespondingEObjectInNewModel(final EObject oldEObject) { checkNotNull(oldEObject, "Precondition violation - argument 'oldEObject' must not be NULL!"); return this.newTx.getEObjectById(((ChronoEObject) oldEObject).getId()); } @Override public void deleteInNewModel(final EObject newObject) { checkNotNull(newObject, "Precondition violation - argument 'newObject' must not be NULL!"); EObject obj = this.getCorrespondingEObjectInNewModel(newObject); if (obj != null) { this.newTx.delete(obj); } } }
4,630
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MetaModelEvolutionProcess.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/evolution/MetaModelEvolutionProcess.java
package org.chronos.chronosphere.impl.evolution; import org.chronos.chronosphere.api.*; import org.chronos.chronosphere.api.exceptions.MetaModelEvolutionCanceledException; import org.chronos.chronosphere.internal.api.ChronoSphereEPackageManagerInternal; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import java.util.Iterator; import static com.google.common.base.Preconditions.*; public class MetaModelEvolutionProcess { public static boolean execute(final ChronoSphere repository, final String branch, final MetaModelEvolutionIncubator incubator, final Iterable<? extends EPackage> newEPackages) { checkNotNull(repository, "Precondition violation - argument 'repository' must not be NULL!"); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(incubator, "Precondition violation - argument 'incubator' must not be NULL!"); MetaModelEvolutionController controller = new IncubatorBasedModelEvolutionController(incubator); return execute(repository, branch, controller, newEPackages); } public static boolean execute(final ChronoSphere repository, final String branch, final MetaModelEvolutionController controller, final Iterable<? extends EPackage> newEPackages) { checkNotNull(repository, "Precondition violation - argument 'repository' must not be NULL!"); checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(controller, "Precondition violation - argument 'controller' must not be NULL!"); // this is going to be our transaction for querying the "old" state ChronoSphereTransaction oldTx = repository.tx(branch); // this is going to be our transaction for writing and querying the "new" state ChronoSphereTransaction newTx = repository.tx(branch); try { // create the context MetaModelEvolutionContext context = new ModelEvolutionContextImpl(repository, branch, oldTx, newTx); // create the new epackages in the graph ((ChronoSphereEPackageManagerInternal) repository.getEPackageManager()).overrideEPackages(newTx, newEPackages); newTx.commitIncremental(); // delete all existing EObjects to start from an empty instance graph Iterator<EObject> allEObjects = newTx.find().startingFromAllEObjects().toIterator(); newTx.delete(allEObjects, false); newTx.commitIncremental(); // invoke the controller controller.migrate(context); // commit the changes (it's very likely that there have been incremental commits in between) newTx.commit(); // roll back the old transaction oldTx.rollback(); // migration successful return true; } catch (MetaModelEvolutionCanceledException e) { // migration failed return false; } finally { // roll back any uncommitted changes if (oldTx != null && oldTx.isOpen()) { oldTx.rollback(); } if (newTx != null && newTx.isOpen()) { newTx.rollback(); } } } }
3,371
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IncubatorBasedModelEvolutionController.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/evolution/IncubatorBasedModelEvolutionController.java
package org.chronos.chronosphere.impl.evolution; import org.chronos.chronosphere.api.MetaModelEvolutionContext; import org.chronos.chronosphere.api.MetaModelEvolutionController; import org.chronos.chronosphere.api.MetaModelEvolutionIncubator; import org.chronos.chronosphere.api.exceptions.ElementCannotBeEvolvedException; import org.chronos.chronosphere.api.exceptions.MetaModelEvolutionCanceledException; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import java.util.Iterator; import static com.google.common.base.Preconditions.*; public class IncubatorBasedModelEvolutionController implements MetaModelEvolutionController { // ===================================================================================================================== // FIELDS // ===================================================================================================================== protected final MetaModelEvolutionIncubator incubator; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public IncubatorBasedModelEvolutionController(final MetaModelEvolutionIncubator incubator) { checkNotNull(incubator, "Precondition violation - argument 'incubator' must not be NULL!"); this.incubator = incubator; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public void migrate(final MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException { checkNotNull(context, "Precondition violation - argument 'context' must not be NULL!"); // phase 1: migrate the EObjects from an old EClass to a new one this.executeClassEvolutionPhase(context); context.flush(); // phase 2: migrate individual property values this.executePropertyEvolutionPhase(context); context.flush(); // phase 3: migrate references this.executeReferenceEvolutionPhase(context); context.flush(); } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== protected void executeClassEvolutionPhase(final MetaModelEvolutionContext context) { // iterate over all elements from the old model Iterator<EObject> elementIterator = context.findInOldModel().startingFromAllEObjects().toIterator(); while (elementIterator.hasNext()) { EObject oldObject = elementIterator.next(); // ask the incubator which EClass this object should have in the new model try { EClass eClass = this.incubator.migrateClass(oldObject, context); if (eClass == null) { // no eclass is specified... we have to discard the element continue; } // create a new EObject in the new model state context.createAndAttachEvolvedEObject(oldObject, eClass); } catch (ElementCannotBeEvolvedException ignored) { // this element cannot be evolved; simply do not include it in the // new repository state } } } protected void executePropertyEvolutionPhase(final MetaModelEvolutionContext context) { // iterate over all elements from the new model (remember: we already transferred // the "plain" EObjects without contents from the old to the new model in phase 1) Iterator<EObject> elementIterator = context.findInNewModel().startingFromAllEObjects().toIterator(); while (elementIterator.hasNext()) { EObject newObject = elementIterator.next(); // find the corresponding old object EObject oldObject = context.getCorrespondingEObjectInOldModel(newObject); try { // ask the incubator to do the translation of attribute values this.incubator.updateAttributeValues(oldObject, newObject, context); } catch (ElementCannotBeEvolvedException e) { // the incubator realized during attribute value evolution that this // EObject cannot be migrated. We have to delete it from the new model, // because we have already persisted it during phase 1. context.deleteInNewModel(newObject); } } } protected void executeReferenceEvolutionPhase(final MetaModelEvolutionContext context) { // iterate over all elements from the new model (remember: we already transferred // the "plain" EObjects without contents from the old to the new model in phase 1) Iterator<EObject> elementIterator = context.findInNewModel().startingFromAllEObjects().toIterator(); while (elementIterator.hasNext()) { EObject newObject = elementIterator.next(); // find the corresponding old object EObject oldObject = context.getCorrespondingEObjectInOldModel(newObject); try { // ask the incubator to do the trnaslation of reference targets this.incubator.updateReferenceTargets(oldObject, newObject, context); } catch (ElementCannotBeEvolvedException e) { // the incubator realized during reference target evolution that this // EObject cannot be migrated. We have to delete it from the new model, // because we have already persisted it during phase 1 and 2. context.deleteInNewModel(newObject); } } } }
6,119
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereTransactionImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/transaction/ChronoSphereTransactionImpl.java
package org.chronos.chronosphere.impl.transaction; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import com.google.common.cache.LoadingCache; import org.apache.commons.lang3.tuple.Pair; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronodb.internal.util.IteratorUtils; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronograph.api.transaction.ChronoGraphTransaction; import org.chronos.chronosphere.api.SphereBranch; import org.chronos.chronosphere.api.query.QueryStepBuilderStarter; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.impl.ChronoEFactory; import org.chronos.chronosphere.emf.impl.ChronoEObjectImpl; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.chronos.chronosphere.emf.internal.impl.store.ChronoGraphEStore; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.impl.query.QueryStepBuilderStarterImpl; import org.chronos.chronosphere.internal.api.ChronoSphereInternal; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.chronos.chronosphere.internal.ogm.api.VertexKind; import org.chronos.common.util.CacheUtils; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.EcoreUtil; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class ChronoSphereTransactionImpl implements ChronoSphereTransactionInternal { // ================================================================================================================= // FIELDS // ================================================================================================================= private ChronoEPackageRegistry ePackageRegistry; private final ChronoSphereInternal owningSphere; private final ChronoGraph txGraph; private final ChronoGraphTransaction tx; private final ChronoGraphEStore graphEStore; private boolean closed; private final LoadingCache<String, ChronoEObject> eObjectCache; // ================================================================================================================= // CONSTRUCTORS // ================================================================================================================= public ChronoSphereTransactionImpl(final ChronoSphereInternal owningSphere, final ChronoGraph txGraph) { checkNotNull(owningSphere, "Precondition violation - argument 'owningSphere' must not be NULL!"); checkNotNull(txGraph, "Precondition violation - argument 'txGraph' must not be NULL!"); this.owningSphere = owningSphere; this.txGraph = txGraph; this.tx = txGraph.tx().getCurrentTransaction(); this.eObjectCache = CacheUtils.buildWeak(this::loadEObjectById); this.ePackageRegistry = this.owningSphere.getEPackageToGraphMapper() .readChronoEPackageRegistryFromGraph(txGraph); this.graphEStore = new ChronoGraphEStore(this); } // ================================================================================================================= // TRANSACTION METADATA // ================================================================================================================= @Override public long getTimestamp() { return this.tx.getTimestamp(); } @Override public SphereBranch getBranch() { return this.owningSphere.getBranchManager().getBranch(this.tx.getBranchName()); } // ================================================================================================================= // ATTACHMENT & DELETION OPERATIONS // ================================================================================================================= @Override public EObject createAndAttach(final EClass eClass) { checkArgument(this.getEPackageRegistry().getEClassID(eClass) != null, "Precondition violation - the given EClass is not known in the repository!"); checkArgument(eClass.getEPackage().getEFactoryInstance() instanceof ChronoEFactory, "Precondition violation - the given EClass is not known in the repository!"); EObject eObject = EcoreUtil.create(eClass); this.attach(eObject); return eObject; } @Override public EObject createAndAttach(final EClass eClass, final String eObjectID) { checkArgument(this.getEPackageRegistry().getEClassID(eClass) != null, "Precondition violation - the given EClass is not known in the repository!"); checkArgument(eClass.getEPackage().getEFactoryInstance() instanceof ChronoEFactory, "Precondition violation - the given EClass is not known in the repository!"); checkNotNull(eObjectID, "Precondition violation - argument 'eObjectID' must not be NULL!"); EObject eObject = new ChronoEObjectImpl(eObjectID, eClass); this.attach(eObject); return eObject; } @Override public void attach(final EObject eObject) { ChronoEObjectInternal eObjectInternal = this.assertIsChronoEObject(eObject); if (eObjectInternal.isAttached()) { // already attached to the store, nothing to do return; } this.attach(Collections.singleton(eObject)); } @Override public void attach(final Iterable<? extends EObject> eObjects) { checkNotNull(eObjects, "Precondition violation - argument 'eObjects' must not be NULL!"); this.attach(eObjects.iterator()); } @Override public void attach(final Iterator<? extends EObject> eObjects) { checkNotNull(eObjects, "Precondition violation - argument 'eObjects' must not be NULL!"); this.attach(eObjects, false); } @Override public void delete(final EObject eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); this.delete(Collections.singleton(eObject)); } @Override public void delete(final Iterator<? extends EObject> eObjects, final boolean cascadeDeletionToEContents) { checkNotNull(eObjects, "Precondition violation - argument 'eObjects' must not be NULL!"); if (eObjects.hasNext() == false) { return; } // consider only attached EObjects Set<ChronoEObjectInternal> eObjectsToDelete = IteratorUtils.stream(eObjects) // only consider our internal EObjects (anything else can't be added anyways) .filter(eObject -> eObject instanceof ChronoEObjectInternal) .map(eObject -> (ChronoEObjectInternal) eObject) // consider only the ones that are currently attached .filter(eObject -> eObject.isAttached()) // collect them in a set .collect(Collectors.toSet()); if (eObjectsToDelete.isEmpty()) { // there's nothing to delete return; } Set<String> idsToInvalidate = eObjectsToDelete.stream().map(ChronoEObject::getId).collect(Collectors.toSet()); this.getGraphEStore().deepDelete(eObjectsToDelete, cascadeDeletionToEContents); this.eObjectCache.invalidateAll(idsToInvalidate); } // ================================================================================================================= // EPACKAGE HANDLING // ================================================================================================================= @Override public EPackage getEPackageByNsURI(final String namespaceURI) { checkNotNull(namespaceURI, "Precondition violation - argument 'namespaceURI' must not be NULL!"); this.assertNotClosed(); return this.getEPackageRegistry().getEPackage(namespaceURI); } @Override public Set<EPackage> getEPackages() { this.assertNotClosed(); return Collections.unmodifiableSet(this.getEPackageRegistry().getEPackages()); } @Override public EPackage getEPackageByQualifiedName(final String qualifiedName) { checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return EMFUtils.getEPackageByQualifiedName(this.getEPackages(), qualifiedName); } @Override public EClassifier getEClassifierByQualifiedName(final String qualifiedName) { checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return EMFUtils.getEClassifierByQualifiedName(this.getEPackages(), qualifiedName); } @Override public EClass getEClassByQualifiedName(final String qualifiedName) { checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return EMFUtils.getEClassByQualifiedName(this.getEPackages(), qualifiedName); } @Override public EStructuralFeature getFeatureByQualifiedName(final String qualifiedName) { checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return EMFUtils.getFeatureByQualifiedName(this.getEPackages(), qualifiedName); } @Override public EAttribute getEAttributeByQualifiedName(final String qualifiedName) { checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return EMFUtils.getEAttributeByQualifiedName(this.getEPackages(), qualifiedName); } @Override public EReference getEReferenceByQualifiedName(final String qualifiedName) { checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return EMFUtils.getEReferenceByQualifiedName(this.getEPackages(), qualifiedName); } @Override public EPackage getEPackageBySimpleName(final String simpleName) { checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return EMFUtils.getEPackageBySimpleName(this.getEPackages(), simpleName); } @Override public EClassifier getEClassifierBySimpleName(final String simpleName) { checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return EMFUtils.getEClassifierBySimpleName(this.getEPackages(), simpleName); } @Override public EClass getEClassBySimpleName(final String simpleName) { checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return EMFUtils.getEClassBySimpleName(this.getEPackages(), simpleName); } // ================================================================================================================= // QUERY & RETRIEVAL OPERATIONS // ================================================================================================================= @Override public ChronoEObject getEObjectById(final String eObjectID) { checkNotNull(eObjectID, "Precondition violation - argument 'eObjectID' must not be NULL!"); try { return this.eObjectCache.get(eObjectID); } catch (ExecutionException e) { throw new RuntimeException("Failed to load EObject with ID '" + eObjectID + "'!", e); } } @Override public Map<String, ChronoEObject> getEObjectById(final Iterable<String> eObjectIDs) { checkNotNull(eObjectIDs, "Precondition violation - argument 'eObjectIDs' must not be NULL!"); return this.getEObjectById(eObjectIDs.iterator()); } @Override public Map<String, ChronoEObject> getEObjectById(final Iterator<String> eObjectIDs) { checkNotNull(eObjectIDs, "Precondition violation - argument 'eObjectIDs' must not be NULL!"); Map<String, ChronoEObject> resultMap = Maps.newHashMap(); eObjectIDs.forEachRemaining(id -> { ChronoEObject eObject = this.getEObjectById(id); resultMap.put(id, eObject); }); return resultMap; } @Override public QueryStepBuilderStarter find() { return new QueryStepBuilderStarterImpl(this); } // ================================================================================================================= // HISTORY ANALYSIS // ================================================================================================================= @Override public Iterator<Long> getEObjectHistory(final EObject eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); if (eObject instanceof ChronoEObjectInternal == false) { return Collections.emptyIterator(); } ChronoEObjectInternal eObjectInternal = (ChronoEObjectInternal) eObject; String id = eObjectInternal.getId(); return this.txGraph.getVertexHistory(id); } @Override public Iterator<Pair<Long, String>> getEObjectModificationsBetween(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 strictly smaller than argument 'timestampUpperBound'!"); return this.txGraph.getVertexModificationsBetween(timestampLowerBound, timestampUpperBound); } // ================================================================================================================= // TRANSACTION CONTROL METHODS // ================================================================================================================= @Override public void commit() { this.assertNotClosed(); this.tx.commit(); this.eObjectCache.invalidateAll(); this.closed = true; } @Override public void commit(final Object commitMetadata) { this.assertNotClosed(); this.tx.commit(commitMetadata); this.eObjectCache.invalidateAll(); this.closed = true; } @Override public void commitIncremental() { this.assertNotClosed(); this.eObjectCache.invalidateAll(); this.tx.commitIncremental(); } @Override public void rollback() { this.assertNotClosed(); this.tx.rollback(); this.eObjectCache.invalidateAll(); this.closed = true; } @Override public boolean isClosed() { return this.closed || this.tx.isOpen() == false; } @Override public boolean isOpen() { return this.isClosed() == false; } @Override public void close() { if (this.isClosed()) { return; } this.rollback(); this.txGraph.close(); this.closed = true; } // ================================================================================================================= // INTERNAL API // ================================================================================================================= @Override public ChronoSphereInternal getOwningSphere() { return this.owningSphere; } @Override public ChronoGraph getGraph() { return this.txGraph; } @Override public ChronoGraphEStore getGraphEStore() { return this.graphEStore; } @Override public ChronoEPackageRegistry getEPackageRegistry() { this.assertNotClosed(); return this.ePackageRegistry; } @Override public void batchInsert(final Iterator<EObject> model) { checkNotNull(model, "Precondition violation - argument 'model' must not be NULL!"); this.attach(model, true); } @Override public void reloadEPackageRegistryFromGraph() { this.ePackageRegistry = this.owningSphere.getEPackageToGraphMapper() .readChronoEPackageRegistryFromGraph(this.txGraph); } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= private void assertNotClosed() { if (this.isClosed()) { throw new IllegalStateException("This ChronoSphereTransaction was already closed!"); } } private ChronoEObjectInternal assertIsChronoEObject(final EObject eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkArgument(eObject instanceof ChronoEObject, "Precondition violation - argument 'eObject' is no ChronoEObject! Did you use the correct EFactory in your EPackage?"); return (ChronoEObjectInternal) eObject; } private ChronoEObject createEObjectFromVertex(final Vertex vertex) { checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkArgument(VertexKind.EOBJECT.equals(ChronoSphereGraphFormat.getVertexKind(vertex)), "Precondition violation - the given vertex does not represent an EObject!"); EClass eClass = ChronoSphereGraphFormat.getEClassForEObjectVertex(this.getEPackageRegistry(), vertex); return new ChronoEObjectImpl((String) vertex.id(), eClass, this.getGraphEStore()); } private void attach(final Iterator<? extends EObject> eObjects, final boolean useIncrementalCommits) { checkNotNull(eObjects, "Precondition violation - argument 'eObjects' must not be NULL!"); List<ChronoEObjectInternal> mergeObjects = Lists.newArrayList(); eObjects.forEachRemaining(eObject -> { ChronoEObjectInternal eObjectInternal = this.assertIsChronoEObject(eObject); if (eObjectInternal.isAttached()) { // already attached, skip it return; } mergeObjects.add(eObjectInternal); }); if (useIncrementalCommits) { int batchSize = this.getOwningSphere().getConfiguration().getBatchInsertBatchSize(); this.getGraphEStore().deepMergeIncremental(mergeObjects, this, batchSize); } else { this.getGraphEStore().deepMerge(mergeObjects); } } private ChronoEObject loadEObjectById(final String eObjectID) { Vertex vertex = ChronoSphereGraphFormat.getVertexForEObject(this.getGraph(), eObjectID); if(vertex == null){ return null; } return this.createEObjectFromVertex(vertex); } }
17,998
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereFactory.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/ChronoSphereFactory.java
package org.chronos.chronosphere.api; import org.chronos.chronosphere.api.builder.repository.ChronoSphereBaseBuilder; import org.chronos.chronosphere.impl.ChronoSphereFactoryImpl; /** * This is the factory for {@link ChronoSphere} instances, and the entry point to the fluent builder API. * * <p> * You can get the singleton instance of this class via {@link ChronoSphere#FACTORY}, or via * {@link ChronoSphereFactory#INSTANCE}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoSphereFactory { /** The singleton instance of this factory. */ public static ChronoSphereFactory INSTANCE = new ChronoSphereFactoryImpl(); /** * Creates a new builder for a {@link ChronoSphere} repository. * * @return The repository builder, for method chaining. Never <code>null</code>. */ public ChronoSphereBaseBuilder create(); }
888
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MetaModelEvolutionContext.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/MetaModelEvolutionContext.java
package org.chronos.chronosphere.api; import java.util.Set; import org.chronos.chronosphere.api.query.QueryStepBuilderStarter; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; public interface MetaModelEvolutionContext { public EPackage getOldEPackage(String namespaceURI); public EPackage getNewEPackage(String namespaceURI); public Set<EPackage> getOldEPackages(); public Set<EPackage> getNewEPackages(); public SphereBranch getMigrationBranch(); public QueryStepBuilderStarter findInOldModel(); public QueryStepBuilderStarter findInNewModel(); public void flush(); public EObject createAndAttachEvolvedEObject(EObject oldObject, EClass newClass); public EObject getCorrespondingEObjectInOldModel(EObject newEObject); public EObject getCorrespondingEObjectInNewModel(EObject oldEObject); public void deleteInNewModel(EObject newObject); }
934
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphere.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/ChronoSphere.java
package org.chronos.chronosphere.api; import static com.google.common.base.Preconditions.*; import java.io.File; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.exceptions.InvalidTransactionBranchException; import org.chronos.chronodb.api.exceptions.InvalidTransactionTimestampException; import org.chronos.chronosphere.emf.impl.ChronoEObjectImpl; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.internal.configuration.api.ChronoSphereConfiguration; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import com.google.common.collect.Iterators; /** * This is the main repository interface, it represents the whole model repository. * * <p> * To get an instance of this class, please use the fluent builder API: * * <pre> * ChronoSphere repository = ChronoSphere.FACTORY.create() /{@literal*}... settings ... {@literal*}/ .buildLRU(); * </pre> * * After creating this class, you should set up your {@link EPackage}s through the methods provided by * {@link #getEPackageManager()}. Then, you can use the various overloads of {@link #tx()} to create * {@linkplain ChronoSphereTransaction transactions} for working with the contents of the repository. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoSphere extends AutoCloseable { // ===================================================================================================================== // CONSTANTS // ===================================================================================================================== /** This is the singleton factory instance for {@link ChronoSphere}s. */ public static final ChronoSphereFactory FACTORY = ChronoSphereFactory.INSTANCE; // ===================================================================================================================== // CONFIGURATION // ===================================================================================================================== /** * Returns the {@linkplain ChronoSphereConfiguration configuration} of this {@link ChronoSphere} instance. * * @return The configuration. Never <code>null</code>. */ public ChronoSphereConfiguration getConfiguration(); // ===================================================================================================================== // TRANSACTION MANAGEMENT // ===================================================================================================================== /** * Produces and returns a new instance of {@link ChronoSphereTransaction} on the <i>master</i> branch <i>head</i> * version. * * <p> * Note that transactions are in general not thread-safe and must not be shared among threads. * * @return The transaction. Never <code>null</code>. */ public ChronoSphereTransaction tx(); /** * Produces and returns a new instance of {@link ChronoSphereTransaction} on the <i>master</i> branch at the given * timestamp. * * <p> * Please note that implementations may choose to refuse opening a transaction on certain timestamps, e.g. when the * desired timestamp is in the future. In such cases, an {@link InvalidTransactionTimestampException} is thrown. * * <p> * Note that transactions are in general not thread-safe and must not be shared among threads. * * @param timestamp * The timestamp to use. Must not be negative. * * @return The transaction. Never <code>null</code>. * * @throws InvalidTransactionTimestampException * Thrown if the transaction could not be opened due to an invalid timestamp. */ public ChronoSphereTransaction tx(final long timestamp) throws InvalidTransactionTimestampException; /** * Produces and returns a new instance of {@link ChronoSphereTransaction} on the <i>master</i> branch at the given * date. * * <p> * Please note that implementations may choose to refuse opening a transaction on certain dates, e.g. when the * desired date is in the future. In such cases, an {@link InvalidTransactionTimestampException} is thrown. * * <p> * Note that transactions are in general not thread-safe and must not be shared among threads. * * @param date * The date to use. Must not be negative. * * @return The transaction. Never <code>null</code>. * * @throws InvalidTransactionTimestampException * Thrown if the transaction could not be opened due to an invalid timestamp. */ public ChronoSphereTransaction tx(final Date date) throws InvalidTransactionTimestampException; /** * Produces and returns a new instance of {@link ChronoSphereTransaction} on the <i>head</i> version of the given * branch. * * <p> * Note that transactions are in general not thread-safe and must not be shared among threads. * * @param branchName * The name of the branch to start a transaction on. Must not be <code>null</code>. Must be the name of * an existing branch. * * @return The transaction. Never <code>null</code>. * * @throws InvalidTransactionBranchException * Thrown if the transaction could not be opened due to an invalid branch name. */ public ChronoSphereTransaction tx(final String branchName) throws InvalidTransactionBranchException; /** * Produces and returns a new instance of {@link ChronoSphereTransaction} at the given timestamp on the given * branch. * * <p> * Please note that implementations may choose to refuse opening a transaction on certain timestamps, e.g. when the * desired timestamp is in the future. In such cases, an {@link InvalidTransactionTimestampException} is thrown. * * <p> * Note that transactions are in general not thread-safe and must not be shared among threads. * * @param branchName * The name of the branch to start a transaction on. Must not be <code>null</code>. Must be the name of * an existing branch. * @param timestamp * The timestamp to use. Must not be negative. * * @return The transaction. Never <code>null</code>. * * @throws InvalidTransactionBranchException * Thrown if the transaction could not be opened due to an invalid branch. * @throws InvalidTransactionTimestampException * Thrown if the transaction could not be opened due to an invalid timestamp. */ public ChronoSphereTransaction tx(final String branchName, final long timestamp) throws InvalidTransactionBranchException, InvalidTransactionTimestampException; /** * Produces and returns a new instance of {@link ChronoSphereTransaction} at the given date on the given branch. * * <p> * Please note that implementations may choose to refuse opening a transaction on certain dates, e.g. when the * desired date is in the future. In such cases, an {@link InvalidTransactionTimestampException} is thrown. * * <p> * Note that transactions are in general not thread-safe and must not be shared among threads. * * @param branchName * The name of the branch to start a transaction on. Must not be <code>null</code>. Must be the name of * an existing branch. * @param date * The date to use. Must not be negative. * * @return The transaction. Never <code>null</code>. * * @throws InvalidTransactionBranchException * Thrown if the transaction could not be opened due to an invalid branch. * @throws InvalidTransactionTimestampException * Thrown if the transaction could not be opened due to an invalid timestamp. */ public ChronoSphereTransaction tx(final String branchName, final Date date) throws InvalidTransactionBranchException, InvalidTransactionTimestampException; // ===================================================================================================================== // BULK INSERTION // ===================================================================================================================== /** * Batch-inserts the {@link EObject} model data from the given XMI content into the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param xmiContent * The XMI content to load. This string must contain the actual XMI contents. Must not be * <code>null</code>, must be syntactically valid XMI. * * @see #batchInsertModelData(File) */ public default void batchInsertModelData(final String xmiContent) { checkNotNull(xmiContent, "Precondition violation - argument 'xmiContent' must not be NULL!"); this.batchInsertModelData(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, xmiContent); } /** * Batch-inserts the {@link EObject} model data from the given XMI content into the given branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param branch * The branch to load the model elements into. Must not be <code>null</code>, must refer to an existing * branch. * @param xmiContent * The XMI content to load. This string must contain the actual XMI contents. Must not be * <code>null</code>, must be syntactically valid XMI. * * @see #batchInsertModelData(String, File) */ public default void batchInsertModelData(final String branch, final String xmiContent) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(this.getBranchManager().existsBranch(branch), "Precondition violation - argument 'branch' must refer to an existing branch!"); checkNotNull(xmiContent, "Precondition violation - argument 'xmiContent' must not be NULL!"); Set<EPackage> ePackages = this.getEPackageManager().getRegisteredEPackages(); List<EObject> eObjectsFromXMI = EMFUtils.readEObjectsFromXMI(xmiContent, ePackages); this.batchInsertModelData(branch, eObjectsFromXMI); } /** * Batch-inserts the {@link EObject} model data from the given XMI file into the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param xmiFile * The XMI file to load. Must not be <code>null</code>, must exist, must be a file, must have a file name * ending with <code>*.xmi</code>, and must contain syntactically valid XMI data. */ public default void batchInsertModelData(final File xmiFile) { checkNotNull(xmiFile, "Precondition violation - argument 'xmiFile' must not be NULL!"); EMFUtils.assertIsXMIFile(xmiFile); this.batchInsertModelData(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, xmiFile); } /** * Batch-inserts the {@link EObject} model data from the given XMI file into the given branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param branch * The branch to load the model elements into. Must not be <code>null</code>, must refer to an existing * branch. * @param xmiFile * The XMI file to load. Must not be <code>null</code>, must exist, must be a file, must have a file name * ending with <code>*.xmi</code>, and must contain syntactically valid XMI data. */ public default void batchInsertModelData(final String branch, final File xmiFile) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(this.getBranchManager().existsBranch(branch), "Precondition violation - argument 'branch' must refer to an existing branch!"); checkNotNull(xmiFile, "Precondition violation - argument 'xmiFile' must not be NULL!"); EMFUtils.assertIsXMIFile(xmiFile); ResourceSet resourceSet = EMFUtils.createResourceSet(); for (EPackage ePackage : this.getEPackageManager().getRegisteredEPackages()) { resourceSet.getPackageRegistry().put(ePackage.getNsURI(), ePackage); } Resource resource = resourceSet.getResource(URI.createFileURI(xmiFile.getAbsolutePath()), true); this.batchInsertModelData(branch, resource.getContents()); } /** * Batch-inserts the given {@link EObject} model data into the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param model * The {@link EObject} model to insert into the repository. Must not be <code>null</code>. All elements * must be an instance of {@link ChronoEObjectImpl}. All {@linkplain EObject#eAllContents() contained} * EObjects will be batch-loaded, recursively. */ public default void batchInsertModelData(final EObject model) { checkNotNull(model, "Precondition violation - argument 'model' must not be NULL!"); checkArgument(model instanceof ChronoEObjectInternal, "Precondition violation - argument 'model' is no ChronoEObject!"); ChronoEObjectInternal chronoEObject = (ChronoEObjectInternal) model; checkArgument(chronoEObject.isAttached() == false, "Precondition violation - the given EObject is already attached to a repository!"); this.batchInsertModelData(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, model); } /** * Batch-inserts the given {@link EObject} model data into the given branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param branch * The branch to load the model elements into. Must not be <code>null</code>, must refer to an existing * branch. * @param model * The {@link EObject} model to insert into the repository. Must not be <code>null</code>. All elements * must be an instance of {@link ChronoEObjectImpl}. All {@linkplain EObject#eAllContents() contained} * EObjects will be batch-loaded, recursively. */ public default void batchInsertModelData(final String branch, final EObject model) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(this.getBranchManager().existsBranch(branch), "Precondition violation - argument 'branch' must refer to an existing branch!"); checkNotNull(model, "Precondition violation - argument 'model' must not be NULL!"); checkArgument(model instanceof ChronoEObjectInternal, "Precondition violation - argument 'model' is no ChronoEObject!"); ChronoEObjectInternal chronoEObject = (ChronoEObjectInternal) model; checkArgument(chronoEObject.isAttached() == false, "Precondition violation - the given EObject is already attached to a repository!"); this.batchInsertModelData(branch, Iterators.singletonIterator(model)); } /** * Batch-inserts the given {@link EObject} model data into the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param model * The {@link EObject} model to insert into the repository. Must not be <code>null</code>. All elements * must be an instance of {@link ChronoEObjectImpl}. All {@linkplain EObject#eAllContents() contained} * EObjects will be batch-loaded, recursively. */ public default void batchInsertModelData(final Iterable<EObject> model) { checkNotNull(model, "Precondition violation - argument 'model' must not be NULL!"); this.batchInsertModelData(model.iterator()); } /** * Batch-inserts the given {@link EObject} model data into the given branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param branch * The branch to load the model elements into. Must not be <code>null</code>, must refer to an existing * branch. * @param model * The {@link EObject} model to insert into the repository. Must not be <code>null</code>. All elements * must be an instance of {@link ChronoEObjectImpl}. All {@linkplain EObject#eAllContents() contained} * EObjects will be batch-loaded, recursively. */ public default void batchInsertModelData(final String branch, final Iterable<EObject> model) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(model, "Precondition violation - argument 'model' must not be NULL!"); checkArgument(this.getBranchManager().existsBranch(branch), "Precondition violation - argument 'branch' does not refer to an existing branch!"); this.batchInsertModelData(branch, model.iterator()); } /** * Batch-inserts the given {@link EObject} model data into the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param model * The {@link EObject} model to insert into the repository. Must not be <code>null</code>. All elements * must be an instance of {@link ChronoEObjectImpl}. All {@linkplain EObject#eAllContents() contained} * EObjects will be batch-loaded, recursively. */ public default void batchInsertModelData(final Iterator<EObject> model) { checkNotNull(model, "Precondition violation - argument 'model' must not be NULL!"); this.batchInsertModelData(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, model); } /** * Batch-inserts the given {@link EObject} model data into the given branch of this repository. * * <p> * Please remember to {@linkplain ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) register} your * {@link EPackage}s before calling this method. * * <p> * Only one batch insert process can be active at any point in time. Any other write transactions will be denied * while this process is running. * * @param branch * The branch to load the model elements into. Must not be <code>null</code>, must refer to an existing * branch. * @param model * The {@link EObject} model to insert into the repository. Must not be <code>null</code>. All elements * must be an instance of {@link ChronoEObjectImpl}. All {@linkplain EObject#eAllContents() contained} * EObjects will be batch-loaded, recursively. */ public void batchInsertModelData(String branch, Iterator<EObject> model); // ===================================================================================================================== // BRANCH MANAGEMENT // ===================================================================================================================== /** * Returns the {@linkplain ChronoSphereBranchManager branch manager} associated with this {@link ChronoSphere} * instance. * * @return The branch manager. Never <code>null</code>. */ public ChronoSphereBranchManager getBranchManager(); // ===================================================================================================================== // INDEX MANAGEMENT // ===================================================================================================================== /** * Returns the {@linkplain ChronoSphereIndexManager index manager} associated with the master branch of this * {@link ChronoSphere} instance. * * @return The index manager for the master branch. Never <code>null</code>. */ public default ChronoSphereIndexManager getIndexManager() { return this.getIndexManager(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } /** * Returns the {@linkplain ChronoSphereIndexManager index manager} associated with the given branch. * * @param branchName * The name of the branch to get the index manager for. Must not be <code>null</code>, must refer to an * existing branch. * @return The index manager for the given branch. Never <code>null</code>. */ public ChronoSphereIndexManager getIndexManager(String branchName); // ================================================================================================================= // PACKAGE MANAGEMENT // ================================================================================================================= /** * Returns the {@linkplain ChronoSphereEPackageManager EPackage manager} associated with this {@link ChronoSphere} * instance. * * @return The EPackage manager. Never <code>null</code>. */ public ChronoSphereEPackageManager getEPackageManager(); // ===================================================================================================================== // CLOSE HANDLING // ===================================================================================================================== /** * Closes this {@link ChronoSphere} instance. * * <p> * Any further attempt to work with this instance will give rise to an appropriate exception, unless noted * explicitly in the method documentation. * * <p> * This method is safe to use on closed instances. When called on an already closed instance, this method is a no-op * and returns immediately. */ @Override public void close(); /** * Checks if this {@link ChronoSphere} instance is closed or not. * * <p> * This method is safe to use on closed instances. * * @return <code>true</code> if this instance is closed, or <code>false</code> if it is still open. * * @see #close() * @see #isOpen() */ public boolean isClosed(); /** * Checks if this {@link ChronoSphere} instance is still open. * * <p> * This method is safe to use on closed instances. * * @return <code>true</code> if this instance is open, or <code>false</code> if it is already closed. * * @see #close() * @see #isClosed() */ public default boolean isOpen() { return this.isClosed() == false; } /** * Returns the "now" timestamp, i.e. the timestamp of the latest commit on the repository, on the master branch. * * <p> * Requesting a transaction on this timestamp will always deliver a transaction on the "head" revision. * * @return The "now" timestamp. Will be zero if no commit has been taken place yet, otherwise a positive value. */ public default long getNow() { return this.getNow(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } /** * Returns the "now" timestamp, i.e. the timestamp of the latest commit on the repository, on the given branch. * * <p> * Requesting a transaction on this timestamp will always deliver a transaction on the "head" revision. * * @param branchName * The name of the branch to retrieve the "now" timestamp for. Must refer to an existing branch. Must not * be <code>null</code>. * * @return The "now" timestamp on the given branch. If no commits have occurred on the branch yet, this method * returns zero (master branch) or the branching timestamp (non-master branch), otherwise a positive value. */ public long getNow(String branchName); // ================================================================================================================= // HISTORY ANALYSIS // ================================================================================================================= /** * Returns the metadata for the commit on the {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch * at the given timestamp. * * <p> * This search will include origin branches (recursively), if the timestamp is after the branching timestamp. * * @param timestamp * The timestamp to get the commit metadata for. Must match the commit timestamp exactly. Must not be * negative. * * @return The commit metadata. May be <code>null</code> if there was no metadata for the commit, or there has not * been a commit at the specified branch and timestamp. */ public default Object getCommitMetadata(final long timestamp) { return this.getCommitMetadata(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, timestamp); } /** * Returns the metadata for the commit on the given branch at the given timestamp. * * <p> * This search will include origin branches (recursively), if the timestamp is after the branching timestamp. * * @param branch * The branch to search for the commit metadata in. Must not be <code>null</code>. * @param timestamp * The timestamp to get the commit metadata for. Must match the commit timestamp exactly. Must not be * negative. * * @return The commit metadata. May be <code>null</code> if there was no metadata for the commit, or there has not * been a commit at the specified branch and timestamp. */ public Object getCommitMetadata(String branch, long timestamp); /** * Returns an iterator over all timestamps where commits have occurred on the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch, bounded between <code>from</code> and * <code>to</code>, in descending order. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * * @return The iterator over the commit timestamps in the given time range, in descending order. May be empty, but * never <code>null</code>. */ public default Iterator<Long> getCommitTimestampsBetween(final long from, final long to) { return this.getCommitTimestampsBetween(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, from, to); } /** * Returns an iterator over all timestamps where commits have occurred on the given branch, bounded between * <code>from</code> and <code>to</code>, in descending order. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * * @return The iterator over the commit timestamps in the given time range, in descending order. May be empty, but * never <code>null</code>. */ public default Iterator<Long> getCommitTimestampsBetween(final String branch, final long from, final long to) { return this.getCommitTimestampsBetween(branch, from, to, Order.DESCENDING); } /** * Returns an iterator over all timestamps where commits have occurred on the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch, bounded between <code>from</code> and * <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param order * The order of the returned timestamps. Must not be <code>null</code>. * * @return The iterator over the commit timestamps in the given time range. May be empty, but never * <code>null</code>. */ public default Iterator<Long> getCommitTimestampsBewteen(final long from, final long to, final Order order) { return this.getCommitTimestampsBetween(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, from, to, order); } /** * Returns an iterator over all timestamps where commits have occurred on the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch, bounded between <code>from</code> and * <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param order * The order of the returned timestamps. Must not be <code>null</code>. * * @return The iterator over the commit timestamps in the given time range. May be empty, but never * <code>null</code>. */ public default Iterator<Long> getCommitTimestampsBetween(final long from, final long to, final Order order) { return this.getCommitTimestampsBetween(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, from, to, order); } /** * Returns an iterator over all timestamps where commits have occurred, bounded between <code>from</code> and * <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param order * The order of the returned timestamps. Must not be <code>null</code>. * * @return The iterator over the commit timestamps in the given time range. May be empty, but never * <code>null</code>. */ public Iterator<Long> getCommitTimestampsBetween(final String branch, long from, long to, Order order); /** * Returns an iterator over the entries of commit timestamp and associated metadata on the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch, bounded between <code>from</code> and * <code>to</code>, in descending order. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * <p> * Please keep in mind that some commits may not have any metadata attached. In this case, the * {@linkplain Entry#getValue() value} component of the {@link Entry} will be set to <code>null</code>. * * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * * @return An iterator over the commits in the given time range in descending order. The contained entries have the * timestamp as the {@linkplain Entry#getKey() key} component and the associated metadata as their * {@linkplain Entry#getValue() value} component (which may be <code>null</code>). May be empty, but never * <code>null</code>. */ public default Iterator<Entry<Long, Object>> getCommitMetadataBetween(final long from, final long to) { return this.getCommitMetadataBetween(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, from, to, Order.DESCENDING); } /** * Returns an iterator over the entries of commit timestamp and associated metadata, bounded between * <code>from</code> and <code>to</code>, in descending order. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * <p> * Please keep in mind that some commits may not have any metadata attached. In this case, the * {@linkplain Entry#getValue() value} component of the {@link Entry} will be set to <code>null</code>. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * * @return An iterator over the commits in the given time range in descending order. The contained entries have the * timestamp as the {@linkplain Entry#getKey() key} component and the associated metadata as their * {@linkplain Entry#getValue() value} component (which may be <code>null</code>). May be empty, but never * <code>null</code>. */ public default Iterator<Entry<Long, Object>> getCommitMetadataBetween(final String branch, final long from, final long to) { return this.getCommitMetadataBetween(branch, from, to, Order.DESCENDING); } /** * Returns an iterator over the entries of commit timestamp and associated metadata on the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch, bounded between <code>from</code> and * <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * <p> * Please keep in mind that some commits may not have any metadata attached. In this case, the * {@linkplain Entry#getValue() value} component of the {@link Entry} will be set to <code>null</code>. * * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param order * The order of the returned commits. Must not be <code>null</code>. * * @return An iterator over the commits in the given time range. The contained entries have the timestamp as the * {@linkplain Entry#getKey() key} component and the associated metadata as their * {@linkplain Entry#getValue() value} component (which may be <code>null</code>). May be empty, but never * <code>null</code>. */ public default Iterator<Entry<Long, Object>> getCommitMetadataBetween(final long from, final long to, final Order order) { return this.getCommitMetadataBetween(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, from, to, order); } /** * Returns an iterator over the entries of commit timestamp and associated metadata, bounded between * <code>from</code> and <code>to</code>. * * <p> * If the <code>from</code> value is greater than the <code>to</code> value, this method always returns an empty * iterator. * * <p> * Please keep in mind that some commits may not have any metadata attached. In this case, the * {@linkplain Entry#getValue() value} component of the {@link Entry} will be set to <code>null</code>. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * @param from * The lower bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param to * The upper bound of the time range to look for commits in (inclusive). Must not be negative. Must be * less than or equal to the timestamp of this transaction. * @param order * The order of the returned commits. Must not be <code>null</code>. * * @return An iterator over the commits in the given time range. The contained entries have the timestamp as the * {@linkplain Entry#getKey() key} component and the associated metadata as their * {@linkplain Entry#getValue() value} component (which may be <code>null</code>). May be empty, but never * <code>null</code>. */ public Iterator<Entry<Long, Object>> getCommitMetadataBetween(String branch, long from, long to, Order order); /** * Returns an iterator over commit timestamps on the {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} * branch in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 * commit timestamps that have occurred before timestamp 10000. Calling * {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the * 400 latest commit timestamps, which are smaller than 123456. * * @param minTimestamp * The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param maxTimestamp * The highest timestamp to consider (inclusive). All higher timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param pageSize * The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting * iterator. Must be greater than zero. * @param pageIndex * The index of the page to retrieve. Must not be negative. * @param order * The desired ordering for the commit timestamps * * @return An iterator that contains the commit timestamps for the requested page. Never <code>null</code>, may be * empty. If the requested page does not exist, this iterator will always be empty. */ public default Iterator<Long> getCommitTimestampsPaged(final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order) { return this.getCommitTimestampsPaged(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, minTimestamp, maxTimestamp, pageSize, pageIndex, order); } /** * Returns an iterator over commit timestamps in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 * commit timestamps that have occurred before timestamp 10000. Calling * {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the * 400 latest commit timestamps, which are smaller than 123456. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * @param minTimestamp * The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param maxTimestamp * The highest timestamp to consider (inclusive). All higher timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param pageSize * The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting * iterator. Must be greater than zero. * @param pageIndex * The index of the page to retrieve. Must not be negative. * @param order * The desired ordering for the commit timestamps * * @return An iterator that contains the commit timestamps for the requested page. Never <code>null</code>, may be * empty. If the requested page does not exist, this iterator will always be empty. */ public Iterator<Long> getCommitTimestampsPaged(final String branch, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order); /** * Returns an iterator over commit timestamps and associated metadata on the * {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 * commit timestamps that have occurred before timestamp 10000. Calling * {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the * 400 latest commit timestamps, which are smaller than 123456. * * <p> * The {@link Entry Entries} returned by the iterator always have the commit timestamp as their first component and * the metadata associated with this commit as their second component. The second component can be <code>null</code> * if the commit was executed without providing metadata. * * @param minTimestamp * The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param maxTimestamp * The highest timestamp to consider. All higher timestamps will be excluded from the pagination. Must be * less than or equal to the timestamp of this transaction. * @param pageSize * The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting * iterator. Must be greater than zero. * @param pageIndex * The index of the page to retrieve. Must not be negative. * @param order * The desired ordering for the commit timestamps * * @return An iterator that contains the commits for the requested page. Never <code>null</code>, may be empty. If * the requested page does not exist, this iterator will always be empty. */ public default Iterator<Entry<Long, Object>> getCommitMetadataPaged(final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order) { return this.getCommitMetadataPaged(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, minTimestamp, maxTimestamp, pageSize, pageIndex, order); } /** * Returns an iterator over commit timestamps and associated metadata in a paged fashion. * * <p> * For example, calling {@code getCommitTimestampsPaged(10000, 100, 0, Order.DESCENDING)} will give the latest 100 * commit timestamps that have occurred before timestamp 10000. Calling * {@code getCommitTimestampsPaged(123456, 200, 2, Order.DESCENDING} will return 200 commit timestamps, skipping the * 400 latest commit timestamps, which are smaller than 123456. * * <p> * The {@link Entry Entries} returned by the iterator always have the commit timestamp as their first component and * the metadata associated with this commit as their second component. The second component can be <code>null</code> * if the commit was executed without providing metadata. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * @param minTimestamp * The minimum timestamp to consider (inclusive). All lower timestamps will be excluded from the * pagination. Must be less than or equal to the timestamp of this transaction. * @param maxTimestamp * The highest timestamp to consider. All higher timestamps will be excluded from the pagination. Must be * less than or equal to the timestamp of this transaction. * @param pageSize * The size of the page, i.e. the maximum number of elements allowed to be contained in the resulting * iterator. Must be greater than zero. * @param pageIndex * The index of the page to retrieve. Must not be negative. * @param order * The desired ordering for the commit timestamps * * @return An iterator that contains the commits for the requested page. Never <code>null</code>, may be empty. If * the requested page does not exist, this iterator will always be empty. */ public Iterator<Entry<Long, Object>> getCommitMetadataPaged(final String branch, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order); /** * Counts the number of commit timestamps on the {@link ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch * between <code>from</code> (inclusive) and <code>to</code> (inclusive). * * <p> * If <code>from</code> is greater than <code>to</code>, this method will always return zero. * * @param from * The minimum timestamp to include in the search (inclusive). Must not be negative. Must be less than or * equal to the timestamp of this transaction. * @param to * The maximum timestamp to include in the search (inclusive). Must not be negative. Must be less than or * equal to the timestamp of this transaction. * * @return The number of commits that have occurred in the specified time range. May be zero, but never negative. */ public default int countCommitTimestampsBetween(final long from, final long to) { return this.countCommitTimestampsBetween(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, from, to); } /** * Counts the number of commit timestamps between <code>from</code> (inclusive) and <code>to</code> (inclusive). * * <p> * If <code>from</code> is greater than <code>to</code>, this method will always return zero. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * @param from * The minimum timestamp to include in the search (inclusive). Must not be negative. Must be less than or * equal to the timestamp of this transaction. * @param to * The maximum timestamp to include in the search (inclusive). Must not be negative. Must be less than or * equal to the timestamp of this transaction. * * @return The number of commits that have occurred in the specified time range. May be zero, but never negative. */ public int countCommitTimestampsBetween(final String branch, long from, long to); /** * Counts the total number of commit timestamps on the {@link ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} * branch. * * @return The total number of commits in the graph. */ public default int countCommitTimestamps() { return this.countCommitTimestamps(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } /** * Counts the total number of commit timestamps in the graph. * * @param branch * The name of the branch to consider. Must not be <code>null</code>, must refer to an existing branch. * * @return The total number of commits in the graph. */ public int countCommitTimestamps(String branch); }
50,894
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereBranchManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/ChronoSphereBranchManager.java
package org.chronos.chronosphere.api; import java.util.Set; import org.chronos.chronodb.api.ChronoDBConstants; /** * The branch manager is responsible for creating and maintaining branches in a {@link ChronoSphere} repository. * * <p> * You can get an instance of this class via {@link ChronoSphere#getBranchManager()}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoSphereBranchManager { /** * Creates a new child of the master branch with the given name. * * <p> * This will use the head revision as the base revision for the new branch. * * @param branchName * The name of the new branch. Must not be <code>null</code>. Must not refer to an already existing * branch. Branch names must be unique. * * @return The newly created branch. Never <code>null</code>. * * @see #createBranch(String, long) * @see #createBranch(String, String) * @see #createBranch(String, String, long) */ public SphereBranch createBranch(String branchName); /** * Creates a new child of the master branch with the given name. * * @param branchName * The name of the new branch. Must not be <code>null</code>. Must not refer to an already existing * branch. Branch names must be unique. * @param branchingTimestamp * The timestamp at which to branch away from the master branch. Must not be negative. Must be less than * or equal to the timestamp of the latest commit on the master branch. * * @return The newly created branch. Never <code>null</code>. * * @see #createBranch(String) * @see #createBranch(String, String) * @see #createBranch(String, String, long) */ public SphereBranch createBranch(String branchName, long branchingTimestamp); /** * Creates a new child of the given parent branch with the given name. * * <p> * This will use the head revision of the given parent branch as the base revision for the new branch. * * @param parentName * The name of the parent branch. Must not be <code>null</code>. Must refer to an existing branch. * @param newBranchName * The name of the new child branch. Must not be <code>null</code>. Must not refere to an already * existing branch. Branch names must be unique. * * @return The newly created branch. Never <code>null</code>. * * @see #createBranch(String) * @see #createBranch(String, long) * @see #createBranch(String, String, long) */ public SphereBranch createBranch(String parentName, String newBranchName); /** * Creates a new child of the given parent branch with the given name. * * @param parentName * The name of the parent branch. Must not be <code>null</code>. Must refer to an existing branch. * @param newBranchName * The name of the new child branch. Must not be <code>null</code>. Must not refere to an already * existing branch. Branch names must be unique. * @param branchingTimestamp * The timestamp at which to branch away from the parent branch. Must not be negative. Must be less than * or equal to the timestamp of the latest commit on the parent branch. * * @return The newly created branch. Never <code>null</code>. * * @see #createBranch(String) * @see #createBranch(String, long) * @see #createBranch(String, String, long) */ public SphereBranch createBranch(String parentName, String newBranchName, long branchingTimestamp); /** * Checks if a branch with the given name exists or not. * * @param branchName * The branch name to check. Must not be <code>null</code>. * @return <code>true</code> if there is an existing branch with the given name, otherwise <code>false</code>. */ public boolean existsBranch(String branchName); /** * Returns the branch with the given name. * * @param branchName * The name of the branch to retrieve. Must not be <code>null</code>. Must refer to an existing branch. * * @return The branch with the given name. Never <code>null</code>. */ public SphereBranch getBranch(String branchName); /** * Returns the master branch. * * @return The master branch. Never <code>null</code>. */ public default SphereBranch getMasterBranch() { return this.getBranch(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } /** * Returns the name of all existing branches. * * @return An unmodifiable view on the names of all branches. May be empty, but never <code>null</code>. */ public Set<String> getBranchNames(); /** * Returns the set of all existing branches. * * @return An unmodifiable view on the set of all branches. May be empty, but never <code>null</code>. */ public Set<SphereBranch> getBranches(); }
4,828
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MetaModelEvolutionIncubator.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/MetaModelEvolutionIncubator.java
package org.chronos.chronosphere.api; import org.chronos.chronosphere.api.exceptions.ElementCannotBeEvolvedException; import org.chronos.chronosphere.api.exceptions.MetaModelEvolutionCanceledException; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; public interface MetaModelEvolutionIncubator { public EClass migrateClass(EObject oldObject, MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException, ElementCannotBeEvolvedException; public void updateAttributeValues(EObject oldObject, EObject newObject, MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException, ElementCannotBeEvolvedException; public void updateReferenceTargets(EObject oldObject, EObject newObject, MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException, ElementCannotBeEvolvedException; }
871
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereEPackageManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/ChronoSphereEPackageManager.java
package org.chronos.chronosphere.api; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Iterator; import java.util.Set; import org.chronos.chronodb.api.ChronoDBConstants; import org.eclipse.emf.ecore.EPackage; import com.google.common.collect.Iterators; public interface ChronoSphereEPackageManager { // ================================================================================================================= // BASIC EPACKAGE MANAGEMENT // ================================================================================================================= public default void registerOrUpdateEPackage(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.registerOrUpdateEPackages(Iterators.singletonIterator(ePackage)); } public default void registerOrUpdateEPackage(final EPackage ePackage, final String branchName) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.registerOrUpdateEPackages(Iterators.singletonIterator(ePackage), branchName); } public default void registerOrUpdateEPackages(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); this.registerOrUpdateEPackages(ePackages.iterator()); } public default void registerOrUpdateEPackages(final Iterable<? extends EPackage> ePackages, final String branchName) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.registerOrUpdateEPackages(ePackages.iterator(), branchName); } public default void registerOrUpdateEPackages(final Iterator<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); this.registerOrUpdateEPackages(ePackages, ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } public void registerOrUpdateEPackages(Iterator<? extends EPackage> ePackages, String branchName); public default void deleteEPackage(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.deleteEPackages(Iterators.singletonIterator(ePackage)); } public default void deleteEPackage(final EPackage ePackage, final String branchName) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.deleteEPackages(Iterators.singletonIterator(ePackage), branchName); } public default void deleteEPackages(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); this.deleteEPackages(ePackages.iterator()); } public default void deleteEPackages(final Iterable<? extends EPackage> ePackages, final String branchName) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); this.deleteEPackages(ePackages.iterator(), branchName); } public default void deleteEPackages(final Iterator<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); this.deleteEPackages(ePackages, ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } public void deleteEPackages(final Iterator<? extends EPackage> ePackages, final String branchName); public default Set<EPackage> getRegisteredEPackages() { return this.getRegisteredEPackages(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER); } public Set<EPackage> getRegisteredEPackages(String branchName); // ================================================================================================================= // METAMODEL EVOLUTION & INSTANCE ADAPTION // ================================================================================================================= public default void evolveMetamodel(final MetaModelEvolutionIncubator incubator, final EPackage ePackage) { checkNotNull(incubator, "Precondition violation - argument 'incubator' must not be NULL!"); checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.evolveMetamodel(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, incubator, Collections.singleton(ePackage)); } public default void evolveMetamodel(final MetaModelEvolutionController controller, final EPackage ePackage) { checkNotNull(controller, "Precondition violation - argument 'controller' must not be NULL!"); checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.evolveMetamodel(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, controller, Collections.singleton(ePackage)); } public default void evolveMetamodel(final MetaModelEvolutionIncubator incubator, final Iterable<? extends EPackage> ePackages) { checkNotNull(incubator, "Precondition violation - argument 'incubator' must not be NULL!"); checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); this.evolveMetamodel(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, incubator, ePackages); } public default void evolveMetamodel(final MetaModelEvolutionController controller, final Iterable<? extends EPackage> ePackages) { checkNotNull(controller, "Precondition violation - argument 'controller' must not be NULL!"); checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); this.evolveMetamodel(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER, controller, ePackages); } public default void evolveMetamodel(final String branch, final MetaModelEvolutionIncubator incubator, final EPackage ePackage) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(incubator, "Precondition violation - argument 'incubator' must not be NULL!"); checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.evolveMetamodel(branch, incubator, Collections.singleton(ePackage)); } public default void evolveMetamodel(final String branch, final MetaModelEvolutionController controller, final EPackage ePackage) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(controller, "Precondition violation - argument 'controller' must not be NULL!"); checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.evolveMetamodel(branch, controller, Collections.singleton(ePackage)); } public void evolveMetamodel(final String branch, final MetaModelEvolutionIncubator incubator, final Iterable<? extends EPackage> newEPackages); public void evolveMetamodel(final String branch, final MetaModelEvolutionController controller, final Iterable<? extends EPackage> newEPackages); }
7,223
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SphereBranch.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/SphereBranch.java
package org.chronos.chronosphere.api; import java.util.List; import org.chronos.chronodb.api.ChronoDBConstants; /** * A {@link SphereBranch} represents a single stream of changes in the versioning system. * * <p> * Branches work much like in document versioning systems, such as GIT or SVN. Every branch has an * "{@linkplain #getOrigin() origin}" (or "parent") branch from which it was created, as well as a * "{@linkplain #getBranchingTimestamp() branching timestamp}" that reflects the point in time from which this branch * was created. There is one special branch, which is the {@linkplain ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master * branch}. It is the transitive origin of all other branches. It always has the same name, an origin of * <code>null</code>, and a branching timestamp of zero. Unlike other branches, the master branch is created by default * and always exists. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface SphereBranch { /** * Returns the name of this branch, which also acts as its unique identifier. * * @return The branch name. Never <code>null</code>. Branch names are unique. */ public String getName(); /** * Returns the branch from which this branch originates. * * @return The origin (parent) branch. May be <code>null</code> if this branch is the master branch. */ public SphereBranch getOrigin(); /** * Returns the timestamp at which this branch was created from the origin (parent) branch. * * @return The branching timestamp. Never negative. */ public long getBranchingTimestamp(); /** * Returns the list of direct and transitive origin branches. * * <p> * The first entry in the list will always be the {@link ChronoDBConstants#MASTER_BRANCH_IDENTIFIER master} branch. * The remaining entries are the descendants of the previous branch in the list which are also direct or transitive * origins of the current branch. * * <p> * For example, if there were the following branching actions: * <ol> * <li>master is forked into new branch A * <li>A is forked into new branch B * <li>B is forked into new branch C * </ol> * * ... and <code>C.getOriginsRecursive()</code> is invoked, then the returned list will consist of * <code>[master, A, B]</code> (in exactly this order). * * @return The list of origin branches. Will be empty for the master branch, and will start with the master branch * for all other branches. Never <code>null</code>. The returned list is a calculated object which may * freely be modified without changing any internal state. */ public List<SphereBranch> getOriginsRecursive(); /** * Returns the "now" timestamp on this branch, i.e. the timestamp at which the last full commit was successfully * executed. * * @return The "now" timestamp. The minimum is the branching timestamp (or zero for the master branch). Never * negative. */ public long getNow(); }
3,002
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MetaModelEvolutionController.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/MetaModelEvolutionController.java
package org.chronos.chronosphere.api; import org.chronos.chronosphere.api.exceptions.MetaModelEvolutionCanceledException; public interface MetaModelEvolutionController { public void migrate(MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException; }
276
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereTransaction.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/ChronoSphereTransaction.java
package org.chronos.chronosphere.api; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.tuple.Pair; import org.chronos.chronosphere.api.query.QueryStepBuilderStarter; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import com.google.common.collect.Iterators; public interface ChronoSphereTransaction extends AutoCloseable { // ================================================================================================================= // TRANSACTION METADATA // ================================================================================================================= public long getTimestamp(); public SphereBranch getBranch(); // ================================================================================================================= // ATTACHMENT & DELETION OPERATIONS // ================================================================================================================= public EObject createAndAttach(EClass eClass); public void attach(EObject eObject); public void attach(Iterable<? extends EObject> eObjects); public void attach(Iterator<? extends EObject> eObjects); public default void delete(final EObject eObject) { this.delete(eObject, true); } public default void delete(final EObject eObject, final boolean cascadeDeletionToEContents) { delete(Iterators.singletonIterator(eObject), cascadeDeletionToEContents); } public default void delete(final Iterable<? extends EObject> eObjects) { this.delete(eObjects, true); } public default void delete(final Iterable<? extends EObject> eObjects, final boolean cascadeDeletionToEContents) { this.delete(eObjects.iterator(), cascadeDeletionToEContents); } public default void delete(final Iterator<? extends EObject> eObjects) { this.delete(eObjects, true); } public void delete(Iterator<? extends EObject> eObjects, boolean cascadeDeletionToEContents); // ================================================================================================================= // EPACKAGE HANDLING // ================================================================================================================= public EPackage getEPackageByNsURI(String namespaceURI); public Set<EPackage> getEPackages(); public EPackage getEPackageByQualifiedName(String qualifiedName); public EClassifier getEClassifierByQualifiedName(String qualifiedName); public EClass getEClassByQualifiedName(String qualifiedName); public EStructuralFeature getFeatureByQualifiedName(String qualifiedName); public EAttribute getEAttributeByQualifiedName(String qualifiedName); public EReference getEReferenceByQualifiedName(String qualifiedName); public EPackage getEPackageBySimpleName(String simpleName); public EClassifier getEClassifierBySimpleName(String simpleName); public EClass getEClassBySimpleName(String simpleName); // ================================================================================================================= // QUERY & RETRIEVAL OPERATIONS // ================================================================================================================= /** * Retrieves a single {@link ChronoEObject} by its unique identifier. * * @param eObjectID * The ID of the EObject to retrieve. Must not be <code>null</code>. * @return The EObject. May be <code>null</code> if there is no EObject for the given ID. */ public ChronoEObject getEObjectById(String eObjectID); /** * Retrieves the {@link ChronoEObject}s for the given unique identifiers. * * @param eObjectIDs * The IDs of the EObjects to retrieve. May be empty, but must not be <code>null</code>. * @return The mapping from unique ID to retrieved EObject. May be empty, but never <code>null</code>. Is guaranteed * to include every given ID as a key. The IDs that did not have a matching EObject have <code>null</code> * values assigned in the map. */ public Map<String, ChronoEObject> getEObjectById(Iterable<String> eObjectIDs); /** * Retrieves the {@link ChronoEObject}s for the given unique identifiers. * * @param eObjectIDs * The IDs of the EObjects to retrieve. May be empty, but must not be <code>null</code>. * @return The mapping from unique ID to retrieved EObject. May be empty, but never <code>null</code>. Is guaranteed * to include every given ID as a key. The IDs that did not have a matching EObject have <code>null</code> * values assigned in the map. */ public Map<String, ChronoEObject> getEObjectById(Iterator<String> eObjectIDs); public QueryStepBuilderStarter find(); // ================================================================================================================= // HISTORY ANALYSIS // ================================================================================================================= /** * Returns an iterator over the change timestamps in the history of the given {@link EObject}. * * @param eObject * The eObject in question. Must not be <code>null</code>. * @return An iterator over the change timestamps, in descending order. May be empty if the given object is not * attached. */ public Iterator<Long> getEObjectHistory(EObject eObject); /** * Returns an iterator over all EObject modifications that have taken place in the given time range. * * @param timestampLowerBound * The lower bound of the time range to search in. Must not be negative. Must be less than or equal to * <code>timestampUpperBound</code>. Must be less than or equal to the transaction timestamp. * @param timestampUpperBound * The upper bound of the time range to search in. Must not be negative. Must be greater than or equal to * <code>timestampLowerBound</code>. Must be less than or equal to the transaction timestamp. * * @return An iterator over pairs, containing the change timestamp at the first and the modified EObject id at the * second position. May be empty, but never <code>null</code>. */ public Iterator<Pair<Long, String>> getEObjectModificationsBetween(final long timestampLowerBound, final long timestampUpperBound); // ================================================================================================================= // TRANSACTION CONTROL METHODS // ================================================================================================================= public void commit(); public void commit(Object commitMetadata); public void commitIncremental(); public void rollback(); public boolean isClosed(); public boolean isOpen(); @Override public void close(); // redefined from AutoClosable#close(), just without "throws Exception" }
7,165
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereIndexManager.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/ChronoSphereIndexManager.java
package org.chronos.chronosphere.api; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EPackage; /** * This class manages the individual secondary indices on a model. * * <p> * You can get an instance of this class via {@link ChronoSphere#getIndexManager()}. * * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface ChronoSphereIndexManager { /** * Creates an index on the given {@link EAttribute}. * * @param eAttribute * The attribute to index. Must not be <code>null</code>. Must be part of a registered {@link EPackage}. * * @return <code>true</code> if a new index for the given EAttribute was created, or <code>false</code> if the index already existed. * * @throws IllegalArgumentException * Thrown if the given EAttribute is not part of any registered EPackage. * @throws NullPointerException * Thrown if the given EAttribute is <code>null</code>. * * @see ChronoSphere#getEPackageManager() * @see ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) */ public boolean createIndexOn(EAttribute eAttribute); /** * Checks if the given {@link EAttribute} is indexed or not. * * @param eAttribute * The EAttribute to check. Must not be <code>null</code>. Must be part of a registered {@link EPackage}. * * @return <code>true</code> if the attribute is indexed, otherwise <code>false</code>. * * @throws IllegalArgumentException * Thrown if the given EAttribute is not part of any registered EPackage. * @throws NullPointerException * Thrown if the given EAttribute is <code>null</code>. * * @see ChronoSphere#getEPackageManager() * @see ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) */ public boolean existsIndexOn(EAttribute eAttribute); /** * Drops an existing index on the given {@link EAttribute} (if such an index exists). * * @param eAttribute * The EAttribute to drop the index for. Must not be <code>null</code>. Must be part of a registered {@link EPackage}. * * @return <code>true</code> if an index on the given EAttribute existed and was dropped successfully, or <code>false</code> if there was no such index. * * @throws IllegalArgumentException * Thrown if the given EAttribute is not part of any registered EPackage. * @throws NullPointerException * Thrown if the given EAttribute is <code>null</code>. * * @see ChronoSphere#getEPackageManager() * @see ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) */ public boolean dropIndexOn(EAttribute eAttribute); /** * Re-indexes all dirty indices. * * <p> * This is a potentially expensive operation that can take a long time, depending on the size of the model stored in the repository. Use it with care. */ public void reindexAll(); /** * Rebuilds the index on the given {@link EAttribute} from scratch. * * <p> * This is a potentially expensive operation that can take a long time, depending on the size of the model stored in the repository. Use it with care. * * @param eAttribute * The EAttribute to rebuild the index for. Must not be <code>null</code>. Must be part of a registered {@link EPackage}. If there is no index on the given EAttribute, this method is a no-op and returns immediately. * * @throws IllegalArgumentException * Thrown if the given EAttribute is not part of any registered EPackage. * @throws NullPointerException * Thrown if the given EAttribute is <code>null</code>. * * @see #isIndexDirty(EAttribute) * @see ChronoSphere#getEPackageManager() * @see ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) * * @deprecated As of Chronos 0.6.8 or later, please use {@link #reindexAll()} instead. * */ @Deprecated public void reindex(EAttribute eAttribute); /** * Checks if the index on the given {@link EAttribute} is dirty. * * <p> * An index can become dirty e.g. when a new index is created on an already existing model, or when the {@link EPackage} contents change. A dirty index is an index that is out-of-synch with the model data and needs to be re-synchronized. This method checks if such re-synchronization is required. * * @param eAttribute * The EAttribute to check the dirty state of its index for. Must not be <code>null</code>. Must be part of a registered {@link EPackage}. If there is no index on the given EAttribute, this method returns <code>false</code>. * * @return <code>true</code> if there is an index on the given EAttribute AND that index is dirty, <code>false</code> either if there is no index on the given EAttribute or that index is not dirty. * * @throws IllegalArgumentException * Thrown if the given EAttribute is not part of any registered EPackage. * @throws NullPointerException * Thrown if the given EAttribute is <code>null</code>. * * @see #isIndexDirty(EAttribute) * @see ChronoSphere#getEPackageManager() * @see ChronoSphereEPackageManager#registerOrUpdateEPackage(EPackage) */ public boolean isIndexDirty(EAttribute eAttribute); }
5,255
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ResourceIsAlreadyClosedException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/ResourceIsAlreadyClosedException.java
package org.chronos.chronosphere.api.exceptions; public class ResourceIsAlreadyClosedException extends ChronoSphereException { public ResourceIsAlreadyClosedException() { super(); } protected ResourceIsAlreadyClosedException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ResourceIsAlreadyClosedException(final String message, final Throwable cause) { super(message, cause); } public ResourceIsAlreadyClosedException(final String message) { super(message); } public ResourceIsAlreadyClosedException(final Throwable cause) { super(cause); } }
710
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MetaModelEvolutionCanceledException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/MetaModelEvolutionCanceledException.java
package org.chronos.chronosphere.api.exceptions; public class MetaModelEvolutionCanceledException extends MetaModelEvolutionException { public MetaModelEvolutionCanceledException() { super(); } protected MetaModelEvolutionCanceledException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public MetaModelEvolutionCanceledException(final String message, final Throwable cause) { super(message, cause); } public MetaModelEvolutionCanceledException(final String message) { super(message); } public MetaModelEvolutionCanceledException(final Throwable cause) { super(cause); } }
734
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectPersistenceException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/EObjectPersistenceException.java
package org.chronos.chronosphere.api.exceptions; public class EObjectPersistenceException extends ChronoSphereException { public EObjectPersistenceException() { super(); } protected EObjectPersistenceException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public EObjectPersistenceException(final String message, final Throwable cause) { super(message, cause); } public EObjectPersistenceException(final String message) { super(message); } public EObjectPersistenceException(final Throwable cause) { super(cause); } }
680
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StorageBackendCorruptedException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/StorageBackendCorruptedException.java
package org.chronos.chronosphere.api.exceptions; public class StorageBackendCorruptedException extends ChronoSphereException { public StorageBackendCorruptedException() { super(); } protected StorageBackendCorruptedException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public StorageBackendCorruptedException(final String message, final Throwable cause) { super(message, cause); } public StorageBackendCorruptedException(final String message) { super(message); } public StorageBackendCorruptedException(final Throwable cause) { super(cause); } }
710
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/ChronoSphereException.java
package org.chronos.chronosphere.api.exceptions; import org.chronos.common.exceptions.ChronosException; public class ChronoSphereException extends ChronosException { public ChronoSphereException() { super(); } protected ChronoSphereException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ChronoSphereException(final String message, final Throwable cause) { super(message, cause); } public ChronoSphereException(final String message) { super(message); } public ChronoSphereException(final Throwable cause) { super(cause); } }
695
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereConfigurationException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/ChronoSphereConfigurationException.java
package org.chronos.chronosphere.api.exceptions; public class ChronoSphereConfigurationException extends ChronoSphereException { public ChronoSphereConfigurationException() { super(); } protected ChronoSphereConfigurationException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ChronoSphereConfigurationException(final String message, final Throwable cause) { super(message, cause); } public ChronoSphereConfigurationException(final String message) { super(message); } public ChronoSphereConfigurationException(final Throwable cause) { super(cause); } }
722
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereCommitException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/ChronoSphereCommitException.java
package org.chronos.chronosphere.api.exceptions; public class ChronoSphereCommitException extends ChronoSphereException { public ChronoSphereCommitException() { super(); } protected ChronoSphereCommitException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ChronoSphereCommitException(final String message, final Throwable cause) { super(message, cause); } public ChronoSphereCommitException(final String message) { super(message); } public ChronoSphereCommitException(final Throwable cause) { super(cause); } }
680
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ElementCannotBeEvolvedException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/ElementCannotBeEvolvedException.java
package org.chronos.chronosphere.api.exceptions; public class ElementCannotBeEvolvedException extends MetaModelEvolutionException { public ElementCannotBeEvolvedException() { super(); } protected ElementCannotBeEvolvedException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ElementCannotBeEvolvedException(final String message, final Throwable cause) { super(message, cause); } public ElementCannotBeEvolvedException(final String message) { super(message); } public ElementCannotBeEvolvedException(final Throwable cause) { super(cause); } }
710
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EPackagesAreNotSelfContainedException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/EPackagesAreNotSelfContainedException.java
package org.chronos.chronosphere.api.exceptions; import static com.google.common.base.Preconditions.*; import org.eclipse.emf.ecore.EReference; public class EPackagesAreNotSelfContainedException extends ChronoSphereConfigurationException { private final String message; public EPackagesAreNotSelfContainedException(final Iterable<? extends EReference> violatingEReferences) { checkNotNull(violatingEReferences, "Precondition violation - argument 'violatingEReferences' must not be NULL!"); this.message = this.generateMessage(violatingEReferences); } private String generateMessage(final Iterable<? extends EReference> eReferences) { StringBuilder msg = new StringBuilder(); msg.append("The given EPackages are not self-contained. " + "There are EReferences that point to non-contained EClasses. These are:"); for (EReference eReference : eReferences) { msg.append("\n"); msg.append(eReference.getEContainingClass().getEPackage().getName()); msg.append("::"); msg.append(eReference.getEContainingClass().getName()); msg.append("#"); msg.append(eReference.getName()); msg.append(" -> "); msg.append(eReference.getEReferenceType().getName()); msg.append(eReference.getEReferenceType().getEPackage().getName()); msg.append(" [NOT CONTAINED]"); } msg.append("\n"); return msg.toString(); } @Override public String getMessage() { return this.message; } }
1,422
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereQueryException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/ChronoSphereQueryException.java
package org.chronos.chronosphere.api.exceptions; public class ChronoSphereQueryException extends ChronoSphereException { public ChronoSphereQueryException() { super(); } protected ChronoSphereQueryException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ChronoSphereQueryException(final String message, final Throwable cause) { super(message, cause); } public ChronoSphereQueryException(final String message) { super(message); } public ChronoSphereQueryException(final Throwable cause) { super(cause); } }
674
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
MetaModelEvolutionException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/MetaModelEvolutionException.java
package org.chronos.chronosphere.api.exceptions; public class MetaModelEvolutionException extends ChronoSphereException { public MetaModelEvolutionException() { super(); } protected MetaModelEvolutionException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public MetaModelEvolutionException(final String message, final Throwable cause) { super(message, cause); } public MetaModelEvolutionException(final String message) { super(message); } public MetaModelEvolutionException(final Throwable cause) { super(cause); } }
680
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
XMIConversionFailedException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/emf/XMIConversionFailedException.java
package org.chronos.chronosphere.api.exceptions.emf; public class XMIConversionFailedException extends ChronoSphereEMFException { public XMIConversionFailedException() { super(); } protected XMIConversionFailedException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public XMIConversionFailedException(final String message, final Throwable cause) { super(message, cause); } public XMIConversionFailedException(final String message) { super(message); } public XMIConversionFailedException(final Throwable cause) { super(cause); } }
693
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereEMFException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/emf/ChronoSphereEMFException.java
package org.chronos.chronosphere.api.exceptions.emf; import org.chronos.chronosphere.api.exceptions.ChronoSphereException; public class ChronoSphereEMFException extends ChronoSphereException { public ChronoSphereEMFException() { super(); } protected ChronoSphereEMFException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public ChronoSphereEMFException(final String message, final Throwable cause) { super(message, cause); } public ChronoSphereEMFException(final String message) { super(message); } public ChronoSphereEMFException(final Throwable cause) { super(cause); } }
737
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NameResolutionException.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/exceptions/emf/NameResolutionException.java
package org.chronos.chronosphere.api.exceptions.emf; public class NameResolutionException extends ChronoSphereEMFException { public NameResolutionException() { super(); } protected NameResolutionException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public NameResolutionException(final String message, final Throwable cause) { super(message, cause); } public NameResolutionException(final String message) { super(message); } public NameResolutionException(final Throwable cause) { super(cause); } }
663
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SubQuery.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/SubQuery.java
package org.chronos.chronosphere.api.query; import org.chronos.chronosphere.impl.query.steps.eobject.*; import org.chronos.chronosphere.impl.query.steps.numeric.*; import org.chronos.chronosphere.impl.query.steps.object.*; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.impl.query.traversal.TraversalSource; import org.eclipse.emf.ecore.*; import java.util.Objects; import java.util.function.Function; import java.util.function.Predicate; public class SubQuery { // ================================================================================================================= // GENERIC QUERY METHODS // ================================================================================================================= /** * Applies the given filter predicate to all elements in the current result. * * @param predicate The predicate to apply. Must not be <code>null</code>. All elements for which the predicate function * returns <code>false</code> will be filtered out and discarded. * @return The query builder, for method chaining. Never <code>null</code>. */ public static <S> UntypedQueryStepBuilder<S, S> filter(final Predicate<S> predicate) { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new ObjectQueryFilterStepBuilder<>(source, predicate); } /** * Uses the given function to map each element from the current result set to a new element. * * @param function The mapping function to apply. Must not be <code>null</code>. Should be idempotent and side-effect * free. * @return The query step builder, for method chaining. Never <code>null</code>. */ public static <S, E> UntypedQueryStepBuilder<S, E> map(final Function<S, E> function) { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new ObjectQueryMapStepBuilder<>(source, function); } /** * Filters out and discards all <code>null</code> values from the current result set. * <p> * <p> * This is the same as: * <p> * <pre> * query.filter(element -> element != null) * </pre> * * @return The query step builder, for method chaining. Never <code>null</code>. * @see #filter(Predicate) */ public static <S> UntypedQueryStepBuilder<S, S> notNull() { return filter(Objects::nonNull); } // ================================================================================================================= // TYPECAST METHODS // ================================================================================================================= /** * Converts the elements in the current result set into {@link EObject}s. * <p> * <p> * This method first checks if the element in question is an instance of EObject. If it is an EObject, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-EObjects will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> EObjectQueryStepBuilder<S> asEObject() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new EObjectQueryAsEObjectStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Boolean}s. * <p> * <p> * This method first checks if the element in question is an instance of Boolean. If it is a Boolean, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-Booleans will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> QueryStepBuilder<S, Boolean> asBoolean() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new ObjectQueryAsBooleanStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Byte}s. * <p> * <p> * This method first checks if the element in question is an instance of Byte. If it is a Byte, it is cast down and * forwarded. Otherwise, it is discarded, i.e. all non-Bytes will be filtered out. All <code>null</code> values will * also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> NumericQueryStepBuilder<S, Byte> asByte() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new NumericQueryAsByteStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Short}s. * <p> * <p> * This method first checks if the element in question is an instance of Short. If it is a Short, it is cast down * and forwarded. Otherwise, it is discarded, i.e. all non-Shorts will be filtered out. All <code>null</code> values * will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> NumericQueryStepBuilder<S, Short> asShort() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new NumericQueryAsShortStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Character}s. * <p> * <p> * This method first checks if the element in question is an instance of Character. If it is a Character, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-Characters will be filtered out. All * <code>null</code> values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> QueryStepBuilder<S, Character> asCharacter() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new ObjectQueryAsCharacterStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Integer}s. * <p> * <p> * This method first checks if the element in question is an instance of Integer. If it is a Integer, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-Integers will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> NumericQueryStepBuilder<S, Integer> asInteger() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new NumericQueryAsIntegerStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Long}s. * <p> * <p> * This method first checks if the element in question is an instance of Long. If it is a Long, it is cast down and * forwarded. Otherwise, it is discarded, i.e. all non-Longs will be filtered out. All <code>null</code> values will * also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> NumericQueryStepBuilder<S, Long> asLong() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new NumericQueryAsLongStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Float}s. * <p> * <p> * This method first checks if the element in question is an instance of Float. If it is a Float, it is cast down * and forwarded. Otherwise, it is discarded, i.e. all non-Floats will be filtered out. All <code>null</code> values * will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> NumericQueryStepBuilder<S, Float> asFloat() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new NumericQueryAsFloatStepBuilder<>(source); } /** * Converts the elements in the current result set into {@link Double}s. * <p> * <p> * This method first checks if the element in question is an instance of Double. If it is a Double, it is cast down * and forwarded. Otherwise, it is discarded, i.e. all non-Doubles will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public static <S> NumericQueryStepBuilder<S, Double> asDouble() { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new NumericQueryAsDoubleStepBuilder<>(source); } /** * Assigns the given name to this {@link QueryStepBuilder}. * <p> * <p> * Note that only the <i>step</i> is named. When coming back to this step, the query result may be different than it * was when it was first reached, depending on the traversal. * * @param stepName The name of the step. Must not be <code>null</code>. Must be unique within the query. * @return The named step, for method chaining. Never <code>null</code>. */ public static <S> QueryStepBuilder<S, S> named(final String stepName) { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new ObjectQueryNamedStepBuilder<>(source, stepName); } @SafeVarargs public static <S> QueryStepBuilder<S, Object> union(final QueryStepBuilder<S, ?>... subqueries) { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new ObjectQueryUnionStepBuilder<>(source, subqueries); } @SafeVarargs public static <S> QueryStepBuilder<S, S> and(final QueryStepBuilder<S, ?>... subqueries) { TraversalChainElement source = TraversalSource.createAnonymousSource(); return new ObjectQueryAndStepBuilder<>(source, subqueries); } @SafeVarargs public static <S> QueryStepBuilder<S, S> or(final QueryStepBuilder<S, ?>... subqueries) { TraversalSource source = TraversalSource.createAnonymousSource(); return new ObjectQueryOrStepBuilder<>(source, subqueries); } // ===================================================================================================================== // EOBJECT METHODS // ===================================================================================================================== /** * Filters all EObjects in the result set that have the given feature set to the given value. * <p> * <p> * Any {@link EObject} that is an instance of an {@link EClass} which does not define any {@link EAttribute} or * {@link EReference} with the given name will be discarded and filtered out. * <p> * <p> * For determining the feature, {@link EClass#getEStructuralFeature(String)} is used per {@link EObject} * individually. * <p> * <p> * The value will be compared via {@link java.util.Objects#equals(Object, Object)}. * * @param eStructuralFeatureName The name of the {@link EStructuralFeature} to filter by. Must not be <code>null</code>. * @param value The value to filter by. May be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> has(final String eStructuralFeatureName, final Object value) { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); // we have to apply this on the EObject API, sadly ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(source); ObjectQueryFilterStepBuilder<Object, EObject> filtered = new ObjectQueryFilterStepBuilder<>(reified, (eObject -> { if (eObject == null) { return false; } EClass eClass = eObject.eClass(); EStructuralFeature feature = eClass.getEStructuralFeature(eStructuralFeatureName); if (feature == null) { return false; } // DON'T DO THIS! This will break EAttributes with enum types that have a default // value even when they are not set! // if (eObject.eIsSet(feature) == false) { // return false; // } return com.google.common.base.Objects.equal(eObject.eGet(feature), value); })); return new EObjectQueryAsEObjectStepBuilder<>(filtered); } /** * Filters all EObjects in the result set that have the given feature set to the given value. * <p> * <p> * Any {@link EObject} that belongs to an {@link EClass} that does not support the given feature will be discarded * and filtered out. * <p> * <p> * The value will be compared via {@link java.util.Objects#equals(Object, Object)}. * * @param eStructuralFeature The feature to filter by. Must not be <code>null</code>. * @param value The value to filter by. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> has(final EStructuralFeature eStructuralFeature, final Object value) { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryHasFeatureValueStepBuilder<>(source, eStructuralFeature, value); } /** * Filters all {@link EObject}s that are an instance of the given {@link EClass}. * <p> * <p> * This method also considers polymorphism, i.e. instances of Sub-EClasses will pass this filter as well. * <p> * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClass The EClass to filter by. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> isInstanceOf(final EClass eClass) { return isInstanceOf(eClass, true); } /** * Filters all {@link EObject}s that are an instance of the given {@link EClass}. * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClass The EClass to filter by. Must not be <code>null</code>. * @param allowSubclasses Whether or not to allow subclasses of the given class. * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> isInstanceOf(final EClass eClass, boolean allowSubclasses) { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryInstanceOfEClassStepBuilder<>(source, eClass, allowSubclasses); } /** * Filters all {@link EObject}s that are a (direct or indirect) instance of an {@link EClass} with the given name. * <p> * This method also considers polymorphism, i.e. instances of Sub-EClasses will pass this filter as well. * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClassName The name of the EClass to search for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> isInstanceOf(final String eClassName) { return isInstanceOf(eClassName, true); } /** * Filters all {@link EObject}s that are a (direct or indirect) instance of an {@link EClass} with the given name. * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClassName The name of the EClass to search for. Must not be <code>null</code>. * @param allowSubclasses Whether or not to allow subclasses of the given class. * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> isInstanceOf(final String eClassName, boolean allowSubclasses) { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryInstanceOfEClassNameStepBuilder<>(source, eClassName, allowSubclasses); } /** * Performs a {@link EObject#eGet(EStructuralFeature)} operation on all {@link EObject}s in the current result and * forwards the result of this method. * <p> * <p> * If a given {@link EObject} does not have the {@link EStructuralFeature} set (i.e. * {@link EObject#eIsSet(EStructuralFeature)} returns <code>false</code>), then no value will be passed onwards. In * any other case, the returned value is passed onwards, even if that value is <code>null</code>. * * @param eStructuralFeatureName The name of the {@link EStructuralFeature} to get the value(s) for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public static UntypedQueryStepBuilder<EObject, Object> eGet(final String eStructuralFeatureName) { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new ObjectQueryEGetByNameStepBuilder<>(source, eStructuralFeatureName); } /** * Performs a {@link EObject#eGet(EStructuralFeature)} operation on all {@link EObject}s in the current result and * forwards the result of this method. * <p> * <p> * If a given {@link EObject} does not have the {@link EStructuralFeature} set (i.e. * {@link EObject#eIsSet(EStructuralFeature)} returns <code>false</code>), then no value will be passed onwards. In * any other case, the returned value is passed onwards, even if that value is <code>null</code>. * * @param eReference The {@link EReference} to get the value(s) for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> eGet(final EReference eReference) { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryEGetReferenceStepBuilder<>(source, eReference); } /** * Performs a {@link EObject#eGet(EStructuralFeature)} operation on all {@link EObject}s in the current result and * forwards the result of this method. * <p> * <p> * If a given {@link EObject} does not have the {@link EStructuralFeature} set (i.e. * {@link EObject#eIsSet(EStructuralFeature)} returns <code>false</code>), then no value will be passed onwards. In * any other case, the returned value is passed onwards, even if that value is <code>null</code>. * * @param eAttribute The {@link EAttribute} to get the value(s) for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public static UntypedQueryStepBuilder<EObject, Object> eGet(final EAttribute eAttribute) { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new ObjectQueryEGetAttributeStepBuilder<>(source, eAttribute); } /** * Navigates from an {@link EObject} to its {@link EObject#eContainer() eContainer}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> eContainer() { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryEContainerStepBuilder<>(source); } /** * Navigates from an {@link EObject} to its {@link EObject#eContents() eContents}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> eContents() { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryEContentsStepBuilder<>(source); } /** * Navigates from an {@link EObject} to its {@link EObject#eAllContents() eAllContents}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> eAllContents() { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryEAllContentsStepBuilder<>(source); } /** * Navigates from an {@link EObject} to all other {@link EObject}s that reference it. * <p> * <p> * This means walking backwards all {@link EReference} instances that have the current EObject as target. This * method will <b>include</b> the {@link EObject#eContainer() eContainer}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public static EObjectQueryStepBuilder<EObject> allReferencingEObjects() { TraversalSource<EObject, EObject> source = TraversalSource.createAnonymousSource(); return new EObjectQueryAllReferencingEObjectsQueryStep<>(source); } }
21,868
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryStepBuilderInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/QueryStepBuilderInternal.java
package org.chronos.chronosphere.api.query; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; public interface QueryStepBuilderInternal<S, E> extends QueryStepBuilder<S, E> { public TraversalChainElement getPrevious(); void setPrevious(TraversalChainElement previous); }
309
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/QueryStepBuilder.java
package org.chronos.chronosphere.api.query; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; public interface QueryStepBuilder<S, E> { // ================================================================================================================= // GENERIC QUERY METHODS // ================================================================================================================= /** * Applies the given filter predicate to all elements in the current result. * * @param predicate The predicate to apply. Must not be <code>null</code>. All elements for which the predicate function * returns <code>false</code> will be filtered out and discarded. * @return The query builder, for method chaining. Never <code>null</code>. */ public QueryStepBuilder<S, E> filter(Predicate<E> predicate); /** * Limits the number of elements in the result set to the given number. * <p> * <p> * Please note that the order of elements is in general arbitrary. Therefore, usually a {@link #limit(long)} is * preceded by a {@link #orderBy(Comparator)}. * * @param limit The limit to apply. Must not be negative. * @return The query builder, for method chaining. Never <code>null</code>. */ public QueryStepBuilder<S, E> limit(long limit); /** * Sorts the current result set by applying the given comparator. * <p> * <p> * This method requires full resolution of all elements and is therefore <b>non-lazy</b>. * * @param comparator The comparator to use. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public QueryStepBuilder<S, E> orderBy(Comparator<E> comparator); /** * Eliminates all duplicated values from the current result. * <p> * <p> * This method is lazy, but requires to keep track of the "already encountered" elements in a set. Therefore, RAM * consumption on this method may be high if it is applied on very large result sets. * * @return The distinct step builder, for method chaining. Never <code>null</code>. */ public QueryStepBuilder<S, E> distinct(); /** * Uses the given function to map each element from the current result set to a new element. * * @param function The mapping function to apply. Must not be <code>null</code>. Should be idempotent and side-effect * free. * @return The query step builder, for method chaining. Never <code>null</code>. */ public <T> UntypedQueryStepBuilder<S, T> map(Function<E, T> function); /** * Uses the given function to map each element to an iterator of output elements. These output iterators will be * concatenated and forwarded. * * @param function The map function to apply. Must not be <code>null</code>. Should be idempotent and side-effect free. * @return The query step builder, for method chaining. Never <code>null</code>. */ public <T> UntypedQueryStepBuilder<S, T> flatMap(Function<E, Iterator<T>> function); /** * Filters out and discards all <code>null</code> values from the current result set. * <p> * <p> * This is the same as: * <p> * <pre> * query.filter(element -> element != null) * </pre> * * @return The query step builder, for method chaining. Never <code>null</code>. * @see #filter(Predicate) */ public QueryStepBuilder<S, E> notNull(); // ================================================================================================================= // NAMED OPERATIONS // ================================================================================================================= /** * Assigns the given name to this {@link QueryStepBuilder}. * <p> * <p> * Note that only the <i>step</i> is named. When coming back to this step, the query result may be different than it * was when it was first reached, depending on the traversal. * * @param stepName The name of the step. Must not be <code>null</code>. Must be unique within the query. * @return The named step, for method chaining. Never <code>null</code>. * @see #back(String) */ public QueryStepBuilder<S, E> named(String stepName); /** * Exits the current traversal state and goes back to a named step, or a named set. * * @param stepName The name of the step to go back to. Must not be <code>null</code>, must refer to a named step. * @return The step after going back, for method chaining. Never <code>null</code>. * @see #named(String) */ public UntypedQueryStepBuilder<S, Object> back(String stepName); /** * Removes all elements from the given {@linkplain #named(String) named step} from this step. * * @param stepName The name of the step. Must not be <code>null</code>, must refer to a named step. * @return The step after removing the elements in the given named step, for method chaining. Never * <code>null</code>. */ public QueryStepBuilder<S, E> except(String stepName); /** * Removes all elements in the given set from the stream. * * @param elementsToExclude The elements to remove. Must not be <code>null</code>. * @return The step after removing the elements in the given set, for method chaining. Never <code>null</code>. */ public QueryStepBuilder<S, E> except(Set<?> elementsToExclude); // ===================================================================================================================== // SET & BOOLEAN OPERATIONS // ===================================================================================================================== @SuppressWarnings("unchecked") public UntypedQueryStepBuilder<S, Object> union(QueryStepBuilder<E, ?>... subqueries); @SuppressWarnings("unchecked") public QueryStepBuilder<S, E> and(QueryStepBuilder<E, ?>... subqueries); @SuppressWarnings("unchecked") public QueryStepBuilder<S, E> or(QueryStepBuilder<E, ?>... subqueries); public QueryStepBuilder<S, E> not(QueryStepBuilder<E, ?> subquery); // ================================================================================================================= // FINISHING OPERATIONS // ================================================================================================================= /** * Calculates the result set of this query and returns it. * <p> * <p> * Please note that iterating over the result set via {@link #toIterator()} is in general faster * and consumes less RAM than first converting the result into a set. * * @return The result set. Never <code>null</code>. May be empty. */ public Set<E> toSet(); /** * Calculates the result of this query and returns it as a {@link List}. * <p> * <p> * Please note that iterating over the result via {@link #toIterator()} is in general faster and * consumes less RAM than first converting the result into a list. * * @return The result list. Never <code>null</code>. May be empty. */ public List<E> toList(); /** * Creates an iterator over the elements in this query and returns it. * * @return The iterator over the resulting elements. May be empty, but never <code>null</code>. */ public Iterator<E> toIterator(); /** * Converts this query into a {@link Stream}. * * @return The stream representation of this query. */ public Stream<E> toStream(); /** * Counts the number of elements in the current result, and returns that count. * * @return The count. Never negative, may be zero. */ public long count(); }
8,085
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
Direction.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/Direction.java
package org.chronos.chronosphere.api.query; public enum Direction { INCOMING, OUTGOING, BOTH; }
102
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericCastableQueryStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/NumericCastableQueryStepBuilder.java
package org.chronos.chronosphere.api.query; public interface NumericCastableQueryStepBuilder<S, E> extends QueryStepBuilder<S, E> { /** * Converts the elements in the current result set into {@link Byte}s. * * <p> * This method first checks if the element in question is an instance of Byte. If it is a Byte, it is cast down and * forwarded. Otherwise, it is discarded, i.e. all non-Bytes will be filtered out. All <code>null</code> values will * also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public NumericQueryStepBuilder<S, Byte> asByte(); /** * Converts the elements in the current result set into {@link Short}s. * * <p> * This method first checks if the element in question is an instance of Short. If it is a Short, it is cast down * and forwarded. Otherwise, it is discarded, i.e. all non-Shorts will be filtered out. All <code>null</code> values * will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public NumericQueryStepBuilder<S, Short> asShort(); /** * Converts the elements in the current result set into {@link Integer}s. * * <p> * This method first checks if the element in question is an instance of Integer. If it is a Integer, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-Integers will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public NumericQueryStepBuilder<S, Integer> asInteger(); /** * Converts the elements in the current result set into {@link Long}s. * * <p> * This method first checks if the element in question is an instance of Long. If it is a Long, it is cast down and * forwarded. Otherwise, it is discarded, i.e. all non-Longs will be filtered out. All <code>null</code> values will * also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public NumericQueryStepBuilder<S, Long> asLong(); /** * Converts the elements in the current result set into {@link Float}s. * * <p> * This method first checks if the element in question is an instance of Float. If it is a Float, it is cast down * and forwarded. Otherwise, it is discarded, i.e. all non-Floats will be filtered out. All <code>null</code> values * will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public NumericQueryStepBuilder<S, Float> asFloat(); /** * Converts the elements in the current result set into {@link Double}s. * * <p> * This method first checks if the element in question is an instance of Double. If it is a Double, it is cast down * and forwarded. Otherwise, it is discarded, i.e. all non-Doubles will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public NumericQueryStepBuilder<S, Double> asDouble(); }
3,100
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryStepBuilderStarter.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/QueryStepBuilderStarter.java
package org.chronos.chronosphere.api.query; import java.util.Iterator; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; public interface QueryStepBuilderStarter { public EObjectQueryStepBuilder<EObject> startingFromAllEObjects(); public EObjectQueryStepBuilder<EObject> startingFromInstancesOf(String eClassName); public EObjectQueryStepBuilder<EObject> startingFromInstancesOf(EClass eClass); public EObjectQueryStepBuilder<EObject> startingFromEObjectsWith(EAttribute attribute, Object value); public EObjectQueryStepBuilder<EObject> startingFromEObject(EObject eObject); public EObjectQueryStepBuilder<EObject> startingFromEObjects(Iterable<? extends EObject> eObjects); public EObjectQueryStepBuilder<EObject> startingFromEObjects(Iterator<? extends EObject> eObjects); }
861
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/EObjectQueryStepBuilder.java
package org.chronos.chronosphere.api.query; import org.eclipse.emf.ecore.*; import java.util.Comparator; import java.util.function.Predicate; public interface EObjectQueryStepBuilder<S> extends QueryStepBuilder<S, EObject> { public EObjectQueryStepBuilder<S> orderBy(EAttribute eAttribute, Order order); @Override public EObjectQueryStepBuilder<S> limit(long limit); @Override public EObjectQueryStepBuilder<S> notNull(); /** * Filters all EObjects in the result set that have the given feature set to the given value. * <p> * <p> * Any {@link EObject} that is an instance of an {@link EClass} which does not define any {@link EAttribute} or * {@link EReference} with the given name will be discarded and filtered out. * <p> * <p> * For determining the feature, {@link EClass#getEStructuralFeature(String)} is used per {@link EObject} * individually. * <p> * <p> * The value will be compared via {@link java.util.Objects#equals(Object, Object)}. * * @param eStructuralFeatureName The name of the {@link EStructuralFeature} to filter by. Must not be <code>null</code>. * @param value The value to filter by. May be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> has(String eStructuralFeatureName, Object value); /** * Filters all EObjects in the result set that have the given feature set to the given value. * <p> * <p> * Any {@link EObject} that belongs to an {@link EClass} that does not support the given feature will be discarded * and filtered out. * <p> * <p> * The value will be compared via {@link java.util.Objects#equals(Object, Object)}. * * @param eStructuralFeature The feature to filter by. Must not be <code>null</code>. * @param value The value to filter by. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> has(EStructuralFeature eStructuralFeature, Object value); /** * Filters all {@link EObject}s that are an instance of the given {@link EClass}. * <p> * <p> * This method also considers polymorphism, i.e. instances of Sub-EClasses will pass this filter as well. * <p> * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClass The EClass to filter by. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> isInstanceOf(EClass eClass); /** * Filters all {@link EObject}s that are an instance of the given {@link EClass}. * <p> * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClass The EClass to filter by. Must not be <code>null</code>. * @param allowSubclasses Whether or not subclasses are allowed. If <code>false</code>, any EObject that passes the filter must * be a direct instance of the given EClass. If <code>true</code>, EObjects that pass the filter can be a * direct or transitive instance of the given EClass. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> isInstanceOf(EClass eClass, boolean allowSubclasses); /** * Filters all {@link EObject}s that are a (direct or indirect) instance of an {@link EClass} with the given name. * <p> * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClassName The name of the EClass to search for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> isInstanceOf(String eClassName); /** * Filters all {@link EObject}s that are a (direct or indirect) instance of an {@link EClass} with the given name. * <p> * <p> * This operation is <code>null</code>-safe. Any <code>null</code> values will be discarded and filtered out. * * @param eClassName The name of the EClass to search for. Must not be <code>null</code>. * @param allowSubclasses Whether or not subclasses are allowed. If <code>false</code>, any EObject that passes the filter must * be a direct instance of the given EClass. If <code>true</code>, EObjects that pass the filter can be a * direct or transitive instance of the given EClass. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> isInstanceOf(String eClassName, boolean allowSubclasses); /** * Performs a {@link EObject#eGet(EStructuralFeature)} operation on all {@link EObject}s in the current result and * forwards the result of this method. * <p> * <p> * If a given {@link EObject} does not have the {@link EStructuralFeature} set (i.e. * {@link EObject#eIsSet(EStructuralFeature)} returns <code>false</code>), then no value will be passed onwards. In * any other case, the returned value is passed onwards, even if that value is <code>null</code>. * * @param eStructuralFeatureName The name of the {@link EStructuralFeature} to get the value(s) for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public UntypedQueryStepBuilder<S, Object> eGet(String eStructuralFeatureName); /** * Performs a {@link EObject#eGet(EStructuralFeature)} operation on all {@link EObject}s in the current result and * forwards the result of this method. * <p> * <p> * If a given {@link EObject} does not have the {@link EStructuralFeature} set (i.e. * {@link EObject#eIsSet(EStructuralFeature)} returns <code>false</code>), then no value will be passed onwards. In * any other case, the returned value is passed onwards, even if that value is <code>null</code>. * * @param eReference The {@link EReference} to get the value(s) for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> eGet(EReference eReference); /** * Navigates along the <i>incoming</i> {@link EReference}s of the given type and forwards the {@link EObject}s on * the other end of the reference. * * @param eReference The EReference to follow backwards. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> eGetInverse(final EReference eReference); /** * Navigates along the <i>incoming</i> {@link EReference}s with the given name and forwards the {@link EObject}s on * the other end of the reference. * * @param referenceName The name of the reference to follow backwards. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> eGetInverse(final String referenceName); /** * Performs a {@link EObject#eGet(EStructuralFeature)} operation on all {@link EObject}s in the current result and * forwards the result of this method. * <p> * <p> * If a given {@link EObject} does not have the {@link EStructuralFeature} set (i.e. * {@link EObject#eIsSet(EStructuralFeature)} returns <code>false</code>), then no value will be passed onwards. In * any other case, the returned value is passed onwards, even if that value is <code>null</code>. * * @param eAttribute The {@link EAttribute} to get the value(s) for. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public UntypedQueryStepBuilder<S, Object> eGet(EAttribute eAttribute); /** * Navigates from an {@link EObject} to its {@link EObject#eContainer() eContainer}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> eContainer(); /** * Navigates from an {@link EObject} to its {@link EObject#eContents() eContents}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> eContents(); /** * Navigates from an {@link EObject} to its {@link EObject#eAllContents() eAllContents}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> eAllContents(); /** * Navigates from an {@link EObject} to all other {@link EObject}s that reference it. * <p> * <p> * This means walking backwards all {@link EReference} instances that have the current EObject as target. This * method will <b>include</b> the {@link EObject#eContainer() eContainer}. * * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> allReferencingEObjects(); @Override public EObjectQueryStepBuilder<S> named(String name); @Override public EObjectQueryStepBuilder<S> filter(Predicate<EObject> predicate); @Override public EObjectQueryStepBuilder<S> orderBy(final Comparator<EObject> comparator); @Override public EObjectQueryStepBuilder<S> distinct(); /** * Calculates the transitive closure of the current {@link EObject} that is created by repeatedly following the given (outgoing) {@link EReference}. * <p> * This method is safe to use in models that contain cyclic paths. Every EObject in the closure will only be returned <i>once</i>, even if multiple paths lead to it. * </p> * <p> * The EObject which is used to start the closure will <b>not</b> be part of the closure. * </p> * <p> * If an EObject is either of an {@link EClass} that does not own the given EReference, or the EObject itself does not have an instance of the EReference, the closure ends at this EObject. * </p> * * @param eReference The EReference to follow repeatedly. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public default EObjectQueryStepBuilder<S> closure(EReference eReference) { return this.closure(eReference, Direction.OUTGOING); } /** * Calculates the transitive closure of the current {@link EObject} that is created by repeatedly following the given (outgoing) {@link EReference}. * <p> * This method is safe to use in models that contain cyclic paths. Every EObject in the closure will only be returned <i>once</i>, even if multiple paths lead to it. * </p> * <p> * The EObject which is used to start the closure will <b>not</b> be part of the closure. * </p> * <p> * If an EObject is either of an {@link EClass} that does not own the given EReference, or the EObject itself does not have an instance of the EReference, the closure ends at this EObject. * </p> * * @param eReference The EReference to follow repeatedly. Must not be <code>null</code>. * @param direction The direction to follow when calculating the closure. Must not be <code>null</code>. * @return The query builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> closure(EReference eReference, Direction direction); }
11,950
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
UntypedQueryStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/UntypedQueryStepBuilder.java
package org.chronos.chronosphere.api.query; import org.eclipse.emf.ecore.EObject; public interface UntypedQueryStepBuilder<S, E> extends QueryStepBuilder<S, E>, NumericCastableQueryStepBuilder<S, E> { /** * Converts the elements in the current result set into {@link EObject}s. * <p> * <p> * This method first checks if the element in question is an instance of EObject. If it is an EObject, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-EObjects will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public EObjectQueryStepBuilder<S> asEObject(); /** * Converts the elements in the current result set into {@link Boolean}s. * <p> * <p> * This method first checks if the element in question is an instance of Boolean. If it is a Boolean, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-Booleans will be filtered out. All <code>null</code> * values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public QueryStepBuilder<S, Boolean> asBoolean(); /** * Converts the elements in the current result set into {@link Character}s. * <p> * <p> * This method first checks if the element in question is an instance of Character. If it is a Character, it is cast * down and forwarded. Otherwise, it is discarded, i.e. all non-Characters will be filtered out. All * <code>null</code> values will also be filtered out. * * @return The step builder, for method chaining. Never <code>null</code>. */ public QueryStepBuilder<S, Character> asCharacter(); }
1,822
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/query/NumericQueryStepBuilder.java
package org.chronos.chronosphere.api.query; import java.util.Optional; public interface NumericQueryStepBuilder<S, E extends Number> extends QueryStepBuilder<S, E>, NumericCastableQueryStepBuilder<S, E> { public Optional<Double> sumAsDouble(); public Optional<Long> sumAsLong(); public Optional<Double> average(); public Optional<Double> maxAsDouble(); public Optional<Long> maxAsLong(); public Optional<Double> minAsDouble(); public Optional<Long> minAsLong(); public NumericQueryStepBuilder<S, Long> round(); public NumericQueryStepBuilder<S, Integer> roundToInt(); public NumericQueryStepBuilder<S, Long> floor(); public NumericQueryStepBuilder<S, Long> ceil(); }
693
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereFinalizableBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/builder/repository/ChronoSphereFinalizableBuilder.java
package org.chronos.chronosphere.api.builder.repository; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.common.builder.ChronoBuilder; public interface ChronoSphereFinalizableBuilder<SELF extends ChronoSphereFinalizableBuilder<?>> extends ChronoBuilder<SELF> { /** * Builds the {@link ChronoSphere} instance, using the properties specified by the fluent API. * * <p> * This method finalizes the buildLRU process. Afterwards, the builder should be discarded. * * @return The new {@link ChronoSphere} instance. Never <code>null</code>. */ public ChronoSphere build(); }
610
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereBaseBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/api/builder/repository/ChronoSphereBaseBuilder.java
package org.chronos.chronosphere.api.builder.repository; import java.io.File; import java.util.Properties; import org.apache.commons.configuration2.Configuration; public interface ChronoSphereBaseBuilder { public ChronoSphereInMemoryBuilder inMemoryRepository(); public ChronoSpherePropertyFileBuilder fromPropertiesFile(File file); public ChronoSpherePropertyFileBuilder fromPropertiesFile(String filePath); public ChronoSpherePropertyFileBuilder fromConfiguration(Configuration configuration); public ChronoSpherePropertyFileBuilder fromProperties(Properties properties); }
590
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/impl/store/ChronoEStore.java
package org.chronos.chronosphere.emf.internal.impl.store; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.InternalEObject.EStore; public interface ChronoEStore extends EStore { /** * The base value for negative, i.e., opposite-end, eContainerFeatureID values. */ static final int EOPPOSITE_FEATURE_BASE = -1; public void setContainer(InternalEObject object, InternalEObject newContainer); public void setContainingFeatureID(InternalEObject object, int newContainerFeatureID); public int getContainingFeatureID(InternalEObject object); public void clearEContainerAndEContainingFeatureSilent(final InternalEObject eObject); }
669
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
OwnedTransientEStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/impl/store/OwnedTransientEStore.java
package org.chronos.chronosphere.emf.internal.impl.store; import static com.google.common.base.Preconditions.*; import java.util.List; import java.util.Map; import org.chronos.chronosphere.emf.impl.ChronoEObjectImpl; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import com.google.common.collect.Maps; public class OwnedTransientEStore extends AbstractChronoEStore { private ChronoEObjectInternal owner; private final Map<EStructuralFeature, Object> contents = Maps.newHashMap(); private ChronoEObjectInternal eContainer; private Integer eContainingFeatureID; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public OwnedTransientEStore(final ChronoEObjectInternal owner) { checkNotNull(owner, "Precondition violation - argument 'owner' must not be NULL!"); this.owner = owner; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public Object get(final InternalEObject object, final EStructuralFeature feature, final int index) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); if (feature.isMany()) { EList<Object> list = this.getListOfValuesFor(feature); if (index == NO_INDEX) { return list; } else { return list.get(index); } } else { return this.contents.get(feature); } } @Override public Object set(final InternalEObject object, final EStructuralFeature feature, final int index, final Object value) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); Object result = null; if (index == NO_INDEX) { if (value == null) { result = this.contents.remove(feature); } else { result = this.contents.put(feature, value); } } else { List<Object> list = this.getListOfValuesFor(feature); result = list.set(index, value); } // if we are dealing with a containment reference, set the eContainer of the value to the owner of this store this.setEContainerReferenceIfNecessary(object, feature, value); return result; } @Override public boolean isSet(final InternalEObject object, final EStructuralFeature feature) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); // special case: a feature is always "set" if it is the container feature and eContainer != null if (feature instanceof EReference) { EReference eReference = (EReference) feature; if (eReference.isContainer()) { return this.getContainer(object) != null; } } if (feature.isMany()) { // for many-valued features, "being set" is defined as "not being empty" return this.getListOfValuesFor(feature).isEmpty() == false; } return this.contents.containsKey(feature); } @Override public void unset(final InternalEObject object, final EStructuralFeature feature) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); if (this.isSet(object, feature) == false) { // no need to unset return; } Object oldValue = object.eGet(feature); this.unsetEContainerReferenceIfNecessary(this.owner, feature, NO_INDEX); this.removeFromEOppositeIfNecessary(this.owner, feature, oldValue); this.contents.remove(feature); } @Override public boolean isEmpty(final InternalEObject object, final EStructuralFeature feature) { this.assertIsOwner(object); return this.getListOfValuesFor(feature).isEmpty(); } @Override public int size(final InternalEObject object, final EStructuralFeature feature) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); return this.getListOfValuesFor(feature).size(); } @Override public boolean contains(final InternalEObject object, final EStructuralFeature feature, final Object value) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); return this.getListOfValuesFor(feature).contains(value); } @Override public int indexOf(final InternalEObject object, final EStructuralFeature feature, final Object value) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); return this.getListOfValuesFor(feature).indexOf(value); } @Override public int lastIndexOf(final InternalEObject object, final EStructuralFeature feature, final Object value) { this.assertIsOwner(object); checkNotNull(value, "Precondition violation - argument 'value' must not be NULL!"); return this.getListOfValuesFor(feature).lastIndexOf(value); } @Override public void add(final InternalEObject object, final EStructuralFeature feature, final int index, final Object value) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); this.getListOfValuesFor(feature).add(index, value); // DON'T do the following! It's already managed by Ecore // this.setEContainerReferenceIfNecessary(object, feature, value); } @Override public Object remove(final InternalEObject object, final EStructuralFeature feature, final int index) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); // special case: if we are removing a contained EObject, we need to unset it's eContainer if (feature instanceof EReference && ((EReference) feature).isContainment()) { Object child = this.get(object, feature, index); this.unsetEContainerReferenceIfNecessary(this.owner, feature, index); this.getListOfValuesFor(feature).remove(child); return child; } return this.getListOfValuesFor(feature).remove(index); } @Override public Object move(final InternalEObject object, final EStructuralFeature feature, final int targetIndex, final int sourceIndex) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); return this.getListOfValuesFor(feature).move(targetIndex, sourceIndex); } @Override public void clear(final InternalEObject object, final EStructuralFeature feature) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); // if the feature is not set, we don't need to do anything... if (this.isSet(object, feature) == false) { return; } // if the feature is a containment reference, clear the eContainer of all children this.unsetEContainerReferenceIfNecessary(this.owner, feature, NO_INDEX); // according to standard implementation "EStoreImpl" this should NOT be "getListOfValuesFor(feature).clear()" this.contents.remove(feature); } @Override public Object[] toArray(final InternalEObject object, final EStructuralFeature feature) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); return this.getListOfValuesFor(feature).toArray(); } @Override public <T> T[] toArray(final InternalEObject object, final EStructuralFeature feature, final T[] array) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); return this.getListOfValuesFor(feature).toArray(array); } @Override public int hashCode(final InternalEObject object, final EStructuralFeature feature) { this.assertIsOwner(object); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); if (this.isSet(object, feature) == false) { return 0; } else { if (feature.isMany()) { return this.getListOfValuesFor(feature).hashCode(); } else { return this.contents.get(feature).hashCode(); } } } @Override public void setContainer(final InternalEObject object, final InternalEObject newContainer) { this.assertIsOwner(object); this.eContainer = (ChronoEObjectInternal) newContainer; } @Override public void setContainingFeatureID(final InternalEObject object, final int newContainerFeatureID) { this.assertIsOwner(object); this.eContainingFeatureID = newContainerFeatureID; } @Override public InternalEObject getContainer(final InternalEObject object) { this.assertIsOwner(object); return this.eContainer; } @Override public EStructuralFeature getContainingFeature(final InternalEObject object) { this.assertIsOwner(object); if (this.eContainingFeatureID == null) { return null; } // prepare a variable to hold the containing feature EStructuralFeature containingFeature = null; if (this.eContainingFeatureID <= EOPPOSITE_FEATURE_BASE) { // inverse feature return this.eContainer.eClass().getEStructuralFeature(EOPPOSITE_FEATURE_BASE - this.eContainingFeatureID); } else { // normal feature // A containing feature is set on this EObject that is a NORMAL EReference. Therefore, there must // be an EOpposite on the EContainer that has 'containment = true'. containingFeature = ((EReference) object.eClass().getEStructuralFeature(this.eContainingFeatureID)) .getEOpposite(); } if (this.eContainingFeatureID != null && containingFeature == null) { throw new IllegalStateException( "Could not resolve Feature ID '" + this.eContainingFeatureID + "' in eContainer '" + this.eContainer + "' (EClass: '" + this.eContainer.eClass().getName() + "')!"); } return containingFeature; } @Override public int getContainingFeatureID(final InternalEObject eObject) { this.assertIsOwner(eObject); if (this.eContainingFeatureID == null) { return 0; } return this.eContainingFeatureID; } @Override public EObject create(final EClass eClass) { ChronoEObjectImpl eObject = new ChronoEObjectImpl(); eObject.eSetClass(eClass); return eObject; } @Override public void clearEContainerAndEContainingFeatureSilent(final InternalEObject eObject) { this.assertIsOwner(eObject); this.eContainer = null; this.eContainingFeatureID = null; } // ===================================================================================================================== // MISCELLANEOUS API // ===================================================================================================================== public ChronoEObjectInternal getOwner() { return this.owner; } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= @SuppressWarnings("unchecked") private EList<Object> getListOfValuesFor(final EStructuralFeature feature) { checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); checkArgument(feature.isMany(), "Precondition violation - argument 'feature' is multiplicity-one, can't get list value!"); EList<Object> result = (EList<Object>) this.contents.get(feature); if (result == null) { result = new BasicEList<Object>(); this.contents.put(feature, result); } return result; } private void assertIsOwner(final EObject eObject) { if (eObject == null) { throw new NullPointerException("OwnedTransientEStore can not work with EObject NULL!"); } if (this.owner != eObject) { throw new IllegalArgumentException("OwnedTransientEStore can only work with the owning EObject!"); } } }
12,197
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractChronoEStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/impl/store/AbstractChronoEStore.java
package org.chronos.chronosphere.emf.internal.impl.store; import static com.google.common.base.Preconditions.*; import java.util.Collection; import java.util.List; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import com.google.common.collect.Lists; public abstract class AbstractChronoEStore implements ChronoEStore { protected int preventCascadeUnsetContainer = 0; protected int preventCascadeRemoveFromOpposite = 0; protected void setEContainerReferenceIfNecessary(final InternalEObject object, final EStructuralFeature feature, final Object value) { // if we are dealing with a containment reference, set the eContainer of the value to the owner of this store if (feature instanceof EReference) { EReference eReference = (EReference) feature; if (eReference.isContainment() && value instanceof EObject) { // set the EContainer of the target object to the owner of this EStore EObject child = (EObject) value; if (child instanceof ChronoEObject == false) { throw new IllegalArgumentException( "Cannot form containment hierarchies between ChronoEObjects and other EObjects!"); } ChronoEObject chronoChild = (ChronoEObject) child; int containingFeatureID = 0; if (eReference.getEOpposite() != null) { // we have an eOpposite, set that as containing feature containingFeatureID = eReference.getEOpposite().getFeatureID(); } else { // invert the feature ID (-1 - ID) to indicate that it is a feature of the parent, // because we have no EOpposite containingFeatureID = -1 - feature.getFeatureID(); } chronoChild.eBasicSetContainer(object, containingFeatureID, null); } } } @SuppressWarnings("unchecked") protected void unsetEContainerReferenceIfNecessary(final InternalEObject object, final EStructuralFeature feature, final int index) { if (feature instanceof EReference == false) { // not a reference return; } EReference eReference = (EReference) feature; if (eReference.isContainment() == false && eReference.isContainer() == false) { // not a containment -> no need to update any containment references return; } if (this.isSet(object, feature) == false) { // no values set -> no containments to update return; } if (this.preventCascadeUnsetContainer > 0) { // already cascading return; } this.preventCascadeUnsetContainer++; try { if (eReference.isContainment()) { // we are removing a child from our containment reference if (eReference.isMany()) { List<Object> values = Lists.newArrayList((EList<Object>) this.get(object, eReference, NO_INDEX)); if (index == NO_INDEX) { // clear all children for (Object value : values) { ChronoEObjectInternal childEObject = (ChronoEObjectInternal) value; childEObject.unsetEContainerSilent(); } return; } else { // clear a single child ChronoEObjectInternal childEObject = (ChronoEObjectInternal) values.get(index); childEObject.unsetEContainerSilent(); return; } } else { // clear a single child ChronoEObjectInternal childEObject = (ChronoEObjectInternal) this.get(object, eReference, NO_INDEX); childEObject.unsetEContainerSilent(); return; } } else if (eReference.isContainer()) { // we are the child and are removing ourselves from the parent // get the parent object and the containing feature EObject eContainer = this.getContainer(object); EStructuralFeature containingFeature = this.getContainingFeature(object); if (containingFeature.isMany()) { List<EObject> children = (List<EObject>) eContainer.eGet(containingFeature); children.remove(object); if (children.contains(object)) { throw new RuntimeException("Children still contains the removed object!"); } } else { eContainer.eSet(containingFeature, null); } // we are no longer part of our container this.clearEContainerAndEContainingFeatureSilent(object); } } finally { this.preventCascadeUnsetContainer--; } } @SuppressWarnings("unchecked") protected void removeFromEOppositeIfNecessary(final ChronoEObject object, final EStructuralFeature feature, final Object otherEnd) { checkNotNull(object, "Precondition violation - argument 'object' must not be NULL!"); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); checkNotNull(otherEnd, "Precondition violation - argument 'otherEnd' must not be NULL!"); if (feature instanceof EReference == false) { // no EReference -> can't have an EOpposite return; } EReference reference = (EReference) feature; if (reference.getEOpposite() == null) { // no opposite available return; } if (this.preventCascadeRemoveFromOpposite > 0) { // already cascading return; } this.preventCascadeRemoveFromOpposite++; try { EReference oppositeRef = reference.getEOpposite(); if (reference.isMany()) { // remove from all opposite ends Collection<EObject> otherEndEObjects = Lists.newArrayList((Collection<EObject>) otherEnd); for (EObject otherEndEObject : otherEndEObjects) { if (oppositeRef.isMany()) { ((List<EObject>) otherEndEObject.eGet(oppositeRef)).remove(object); } else { otherEndEObject.eSet(oppositeRef, null); } } } else { // remove from single opposite end EObject otherEndEObject = (EObject) otherEnd; if (oppositeRef.isMany()) { ((List<EObject>) otherEndEObject.eGet(oppositeRef)).remove(object); } else { otherEndEObject.eSet(oppositeRef, null); } } } finally { this.preventCascadeRemoveFromOpposite--; } } }
5,993
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoGraphEStore.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/impl/store/ChronoGraphEStore.java
package org.chronos.chronosphere.emf.internal.impl.store; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.chronos.chronosphere.internal.ogm.api.VertexKind; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class ChronoGraphEStore extends AbstractChronoEStore { // ================================================================================================================= // FIELDS // ================================================================================================================= private final ChronoSphereTransactionInternal owningTransaction; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public ChronoGraphEStore(final ChronoSphereTransactionInternal owningTransaction) { checkNotNull(owningTransaction, "Precondition violation - argument 'owningTransaction' must not be NULL!"); this.owningTransaction = owningTransaction; } // ===================================================================================================================== // ESTORE API // ===================================================================================================================== @Override public Object get(final InternalEObject object, final EStructuralFeature feature, final int index) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); if (feature.isMany()) { EList<Object> list = this.getListOfValuesFor(ePackage, vertex, feature); if (index == NO_INDEX) { return list; } else { return list.get(index); } } else { return this.getSingleValueFor(ePackage, vertex, feature); } } @Override @SuppressWarnings("unchecked") public Object set(final InternalEObject object, final EStructuralFeature feature, final int index, final Object value) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); Object result = null; if (index == NO_INDEX) { if (feature.isMany()) { // multiplicity-many feature if (value == null) { if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; ChronoSphereGraphFormat.setEAttributeValues(ePackage, vertex, eAttribute, null); } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; ChronoSphereGraphFormat.setEReferenceTargets(ePackage, vertex, eReference, null); } else { throw unknownFeatureTypeException(feature); } } else { if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; ChronoSphereGraphFormat.setEAttributeValues(ePackage, vertex, eAttribute, (Collection<?>) value); } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; List<Vertex> targetVertices = Lists.newArrayList(); Collection<? extends EObject> targetEObjects = (Collection<? extends EObject>) value; for (EObject targetEObject : targetEObjects) { targetVertices.add(this.getEObjectVertex((ChronoEObject) targetEObject)); } ChronoSphereGraphFormat.setEReferenceTargets(ePackage, vertex, eReference, targetVertices); } else { throw unknownFeatureTypeException(feature); } } } else { // multiplicity-one feature if (value == null) { if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; ChronoSphereGraphFormat.setEAttributeValue(ePackage, vertex, eAttribute, null); } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; ChronoSphereGraphFormat.setEReferenceTarget(ePackage, vertex, eReference, null); } else { throw unknownFeatureTypeException(feature); } } else { if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; ChronoSphereGraphFormat.setEAttributeValue(ePackage, vertex, eAttribute, value); } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; Vertex targetVertex = this.getEObjectVertex((ChronoEObject) value); ChronoSphereGraphFormat.setEReferenceTarget(ePackage, vertex, eReference, targetVertex); } else { throw unknownFeatureTypeException(feature); } } } } else { // we are always dealing with a multiplicity-many feature here. List<Object> list = this.getListOfValuesFor(ePackage, vertex, feature); result = list.set(index, value); this.writeListOfValuesToGraph(ePackage, vertex, feature, list); } // if we are dealing with a containment reference, set the eContainer of the value to the owner of this store this.setEContainerReferenceIfNecessary(object, feature, value); return result; } @Override public boolean isSet(final InternalEObject object, final EStructuralFeature feature) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); // special case: a feature is always "set" if it is the container feature and eContainer != null if (feature instanceof EReference) { EReference eReference = (EReference) feature; if (eReference.isContainer()) { return this.getContainer(object) != null; } } if (feature.isMany()) { // for many-valued features, "being set" is defined as "not being empty" return this.getListOfValuesFor(ePackage, vertex, feature).isEmpty() == false; } if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; return ChronoSphereGraphFormat.getEAttributeValue(ePackage, vertex, eAttribute) != null; } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; return ChronoSphereGraphFormat.getEReferenceTarget(ePackage, vertex, eReference) != null; } else { throw unknownFeatureTypeException(feature); } } @Override public void unset(final InternalEObject object, final EStructuralFeature feature) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); if (this.isSet(object, feature) == false) { // no need to unset return; } Object oldValue = object.eGet(feature); this.unsetEContainerReferenceIfNecessary(eObject, feature, NO_INDEX); this.removeFromEOppositeIfNecessary(eObject, feature, oldValue); if (feature.isMany() == false) { if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; ChronoSphereGraphFormat.setEAttributeValue(ePackage, vertex, eAttribute, null); } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; ChronoSphereGraphFormat.setEReferenceTarget(ePackage, vertex, eReference, null); } else { throw unknownFeatureTypeException(feature); } } else { this.writeListOfValuesToGraph(ePackage, vertex, feature, null); } } @Override public boolean isEmpty(final InternalEObject object, final EStructuralFeature feature) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); return this.getListOfValuesFor(ePackage, vertex, feature).isEmpty(); } @Override public int size(final InternalEObject object, final EStructuralFeature feature) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); return this.getListOfValuesFor(ePackage, vertex, feature).size(); } @Override public boolean contains(final InternalEObject object, final EStructuralFeature feature, final Object value) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); return this.getListOfValuesFor(ePackage, vertex, feature).contains(value); } @Override public int indexOf(final InternalEObject object, final EStructuralFeature feature, final Object value) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); return this.getListOfValuesFor(ePackage, vertex, feature).indexOf(value); } @Override public int lastIndexOf(final InternalEObject object, final EStructuralFeature feature, final Object value) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); return this.getListOfValuesFor(ePackage, vertex, feature).lastIndexOf(value); } @Override public void add(final InternalEObject object, final EStructuralFeature feature, final int index, final Object value) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); List<Object> list = this.getListOfValuesFor(ePackage, vertex, feature); list.add(index, value); // write to graph this.writeListOfValuesToGraph(ePackage, vertex, feature, list); } @Override public Object remove(final InternalEObject object, final EStructuralFeature feature, final int index) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); // special case: if we are removing a contained EObject, we need to unset it's eContainer if (feature instanceof EReference && ((EReference) feature).isContainment()) { Object child = this.get(object, feature, index); this.unsetEContainerReferenceIfNecessary(eObject, feature, index); List<Object> values = this.getListOfValuesFor(ePackage, vertex, feature); values.remove(child); this.writeListOfValuesToGraph(ePackage, vertex, feature, values); return child; } List<Object> list = this.getListOfValuesFor(ePackage, vertex, feature); Object result = list.remove(index); this.writeListOfValuesToGraph(ePackage, vertex, feature, list); return result; } @Override public Object move(final InternalEObject object, final EStructuralFeature feature, final int targetIndex, final int sourceIndex) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); EList<Object> values = this.getListOfValuesFor(ePackage, vertex, feature); Object result = values.move(targetIndex, sourceIndex); this.writeListOfValuesToGraph(ePackage, vertex, feature, values); return result; } @Override public void clear(final InternalEObject object, final EStructuralFeature feature) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); // if the feature is not set, we don't need to do anything... if (this.isSet(object, feature) == false) { return; } ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); // if the feature is a containment reference, clear the eContainer of all children this.unsetEContainerReferenceIfNecessary(eObject, feature, NO_INDEX); this.writeListOfValuesToGraph(ePackage, vertex, feature, null); } @Override public Object[] toArray(final InternalEObject object, final EStructuralFeature feature) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); return this.getListOfValuesFor(ePackage, vertex, feature).toArray(); } @Override @SuppressWarnings("hiding") public <T> T[] toArray(final InternalEObject object, final EStructuralFeature feature, final T[] array) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); return this.getListOfValuesFor(ePackage, vertex, feature).toArray(array); } @Override public int hashCode(final InternalEObject object, final EStructuralFeature feature) { this.assertTxOpen(); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); if (this.isSet(object, feature) == false) { return 0; } else { ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); if (feature.isMany()) { return this.getListOfValuesFor(ePackage, vertex, feature).hashCode(); } else { Object singleValue = this.getSingleValueFor(ePackage, vertex, feature); if (singleValue == null) { // according to the documentation of System#identityHashCode(...), // the hash code of the null reference is zero. return 0; } return singleValue.hashCode(); } } } @Override public void setContainer(final InternalEObject object, final InternalEObject newContainer) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); if (newContainer != null) { // change container Vertex targetVertex = this.getEObjectVertex(this.assertIsChronoEObject(newContainer)); ChronoSphereGraphFormat.setEContainer(vertex, targetVertex); } else { // unset container ChronoSphereGraphFormat.setEContainer(vertex, null); } } @Override public void setContainingFeatureID(final InternalEObject object, final int newContainerFeatureID) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoSphereGraphFormat.setEContainingFeatureId(vertex, newContainerFeatureID); } @Override public InternalEObject getContainer(final InternalEObject object) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); if (vertex == null) { return null; } ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); Vertex eContainerVertex = ChronoSphereGraphFormat.getEContainer(vertex); if (eContainerVertex == null) { return null; } return this.createEObjectForVertex(ePackage, eContainerVertex); } @Override public EStructuralFeature getContainingFeature(final InternalEObject object) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); Integer eContainingFeatureID = ChronoSphereGraphFormat.getEContainingFeatureId(vertex); if (eContainingFeatureID == null) { return null; } ChronoEObjectInternal eContainer = (ChronoEObjectInternal) this.getContainer(eObject); // prepare a variable to hold the containing feature EStructuralFeature containingFeature = null; if (eContainingFeatureID < 0) { // inverse feature return eContainer.eClass().getEStructuralFeature(EOPPOSITE_FEATURE_BASE - eContainingFeatureID); } else { // normal feature // A containing feature is set on this EObject that is a NORMAL EReference. Therefore, there must // be an EOpposite on the EContainer that has 'containment = true'. containingFeature = ((EReference) object.eClass().getEStructuralFeature(eContainingFeatureID)) .getEOpposite(); } if (containingFeature == null) { throw new IllegalStateException("Could not resolve Feature ID '" + eContainingFeatureID + "' in eContainer '" + eContainer + "' (EClass: '" + eContainer.eClass().getName() + "')!"); } return containingFeature; } @Override public int getContainingFeatureID(final InternalEObject object) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); Integer eContainingFeatureID = ChronoSphereGraphFormat.getEContainingFeatureId(vertex); if (eContainingFeatureID == null) { return 0; } else { return eContainingFeatureID; } } @Override public EObject create(final EClass eClass) { this.assertTxOpen(); checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); EPackage ePackage = eClass.getEPackage(); while (ePackage.getESuperPackage() != null) { ePackage = ePackage.getESuperPackage(); } ChronoEPackageRegistry cep = this.owningTransaction.getEPackageRegistry(); Vertex vertex = this.getGraph().addVertex(T.id, UUID.randomUUID()); ChronoSphereGraphFormat.setVertexKind(vertex, VertexKind.EOBJECT); ChronoSphereGraphFormat.setEClassForEObjectVertex(cep, vertex, eClass); return this.createEObjectForVertex(cep, vertex); } @Override public void clearEContainerAndEContainingFeatureSilent(final InternalEObject object) { this.assertTxOpen(); ChronoEObjectInternal eObject = this.assertIsChronoEObject(object); Vertex vertex = this.getEObjectVertex(eObject); ChronoSphereGraphFormat.setEContainer(vertex, null); ChronoSphereGraphFormat.setEContainingFeatureId(vertex, null); } // ===================================================================================================================== // MISCELLANEOUS PUBLIC API // ===================================================================================================================== public void deepMerge(final Collection<ChronoEObjectInternal> mergeObjects) { this.deepMerge(mergeObjects, null, false, 0); } public void deepMergeIncremental(final Collection<ChronoEObjectInternal> mergeObjects, final ChronoSphereTransaction tx, final int batchSize) { checkNotNull(mergeObjects, "Precondition violation - argument 'eObject' must not be NULL!"); checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkArgument(batchSize > 0, "Precondition violation - argument 'batchSize' must be greater than zero!"); this.deepMerge(mergeObjects, tx, true, batchSize); } public void deepDelete(final Collection<ChronoEObjectInternal> eObjectsToDelete, final boolean cascadeDeletionToEContents) { checkNotNull(eObjectsToDelete, "Precondition violation - argument 'eObjectsToDelete' must not be NULL!"); this.deepDelete(eObjectsToDelete, null, false, 0, cascadeDeletionToEContents); } public void deepDelete(final Collection<ChronoEObjectInternal> eObjectsToDelete, final ChronoSphereTransaction tx, final int batchSize, final boolean cascadeDeletionToEContents) { this.deepDelete(eObjectsToDelete, tx, true, batchSize, cascadeDeletionToEContents); } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= private void deepMerge(final Collection<ChronoEObjectInternal> mergeObjects, final ChronoSphereTransaction tx, final boolean useIncrementalCommits, final int batchSize) { Set<ChronoEObjectInternal> objectsToMerge = Sets.newHashSet(); for (ChronoEObjectInternal eObject : mergeObjects) { TreeIterator<EObject> contents = eObject.eAllContents(); objectsToMerge.add(eObject); while (contents.hasNext()) { objectsToMerge.add((ChronoEObjectInternal) contents.next()); } } int currentBatchSize = 0; // in the first iteration, create the EObject vertices in the graph and merge the EAttributes for (ChronoEObjectInternal currentEObject : objectsToMerge) { this.mergeObjectAndAttributes(currentEObject); currentBatchSize++; if (useIncrementalCommits && currentBatchSize >= batchSize) { tx.commitIncremental(); currentBatchSize = 0; } } // having created all vertices, we can now merge the eReferences for (ChronoEObjectInternal currentEObject : objectsToMerge) { this.mergeEReferencesAndEContainer(currentEObject); currentBatchSize++; if (useIncrementalCommits && currentBatchSize >= batchSize) { tx.commitIncremental(); currentBatchSize = 0; } } // as the last step, replace the in-memory stores with the graph store for (ChronoEObjectInternal currentEObject : objectsToMerge) { currentEObject.eSetStore(this); currentBatchSize++; if (useIncrementalCommits && currentBatchSize >= batchSize) { tx.commitIncremental(); currentBatchSize = 0; } } } private void mergeObjectAndAttributes(final ChronoEObjectInternal eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); if (eObject.isAttached()) { // already attached to the store, nothing to merge return; } ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); // create a vertex for the eObject Vertex vertex = this.createVertexForEObject(eObject); for (EAttribute eAttribute : eObject.eClass().getEAllAttributes()) { if (eObject.eIsSet(eAttribute) == false) { // ignore eAttributes that have no value assigned in the given EObject continue; } Object value = eObject.eGet(eAttribute); if (eAttribute.isMany()) { ChronoSphereGraphFormat.setEAttributeValues(ePackage, vertex, eAttribute, (Collection<?>) value); } else { ChronoSphereGraphFormat.setEAttributeValue(ePackage, vertex, eAttribute, value); } } } @SuppressWarnings("unchecked") private void mergeEReferencesAndEContainer(final ChronoEObjectInternal eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); if (eObject.isAttached()) { // already attached to the store, nothing to merge return; } ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); // get the vertex for this EObject Vertex vertex = Iterators.getOnlyElement(this.getGraph().vertices(eObject.getId())); // set the eContainer (if any) ChronoEObjectInternal eContainer = (ChronoEObjectInternal) eObject.eContainer(); if (eContainer != null) { Vertex eContainerVertex = this.getEObjectVertex(eContainer); ChronoSphereGraphFormat.setEContainer(vertex, eContainerVertex); EStructuralFeature eContainingFeature = eObject.eContainingFeature(); if (eContainingFeature != null) { int containingFeatureID = -1; if (eObject.eClass().getFeatureID(eContainingFeature) >= 0) { // containing feature belongs to our class, use the ID containingFeatureID = eObject.eClass().getFeatureID(eContainingFeature); } else { // containing feature belongs to eContainer class containingFeatureID = -1 - eContainingFeature.getFeatureID(); } ChronoSphereGraphFormat.setEContainingFeatureId(vertex, containingFeatureID); } } // map the EReferences for (EReference eReference : eObject.eClass().getEAllReferences()) { if (eObject.eIsSet(eReference) == false) { // reference is not set on this EObject, nothing to merge continue; } Object value = eObject.eGet(eReference); if (eReference.isMany()) { List<ChronoEObjectInternal> targets = (List<ChronoEObjectInternal>) value; List<Vertex> targetVertices = targets.stream().map(obj -> this.getEObjectVertex(obj)) .filter(obj -> obj != null).collect(Collectors.toList()); ChronoSphereGraphFormat.setEReferenceTargets(ePackage, vertex, eReference, targetVertices); } else { ChronoEObjectInternal target = (ChronoEObjectInternal) value; Vertex targetVertex = this.getEObjectVertex(target); if (targetVertex == null) { // the target EObject is not attached to the store! continue; } ChronoSphereGraphFormat.setEReferenceTarget(ePackage, vertex, eReference, targetVertex); } } } private Vertex createVertexForEObject(final ChronoEObjectInternal eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); ChronoEPackageRegistry ePackage = this.getEPackageRegistry(); Vertex vertex = this.getGraph().addVertex(T.id, eObject.getId()); ChronoSphereGraphFormat.setVertexKind(vertex, VertexKind.EOBJECT); ChronoSphereGraphFormat.setEClassForEObjectVertex(ePackage, vertex, eObject.eClass()); return vertex; } private void assertTxOpen() { if (this.owningTransaction.isClosed()) { throw new IllegalStateException("ChronoSphereTransaction has already been closed!"); } } private ChronoGraph getGraph() { return this.owningTransaction.getGraph(); } private ChronoEObjectInternal assertIsChronoEObject(final EObject eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkArgument(eObject instanceof ChronoEObject, "Precondition violation - argument 'eObject' is no ChronoEObject! Did you use the correct EFactory in your EPackage?"); return (ChronoEObjectInternal) eObject; } private Vertex getEObjectVertex(final ChronoEObject object) { String id = object.getId(); Iterator<Vertex> iterator = this.getGraph().vertices(id); return Iterators.getOnlyElement(iterator, null); } private ChronoEPackageRegistry getEPackageRegistry() { return this.owningTransaction.getEPackageRegistry(); } private ChronoEObjectInternal createEObjectForVertex(final ChronoEPackageRegistry cep, final Vertex vertex) { // checkNotNull(cep, "Precondition violation - argument 'cep' must not be NULL!"); // checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); // String id = (String) vertex.id(); // EClass eClass = ChronoSphereGraphFormat.getEClassForEObjectVertex(cep, vertex); // ChronoEObjectInternal eObject = new ChronoEObjectImpl(id, eClass, this); // return eObject; return (ChronoEObjectInternal) this.owningTransaction.getEObjectById((String) vertex.id()); } private EList<Object> getListOfValuesFor(final ChronoEPackageRegistry cep, final Vertex vertex, final EStructuralFeature feature) { checkNotNull(cep, "Precondition violation - argument 'cep' must not be NULL!"); checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); EList<Object> eList = new BasicEList<>(); if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; eList.addAll(ChronoSphereGraphFormat.getEAttributeValues(cep, vertex, eAttribute)); return eList; } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; List<Vertex> vertices = ChronoSphereGraphFormat.getEReferenceTargets(cep, vertex, eReference); for (Vertex eObjectVertex : vertices) { ChronoEObjectInternal eObjectForVertex = this.createEObjectForVertex(cep, eObjectVertex); eList.add(eObjectForVertex); } return eList; } else { throw unknownFeatureTypeException(feature); } } private Object getSingleValueFor(final ChronoEPackageRegistry ePackage, final Vertex vertex, final EStructuralFeature feature) { if (feature instanceof EAttribute) { EAttribute attribute = (EAttribute) feature; return ChronoSphereGraphFormat.getEAttributeValue(ePackage, vertex, attribute); } else if (feature instanceof EReference) { EReference reference = (EReference) feature; Vertex targetVertex = ChronoSphereGraphFormat.getEReferenceTarget(ePackage, vertex, reference); if (targetVertex == null) { return null; } else { return this.createEObjectForVertex(ePackage, targetVertex); } } else { throw unknownFeatureTypeException(feature); } } private static RuntimeException unknownFeatureTypeException(final EStructuralFeature feature) { String className = feature.getClass().getName(); return new RuntimeException("Encountered unknown subclass of EStructuralFeature: '" + className + "'!"); } private void writeListOfValuesToGraph(final ChronoEPackageRegistry ePackage, final Vertex vertex, final EStructuralFeature feature, final List<Object> list) { if (feature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) feature; ChronoSphereGraphFormat.setEAttributeValues(ePackage, vertex, eAttribute, Lists.newArrayList(list)); } else if (feature instanceof EReference) { EReference eReference = (EReference) feature; if (list == null || list.isEmpty()) { // "unset" the reference, clear it in the graph ChronoSphereGraphFormat.setEReferenceTargets(ePackage, vertex, eReference, null); } else { // for each target EObject, identify the corresponding vertex List<Vertex> targetVertices = Lists.newArrayList(); for (Object target : list) { // we already know it's an EObject, because EReference targets can only be EObjects. EObject targetEObject = (EObject) target; targetVertices.add(this.getEObjectVertex((ChronoEObject) targetEObject)); } ChronoSphereGraphFormat.setEReferenceTargets(ePackage, vertex, eReference, targetVertices); } } else { throw unknownFeatureTypeException(feature); } } private void deepDelete(final Collection<ChronoEObjectInternal> eObjectsToDelete, final ChronoSphereTransaction tx, final boolean useIncrementalCommits, final int batchSize, final boolean cascadeDeletionToEContents) { Set<ChronoEObjectInternal> allEObjectsToDelete = Sets.newHashSet(); if (cascadeDeletionToEContents) { for (ChronoEObjectInternal eObject : eObjectsToDelete) { TreeIterator<EObject> contents = eObject.eAllContents(); allEObjectsToDelete.add(eObject); while (contents.hasNext()) { allEObjectsToDelete.add((ChronoEObjectInternal) contents.next()); } } } else { allEObjectsToDelete.addAll(eObjectsToDelete); } int currentBatchSize = 0; // in the first iteration, create the EObject vertices in the graph and merge the EAttributes for (ChronoEObjectInternal currentEObject : allEObjectsToDelete) { Vertex vertex = ChronoSphereGraphFormat.getVertexForEObject(this.getGraph(), currentEObject); if (vertex == null) { // already deleted continue; } vertex.remove(); currentBatchSize++; if (useIncrementalCommits && currentBatchSize >= batchSize) { tx.commitIncremental(); currentBatchSize = 0; } } } }
38,677
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEObjectInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/api/ChronoEObjectInternal.java
package org.chronos.chronosphere.emf.internal.api; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.internal.impl.store.ChronoGraphEStore; import org.eclipse.emf.ecore.InternalEObject; public interface ChronoEObjectInternal extends ChronoEObject, InternalEObject { public ChronoEObjectLifecycle getLifecycleStatus(); public void setLifecycleStatus(ChronoEObjectLifecycle status); public void unsetEContainerSilent(); public default boolean isAttached() { return this.eStore() instanceof ChronoGraphEStore; } }
566
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoResource.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/api/ChronoResource.java
package org.chronos.chronosphere.emf.internal.api; import java.util.Date; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronograph.api.transaction.ChronoGraphTransaction; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.exceptions.ChronoSphereCommitException; import org.chronos.chronosphere.api.exceptions.ResourceIsAlreadyClosedException; import org.eclipse.emf.ecore.resource.Resource; public interface ChronoResource extends Resource, AutoCloseable { /** * Returns the graph transaction to which this resource is currently bound. * * <p> * Over the lifetime of a resource, it can be bound to several different transactions (but never more than one at a * time). * * @return The graph transaction this resource is currently bound to. Never <code>null</code>. * * @throws ResourceIsAlreadyClosedException * Thrown if {@link #isOpen()} returns <code>false</code> and this method was called. */ public ChronoGraphTransaction getGraphTransaction(); /** * Returns the timestamp on which the resource is currently operating. * * @return The current timestamp. Never negative. May be zero. * * @throws ResourceIsAlreadyClosedException * Thrown if {@link #isOpen()} returns <code>false</code> and this method was called. */ public default long getTimestamp() { return this.getGraphTransaction().getTimestamp(); } /** * Returns the {@link ChronoGraph} instance associated with this resource. * * @return The graph instance. Never <code>null</code>. * * @throws ResourceIsAlreadyClosedException * Thrown if {@link #isOpen()} returns <code>false</code> and this method was called. */ public default ChronoGraph getGraph() { return this.getGraphTransaction().getGraph(); } /** * Closes this resource. * * * <p> * <b>/!\ WARNING:</b> Closing a resource before saving it will roll back any changes on the resource or its * attached elements! * * <p> * If this resource is already closed, this method is a no-op and returns immediately. * * * * <p> * This method overrides {@link AutoCloseable#close()} and removes the <code>throws Exception</code> declaration. * This method will not throw checked exceptions. */ @Override public void close(); /** * Checks if this resource is still open. * * @return <code>true</code> if the resource is still open, or <code>false</code> if it has been closed. */ public boolean isOpen(); /** * Checks if this resource is closed. * * <p> * This is just syntactic sugar for <code>isOpen() == false</code>. * * @return <code>true</code> if the resource is closed, otherwise <code>false</code>. */ public default boolean isClosed() { return this.isOpen() == false; } /** * Rolls back all changes performed in the context of this resource. * * <p> * After this operation returns, it will be in sync with the persistence backend, at the specified timestamp. The * resource itself remains open and client code may continue using it as usual. * * <p> * <b>/!\ WARNING:</b><br> * This operation <b>cannot be undone</b> and all uncommitted changes will be <b>permanently lost!</b> * * @throws ResourceIsAlreadyClosedException * Thrown if {@link #isOpen()} returns <code>false</code> and this method was called. */ public void rollback(); /** * Performs a full commit of the changes performed in the context of this resource. * * <p> * After this operation returns, the changes will be persisted, and the timestamp of the resource will be advanced * to the commit timestamp. This implies that all changes by the commit will continue to be visible, but also * commits performed by other transactions will be visible. * * <p> * Please note that each full commit creates a new revision for all changed elements. For larger processes (e.g. * batch imports) which should show up as a single commit in the history, but have change sets which are too big to * fit into main memory, clients may use {@link #commitIncremental()} instead. * * @throws ResourceIsAlreadyClosedException * Thrown if {@link #isOpen()} returns <code>false</code> and this method was called. * * @see #commitIncremental() */ public void commit(); /** * Performs an incremental commit on this resource. * * <p> * Incremental commits can be used to insert large batches of data into a repository. Their advantage over normal * commits is that they do not require the entire data to be contained in main memory before writing it to the * storage backend. * * <p> * Recommended usage of this method: * * <pre> * ChronoResource resource = ...; // acquire a resource * try { * // ... do some heavy work * resource.commitIncremental(); * // ... more work... * resource.commitIncremental(); * // ... more work... * // ... and finally, accept the changes and make them visible to others * resource.commit(); * } finally { * // make absolutely sure that the incremental process is terminated in case of error * resource.rollback(); * } * </pre> * * <p> * Using an incremental commit implies all of the following facts: * <ul> * <li>Only one incremental commit process may be active on any given {@link ChronoSphere} instance at any point in * time. Attempting to have multiple incremental commit processes on the same {@link ChronoSphere} instance will * result in a {@link ChronoSphereCommitException} on all processes, except for the first process. * <li>While an incremental commit process is active, no regular commits on other transactions can be accepted. * <li>Other transactions may continue to read data while an incremental commit process is active, but they cannot * see the changes made by incremental commits. * <li>An incremental commit process consists of several calls to {@link #commitIncremental()}, and is terminated * either by a full-fledged {@link #commit()}, or by a {@link #rollback()}. * <li>It is the responsibility of the caller to ensure that either {@link #commit()} or {@link #rollback()} are * called after the initial {@link #commitIncremental()} was called. Failure to do so will result in this * {@link ChronoSphere} instance no longer accepting any commits. * <li>After the terminating {@link #commit()}, the changes will be visible to other transactions, provided that * they use an appropriate timestamp. * <li>The timestamp of all changes in an incremental commit process is the timestamp of the first * {@link #commitIncremental()} invocation. * <li>In contrast to regular transactions, several calls to {@link #commitIncremental()} may modify the same data. * Overwrites within the same incremental commit process are <b>not</b> tracked by the versioning system, and follow * the "last writer wins" principle. * <li>In the history of any given key, an incremental commit process appears as a single, large commit. In * particular, it is not possible to select a point in time where only parts of the incremental commit process were * applied. * <li>A call to {@link #commitIncremental()} does not update the "now" (head revision) timestamp. Only the * terminating call to {@link #commit()} updates this timestamp. * <li>The timestamp of the transaction executing the incremental commit will be increased after each call to * {@link #commitIncremental()} in order to allow the transaction to read the data it has written in the incremental * update. If the incremental commit process fails at any point, this timestamp will be reverted to the original * timestamp of the transaction before the incremental commit process started. * <li>Durability of the changes made by {@link #commitIncremental()} can only be guaranteed by {@link ChronoSphere} * if the terminating call to {@link #commit()} is successful. Any other changes may be lost in case of errors. * <li>If the JVM process is terminated during an incremental commit process, and the terminating call to * {@link #commit()} has not yet been completed successfully, any data stored by that process will be lost and * rolled back on the next startup. * </ul> * * @throws ChronoSphereCommitException * Thrown if the commit fails. If this exception is thrown, the entire incremental commit process is * aborted, and any changes to the data made by that process will be rolled back. * @throws ResourceIsAlreadyClosedException * Thrown if {@link #isOpen()} returns <code>false</code> and this method was called. */ public void commitIncremental(); /** * Returns the time machine that is bound to this resource. * * @return The time machine. Never <code>null</code>. */ public TimeMachine timeMachine(); /** * The {@link TimeMachine} controls the point in time at which data is read in an associated {@link ChronoResource}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface TimeMachine { /** * Performs a time jump with the attached {@link ChronoResource} to the specified timestamp. * * <p> * Please note that the timestamp is subject to the following conditions: * <ul> * <li>The timestamp must never be negative. * <li>The timestamp must not be greater than the timestamp of the last commit in the repository (i.e. it must * not be "in the future"). * </ul> * * Other than the conditions outlined above, the timestamp can be chosen freely. In particular, it does not need * to (but may) exactly match the timestamp of a past commit. * * @param timestamp * The timestamp to jump to. Must match the criteria outlined above. * @see #jumpTo(Date) */ public void jumpTo(long timestamp); /** * Performs a time jump with the attached {@link ChronoResource} to the specified date. * * <p> * Please note that the date is subject to the following conditions: * <ul> * <li>It must not be <code>null</code>. * <li>The date must not be after the timestamp of the last commit in the repository (i.e. it must not be * "in the future"). * </ul> * * Other than the conditions outlined above, the date can be chosen freely. In particular, it does not need to * (but may) exactly match the date of a past commit. * * @param date * The date to jump to. Must match the criteria outlined above. */ public void jumpTo(Date date); /** * Performs a time jump with the attached {@link ChronoResource} to the latest commit (present). * * <p> * Use this method to see the changes made by other participants to the repository since the creation of the * attached {@link ChronoResource}. */ public void jumpToPresent(); } }
10,894
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEObjectLifecycle.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/api/ChronoEObjectLifecycle.java
package org.chronos.chronosphere.emf.internal.api; public enum ChronoEObjectLifecycle { TRANSIENT, PERSISTENT_CLEAN, PERSISTENT_MODIFIED, PERSISTENT_REMOVED; public boolean isTransient() { return TRANSIENT.equals(this); } public boolean isPersistent() { return this.isTransient() == false; } public boolean isRemoved() { return PERSISTENT_REMOVED.equals(this); } }
383
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EMFUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/internal/util/EMFUtils.java
package org.chronos.chronosphere.emf.internal.util; import static com.google.common.base.Preconditions.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.chronos.chronosphere.api.exceptions.EPackagesAreNotSelfContainedException; import org.chronos.chronosphere.api.exceptions.emf.NameResolutionException; import org.chronos.chronosphere.api.exceptions.emf.XMIConversionFailedException; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; public class EMFUtils { public static final String PACKAGE_PATH_SEPARATOR = "::"; public static final String CLASS_FEATURE_SEPARATOR = "#"; /** * Factory method: Instantiates a new default {@link ResourceSet}. * * <p> * The new resource set will always have the XMI factory associated with the "*.xmi" file ending. * * @return The new resource set. Never <code>null</code>. */ public static ResourceSet createResourceSet() { return createResourceSet(Collections.emptySet()); } /** * Factory method: Instantiates a new default {@link ResourceSet}. * * <p> * The new resource set will always have the XMI factory associated with the "*.xmi" file ending. * * @param ePackages * The {@link EPackage}s to register at the resource set. Must not be <code>null</code>. * * @return The new resource set. Never <code>null</code>. */ public static ResourceSet createResourceSet(final Set<EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); ResourceSet resSet = new ResourceSetImpl(); // make sure that XMI is available resSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); for (EPackage ePackage : ePackages) { resSet.getPackageRegistry().put(ePackage.getNsURI(), ePackage); } return resSet; } /** * Creates a temporary resource.<br> * The resource will be contained in a (new) temporary resource set. It is important <b>not</b> to save this * resource to disk! * * @param name * The name of the resource (implementation will be selected based on ending) * @param contents * The contents to put into the new temporary resource * @return The resource with the given contents and name */ public static Resource createTemporaryResource(final String name, final EObject... contents) { return createTemporaryResource(name, Collections.emptySet(), contents); } /** * Creates a temporary resource.<br> * The resource will be contained in a (new) temporary resource set. It is important <b>not</b> to save this * resource to disk! * * @param name * The name of the resource (implementation will be selected based on ending) * @param ePackages * The {@link EPackage}s to register at the temporary {@link ResourceSet}. Must not be <code>null</code>. * @param contents * The contents to put into the new temporary resource * @return The resource with the given contents and name */ public static Resource createTemporaryResource(final String name, final Set<EPackage> ePackages, final EObject... contents) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); ResourceSet resSet = createResourceSet(ePackages); return createTemporaryResource(resSet, name, contents); } /** * Creates a temporary resource.<br> * It is important <b>not</b> to save this resource to disk! * * @param set * The {@link ResourceSet} to put this resource into * @param name * The name of the resource (implementation will be selected based on ending) * @param contents * The contents to put into the new temporary resource * @return The resource with the given contents and name */ public static Resource createTemporaryResource(final ResourceSet set, final String name, final EObject... contents) { Resource res = set.createResource(URI.createPlatformResourceURI("TEMP/" + name, false)); for (EObject obj : contents) { res.getContents().add(obj); } return res; } /** * Writes the given {@link EPackage} to XMI. * * @param ePackage * The EPackage to convert to XMI. Must not be <code>null</code>. * @return The XMI representation of the EPackage. Never <code>null</code>. */ public static String writeEPackageToXMI(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); return writeEPackagesToXMI(Collections.singleton(ePackage)); } /** * Writes the given {@link EPackage}s to XMI. * * @param ePackages * The EPackages to convert to XMI. Must not be <code>null</code>. * @return The XMI representation of the EPackages. Never <code>null</code>. */ public static String writeEPackagesToXMI(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); try { return writeEObjectsToXMI(ePackages); } catch (XMIConversionFailedException e) { throw new XMIConversionFailedException("Could not convert EPackages to XMI!", e); } } /** * Reads the given XMI contents and converts them into an {@link EPackage}. * * <p> * It is the responsibility of the caller to assert that there is exactly one {@link EObject} in the given XMI data, * and that this object is an instance of {@link EPackage}. * * @param xmiContents * The XMI data that contains the EPackage to deserialize. Must not be <code>null</code>. * @return The EPackage that was contained in the given XMI data. May be <code>null</code> if the XMI data was * empty. */ public static EPackage readEPackageFromXMI(final String xmiContents) { checkNotNull(xmiContents, "Precondition violation - argument 'xmiContents' must not be NULL!"); try { List<EObject> eObjects = readEObjectsFromXMI(xmiContents); if (eObjects == null || eObjects.isEmpty()) { return null; } EObject singleObject = Iterables.getOnlyElement(eObjects); if (singleObject instanceof EPackage == false) { throw new IllegalStateException( "Attempted to read EPackage from XMI, but encountered EObject with EClass '" + singleObject.eClass().getName() + "'!"); } return (EPackage) singleObject; } catch (XMIConversionFailedException e) { throw new XMIConversionFailedException("Could not read EPackage from XMI data!", e); } } public static List<EPackage> readEPackagesFromXMI(final String xmiContents) { checkNotNull(xmiContents, "Precondition violation - argument 'xmiContents' must not be NULL!"); try { List<EObject> eObjects = readEObjectsFromXMI(xmiContents); if (eObjects == null || eObjects.isEmpty()) { return null; } List<EPackage> ePackages = Lists.newArrayList(); eObjects.forEach(eObject -> { if (eObject instanceof EPackage == false) { throw new IllegalStateException( "Attempted to read EPackage from XMI, but encountered EObject with EClass '" + eObject.eClass().getName() + "'!"); } ePackages.add((EPackage) eObject); }); return ePackages; } catch (XMIConversionFailedException e) { throw new XMIConversionFailedException("Could not read EPackage from XMI data!", e); } } /** * Writes the given {@link EObject} into its XMI representation. * * @param eObject * The EObject to convert to XMI. Must not be <code>null</code>. * @return The XMI representation of the given EObject. Never <code>null</code>. */ public static String writeEObjectToXMI(final EObject eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); return writeEObjectsToXMI(Collections.singleton(eObject)); } /** * Writse the given (@link EObject}s into their XMI representation. * * @param eObjects * The EObjects to convert to XMI. Must not be <code>null</code>. * @return The XMI representation of the given EObjects. Never <code>null</code>. */ public static String writeEObjectsToXMI(final Iterable<? extends EObject> eObjects) { checkNotNull(eObjects, "Precondition violation - argument 'eObjects' must not be NULL!"); EObject[] eObjectArray = Iterables.toArray(eObjects, EObject.class); Resource resource = createTemporaryResource("temp.xmi", eObjectArray); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { resource.save(baos, null); String xmi = baos.toString(); return xmi; } catch (IOException ioe) { throw new XMIConversionFailedException("Could not convert EObject to XMI!", ioe); } } /** * Reads the {@link EObject}s contained in the given XMI data. * * @param xmiContents * The XMI data to deserialize the EObjects from. Must not be <code>null</code>. * @return The list of deserialized EObjects. May be empty, but never <code>null</code>. */ public static List<EObject> readEObjectsFromXMI(final String xmiContents) { checkNotNull(xmiContents, "Precondition violation - argument 'xmiContents' must not be NULL!"); return readEObjectsFromXMI(xmiContents, Collections.emptySet()); } /** * Reads the {@link EObject}s contained in the given XMI data. * * @param xmiContents * The XMI data to deserialize the EObjects from. Must not be <code>null</code>. * @param ePackages * The {@link EPackage}s to use for reading the XMI contents. Must not be <code>null</code>. * * @return The list of deserialized EObjects. May be empty, but never <code>null</code>. */ public static List<EObject> readEObjectsFromXMI(final String xmiContents, final Set<EPackage> ePackages) { checkNotNull(xmiContents, "Precondition violation - argument 'xmiContents' must not be NULL!"); checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); Resource resource = createTemporaryResource("temp.xmi", ePackages); try (ByteArrayInputStream bais = new ByteArrayInputStream(xmiContents.getBytes())) { resource.load(bais, null); return resource.getContents(); } catch (IOException ioe) { throw new XMIConversionFailedException("Could not read EObject(s) from XMI data!", ioe); } } /** * Checks that the given {@link File} is an XMI file. * * @param file * The file to check. Must not be <code>null</code>. * * @return <code>true</code> if the given file is an XMI file, otherwise <code>false</code>. * * @see #assertIsXMIFile(File) */ public static boolean isXMIFile(final File file) { if (file == null) { return false; } if (file.exists() == false) { return false; } if (file.isFile() == false) { return false; } if (file.getName().endsWith(".xmi") == false) { return false; } return true; } /** * Asserts that the given file is a valid, existing XMI file. * * @param file * The file to check. Must not be <code>null</code>. * * @throws IllegalArgumentException * Thrown if there are some irregularities with the given XMI file. The description of the exception * provides details. */ public static void assertIsXMIFile(final File file) { checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!"); checkArgument(file.exists(), "Precondition violation - the given XMI File does not exist!"); checkArgument(file.isFile(), "Precondition violation - the given XMI File is a directory, not a file!"); checkArgument(file.getName().endsWith(".xmi"), "Precondition violation - the given file does not end with '*.xmi'!"); } /** * A specialized version of {@link EObject#eGet(org.eclipse.emf.ecore.EStructuralFeature) eGet(...)} that works for * multiplicity-many {@link EReference}s only. * * @param eObject * The eObject to run the operation on. Must not be <code>null</code>. * @param eReference * The EReference to retrieve the targets for. Must not be <code>null</code>, must be multiplicity-many. * @return The EObject-backed list of targets. May be empty, but never <code>null</code>. */ public static EList<EObject> eGetMany(final EObject eObject, final EReference eReference) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); checkArgument(eReference.isMany(), "Precondition violation - argument 'eReference' must be multiplicity-many!"); @SuppressWarnings("unchecked") EList<EObject> list = (EList<EObject>) eObject.eGet(eReference); return list; } /** * Given a collection of {@link EPackage}s, this method returns all {@link EReference}s with * {@link EReference#getEReferenceType() target types} that are not contained in any of the given EPackages, * E-Sub-Packages, or the Ecore EPackage. * * @param ePackages * The EPackages to check (recursively). Must not be <code>null</code>, may be empty. * @return The set of {@link EReference}s that have target types outside the given EPackages (and also outside the * Ecore EPackage). Never <code>null</code>, may be empty. * * @see #areEPackagesSelfContained(Iterable) * @see #assertEPackagesAreSelfContained(Iterable) */ public static Set<EReference> getEReferencesWithNonContainedEReferenceTypes( final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); // flatten the EPackage hierarchy Set<EPackage> allEPackages = flattenEPackages(ePackages); // all elements from the Ecore EPackage are also okay, even if they are not contained in the set above Set<EPackage> containedEPackages = Sets.newHashSet(allEPackages); containedEPackages.addAll(flattenEPackage(EcorePackage.eINSTANCE)); // prepare the result set Set<EReference> resultSet = Sets.newHashSet(); // for each ePackage, iterate over all EClasses, and find all EReferences with a target type that is NOT // contained in any known epackage for (EPackage ePackage : allEPackages) { for (EClassifier eClassifier : ePackage.getEClassifiers()) { if (eClassifier instanceof EClass == false) { // ignore non-eclasses continue; } EClass eClass = (EClass) eClassifier; for (EReference eReference : eClass.getEAllReferences()) { EClass eReferenceType = eReference.getEReferenceType(); EPackage owningEPackage = eReferenceType.getEPackage(); if (containedEPackages.contains(owningEPackage) == false) { resultSet.add(eReference); } } } } return resultSet; } /** * Asserts that the given collection of {@link EPackage}s is self-contained, i.e. does not reference any * {@link EClass}es that reside outside the given collection of EPackages (and also outside of the * {@link EcorePackage} ). * * @param ePackages * The {@link EPackage}s to check. Must not be <code>null</code>. May be empty. * @return <code>true</code> if the given collection of {@link EPackage}s is self-contained, otherwise * <code>false</code>. * * @see #getEReferencesWithNonContainedEReferenceTypes(Iterable) * @see #assertEPackagesAreSelfContained(Iterable) */ public static boolean areEPackagesSelfContained(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); Set<EReference> nonContainedReferences = getEReferencesWithNonContainedEReferenceTypes(ePackages); if (nonContainedReferences.isEmpty() == false) { return false; } else { return true; } } /** * Asserts that the given collection of {@link EPackage}s is self-contained, i.e. does not reference any * {@link EClass}es that reside outside the given collection of EPackages (and also outside of the * {@link EcorePackage} ). * * @param ePackages * The {@link EPackage}s to check. Must not be <code>null</code>. May be empty. * @throws EPackagesAreNotSelfContainedException * Thrown if there is at least one {@link EReference} in the given EPackages that points to an EClass * that is not (recursively) contained in the given EPackages. * * @see #getEReferencesWithNonContainedEReferenceTypes(Iterable) * @see #areEPackagesSelfContained(Iterable) */ public static void assertEPackagesAreSelfContained(final Iterable<? extends EPackage> ePackages) throws EPackagesAreNotSelfContainedException { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); Set<EReference> nonContainedReferences = getEReferencesWithNonContainedEReferenceTypes(ePackages); if (nonContainedReferences.isEmpty()) { return; } throw new EPackagesAreNotSelfContainedException(nonContainedReferences); } /** * "Flattens" the given {@link EPackage} by iterating recursively over its sub-packages and throwing all encountered * packages into a set. * * @param ePackage * The EPackage to flatten. Must not be <code>null</code>. * @return A set containing the given EPackage, plus all of its sub-EPackages (recursively). Never <code>null</code> * , never empty. */ public static Set<EPackage> flattenEPackage(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); return flattenEPackages(Collections.singleton(ePackage)); } /** * "Flattens" the given collection of {@link EPackage}s by iterating recursively over their sub-packages and * throwing all encountered packages into a set. * * @param ePackages * The EPackages to flatten. Must not be <code>null</code>. May be empty. * @return A set containing the given EPackage, plus all of its sub-EPackages (recursively). Never <code>null</code> * , may be empty. */ public static Set<EPackage> flattenEPackages(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); Set<EPackage> flattenedEPackages = Sets.newHashSet(); for (EPackage rootEPackage : ePackages) { flattenedEPackages.add(rootEPackage); TreeIterator<EObject> eAllContents = rootEPackage.eAllContents(); eAllContents.forEachRemaining(eObject -> { if (eObject instanceof EPackage) { flattenedEPackages.add((EPackage) eObject); } }); } return flattenedEPackages; } /** * "Flattens" the given collection of {@link EPackage}s by iterating recursively over their sub-packages and * throwing all encountered packages into a set. * * @param ePackages * The EPackages to flatten. Must not be <code>null</code>. May be empty. * @return A set containing the given EPackage, plus all of its sub-EPackages (recursively). Never <code>null</code> * , may be empty. */ public static Set<EPackage> flattenEPackages(final Iterator<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); Set<EPackage> flattenedEPackages = Sets.newHashSet(); while (ePackages.hasNext()) { EPackage rootEPackage = ePackages.next(); flattenedEPackages.add(rootEPackage); TreeIterator<EObject> eAllContents = rootEPackage.eAllContents(); eAllContents.forEachRemaining(eObject -> { if (eObject instanceof EPackage) { flattenedEPackages.add((EPackage) eObject); } }); } return flattenedEPackages; } /** * Finds and returns the {@link EReference} with the given name in the given {@link EClass}. * * @param eClass * The EClass to get the EReference from. Must not be <code>null</code>. * @param name * The name of the EReference to look for. Must not be <code>null</code>. * * @return The EReference that is owned by the given EClass and has the given name, or <code>null</code> if none * exists. */ public static EReference getEReference(final EClass eClass, final String name) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); return eClass.getEAllReferences().stream().filter(eRef -> eRef.getName().equals(name)).findFirst().orElse(null); } /** * Finds and returns the {@link EAttribute} with the given name in the given {@link EClass}. * * @param eClass * The EClass to get the EAttribute from. Must not be <code>null</code>. * @param name * The name of the EAttribute to look for. Must not be <code>null</code>. * * @return The EAttribute that is owned by the given EClass and has the given name, or <code>null</code> if none * exists. */ public static EAttribute getEAttribute(final EClass eClass, final String name) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); return eClass.getEAllAttributes().stream().filter(eAttr -> eAttr.getName().equals(name)).findFirst() .orElse(null); } /** * Returns the fully qualified name for the given {@link EStructuralFeature feature}. * * @param feature * The feature to get the fully qualified name for. Must not be <code>null</code>. * @return The fully qualified name for the given feature. */ public static String fullyQualifiedNameFor(final EStructuralFeature feature) { checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); String eClassName = fullyQualifiedNameFor(feature.getEContainingClass()); return eClassName + CLASS_FEATURE_SEPARATOR + feature.getName(); } /** * Returns the fully qualified name for the given {@link EClass}. * * @param eClass * The EClass to get the fully qualified name for. Must not be <code>null</code>. * @return The fully qualified name for the given EClass. */ public static String fullyQualifiedNameFor(final EClass eClass) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); String ePackageQualifiedName = fullyQualifiedNameFor(eClass.getEPackage()); return ePackageQualifiedName + PACKAGE_PATH_SEPARATOR + eClass.getName(); } /** * Returns the fully qualified name for the given {@link EClassifier}. * * @param eClassifier * The EClassifier to get the fully qualified name for. Must not be <code>null</code>. * @return The fully qualified name for the given EClassifier. */ public static String fullyQualifiedNameFor(final EClassifier eClassifier) { checkNotNull(eClassifier, "Precondition violation - argument 'eClassifier' must not be NULL!"); String ePackageQualifiedName = fullyQualifiedNameFor(eClassifier.getEPackage()); return ePackageQualifiedName + PACKAGE_PATH_SEPARATOR + eClassifier.getName(); } /** * Returns the fully qualified name for the given {@link EPackage}. * * @param ePackage * The EPackage to get the fully qualified name for. Must not be <code>null</code>. * @return The fully qualified name for the given EPackage. */ public static String fullyQualifiedNameFor(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); List<String> qualifierChain = Lists.newArrayList(); EPackage currentEPackage = ePackage; while (currentEPackage != null) { qualifierChain.add(currentEPackage.getName()); currentEPackage = currentEPackage.getESuperPackage(); } List<String> qualifiedNameParts = Lists.reverse(qualifierChain); StringBuilder builder = new StringBuilder(); String separator = ""; for (String namePart : qualifiedNameParts) { builder.append(separator); separator = PACKAGE_PATH_SEPARATOR; builder.append(namePart); } return builder.toString(); } /** * Returns all {@link EClass}es that are <i>directly</i> contained in the given {@link EPackage}. * * @param ePackage * The EPackage to get the directly contained classes for. Must not be <code>null</code>. * @return An unmodifiable set of EClasses which are directly contained in the given EPackage. May be empty, but * never <code>null</code>. * * @see #allEClasses(EPackage) */ public static Set<EClass> eClasses(final EPackage ePackage) { EList<EClassifier> eClassifiers = ePackage.getEClassifiers(); Set<EClass> eClasses = eClassifiers.stream().filter(classifier -> classifier instanceof EClass) .map(classifier -> (EClass) classifier).collect(Collectors.toSet()); return Collections.unmodifiableSet(eClasses); } /** * Returns an {@link Iterable} over all {@link EClass}es that are <i>directly or transitively</i> contained in the * given {@link EPackage}. * * @param ePackage * The EPackage to get the directly and transitively contained EClasses for. Must not be * <code>null</code>. * @return An unmodifiable set of EClasses which are directly or transitively contained in the given EPackage. May * be empty, but never <code>null</code>. * * @see #eClasses(EPackage) */ public static Set<EClass> allEClasses(final EPackage ePackage) { Set<EPackage> packages = flattenEPackage(ePackage); Set<EClass> eClasses = Sets.newHashSet(); for (EPackage pack : packages) { eClasses.addAll(eClasses(pack)); } return Collections.unmodifiableSet(eClasses); } public static Set<EClass> allEClasses(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); return allEClasses(ePackages.iterator()); } public static Set<EClass> allEClasses(final EPackage[] ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); return allEClasses(Arrays.asList(ePackages)); } public static Set<EClass> allEClasses(final Iterator<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); Set<EClass> eClasses = Sets.newHashSet(); while (ePackages.hasNext()) { EPackage ePackage = ePackages.next(); eClasses.addAll(allEClasses(ePackage)); } return Collections.unmodifiableSet(eClasses); } public static EPackage getEPackageByQualifiedName(final Iterable<EPackage> packages, final String qualifiedName) { checkNotNull(packages, "Precondition violation - argument 'packages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : packages) { EPackage resultPackage = getEPackageByQualifiedName(ePackage, qualifiedName); if (resultPackage != null) { return resultPackage; } } return null; } public static EPackage getEPackageByQualifiedName(final Iterator<EPackage> packages, final String qualifiedName) { checkNotNull(packages, "Precondition violation - argument 'packages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); while (packages.hasNext()) { EPackage ePackage = packages.next(); EPackage resultPackage = getEPackageByQualifiedName(ePackage, qualifiedName); if (resultPackage != null) { return resultPackage; } } return null; } public static EPackage getEPackageByQualifiedName(final EPackage[] packages, final String qualifiedName) { checkNotNull(packages, "Precondition violation - argument 'packages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : packages) { EPackage resultPackage = getEPackageByQualifiedName(ePackage, qualifiedName); if (resultPackage != null) { return resultPackage; } } return null; } public static EPackage getEPackageByQualifiedName(final EPackage rootPackage, final String qualifiedName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); String[] parts = qualifiedName.split(PACKAGE_PATH_SEPARATOR); return getEPackageByQualifiedName(rootPackage, parts, 0); } private static EPackage getEPackageByQualifiedName(final EPackage ePackage, final String[] path, final int pathIndex) { String name = path[pathIndex]; if (ePackage.getName().equals(name) == false) { return null; } if (pathIndex + 1 >= path.length) { // it's this package return ePackage; } // step deeper String subPackageName = path[pathIndex + 1]; for (EPackage subPackage : ePackage.getESubpackages()) { if (subPackage.getName().equals(subPackageName)) { return getEPackageByQualifiedName(subPackage, path, pathIndex + 1); } } // not found return null; } public static EClassifier getEClassifierByQualifiedName(final EPackage rootPackage, final String qualifiedName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); String[] path = qualifiedName.split(PACKAGE_PATH_SEPARATOR); if (path.length <= 1) { // not a qualified name return null; } // split the path into the package path and the classifier name String classifierName = path[path.length - 1]; String packagePath = qualifiedName.substring(0, qualifiedName.length() - classifierName.length() - PACKAGE_PATH_SEPARATOR.length()); // get the EPackage EPackage ePackage = getEPackageByQualifiedName(rootPackage, packagePath); if (ePackage == null) { return null; } return ePackage.getEClassifier(classifierName); } public static EClassifier getEClassifierByQualifiedName(final Iterable<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EClassifier classifier = getEClassifierByQualifiedName(ePackage, qualifiedName); if (classifier != null) { return classifier; } } return null; } public static EClassifier getEClassifierByQualifiedName(final Iterator<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); while (rootPackages.hasNext()) { EPackage ePackage = rootPackages.next(); EClassifier classifier = getEClassifierByQualifiedName(ePackage, qualifiedName); if (classifier != null) { return classifier; } } return null; } public static EClassifier getEClassifierByQualifiedName(final EPackage[] rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EClassifier classifier = getEClassifierByQualifiedName(ePackage, qualifiedName); if (classifier != null) { return classifier; } } return null; } public static EClass getEClassByQualifiedName(final EPackage rootPackage, final String qualifiedName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); EClassifier eClassifier = getEClassifierByQualifiedName(rootPackage, qualifiedName); return (EClass) eClassifier; } public static EClass getEClassByQualifiedName(final Iterable<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); EClassifier eClassifier = getEClassifierByQualifiedName(rootPackages, qualifiedName); return (EClass) eClassifier; } public static EClass getEClassByQualifiedName(final Iterator<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); EClassifier eClassifier = getEClassifierByQualifiedName(rootPackages, qualifiedName); return (EClass) eClassifier; } public static EClass getEClassByQualifiedName(final EPackage[] rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); EClassifier eClassifier = getEClassifierByQualifiedName(rootPackages, qualifiedName); return (EClass) eClassifier; } public static EStructuralFeature getFeatureByQualifiedName(final EPackage rootPackage, final String qualifiedName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return getFeatureByQualifiedName(rootPackage, qualifiedName, EStructuralFeature.class); } public static EStructuralFeature getFeatureByQualifiedName(final Iterable<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EStructuralFeature feature = getFeatureByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EStructuralFeature getFeatureByQualifiedName(final EPackage[] rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EStructuralFeature feature = getFeatureByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EStructuralFeature getFeatureByQualifiedName(final Iterator<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); while (rootPackages.hasNext()) { EPackage ePackage = rootPackages.next(); EStructuralFeature feature = getFeatureByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } @SuppressWarnings("unchecked") private static <T extends EStructuralFeature> T getFeatureByQualifiedName(final EPackage rootPackage, final String qualifiedName, final Class<T> featureClass) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); checkNotNull(featureClass, "Precondition violation - argument 'featureClass' must not be NULL!"); int featureSeparatorIndex = qualifiedName.lastIndexOf(CLASS_FEATURE_SEPARATOR); if (featureSeparatorIndex < 0) { // not a qualified feature name return null; } String featureName = qualifiedName.substring(featureSeparatorIndex + 1, qualifiedName.length()); String qualifiedClassName = qualifiedName.substring(0, featureSeparatorIndex); EClass eClass = getEClassByQualifiedName(rootPackage, qualifiedClassName); if (eClass == null) { return null; } if (featureClass.equals(EStructuralFeature.class)) { // we don't care about the type of feature return (T) eClass.getEStructuralFeature(featureName); } else if (featureClass.equals(EAttribute.class)) { return (T) getEAttribute(eClass, featureName); } else if (featureClass.equals(EReference.class)) { return (T) getEReference(eClass, featureName); } else { throw new RuntimeException("Unknown subtype of EStructuralFeature: " + featureClass.getCanonicalName()); } } public static EAttribute getEAttributeByQualifiedName(final EPackage rootPackage, final String qualifiedName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return getFeatureByQualifiedName(rootPackage, qualifiedName, EAttribute.class); } public static EAttribute getEAttributeByQualifiedName(final Iterable<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EAttribute feature = getEAttributeByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EAttribute getEAttributeByQualifiedName(final EPackage[] rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EAttribute feature = getEAttributeByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EAttribute getEAttributeByQualifiedName(final Iterator<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); while (rootPackages.hasNext()) { EPackage ePackage = rootPackages.next(); EAttribute feature = getEAttributeByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EReference getEReferenceByQualifiedName(final EPackage rootPackage, final String qualifiedName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); return getFeatureByQualifiedName(rootPackage, qualifiedName, EReference.class); } public static EReference getEReferenceByQualifiedName(final Iterable<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EReference feature = getEReferenceByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EReference getEReferenceByQualifiedName(final EPackage[] rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); for (EPackage ePackage : rootPackages) { EReference feature = getEReferenceByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EReference getEReferenceByQualifiedName(final Iterator<? extends EPackage> rootPackages, final String qualifiedName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(qualifiedName, "Precondition violation - argument 'qualifiedName' must not be NULL!"); while (rootPackages.hasNext()) { EPackage ePackage = rootPackages.next(); EReference feature = getEReferenceByQualifiedName(ePackage, qualifiedName); if (feature != null) { return feature; } } return null; } public static EPackage getEPackageBySimpleName(final EPackage rootPackage, final String simpleName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return getEPackageBySimpleName(Collections.singleton(rootPackage), simpleName); } public static EPackage getEPackageBySimpleName(final Iterable<? extends EPackage> rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return getEPackageBySimpleName(rootPackages.iterator(), simpleName); } public static EPackage getEPackageBySimpleName(final Iterator<? extends EPackage> rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); Set<EPackage> allPackages = flattenEPackages(rootPackages); EPackage resultPackage = null; for (EPackage ePackage : allPackages) { if (ePackage.getName().equals(simpleName)) { if (resultPackage == null) { resultPackage = ePackage; } else { throw new NameResolutionException("The simple EPackage name '" + simpleName + "' is ambiguous! Candidates are '" + fullyQualifiedNameFor(resultPackage) + "' and '" + fullyQualifiedNameFor(ePackage) + "' (potential others as well)."); } } } return resultPackage; } public static EPackage getEPackageBySimpleName(final EPackage[] rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return getEPackageBySimpleName(Arrays.asList(rootPackages), simpleName); } public static EClassifier getEClassifierBySimpleName(final EPackage rootPackage, final String simpleName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return getEClassifierBySimpleName(Collections.singleton(rootPackage), simpleName); } public static EClassifier getEClassifierBySimpleName(final Iterable<? extends EPackage> rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return getEClassifierBySimpleName(rootPackages.iterator(), simpleName); } public static EClassifier getEClassifierBySimpleName(final EPackage[] rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return getEClassifierBySimpleName(Arrays.asList(rootPackages), simpleName); } public static EClassifier getEClassifierBySimpleName(final Iterator<? extends EPackage> rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); Set<EPackage> allPackages = flattenEPackages(rootPackages); EClassifier resultClassifier = null; for (EPackage ePackage : allPackages) { EClassifier classifier = ePackage.getEClassifier(simpleName); if (classifier != null) { if (resultClassifier == null) { resultClassifier = classifier; } else { throw new NameResolutionException("The simple EClassifier name '" + simpleName + "' is ambiguous! Candidates are '" + fullyQualifiedNameFor(resultClassifier) + "' and '" + fullyQualifiedNameFor(classifier) + "' (potential others as well)."); } } } return resultClassifier; } public static EClass getEClassBySimpleName(final EPackage rootPackage, final String simpleName) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return (EClass) getEClassifierBySimpleName(rootPackage, simpleName); } public static EClass getEClassBySimpleName(final Iterable<? extends EPackage> rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackage' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return (EClass) getEClassifierBySimpleName(rootPackages, simpleName); } public static EClass getEClassBySimpleName(final EPackage[] rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return (EClass) getEClassifierBySimpleName(rootPackages, simpleName); } public static EClass getEClassBySimpleName(final Iterator<? extends EPackage> rootPackages, final String simpleName) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); checkNotNull(simpleName, "Precondition violation - argument 'simpleName' must not be NULL!"); return (EClass) getEClassifierBySimpleName(rootPackages, simpleName); } @SuppressWarnings("unchecked") public static <T> T eGet(final EObject eObject, final String featureName) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkNotNull(featureName, "Precondition violation - argument 'featureName' must not be NULL!"); EStructuralFeature feature = eObject.eClass().getEStructuralFeature(featureName); if (feature == null) { throw new IllegalArgumentException( "EClass '" + eObject.eClass().getName() + "' does not have a feature named '" + featureName + "'!"); } return (T) eObject.eGet(feature); } public static Set<EReference> getEReferencesToEClass(final EPackage ePackage, final EClass targetEClass) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); checkNotNull(targetEClass, "Precondition violation - argument 'targetEClass' must not be NULL!"); return getEReferencesToEClass(Collections.singleton(ePackage), targetEClass); } public static Set<EReference> getEReferencesToEClass(final Iterable<? extends EPackage> ePackages, final EClass targetEClass) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); checkNotNull(targetEClass, "Precondition violation - argument 'targetEClass' must not be NULL!"); return getEReferencesToEClass(ePackages.iterator(), targetEClass); } public static Set<EReference> getEReferencesToEClass(final EPackage[] ePackages, final EClass targetEClass) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); checkNotNull(targetEClass, "Precondition violation - argument 'targetEClass' must not be NULL!"); return getEReferencesToEClass(Arrays.asList(ePackages), targetEClass); } public static Set<EReference> getEReferencesToEClass(final Iterator<? extends EPackage> ePackages, final EClass targetEClass) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); checkNotNull(targetEClass, "Precondition violation - argument 'targetEClass' must not be NULL!"); Set<EReference> resultSet = Sets.newHashSet(); Set<EPackage> packages = flattenEPackages(ePackages); for (EPackage ePackage : packages) { for (EClass eClass : eClasses(ePackage)) { for (EReference eReference : eClass.getEAllReferences()) { if (eReference.getEReferenceType().isSuperTypeOf(targetEClass)) { resultSet.add(eReference); } } } } return resultSet; } public static SetMultimap<EClass, EReference> eClassToIncomingEReferences( final Iterable<? extends EPackage> rootPackages) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); SetMultimap<EClass, EReference> multimap = HashMultimap.create(); for (EPackage ePackage : rootPackages) { for (EClass eClass : allEClasses(ePackage)) { multimap.putAll(eClass, getEReferencesToEClass(rootPackages, eClass)); } } return multimap; } public static SetMultimap<EClass, EReference> eClassToIncomingEReferences( final Iterator<? extends EPackage> rootPackages) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); return eClassToIncomingEReferences(Lists.newArrayList(rootPackages)); } public static SetMultimap<EClass, EReference> eClassToIncomingEReferences(final EPackage[] rootPackages) { checkNotNull(rootPackages, "Precondition violation - argument 'rootPackages' must not be NULL!"); return eClassToIncomingEReferences(Arrays.asList(rootPackages)); } public static SetMultimap<EClass, EReference> eClassToIncomingEReferences(final EPackage rootPackage) { checkNotNull(rootPackage, "Precondition violation - argument 'rootPackage' must not be NULL!"); return eClassToIncomingEReferences(Collections.singleton(rootPackage)); } }
51,647
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEObjectImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/impl/ChronoEObjectImpl.java
package org.chronos.chronosphere.emf.impl; import static com.google.common.base.Preconditions.*; import java.util.UUID; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectLifecycle; import org.chronos.chronosphere.emf.internal.impl.store.ChronoEStore; import org.chronos.chronosphere.emf.internal.impl.store.OwnedTransientEStore; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.EStoreEObjectImpl; import org.eclipse.emf.ecore.impl.MinimalEStoreEObjectImpl; public class ChronoEObjectImpl extends MinimalEStoreEObjectImpl implements ChronoEObject, ChronoEObjectInternal { private String id; private ChronoEObjectLifecycle lifecycleStatus; private ChronoEStore eStore; public ChronoEObjectImpl() { // by default, we always assign a new ID. this.id = UUID.randomUUID().toString(); // by default, we assume the TRANSIENT state (i.e. the object has never been persisted to the repository) this.lifecycleStatus = ChronoEObjectLifecycle.TRANSIENT; // since we are in transient mode, we cannot rely on the repository to manage the EStore for us, we // have to do it ourselves with an in-memory store. this.eSetStore(new OwnedTransientEStore(this)); } public ChronoEObjectImpl(final String id, final EClass eClass) { checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!"); this.id = id; // by default, we assume the TRANSIENT state (i.e. the object has never been persisted to the repository) this.lifecycleStatus = ChronoEObjectLifecycle.TRANSIENT; // since we are in transient mode, we cannot rely on the repository to manage the EStore for us, we // have to do it ourselves with an in-memory store. this.eSetStore(new OwnedTransientEStore(this)); this.eSetClass(eClass); } public ChronoEObjectImpl(final String id, final EClass eClass, final ChronoEStore eStore) { checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!"); checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); checkNotNull(eStore, "Precondition violation - argument 'eStore' must not be NULL!"); this.id = id; this.eSetClass(eClass); this.eStore = eStore; this.lifecycleStatus = ChronoEObjectLifecycle.PERSISTENT_CLEAN; } // ===================================================================================================================== // ECORE IMPLEMENTATION OVERRIDES // ===================================================================================================================== @Override protected boolean eIsCaching() { // don't cache on EObject level; we do this ourselves return false; } @Override public Object dynamicGet(final int dynamicFeatureID) { final EStructuralFeature feature = this.eDynamicFeature(dynamicFeatureID); if (feature.isMany()) { return new EStoreEObjectImpl.BasicEStoreEList<Object>(this, feature); } else { return this.eStore().get(this, feature, EStore.NO_INDEX); } } @Override public void dynamicSet(final int dynamicFeatureID, final Object value) { EStructuralFeature feature = this.eDynamicFeature(dynamicFeatureID); if (feature.isMany()) { this.eStore().unset(this, feature); @SuppressWarnings("rawtypes") EList collection = (EList) value; for (int index = 0; index < collection.size(); index++) { this.eStore().set(this, feature, index, value); } } else { this.eStore().set(this, feature, InternalEObject.EStore.NO_INDEX, value); } } @Override public void dynamicUnset(final int dynamicFeatureID) { EStructuralFeature feature = this.eDynamicFeature(dynamicFeatureID); this.eStore().unset(this, feature); } @Override public void eDynamicUnset(final EStructuralFeature eFeature) { this.eStore().unset(this, eFeature); } @Override protected void eDynamicUnset(final int dynamicFeatureID, final EStructuralFeature eFeature) { this.eStore().unset(this, eFeature); } @Override protected void eBasicSetContainer(final InternalEObject newContainer) { this.eStore.setContainer(this, newContainer); } @Override protected void eBasicSetContainerFeatureID(final int newContainerFeatureID) { this.eStore.setContainingFeatureID(this, newContainerFeatureID); } @Override public void unsetEContainerSilent() { this.eStore().clearEContainerAndEContainingFeatureSilent(this); } // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== @Override public String getId() { return this.id; } @Override public ChronoEObjectLifecycle getLifecycleStatus() { return this.lifecycleStatus; } @Override public void setLifecycleStatus(final ChronoEObjectLifecycle status) { checkNotNull(status, "Precondition violation - argument 'status' must not be NULL!"); this.lifecycleStatus = status; } @Override public boolean exists() { return this.getLifecycleStatus().isRemoved() == false; } @Override public ChronoEStore eStore() { return this.eStore; } @Override public void eSetStore(final EStore store) { this.eStore = (ChronoEStore) store; } // @Override // public int eContainerFeatureID() { // return this.eStore.getContainingFeatureID(this); // } // ===================================================================================================================== // HASH CODE & EQUALS (based on ID only) // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.id == null ? 0 : this.id.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; } ChronoEObjectImpl other = (ChronoEObjectImpl) obj; if (this.id == null) { if (other.id != null) { return false; } } else if (!this.id.equals(other.id)) { return false; } return true; } // ===================================================================================================================== // TOSTRING // ===================================================================================================================== @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.eClass().getName() + "@" + this.id); return builder.toString(); } }
6,929
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEFactory.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/impl/ChronoEFactory.java
package org.chronos.chronosphere.emf.impl; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EFactory; import org.eclipse.emf.ecore.impl.EFactoryImpl; public class ChronoEFactory extends EFactoryImpl implements EFactory { @Override protected ChronoEObject basicCreate(final EClass eClass) { ChronoEObjectImpl eObject = new ChronoEObjectImpl(); eObject.eSetClass(eClass); return eObject; } }
475
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEObject.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/emf/api/ChronoEObject.java
package org.chronos.chronosphere.emf.api; import org.eclipse.emf.ecore.InternalEObject; public interface ChronoEObject extends InternalEObject { public String getId(); public boolean exists(); }
202
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
JsonTest.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/test/java/JsonTest.java
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.junit.Test; public class JsonTest { public static final String str = "{\"code\":\"M0\",\"featureNameList\":[\"\"],\"numArray\":[16643791351,0,0,0,1,0,0,0,0,0,0,0,16643939273,0,0,0,1,0,0,0,0,0,0,0,16604431897,0,0,0,1,0,0,0,0,0,0,0,16643937655,0,0,0,1,0,0,0,0,0,0,0,16643791392,0,0,0,1,0,0,0,0,0,0,0,16643791087,0,0,0,1,0,0,0,0,0,0,0,16643933262,0,0,0,1,0,0,0,0,0,0,0,16643519731,0,0,0,1,0,0,0,0,0,0,0,16643549387,0,0,0,1,0,0,0,0,0,0,0,16604431653,0,0,0,1,0,0,0,0,0,0,0,16643538576,0,0,0,1,0,0,0,0,0,0,0,16643938190,0,0,0,1,0,0,0,0,0,0,0,16643538739,0,0,0,1,0,0,0,0,0,0,0,17549685095,0,0,0,1,0,0,0,0,0,0,0,16643937922,0,0,0,1,0,0,0,0,0,0,0,16643418302,0,0,0,1,0,0,0,0,0,0,0,16643933134,0,0,0,1,0,0,1,0,0,0,0,16643578752,0,0,0,1,0,0,0,0,0,0,0,16643933298,0,0,0,1,0,0,0,0,0,0,0,16643937961,0,0,0,1,0,0,0,0,0,0,0,16643938316,0,0,0,1,0,0,0,0,0,0,0,18544129210,0,0,0,1,0,0,0,0,0,0,0,17543817357,0,0,0,1,0,0,0,0,0,0,0,16643519730,0,0,0,1,0,0,0,0,0,0,0,17549685976,0,0,0,1,0,0,0,0,0,0,0,17543817013,0,0,0,1,0,0,0,0,0,0,0,16643938752,0,0,0,1,0,0,0,0,0,0,0,16643417105,0,0,0,1,0,0,0,0,0,0,0,16643938213,0,0,0,1,0,0,0,0,0,0,0,16643939755,0,0,0,1,0,0,0,0,0,0,0,16643939631,0,0,0,1,0,0,0,0,0,0,0,16643552679,0,0,0,1,0,0,0,0,0,0,0,16643519715,0,0,0,1,0,0,0,0,0,0,0,16643938083,0,0,0,1,0,0,0,0,0,0,0,16604423015,0,0,0,1,0,0,0,0,0,0,0,17543816952,0,0,0,1,0,0,0,0,0,0,0,16643932671,0,0,0,1,0,0,0,0,0,0,0,16643938523,0,0,0,1,0,0,0,0,0,0,0,16643937912,0,0,0,1,0,0,0,0,0,0,0,16643938058,0,0,0,1,0,0,0,0,0,0,0,16643938958,0,0,0,1,0,0,0,0,0,0,0,16643932170,0,0,0,1,0,0,0,0,0,0,0,16643938235,0,0,0,1,0,0,0,0,0,0,0,17543817006,0,0,0,1,0,0,0,0,0,0,0,16643531731,0,0,0,1,0,0,0,0,0,0,0,16643579053,0,0,0,1,0,0,0,0,0,0,0,16643938197,0,0,0,1,0,0,0,0,0,0,0,16643937750,0,0,0,1,0,0,0,0,0,0,0,16643937636,0,0,0,1,0,0,0,0,0,0,0,16643791022,0,0,0,1,0,0,0,0,0,0,0,16643938716,0,0,0,1,0,0,0,0,0,0,0,17543816957,0,0,0,1,0,0,0,0,0,0,0,16643531381,0,0,0,1,0,0,0,0,0,0,0,16643938131,0,0,0,1,0,0,0,0,0,0,0,16643531805,0,0,0,1,0,0,0,0,0,0,0,16643549578,0,0,0,1,0,0,0,0,0,0,0,18544129178,0,0,0,1,0,0,0,0,0,0,0,16643549852,0,0,0,1,0,0,0,0,0,0,0,16643791076,0,0,0,1,0,0,0,0,0,0,0,16643791598,0,0,0,1,0,0,0,0,0,0,0,16643418193,0,0,0,1,0,0,0,0,0,0,0,16643791179,0,0,0,1,0,0,0,0,0,0,0,16643938531,0,0,0,1,0,0,0,0,0,0,0,16643519635,0,0,0,1,0,0,0,0,0,0,0,16643938963,0,0,0,1,0,0,0,0,0,0,0,16643443172,0,0,0,1,0,0,0,0,0,0,0,16643932892,0,0,0,1,0,0,0,0,0,0,0,16643443185,0,0,0,1,0,0,0,0,0,0,0,16643939583,0,0,0,1,0,0,0,0,0,0,0,16643939675,0,0,0,1,0,0,0,0,0,0,0,16643791535,0,0,0,1,0,0,0,0,0,0,0,16643791670,0,0,0,1,0,0,0,0,0,0,0,17543817101,0,0,0,1,0,0,0,0,0,0,0,16643538952,0,0,0,1,0,0,0,0,0,0,0,16643932352,0,0,0,1,0,0,0,0,0,0,0,16643931935,0,0,0,1,0,0,0,0,0,0,0,16643938125,0,0,0,1,0,0,0,0,0,0,0,17543817016,0,0,0,1,0,0,0,0,0,0,0,16643791509,0,0,0,1,0,0,0,0,0,0,0,16643416972,0,0,0,1,0,0,0,0,0,0,0,18544128609,0,0,0,1,0,0,0,0,0,0,0,16643552752,0,0,0,1,0,0,0,0,0,0,0,16643938907,0,0,0,1,0,0,0,0,0,0,0,16643933125,0,0,0,1,0,0,0,0,0,0,0,16643938731,0,0,0,1,0,0,0,0,0,0,0,16643932853,0,0,0,1,0,0,0,0,0,0,0,16643932563,0,0,0,1,0,0,0,0,0,0,0,16643791205,0,0,0,1,0,0,0,0,0,0,0,18544129251,0,0,0,1,0,0,0,0,0,0,0,16643549792,0,0,0,1,0,0,0,0,0,0,0,16643939215,0,0,0,1,0,0,0,0,0,0,0,16643791281,0,0,0,1,0,0,0,0,0,0,0,16643549753,0,0,0,1,0,0,0,0,0,0,0,16643538759,0,0,0,1,0,0,0,0,0,0,0,13196048312,0,0,0,1,0,0,0,0,0,0,0,17543817320,0,0,0,1,0,0,0,0,0,0,0,16643939230,0,0,0,1,0,0,0,0,0,0,0,16643932670,0,0,0,1,0,0,0,0,0,0,0,17543816892,0,0,0,1,0,0,0,0,0,0,0,17543817363,0,0,0,1,0,0,0,0,0,0,0],\"numRetailList\":[\"\"],\"provinceShowHuiTag\":\"0\",\"splitLen\":\"12\",\"uuid\":\"d2071553-dfdd-4e0b-b91c-0844e02ef8d7\"}"; public static final String str1 = "{\"code\":\"M1\",\"numArray\":[],\"provinceShowHuiTag\":\"0\",\"splitLen\":\"12\",\"uuid\":\"b4779ec9-5455-464d-a98e-68b101bc4b82\"}"; public static void main(String[] args) { JSONObject object = JSON.parseObject(str); String code = object.getString("code"); System.out.println(code); } @Test public void test1() { JSONObject object = JSON.parseObject(str1); String code = object.getString("code"); System.out.println(code); } }
4,283
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
MainTest.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/test/java/com/xubingbing/MainTest.java
package com.xubingbing; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class MainTest { public static void main(String[] args) { Pattern p = Pattern.compile("([\\d])\\1{2,}"); Pattern p1 = Pattern.compile("([\\d])\\1{3,}"); Matcher matcher = p.matcher("18865888"); System.out.println(matcher.find()); System.out.println(matcher.matches()); Matcher matcher1 = p1.matcher("188888"); Matcher matcher2 = p1.matcher("1888"); Matcher matcher3 = p1.matcher("1888346666"); System.out.println(matcher1.find()); System.out.println(matcher2.find()); System.out.println(matcher3.find()); } @Test public void abcde() { Pattern pattern = Pattern.compile("(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){4}\\d"); Matcher matcher = pattern.matcher("123456"); assertTrue(matcher.find()); Matcher matcher1 = pattern.matcher("13123454345"); assertTrue(matcher1.find()); Matcher matcher2 = pattern.matcher("122456"); assertFalse(matcher2.find()); Matcher matcher3 = pattern.matcher("1265432"); assertFalse(matcher3.find()); } @Test public void edcba() { Pattern pattern = Pattern.compile("^\\d(?:(?:0(?=9)|9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){3,})\\d"); Matcher matcher = pattern.matcher("87654"); assertTrue(matcher.find()); Matcher matcher1 = pattern.matcher("13123454345"); assertFalse(matcher1.find()); Matcher matcher2 = pattern.matcher("122456"); assertFalse(matcher2.find()); Matcher matcher3 = pattern.matcher("654321"); assertTrue(matcher3.find()); } @Test public void huiwen() { Pattern pattern = Pattern.compile("(\\d)(\\d)(\\d)(\\d)(\\d)(\\d)(\\d)\\6\\5\\4\\3\\2\\1"); Matcher matcher = pattern.matcher("1234567654321"); assertTrue(matcher.find()); Matcher matcher1 = pattern.matcher("1312341432131"); assertTrue(matcher1.find()); Matcher matcher2 = pattern.matcher("122456"); assertFalse(matcher2.find()); Matcher matcher3 = pattern.matcher("654321"); assertFalse(matcher3.find()); } @Test public void abcdabcd() { Pattern pattern = Pattern.compile("(\\d)(\\d)(\\d)(\\d)\\1\\2\\3\\4"); Matcher matcher = pattern.matcher("153123412343"); assertTrue(matcher.find()); Matcher matcher1 = pattern.matcher("131234123454345"); assertTrue(matcher1.find()); Matcher matcher2 = pattern.matcher("122456"); assertFalse(matcher2.find()); Matcher matcher3 = pattern.matcher("654321"); assertFalse(matcher3.find()); } @Test public void unique3() { Pattern pattern = Patterns.less3; Matcher matcher = pattern.matcher("153123412343"); assertFalse(matcher.find()); Matcher matcher1 = pattern.matcher("13123452345"); assertFalse(matcher1.find()); Matcher matcher2 = pattern.matcher("13133113133"); assertTrue(matcher2.find()); Matcher matcher3 = pattern.matcher("18989898989"); assertTrue(matcher3.find()); } @Test public void n5() { Pattern pattern = Patterns.one5s; Matcher matcher = pattern.matcher("153123412343"); assertFalse(matcher.find()); Matcher matcher1 = pattern.matcher("13123452345"); assertFalse(matcher1.find()); Matcher matcher2 = pattern.matcher("15692666276"); assertTrue(matcher2.find()); Matcher matcher3 = pattern.matcher("18989898989"); assertTrue(matcher3.find()); Matcher matcher4 = pattern.matcher("15313332339"); assertTrue(matcher4.find()); } @Test public void aaabbb() { Pattern pattern = Pattern.compile("(\\d)\\1{2}((?!\\1)\\d)\\2{2}"); Matcher matcher = pattern.matcher("123456"); assertFalse(matcher.find()); Matcher matcher1 = pattern.matcher("13123454345"); assertFalse(matcher1.find()); Matcher matcher2 = pattern.matcher("122456"); assertFalse(matcher2.find()); Matcher matcher3 = pattern.matcher("122244456"); assertTrue(matcher3.find()); Matcher matcher4 = pattern.matcher("22244456"); assertTrue(matcher4.find()); Matcher matcher5 = pattern.matcher("2222444555666"); assertTrue(matcher5.find()); } @Test(expected = Exception.class) public void test() { ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.shutdown(); executorService.execute(() -> System.out.println(1)); } @Test public void testExecutor() { } }
5,047
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
StringTest.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/test/java/com/xubingbing/StringTest.java
package com.xubingbing; import org.junit.Test; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class StringTest { @Test public void testFormat() { String str = "https://m.10010.com/NumApp/NumberCenter/qryNum?callback=jsonp_queryMoreNums&provinceCode=%s" + "&cityCode=%s&monthFeeLimit=0&groupKey=%s&searchCategory=3&net=01&amounts=200&codeTypeCode=&searchValue=&qryType=02&goodsNet=4&_=%s"; System.out.println(String.format(str, 1, 2, 3, 4)); } @Test public void testFindAny() { Map<String, String> map = new HashMap<>(); map.put("2", "3"); map.put("1", "2"); map.put("3", "4"); // Optional<Map.Entry<String, String>> any = map.entrySet().parallelStream().p.findAny(); // System.out.println(any.get().getKey()); } }
1,044
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
CityConverter.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/CityConverter.java
package com.xubingbing; import javafx.util.StringConverter; public class CityConverter extends StringConverter<City> { @Override public String toString(City object) { return object.getCITY_NAME(); } @Override public City fromString(String string) { return Controller.cityMap.get(string); } }
335
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
Patterns.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/Patterns.java
package com.xubingbing; import java.util.regex.Pattern; final public class Patterns { public static final Pattern abcdabcd = Pattern.compile("(\\d)(\\d)(\\d)(\\d)\\1\\2\\3\\4"); public static final Pattern aabbcc = Pattern.compile("(\\d)\\1((?!\\1)\\d)\\2((?!\\2)(?!\\1)\\d)\\3"); public static final Pattern abccba = Pattern.compile("(\\d)((?!\\2)\\d)((?!\\2)(?!\\3)\\d)\\3\\2\\1"); public static final Pattern a3 = Pattern.compile("([\\d])\\1{2,}"); public static final Pattern a4p = Pattern.compile("([\\d])\\1{3,}"); public static final Pattern aabb = Pattern.compile("(\\d)\\1{1}((?!\\1)\\d)\\2{1}"); public static final Pattern abcde = Pattern.compile("(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){4}\\d"); public static final Pattern edcba = Pattern.compile("^\\d(?:(?:0(?=9)|9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){3,})\\d"); public static final Pattern abcd = Pattern.compile("(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){3}\\d"); public static final Pattern less3 = Pattern.compile("^(?=(\\d)\\1*(\\d)(?:\\1|\\2)*(\\d)(?:\\1|\\2|\\3)*$)\\d{11}$"); public static final Pattern one5s = Pattern.compile("^(?=\\d*(\\d)\\d*(?:\\1\\d*){4})\\d{11}$"); }
1,262
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
City.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/City.java
package com.xubingbing; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class City { private String CITY_NAME; private Integer CITY_CODE; }
241
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
Main.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/Main.java
package com.xubingbing; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("靓号助手"); Parent root = FXMLLoader.load(getClass().getResource("/app.fxml")); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/scan.ico"))); primaryStage.show(); } public static void main(String[] args){ launch(args); } }
732
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
Province.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/Province.java
package com.xubingbing; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Province { private String PROVINCE_NAME; private Integer PROVINCE_CODE; }
253
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
Util.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/Util.java
package com.xubingbing; public class Util { public static boolean isNumeric(String str){ if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c <= '/' || c >= ':') { return false; } } return true; } }
608
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
Controller.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/Controller.java
package com.xubingbing; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.xubingbing.Patterns.*; public class Controller implements Initializable { private final static Logger LOG = LoggerFactory.getLogger(Controller.class); static Map<String, Province> provinceMap = new HashMap<>(); static Map<Province, List<City>> provinceCity = new HashMap<>(); static Map<String, City> cityMap = new HashMap<>(); private CloseableHttpClient httpclient = HttpClients.createDefault(); private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); private JSONObject proGroupNum; private LinkedHashSet<String> allNums = new LinkedHashSet<>(); private final String queryUrlFormat = "https://m.10010.com/NumApp/NumberCenter/qryNum?callback=jsonp_queryMoreNums&provinceCode=%s" + "&cityCode=%s&monthFeeLimit=0&groupKey=%s&searchCategory=3&net=01&amounts=200&codeTypeCode=&searchValue=&qryType=02&goodsNet=4&_=%s"; private final static Random rand = new Random(); // 任务是否启动 private static volatile boolean start = true; private final String wang = "https://m.10010.com/king/kingNumCard/init?product=4&channel=1306"; private final String mi = "https://m.10010.com/king/kingNumCard/newmiinit?product=1"; private final String ali = "https://m.10010.com/king/kingNumCard/alibaoinit?product=1"; @FXML private ChoiceBox<Province> box1; @FXML private ChoiceBox<City> box2; @FXML private ListView<String> listView; @FXML private ListView all, aaa, aaa2, aaa3, aaa4, aaa5, aaa6, aaa7, aaa8, aaa9, aaa10, aaa11, aaa12; @FXML private RadioButton aaaBtn, aaaBtn2, aaaBtn3, aaaBtn4, aaaBtn5, aaaBtn6, aaaBtn7, aaaBtn8, aaaBtn9, aaaBtn10, aaaBtn11, aaaBtn12; @FXML private TextField exclude, custom; public void initialize(URL location, ResourceBundle resources) { LOG.info("应用启动"); // 初始化ListView ObservableList<String> items = FXCollections.observableArrayList( "大王卡", "米粉卡", "阿里宝卡"); listView.setItems(items); listView.getSelectionModel().selectFirst(); // 初始化ChoiceBox HttpGet httpGet = new HttpGet(wang); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { String s = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = JSONObject.parseObject(s); // 初始化省份 String provinceData = jsonObject.getString("provinceData"); box1.setConverter(new ProvinceConverter()); List<Province> provinces = JSON.parseArray(provinceData, Province.class); provinces.forEach(p -> { provinceMap.put(p.getPROVINCE_NAME(), p); JSONObject cityData = jsonObject.getJSONObject("cityData"); List<City> cities = JSON.parseArray(cityData.getString(p.getPROVINCE_CODE().toString()), City.class); provinceCity.put(p, cities); }); provinces.add(0, new Province("全国", 0)); provinceMap.put("全国", new Province("全国", 0)); LOG.info(JSON.toJSONString(provinceCity)); ObservableList<Province> province = FXCollections.observableArrayList(provinces); box1.setItems(province); box1.getSelectionModel().selectFirst(); // 初始化城市 box2.setConverter(new CityConverter()); ChangeListener<Province> changeListener = (ObservableValue<? extends Province> observable, Province oldValue, Province newValue) -> { Province p = provinceMap.get(newValue.getPROVINCE_NAME()); JSONObject cityData = jsonObject.getJSONObject("cityData"); List<City> cities = JSON.parseArray(cityData.getString(p.getPROVINCE_CODE().toString()), City.class); cities.forEach(c -> cityMap.put(c.getCITY_NAME(), c)); box2.setItems(FXCollections.observableArrayList(cities)); box2.getSelectionModel().selectFirst(); }; box1.getSelectionModel().selectedItemProperty().addListener(changeListener); Integer code = box1.getSelectionModel().selectedItemProperty().getValue().getPROVINCE_CODE(); List<City> cities; if (code == 0) { cities = new ArrayList<>(); cities.add(new City("全国", 0)); } else { JSONObject cityData = jsonObject.getJSONObject("cityData"); cities = JSON.parseArray(cityData.getString(code.toString()), City.class); } cities.forEach(c -> { cityMap.put(c.getCITY_NAME(), c); }); box2.setItems(FXCollections.observableArrayList(cities)); box2.getSelectionModel().selectFirst(); // 初始化提示 Tooltip tip = new Tooltip("输入数字,多个用空格分隔"); exclude.setTooltip(tip); } catch (IOException e) { e.printStackTrace(); } } @FXML private void search() throws Exception { String selectedItem = listView.getSelectionModel().getSelectedItem(); String groupUrl = wang; switch (selectedItem) { case "大王卡": groupUrl = wang; break; case "阿里宝卡": groupUrl = ali; break; case "米粉卡": groupUrl = mi; break; default: } HttpGet httpGet = new HttpGet(groupUrl); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { String s = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = JSONObject.parseObject(s); // 请求需要Groupkey proGroupNum = jsonObject.getJSONObject("proGroupNum"); } start = true; ReadOnlyObjectProperty<Province> property = box1.getSelectionModel().selectedItemProperty(); Integer provinceCode = property.getValue().getPROVINCE_CODE(); Integer cityCode = box2.getSelectionModel().selectedItemProperty().getValue().getCITY_CODE(); String queryUrl = String.format(queryUrlFormat, provinceCode, cityCode, proGroupNum.getString(provinceCode.toString()), System.currentTimeMillis()); LOG.info(queryUrl); HttpGet get = new HttpGet(queryUrl); get.addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N)" + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36"); get.addHeader("Referer", "https://m.10010.com/queen/tencent/tencent-pc-fill.html" + "?product=4&channel=1306"); LOG.info("搜索{},省份:{},城市:{}启动", selectedItem, property.get().getPROVINCE_NAME(), box2.getSelectionModel() .selectedItemProperty().get().getCITY_NAME()); service.scheduleWithFixedDelay(() -> { while (!start) { return; } final City c; Integer code = box1.getSelectionModel().selectedItemProperty().get().getPROVINCE_CODE(); if (code == 0) { Set<Map.Entry<Province, List<City>>> entries = provinceCity.entrySet(); List<Map.Entry<Province, List<City>>> list = new ArrayList<>(entries); Map.Entry<Province, List<City>> provinceListEntry = list.get(rand.nextInt(list.size())); Integer province = provinceListEntry.getKey().getPROVINCE_CODE(); List<City> cities = provinceListEntry.getValue(); c = cities.get(rand.nextInt(cities.size())); Integer city = c.getCITY_CODE(); String url = String.format(queryUrlFormat, province, city, proGroupNum.getString(province.toString()), System.currentTimeMillis()); try { get.setURI(new URI(url)); } catch (URISyntaxException e) { e.printStackTrace(); } LOG.debug("号码请求地址:{}", get.getURI().toString()); } else { c = box2.getSelectionModel().selectedItemProperty().getValue(); } try (CloseableHttpResponse r = httpclient.execute(get)) { String string = EntityUtils.toString(r.getEntity()); StringBuilder sb = new StringBuilder(string); sb.delete(0, 20); sb.deleteCharAt(sb.length() - 1); LOG.info("响应数据:{}", sb); JSONObject object = null; try { object = JSON.parseObject(sb.toString()); } catch (Exception e) { LOG.warn("返回码异常,返回数据:{}", string); return; } JSONArray numArray = object.getJSONArray("numArray"); numArray.forEach(n -> { if (n.toString().length() == 11) { allNums.add(n.toString()); } String num = n.toString(); String excludeText = exclude.getText(); String[] s = excludeText.split(" "); for (String s1 : s) { boolean numeric = Util.isNumeric(s1); if (numeric) { LOG.debug("不包含:{}", excludeText); if (num.contains(s1)) { return; } } } if (all.getItems().contains(n.toString())) { return; } if (n.toString().length() == 11) { Platform.runLater(() -> { all.getItems().add(n.toString()); all.scrollTo(all.getItems().size()); }); } // AAA process(aaaBtn, a3, aaa, num, c); // 4A+ process(aaaBtn2, a4p, aaa2, num, c); // AABBCC process(aaaBtn3, aabbcc, aaa3, num, c); // AABB process(aaaBtn4, aabb, aaa4, num, c); // ABCDE process(aaaBtn5, abcde, aaa5, num, c); // ABCCBA process(aaaBtn6, abccba, aaa6, num, c); // EDCBA process(aaaBtn7, edcba, aaa7, num, c); // ABCD process(aaaBtn8, abcd, aaa8, num, c); // ABCDABCD process(aaaBtn9, abcdabcd, aaa9, num, c); // 只出现三个不同数字 process(aaaBtn10, less3, aaa10, num, c); // 同一数字超过5次 process(aaaBtn11, one5s, aaa11, num, c); // Custom if (aaaBtn12.isSelected()) { String str = custom.getText(); if (null == str || str.trim() == "" || str.length() == 0) { return; } try { Pattern pattern = Pattern.compile(str); process(aaaBtn12, pattern, aaa12, num, c); } catch (Exception e) { e.printStackTrace(); } } }); LOG.info("已经扫描号码总数为:{}", allNums.size()); } catch (IOException ex) { ex.printStackTrace(); } }, 0, 2, TimeUnit.SECONDS); } @FXML private void stop() { start = false; } @FXML private void clear(MouseEvent event) { Label label = (Label) event.getSource(); Parent parent = label.getParent().getParent(); ObservableList<Node> childrenUnmodifiable = parent.getChildrenUnmodifiable(); for (Node node : childrenUnmodifiable) { if (node instanceof ListView) { ((ListView) node).getItems().clear(); } } } @FXML private void clearAll() { all.getItems().clear(); } @FXML public void desc(ActionEvent actionEvent) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setContentText("1.找到心怡的号码后可以去申请地址,搜索号码后四位.\n2.每天搜索达到一定数量后,可能搜不出任何结果,等一天再试." + "\n3.大王卡,阿里宝卡支持全国配送,所以在任何地区找到的靓号,都可以申请.\n4.通用设置中不包含输入数字,多个用空格分隔,自定义中可以输入数字或者正则"); alert.showAndWait(); } @FXML public void applyWangKa() { openBrowser("https://m.10010.com/queen/tencent/king-tab.html?channel=62&act_type=" + "jXPAuZEJF5sW8RRofWbp9w%3D%3D&id_type=qJKHBMChSUWopNbX1I%2B4Uw%3D%3D&share_id=YqLJGOzSpdTPh0iKvxyVumBT" + "8S%2FA8vXmnAr5A6orOxg%3D&beinvited_id=YqLJGOzSpdTPh0iKvxyVumBT8S%2FA8vXmnAr5A6orOxg%3D"); } @FXML public void applyBao() { openBrowser("https://m.10010.com/scaffold-show/Alicard"); } @FXML public void applyMi() { openBrowser("http://m.10010.com/scaffold-show/mifans-zhf?channel=5103&share_id=" + "57636342597964306647494276667153707744356B4136774F665452614644564F753744367468764C75303D&act_type=597" + "14E5770367568415148623453647655656B4E45513D3D&id_type=42797231722F426D492B426F512F526949616B347A513D3D"); } private static void process(RadioButton btn, Pattern p, ListView listView, String string, City c) { if (btn.isSelected()) { Matcher matcher = p.matcher(string); if (matcher.find()) { Platform.runLater(() -> { listView.getItems().add(string + c.getCITY_NAME()); listView.scrollTo(listView.getItems().size()); }); } } } private static void openBrowser(String url) { try { Desktop.getDesktop().browse(new URI(url)); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } }
16,160
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
ProvinceConverter.java
/FileExtraction/Java_unseen/xbb2yy_scan/src/main/java/com/xubingbing/ProvinceConverter.java
package com.xubingbing; import javafx.util.StringConverter; public class ProvinceConverter extends StringConverter<Province> { @Override public String toString(Province object) { return object.getPROVINCE_NAME(); } @Override public Province fromString(String string) { return Controller.provinceMap.get(string); } }
360
Java
.java
xbb2yy/scan
25
9
4
2019-04-23T09:44:52Z
2022-06-17T02:08:16Z
HelloWorld.javadoc.gold.txt
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/make/test/HelloWorld.javadoc.gold.txt
./HelloWorld.html ./allclasses-frame.html ./allclasses-noframe.html ./constant-values.html ./deprecated-list.html ./help-doc.html ./index-all.html ./index.html ./overview-tree.html ./package-frame.html ./package-list ./package-summary.html ./package-tree.html ./resources/inherit.gif ./stylesheet.css
301
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
HelloWorld.javap.gold.txt
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/make/test/HelloWorld.javap.gold.txt
Compiled from "HelloWorld.java" public class HelloWorld extends java.lang.Object{ public HelloWorld(); public static void main(java.lang.String[]); public native void test(); }
190
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
HelloWorld.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/make/test/HelloWorld.java
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ // NOTE: The javadoc comments are used by the apt tests. /** * This class is used to test the results of the langtools build. */ public class HelloWorld { /** * The old standby! * @param args The parameters are ignored. */ public static void main(String... args) { System.out.println("Hello World!"); } /** * This declaration is for the benefit of javah tests. */ public native void test(); }
1,658
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
CompileProperties.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/make/tools/CompileProperties/CompileProperties.java
/* * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Properties; /** Translates a .properties file into a .java file containing the * definition of a java.util.Properties subclass which can then be * compiled with javac. <P> * * Usage: java CompileProperties [path to .properties file] [path to .java file to be output] [super class] * * Infers the package by looking at the common suffix of the two * inputs, eliminating "classes" from it. * * @author Scott Violet * @author Kenneth Russell */ public class CompileProperties { public static void main(String[] args) { CompileProperties cp = new CompileProperties(); boolean ok = cp.run(args); if ( !ok ) { System.exit(1); } } static interface Log { void info(String msg); void verbose(String msg); void error(String msg, Exception e); } private String propfiles[]; private String outfiles[] ; private String supers[] ; private int compileCount = 0; private boolean quiet = false; private Log log; public void setLog(Log log) { this.log = log; } public boolean run(String[] args) { if (log == null) { log = new Log() { public void error(String msg, Exception e) { System.err.println("ERROR: CompileProperties: " + msg); if ( e != null ) { System.err.println("EXCEPTION: " + e.toString()); e.printStackTrace(); } } public void info(String msg) { System.out.println(msg); } public void verbose(String msg) { if (!quiet) System.out.println(msg); } }; } boolean ok = true; /* Original usage */ if (args.length == 2 && args[0].charAt(0) != '-' ) { ok = createFile(args[0], args[1], "java.util.ListResourceBundle"); } else if (args.length == 3) { ok = createFile(args[0], args[1], args[2]); } else if (args.length == 0) { usage(log); ok = false; } else { /* New batch usage */ ok = parseOptions(args); if ( ok && compileCount == 0 ) { log.error("options parsed but no files to compile", null); ok = false; } /* Need at least one file. */ if ( !ok ) { usage(log); } else { /* Process files */ for ( int i = 0; i < compileCount && ok ; i++ ) { ok = createFile(propfiles[i], outfiles[i], supers[i]); } } } return ok; } private boolean parseOptions(String args[]) { boolean ok = true; if ( compileCount > 0 ) { String new_propfiles[] = new String[compileCount + args.length]; String new_outfiles[] = new String[compileCount + args.length]; String new_supers[] = new String[compileCount + args.length]; System.arraycopy(propfiles, 0, new_propfiles, 0, compileCount); System.arraycopy(outfiles, 0, new_outfiles, 0, compileCount); System.arraycopy(supers, 0, new_supers, 0, compileCount); propfiles = new_propfiles; outfiles = new_outfiles; supers = new_supers; } else { propfiles = new String[args.length]; outfiles = new String[args.length]; supers = new String[args.length]; } for ( int i = 0; i < args.length ; i++ ) { if ( "-compile".equals(args[i]) && i+3 < args.length ) { propfiles[compileCount] = args[++i]; outfiles[compileCount] = args[++i]; supers[compileCount] = args[++i]; compileCount++; } else if ( "-optionsfile".equals(args[i]) && i+1 < args.length ) { String filename = args[++i]; FileInputStream finput = null; byte contents[] = null; try { finput = new FileInputStream(filename); int byteCount = finput.available(); if ( byteCount <= 0 ) { log.error("The -optionsfile file is empty", null); ok = false; } else { contents = new byte[byteCount]; int bytesRead = finput.read(contents); if ( byteCount != bytesRead ) { log.error("Cannot read all of -optionsfile file", null); ok = false; } } } catch ( IOException e ) { log.error("cannot open " + filename, e); ok = false; } if ( finput != null ) { try { finput.close(); } catch ( IOException e ) { ok = false; log.error("cannot close " + filename, e); } } if ( ok = true && contents != null ) { String tokens[] = (new String(contents)).split("\\s+"); if ( tokens.length > 0 ) { ok = parseOptions(tokens); } } if ( !ok ) { break; } } else if ( "-quiet".equals(args[i]) ) { quiet = true; } else { log.error("argument error", null); ok = false; } } return ok; } private boolean createFile(String propertiesPath, String outputPath, String superClass) { boolean ok = true; log.verbose("parsing: " + propertiesPath); Properties p = new Properties(); try { p.load(new FileInputStream(propertiesPath)); } catch ( FileNotFoundException e ) { ok = false; log.error("Cannot find file " + propertiesPath, e); } catch ( IOException e ) { ok = false; log.error("IO error on file " + propertiesPath, e); } if ( ok ) { String packageName = inferPackageName(propertiesPath, outputPath); log.verbose("inferred package name: " + packageName); List<String> sortedKeys = new ArrayList<String>(); for ( Object key : p.keySet() ) { sortedKeys.add((String)key); } Collections.sort(sortedKeys); Iterator keys = sortedKeys.iterator(); StringBuffer data = new StringBuffer(); while (keys.hasNext()) { Object key = keys.next(); data.append(" { \"" + escape((String)key) + "\", \"" + escape((String)p.get(key)) + "\" },\n"); } // Get class name from java filename, not the properties filename. // (zh_TW properties might be used to create zh_HK files) File file = new File(outputPath); String name = file.getName(); int dotIndex = name.lastIndexOf('.'); String className; if (dotIndex == -1) { className = name; } else { className = name.substring(0, dotIndex); } String packageString = ""; if (packageName != null && !packageName.equals("")) { packageString = "package " + packageName + ";\n\n"; } Writer writer = null; try { writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outputPath), "8859_1")); MessageFormat format = new MessageFormat(FORMAT); writer.write(format.format(new Object[] { packageString, className, superClass, data })); } catch ( IOException e ) { ok = false; log.error("IO error writing to file " + outputPath, e); } if ( writer != null ) { try { writer.flush(); } catch ( IOException e ) { ok = false; log.error("IO error flush " + outputPath, e); } try { writer.close(); } catch ( IOException e ) { ok = false; log.error("IO error close " + outputPath, e); } } log.verbose("wrote: " + outputPath); } return ok; } private static void usage(Log log) { log.info("usage:"); log.info(" java CompileProperties path_to_properties_file path_to_java_output_file [super_class]"); log.info(" -OR-"); log.info(" java CompileProperties {-compile path_to_properties_file path_to_java_output_file super_class} -or- -optionsfile filename"); log.info(""); log.info("Example:"); log.info(" java CompileProperties -compile test.properties test.java java.util.ListResourceBundle"); log.info(" java CompileProperties -optionsfile option_file"); log.info("option_file contains: -compile test.properties test.java java.util.ListResourceBundle"); } private static String escape(String theString) { // This is taken from Properties.saveConvert with changes for Java strings int len = theString.length(); StringBuffer outBuffer = new StringBuffer(len*2); for(int x=0; x<len; x++) { char aChar = theString.charAt(x); switch(aChar) { case '\\':outBuffer.append('\\'); outBuffer.append('\\'); break; case '\t':outBuffer.append('\\'); outBuffer.append('t'); break; case '\n':outBuffer.append('\\'); outBuffer.append('n'); break; case '\r':outBuffer.append('\\'); outBuffer.append('r'); break; case '\f':outBuffer.append('\\'); outBuffer.append('f'); break; default: if ((aChar < 0x0020) || (aChar > 0x007e)) { outBuffer.append('\\'); outBuffer.append('u'); outBuffer.append(toHex((aChar >> 12) & 0xF)); outBuffer.append(toHex((aChar >> 8) & 0xF)); outBuffer.append(toHex((aChar >> 4) & 0xF)); outBuffer.append(toHex( aChar & 0xF)); } else { if (specialSaveChars.indexOf(aChar) != -1) { outBuffer.append('\\'); } outBuffer.append(aChar); } } } return outBuffer.toString(); } private static String inferPackageName(String inputPath, String outputPath) { // Normalize file names inputPath = new File(inputPath).getPath(); outputPath = new File(outputPath).getPath(); // Split into components String sep; if (File.separatorChar == '\\') { sep = "\\\\"; } else { sep = File.separator; } String[] inputs = inputPath.split(sep); String[] outputs = outputPath.split(sep); // Match common names, eliminating first "classes" entry from // each if present int inStart = 0; int inEnd = inputs.length - 2; int outEnd = outputs.length - 2; int i = inEnd; int j = outEnd; while (i >= 0 && j >= 0) { if (!inputs[i].equals(outputs[j]) || (inputs[i].equals("gensrc") && inputs[j].equals("gensrc"))) { ++i; ++j; break; } --i; --j; } String result; if (i < 0 || j < 0 || i >= inEnd || j >= outEnd) { result = ""; } else { if (inputs[i].equals("classes") && outputs[j].equals("classes")) { ++i; } inStart = i; StringBuffer buf = new StringBuffer(); for (i = inStart; i <= inEnd; i++) { buf.append(inputs[i]); if (i < inEnd) { buf.append('.'); } } result = buf.toString(); } return result; } private static final String FORMAT = "{0}" + "public final class {1} extends {2} '{'\n" + " protected final Object[][] getContents() '{'\n" + " return new Object[][] '{'\n" + "{3}" + " };\n" + " }\n" + "}\n"; // This comes from Properties private static char toHex(int nibble) { return hexDigit[(nibble & 0xF)]; } // This comes from Properties private static final char[] hexDigit = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; // Note: different from that in Properties private static final String specialSaveChars = "\""; }
15,178
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
CompilePropertiesTask.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/make/tools/CompileProperties/CompilePropertiesTask.java
/* * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.MatchingTask; public class CompilePropertiesTask extends MatchingTask { public void setSrcDir(File srcDir) { this.srcDir = srcDir; } public void setDestDir(File destDir) { this.destDir = destDir; } public void setSuperclass(String superclass) { this.superclass = superclass; } @Override public void execute() { CompileProperties.Log log = new CompileProperties.Log() { public void error(String msg, Exception e) { log(msg, Project.MSG_ERR); } public void info(String msg) { log(msg, Project.MSG_INFO); } public void verbose(String msg) { log(msg, Project.MSG_VERBOSE); } }; List<String> mainOpts = new ArrayList<String>(); int count = 0; DirectoryScanner s = getDirectoryScanner(srcDir); for (String path: s.getIncludedFiles()) { if (path.endsWith(".properties")) { String destPath = path.substring(0, path.length() - ".properties".length()) + ".java"; File srcFile = new File(srcDir, path); File destFile = new File(destDir, destPath); // Arguably, the comparison in the next line should be ">", not ">=" // but that assumes the resolution of the last modified time is fine // grained enough; in practice, it is better to use ">=". if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) continue; destFile.getParentFile().mkdirs(); mainOpts.add("-compile"); mainOpts.add(srcFile.getPath()); mainOpts.add(destFile.getPath()); mainOpts.add(superclass); count++; } } if (mainOpts.size() > 0) { log("Generating " + count + " resource files to " + destDir, Project.MSG_INFO); CompileProperties cp = new CompileProperties(); cp.setLog(log); boolean ok = cp.run(mainOpts.toArray(new String[mainOpts.size()])); if (!ok) throw new BuildException("CompileProperties failed."); } } private File srcDir; private File destDir; private String superclass = "java.util.ListResourceBundle"; }
3,894
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
SelectToolTask.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/make/tools/SelectTool/SelectToolTask.java
/* * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; /** * Task to allow the user to control langtools tools built when using NetBeans. * * There are two primary modes. * 1) Property mode. In this mode, property names are provided to get values * that may be specified by the user, either directly in a GUI dialog, or * read from a properties file. If the GUI dialog is invoked, values may * optionally be set for future use. * 2) Setup mode. In this mode, no property names are provided, and the GUI * is invoked to allow the user to set or reset values for use in property mode. */ public class SelectToolTask extends Task { /** * Set the location of the private properties file used to keep the retain * user preferences for this repository. */ public void setPropertyFile(File propertyFile) { this.propertyFile = propertyFile; } /** * Set the name of the property which will be set to the name of the * selected tool, if any. If no tool is selected, the property will * remain unset. */ public void setToolProperty(String toolProperty) { this.toolProperty = toolProperty; } /** * Set the name of the property which will be set to the execution args of the * selected tool, if any. The args default to an empty string. */ public void setArgsProperty(String argsProperty) { this.argsProperty = argsProperty; } /** * Specify whether or not to pop up a dialog if the user has not specified * a default value for a property. */ public void setAskIfUnset(boolean askIfUnset) { this.askIfUnset = askIfUnset; } @Override public void execute() { Project p = getProject(); Properties props = readProperties(propertyFile); toolName = props.getProperty("tool.name"); if (toolName != null) { toolArgs = props.getProperty(toolName + ".args", ""); } if (toolProperty == null || askIfUnset && (toolName == null || (argsProperty != null && toolArgs == null))) { showGUI(props); } // finally, return required values, if any if (toolProperty != null && !(toolName == null || toolName.equals(""))) { p.setProperty(toolProperty, toolName); if (argsProperty != null && toolArgs != null) p.setProperty(argsProperty, toolArgs); } } void showGUI(Properties fileProps) { Properties guiProps = new Properties(fileProps); JOptionPane p = createPane(guiProps); p.createDialog("Select Tool").setVisible(true); toolName = (String) toolChoice.getSelectedItem(); toolArgs = argsField.getText(); if (defaultCheck.isSelected()) { if (toolName.equals("")) { fileProps.remove("tool.name"); } else { fileProps.put("tool.name", toolName); fileProps.put(toolName + ".args", toolArgs); } writeProperties(propertyFile, fileProps); } } JOptionPane createPane(final Properties props) { JPanel body = new JPanel(new GridBagLayout()); GridBagConstraints lc = new GridBagConstraints(); lc.insets.right = 10; lc.insets.bottom = 3; GridBagConstraints fc = new GridBagConstraints(); fc.anchor = GridBagConstraints.WEST; fc.gridx = 1; fc.gridwidth = GridBagConstraints.REMAINDER; fc.insets.bottom = 3; JLabel toolLabel = new JLabel("Tool:"); body.add(toolLabel, lc); String[] toolChoices = { "apt", "javac", "javadoc", "javah", "javap" }; if (true || toolProperty == null) { // include empty value in setup mode List<String> l = new ArrayList<String>(Arrays.asList(toolChoices)); l.add(0, ""); toolChoices = l.toArray(new String[l.size()]); } toolChoice = new JComboBox(toolChoices); if (toolName != null) toolChoice.setSelectedItem(toolName); toolChoice.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { String tn = (String) e.getItem(); argsField.setText(getDefaultArgsForTool(props, tn)); if (toolProperty != null) okButton.setEnabled(!tn.equals("")); } }); body.add(toolChoice, fc); argsField = new JTextField(getDefaultArgsForTool(props, toolName), 40); if (toolProperty == null || argsProperty != null) { JLabel argsLabel = new JLabel("Args:"); body.add(argsLabel, lc); body.add(argsField, fc); argsField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { String toolName = (String) toolChoice.getSelectedItem(); if (toolName.length() > 0) props.put(toolName + ".args", argsField.getText()); } }); } defaultCheck = new JCheckBox("Set as default"); if (toolProperty == null) defaultCheck.setSelected(true); else body.add(defaultCheck, fc); final JOptionPane p = new JOptionPane(body); okButton = new JButton("OK"); okButton.setEnabled(toolProperty == null || (toolName != null && !toolName.equals(""))); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JDialog d = (JDialog) SwingUtilities.getAncestorOfClass(JDialog.class, p); d.setVisible(false); } }); p.setOptions(new Object[] { okButton }); return p; } Properties readProperties(File file) { Properties p = new Properties(); if (file != null && file.exists()) { Reader in = null; try { in = new BufferedReader(new FileReader(file)); p.load(in); in.close(); } catch (IOException e) { throw new BuildException("error reading property file", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { throw new BuildException("cannot close property file", e); } } } } return p; } void writeProperties(File file, Properties p) { if (file != null) { Writer out = null; try { File dir = file.getParentFile(); if (dir != null && !dir.exists()) dir.mkdirs(); out = new BufferedWriter(new FileWriter(file)); p.store(out, "langtools properties"); out.close(); } catch (IOException e) { throw new BuildException("error writing property file", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { throw new BuildException("cannot close property file", e); } } } } } String getDefaultArgsForTool(Properties props, String tn) { return (tn == null || tn.equals("")) ? "" : props.getProperty(tn + ".args", ""); } // Ant task parameters private boolean askIfUnset; private String toolProperty; private String argsProperty; private File propertyFile; // GUI components private JComboBox toolChoice; private JTextField argsField; private JCheckBox defaultCheck; private JButton okButton; // Result values for the client private String toolName; private String toolArgs; }
10,217
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
GenStubs.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/make/tools/GenStubs/GenStubs.java
/* * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.*; import java.util.*; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.util.JavacTask; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCImport; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCModifiers; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.Pretty; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.tree.TreeTranslator; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import javax.tools.JavaFileManager; /** * Generate stub source files by removing implementation details from input files. * * This is a special purpose stub generator, specific to the needs of generating * stub files for JDK 7 API that are needed to compile langtools files that depend * on that API. The stub generator works by removing as much of the API source code * as possible without affecting the public signature, in order to reduce the * transitive closure of the API being referenced. The resulting stubs can be * put on the langtools sourcepath with -implicit:none to compile the langtools * files that depend on the JDK 7 API. * * Usage: * genstubs -s <outdir> -sourcepath <path> <classnames> * * The specified class names are looked up on the sourcepath, and corresponding * stubs are written to the source output directory. * * Classes are parsed into javac ASTs, then processed with a javac TreeTranslator * to remove implementation details, and written out in the source output directory. * Documentation comments and annotations are removed. Method bodies are removed * and methods are marked native. Private and package-private field definitions * have their initializers replace with 0, 0.0, false, null as appropriate. * * An Ant task, Main$Ant is also provided. Files are specified with an implicit * fileset, using srcdir as a base directory. The set of files to be included * is specified with an includes attribute or nested <includes> set. However, * unlike a normal fileset, an empty includes attribute means "no files" instead * of "all files". The Ant task also accepts "fork=true" and classpath attribute * or nested <classpath> element to run GenStubs in a separate VM with the specified * path. This is likely necessary if a JDK 7 parser is required to read the * JDK 7 input files. */ public class GenStubs { static class Fault extends Exception { private static final long serialVersionUID = 0; Fault(String message) { super(message); } Fault(String message, Throwable cause) { super(message); initCause(cause); } } public static void main(String[] args) { boolean ok = new GenStubs().run(args); if (!ok) System.exit(1); } boolean run(String... args) { File outdir = null; String sourcepath = null; List<String> classes = new ArrayList<String>(); for (ListIterator<String> iter = Arrays.asList(args).listIterator(); iter.hasNext(); ) { String arg = iter.next(); if (arg.equals("-s") && iter.hasNext()) outdir = new File(iter.next()); else if (arg.equals("-sourcepath") && iter.hasNext()) sourcepath = iter.next(); else if (arg.startsWith("-")) throw new IllegalArgumentException(arg); else { classes.add(arg); while (iter.hasNext()) classes.add(iter.next()); } } return run(sourcepath, outdir, classes); } boolean run(String sourcepath, File outdir, List<String> classes) { //System.err.println("run: sourcepath:" + sourcepath + " outdir:" + outdir + " classes:" + classes); if (sourcepath == null) throw new IllegalArgumentException("sourcepath not set"); if (outdir == null) throw new IllegalArgumentException("source output dir not set"); JavacTool tool = JavacTool.create(); StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null); try { fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outdir)); fm.setLocation(StandardLocation.SOURCE_PATH, splitPath(sourcepath)); List<JavaFileObject> files = new ArrayList<JavaFileObject>(); for (String c: classes) { JavaFileObject fo = fm.getJavaFileForInput( StandardLocation.SOURCE_PATH, c, JavaFileObject.Kind.SOURCE); if (fo == null) error("class not found: " + c); else files.add(fo); } JavacTask t = tool.getTask(null, fm, null, null, null, files); Iterable<? extends CompilationUnitTree> trees = t.parse(); for (CompilationUnitTree tree: trees) { makeStub(fm, tree); } } catch (IOException e) { error("IO error " + e, e); } return (errors == 0); } void makeStub(StandardJavaFileManager fm, CompilationUnitTree tree) throws IOException { CompilationUnitTree tree2 = new StubMaker().translate(tree); CompilationUnitTree tree3 = new ImportCleaner(fm).removeRedundantImports(tree2); String className = fm.inferBinaryName(StandardLocation.SOURCE_PATH, tree.getSourceFile()); JavaFileObject fo = fm.getJavaFileForOutput(StandardLocation.SOURCE_OUTPUT, className, JavaFileObject.Kind.SOURCE, null); // System.err.println("Writing " + className + " to " + fo.getName()); Writer out = fo.openWriter(); try { new Pretty(out, true).printExpr((JCTree) tree3); } finally { out.close(); } } List<File> splitPath(String path) { List<File> list = new ArrayList<File>(); for (String p: path.split(File.pathSeparator)) { if (p.length() > 0) list.add(new File(p)); } return list; } void error(String message) { System.err.println(message); errors++; } void error(String message, Throwable cause) { error(message); } int errors; class StubMaker extends TreeTranslator { CompilationUnitTree translate(CompilationUnitTree tree) { return super.translate((JCCompilationUnit) tree); } /** * compilation units: remove javadoc comments * -- required, in order to remove @deprecated tags, since we * (separately) remove all annotations, including @Deprecated */ public void visitTopLevel(JCCompilationUnit tree) { super.visitTopLevel(tree); tree.docComments = Collections.emptyMap(); } /** * methods: remove method bodies, make methods native */ @Override public void visitMethodDef(JCMethodDecl tree) { tree.mods = translate(tree.mods); tree.restype = translate(tree.restype); tree.typarams = translateTypeParams(tree.typarams); tree.params = translateVarDefs(tree.params); tree.thrown = translate(tree.thrown); if (tree.restype != null && tree.body != null) { tree.mods.flags |= Flags.NATIVE; tree.body = null; } result = tree; } /** * modifiers: remove annotations */ @Override public void visitModifiers(JCModifiers tree) { tree.annotations = com.sun.tools.javac.util.List.nil(); result = tree; } /** * field definitions: replace initializers with 0, 0.0, false etc * when possible -- i.e. leave public, protected initializers alone */ @Override public void visitVarDef(JCVariableDecl tree) { tree.mods = translate(tree.mods); tree.vartype = translate(tree.vartype); if (tree.init != null) { if ((tree.mods.flags & (Flags.PUBLIC | Flags.PROTECTED)) != 0) tree.init = translate(tree.init); else { String t = tree.vartype.toString(); if (t.equals("boolean")) tree.init = new JCLiteral(TypeTags.BOOLEAN, 0) { }; else if (t.equals("byte")) tree.init = new JCLiteral(TypeTags.BYTE, 0) { }; else if (t.equals("char")) tree.init = new JCLiteral(TypeTags.CHAR, 0) { }; else if (t.equals("double")) tree.init = new JCLiteral(TypeTags.DOUBLE, 0.d) { }; else if (t.equals("float")) tree.init = new JCLiteral(TypeTags.FLOAT, 0.f) { }; else if (t.equals("int")) tree.init = new JCLiteral(TypeTags.INT, 0) { }; else if (t.equals("long")) tree.init = new JCLiteral(TypeTags.LONG, 0) { }; else if (t.equals("short")) tree.init = new JCLiteral(TypeTags.SHORT, 0) { }; else tree.init = new JCLiteral(TypeTags.BOT, null) { }; } } result = tree; } } class ImportCleaner extends TreeScanner { private Set<Name> names = new HashSet<Name>(); private TreeMaker m; ImportCleaner(JavaFileManager fm) { // ImportCleaner itself doesn't require a filemanager, but instantiating // a TreeMaker does, indirectly (via ClassReader, sigh) Context c = new Context(); c.put(JavaFileManager.class, fm); m = TreeMaker.instance(c); } CompilationUnitTree removeRedundantImports(CompilationUnitTree t) { JCCompilationUnit tree = (JCCompilationUnit) t; tree.accept(this); ListBuffer<JCTree> defs = new ListBuffer<JCTree>(); for (JCTree def: tree.defs) { if (def.getTag() == JCTree.IMPORT) { JCImport imp = (JCImport) def; if (imp.qualid.getTag() == JCTree.SELECT) { JCFieldAccess qualid = (JCFieldAccess) imp.qualid; if (!qualid.name.toString().equals("*") && !names.contains(qualid.name)) { continue; } } } defs.add(def); } return m.TopLevel(tree.packageAnnotations, tree.pid, defs.toList()); } @Override public void visitImport(JCImport tree) { } // ignore names found in imports @Override public void visitIdent(JCIdent tree) { names.add(tree.name); } @Override public void visitSelect(JCFieldAccess tree) { super.visitSelect(tree); names.add(tree.name); } } //---------- Ant Invocation ------------------------------------------------ public static class Ant extends MatchingTask { private File srcDir; private File destDir; private boolean fork; private Path classpath; private String includes; public void setSrcDir(File dir) { this.srcDir = dir; } public void setDestDir(File dir) { this.destDir = dir; } public void setFork(boolean v) { this.fork = v; } public void setClasspath(Path cp) { if (classpath == null) classpath = cp; else classpath.append(cp); } public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } public void setIncludes(String includes) { super.setIncludes(includes); this.includes = includes; } @Override public void execute() { if (includes != null && includes.trim().isEmpty()) return; DirectoryScanner s = getDirectoryScanner(srcDir); String[] files = s.getIncludedFiles(); // System.err.println("Ant.execute: srcDir " + srcDir); // System.err.println("Ant.execute: destDir " + destDir); // System.err.println("Ant.execute: files " + Arrays.asList(files)); files = filter(srcDir, destDir, files); if (files.length == 0) return; System.out.println("Generating " + files.length + " stub files to " + destDir); List<String> classNames = new ArrayList<String>(); for (String file: files) { classNames.add(file.replaceAll(".java$", "").replace('/', '.')); } if (!fork) { GenStubs m = new GenStubs(); boolean ok = m.run(srcDir.getPath(), destDir, classNames); if (!ok) throw new BuildException("genstubs failed"); } else { List<String> cmd = new ArrayList<String>(); String java_home = System.getProperty("java.home"); cmd.add(new File(new File(java_home, "bin"), "java").getPath()); if (classpath != null) cmd.add("-Xbootclasspath/p:" + classpath); cmd.add(GenStubs.class.getName()); cmd.add("-sourcepath"); cmd.add(srcDir.getPath()); cmd.add("-s"); cmd.add(destDir.getPath()); cmd.addAll(classNames); //System.err.println("GenStubs exec " + cmd); ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); try { Process p = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); try { String line; while ((line = in.readLine()) != null) System.out.println(line); } finally { in.close(); } int rc = p.waitFor(); if (rc != 0) throw new BuildException("genstubs failed"); } catch (IOException e) { throw new BuildException("genstubs failed", e); } catch (InterruptedException e) { throw new BuildException("genstubs failed", e); } } } String[] filter(File srcDir, File destDir, String[] files) { List<String> results = new ArrayList<String>(); for (String f: files) { long srcTime = new File(srcDir, f).lastModified(); long destTime = new File(destDir, f).lastModified(); if (srcTime > destTime) results.add(f); } return results.toArray(new String[results.size()]); } } }
17,618
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
ParamClassTest.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/test/tools/javah/ParamClassTest.java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Class containing a native method which contains a native * method with non primitive type */ public class ParamClassTest { public native void method(Param s); public static void main(String args[]) { } } class Param extends MissingParamClassException { Param() { System.out.println("Param constructor"); } }
1,406
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
T5070898.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/test/tools/javah/T5070898.java
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test * @bug 5070898 * @summary javah command doesn't throw correct exit code in case of error */ import java.io.*; import java.util.*; import javax.tools.*; public class T5070898 { public static void main(String... args) throws Exception { new T5070898().run(); } public void run() throws Exception { writeFile(); compileFile(); int rc = runJavah(); System.err.println("exit code: " + rc); if (rc == 0) throw new Exception("unexpected exit code: " + rc); } void writeFile() throws Exception { String content = "package test;\n" + "public class JavahTest{\n" + " public static void main(String args){\n" + " System.out.println(\"Test Message\");" + " }\n" + " private static native Object nativeTest();\n" + "}\n"; FileWriter out = new FileWriter("JavahTest.java"); try { out.write(content); } finally { out.close(); } } void compileFile() throws Exception { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); int rc = javac.run(null, null, null, "JavahTest.java"); if (rc != 0) throw new Exception("compilation failed"); } int runJavah() throws Exception { List<String> cmd = new ArrayList<String>(); File java_home = new File(System.getProperty("java.home")); if (java_home.getName().equals("jre")) java_home = java_home.getParentFile(); cmd.add(new File(new File(java_home, "bin"), "javah").getPath()); // ensure we run with the same bootclasspath as this test, // in case this test is being run with -Xbootclasspath cmd.add("-J-Xbootclasspath:" + System.getProperty("sun.boot.class.path")); cmd.add("JavahTest"); ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); pb.environment().remove("CLASSPATH"); Process p = pb.start(); p.getOutputStream().close(); String line; DataInputStream in = new DataInputStream(p.getInputStream()); try { while ((line = in.readLine()) != null) System.err.println(line); } finally { in.close(); } return p.waitFor(); } }
3,453
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
SubClassConsts.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/test/tools/javah/SubClassConsts.java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Subclass defines its own set of constants * It is itself serializable by virtue of extending SuperClassConsts * */ public class SubClassConsts extends SuperClassConsts { private final static int SUB_INT_CONSTANT = 2; private final static double SUB_DOUBLE_CONSTANT = 2.25; private final static float SUB_FLOAT_CONSTANT = 7.90f; private final static boolean SUB_BOOLEAN_CONSTANT = true; public SubClassConsts(String p) { super(p); } }
1,536
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
SuperClassConsts.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/test/tools/javah/SuperClassConsts.java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Parent class implements serializable and provides static initializers * for a bunch of primitive type class constants * (required for regtest 4786406, 4780341) */ import java.io.*; public class SuperClassConsts implements Serializable { // Define class constant values, base class is serializable private static final long serialVersionUID = 6733861379283244755L; public static final int SUPER_INT_CONSTANT = 3; public final static float SUPER_FLOAT_CONSTANT = 99.3f; public final static double SUPER_DOUBLE_CONSTANT = 33.2; public final static boolean SUPER_BOOLEAN_CONSTANT = false; // A token instance field int instanceField; public SuperClassConsts(String p) { } public native int numValues(); private void writeObject(ObjectOutputStream s) throws IOException { System.err.println("writing state"); } /** * readObject is called to restore the state of the FilePermission from * a stream. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { System.err.println("reading back state"); } }
2,231
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
MissingParamClassException.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/test/tools/javah/MissingParamClassException.java
/* * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * ParamClassTest has a native method param which subclasses * this class * */ public class MissingParamClassException extends Exception { public MissingParamClassException() { System.out.println("MissingParamClassException constructor called"); } }
1,332
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z
T6994608.java
/FileExtraction/Java_unseen/openjdk-mirror_jdk7u-langtools/test/tools/javah/T6994608.java
/* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 6994608 * @summary javah no longer accepts parameter files as input */ import java.io.*; import java.util.*; public class T6994608 { public static void main(String... args) throws Exception { new T6994608().run(); } void run() throws Exception { Locale prev = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); try { File f = writeFile(new File("classList"), "java.lang.Object"); test(Arrays.asList("@" + f.getPath()), 0, null); test(Arrays.asList("@badfile"), 1, "Can't find file badfile"); if (errors > 0) throw new Exception(errors + " errors occurred"); } finally { Locale.setDefault(prev); } } void test(List<String> args, int expectRC, String expectOut) { System.err.println("Test: " + args + " rc:" + expectRC + ((expectOut != null) ? " out:" + expectOut : "")); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); int rc = com.sun.tools.javah.Main.run(args.toArray(new String[args.size()]), pw); pw.close(); String out = sw.toString(); if (!out.isEmpty()) System.err.println(out); if (rc != expectRC) error("Unexpected exit code: " + rc + "; expected: " + expectRC); if (expectOut != null && !out.contains(expectOut)) error("Expected string not found: " + expectOut); System.err.println(); } File writeFile(File f, String s) throws IOException { if (f.getParentFile() != null) f.getParentFile().mkdirs(); try (FileWriter out = new FileWriter(f)) { out.write(s); } return f; } void error(String msg) { System.err.println(msg); errors++; } int errors; }
2,962
Java
.java
openjdk-mirror/jdk7u-langtools
9
3
0
2012-05-07T19:45:34Z
2012-05-08T17:47:06Z