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
LongWithinCP.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/query/LongWithinCP.java
package org.chronos.chronograph.api.builder.query; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.function.BiPredicate; public class LongWithinCP implements BiPredicate<Object, Collection> { public LongWithinCP() { } @Override @SuppressWarnings("unchecked") public boolean test(final Object o, final Collection collection) { if(collection == null || collection.isEmpty()){ return false; } if(o instanceof Long){ return collection.contains(o); }else if(o instanceof Collection){ for(Object element : (Collection<Object>)o){ if(test(element, collection)){ return true; } } } return false; } @NotNull @Override public BiPredicate<Object, Collection> negate() { return new LongWithoutCP(); } @Override public int hashCode(){ return this.getClass().hashCode(); } @Override public boolean equals(Object other){ if(other == null){ return false; } return other instanceof LongWithinCP; } @Override public String toString() { return "Long Within"; } }
1,277
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
DoubleEqualsCP.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/query/DoubleEqualsCP.java
package org.chronos.chronograph.api.builder.query; import org.chronos.chronograph.internal.impl.query.ChronoCompareUtil; import org.jetbrains.annotations.NotNull; import java.util.function.BiPredicate; public class DoubleEqualsCP implements BiPredicate<Object, Object> { private final double tolerance; @SuppressWarnings({"unchecked", "rawtypes"}) public DoubleEqualsCP(final double tolerance) { this.tolerance = tolerance; } public double getTolerance() { return this.tolerance; } @Override public boolean test(final Object o, final Object o2) { return ChronoCompareUtil.compare(o, o2, this::testAtomic); } private boolean testAtomic(final Object o, final Object o2){ if(o instanceof Number == false || o2 instanceof Number == false){ return false; } double left = ((Number)o).doubleValue(); double right = ((Number)o2).doubleValue(); return Math.abs(left - right) < this.tolerance; } @NotNull @Override public BiPredicate<Object, Object> negate() { return new DoubleNotEqualsCP(this.tolerance); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DoubleEqualsCP that = (DoubleEqualsCP) o; return Double.compare(that.tolerance, tolerance) == 0; } @Override public int hashCode() { long temp = Double.doubleToLongBits(tolerance); return (int) (temp ^ (temp >>> 32)); } @Override public String toString() { return "Double Eq"; } }
1,717
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StringWithinCP.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/query/StringWithinCP.java
package org.chronos.chronograph.api.builder.query; import org.chronos.chronodb.internal.impl.query.TextMatchMode; import org.chronos.common.exceptions.UnknownEnumLiteralException; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.function.BiPredicate; import static com.google.common.base.Preconditions.*; public class StringWithinCP implements BiPredicate<Object, Collection> { private final TextMatchMode matchMode; public StringWithinCP(TextMatchMode matchMode) { checkNotNull(matchMode, "Precondition violation - argument 'matchMode' must not be NULL!"); this.matchMode = matchMode; } public TextMatchMode getMatchMode() { return this.matchMode; } @Override @SuppressWarnings("unchecked") public boolean test(final Object o, final Collection collection) { if (collection == null || collection.isEmpty()) { return false; } if (o instanceof String) { switch (this.matchMode) { case STRICT: return collection.contains(o); case CASE_INSENSITIVE: for (Object element : collection) { if (element instanceof String) { if (((String) element).equalsIgnoreCase((String) o)) { return true; } } } return false; default: throw new UnknownEnumLiteralException(this.matchMode); } } else if (o instanceof Collection) { for (Object element : (Collection<Object>) o) { if (test(element, collection)) { return true; } } } return false; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StringWithinCP that = (StringWithinCP) o; return matchMode == that.matchMode; } @Override public int hashCode() { return matchMode != null ? matchMode.hashCode() : 0; } @NotNull @Override public BiPredicate<Object, Collection> negate() { return new StringWithoutCP(this.matchMode); } @Override public String toString() { return "String Within" + (this.matchMode == TextMatchMode.CASE_INSENSITIVE ? " [CI]" : ""); } }
2,591
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
COrder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/query/ordering/COrder.java
package org.chronos.chronograph.api.builder.query.ordering; import org.chronos.chronodb.api.NullSortPosition; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.api.TextCompare; import java.util.Comparator; import static com.google.common.base.Preconditions.*; /** * ChronoGraph-specific variant of {@link org.apache.tinkerpop.gremlin.process.traversal.Order} that allows for more configuration options. * */ public interface COrder extends Comparator<Object> { public static COrder asc() { return asc(TextCompare.DEFAULT, NullSortPosition.DEFAULT); } public static COrder asc(TextCompare textCompare){ checkNotNull(textCompare, "Precondition violation - argument 'textCompare' must not be NULL!"); return asc(textCompare, NullSortPosition.DEFAULT); } public static COrder asc(NullSortPosition nullSortPosition) { checkNotNull(nullSortPosition, "Precondition violation - argument 'nullSortPosition' must not be NULL!"); return asc(TextCompare.DEFAULT, nullSortPosition); } public static COrder asc(TextCompare textCompare, NullSortPosition nullSortPosition){ checkNotNull(textCompare, "Precondition violation - argument 'textCompare' must not be NULL!"); checkNotNull(nullSortPosition, "Precondition violation - argument 'null' must not be NULL!"); return new AscendingCOrder(textCompare, nullSortPosition); } public static COrder desc() { return desc(TextCompare.DEFAULT, NullSortPosition.DEFAULT); } public static COrder desc(TextCompare textCompare){ checkNotNull(textCompare, "Precondition violation - argument 'textCompare' must not be NULL!"); return desc(textCompare, NullSortPosition.DEFAULT); } public static COrder desc(NullSortPosition nullSortPosition) { checkNotNull(nullSortPosition, "Precondition violation - argument 'nullSortPosition' must not be NULL!"); return desc(TextCompare.DEFAULT, nullSortPosition); } public static COrder desc(TextCompare textCompare, NullSortPosition nullSortPosition){ checkNotNull(textCompare, "Precondition violation - argument 'textCompare' must not be NULL!"); checkNotNull(nullSortPosition, "Precondition violation - argument 'null' must not be NULL!"); return new DescendingCOrder(textCompare, nullSortPosition); } public Object normalize(Object obj); public Order getDirection(); public TextCompare getTextCompare(); public NullSortPosition getNullSortPosition(); public COrder reversed(); public int compare(Object first, Object second); }
2,647
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
VertexIndexBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/index/VertexIndexBuilder.java
package org.chronos.chronograph.api.builder.index; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronograph.api.index.ChronoGraphIndex; /** * A step in the fluent graph index builder API. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface VertexIndexBuilder { public FinalizableVertexIndexBuilder withValidityPeriod(long startTimestamp, long endTimestamp); public default FinalizableVertexIndexBuilder withValidityPeriod(Period period) { return this.withValidityPeriod(period.getLowerBound(), period.getUpperBound()); } public default FinalizableVertexIndexBuilder acrossAllTimestamps(){ return this.withValidityPeriod(Period.eternal()); } }
751
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
IndexBuilderStarter.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/index/IndexBuilderStarter.java
package org.chronos.chronograph.api.builder.index; import org.chronos.chronograph.api.index.ChronoGraphIndexManager; /** * The first step of the fluent builder API for creating graph indices. * * <p> * You can get an instance of this class by calling {@link ChronoGraphIndexManager#create()}. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface IndexBuilderStarter { /** * Creates an index where individual values are strings. * * @return The builder, for method chaining. Never <code>null</code>. */ public ElementTypeChoiceIndexBuilder stringIndex(); /** * Creates an index where individual values are longs. * * <p> * Besides {@link Long}, there are also several other classes that work with this type of index (conversion to {@link Long} takes place automatically): * <ul> * <li>{@link Byte} * <li>{@link Short} * <li>{@link Integer} * </ul> * * @return The builder, for method chaining. Never <code>null</code>. */ public ElementTypeChoiceIndexBuilder longIndex(); /** * Creates an index where individual values are doubles. * * <p> * Besides {@link Double}, this index is also compatible with values of type {@link Float}, which will automatically be converted to {@link Double}. * * @return The builder, for method chaining. Never <code>null</code>. */ public ElementTypeChoiceIndexBuilder doubleIndex(); }
1,418
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
FinalizableEdgeIndexBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/index/FinalizableEdgeIndexBuilder.java
package org.chronos.chronograph.api.builder.index; import org.chronos.chronograph.api.index.ChronoGraphIndex; public interface FinalizableEdgeIndexBuilder { public FinalizableEdgeIndexBuilder assumeNoPriorValues(boolean assumeNoPriorValues); public ChronoGraphIndex build(); }
290
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
FinalizableVertexIndexBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/index/FinalizableVertexIndexBuilder.java
package org.chronos.chronograph.api.builder.index; import org.chronos.chronograph.api.index.ChronoGraphIndex; public interface FinalizableVertexIndexBuilder { public FinalizableVertexIndexBuilder assumeNoPriorValues(boolean assumeNoPriorValues); public ChronoGraphIndex build(); }
294
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EdgeIndexBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/index/EdgeIndexBuilder.java
package org.chronos.chronograph.api.builder.index; import org.chronos.chronodb.internal.api.Period; /** * A step in the fluent graph index builder API. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface EdgeIndexBuilder { public FinalizableEdgeIndexBuilder withValidityPeriod(long startTimestamp, long endTimestamp); public default FinalizableEdgeIndexBuilder withValidityPeriod(Period period) { return this.withValidityPeriod(period.getLowerBound(), period.getUpperBound()); } public default FinalizableEdgeIndexBuilder acrossAllTimestamps(){ return this.withValidityPeriod(Period.eternal()); } }
684
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ElementTypeChoiceIndexBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronograph/src/main/java/org/chronos/chronograph/api/builder/index/ElementTypeChoiceIndexBuilder.java
package org.chronos.chronograph.api.builder.index; /** * A step in the fluent graph index builder API. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API */ public interface ElementTypeChoiceIndexBuilder { /** * Creates a new index on the given vertex property. * * @param propertyName * The name (key) of the vertex property to index. Must not be <code>null</code>. * * @return The next step in the fluent builder, for method chaining. Never <code>null</code>. */ public VertexIndexBuilder onVertexProperty(String propertyName); /** * Creates a new index on the given edge property. * * @param propertyName * The name (key) of the edge property to index. Must not be <code>null</code>. * @return The next step in the fluent builder, for method chaining. Never <code>null</code>. */ public EdgeIndexBuilder onEdgeProperty(String propertyName); }
926
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ExodusSecondaryIndex.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronodb.exodus/src/main/java/org/chronos/chronodb/exodus/secondaryindex/ExodusSecondaryIndex.java
package org.chronos.chronodb.exodus.secondaryindex; import org.chronos.chronodb.api.SecondaryIndex; import org.chronos.chronodb.api.indexing.Indexer; import org.chronos.chronodb.internal.api.Period; import org.chronos.chronodb.internal.impl.index.IndexingOption; import org.chronos.chronodb.internal.impl.index.SecondaryIndexImpl; import org.chronos.common.annotation.PersistentClass; import org.chronos.common.serialization.KryoManager; import java.util.Base64; import java.util.Set; import static com.google.common.base.Preconditions.*; @PersistentClass("kryo") public class ExodusSecondaryIndex { private String id; private String name; private String indexerBytesBase64; private long validFrom; private long validTo; private String branch; private String parentIndexId; private Boolean dirty; private Set<IndexingOption> options; private ExodusSecondaryIndex() { // default constructor for deserialization } public ExodusSecondaryIndex(SecondaryIndex index) { checkNotNull(index, "Precondition violation - argument 'index' must not be NULL!"); this.id = index.getId(); this.name = index.getName(); byte[] indexerSerialized = KryoManager.serialize(index.getIndexer()); this.indexerBytesBase64 = Base64.getEncoder().encodeToString(indexerSerialized); this.validFrom = index.getValidPeriod().getLowerBound(); this.validTo = index.getValidPeriod().getUpperBound(); this.branch = index.getBranch(); this.parentIndexId = index.getParentIndexId(); this.dirty = index.getDirty(); this.options = index.getOptions(); } public SecondaryIndex toSecondaryIndex() { byte[] serialForm = Base64.getDecoder().decode(this.indexerBytesBase64); Indexer<?> indexer = KryoManager.deserialize(serialForm); return new SecondaryIndexImpl( id, name, indexer, Period.createRange(validFrom, validTo), branch, parentIndexId, dirty, options ); } }
2,114
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
JohnDoeFamilyModel.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/testmodels/instance/JohnDoeFamilyModel.java
package org.chronos.chronosphere.test.testmodels.instance; import org.chronos.chronosphere.test.testmodels.meta.PersonMetamodel; import org.chronos.chronosphere.test.utils.EMFTestUtils; 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 static org.junit.Assert.*; public class JohnDoeFamilyModel extends AbstractTestModel { public static final String ID_JOHN_DOE = "4145c03e-d324-498a-a02b-0db5ed566019"; public static final String ID_JANE_DOE = "ba0ca4f4-c431-49c7-9292-a03fe0c449a5"; public static final String ID_JACK_SMITH = "87f231e4-eb41-477c-bd7f-60ad686c6e35"; public static final String ID_JOHN_PARKER = "98587546-92a0-4a75-855d-043c36184fc5"; public static final String ID_SARAH_DOE = "16556ba6-1339-4861-acbd-b8eb4d76c0be"; public JohnDoeFamilyModel() { super(PersonMetamodel.createPersonEPackage()); } // ===================================================================================================================== // MODEL CREATION // ===================================================================================================================== @Override protected void createModelData() { EPackage ePackage = this.getEPackage(); // extract some data from the EPackage EClass ecPerson = (EClass) ePackage.getEClassifier("Person"); assertNotNull(ecPerson); EAttribute eaFirstName = (EAttribute) ecPerson.getEStructuralFeature("firstName"); EAttribute eaLastName = (EAttribute) ecPerson.getEStructuralFeature("lastName"); EReference erFriend = (EReference) ecPerson.getEStructuralFeature("friend"); EReference erMarried = (EReference) ecPerson.getEStructuralFeature("married"); EReference erChild = (EReference) ecPerson.getEStructuralFeature("child"); assertNotNull(eaFirstName); assertNotNull(eaLastName); assertNotNull(erFriend); assertNotNull(erMarried); assertNotNull(erChild); // create some persons EObject pJohnDoe = this.createAndRegisterEObject(ID_JOHN_DOE, ecPerson); pJohnDoe.eSet(eaFirstName, "John"); pJohnDoe.eSet(eaLastName, "Doe"); EObject pJaneDoe = this.createAndRegisterEObject(ID_JANE_DOE, ecPerson); pJaneDoe.eSet(eaFirstName, "Jane"); pJaneDoe.eSet(eaLastName, "Doe"); // marry john and jane pJohnDoe.eSet(erMarried, pJaneDoe); // assert that the inverse was set assertEquals(pJohnDoe, pJaneDoe.eGet(erMarried)); EObject pJackSmith = this.createAndRegisterEObject(ID_JACK_SMITH, ecPerson); pJackSmith.eSet(eaFirstName, "Jack"); pJackSmith.eSet(eaLastName, "Smith"); // john and jack are friends EMFTestUtils.addToEReference(pJohnDoe, erFriend, pJackSmith); EMFTestUtils.addToEReference(pJackSmith, erFriend, pJohnDoe); EObject pJohnParker = this.createAndRegisterEObject(ID_JOHN_PARKER, ecPerson); pJohnParker.eSet(eaFirstName, "John"); pJohnParker.eSet(eaLastName, "Parker"); // john d. and john p. are also friends EMFTestUtils.addToEReference(pJohnDoe, erFriend, pJohnParker); EMFTestUtils.addToEReference(pJohnParker, erFriend, pJohnDoe); EObject pSarahDoe = this.createAndRegisterEObject(ID_SARAH_DOE, ecPerson); pSarahDoe.eSet(eaFirstName, "Sarah"); pSarahDoe.eSet(eaLastName, "Doe"); // sarah is the child of john and jane EMFTestUtils.addToEReference(pJohnDoe, erChild, pSarahDoe); EMFTestUtils.addToEReference(pJaneDoe, erChild, pSarahDoe); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== public EObject getJohnDoe() { return this.getEObjectByID(ID_JOHN_DOE); } public EObject getJaneDoe() { return this.getEObjectByID(ID_JANE_DOE); } public EObject getSarahDoe() { return this.getEObjectByID(ID_SARAH_DOE); } public EObject getJackSmith() { return this.getEObjectByID(ID_JACK_SMITH); } public EObject getJohnParker() { return this.getEObjectByID(ID_JOHN_PARKER); } }
4,508
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractTestModel.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/testmodels/instance/AbstractTestModel.java
package org.chronos.chronosphere.test.testmodels.instance; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.impl.ChronoEObjectImpl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.*; public abstract class AbstractTestModel implements TestModel { private final Map<String, EObject> eObjectById = Maps.newHashMap(); private final EPackage ePackage; protected AbstractTestModel(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.ePackage = ePackage; this.createModelData(); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public EPackage getEPackage() { return this.ePackage; } @Override public EObject getEObjectByID(final String id) { checkNotNull(id, "Precondition violation - argument 'id' must not be NULL!"); return this.eObjectById.get(id); } @Override public Set<EObject> getAllEObjects() { return Collections.unmodifiableSet(Sets.newHashSet(this.eObjectById.values())); } @Override public Iterator<EObject> iterator() { return this.getAllEObjects().iterator(); } // ===================================================================================================================== // INTERNAL API // ===================================================================================================================== protected void registerEObject(final EObject eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); ChronoEObject chronoEObject = (ChronoEObject) eObject; this.eObjectById.put(chronoEObject.getId(), chronoEObject); } protected EObject createAndRegisterEObject(final String eObjectId, final EClass eClass) { checkNotNull(eObjectId, "Precondition violation - argument 'eObjectId' must not be NULL!"); checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); EObject eObject = new ChronoEObjectImpl(eObjectId, eClass); this.registerEObject(eObject); return eObject; } // ===================================================================================================================== // ABSTRACT METHOD DECLARATIONS // ===================================================================================================================== protected abstract void createModelData(); }
3,077
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TestModel.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/testmodels/instance/TestModel.java
package org.chronos.chronosphere.test.testmodels.instance; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import java.util.Set; public interface TestModel extends Iterable<EObject> { public EPackage getEPackage(); public Set<EObject> getAllEObjects(); public EObject getEObjectByID(String id); }
345
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
PersonMetamodel.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/testmodels/meta/PersonMetamodel.java
package org.chronos.chronosphere.test.testmodels.meta; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; public class PersonMetamodel { public static final String PERSON_EPACKAGE_NS_URI = "http://www.example.com/model/person"; public static EPackage createPersonEPackage() { EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setNsURI(PERSON_EPACKAGE_NS_URI); ePackage.setNsPrefix("http://www.example.com/model"); ePackage.setName("Person"); { EClass ecPerson = EcoreFactory.eINSTANCE.createEClass(); ecPerson.setName("Person"); { EAttribute eaFirstName = EcoreFactory.eINSTANCE.createEAttribute(); eaFirstName.setName("firstName"); eaFirstName.setEType(EcorePackage.Literals.ESTRING); eaFirstName.setLowerBound(0); eaFirstName.setUpperBound(1); ecPerson.getEStructuralFeatures().add(eaFirstName); EAttribute eaLastName = EcoreFactory.eINSTANCE.createEAttribute(); eaLastName.setName("lastName"); eaLastName.setEType(EcorePackage.Literals.ESTRING); eaLastName.setLowerBound(0); eaLastName.setUpperBound(1); ecPerson.getEStructuralFeatures().add(eaLastName); EReference erFriend = EcoreFactory.eINSTANCE.createEReference(); erFriend.setName("friend"); erFriend.setEType(ecPerson); erFriend.setLowerBound(0); erFriend.setUpperBound(-1); erFriend.setOrdered(false); erFriend.setUnique(true); erFriend.setContainment(false); ecPerson.getEStructuralFeatures().add(erFriend); EReference erMarried = EcoreFactory.eINSTANCE.createEReference(); erMarried.setName("married"); erMarried.setEType(ecPerson); erMarried.setEOpposite(erMarried); erMarried.setLowerBound(0); erMarried.setUpperBound(1); erMarried.setContainment(false); ecPerson.getEStructuralFeatures().add(erMarried); EReference erChild = EcoreFactory.eINSTANCE.createEReference(); erChild.setName("child"); erChild.setEType(ecPerson); erChild.setLowerBound(0); erChild.setUpperBound(-1); erChild.setUnique(true); erChild.setOrdered(false); ecPerson.getEStructuralFeatures().add(erChild); } ePackage.getEClassifiers().add(ecPerson); } return ePackage; } }
2,951
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GrabatsMetamodel.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/testmodels/meta/GrabatsMetamodel.java
package org.chronos.chronosphere.test.testmodels.meta; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.eclipse.emf.ecore.EPackage; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.List; public class GrabatsMetamodel { private static final String GRABATS_DIR = "testmetamodels/grabats/"; public static List<EPackage> createCFGEPackages() { return loadGrabatsEPackages("CFG.ecore"); } public static List<EPackage> createJDTASTEPackages() { return loadGrabatsEPackages("JDTAST.ecore"); } public static List<EPackage> createPGEPackages() { return loadGrabatsEPackages("PDG.ecore"); } public static List<EPackage> createQ1ViewEPackages() { return loadGrabatsEPackages("Q1View.ecore"); } public static List<EPackage> createAllEPackages() { List<EPackage> resultList = Lists.newArrayList(); resultList.addAll(createCFGEPackages()); resultList.addAll(createJDTASTEPackages()); resultList.addAll(createPGEPackages()); resultList.addAll(createQ1ViewEPackages()); return resultList; } private static List<EPackage> loadGrabatsEPackages(final String ecoreFileName) { try { InputStream stream = GrabatsMetamodel.class.getClassLoader() .getResourceAsStream(GRABATS_DIR + ecoreFileName); String xmiContents = IOUtils.toString(stream, Charset.forName("utf-8")); return EMFUtils.readEPackagesFromXMI(xmiContents); } catch (IOException ioe) { throw new RuntimeException("Failed to load Ecore test file!", ioe); } } }
1,787
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereTestSuite.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/_suite/ChronoSphereTestSuite.java
package org.chronos.chronosphere.test._suite; import org.chronos.chronograph.test._suite.ChronoGraphTestSuite; import org.chronos.common.test.junit.ExcludeCategories; import org.chronos.common.test.junit.PackageSuite; import org.chronos.common.test.junit.SuiteIncludes; import org.chronos.common.test.junit.SuitePackages; import org.chronos.common.test.junit.categories.PerformanceTest; import org.chronos.common.test.junit.categories.SlowTest; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Suite; @Category(Suite.class) @RunWith(PackageSuite.class) @SuiteIncludes(ChronoGraphTestSuite.class) @SuitePackages("org.chronos.chronosphere.test.cases") @ExcludeCategories({PerformanceTest.class, SlowTest.class}) public class ChronoSphereTestSuite { }
812
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GrabatsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/grabats/GrabatsTest.java
package org.chronos.chronosphere.test.cases.grabats; import com.google.common.base.Charsets; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; import org.apache.commons.io.IOUtils; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.test.base.AllChronoSphereBackendsTest; import org.chronos.chronosphere.test.testmodels.meta.GrabatsMetamodel; import org.chronos.common.test.junit.categories.PerformanceTest; 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.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.List; import java.util.zip.GZIPInputStream; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; @Category(PerformanceTest.class) public class GrabatsTest extends AllChronoSphereBackendsTest { private static final Logger log = LoggerFactory.getLogger(GrabatsTest.class); @Test public void grabatsMetamodelFilesArePresent() { assertTrue(GrabatsMetamodel.createCFGEPackages().size() > 0); assertTrue(GrabatsMetamodel.createJDTASTEPackages().size() > 0); assertTrue(GrabatsMetamodel.createPGEPackages().size() > 0); assertTrue(GrabatsMetamodel.createQ1ViewEPackages().size() > 0); } @Test public void canRegisterGrabatsMetamodels() { ChronoSphere sphere = this.getChronoSphere(); registerGrabatsMetamodels(sphere); try (ChronoSphereTransaction tx = sphere.tx()) { for (EPackage ePackage : GrabatsMetamodel.createAllEPackages()) { EPackage storedEPackage = tx.getEPackageByNsURI(ePackage.getNsURI()); assertNotNull(storedEPackage); checkEPackageConsistency(storedEPackage); } } } @Test public void canLoadGrabatsSet0withStandardEcoreXMI() throws Exception { long timeBeforeXMIread = System.currentTimeMillis(); InputStream stream = new GZIPInputStream( GrabatsTest.class.getClassLoader().getResourceAsStream("testinstancemodels/grabats/set0.xmi.gz")); String xmiContents = IOUtils.toString(stream, Charsets.UTF_8); long timeAfterXMIread = System.currentTimeMillis(); log.info("Loaded GRABATS set0.xmi into a String in " + (timeAfterXMIread - timeBeforeXMIread) + "ms."); long timeBeforeBatchLoad = System.currentTimeMillis(); List<EObject> eObjects = EMFUtils.readEObjectsFromXMI(xmiContents, Sets.newHashSet(GrabatsMetamodel.createAllEPackages())); long timeAfterBatchLoad = System.currentTimeMillis(); log.info("Loaded GRABATS set0.xmi into Ecore in " + (timeAfterBatchLoad - timeBeforeBatchLoad) + "ms."); int count = 0; for (EObject eObject : eObjects) { count += Iterators.size(eObject.eAllContents()) + 1; } log.info("GRABATS set0.xmi contains " + count + " EObjects."); } @Test public void canLoadGrabatsSet0withBatchLoad() throws Exception { ChronoSphere sphere = this.getChronoSphere(); registerGrabatsMetamodels(sphere); long timeBeforeXMIread = System.currentTimeMillis(); InputStream stream = new GZIPInputStream( GrabatsMetamodel.class.getClassLoader().getResourceAsStream("testinstancemodels/grabats/set0.xmi.gz")); String xmiContents = IOUtils.toString(stream, Charsets.UTF_8); long timeAfterXMIread = System.currentTimeMillis(); log.info("Loaded GRABATS set0.xmi into a String in " + (timeAfterXMIread - timeBeforeXMIread) + "ms."); long timeBeforeBatchLoad = System.currentTimeMillis(); sphere.batchInsertModelData(xmiContents); long timeAfterBatchLoad = System.currentTimeMillis(); log.info("Loaded GRABATS set0.xmi into ChronoSphere in " + (timeAfterBatchLoad - timeBeforeBatchLoad) + "ms."); } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private static void registerGrabatsMetamodels(final ChronoSphere sphere) { sphere.getEPackageManager().registerOrUpdateEPackages(GrabatsMetamodel.createAllEPackages()); } private static void checkEPackageConsistency(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); for (EClassifier eClassifier : ePackage.getEClassifiers()) { if (eClassifier instanceof EClass == false) { continue; } assertNotNull(eClassifier.getEPackage()); assertNotNull(eClassifier.getName()); for (EReference feature : ((EClass) eClassifier).getEAllReferences()) { EClassifier eType = feature.getEType(); if (eType instanceof EClass == false) { continue; } assertNotNull("FAIL: " + eClassifier.getEPackage().getNsURI() + " -> " + eClassifier.getName() + " -> " + feature.getName() + " :: EType has no EPackage!", eType.getEPackage()); assertNotNull("FAIL: " + eClassifier.getEPackage().getNsURI() + " -> " + eClassifier.getName() + " -> " + feature.getName() + " :: EType has no Name!", eType.getName()); } } for (EPackage subPackage : ePackage.getESubpackages()) { checkEPackageConsistency(subPackage); } } }
5,985
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereConfigurationTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/configuration/ChronoSphereConfigurationTest.java
package org.chronos.chronosphere.test.cases.configuration; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.internal.api.ChronoSphereInternal; import org.chronos.chronosphere.test.base.AllChronoSphereBackendsTest; import org.chronos.common.test.junit.categories.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoSphereConfigurationTest extends AllChronoSphereBackendsTest { @Test public void configurationIsPresent() { ChronoSphereInternal repository = this.getChronoSphere(); assertNotNull(repository); assertNotNull(repository.getConfiguration()); assertNotNull(repository.getRootGraph()); } @Test public void canOpenAndCloseRepository() { ChronoSphere repository = this.getChronoSphere(); // assert that it's open assertTrue(repository.isOpen()); assertFalse(repository.isClosed()); // close it now repository.close(); // assert that it's closed assertFalse(repository.isOpen()); assertTrue(repository.isClosed()); } }
1,216
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryAPITest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/query/QueryAPITest.java
package org.chronos.chronosphere.test.cases.query; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.test.base.AllChronoSphereBackendsTest; import org.chronos.chronosphere.test.testmodels.instance.JohnDoeFamilyModel; import org.chronos.chronosphere.test.testmodels.meta.PersonMetamodel; import org.chronos.chronosphere.test.utils.ChronoSphereTestUtils; 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.junit.Test; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static org.chronos.chronosphere.api.query.SubQuery.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; public class QueryAPITest extends AllChronoSphereBackendsTest { @Test public void canFindJohnsFriends() { ChronoSphere sphere = this.getChronoSphere(); // create and register the EPackage for this test JohnDoeFamilyModel testModel = new JohnDoeFamilyModel(); EPackage ePackage = testModel.getEPackage(); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // open a transaction ChronoSphereTransaction tx = sphere.tx(); // attach all elements from the test model tx.attach(testModel); ChronoSphereTestUtils.assertCommitAssert(tx, transaction -> { Set<EObject> johnsFriends = transaction.find() // we start with all EObjects .startingFromAllEObjects() // we are interested only in persons .isInstanceOf("Person") // we are interested only in persons named John .has("firstName", "John") // ... that also have last name "Doe" .has("lastName", "Doe") // we get the friends of that person .eGet("friend") // and collect everything in a set of EObjects .asEObject().toSet(); EObject johnParker = testModel.getJohnParker(); EObject jackSmith = testModel.getJackSmith(); assertEquals(Sets.newHashSet(johnParker, jackSmith), johnsFriends); }); } @Test public void canFindSarahsParentsViaReferencingEObjects() { ChronoSphere sphere = this.getChronoSphere(); // create and register the EPackage for this test JohnDoeFamilyModel testModel = new JohnDoeFamilyModel(); EPackage ePackage = testModel.getEPackage(); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // open a transaction ChronoSphereTransaction tx = sphere.tx(); // attach all elements from the test model tx.attach(testModel); ChronoSphereTestUtils.assertCommitAssert(tx, transaction -> { EObject sarahDoe = testModel.getSarahDoe(); Set<EObject> sarahsParents = transaction.find() // we start with all EObjects .startingFromEObject(sarahDoe) // get the referencing eobjects (which should be her parents) .allReferencingEObjects().toSet(); EObject johnDoe = testModel.getJohnDoe(); EObject janeDoe = testModel.getJaneDoe(); assertEquals(Sets.newHashSet(johnDoe, janeDoe), sarahsParents); }); } @Test public void canFindAllPersonsWhoHaveChildren() { ChronoSphere sphere = this.getChronoSphere(); // create and register the EPackage for this test JohnDoeFamilyModel testModel = new JohnDoeFamilyModel(); EPackage ePackage = testModel.getEPackage(); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // open a transaction ChronoSphereTransaction tx = sphere.tx(); // attach all elements from the test model tx.attach(testModel); ChronoSphereTestUtils.assertCommitAssert(tx, transaction -> { EClass person = (EClass) ePackage.getEClassifier("Person"); Set<EObject> personsWithChildren = transaction.find().startingFromInstancesOf(person).named("parents") .eGet("child").back("parents").asEObject().toSet(); EObject johnDoe = testModel.getJohnDoe(); EObject janeDoe = testModel.getJaneDoe(); assertEquals(Sets.newHashSet(johnDoe, janeDoe), personsWithChildren); }); } @Test @SuppressWarnings("unchecked") public void canFindFamilyOfJohnWithSubqueries() { ChronoSphere sphere = this.getChronoSphere(); // create and register the EPackage for this test JohnDoeFamilyModel testModel = new JohnDoeFamilyModel(); EPackage ePackage = testModel.getEPackage(); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // open a transaction ChronoSphereTransaction tx = sphere.tx(); // attach all elements from the test model tx.attach(testModel); ChronoSphereTestUtils.assertCommitAssert(tx, transaction -> { EObject johnDoe = testModel.getJohnDoe(); Set<EObject> queryResult = transaction.find() .startingFromEObject(johnDoe) .union( eGet("child"), eGet("married") ).asEObject() .toSet(); // married to EObject janeDoe = testModel.getJaneDoe(); // children EObject sarahDoe = testModel.getSarahDoe(); Set<EObject> family = Sets.newHashSet(janeDoe, sarahDoe); assertEquals(family, queryResult); }); } @Test @SuppressWarnings("unchecked") public void canFindFamilyOfJohnWithSubqueries2() { ChronoSphere sphere = this.getChronoSphere(); // create and register the EPackage for this test JohnDoeFamilyModel testModel = new JohnDoeFamilyModel(); EPackage ePackage = testModel.getEPackage(); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // open a transaction ChronoSphereTransaction tx = sphere.tx(); // attach all elements from the test model tx.attach(testModel); EReference child = tx.getEReferenceByQualifiedName("Person::Person#child"); assertNotNull(child); EReference married = tx.getEReferenceByQualifiedName("Person::Person#married"); assertNotNull(married); ChronoSphereTestUtils.assertCommitAssert(tx, transaction -> { EObject johnDoe = testModel.getJohnDoe(); Set<EObject> queryResult = transaction.find() .startingFromEObject(johnDoe) .union( eGet(child), eGet(married) ).asEObject() .toSet(); // married to EObject janeDoe = testModel.getJaneDoe(); // children EObject sarahDoe = testModel.getSarahDoe(); Set<EObject> family = Sets.newHashSet(janeDoe, sarahDoe); assertEquals(family, queryResult); }); } @Test public void canCalculateTransitiveClosure() { ChronoSphere sphere = this.getChronoSphere(); EPackage personEPackage = PersonMetamodel.createPersonEPackage(); sphere.getEPackageManager().registerOrUpdateEPackage(personEPackage); { // setup // open a transaction ChronoSphereTransaction tx = sphere.tx(); EClass person = tx.getEClassBySimpleName("Person"); assertNotNull(person); EAttribute firstName = EMFUtils.getEAttribute(person, "firstName"); assertNotNull(firstName); EReference friend = EMFUtils.getEReference(person, "friend"); assertNotNull(friend); // create an instance model for testing. // the following four persons form a circle EObject p1 = tx.createAndAttach(person); p1.eSet(firstName, "p1"); EObject p2 = tx.createAndAttach(person); p2.eSet(firstName, "p2"); EObject p3 = tx.createAndAttach(person); p3.eSet(firstName, "p3"); EObject p4 = tx.createAndAttach(person); p4.eSet(firstName, "p4"); EMFUtils.eGetMany(p1, friend).add(p2); EMFUtils.eGetMany(p2, friend).add(p3); EMFUtils.eGetMany(p3, friend).add(p4); EMFUtils.eGetMany(p4, friend).add(p1); // the following objects form a cycle of size 2 with each of the // four original persons EObject p5 = tx.createAndAttach(person); p5.eSet(firstName, "p5"); EObject p6 = tx.createAndAttach(person); p6.eSet(firstName, "p6"); EObject p7 = tx.createAndAttach(person); p7.eSet(firstName, "p7"); EObject p8 = tx.createAndAttach(person); p8.eSet(firstName, "p8"); EMFUtils.eGetMany(p1, friend).add(p5); EMFUtils.eGetMany(p5, friend).add(p1); EMFUtils.eGetMany(p2, friend).add(p6); EMFUtils.eGetMany(p6, friend).add(p2); EMFUtils.eGetMany(p3, friend).add(p7); EMFUtils.eGetMany(p7, friend).add(p3); EMFUtils.eGetMany(p4, friend).add(p8); EMFUtils.eGetMany(p8, friend).add(p4); tx.commit(); } { // test // open a new transaction ChronoSphereTransaction tx = sphere.tx(); EClass person = tx.getEClassBySimpleName("Person"); assertNotNull(person); EAttribute firstName = EMFUtils.getEAttribute(person, "firstName"); assertNotNull(firstName); EReference friend = EMFUtils.getEReference(person, "friend"); assertNotNull(friend); Set<EObject> startPersons = tx.find().startingFromInstancesOf(person).has(firstName, "p1").toSet(); assertThat(startPersons.size(), is(1)); EObject p1Reloaded = Iterables.getOnlyElement(startPersons); assertThat(p1Reloaded.eGet(firstName), is("p1")); // start the closure calculation List<EObject> eObjects = tx.find().startingFromEObject(p1Reloaded).closure(friend).toList(); assertThat(eObjects.size(), is(7)); List<String> names = eObjects.stream().map(eObj -> (String) eObj.eGet(firstName)).collect(Collectors.toList()); assertTrue(names.contains("p2")); assertTrue(names.contains("p3")); assertTrue(names.contains("p4")); assertTrue(names.contains("p5")); assertTrue(names.contains("p6")); assertTrue(names.contains("p7")); } } }
11,172
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereIndexManagerTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/indexing/ChronoSphereIndexManagerTest.java
package org.chronos.chronosphere.test.cases.indexing; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.internal.api.ChronoSphereInternal; import org.chronos.chronosphere.test.base.AllChronoSphereBackendsTest; import org.chronos.chronosphere.test.testmodels.instance.JohnDoeFamilyModel; import org.chronos.chronosphere.test.testmodels.meta.PersonMetamodel; import org.chronos.chronosphere.test.utils.ChronoSphereTestUtils; import org.chronos.common.test.junit.categories.IntegrationTest; 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.junit.Test; import org.junit.experimental.categories.Category; import java.util.Set; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoSphereIndexManagerTest extends AllChronoSphereBackendsTest { @Test public void canCreateAndDropIndexOnEAttribute() { ChronoSphereInternal sphere = this.getChronoSphere(); EPackage ePackage = PersonMetamodel.createPersonEPackage(); EClass ecPerson = (EClass) ePackage.getEClassifier("Person"); assertNotNull(ecPerson); EAttribute eaFirstName = (EAttribute) ecPerson.getEStructuralFeature("firstName"); assertNotNull(eaFirstName); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // check that the "first name" attribute is not indexed yet assertFalse(sphere.getIndexManager().existsIndexOn(eaFirstName)); assertFalse(sphere.getIndexManager().isIndexDirty(eaFirstName)); // create the index assertTrue(sphere.getIndexManager().createIndexOn(eaFirstName)); // reindex it sphere.getIndexManager().reindexAll(); // it should not be dirty anymore assertFalse(sphere.getIndexManager().isIndexDirty(eaFirstName)); // drop the index assertTrue(sphere.getIndexManager().dropIndexOn(eaFirstName)); // it should not be there anymore assertFalse(sphere.getIndexManager().existsIndexOn(eaFirstName)); } @Test public void canQueryIndex() { ChronoSphereInternal sphere = this.getChronoSphere(); // create the model and metamodel in-memory JohnDoeFamilyModel model = new JohnDoeFamilyModel(); EPackage ePackage = model.getEPackage(); // extract the EAttribute we want to index from the EPackage EClass ecPerson = (EClass) ePackage.getEClassifier("Person"); assertNotNull(ecPerson); EAttribute eaFirstName = (EAttribute) ecPerson.getEStructuralFeature("firstName"); assertNotNull(eaFirstName); // register the epackage sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // create the index sphere.getIndexManager().createIndexOn(eaFirstName); sphere.getIndexManager().reindexAll(); assertTrue(sphere.getIndexManager().existsIndexOn(eaFirstName)); assertFalse(sphere.getIndexManager().isIndexDirty(eaFirstName)); // attach the model ChronoSphereTransaction transaction = sphere.tx(); transaction.attach(model); ChronoSphereTestUtils.assertCommitAssert(transaction, tx -> { Set<EObject> johns = tx.find().startingFromEObjectsWith(eaFirstName, "John").toSet(); assertEquals(2, johns.size()); assertTrue(johns.contains(model.getJohnDoe())); assertTrue(johns.contains(model.getJohnParker())); }); } }
3,589
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BasicMetamodelEvolutionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/evolution/BasicMetamodelEvolutionTest.java
package org.chronos.chronosphere.test.cases.evolution; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.api.MetaModelEvolutionContext; import org.chronos.chronosphere.api.MetaModelEvolutionIncubator; import org.chronos.chronosphere.api.exceptions.ElementCannotBeEvolvedException; import org.chronos.chronosphere.api.exceptions.MetaModelEvolutionCanceledException; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.test.base.AllChronoSphereBackendsTest; import org.chronos.chronosphere.test.testmodels.instance.JohnDoeFamilyModel; import org.chronos.chronosphere.test.testmodels.meta.PersonMetamodel; 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.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import org.junit.Test; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import static org.junit.Assert.*; public class BasicMetamodelEvolutionTest extends AllChronoSphereBackendsTest { @Test public void canPerformSimpleMigrationWithIncubator() { ChronoSphere sphere = this.getChronoSphere(); // prepare the epackage EPackage personEPackage = PersonMetamodel.createPersonEPackage(); sphere.getEPackageManager().registerOrUpdateEPackage(personEPackage); // attach the EObjects try (ChronoSphereTransaction tx = sphere.tx()) { tx.attach(new JohnDoeFamilyModel()); tx.commit(); } long afterFirstInsert = sphere.getBranchManager().getMasterBranch().getNow(); // check that the new EObjects have been stored successfully try (ChronoSphereTransaction tx = sphere.tx()) { EPackage ePackage = tx.getEPackageByNsURI(PersonMetamodel.PERSON_EPACKAGE_NS_URI); EClass personEClass = (EClass) ePackage.getEClassifier("Person"); assertEquals(5, tx.find().startingFromInstancesOf(personEClass).count()); } // create another copy of the person EPackage... EPackage evolvedPersonEPackage = PersonMetamodel.createPersonEPackage(); // ... and evolve it to the next version evolvePersonEPackage(evolvedPersonEPackage); // create the incubator for this change MetaModelEvolutionIncubator incubator = new PersonMetamodelIncubator(); // evolve the instance model sphere.getEPackageManager().evolveMetamodel(incubator, evolvedPersonEPackage); long afterMetamodelEvolution = sphere.getBranchManager().getMasterBranch().getNow(); assertTrue(afterMetamodelEvolution > afterFirstInsert); // assert that the old version is still there and valid try (ChronoSphereTransaction tx = sphere.tx(afterFirstInsert)) { Set<EObject> eObjects = tx.find().startingFromAllEObjects().has("firstName", "John").has("lastName", "Doe") .toSet(); assertEquals(1, eObjects.size()); EObject johnDoe = Iterables.getOnlyElement(eObjects); assertNotNull(johnDoe.eClass().getEStructuralFeature("firstName")); assertNotNull(johnDoe.eClass().getEStructuralFeature("lastName")); } // assert that the new version exists and is valid try (ChronoSphereTransaction tx = sphere.tx(afterMetamodelEvolution)) { Set<EObject> eObjects = tx.find().startingFromAllEObjects().has("name", "John Doe").toSet(); assertEquals(1, eObjects.size()); EObject johnDoe = Iterables.getOnlyElement(eObjects); EClass person = johnDoe.eClass(); EAttribute name = EMFUtils.getEAttribute(person, "name"); assertNotNull(person.getEStructuralFeature("name")); assertNull(person.getEStructuralFeature("firstName")); assertNull(person.getEStructuralFeature("lastName")); EReference married = EMFUtils.getEReference(person, "married"); assertNotNull(married); EObject janeDoe = (EObject) johnDoe.eGet(married); assertNotNull(janeDoe); assertEquals("Jane Doe", janeDoe.eGet(name)); } // assert that the history of a migrated eobject is not cut at the migration step try (ChronoSphereTransaction tx = sphere.tx()) { Set<EObject> eObjects = tx.find().startingFromAllEObjects().has("name", "John Doe").toSet(); assertEquals(1, eObjects.size()); EObject johnDoe = Iterables.getOnlyElement(eObjects); Iterator<Long> johnsHistory = tx.getEObjectHistory(johnDoe); Iterator<Long> earlierHistory = Iterators.filter(johnsHistory, timestamp -> timestamp < afterMetamodelEvolution); assertTrue(Iterators.contains(earlierHistory, afterFirstInsert)); } } private static void evolvePersonEPackage(final EPackage personEPackage) { EClass ecPerson = (EClass) personEPackage.getEClassifier("Person"); EAttribute eaFirstName = (EAttribute) ecPerson.getEStructuralFeature("firstName"); EAttribute eaLastName = (EAttribute) ecPerson.getEStructuralFeature("lastName"); ecPerson.getEStructuralFeatures().remove(eaFirstName); ecPerson.getEStructuralFeatures().remove(eaLastName); EAttribute eaName = EcoreFactory.eINSTANCE.createEAttribute(); eaName.setName("name"); eaName.setLowerBound(0); eaName.setUpperBound(1); eaName.setEType(EcorePackage.Literals.ESTRING); ecPerson.getEStructuralFeatures().add(eaName); } private static class PersonMetamodelIncubator implements MetaModelEvolutionIncubator { @Override public EClass migrateClass(final EObject oldObject, final MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException, ElementCannotBeEvolvedException { // extract data from the old metamodel EPackage oldPersonEPackage = context.getOldEPackage(PersonMetamodel.PERSON_EPACKAGE_NS_URI); EClass oldPersonEClass = (EClass) oldPersonEPackage.getEClassifier("Person"); // extract data from the new metamodel EPackage newPersonEPackage = context.getNewEPackage(PersonMetamodel.PERSON_EPACKAGE_NS_URI); EClass newPersonEClass = (EClass) newPersonEPackage.getEClassifier("Person"); // choose the new class of our EObject based on the old class if (oldPersonEClass.isInstance(oldObject)) { return newPersonEClass; } else { throw new ElementCannotBeEvolvedException(); } } @Override public void updateAttributeValues(final EObject oldObject, final EObject newObject, final MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException, ElementCannotBeEvolvedException { // create a lookup of values from the old version Map<String, Object> attributeValues = Maps.newHashMap(); for (EAttribute eAttribute : oldObject.eClass().getEAllAttributes()) { attributeValues.put(eAttribute.getName(), oldObject.eGet(eAttribute)); } // try to apply the values from the old version by-name to the new version when possible for (EAttribute eAttribute : newObject.eClass().getEAllAttributes()) { Object values = attributeValues.get(eAttribute.getName()); if (values != null) { newObject.eSet(eAttribute, values); } } // explicitly set the new "name" attribute, based on "firstName" and "lastName" in // the old model EAttribute eaName = EMFUtils.getEAttribute(newObject.eClass(), "name"); String newName = attributeValues.get("firstName") + " " + attributeValues.get("lastName"); newObject.eSet(eaName, newName); } @Override @SuppressWarnings("unchecked") public void updateReferenceTargets(final EObject oldObject, final EObject newObject, final MetaModelEvolutionContext context) throws MetaModelEvolutionCanceledException, ElementCannotBeEvolvedException { for (EReference newEReference : newObject.eClass().getEAllReferences()) { EReference oldEReference = EMFUtils.getEReference(oldObject.eClass(), newEReference.getName()); Object oldTargets = oldObject.eGet(oldEReference); Object newTargets = null; if (oldTargets != null) { if (oldEReference.isMany()) { // multiplicity-many Collection<EObject> oldTargetCollection = (Collection<EObject>) oldTargets; Collection<EObject> newTargetCollection = Lists.newArrayList(); for (EObject target : oldTargetCollection) { EObject newTarget = context.getCorrespondingEObjectInNewModel(target); newTargetCollection.add(newTarget); } newTargets = newTargetCollection; } else { // multiplicity-one EObject oldTarget = (EObject) oldTargets; EObject newTarget = context.getCorrespondingEObjectInNewModel(oldTarget); newTargets = newTarget; } } if (newTargets != null) { newObject.eSet(newEReference, newTargets); } } } } }
10,151
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereTransactionTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/transaction/ChronoSphereTransactionTest.java
package org.chronos.chronosphere.test.cases.transaction; import com.google.common.collect.Iterables; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.impl.ChronoEFactory; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.test.base.AllChronoSphereBackendsTest; import org.chronos.chronosphere.test.utils.EMFTestUtils; import org.chronos.common.test.junit.categories.IntegrationTest; import org.eclipse.emf.common.util.EList; 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.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.util.EcoreUtil; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.List; import java.util.Set; import static org.junit.Assert.*; @Category(IntegrationTest.class) public class ChronoSphereTransactionTest extends AllChronoSphereBackendsTest { @Test public void canOpenAndCloseTransaction() { ChronoSphere sphere = this.getChronoSphere(); ChronoSphereTransaction tx = sphere.tx(); assertNotNull(tx); assertTrue(tx.isOpen()); assertFalse(tx.isClosed()); tx.close(); assertFalse(tx.isOpen()); assertTrue(tx.isClosed()); } @Test public void canConfigureEPackage() { ChronoSphere sphere = this.getChronoSphere(); // create a simple dummy EPackage EPackage ePackage = this.createSimpleEPackage(); // register the EPackage at ChronoSphere sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // the registration should have replaced our EFactory assertTrue(ePackage.getEFactoryInstance() instanceof ChronoEFactory); // check that the EPackage is registered by opening a new transaction and checking the registry ChronoSphereTransaction tx = sphere.tx(); EPackage storedPackage = tx.getEPackageByNsURI("http://com.example.model.MyEPackage"); assertNotNull(storedPackage); tx.close(); } @Test public void canConfigureEPackageWithNestedSubpackages() { ChronoSphere sphere = this.getChronoSphere(); // create the EPackage that contains subpackages EPackage ePackage = this.createEPackageWithNestedEPackages(); // register the EPackage at ChronoSphere sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // the registration should have replaced our EFactory assertTrue(ePackage.getEFactoryInstance() instanceof ChronoEFactory); // check that the EPackage is registered by opening a new transaction and checking the registry ChronoSphereTransaction tx = sphere.tx(); EPackage storedPackage = tx.getEPackageByNsURI("http://com.example.model.MyEPackage"); assertNotNull(storedPackage); tx.close(); } @Test public void canAttachAndLoadSimpleEObject() { ChronoSphere sphere = this.getChronoSphere(); // create a simple dummy EPackage EPackage ePackage = this.createSimpleEPackage(); // register the EPackage at ChronoSphere sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); String eObjectID = null; // open a transaction, and write an EObject { ChronoSphereTransaction tx = sphere.tx(); // fetch the EClass from the package EClass eClass = (EClass) tx.getEPackageByNsURI("http://com.example.model.MyEPackage") .getEClassifier("MyEClass"); assertNotNull(eClass); // fetch the attribute EAttribute eaName = (EAttribute) eClass.getEStructuralFeature("name"); assertNotNull(eaName); // create an EObject EObject eObject = EcoreUtil.create(eClass); assertTrue(eObject instanceof ChronoEObject); eObject.eSet(eaName, "MyEObject"); eObjectID = ((ChronoEObject) eObject).getId(); // make sure that the EObject has an ID assertNotNull(eObjectID); // attach the EObject to the transaction tx.attach(eObject); // assert that the attachment was successful assertTrue(((ChronoEObjectInternal) eObject).isAttached()); // commit the transaction tx.commit(); } // now, when we open a transaction, we should be able to retrieve the EObject by ID { ChronoSphereTransaction tx = sphere.tx(); // fetch the EClass from the package EClass eClass = (EClass) tx.getEPackageByNsURI("http://com.example.model.MyEPackage") .getEClassifier("MyEClass"); assertNotNull(eClass); // fetch the attribute EAttribute eaName = (EAttribute) eClass.getEStructuralFeature("name"); assertNotNull(eaName); assertTrue(tx.getTimestamp() > 0); EObject eObject = tx.getEObjectById(eObjectID); assertNotNull(eObject); assertEquals(eClass, eObject.eClass()); assertEquals("MyEObject", eObject.eGet(eaName)); } } @Test @SuppressWarnings("unchecked") public void canCreateCrossReferencesBetweenAttachedEObjects() { ChronoSphere sphere = this.getChronoSphere(); // create an EPackage EPackage ePackage = this.createEPackageWithNestedEPackages(); // register the EPackage at ChronoSphere sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); String eObject1ID = null; String eObject2ID = null; String eObject3ID = null; // open a transaction, and write the three EObjects { ChronoSphereTransaction tx = sphere.tx(); // fetch the EClasses from the package EClass myEClass = EMFTestUtils .getEClassRecursive(tx.getEPackageByNsURI("http://com.example.model.MyEPackage"), "MyEClass"); EClass yourEClass = EMFTestUtils .getEClassRecursive(tx.getEPackageByNsURI("http://com.example.model.MyEPackage"), "YourEClass"); assertNotNull(myEClass); assertNotNull(yourEClass); // fetch the attribute EAttribute eaName = (EAttribute) myEClass.getEStructuralFeature("name"); assertNotNull(eaName); // create an EObject EObject eObject1 = EcoreUtil.create(myEClass); assertTrue(eObject1 instanceof ChronoEObject); eObject1.eSet(eaName, "EObject1"); eObject1ID = ((ChronoEObject) eObject1).getId(); // make sure that the EObject has an ID assertNotNull(eObject1ID); // attach the EObject to the transaction tx.attach(eObject1); // assert that the attachment was successful assertTrue(((ChronoEObjectInternal) eObject1).isAttached()); // create another EObject EObject eObject2 = EcoreUtil.create(yourEClass); assertTrue(eObject2 instanceof ChronoEObject); eObject2.eSet(eaName, "EObject2"); eObject2ID = ((ChronoEObject) eObject2).getId(); // make sure that the EObject has an ID assertNotNull(eObject2ID); // attach the EObject to the transaction tx.attach(eObject2); // assert that the attachment was successful assertTrue(((ChronoEObjectInternal) eObject2).isAttached()); // create another EObject EObject eObject3 = EcoreUtil.create(yourEClass); assertTrue(eObject3 instanceof ChronoEObject); eObject3.eSet(eaName, "EObject3"); eObject3ID = ((ChronoEObject) eObject3).getId(); // make sure that the EObject has an ID assertNotNull(eObject3ID); // attach the EObject to the transaction tx.attach(eObject3); // assert that the attachment was successful assertTrue(((ChronoEObjectInternal) eObject3).isAttached()); // get the EReference EReference eReference = (EReference) myEClass.getEStructuralFeature("knows"); assertNotNull(eReference); assertTrue(eReference.isMany()); // connect EObject1->EObject2, EObject1->EObject3 ((List<EObject>) eObject1.eGet(eReference)).add(eObject2); ((List<EObject>) eObject1.eGet(eReference)).add(eObject3); // commit the transaction tx.commit(); } // open another transaction and check that everything's there { ChronoSphereTransaction tx = sphere.tx(); // get the metamodel stuff EClass myEClass = EMFTestUtils .getEClassRecursive(tx.getEPackageByNsURI("http://com.example.model.MyEPackage"), "MyEClass"); EClass yourEClass = EMFTestUtils .getEClassRecursive(tx.getEPackageByNsURI("http://com.example.model.MyEPackage"), "YourEClass"); EReference eReference = (EReference) myEClass.getEStructuralFeature("knows"); // load EObject 1 ChronoEObject eObject1 = tx.getEObjectById(eObject1ID); assertNotNull(eObject1); assertEquals(eObject1ID, eObject1.getId()); // try to navigate to EObject2 and EObject3 List<ChronoEObject> knownEObjects = (List<ChronoEObject>) eObject1.eGet(eReference); assertEquals(2, knownEObjects.size()); ChronoEObject eObject2 = knownEObjects.get(0); ChronoEObject eObject3 = knownEObjects.get(1); // the first eObject should be eObject2 assertEquals(eObject2ID, eObject2.getId()); // ... and it should be an instance of "YourEClass" assertTrue(yourEClass.isInstance(eObject2)); // the second eObject should be eObject3 assertEquals(eObject3ID, eObject3.getId()); // ... and it should be an instance of "YourEClass" assertTrue(yourEClass.isInstance(eObject3)); } } @Test public void canCreateMultiplicityManyNonUniqueOrderedCrossReferences() { ChronoSphere sphere = this.getChronoSphere(); // prepare the EPackage EPackage ePackage = this.createEPackageWithNonUniqueMultiplicityManyOrderedCrossReference(); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); // open a transaction and create some EObject instances based on the EPackage try (ChronoSphereTransaction tx = sphere.tx()) { ePackage = tx.getEPackageByNsURI("http://com.example.model.MyEPackage"); EClass eClass = (EClass) ePackage.getEClassifier("MyClass"); assertNotNull(eClass); EReference eRef = (EReference) eClass.getEStructuralFeature("ref"); assertNotNull(eRef); EAttribute name = (EAttribute) eClass.getEStructuralFeature("Name"); assertNotNull(name); EObject eObj1 = tx.createAndAttach(eClass); eObj1.eSet(name, "EObj1"); EObject eObj2 = tx.createAndAttach(eClass); eObj2.eSet(name, "EObj2"); EObject eObj3 = tx.createAndAttach(eClass); eObj3.eSet(name, "EObj3"); EObject eObj4 = tx.createAndAttach(eClass); eObj4.eSet(name, "EObj4"); EList<EObject> targets = EMFUtils.eGetMany(eObj1, eRef); targets.add(eObj2); targets.add(eObj3); targets.add(eObj3); targets.add(eObj2); targets.add(eObj4); EList<EObject> targets2 = EMFUtils.eGetMany(eObj1, eRef); assertEquals(targets, targets2); assertEquals(eObj2, targets2.get(0)); assertEquals(eObj3, targets2.get(1)); assertEquals(eObj3, targets2.get(2)); assertEquals(eObj2, targets2.get(3)); assertEquals(eObj4, targets2.get(4)); tx.commit(); } // assert that the references are okay via standard Ecore methods try (ChronoSphereTransaction tx = sphere.tx()) { ePackage = tx.getEPackageByNsURI("http://com.example.model.MyEPackage"); EClass eClass = (EClass) ePackage.getEClassifier("MyClass"); assertNotNull(eClass); EReference eRef = (EReference) eClass.getEStructuralFeature("ref"); assertNotNull(eRef); EAttribute name = (EAttribute) eClass.getEStructuralFeature("Name"); assertNotNull(name); Set<EObject> queryResult = tx.find().startingFromAllEObjects().has(name, "EObj1").toSet(); EObject eObj1 = Iterables.getOnlyElement(queryResult); assertNotNull(eObj1); EList<EObject> targets = EMFUtils.eGetMany(eObj1, eRef); assertEquals("EObj2", targets.get(0).eGet(name)); assertEquals("EObj3", targets.get(1).eGet(name)); assertEquals("EObj3", targets.get(2).eGet(name)); assertEquals("EObj2", targets.get(3).eGet(name)); assertEquals("EObj4", targets.get(4).eGet(name)); } // assert that the references are okay via EQuery try (ChronoSphereTransaction tx = sphere.tx()) { ePackage = tx.getEPackageByNsURI("http://com.example.model.MyEPackage"); EClass eClass = (EClass) ePackage.getEClassifier("MyClass"); assertNotNull(eClass); EReference eRef = (EReference) eClass.getEStructuralFeature("ref"); assertNotNull(eRef); EAttribute name = (EAttribute) eClass.getEStructuralFeature("Name"); assertNotNull(name); List<EObject> targets = tx.find().startingFromAllEObjects().has(name, "EObj1").eGet(eRef).toList(); assertEquals("EObj2", targets.get(0).eGet(name)); assertEquals("EObj3", targets.get(1).eGet(name)); assertEquals("EObj3", targets.get(2).eGet(name)); assertEquals("EObj2", targets.get(3).eGet(name)); assertEquals("EObj4", targets.get(4).eGet(name)); } } @Test public void canWorkWithGrabatsFragmentModel() { // the following test uses a fragment of the 'JDTAST.ecore' model (from GRABATS). ChronoSphere sphere = this.getChronoSphere(); // create a model and attach it String packageRootID = null; String frag1ID = null; String frag2ID = null; String frag3ID = null; { // prepare the EPackage EPackage ePackage = this.createEPackageForGrabatsFragmentTest(); sphere.getEPackageManager().registerOrUpdateEPackage(ePackage); EClass ecIPackageFragment = (EClass) ePackage.getEClassifier("IPackageFragment"); assertNotNull(ecIPackageFragment); EClass ecBinaryPackageFragmentRoot = (EClass) ePackage.getEClassifier("BinaryPackageFragmentRoot"); assertNotNull(ecBinaryPackageFragmentRoot); EReference erPackageFragments = (EReference) ecBinaryPackageFragmentRoot .getEStructuralFeature("packageFragments"); assertNotNull(erPackageFragments); EReference erPackageFragmentRoot = (EReference) ecIPackageFragment .getEStructuralFeature("packageFragmentRoot"); assertNotNull(erPackageFragmentRoot); EAttribute eaElementName = (EAttribute) ecBinaryPackageFragmentRoot.getEStructuralFeature("elementName"); assertNotNull(eaElementName); EAttribute eaPath = (EAttribute) ecIPackageFragment.getEStructuralFeature("path"); assertNotNull(eaPath); EAttribute eaIsReadOnly = (EAttribute) ecIPackageFragment.getEStructuralFeature("isReadOnly"); assertNotNull(eaIsReadOnly); EObject packageRoot = EcoreUtil.create(ecBinaryPackageFragmentRoot); packageRootID = ((ChronoEObject) packageRoot).getId(); packageRoot.eSet(eaElementName, "root"); packageRoot.eSet(eaPath, "/"); packageRoot.eSet(eaIsReadOnly, true); EObject frag1 = EcoreUtil.create(ecIPackageFragment); frag1ID = ((ChronoEObject) frag1).getId(); assertEquals(ecIPackageFragment, frag1.eClass()); frag1.eSet(eaElementName, "Frag1"); frag1.eSet(eaIsReadOnly, true); frag1.eSet(eaPath, ".frag1"); EMFUtils.eGetMany(packageRoot, erPackageFragments).add(frag1); // frag1.eSet(erPackageFragmentRoot, packageRoot); EObject frag2 = EcoreUtil.create(ecIPackageFragment); frag2ID = ((ChronoEObject) frag2).getId(); assertEquals(ecIPackageFragment, frag2.eClass()); frag2.eSet(eaElementName, "Frag2"); frag2.eSet(eaIsReadOnly, true); frag2.eSet(eaPath, ".frag2"); frag2.eSet(erPackageFragmentRoot, packageRoot); EObject frag3 = EcoreUtil.create(ecIPackageFragment); frag3ID = ((ChronoEObject) frag3).getId(); assertEquals(ecIPackageFragment, frag3.eClass()); frag3.eSet(eaElementName, "Frag3"); frag3.eSet(eaIsReadOnly, true); frag3.eSet(eaPath, ".frag3"); frag3.eSet(erPackageFragmentRoot, packageRoot); assertEquals(packageRoot, frag1.eGet(erPackageFragmentRoot)); assertEquals(packageRoot, frag1.eContainer()); sphere.batchInsertModelData(packageRoot); } try (ChronoSphereTransaction tx = sphere.tx()) { // extract EPackage data EPackage ePackage = tx.getEPackageByNsURI("http://com.example.model.MyEPackage"); assertNotNull(ePackage); EClass ecIPackageFragment = (EClass) ePackage.getEClassifier("IPackageFragment"); assertNotNull(ecIPackageFragment); EClass ecBinaryPackageFragmentRoot = (EClass) ePackage.getEClassifier("BinaryPackageFragmentRoot"); assertNotNull(ecBinaryPackageFragmentRoot); EReference erPackageFragments = (EReference) ecBinaryPackageFragmentRoot .getEStructuralFeature("packageFragments"); assertNotNull(erPackageFragments); EReference erPackageFragmentRoot = (EReference) ecIPackageFragment .getEStructuralFeature("packageFragmentRoot"); assertNotNull(erPackageFragmentRoot); EAttribute eaElementName = (EAttribute) ecBinaryPackageFragmentRoot.getEStructuralFeature("elementName"); assertNotNull(eaElementName); EAttribute eaPath = (EAttribute) ecIPackageFragment.getEStructuralFeature("path"); assertNotNull(eaPath); EAttribute eaIsReadOnly = (EAttribute) ecIPackageFragment.getEStructuralFeature("isReadOnly"); assertNotNull(eaIsReadOnly); EObject packageRoot = tx.getEObjectById(packageRootID); assertNotNull(packageRoot); EObject frag1 = tx.getEObjectById(frag1ID); assertNotNull(frag1); assertEquals(ecIPackageFragment, frag1.eClass()); EObject frag2 = tx.getEObjectById(frag2ID); assertNotNull(frag2); assertEquals(ecIPackageFragment, frag2.eClass()); EObject frag3 = tx.getEObjectById(frag3ID); assertNotNull(frag3); assertEquals(ecIPackageFragment, frag3.eClass()); assertEquals(packageRoot, frag1.eGet(erPackageFragmentRoot)); assertEquals(packageRoot, frag1.eContainer()); assertEquals(packageRoot, frag2.eContainer()); assertEquals(packageRoot, frag3.eContainer()); assertEquals(3, tx.find().startingFromAllEObjects().named("fragments").eGet("packageFragmentRoot") .back("fragments").count()); } } // ===================================================================================================================== // EPACKAGES // ===================================================================================================================== private EPackage createSimpleEPackage() { EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setName("MyEPackage"); ePackage.setNsURI("http://com.example.model.MyEPackage"); ePackage.setNsPrefix("com.example"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eReference = EcoreFactory.eINSTANCE.createEReference(); eReference.setName("child"); eReference.setEType(eOtherClass); eReference.setLowerBound(0); eReference.setUpperBound(1); eReference.setContainment(true); eClass.getEStructuralFeatures().add(eReference); EAttribute eaName = EcoreFactory.eINSTANCE.createEAttribute(); eaName.setName("name"); eaName.setLowerBound(0); eaName.setUpperBound(1); eaName.setEType(EcorePackage.Literals.ESTRING); eClass.getEStructuralFeatures().add(eaName); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); return ePackage; } private EPackage createEPackageWithNestedEPackages() { EPackage rootEPackage = EcoreFactory.eINSTANCE.createEPackage(); rootEPackage.setName("MyEPackage"); rootEPackage.setNsURI("http://com.example.model.MyEPackage"); rootEPackage.setNsPrefix("com.example"); EPackage sub1 = EcoreFactory.eINSTANCE.createEPackage(); sub1.setName("sub1"); sub1.setNsURI("http://com.example.model.MyEPackage.sub1"); sub1.setNsPrefix("com.example.sub1"); rootEPackage.getESubpackages().add(sub1); EPackage sub2 = EcoreFactory.eINSTANCE.createEPackage(); sub2.setName("sub2"); sub2.setNsURI("http://com.example.model.MyEPackage.sub2"); sub2.setNsPrefix("com.example.sub2"); rootEPackage.getESubpackages().add(sub2); EPackage sub1a = EcoreFactory.eINSTANCE.createEPackage(); sub1a.setName("sub1a"); sub1a.setNsURI("http://com.example.model.MyEPackage.sub1.sub1a"); sub1a.setNsPrefix("com.example.sub1.sub1a"); sub1.getESubpackages().add(sub1a); EPackage sub1b = EcoreFactory.eINSTANCE.createEPackage(); sub1b.setName("sub1b"); sub1b.setNsURI("http://com.example.model.MyEPackage.sub1.sub1b"); sub1b.setNsPrefix("com.example.sub1.sub1b"); sub1.getESubpackages().add(sub1b); EClass eBaseClass = EcoreFactory.eINSTANCE.createEClass(); eBaseClass.setName("BaseClass"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); eClass.getESuperTypes().add(eBaseClass); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); eOtherClass.getESuperTypes().add(eBaseClass); EReference eReference = EcoreFactory.eINSTANCE.createEReference(); eReference.setName("knows"); eReference.setEType(eOtherClass); eReference.setLowerBound(0); eReference.setUpperBound(-1); eReference.setContainment(false); eClass.getEStructuralFeatures().add(eReference); EAttribute eaName = EcoreFactory.eINSTANCE.createEAttribute(); eaName.setName("name"); eaName.setLowerBound(0); eaName.setUpperBound(1); eaName.setEType(EcorePackage.Literals.ESTRING); eBaseClass.getEStructuralFeatures().add(eaName); sub2.getEClassifiers().add(eBaseClass); sub1a.getEClassifiers().add(eClass); sub1b.getEClassifiers().add(eOtherClass); return rootEPackage; } private EPackage createEPackageWithNonUniqueMultiplicityManyOrderedCrossReference() { EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setName("MyEPackage"); ePackage.setNsURI("http://com.example.model.MyEPackage"); ePackage.setNsPrefix("com.example"); { EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyClass"); { { EReference eRef = EcoreFactory.eINSTANCE.createEReference(); eRef.setName("ref"); // multiplicity-many eRef.setLowerBound(0); eRef.setUpperBound(-1); // non-unique eRef.setUnique(false); // ordered eRef.setOrdered(true); // cross-reference eRef.setContainment(false); eRef.setEType(eClass); eClass.getEStructuralFeatures().add(eRef); } { EAttribute eaName = EcoreFactory.eINSTANCE.createEAttribute(); eaName.setName("Name"); eaName.setLowerBound(0); eaName.setUpperBound(1); eaName.setEType(EcorePackage.Literals.ESTRING); eClass.getEStructuralFeatures().add(eaName); } } ePackage.getEClassifiers().add(eClass); } return ePackage; } private EPackage createEPackageForGrabatsFragmentTest() { // the following is a fragment of the 'JDTAST.ecore' model (from GRABATS). EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setName("MyEPackage"); ePackage.setNsURI("http://com.example.model.MyEPackage"); ePackage.setNsPrefix("com.example"); { EClass ecIJavaElement = EcoreFactory.eINSTANCE.createEClass(); ecIJavaElement.setName("IJavaElement"); ecIJavaElement.setAbstract(true); { EAttribute eaElementName = EcoreFactory.eINSTANCE.createEAttribute(); eaElementName.setName("elementName"); eaElementName.setEType(EcorePackage.Literals.ESTRING); eaElementName.setLowerBound(1); eaElementName.setOrdered(false); eaElementName.setUnique(false); ecIJavaElement.getEStructuralFeatures().add(eaElementName); } ePackage.getEClassifiers().add(ecIJavaElement); EClass ecPhysicalElement = EcoreFactory.eINSTANCE.createEClass(); ecPhysicalElement.setName("PhysicalElement"); ecPhysicalElement.setAbstract(true); { EAttribute eaPath = EcoreFactory.eINSTANCE.createEAttribute(); eaPath.setName("path"); eaPath.setEType(EcorePackage.Literals.ESTRING); eaPath.setLowerBound(1); eaPath.setOrdered(false); eaPath.setUnique(false); ecPhysicalElement.getEStructuralFeatures().add(eaPath); EAttribute eaIsReadOnly = EcoreFactory.eINSTANCE.createEAttribute(); eaIsReadOnly.setName("isReadOnly"); eaIsReadOnly.setEType(EcorePackage.Literals.EBOOLEAN); eaIsReadOnly.setOrdered(false); eaIsReadOnly.setUnique(false); eaIsReadOnly.setLowerBound(1); ecPhysicalElement.getEStructuralFeatures().add(eaIsReadOnly); } ePackage.getEClassifiers().add(ecPhysicalElement); EClass ecIPackageFragment = EcoreFactory.eINSTANCE.createEClass(); ecIPackageFragment.setName("IPackageFragment"); ecIPackageFragment.getESuperTypes().add(ecIJavaElement); ecIPackageFragment.getESuperTypes().add(ecPhysicalElement); { EAttribute eaIsDefaultPackage = EcoreFactory.eINSTANCE.createEAttribute(); eaIsDefaultPackage.setName("isDefaultPackage"); eaIsDefaultPackage.setEType(EcorePackage.Literals.EBOOLEAN); eaIsDefaultPackage.setLowerBound(1); eaIsDefaultPackage.setOrdered(false); eaIsDefaultPackage.setUnique(false); ecIPackageFragment.getEStructuralFeatures().add(eaIsDefaultPackage); } ePackage.getEClassifiers().add(ecIPackageFragment); EClass ecIPackageFragmentRoot = EcoreFactory.eINSTANCE.createEClass(); ecIPackageFragmentRoot.setName("IPackageFragmentRoot"); ecIPackageFragmentRoot.setAbstract(true); ecIPackageFragmentRoot.getESuperTypes().add(ecPhysicalElement); ecIPackageFragmentRoot.getESuperTypes().add(ecIJavaElement); { // no additional features } ePackage.getEClassifiers().add(ecIPackageFragmentRoot); // add some bidirectional references EReference erPackageFragments = EcoreFactory.eINSTANCE.createEReference(); erPackageFragments.setName("packageFragments"); erPackageFragments.setEType(ecIPackageFragment); erPackageFragments.setOrdered(false); erPackageFragments.setUpperBound(-1); erPackageFragments.setContainment(true); ecIPackageFragmentRoot.getEStructuralFeatures().add(erPackageFragments); EReference erPackageFragmentRoot = EcoreFactory.eINSTANCE.createEReference(); erPackageFragmentRoot.setName("packageFragmentRoot"); erPackageFragmentRoot.setEType(ecIPackageFragmentRoot); erPackageFragmentRoot.setOrdered(false); erPackageFragmentRoot.setLowerBound(1); ecIPackageFragment.getEStructuralFeatures().add(erPackageFragmentRoot); // these references are opposites of each other erPackageFragmentRoot.setEOpposite(erPackageFragments); erPackageFragments.setEOpposite(erPackageFragmentRoot); EClass ecBinaryPackageFragmentRoot = EcoreFactory.eINSTANCE.createEClass(); ecBinaryPackageFragmentRoot.setName("BinaryPackageFragmentRoot"); ecBinaryPackageFragmentRoot.getESuperTypes().add(ecIPackageFragmentRoot); { // no additional features } ePackage.getEClassifiers().add(ecBinaryPackageFragmentRoot); return ePackage; } } }
30,989
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereBuilderTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/builder/ChronoSphereBuilderTest.java
package org.chronos.chronosphere.test.cases.builder; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.test.base.ChronoSphereUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.junit.Test; import org.junit.experimental.categories.Category; import static org.junit.Assert.*; @Category(UnitTest.class) public class ChronoSphereBuilderTest extends ChronoSphereUnitTest { @Test public void canCreateInMemorySphere() { ChronoSphere sphere = ChronoSphere.FACTORY.create().inMemoryRepository().build(); assertNotNull(sphere); } }
615
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EMFUtilsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/emf/EMFUtilsTest.java
package org.chronos.chronosphere.test.cases.emf; import com.google.common.collect.Iterables; import org.apache.commons.io.IOUtils; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.test.base.ChronoSphereUnitTest; import org.chronos.common.test.junit.categories.UnitTest; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Collection; import static org.junit.Assert.*; @Category(UnitTest.class) public class EMFUtilsTest extends ChronoSphereUnitTest { @Test public void canConvertBetweenEPackageAndXMI() { EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setName("MyEPackage"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute(); eAttribute.setName("MyAttribute"); eAttribute.setEType(EcorePackage.Literals.ESTRING); eAttribute.setLowerBound(0); eAttribute.setUpperBound(1); eClass.getEStructuralFeatures().add(eAttribute); EReference eReference = EcoreFactory.eINSTANCE.createEReference(); eReference.setName("self"); eReference.setEType(eClass); eReference.setUpperBound(-1); eReference.setLowerBound(0); eClass.getEStructuralFeatures().add(eReference); ePackage.getEClassifiers().add(eClass); String xmi = EMFUtils.writeEPackageToXMI(ePackage); assertNotNull(xmi); assertFalse(xmi.trim().isEmpty()); // print it for debugging purposes System.out.println(xmi); // deserialize EPackage ePackage2 = EMFUtils.readEPackageFromXMI(xmi); assertNotNull(ePackage2); assertEquals("MyEPackage", ePackage2.getName()); EClass eClass2 = (EClass) ePackage2.getEClassifier("MyEClass"); assertNotNull(eClass2); assertEquals("MyEClass", eClass2.getName()); EAttribute eAttribute2 = Iterables.getOnlyElement(eClass2.getEAttributes()); assertNotNull(eAttribute2); assertEquals("MyAttribute", eAttribute2.getName()); assertEquals(0, eAttribute2.getLowerBound()); assertEquals(1, eAttribute2.getUpperBound()); assertEquals(EcorePackage.Literals.ESTRING, eAttribute2.getEType()); EReference eReference2 = Iterables.getOnlyElement(eClass2.getEReferences()); assertNotNull(eReference2); assertEquals("self", eReference2.getName()); assertEquals(eClass2, eReference2.getEReferenceType()); assertEquals(0, eReference2.getLowerBound()); assertEquals(-1, eReference2.getUpperBound()); } @Test public void getEPackageByQualifiedName() { Collection<EPackage> ePackages = loadSocialNetworkPackages(); EPackage socialNetworkPackage = EMFUtils.getEPackageByQualifiedName(ePackages, "socialnetwork"); assertNotNull(socialNetworkPackage); assertEquals("socialnetwork", socialNetworkPackage.getName()); EPackage activityPackage = EMFUtils.getEPackageByQualifiedName(ePackages, "socialnetwork::activity"); assertNotNull(activityPackage); assertEquals("activity", activityPackage.getName()); } @Test public void getEClassByQualifiedName() { Collection<EPackage> ePackages = loadSocialNetworkPackages(); EClass ecPerson = EMFUtils.getEClassByQualifiedName(ePackages, "socialnetwork::user::Person"); assertNotNull(ecPerson); assertEquals("Person", ecPerson.getName()); } @Test public void getFeatureByQualifiedName() { Collection<EPackage> ePackages = loadSocialNetworkPackages(); EStructuralFeature eaFirstName = EMFUtils.getFeatureByQualifiedName(ePackages, "socialnetwork::user::Person#firstName"); assertNotNull(eaFirstName); assertEquals("firstName", eaFirstName.getName()); } @Test public void getEAttributeByQualifiedName() { Collection<EPackage> ePackages = loadSocialNetworkPackages(); EAttribute eaFirstName = EMFUtils.getEAttributeByQualifiedName(ePackages, "socialnetwork::user::Person#firstName"); assertNotNull(eaFirstName); assertEquals("firstName", eaFirstName.getName()); } @Test public void getEReferenceByQualifiedName() { Collection<EPackage> ePackages = loadSocialNetworkPackages(); EReference eaFriends = EMFUtils.getEReferenceByQualifiedName(ePackages, "socialnetwork::user::Person#friends"); assertNotNull(eaFriends); assertEquals("friends", eaFriends.getName()); } @Test public void getEPackageBySimpleName() { Collection<EPackage> ePackages = loadSocialNetworkPackages(); EPackage socialNetworkPackage = EMFUtils.getEPackageBySimpleName(ePackages, "socialnetwork"); assertNotNull(socialNetworkPackage); assertEquals("socialnetwork", socialNetworkPackage.getName()); EPackage activityPackage = EMFUtils.getEPackageBySimpleName(ePackages, "activity"); assertNotNull(activityPackage); assertEquals("activity", activityPackage.getName()); } @Test public void getEClassBySimpleName() { Collection<EPackage> ePackages = loadSocialNetworkPackages(); EClass ecPerson = EMFUtils.getEClassBySimpleName(ePackages, "Person"); assertNotNull(ecPerson); assertEquals("Person", ecPerson.getName()); } private static Collection<EPackage> loadSocialNetworkPackages() { try { InputStream inputStream = EMFUtilsTest.class.getClassLoader() .getResourceAsStream("org/chronos/chronosphere/test/metamodels/socialnetwork.ecore"); String xmiContents = IOUtils.toString(inputStream, StandardCharsets.UTF_8); return EMFUtils.readEPackagesFromXMI(xmiContents); } catch (Exception e) { throw new RuntimeException("Failed to load socialnetwork.ecore!", e); } } }
6,417
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
BasicEStoreTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/emf/estore/impl/BasicEStoreTest.java
package org.chronos.chronosphere.test.cases.emf.estore.impl; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.test.cases.emf.estore.base.EStoreTest; 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.EcoreFactory; import org.eclipse.emf.ecore.EcorePackage; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; public class BasicEStoreTest extends EStoreTest { // ================================================================================================================= // CROSS EREFERENCES TESTS (NON-CONTAINMENT) // ================================================================================================================= @Test public void multiplicityOneCrossRefWithoutOppositeRefWorks() { this.createEPackageMultiplicityOneCrossRefNoOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference childRef = (EReference) myClass.getEStructuralFeature("child"); assertNotNull(childRef); EObject eObj1 = this.createEObject(myClass); EObject eObj2 = this.createEObject(yourClass); // set eObj2 as the child of eObj1 eObj1.eSet(childRef, eObj2); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); // unSet the child reference in eObj1 eObj1.eUnset(childRef); assertFalse(eObj1.eIsSet(childRef)); assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); // set eObj2 as the child of eObj1 again eObj1.eSet(childRef, eObj2); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); // this time, clear the child reference in eObj1 by assigning NULL eObj1.eSet(childRef, null); assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); } @Test public void multiplicityOneCrossRefWithMultiplicityOneOppositeRefWorks() { this.createEPackageMultiplicityOneCrossRefWithMultiplicityOneOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference childRef = (EReference) myClass.getEStructuralFeature("child"); assertNotNull(childRef); EReference parentRef = (EReference) yourClass.getEStructuralFeature("parent"); assertNotNull(parentRef); EObject eObj1 = this.createEObject(myClass); EObject eObj2 = this.createEObject(yourClass); // set eObj2 as the child of eObj1 eObj1.eSet(childRef, eObj2); assertTrue(eObj1.eIsSet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); assertTrue(eObj2.eIsSet(parentRef)); assertEquals(eObj1, eObj2.eGet(parentRef)); // unSet the child reference in eObj1 eObj1.eUnset(childRef); assertFalse(eObj1.eIsSet(childRef)); assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); assertFalse(eObj2.eIsSet(parentRef)); assertNull(eObj2.eGet(parentRef)); // set eObj2 as the child of eObj1 again eObj1.eSet(childRef, eObj2); assertTrue(eObj1.eIsSet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); assertTrue(eObj2.eIsSet(parentRef)); assertEquals(eObj1, eObj2.eGet(parentRef)); // this time, clear the child reference in eObj1 by assigning NULL eObj1.eSet(childRef, null); assertFalse(eObj1.eIsSet(childRef)); // according to Ecore reference impl, this has to be false assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); assertFalse(eObj2.eIsSet(parentRef)); assertNull(eObj2.eGet(parentRef)); // set eObj1 as the parent of eObj2 eObj2.eSet(parentRef, eObj1); assertTrue(eObj1.eIsSet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); assertTrue(eObj2.eIsSet(parentRef)); assertEquals(eObj1, eObj2.eGet(parentRef)); } @Test @SuppressWarnings("unchecked") public void multiplicityOneCrossRefWithMultiplicityManyOppositeRefWorks() { this.createEPackageMultiplicityOneCrossRefWithMultiplicityManyOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference childRef = (EReference) myClass.getEStructuralFeature("child"); assertNotNull(childRef); EReference parentRef = (EReference) yourClass.getEStructuralFeature("parents"); assertNotNull(parentRef); EObject parent1 = ePackage.getEFactoryInstance().create(myClass); EObject parent2 = ePackage.getEFactoryInstance().create(myClass); EObject child = ePackage.getEFactoryInstance().create(yourClass); // attach the parents to the child via the "child" references parent1.eSet(childRef, child); parent2.eSet(childRef, child); assertEquals(child, parent1.eGet(childRef)); assertEquals(child, parent2.eGet(childRef)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent1)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent2)); assertTrue(parent1.eIsSet(childRef)); assertTrue(parent2.eIsSet(childRef)); assertTrue(child.eIsSet(parentRef)); assertNull(child.eContainer()); assertNull(child.eContainingFeature()); // remove one of the parents ((List<EObject>) child.eGet(parentRef)).remove(parent1); assertFalse(parent1.eIsSet(childRef)); assertTrue(parent2.eIsSet(childRef)); assertEquals(null, parent1.eGet(childRef)); assertEquals(child, parent2.eGet(childRef)); assertFalse(((List<EObject>) child.eGet(parentRef)).contains(parent1)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent2)); assertNull(child.eContainer()); assertNull(child.eContainingFeature()); // add the parent again by adding it to the "parents" reference ((List<EObject>) child.eGet(parentRef)).add(parent1); assertTrue(parent1.eIsSet(childRef)); assertTrue(parent2.eIsSet(childRef)); assertEquals(child, parent1.eGet(childRef)); assertEquals(child, parent2.eGet(childRef)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent1)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent2)); assertNull(child.eContainer()); assertNull(child.eContainingFeature()); // remove the second parent by setting its child to null parent2.eSet(childRef, null); assertTrue(parent1.eIsSet(childRef)); assertFalse(parent2.eIsSet(childRef)); assertEquals(child, parent1.eGet(childRef)); assertEquals(null, parent2.eGet(childRef)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent1)); assertFalse(((List<EObject>) child.eGet(parentRef)).contains(parent2)); assertNull(child.eContainer()); assertNull(child.eContainingFeature()); // remove the first parent by unsetting its child reference parent1.eUnset(childRef); assertFalse(parent1.eIsSet(childRef)); assertFalse(parent2.eIsSet(childRef)); assertEquals(null, parent1.eGet(childRef)); assertEquals(null, parent2.eGet(childRef)); assertFalse(((List<EObject>) child.eGet(parentRef)).contains(parent1)); assertFalse(((List<EObject>) child.eGet(parentRef)).contains(parent2)); assertNull(child.eContainer()); assertNull(child.eContainingFeature()); // add the parents again parent1.eSet(childRef, child); parent2.eSet(childRef, child); assertEquals(child, parent1.eGet(childRef)); assertEquals(child, parent2.eGet(childRef)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent1)); assertTrue(((List<EObject>) child.eGet(parentRef)).contains(parent2)); assertTrue(parent1.eIsSet(childRef)); assertTrue(parent2.eIsSet(childRef)); assertTrue(child.eIsSet(parentRef)); assertNull(child.eContainer()); assertNull(child.eContainingFeature()); // remove the parents by clearing the "parents" reference child.eUnset(parentRef); assertFalse(parent1.eIsSet(childRef)); assertFalse(parent2.eIsSet(childRef)); assertEquals(null, parent1.eGet(childRef)); assertEquals(null, parent2.eGet(childRef)); assertFalse(((List<EObject>) child.eGet(parentRef)).contains(parent1)); assertFalse(((List<EObject>) child.eGet(parentRef)).contains(parent2)); assertNull(child.eContainer()); assertNull(child.eContainingFeature()); } @Test @SuppressWarnings("unchecked") public void multiplicityManyCrossRefWithoutOppositeRefWorks() { this.createEPackageMultiplicityManyCrossRefNoOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference childRef = (EReference) myClass.getEStructuralFeature("children"); assertNotNull(childRef); EObject parent = this.createEObject(myClass); EObject child1 = this.createEObject(yourClass); EObject child2 = this.createEObject(yourClass); // add the children to the parent ((List<EObject>) parent.eGet(childRef)).add(child1); ((List<EObject>) parent.eGet(childRef)).add(child2); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // remove child1 ((List<EObject>) parent.eGet(childRef)).remove(child1); assertTrue(parent.eIsSet(childRef)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // re-add child1 ((List<EObject>) parent.eGet(childRef)).add(child1); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // clear the children reference ((List<EObject>) parent.eGet(childRef)).clear(); assertFalse(parent.eIsSet(childRef)); // according to standard Ecore implementation assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // add the children to the parent ((List<EObject>) parent.eGet(childRef)).add(child1); ((List<EObject>) parent.eGet(childRef)).add(child2); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // unset the children reference parent.eUnset(childRef); assertFalse(parent.eIsSet(childRef)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // add the children to the parent ((List<EObject>) parent.eGet(childRef)).add(child1); ((List<EObject>) parent.eGet(childRef)).add(child2); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // remove the children one by one ((List<EObject>) parent.eGet(childRef)).remove(child1); ((List<EObject>) parent.eGet(childRef)).remove(child2); assertFalse(parent.eIsSet(childRef)); // according to Ecore implementation assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); } @Test @SuppressWarnings("unchecked") public void multiplicityManyCrossRefWithMultiplicityOneOppositeRefWorks() { this.createEPackageMultiplicityManyCrossRefWithMultiplicityOneOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference childRef = (EReference) myClass.getEStructuralFeature("children"); assertNotNull(childRef); EReference parentRef = (EReference) yourClass.getEStructuralFeature("parent"); assertNotNull(parentRef); EObject parent = this.createEObject(myClass); EObject child1 = this.createEObject(yourClass); EObject child2 = this.createEObject(yourClass); // add the children to the parent by adding them to the "children" reference ((List<EObject>) parent.eGet(childRef)).add(child1); ((List<EObject>) parent.eGet(childRef)).add(child2); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertTrue(child1.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertTrue(child2.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // remove child1 by removing it from the children list ((List<EObject>) parent.eGet(childRef)).remove(child1); assertTrue(parent.eIsSet(childRef)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertFalse(child1.eIsSet(parentRef)); assertEquals(null, child1.eGet(parentRef)); assertTrue(child2.eIsSet(parentRef)); assertEquals(parent, child2.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // re-add child1 by setting the parent reference child1.eSet(parentRef, parent); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertTrue(child1.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertTrue(child2.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // clear the children reference ((List<EObject>) parent.eGet(childRef)).clear(); assertFalse(parent.eIsSet(childRef)); // according to standard Ecore implementation assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertFalse(child1.eIsSet(parentRef)); assertNull(child1.eGet(parentRef)); assertFalse(child2.eIsSet(parentRef)); assertNull(child1.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // add the children to the parent ((List<EObject>) parent.eGet(childRef)).add(child1); ((List<EObject>) parent.eGet(childRef)).add(child2); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertTrue(child1.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertTrue(child2.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // unset the parent reference in child2 child2.eUnset(parentRef); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertTrue(child1.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertFalse(child2.eIsSet(parentRef)); assertEquals(null, child2.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // add child2 to the parent by adding it to the children reference ((List<EObject>) parent.eGet(childRef)).add(child2); assertTrue(parent.eIsSet(childRef)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertTrue(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertTrue(child1.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertTrue(child2.eIsSet(parentRef)); assertEquals(parent, child1.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); // unset the children reference parent.eUnset(childRef); assertFalse(parent.eIsSet(childRef)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child1)); assertFalse(((List<EObject>) parent.eGet(childRef)).contains(child2)); assertFalse(child1.eIsSet(parentRef)); assertNull(child1.eGet(parentRef)); assertFalse(child2.eIsSet(parentRef)); assertNull(child2.eGet(parentRef)); assertNull(child1.eContainer()); assertNull(child1.eContainingFeature()); assertNull(child2.eContainer()); assertNull(child2.eContainingFeature()); } @Test public void symmetricMultiplicityManyCrossRefWorks() { this.createEPackageSymmetricMultiplicityManyCrosssRef(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); assertNotNull(ePackage); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); assertNotNull(myClass); EReference eRef = (EReference) myClass.getEStructuralFeature("ref"); assertNotNull(eRef); EObject eObj1 = this.createEObject(myClass); EObject eObj2 = this.createEObject(myClass); EObject eObj3 = this.createEObject(myClass); List<EObject> targets = EMFUtils.eGetMany(eObj1, eRef); targets.add(eObj2); targets.add(eObj3); // since "ref" is symmetric, eobj1-[ref]->eobj2 implies that eobj2-[ref]->eobj1 assertTrue(EMFUtils.eGetMany(eObj2, eRef).contains(eObj1)); // since "ref" is symmetric, eobj1-[ref]->eobj3 implies that eobj3-[ref]->eobj1 assertTrue(EMFUtils.eGetMany(eObj3, eRef).contains(eObj1)); // since "ref" is not transitive, eobj3 and eobj2 should not know each other assertFalse(EMFUtils.eGetMany(eObj2, eRef).contains(eObj3)); assertFalse(EMFUtils.eGetMany(eObj3, eRef).contains(eObj2)); } // ================================================================================================================= // CONTAINMENT EREFERENCE TESTS // ================================================================================================================= @Test public void multiplicityOneContainmentWithoutOppositeRefWorks() { this.createEPackageMultiplicityOneContainmentNoOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference childRef = (EReference) myClass.getEStructuralFeature("child"); assertNotNull(childRef); EObject eObj1 = this.createEObject(myClass); EObject eObj2 = this.createEObject(yourClass); // set eObj2 as the child of eObj1 eObj1.eSet(childRef, eObj2); assertEquals(eObj1, eObj2.eContainer()); assertEquals(childRef, eObj2.eContainingFeature()); // unSet the child reference in eObj1 eObj1.eUnset(childRef); assertFalse(eObj1.eIsSet(childRef)); assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); // set eObj2 as the child of eObj1 again eObj1.eSet(childRef, eObj2); assertEquals(eObj1, eObj2.eContainer()); assertEquals(childRef, eObj2.eContainingFeature()); // this time, clear the child reference in eObj1 by assigning NULL eObj1.eSet(childRef, null); assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); } @Test public void multiplicityOneContainmentWithOppositeRefWorks() { this.createEPackageMultiplicityOneContainmentWithOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference childRef = (EReference) myClass.getEStructuralFeature("child"); assertNotNull(childRef); EReference parentRef = (EReference) yourClass.getEStructuralFeature("parent"); assertNotNull(parentRef); EObject eObj1 = this.createEObject(myClass); EObject eObj2 = this.createEObject(yourClass); // set eObj2 as the child of eObj1 eObj1.eSet(childRef, eObj2); assertTrue(eObj1.eIsSet(childRef)); assertEquals(eObj1, eObj2.eContainer()); assertEquals(childRef, eObj2.eContainingFeature()); assertTrue(eObj2.eIsSet(parentRef)); assertEquals(eObj1, eObj2.eGet(parentRef)); // unSet the child reference in eObj1 eObj1.eUnset(childRef); assertFalse(eObj1.eIsSet(childRef)); assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); assertNull(eObj2.eGet(parentRef)); // set eObj2 as the child of eObj1 again eObj1.eSet(childRef, eObj2); assertTrue(eObj1.eIsSet(childRef)); assertEquals(eObj1, eObj2.eContainer()); assertEquals(childRef, eObj2.eContainingFeature()); assertTrue(eObj2.eIsSet(parentRef)); assertEquals(eObj1, eObj2.eGet(parentRef)); // this time, clear the child reference in eObj1 by assigning NULL eObj1.eSet(childRef, null); assertFalse(eObj1.eIsSet(childRef)); // according to Ecore reference impl, this has to be false assertNull(eObj1.eGet(childRef)); assertNull(eObj2.eContainer()); assertNull(eObj2.eContainingFeature()); assertFalse(eObj2.eIsSet(parentRef)); assertNull(eObj2.eGet(parentRef)); // set eObj1 as the parent of eObj2 eObj2.eSet(parentRef, eObj1); assertTrue(eObj1.eIsSet(childRef)); assertEquals(eObj1, eObj2.eContainer()); assertEquals(childRef, eObj2.eContainingFeature()); assertTrue(eObj2.eIsSet(parentRef)); assertEquals(eObj1, eObj2.eGet(parentRef)); } @Test @SuppressWarnings("unchecked") public void multiplicityManyContainmentWithoutOppositeRefWorks() { this.createEPackageMultiplicityManyContainmentNoOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EAttribute myAttribute = (EAttribute) myClass.getEStructuralFeature("MyAttribute"); EReference myReference = (EReference) myClass.getEStructuralFeature("children"); EObject eObj1 = this.createEObject(myClass); EObject eObj2 = this.createEObject(yourClass); // assign a property to eObj1 assertNull(eObj1.eGet(myAttribute)); eObj1.eSet(myAttribute, "Hello World!"); assertEquals("Hello World!", eObj1.eGet(myAttribute)); // assign a reference target to eObj1 ((List<EObject>) eObj1.eGet(myReference)).add(eObj2); // get the EContainer of eObj2 assertEquals(eObj1, eObj2.eContainer()); // get the eContainingFeature of eObj2 assertEquals(myReference, eObj2.eContainingFeature()); // assert that our children reference was updated assertTrue(((List<EObject>) eObj1.eGet(myReference)).contains(eObj2)); // clear the list in eObj1#children ((List<EObject>) eObj1.eGet(myReference)).clear(); // get the EContainer of eObj2 assertNull(eObj2.eContainer()); } @Test @SuppressWarnings("unchecked") public void multiplicityManyContainmentWithMultiplicityOneOppositeRefWorks() { this.createEPackageMultiplicityManyContainmentWithMultiplicityOneOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass myClass = (EClass) ePackage.getEClassifier("MyEClass"); EClass yourClass = (EClass) ePackage.getEClassifier("YourEClass"); assertNotNull(myClass); assertNotNull(yourClass); EReference eRefChildren = (EReference) myClass.getEStructuralFeature("children"); EReference eRefParent = (EReference) yourClass.getEStructuralFeature("parent"); assertNotNull(eRefChildren); assertNotNull(eRefParent); assertEquals(eRefParent, eRefChildren.getEOpposite()); assertEquals(eRefChildren, eRefParent.getEOpposite()); assertTrue(eRefChildren.isContainment()); assertTrue(eRefParent.isContainer()); EObject container = this.createEObject(myClass); EObject child1 = this.createEObject(yourClass); EObject child2 = this.createEObject(yourClass); // add a child to the container by adding it to the children reference ((List<EObject>) container.eGet(eRefChildren)).add(child1); // add a child to the container by setting the container as parent in the child child2.eSet(eRefParent, container); // make sure that both children are referencing the container as parent assertEquals(container, child1.eContainer()); assertEquals(container, child2.eContainer()); assertTrue(child1.eIsSet(eRefParent)); assertTrue(child2.eIsSet(eRefParent)); assertEquals(container, child1.eGet(eRefParent)); assertEquals(container, child2.eGet(eRefParent)); assertEquals(eRefChildren, child1.eContainingFeature()); assertEquals(eRefChildren, child2.eContainingFeature()); // remove the first child from the container by unsetting the parent reference child1.eUnset(eRefParent); // make sure that it's no longer part of the container assertNull(child1.eContainer()); assertFalse(((List<EObject>) container.eGet(eRefChildren)).contains(child1)); // remove the second child from the container by removing it from the children list ((List<EObject>) container.eGet(eRefChildren)).remove(child2); // assert that its parent reference has been unset assertNull(child2.eGet(eRefParent)); assertFalse(child2.eIsSet(eRefParent)); } @Test public void inheritedMultiplicityManyContainmentWithNonInheritedMultiplicityOneOppositeWorks() { this.createEPackageInheritedMultiplicityManyContainmentWithNonInheritedMultiplicityOneOpposite(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); EClass ecContainer = (EClass) ePackage.getEClassifier("Container"); assertNotNull(ecContainer); EClass ecElement = (EClass) ePackage.getEClassifier("Element"); assertNotNull(ecElement); EReference erElements = (EReference) ecContainer.getEStructuralFeature("elements"); EReference erContainer = (EReference) ecElement.getEStructuralFeature("container"); assertNotNull(erElements); assertNotNull(erContainer); assertEquals(erContainer, erElements.getEOpposite()); assertEquals(erElements, erContainer.getEOpposite()); assertTrue(erElements.isContainment()); assertTrue(erContainer.isContainer()); EObject container = this.createEObject(ecContainer); EObject child1 = this.createEObject(ecElement); EObject child2 = this.createEObject(ecElement); // add a child to the container by adding it to the children reference EMFUtils.eGetMany(container, erElements).add(child1); // add a child to the container by setting the container as parent in the child child2.eSet(erContainer, container); // make sure that both children are referencing the container as parent assertEquals(container, child1.eContainer()); assertEquals(container, child2.eContainer()); assertTrue(child1.eIsSet(erContainer)); assertTrue(child2.eIsSet(erContainer)); assertEquals(container, child1.eGet(erContainer)); assertEquals(container, child2.eGet(erContainer)); assertEquals(erElements, child1.eContainingFeature()); assertEquals(erElements, child2.eContainingFeature()); // remove the first child from the container by unsetting the parent reference child1.eUnset(erContainer); // make sure that it's no longer part of the container assertNull(child1.eContainer()); assertFalse(EMFUtils.eGetMany(container, erElements).contains(child1)); // remove the second child from the container by removing it from the children list EMFUtils.eGetMany(container, erElements).remove(child2); // assert that its parent reference has been unset assertNull(child2.eGet(erContainer)); assertFalse(child2.eIsSet(erContainer)); } // ===================================================================================================================== // GRABATS TESTS // ===================================================================================================================== @Test public void grabatsFragmantModelWorks() { // the following test uses a fragment of the 'JDTAST.ecore' model (from GRABATS). this.createGrabatsFragmentsEPackage(); EPackage ePackage = this.getEPackageByNsURI("http://www.example.com/model"); // open a transaction and create some EObject instances based on the EPackage EClass ecIPackageFragment = (EClass) ePackage.getEClassifier("IPackageFragment"); assertNotNull(ecIPackageFragment); EClass ecBinaryPackageFragmentRoot = (EClass) ePackage.getEClassifier("BinaryPackageFragmentRoot"); assertNotNull(ecBinaryPackageFragmentRoot); EReference erPackageFragments = (EReference) ecBinaryPackageFragmentRoot .getEStructuralFeature("packageFragments"); assertNotNull(erPackageFragments); EReference erPackageFragmentRoot = (EReference) ecIPackageFragment.getEStructuralFeature("packageFragmentRoot"); assertNotNull(erPackageFragmentRoot); EAttribute eaElementName = (EAttribute) ecBinaryPackageFragmentRoot.getEStructuralFeature("elementName"); assertNotNull(eaElementName); EAttribute eaPath = (EAttribute) ecIPackageFragment.getEStructuralFeature("path"); assertNotNull(eaPath); EAttribute eaIsReadOnly = (EAttribute) ecIPackageFragment.getEStructuralFeature("isReadOnly"); assertNotNull(eaIsReadOnly); // create a model and attach it EObject packageRoot = this.createEObject(ecBinaryPackageFragmentRoot); packageRoot.eSet(eaElementName, "root"); packageRoot.eSet(eaPath, "/"); packageRoot.eSet(eaIsReadOnly, true); EObject frag1 = this.createEObject(ecIPackageFragment); frag1.eSet(eaElementName, "Frag1"); frag1.eSet(eaIsReadOnly, true); frag1.eSet(eaPath, ".frag1"); EMFUtils.eGetMany(packageRoot, erPackageFragments).add(frag1); assertEquals(packageRoot, frag1.eGet(erPackageFragmentRoot)); } // ===================================================================================================================== // EPACKAGES // ===================================================================================================================== private void createEPackageMultiplicityOneCrossRefNoOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eReference = EcoreFactory.eINSTANCE.createEReference(); eReference.setName("child"); eReference.setEType(eOtherClass); eReference.setLowerBound(0); eReference.setUpperBound(1); eReference.setContainment(false); eClass.getEStructuralFeatures().add(eReference); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageMultiplicityOneCrossRefWithMultiplicityOneOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eRefChild = EcoreFactory.eINSTANCE.createEReference(); eRefChild.setName("child"); eRefChild.setEType(eOtherClass); eRefChild.setLowerBound(0); eRefChild.setUpperBound(1); eRefChild.setContainment(false); EReference eRefParent = EcoreFactory.eINSTANCE.createEReference(); eRefParent.setName("parent"); eRefParent.setLowerBound(0); eRefParent.setUpperBound(1); eRefParent.setEType(eClass); eRefParent.setEOpposite(eRefChild); eRefChild.setEOpposite(eRefParent); eClass.getEStructuralFeatures().add(eRefChild); eOtherClass.getEStructuralFeatures().add(eRefParent); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageMultiplicityOneCrossRefWithMultiplicityManyOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eRefChild = EcoreFactory.eINSTANCE.createEReference(); eRefChild.setName("child"); eRefChild.setEType(eOtherClass); eRefChild.setLowerBound(0); eRefChild.setUpperBound(1); eRefChild.setContainment(false); EReference eRefParent = EcoreFactory.eINSTANCE.createEReference(); eRefParent.setName("parents"); eRefParent.setLowerBound(0); eRefParent.setUpperBound(-1); eRefParent.setEType(eClass); eRefParent.setEOpposite(eRefChild); eRefChild.setEOpposite(eRefParent); eClass.getEStructuralFeatures().add(eRefChild); eOtherClass.getEStructuralFeatures().add(eRefParent); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageMultiplicityManyCrossRefNoOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eReference = EcoreFactory.eINSTANCE.createEReference(); eReference.setName("children"); eReference.setEType(eOtherClass); eReference.setLowerBound(0); eReference.setUpperBound(-1); eReference.setContainment(false); eClass.getEStructuralFeatures().add(eReference); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageMultiplicityManyCrossRefWithMultiplicityOneOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eRefChildren = EcoreFactory.eINSTANCE.createEReference(); eRefChildren.setName("children"); eRefChildren.setEType(eOtherClass); eRefChildren.setLowerBound(0); eRefChildren.setUpperBound(-1); eRefChildren.setContainment(false); eClass.getEStructuralFeatures().add(eRefChildren); EReference eRefParent = EcoreFactory.eINSTANCE.createEReference(); eRefParent.setName("parent"); eRefParent.setLowerBound(0); eRefParent.setUpperBound(1); eRefParent.setEType(eClass); eRefParent.setEOpposite(eRefChildren); eRefChildren.setEOpposite(eRefParent); eOtherClass.getEStructuralFeatures().add(eRefParent); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageSymmetricMultiplicityManyCrosssRef() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); { EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); { EReference eRef = EcoreFactory.eINSTANCE.createEReference(); eRef.setName("ref"); eRef.setEType(eClass); eRef.setLowerBound(0); eRef.setUpperBound(-1); eRef.setEOpposite(eRef); eRef.setContainment(false); eRef.setOrdered(true); eRef.setUnique(true); eClass.getEStructuralFeatures().add(eRef); } ePackage.getEClassifiers().add(eClass); } this.registerEPackages(ePackage); } private void createEPackageMultiplicityOneContainmentNoOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eReference = EcoreFactory.eINSTANCE.createEReference(); eReference.setName("child"); eReference.setEType(eOtherClass); eReference.setLowerBound(0); eReference.setUpperBound(1); eReference.setContainment(true); eClass.getEStructuralFeatures().add(eReference); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageMultiplicityOneContainmentWithOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eRefChild = EcoreFactory.eINSTANCE.createEReference(); eRefChild.setName("child"); eRefChild.setEType(eOtherClass); eRefChild.setLowerBound(0); eRefChild.setUpperBound(1); eRefChild.setContainment(true); EReference eRefParent = EcoreFactory.eINSTANCE.createEReference(); eRefParent.setName("parent"); eRefParent.setLowerBound(0); eRefParent.setUpperBound(1); eRefParent.setEType(eClass); eRefParent.setEOpposite(eRefChild); eRefChild.setEOpposite(eRefParent); eClass.getEStructuralFeatures().add(eRefChild); eOtherClass.getEStructuralFeatures().add(eRefParent); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageMultiplicityManyContainmentNoOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EAttribute eAttribute = EcoreFactory.eINSTANCE.createEAttribute(); eAttribute.setName("MyAttribute"); eAttribute.setEType(EcorePackage.Literals.ESTRING); eAttribute.setLowerBound(0); eAttribute.setUpperBound(1); eClass.getEStructuralFeatures().add(eAttribute); EReference eReference = EcoreFactory.eINSTANCE.createEReference(); eReference.setName("children"); eReference.setEType(eOtherClass); eReference.setLowerBound(0); eReference.setUpperBound(-1); eReference.setContainment(true); eClass.getEStructuralFeatures().add(eReference); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageMultiplicityManyContainmentWithMultiplicityOneOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); ePackage.setName("MyPackage"); EClass eClass = EcoreFactory.eINSTANCE.createEClass(); eClass.setName("MyEClass"); EClass eOtherClass = EcoreFactory.eINSTANCE.createEClass(); eOtherClass.setName("YourEClass"); EReference eRefChildren = EcoreFactory.eINSTANCE.createEReference(); eRefChildren.setName("children"); eRefChildren.setEType(eOtherClass); eRefChildren.setLowerBound(0); eRefChildren.setUpperBound(-1); eRefChildren.setContainment(true); eClass.getEStructuralFeatures().add(eRefChildren); EReference eRefParent = EcoreFactory.eINSTANCE.createEReference(); eRefParent.setName("parent"); eRefParent.setLowerBound(0); eRefParent.setUpperBound(1); eRefParent.setEType(eClass); eRefParent.setEOpposite(eRefChildren); eRefChildren.setEOpposite(eRefParent); eOtherClass.getEStructuralFeatures().add(eRefParent); ePackage.getEClassifiers().add(eClass); ePackage.getEClassifiers().add(eOtherClass); this.registerEPackages(ePackage); } private void createEPackageInheritedMultiplicityManyContainmentWithNonInheritedMultiplicityOneOpposite() { EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); ePackage.setName("MyPackage"); EClass ecIContainer = EcoreFactory.eINSTANCE.createEClass(); ecIContainer.setName("IContainer"); EClass ecContainer = EcoreFactory.eINSTANCE.createEClass(); ecContainer.setName("Container"); ecContainer.getESuperTypes().add(ecIContainer); EClass ecIElement = EcoreFactory.eINSTANCE.createEClass(); ecIElement.setName("IElement"); EClass ecElement = EcoreFactory.eINSTANCE.createEClass(); ecElement.setName("Element"); ecElement.getESuperTypes().add(ecIElement); EReference erElements = EcoreFactory.eINSTANCE.createEReference(); erElements.setName("elements"); erElements.setEType(ecIElement); erElements.setLowerBound(0); erElements.setUpperBound(-1); erElements.setContainment(true); ecIContainer.getEStructuralFeatures().add(erElements); EAttribute eaA = EcoreFactory.eINSTANCE.createEAttribute(); eaA.setName("a"); eaA.setEType(EcorePackage.Literals.ESTRING); eaA.setLowerBound(0); eaA.setUpperBound(1); ecIContainer.getEStructuralFeatures().add(eaA); EAttribute eaB = EcoreFactory.eINSTANCE.createEAttribute(); eaB.setName("b"); eaB.setEType(EcorePackage.Literals.ESTRING); eaB.setLowerBound(0); eaB.setUpperBound(1); ecIContainer.getEStructuralFeatures().add(eaB); EReference erContainer = EcoreFactory.eINSTANCE.createEReference(); erContainer.setName("container"); erContainer.setLowerBound(0); erContainer.setUpperBound(1); erContainer.setEType(ecIContainer); erContainer.setEOpposite(erElements); erElements.setEOpposite(erContainer); ecIElement.getEStructuralFeatures().add(erContainer); ePackage.getEClassifiers().add(ecIContainer); ePackage.getEClassifiers().add(ecContainer); ePackage.getEClassifiers().add(ecIElement); ePackage.getEClassifiers().add(ecElement); this.registerEPackages(ePackage); } private void createGrabatsFragmentsEPackage() { // the following is a fragment of the 'JDTAST.ecore' model (from GRABATS). EPackage ePackage = this.createNewEPackage("MyEPackage", "http://www.example.com/model", "model"); { EClass ecIJavaElement = EcoreFactory.eINSTANCE.createEClass(); ecIJavaElement.setName("IJavaElement"); ecIJavaElement.setAbstract(true); { EAttribute eaElementName = EcoreFactory.eINSTANCE.createEAttribute(); eaElementName.setName("elementName"); eaElementName.setEType(EcorePackage.Literals.ESTRING); eaElementName.setLowerBound(1); eaElementName.setOrdered(false); eaElementName.setUnique(false); ecIJavaElement.getEStructuralFeatures().add(eaElementName); } ePackage.getEClassifiers().add(ecIJavaElement); EClass ecPhysicalElement = EcoreFactory.eINSTANCE.createEClass(); ecPhysicalElement.setName("PhysicalElement"); ecPhysicalElement.setAbstract(true); { EAttribute eaPath = EcoreFactory.eINSTANCE.createEAttribute(); eaPath.setName("path"); eaPath.setEType(EcorePackage.Literals.ESTRING); eaPath.setLowerBound(1); eaPath.setOrdered(false); eaPath.setUnique(false); ecPhysicalElement.getEStructuralFeatures().add(eaPath); EAttribute eaIsReadOnly = EcoreFactory.eINSTANCE.createEAttribute(); eaIsReadOnly.setName("isReadOnly"); eaIsReadOnly.setEType(EcorePackage.Literals.EBOOLEAN); eaIsReadOnly.setOrdered(false); eaIsReadOnly.setUnique(false); eaIsReadOnly.setLowerBound(1); ecPhysicalElement.getEStructuralFeatures().add(eaIsReadOnly); } ePackage.getEClassifiers().add(ecPhysicalElement); EClass ecIPackageFragment = EcoreFactory.eINSTANCE.createEClass(); ecIPackageFragment.setName("IPackageFragment"); ecIPackageFragment.getESuperTypes().add(ecIJavaElement); ecIPackageFragment.getESuperTypes().add(ecPhysicalElement); { EAttribute eaIsDefaultPackage = EcoreFactory.eINSTANCE.createEAttribute(); eaIsDefaultPackage.setName("isDefaultPackage"); eaIsDefaultPackage.setEType(EcorePackage.Literals.EBOOLEAN); eaIsDefaultPackage.setLowerBound(1); eaIsDefaultPackage.setOrdered(false); eaIsDefaultPackage.setUnique(false); ecIPackageFragment.getEStructuralFeatures().add(eaIsDefaultPackage); } ePackage.getEClassifiers().add(ecIPackageFragment); EClass ecIPackageFragmentRoot = EcoreFactory.eINSTANCE.createEClass(); ecIPackageFragmentRoot.setName("IPackageFragmentRoot"); ecIPackageFragmentRoot.setAbstract(true); ecIPackageFragmentRoot.getESuperTypes().add(ecPhysicalElement); ecIPackageFragmentRoot.getESuperTypes().add(ecIJavaElement); { // no additional features } ePackage.getEClassifiers().add(ecIPackageFragmentRoot); // add some bidirectional references EReference erPackageFragments = EcoreFactory.eINSTANCE.createEReference(); erPackageFragments.setName("packageFragments"); erPackageFragments.setEType(ecIPackageFragment); erPackageFragments.setOrdered(false); erPackageFragments.setUpperBound(-1); erPackageFragments.setContainment(true); ecIPackageFragmentRoot.getEStructuralFeatures().add(erPackageFragments); EReference erPackageFragmentRoot = EcoreFactory.eINSTANCE.createEReference(); erPackageFragmentRoot.setName("packageFragmentRoot"); erPackageFragmentRoot.setEType(ecIPackageFragmentRoot); erPackageFragmentRoot.setOrdered(false); erPackageFragmentRoot.setLowerBound(1); ecIPackageFragment.getEStructuralFeatures().add(erPackageFragmentRoot); // these references are opposites of each other erPackageFragmentRoot.setEOpposite(erPackageFragments); erPackageFragments.setEOpposite(erPackageFragmentRoot); EClass ecBinaryPackageFragmentRoot = EcoreFactory.eINSTANCE.createEClass(); ecBinaryPackageFragmentRoot.setName("BinaryPackageFragmentRoot"); ecBinaryPackageFragmentRoot.getESuperTypes().add(ecIPackageFragmentRoot); { // no additional features } ePackage.getEClassifiers().add(ecBinaryPackageFragmentRoot); } this.registerEPackages(ePackage); } }
54,678
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EmfAPI.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/emf/estore/base/EmfAPI.java
package org.chronos.chronosphere.test.cases.emf.estore.base; public enum EmfAPI { REFERENCE_IMPLEMENTATION, CHRONOS_TRANSIENT, CHRONOS_GRAPH; public boolean requiresChronoSphere() { if (CHRONOS_GRAPH.equals(this)) { return true; } else { return false; } } }
322
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EStoreTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/cases/emf/estore/base/EStoreTest.java
package org.chronos.chronosphere.test.cases.emf.estore.base; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.emf.impl.ChronoEFactory; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.test.utils.factories.EMFEFactory; import org.chronos.common.exceptions.UnknownEnumLiteralException; import org.chronos.common.test.junit.categories.IntegrationTest; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EFactory; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.util.EcoreUtil; import org.junit.After; import org.junit.Before; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.Map; import static com.google.common.base.Preconditions.*; import static org.junit.Assert.*; @RunWith(Parameterized.class) @Category(IntegrationTest.class) public abstract class EStoreTest { // ===================================================================================================================== // JUNIT PARAMETERS // ===================================================================================================================== @Parameters(name = "Using {0}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ // option 1 {"EMF Reference", EmfAPI.REFERENCE_IMPLEMENTATION}, // option 2 {"Chronos-Transient", EmfAPI.CHRONOS_TRANSIENT}, // option 3 {"Chronos-Graph", EmfAPI.CHRONOS_GRAPH} // end options }); } // ===================================================================================================================== // JUNIT PARAMETER FIELDS // ===================================================================================================================== @Parameter(0) public String name; @Parameter(1) public EmfAPI emfAPI; // ===================================================================================================================== // INTERNAL FIELDS // ===================================================================================================================== private ChronoSphere chronoSphereInstance = null; private ChronoSphereTransaction chronoSphereTransaction = null; private final Map<String, EPackage> registeredEPackages = Maps.newHashMap(); // ===================================================================================================================== // SETUP & TEAR DOWN // ===================================================================================================================== @Before public void setup() { this.registeredEPackages.clear(); if (this.emfAPI.requiresChronoSphere()) { this.chronoSphereInstance = ChronoSphere.FACTORY.create().inMemoryRepository().build(); } } @After public void tearDown() { if (this.chronoSphereTransaction != null) { this.chronoSphereTransaction.close(); } if (this.chronoSphereInstance != null) { this.chronoSphereInstance.close(); this.chronoSphereInstance = null; } this.registeredEPackages.clear(); } // ===================================================================================================================== // METHODS FOR SUBCLASSES // ===================================================================================================================== protected EFactory createNewEFactory() { switch (this.emfAPI) { case REFERENCE_IMPLEMENTATION: return new EMFEFactory(); case CHRONOS_TRANSIENT: return new ChronoEFactory(); case CHRONOS_GRAPH: return new ChronoEFactory(); default: throw new UnknownEnumLiteralException(this.emfAPI); } } protected EPackage createNewEPackage(final String name, final String nsURI, final String nsPrefix) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); checkNotNull(nsURI, "Precondition violation - argument 'nsURI' must not be NULL!"); checkNotNull(nsPrefix, "Precondition violation - argument 'nsPrefix' must not be NULL!"); EPackage ePackage = EcoreFactory.eINSTANCE.createEPackage(); ePackage.setEFactoryInstance(this.createNewEFactory()); ePackage.setName(name); ePackage.setNsURI(nsURI); ePackage.setNsPrefix(nsPrefix); return ePackage; } protected void registerEPackages(final Collection<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); if (this.chronoSphereInstance != null) { this.chronoSphereInstance.getEPackageManager().registerOrUpdateEPackages(ePackages); } for (EPackage ePackage : EMFUtils.flattenEPackages(ePackages)) { assertNotNull(ePackage.getNsURI()); assertNotNull(ePackage.getNsPrefix()); this.registeredEPackages.put(ePackage.getNsURI(), ePackage); } } protected void registerEPackages(final EPackage... ePackages) { this.registerEPackages(Lists.newArrayList(ePackages)); } protected EObject createEObject(final EClass eClass) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); if (this.registeredEPackages.isEmpty()) { throw new IllegalStateException("EPackages were not registered yet! " + "Please call #registerEPackages(...) before creating EObjects!"); } EObject eObject = null; switch (this.emfAPI) { case REFERENCE_IMPLEMENTATION: eObject = EcoreUtil.create(eClass); break; case CHRONOS_TRANSIENT: eObject = EcoreUtil.create(eClass); break; case CHRONOS_GRAPH: ChronoSphereTransaction tx = this.getTransaction(); eObject = tx.createAndAttach(eClass); break; default: throw new UnknownEnumLiteralException(this.emfAPI); } assertNotNull(eObject); return eObject; } protected EPackage getEPackageByNsURI(final String nsUri) { if (this.registeredEPackages.isEmpty()) { throw new IllegalStateException("EPackages were not registered yet! " + "Please call #registerEPackages(...) before requesting EPackages by NS URI!"); } if (this.chronoSphereInstance != null) { // use the EPackage from the transaction return this.getTransaction().getEPackageByNsURI(nsUri); } else { return this.registeredEPackages.get(nsUri); } } private ChronoSphereTransaction getTransaction() { if (this.registeredEPackages.isEmpty()) { throw new IllegalStateException("EPackages were not registered yet! " + "Please call #registerEPackages(...) before creating EObjects!"); } if (this.chronoSphereTransaction != null) { if (this.chronoSphereTransaction.isClosed()) { // we had a transaction, but it is already closed; open a new one this.chronoSphereTransaction = this.chronoSphereInstance.tx(); } // reuse existing transaction return this.chronoSphereTransaction; } if (this.chronoSphereInstance == null) { throw new IllegalArgumentException("The EMF API '" + this.emfAPI + "' does not involve a ChronoSphere instance, cannot create a transaction!"); } // we never used a transaction so far; create a new one this.chronoSphereTransaction = this.chronoSphereInstance.tx(); return this.chronoSphereTransaction; } }
8,535
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EMFTestUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/utils/EMFTestUtils.java
package org.chronos.chronosphere.test.utils; 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 java.util.List; import static com.google.common.base.Preconditions.*; public class EMFTestUtils { public static EClassifier getEClassifierRecursive(final EPackage rootEPackage, final String classifierName) { checkNotNull(rootEPackage, "Precondition violation - argument 'rootEPackage' must not be NULL!"); checkNotNull(classifierName, "Precondition violation - argument 'classifierName' must not be NULL!"); EClassifier eClassifier = rootEPackage.getEClassifier(classifierName); if (eClassifier != null) { return eClassifier; } for (EPackage ePackage : rootEPackage.getESubpackages()) { eClassifier = getEClassifierRecursive(ePackage, classifierName); if (eClassifier != null) { return eClassifier; } } return null; } public static EClass getEClassRecursive(final EPackage rootEPackage, final String className) { checkNotNull(rootEPackage, "Precondition violation - argument 'rootEPackage' must not be NULL!"); checkNotNull(className, "Precondition violation - argument 'className' must not be NULL!"); EClass eClass = (EClass) rootEPackage.getEClassifier(className); if (eClass != null) { return eClass; } for (EPackage ePackage : rootEPackage.getESubpackages()) { eClass = getEClassRecursive(ePackage, className); if (eClass != null) { return eClass; } } return null; } @SuppressWarnings("unchecked") public static void addToEReference(final EObject owner, final EReference reference, final EObject target) { checkNotNull(owner, "Precondition violation - argument 'owner' must not be NULL!"); checkNotNull(reference, "Precondition violation - argument 'reference' must not be NULL!"); checkArgument(reference.isMany(), "Precondition violation - argument 'reference' must be many-valued!"); checkNotNull(target, "Precondition violation - argument 'target' must not be NULL!"); Object eGet = owner.eGet(reference); List<EObject> list = (List<EObject>) eGet; list.add(target); } @SuppressWarnings("unchecked") public static void removeFromEReference(final EObject owner, final EReference reference, final EObject target) { checkNotNull(owner, "Precondition violation - argument 'owner' must not be NULL!"); checkNotNull(reference, "Precondition violation - argument 'reference' must not be NULL!"); checkArgument(reference.isMany(), "Precondition violation - argument 'reference' must be many-valued!"); checkNotNull(target, "Precondition violation - argument 'target' must not be NULL!"); Object eGet = owner.eGet(reference); List<EObject> list = (List<EObject>) eGet; list.remove(target); } }
3,159
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereTestUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/utils/ChronoSphereTestUtils.java
package org.chronos.chronosphere.test.utils; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import java.util.function.Consumer; import static com.google.common.base.Preconditions.*; public class ChronoSphereTestUtils { public static void assertCommitAssert(final ChronoSphereTransaction tx, final Consumer<ChronoSphereTransaction> assertion) { checkNotNull(tx, "Precondition violation - argument 'tx' must not be NULL!"); checkNotNull(assertion, "Precondition violation - argument 'assertion' must not be NULL!"); ChronoSphere sphere = ((ChronoSphereTransactionInternal) tx).getOwningSphere(); assertion.accept(tx); tx.commit(); try (ChronoSphereTransaction tx2 = sphere.tx(tx.getBranch().getName())) { assertion.accept(tx2); } } }
998
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EMFEFactory.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/utils/factories/EMFEFactory.java
package org.chronos.chronosphere.test.utils.factories; import org.eclipse.emf.ecore.impl.EFactoryImpl; public class EMFEFactory extends EFactoryImpl { }
156
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EStoreEFactory.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/utils/factories/EStoreEFactory.java
package org.chronos.chronosphere.test.utils.factories; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.impl.EStoreEObjectImpl; public class EStoreEFactory extends EFactoryImpl { @Override protected EObject basicCreate(final EClass eClass) { return new EStoreEObjectImpl(eClass, new EStoreEObjectImpl.EStoreImpl()); } }
447
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereUnitTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/base/ChronoSphereUnitTest.java
package org.chronos.chronosphere.test.base; import org.chronos.common.test.ChronosUnitTest; public class ChronoSphereUnitTest extends ChronosUnitTest { }
157
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AllChronoSphereBackendsTest.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/test/java/org/chronos/chronosphere/test/base/AllChronoSphereBackendsTest.java
package org.chronos.chronosphere.test.base; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.test.base.AllBackendsTest; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.internal.api.ChronoSphereInternal; import org.junit.After; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.*; public abstract class AllChronoSphereBackendsTest extends AllBackendsTest { private static final Logger log = LoggerFactory.getLogger(AllChronoSphereBackendsTest.class); // ===================================================================================================================== // FIELDS // ===================================================================================================================== private ChronoSphereInternal chronoSphere; // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== protected ChronoSphereInternal getChronoSphere() { if (this.chronoSphere == null) { this.chronoSphere = this.instantiateChronoSphere(this.backend); } return this.chronoSphere; } // ===================================================================================================================== // JUNIT CONTROL // ===================================================================================================================== @After public void cleanUp() { log.debug("Closing ChronoSphere on backend '" + this.backend + "'."); if (this.chronoSphere != null && this.chronoSphere.isOpen()) { this.chronoSphere.close(); } } // ===================================================================================================================== // UTILITY // ===================================================================================================================== protected ChronoSphereInternal reinstantiateChronoSphere() { log.debug("Reinstantiating ChronoSphere on backend '" + this.backend + "'."); if (this.chronoSphere != null && this.chronoSphere.isOpen()) { this.chronoSphere.close(); } this.chronoSphere = this.instantiateChronoSphere(this.backend); return this.chronoSphere; } protected ChronoSphereInternal instantiateChronoSphere(final String backend) { checkNotNull(backend, "Precondition violation - argument 'backend' must not be NULL!"); Configuration configuration = this.createChronosConfiguration(backend); ChronoSphere sphere = ChronoSphere.FACTORY.create().fromConfiguration(configuration).build(); return (ChronoSphereInternal)sphere; } }
2,793
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereTransactionInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/api/ChronoSphereTransactionInternal.java
package org.chronos.chronosphere.internal.api; import java.util.Iterator; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.emf.internal.impl.store.ChronoGraphEStore; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; public interface ChronoSphereTransactionInternal extends ChronoSphereTransaction { public EObject createAndAttach(EClass eClass, String eObjectID); public ChronoSphereInternal getOwningSphere(); public ChronoGraph getGraph(); public ChronoGraphEStore getGraphEStore(); public ChronoEPackageRegistry getEPackageRegistry(); public void batchInsert(Iterator<EObject> model); public void reloadEPackageRegistryFromGraph(); }
855
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SphereTransactionContext.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/api/SphereTransactionContext.java
package org.chronos.chronosphere.internal.api; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; public interface SphereTransactionContext { public ChronoSphereTransactionInternal getTransaction(); public default ChronoGraph getGraph() { return this.getTransaction().getGraph(); } public ChronoEPackageRegistry getChronoEPackage(); }
427
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/api/ChronoSphereInternal.java
package org.chronos.chronosphere.internal.api; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.internal.ogm.api.EObjectToGraphMapper; import org.chronos.chronosphere.internal.ogm.api.EPackageToGraphMapper; public interface ChronoSphereInternal extends ChronoSphere { public ChronoGraph getRootGraph(); public EObjectToGraphMapper getEObjectToGraphMapper(); public EPackageToGraphMapper getEPackageToGraphMapper(); }
517
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereEPackageManagerInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/api/ChronoSphereEPackageManagerInternal.java
package org.chronos.chronosphere.internal.api; import org.chronos.chronosphere.api.ChronoSphereEPackageManager; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; public interface ChronoSphereEPackageManagerInternal extends ChronoSphereEPackageManager { /** * Overrides the registered {@link EPackage}s with the given ones without touching the corresponding * {@link EObject}s. * * <p> * <u><b>/!\</u> <u>WARNING</u> <u>/!\</b></u><br> * After calling this method, the {@link EObject}s in the model may be <b>out of synch</b> with their corresponding * {@link EClass}es! This method will <b>not</b> take anyprecautions against this problem; it will simply override * the registered EPackages! * * * @param transaction * The transaction to work on. Must not be <code>null</code>. Will not be committed. * @param newEPackages * The new EPackages to use for overriding existing ones. Must not be <code>null</code>. If this iterable * is empty, this method is a no-op. */ public void overrideEPackages(ChronoSphereTransaction transaction, Iterable<? extends EPackage> newEPackages); }
1,275
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereConfigurationImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/configuration/impl/ChronoSphereConfigurationImpl.java
package org.chronos.chronosphere.internal.configuration.impl; import org.chronos.chronosphere.internal.configuration.api.ChronoSphereConfiguration; import org.chronos.common.configuration.AbstractConfiguration; import org.chronos.common.configuration.annotation.Namespace; import org.chronos.common.configuration.annotation.Parameter; @Namespace(ChronoSphereConfiguration.NAMESPACE) public class ChronoSphereConfigurationImpl extends AbstractConfiguration implements ChronoSphereConfiguration { // ===================================================================================================================== // FIELDS // ===================================================================================================================== @Parameter(key = BATCH_INSERT__BATCH_SIZE, optional = true) private int batchInsertBatchSize = 10_000; // ===================================================================================================================== // GETTERS & SETTERS // ===================================================================================================================== @Override public int getBatchInsertBatchSize() { return this.batchInsertBatchSize; } }
1,220
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereConfiguration.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/configuration/api/ChronoSphereConfiguration.java
package org.chronos.chronosphere.internal.configuration.api; import org.chronos.common.configuration.ChronosConfiguration; public interface ChronoSphereConfiguration extends ChronosConfiguration { // ===================================================================================================================== // STATIC KEY NAMES // ===================================================================================================================== public static final String NAMESPACE = "org.chronos.chronosphere"; public static final String NS_DOT = NAMESPACE + '.'; public static final String BATCH_INSERT__BATCH_SIZE = NS_DOT + "batchInsert.batchSize"; // ================================================================================================================= // GENERAL CONFIGURATION // ================================================================================================================= public int getBatchInsertBatchSize(); }
984
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EPackageBundleImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/impl/EPackageBundleImpl.java
package org.chronos.chronosphere.internal.ogm.impl; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.internal.ogm.api.EPackageBundle; import org.eclipse.emf.ecore.EPackage; import com.google.common.collect.Lists; import com.google.common.collect.Sets; public class EPackageBundleImpl implements EPackageBundle { private final List<EPackage> ePackages; public EPackageBundleImpl(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); checkArgument(ePackages.iterator().hasNext(), "Precondition violation - argument 'EPackages' must not be empty!"); for (EPackage ePackage : ePackages) { checkNotNull(ePackage.getNsURI(), "Precondition violation - argument 'ePackages' contains an EPackage where 'ePackage.getNsURI()' == NULL!"); checkNotNull(ePackage.getNsPrefix(), "Precondition violation - argument 'ePackages' contains an EPackage where 'ePackage.getNsPrefix()' == NULL!"); checkNotNull(ePackage.getName(), "Precondition violation - argument 'ePackages' contains an EPackage where 'ePackage.getName()' == NULL!"); } EMFUtils.assertEPackagesAreSelfContained(ePackages); // remove duplicates from the epackages Set<EPackage> ePackageSet = Sets.newLinkedHashSet(ePackages); this.ePackages = Collections.unmodifiableList(Lists.newArrayList(ePackageSet)); } @Override public Iterator<EPackage> iterator() { return this.ePackages.iterator(); } @Override public List<EPackage> getContents() { return this.ePackages; } @Override public EPackage getEPackageByNsURI(final String ePackageNsURI) { checkNotNull(ePackageNsURI, "Precondition violation - argument 'ePackageNsURI' must not be NULL!"); for (EPackage ePackage : this) { if (ePackage.getNsURI().equals(ePackageNsURI)) { return ePackage; } } return null; } }
2,082
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GremlinUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/impl/GremlinUtils.java
package org.chronos.chronosphere.internal.ogm.impl; import static com.google.common.base.Preconditions.*; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; public class GremlinUtils { /** * Makes sure that only a single outgoing {@link Edge} with the given <code>label</code> exists in the * <code>source</code> {@link Vertex} and that edge connects to the <code>target</code> {@link Vertex}. * * <p> * There are several cases: * <ol> * <li>There is no outgoing edge at the source vertex with the given label. In this case, a new edge will be added * from source to target vertex with the given label. * <li>There is an outgoing edge at the source vertex with the given label, and that edge connects to the given * target vertex. In this case, this method is a no-op and simply returns that edge. * <li>There is an outgoing edge at the source vertex with the given label, and that edge connects to a vertex other * than the given target vertex. In this case, this old edge is removed, a new edge is added from the given source * vertex to the given target vertex with the given label, and the new edge is returned. * </ol> * * @param source * The source vertex that owns the edge to override. Must not be <code>null</code>. * @param label * The label of the single edge. Must not be <code>null</code>. * @param target * The target vertex to which the single edge should connect. Must not be <code>null</code>. * @return The single outgoing edge in the source vertex with the given label that connects to the given target * vertex. The edge may have been created, may have already existed, or may have been redirected from a * previous target (see specification above). */ public static Edge setEdgeTarget(final Vertex source, final String label, final Vertex target) { checkNotNull(source, "Precondition violation - argument 'source' must not be NULL!"); checkNotNull(target, "Precondition violation - argument 'target' must not be NULL!"); checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!"); Set<Edge> edges = Sets.newHashSet(source.edges(Direction.OUT, label)); if (edges.isEmpty()) { // there is no existing outgoing edge with the given label at the source vertex. // We can "override" by simply adding a new edge to the desired target vertex with our label. return source.addEdge(label, target); } else { // there is at least one outgoing edge from the source verex wiht our label. Check where it leads to. Edge edgeToKeep = null; for (Edge edge : edges) { if (edge.inVertex().equals(target)) { // this is the correct edge; we can keep it. edgeToKeep = edge; } else { // this edge leads to the wrong target, remove it edge.remove(); } } if (edgeToKeep != null) { // we have found an edge that leads to the desired target, no need to override return edgeToKeep; } else { // all previous edges with the given label lead to other vertices. We removed them all, // so now we need to create the edge to the desired target. return source.addEdge(label, target); } } } /** * Makes sure that every {@linkplain Edge edge} with the given <code>label</code> that is outgoing from the given * <code>source</code> {@linkplain Vertex vertex} leads to one of the given <code>targets</code>, and that there is * one edge for each target. * * <p> * This method is a two-step process. * <ol> * <li>In the <code>source</code> vertex, iterate over the outgoing edges that have the given <code>label</code>. * <ol> * <li>If the current edge leads to a vertex that is in our <code>targets</code> set, keep the edge and add it to * the result set. * <li>if the current edge leads to a vertex that is not in our <code>targets</code> set, delete it. * </ol> * <li>For each vertex in our <code>targets</code> that we did not find in the previous step, create a new edge from * the <code>source</code> vertex with the given label, and add it to the result set. * </ol> * * @param source * The source vertex that owns the edge to override. Must not be <code>null</code>. * @param label * The edge label in question. Must not be <code>null</code>. * @param targets * The desired set of target vertices. May be empty (in which case all outgoing edges from the source * vertex will be deleted and the result set will be empty), but must not be <code>null</code>. * @return The set of edges that lead from the source vertex to one of the target vertices via the given label. The * edges may have already existed, or were generated by this method. May be empty in case that the * <code>targets</code> set was empty, but will never be <code>null</code>. */ public static Set<Edge> setEdgeTargets(final Vertex source, final String label, final Set<Vertex> targets) { checkNotNull(source, "Precondition violation - argument 'source' must not be NULL!"); checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!"); checkNotNull(targets, "Precondition violation - argument 'targets' must not be NULL!"); Set<Edge> resultSet = Sets.newHashSet(); Set<Vertex> verticesToConnectTo = Sets.newHashSet(targets); Set<Edge> existingEdges = Sets.newHashSet(source.edges(Direction.OUT, label)); for (Edge edge : existingEdges) { Vertex target = edge.inVertex(); if (targets.contains(target)) { // we are already connected with this vertex verticesToConnectTo.remove(target); resultSet.add(edge); } else { // this edge is no longer required, remove it edge.remove(); } } // in case that we have target vertices to which we are not already connectd, add these edges now for (Vertex target : verticesToConnectTo) { Edge newEdge = source.addEdge(label, target); resultSet.add(newEdge); } return resultSet; } /** * A variant of {@link #setEdgeTargets(Vertex, String, Set)} that respects target ordering and non-uniqueness of * targets. * * <p> * This method will check if there is an {@link Edge} from the given <code>source</code> {@link Vertex} to each of * the given <code>target</code> vertices. If the list of targets contains one vertex several times, this method * will ensure that there are as many edges to that target. Any outgoing edge from the given <code>source</code> * with the given <code>label</code> that is <b>not</b> reused by this process will be deleted. Additional edges * will be created only if necessary. The returned list of edges will be ordered by target vertex, and have the same * ordering as the given list of <code>targets</code>. * * @param source * The source vertex that owns the edge to override. Must not be <code>null</code>. * @param label * The edge label in question. Must not be <code>null</code>. * @param targets * The desired list of target vertices. May be empty (in which case all outgoing edges from the source * vertex will be deleted and the result set will be empty), but must not be <code>null</code>. Multiple * occurrences of the same vertex will be respected, as well as the ordering of vertices in the list. * @return The list of edges that lead from the source vertex to one of the target vertices via the given label. The * edges may have already existed, or were generated by this method. May be empty in case that the * <code>targets</code> set was empty, but will never be <code>null</code>. */ public static List<Edge> setEdgeTargets(final Vertex source, final String label, final List<Vertex> targets) { checkNotNull(source, "Precondition violation - argument 'source' must not be NULL!"); checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!"); checkNotNull(targets, "Precondition violation - argument 'targets' must not be NULL!"); List<Edge> resultList = Lists.newArrayList(); Set<Edge> existingEdges = Sets.newHashSet(source.edges(Direction.OUT, label)); for (Vertex targetVertex : targets) { Optional<Edge> maybeEdge = existingEdges.stream().filter(edge -> edge.inVertex().equals(targetVertex)) .findAny(); if (maybeEdge.isPresent()) { Edge edge = maybeEdge.get(); // we reuse this edge resultList.add(edge); // ... and make sure that we don't reuse it twice existingEdges.remove(edge); } else { // we don't have an edge to this target; add one resultList.add(source.addEdge(label, targetVertex)); } } // all edges that remain are "unused" and therefore need to be deleted existingEdges.forEach(edge -> edge.remove()); return resultList; } /** * Finds and returns the single {@link Edge} that connects the given <code>source</code> {@link Vertex} with the * given <code>target</code> {@link Vertex}. * * @param source * The source vertex of the edge to look for. Must not be <code>null</code>. * @param label * The label of the edge to look for. Must not be <code>null</code>. * @param target * The target vertex of the edge to look for. Must not be <code>null</code>. * @return The single egde that connects the given source and target vertices with the given label, or * <code>null</code> if no such edge exists. * * @throws IllegalArgumentException * Thrown if there is more than one edge with the given label from the given source to the given target * vertex. */ public static Edge getEdge(final Vertex source, final String label, final Vertex target) { Set<Edge> edges = getEdges(source, label, target); if (edges.isEmpty()) { return null; } if (edges.size() > 1) { throw new IllegalArgumentException("Multiple edges (" + edges.size() + ") with label '" + label + "'connect the source vertex " + source + " with target vertex " + target + "!"); } return Iterables.getOnlyElement(edges); } /** * Finds and returns the {@link Edge}s that connects the given <code>source</code> {@link Vertex} with the given * <code>target</code> {@link Vertex}. * * @param source * The source vertex of the edge to look for. Must not be <code>null</code>. * @param label * The label of the edge to look for. Must not be <code>null</code>. * @param target * The target vertex of the edge to look for. Must not be <code>null</code>. * @return The edges that connects the given source and target vertices with the given label. May be empty if no * edge is found, but never <code>null</code>. */ public static Set<Edge> getEdges(final Vertex source, final String label, final Vertex target) { checkNotNull(source, "Precondition violation - argument 'source' must not be NULL!"); checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!"); checkNotNull(target, "Precondition violation - argument 'target' must not be NULL!"); Set<Edge> resultSet = Sets.newHashSet(); source.edges(Direction.OUT, label).forEachRemaining(edge -> { if (edge.inVertex().equals(target)) { resultSet.add(edge); } }); return resultSet; } /** * Searches for an {@link Edge} between the given <code>source</code> and <code>target</code> {@linkplain Vertex * vertices} and returns it, creating a new one if it does not exist. * * @param source * The source vertex. Must not be <code>null</code>. * @param label * The edge label. Must not be <code>null</code>. * @param target * The target vertex. Must not be <code>null</code>. * * @return The edge. If it already existed, it will be returned untouched, otherwise a new edge was created and will * be returned. */ public static Edge ensureEdgeExists(final Vertex source, final String label, final Vertex target) { checkNotNull(source, "Precondition violation - argument 'source' must not be NULL!"); checkNotNull(label, "Precondition violation - argument 'label' must not be NULL!"); checkNotNull(target, "Precondition violation - argument 'target' must not be NULL!"); Iterator<Edge> edges = source.edges(Direction.OUT, label); while (edges.hasNext()) { Edge edge = edges.next(); if (edge.inVertex().equals(target)) { // found it return edge; } } // edge not found; create it return source.addEdge(label, target); } }
12,880
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EPackageToGraphMapperImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/impl/EPackageToGraphMapperImpl.java
package org.chronos.chronosphere.internal.ogm.impl; import static com.google.common.base.Preconditions.*; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import org.apache.tinkerpop.gremlin.structure.Direction; 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.emf.impl.ChronoEFactory; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistryInternal; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.chronos.chronosphere.internal.ogm.api.EPackageBundle; import org.chronos.chronosphere.internal.ogm.api.EPackageToGraphMapper; import org.chronos.chronosphere.internal.ogm.api.VertexKind; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; public class EPackageToGraphMapperImpl implements EPackageToGraphMapper { @Override public void mapToGraph(final ChronoGraph graph, final EPackageBundle bundle) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(bundle, "Precondition violation - argument 'bundle' must not be NULL!"); this.mergeEPackageBundleIntoGraph(bundle, graph); } @Override public ChronoEPackageRegistry readChronoEPackageRegistryFromGraph(final ChronoGraph graph) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); ChronoEPackageRegistryInternal registry = new ChronoEPackageRegistryImpl(); Set<Vertex> bundleVertices = ChronoSphereGraphFormat.getEpackageBundleVertices(graph); for (Vertex bundleVertex : bundleVertices) { String xmi = ChronoSphereGraphFormat.getXMIContents(bundleVertex); List<EPackage> ePackages = EMFUtils.readEPackagesFromXMI(xmi); EMFUtils.flattenEPackages(ePackages) .forEach(ePackage -> ePackage.setEFactoryInstance(new ChronoEFactory())); for (EPackage ePackage : ePackages) { this.registerPackageContentsRecursively(graph, ePackage, registry); } } return registry; } @Override public void deleteInGraph(final ChronoGraph graph, final EPackageBundle bundle) { checkNotNull(bundle, "Precondition violation - argument 'bundle' must not be NULL!"); Vertex bundleVertex = this.getCommonBundleVertex(graph, bundle); if (bundleVertex == null) { // the bundle is not part of the graph return; } Iterator<Vertex> ePackageVertices = bundleVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__BUNDLE_OWNED_EPACKAGE); while (ePackageVertices.hasNext()) { Vertex ePackageVertex = ePackageVertices.next(); this.deleteEPackageVertex(ePackageVertex); } bundleVertex.remove(); } // ================================================================================================================= // INTERNAL HELPER METHODS // ================================================================================================================= private void mergeEPackageBundleIntoGraph(final EPackageBundle bundle, final ChronoGraph graph) { ChronoEPackageRegistryInternal registry = new ChronoEPackageRegistryImpl(); // check if one of the given EPackages is already mapped Vertex commonBundleVertex = null; for (EPackage ePackage : bundle) { Vertex packageVertex = ChronoSphereGraphFormat.getVertexForEPackage(graph, ePackage); if (packageVertex != null) { Iterator<Vertex> bundleVertices = packageVertex.vertices(Direction.IN, ChronoSphereGraphFormat.E_LABEL__BUNDLE_OWNED_EPACKAGE); Vertex bundleVertex = Iterators.getOnlyElement(bundleVertices); if (commonBundleVertex != null && commonBundleVertex.equals(bundleVertex) == false) { throw new IllegalStateException( "The EPackage '" + ePackage.getName() + "' belongs to a different bundle of EPackages!"); } commonBundleVertex = bundleVertex; } } if (commonBundleVertex != null) { // we have a common bundle vertex, we need to update it // there might be EPackages in the old bundle that are not in the new bundle anymore Iterator<Vertex> ePackageVertices = commonBundleVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__BUNDLE_OWNED_EPACKAGE); ePackageVertices.forEachRemaining(ePackageVertex -> { String nsURI = ChronoSphereGraphFormat.getNsURI(ePackageVertex); if (bundle.containsEPackageWithNsURI(nsURI) == false) { // delete that EPackage this.deleteEPackageVertex(ePackageVertex); } }); // update the bundle XMI ChronoSphereGraphFormat.updateEPackageBundleVertex(commonBundleVertex, bundle); } else { // there is no bundle vertex yet, create it commonBundleVertex = ChronoSphereGraphFormat.createVertexForEPackageBundle(graph, bundle); } for (EPackage ePackage : bundle) { this.mergeEPackageIntoGraphRecursive(commonBundleVertex, ePackage, graph); } // seal the ChronoEPackage (i.e. prevent any further modification to it) registry.seal(); // map the ESuperType edges this.mergeESuperTypeEdges(registry, graph); } private Vertex mergeEPackageIntoGraphRecursive(final Vertex bundleVertex, final EPackage ePackage, final ChronoGraph graph) { Vertex ePackageVertex = ChronoSphereGraphFormat.getVertexForEPackage(graph, ePackage); if (ePackageVertex == null) { ePackageVertex = ChronoSphereGraphFormat.createVertexForEPackage(graph, ePackage); } if (bundleVertex != null) { // this EPackage is a root EPackage; create an edge from the bundle to the EPackage GremlinUtils.ensureEdgeExists(bundleVertex, ChronoSphereGraphFormat.E_LABEL__BUNDLE_OWNED_EPACKAGE, ePackageVertex); } // map the EClassifiers (EClasses) Set<Vertex> eClassVertices = Sets.newHashSet(); for (EClassifier classifier : ePackage.getEClassifiers()) { if (classifier instanceof EClass == false) { // we are not interested in EDataTypes here, skip them continue; } EClass eClass = (EClass) classifier; Vertex eClassVertex = this.mergeEClassIntoGraph(ePackageVertex, eClass); eClassVertices.add(eClassVertex); } // remove all EClass vertices that we did not visit (they were removed in the EPackage) Set<Vertex> existingEClassVertices = Sets.newHashSet( ePackageVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__EPACKAGE_OWNED_CLASSIFIERS)); existingEClassVertices.removeAll(eClassVertices); existingEClassVertices.forEach(eClassVertex -> this.deleteEClassVertex(eClassVertex)); // map the child EPackages recursively Set<Vertex> childEPackageVertices = Sets.newHashSet(); for (EPackage childPackage : ePackage.getESubpackages()) { Vertex childPackageVertex = this.mergeEPackageIntoGraphRecursive(bundleVertex, childPackage, graph); childEPackageVertices.add(childPackageVertex); } Set<Vertex> allSubPackageVertices = Sets .newHashSet(ePackageVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__ESUBPACKAGE)); allSubPackageVertices.removeAll(childEPackageVertices); // all other subpackages have been removed for (Vertex subPackageVertex : allSubPackageVertices) { this.deleteEPackageVertex(subPackageVertex); } return ePackageVertex; } private Vertex mergeEClassIntoGraph(final Vertex ePackageVertex, final EClass eClass) { ChronoGraph graph = (ChronoGraph) ePackageVertex.graph(); // try to find the EClass vertex in the graph Vertex eClassVertex = ChronoSphereGraphFormat.getVertexForEClassRaw(graph, eClass); if (eClassVertex == null) { // eClass has not yet been mapped; create the vertex and an ID for it String id = UUID.randomUUID().toString(); eClassVertex = graph.addVertex(T.id, id); ChronoSphereGraphFormat.setVertexKind(eClassVertex, VertexKind.ECLASS); ePackageVertex.addEdge(ChronoSphereGraphFormat.E_LABEL__EPACKAGE_OWNED_CLASSIFIERS, eClassVertex); ChronoSphereGraphFormat.setVertexName(eClassVertex, eClass.getName()); } else { // eClass has already been mapped; nothing to do } // in order to remove vertices for EReferences and EAttributes in the graph that do not exist anymore in the // EPackage, remember which vertices we visited Set<Vertex> eAttributeVertices = Sets.newHashSet(); Set<Vertex> eReferenceVertices = Sets.newHashSet(); // map the EAttributes of that EClass for (EAttribute eAttribute : eClass.getEAttributes()) { // try to find the EAttribute vertex in the graph Vertex eAttributeVertex = ChronoSphereGraphFormat.getVertexForEAttributeRaw(eClassVertex, eAttribute); // if no vertex exists, create it if (eAttributeVertex == null) { String id = UUID.randomUUID().toString(); eAttributeVertex = graph.addVertex(T.id, id); ChronoSphereGraphFormat.setVertexKind(eAttributeVertex, VertexKind.EATTRIBUTE); eClassVertex.addEdge(ChronoSphereGraphFormat.E_LABEL__ECLASS_OWNED_EATTRIBUTE, eAttributeVertex); ChronoSphereGraphFormat.setVertexName(eAttributeVertex, eAttribute.getName()); } // remember that we visited this vertex eAttributeVertices.add(eAttributeVertex); } // map the EReferences of that EClass for (EReference eReference : eClass.getEReferences()) { // try to find the EReference vertex in the graph Vertex eReferenceVertex = ChronoSphereGraphFormat.getVertexForEReferenceRaw(eClassVertex, eReference); // if no vertex exists, create it if (eReferenceVertex == null) { String id = UUID.randomUUID().toString(); eReferenceVertex = graph.addVertex(T.id, id); ChronoSphereGraphFormat.setVertexKind(eReferenceVertex, VertexKind.EREFERENCE); eClassVertex.addEdge(ChronoSphereGraphFormat.E_LABEL__ECLASS_OWNED_EREFERENCE, eReferenceVertex); ChronoSphereGraphFormat.setVertexName(eReferenceVertex, eReference.getName()); } // remember that we visited this vertex eReferenceVertices.add(eReferenceVertex); } // remove all EAttribute vertices that do not exist anymore in the graph Set<Vertex> existingEAttributeVertices = Sets.newHashSet( eClassVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__ECLASS_OWNED_EATTRIBUTE)); existingEAttributeVertices.removeAll(eAttributeVertices); // all remaining eAttribute vertices represent removed eAttributes for (Vertex eAttributeVertex : existingEAttributeVertices) { eAttributeVertex.remove(); } // remove all EReference vertices that do not exist anymore in the graph Set<Vertex> existingEReferenceVertices = Sets.newHashSet( eClassVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__ECLASS_OWNED_EREFERENCE)); existingEReferenceVertices.removeAll(eReferenceVertices); // all remaining eAttribute vertices represent removed eAttributes for (Vertex eReferenceVertex : existingEReferenceVertices) { eReferenceVertex.remove(); } return eClassVertex; } private void mergeESuperTypeEdges(final ChronoEPackageRegistry chronoEPackage, final ChronoGraph graph) { checkNotNull(chronoEPackage, "Precondition violation - argument 'chronoEPackage' must not be NULL!"); checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); for (EClass eClass : chronoEPackage.getEClasses()) { Vertex eClassVertex = ChronoSphereGraphFormat.getVertexForEClass(chronoEPackage, graph, eClass); List<EClass> superTypes = eClass.getESuperTypes(); Set<Vertex> superTypeVertices = Sets.newHashSet(); for (EClass superType : superTypes) { Vertex superTypeVertex = ChronoSphereGraphFormat.getVertexForEClass(chronoEPackage, graph, superType); if (superTypeVertex == null) { throw new IllegalStateException("Could not find vertex for supertype '" + superType.getName() + "' of EClass '" + eClass.getName() + "'!"); } superTypeVertices.add(superTypeVertex); } GremlinUtils.setEdgeTargets(eClassVertex, ChronoSphereGraphFormat.E_LABEL__ECLASS_ESUPERTYPE, superTypeVertices); } } private void deleteEPackageVertex(final Vertex packageVertex) { Set<Vertex> verticesToRemove = this.deleteEPackageVertexRecursively(packageVertex); for (Vertex vertex : verticesToRemove) { vertex.remove(); } } private Set<Vertex> deleteEPackageVertexRecursively(final Vertex packageVertex) { Set<Vertex> verticesToRemove = Sets.newHashSet(); verticesToRemove.add(packageVertex); // traverse the eClasses Set<Vertex> eClassVertices = Sets.newHashSet( packageVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__EPACKAGE_OWNED_CLASSIFIERS)); verticesToRemove.addAll(eClassVertices); // traverse the eAttributes, eReferences and instance EObjects for (Vertex eClassVertex : eClassVertices) { verticesToRemove.addAll(this.deleteEClassVertexRecursively(eClassVertex)); } // do the same for the subpackages Set<Vertex> subPackageVertices = Sets .newHashSet(packageVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__ESUBPACKAGE)); for (Vertex subPackageVertex : subPackageVertices) { verticesToRemove.addAll(this.deleteEPackageVertexRecursively(subPackageVertex)); } return verticesToRemove; } private void deleteEClassVertex(final Vertex vertex) { this.deleteEClassVertexRecursively(vertex).forEach(v -> v.remove()); } private Set<Vertex> deleteEClassVertexRecursively(final Vertex eClassVertex) { Set<Vertex> verticesToRemove = Sets.newHashSet(); verticesToRemove.add(eClassVertex); // eAttributes Iterator<Vertex> eAttributeVertices = eClassVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__ECLASS_OWNED_EATTRIBUTE); eAttributeVertices.forEachRemaining(v -> verticesToRemove.add(v)); // eReferences Iterator<Vertex> eReferenceVertices = eClassVertex.vertices(Direction.OUT, ChronoSphereGraphFormat.E_LABEL__ECLASS_OWNED_EREFERENCE); eReferenceVertices.forEachRemaining(v -> verticesToRemove.add(v)); // instance EObjects Iterator<Vertex> eObjectVertices = eClassVertex.graph().traversal() // start from all vertices .V() // restrict to EObjects only .has(ChronoSphereGraphFormat.V_PROP__KIND, VertexKind.EOBJECT.toString()) // restrict to EObjects which have the EClass which we want to delete .has(ChronoSphereGraphFormat.V_PROP__ECLASS_ID, eClassVertex.id()); eObjectVertices.forEachRemaining(v -> verticesToRemove.add(v)); return verticesToRemove; } private void registerPackageContentsRecursively(final ChronoGraph graph, final EPackage ePackage, final ChronoEPackageRegistryInternal chronoEPackage) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); checkNotNull(chronoEPackage, "Precondition violation - argument 'chronoEPackage' must not be NULL!"); chronoEPackage.registerEPackage(ePackage); Vertex ePackageVertex = ChronoSphereGraphFormat.getVertexForEPackage(graph, ePackage); if (ePackageVertex == null) { throw new IllegalArgumentException("Could not find EPackage '" + ePackage.getName() + "' (NS URI: '" + ePackage.getNsURI() + "') in data store! Was it registered before?"); } for (EClassifier eClassifier : ePackage.getEClassifiers()) { if (eClassifier instanceof EClass == false) { // we are not interested in EDataTypes here; skip them continue; } EClass eClass = (EClass) eClassifier; Vertex eClassVertex = ChronoSphereGraphFormat.getVertexForEClassRaw(graph, eClass); if (eClassVertex == null) { throw new IllegalArgumentException("Could not find EClass '" + eClass.getName() + "' in data store! Did the EPackage contents change?"); } chronoEPackage.registerEClassID(eClass, (String) eClassVertex.id()); for (EAttribute eAttribute : eClass.getEAttributes()) { Vertex eAttributeVertex = ChronoSphereGraphFormat.getVertexForEAttributeRaw(eClassVertex, eAttribute); if (eAttributeVertex == null) { throw new IllegalArgumentException("Could not find EAttribute '" + eClass.getName() + "#" + eAttribute.getName() + "' in data store! Did the EPackage contents change?"); } chronoEPackage.registerEAttributeID(eAttribute, (String) eAttributeVertex.id()); } for (EReference eReference : eClass.getEReferences()) { Vertex eReferenceVertex = ChronoSphereGraphFormat.getVertexForEReferenceRaw(eClassVertex, eReference); if (eReferenceVertex == null) { throw new IllegalArgumentException("Could not find EReference '" + eClass.getName() + "#" + eReference.getName() + "' in data store! Did the EPackage contents change?"); } chronoEPackage.registerEReferenceID(eReference, (String) eReferenceVertex.id()); } } for (EPackage subPackage : ePackage.getESubpackages()) { this.registerPackageContentsRecursively(graph, subPackage, chronoEPackage); } } private Vertex getCommonBundleVertex(final ChronoGraph graph, final EPackageBundle bundle) { Vertex commonBundleVertex = null; for (EPackage ePackage : bundle) { Vertex packageVertex = ChronoSphereGraphFormat.getVertexForEPackage(graph, ePackage); if (packageVertex != null) { Iterator<Vertex> bundleVertices = packageVertex.vertices(Direction.IN, ChronoSphereGraphFormat.E_LABEL__BUNDLE_OWNED_EPACKAGE); Vertex bundleVertex = Iterators.getOnlyElement(bundleVertices); if (commonBundleVertex != null && commonBundleVertex.equals(bundleVertex) == false) { throw new IllegalStateException( "The EPackage '" + ePackage.getName() + "' belongs to a different bundle of EPackages!"); } commonBundleVertex = bundleVertex; } } return commonBundleVertex; } }
17,923
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEPackageRegistryImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/impl/ChronoEPackageRegistryImpl.java
package org.chronos.chronosphere.internal.ogm.impl; import static com.google.common.base.Preconditions.*; import java.util.Collections; import java.util.Set; import java.util.Stack; import org.chronos.chronosphere.emf.impl.ChronoEFactory; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistryInternal; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ChronoEPackageRegistryImpl implements ChronoEPackageRegistryInternal { private static final Logger log = LoggerFactory.getLogger(ChronoEPackageRegistryImpl.class); private final BiMap<String, EPackage> nsURItoEPackage = HashBiMap.create(); private final BiMap<EClass, String> eClassToID = HashBiMap.create(); private final BiMap<EAttribute, String> eAttributeToID = HashBiMap.create(); private final BiMap<EReference, String> eReferenceToID = HashBiMap.create(); private boolean isSealed; // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public boolean existsEPackage(final String namespaceURI) { checkNotNull(namespaceURI, "Precondition violation - argument 'namespaceURI' must not be NULL!"); return this.getEPackage(namespaceURI) != null; } @Override public EPackage getEPackage(final String namespaceURI) { checkNotNull(namespaceURI, "Precondition violation - argument 'namespaceURI' must not be NULL!"); return this.nsURItoEPackage.get(namespaceURI); } @Override public EClass getEClassByID(final String chronoEClassID) { checkNotNull(chronoEClassID, "Precondition violation - argument 'chronoEClassID' must not be NULL!"); return this.eClassToID.inverse().get(chronoEClassID); } @Override public String getEClassID(final EClass eClass) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); String eClassID = this.eClassToID.get(eClass); if (eClassID != null) { // we found the EClass ID via '==' comparison return eClassID; } // we did not find the eClass instance - try to find it via owning EPackage NS URI EClass registeredClass = this.getRegisteredEClassforEClassViaEPackage(eClass); if (registeredClass != null) { return this.eClassToID.get(registeredClass); } else { // the ePackage must have changed in structure, can't find the class return null; } } @Override public Set<EClass> getEClasses() { return Collections.unmodifiableSet(this.eClassToID.keySet()); } @Override public EAttribute getEAttributeByID(final String chronoEAttributeID) { checkNotNull(chronoEAttributeID, "Precondition violation - argument 'chronoEAttributeID' must not be NULL!"); return this.eAttributeToID.inverse().get(chronoEAttributeID); } @Override public String getEAttributeID(final EAttribute eAttribute) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); String eAttributeID = this.eAttributeToID.get(eAttribute); if (eAttributeID != null) { // found the EAttribute ID via '==' comparison return eAttributeID; } // we did not find the EAttribute instance - try to find it via owning EClass EClass eClass = this.getRegisteredEClassforEClassViaEPackage(eAttribute.getEContainingClass()); if (eClass == null) { // we don't know the owning EClass, maybe the EPackage was not registered? return null; } EStructuralFeature feature = eClass.getEStructuralFeature(eAttribute.getName()); if (feature == null) { // in our version of the EClass, no such feature exists... return null; } if (feature instanceof EAttribute == false) { // in our version of the eClass, it's an EReference... return null; } EAttribute registeredEAttribute = (EAttribute) feature; return this.eAttributeToID.get(registeredEAttribute); } @Override public EReference getEReferenceByID(final String chronoEReferenceID) { checkNotNull(chronoEReferenceID, "Precondition violation - argument 'chronoEReferenceID' must not be NULL!"); return this.eReferenceToID.inverse().get(chronoEReferenceID); } @Override public String getEReferenceID(final EReference eReference) { checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); String eReferenceID = this.eReferenceToID.get(eReference); if (eReferenceID != null) { // found the EReference ID via '==' comparison return eReferenceID; } // we did not find the EReference instance - try to find it via owning EClass EClass eClass = this.getRegisteredEClassforEClassViaEPackage(eReference.getEContainingClass()); if (eClass == null) { // we don't know the owning EClass, maybe the EPackage was not registered? return null; } EStructuralFeature feature = eClass.getEStructuralFeature(eReference.getName()); if (feature == null) { // in our version of the EClass, no such feature exists... return null; } if (feature instanceof EReference == false) { // in our version of the eClass, it's an EAttribute... return null; } EReference registeredReference = (EReference) feature; return this.eReferenceToID.get(registeredReference); } // ================================================================================================================= // INTERNAL API // ================================================================================================================= @Override public void registerEPackage(final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); this.assertNotSealed(); if (ePackage.getNsURI() == null || ePackage.getNsURI().trim().isEmpty()) { throw new IllegalArgumentException("Cannot store an EPackage that has no Namespace URI (NSURI)!"); } EPackage existingEPackage = this.nsURItoEPackage.put(ePackage.getNsURI(), ePackage); if (existingEPackage != null) { log.warn("Registration of EPackage with Namespace URI '" + ePackage.getNsURI() + "' overrides an existing EPackage!"); } } @Override public void registerEClassID(final EClass eClass, final String chronoEClassID) { this.assertNotSealed(); String previousID = this.eClassToID.get(eClass); if (previousID != null) { if (previousID.equals(chronoEClassID) == false) { throw new IllegalStateException("EClass '" + eClass.getName() + "' already has an assigned ID of '" + previousID + "', can't assign ID '" + chronoEClassID + "'!"); } else { // same id has already been assigned return; } } this.eClassToID.put(eClass, chronoEClassID); } @Override public void registerEAttributeID(final EAttribute eAttribute, final String chronoEAttributeID) { this.assertNotSealed(); String previousID = this.eAttributeToID.get(eAttribute); if (previousID != null) { if (previousID.equals(chronoEAttributeID) == false) { throw new IllegalStateException( "EAttribute '" + eAttribute.getName() + "' already has an assigned ID of '" + previousID + "', can't assign ID '" + chronoEAttributeID + "'!"); } else { // same id has already been assigned return; } } this.eAttributeToID.put(eAttribute, chronoEAttributeID); } @Override public void registerEReferenceID(final EReference eReference, final String chronoEReferenceID) { this.assertNotSealed(); String previousID = this.eReferenceToID.get(eReference); if (previousID != null) { if (previousID.equals(chronoEReferenceID) == false) { throw new IllegalStateException( "EAttribute '" + eReference.getName() + "' already has an assigned ID of '" + previousID + "', can't assign ID '" + chronoEReferenceID + "'!"); } else { // same id has already been assigned return; } } this.eReferenceToID.put(eReference, chronoEReferenceID); } @Override public Set<EPackage> getEPackages() { return Sets.newHashSet(this.nsURItoEPackage.values()); } @Override public void seal() { if (this.isSealed) { return; } // register the correct EFactory instance at all (sub-)packages Stack<EPackage> ePackagesToVisit = new Stack<>(); for (EPackage ePackage : this.nsURItoEPackage.values()) { ePackagesToVisit.push(ePackage); } Set<EPackage> visitedEPackages = Sets.newHashSet(); while (ePackagesToVisit.isEmpty() == false) { EPackage pack = ePackagesToVisit.pop(); if (visitedEPackages.contains(pack)) { continue; } visitedEPackages.add(pack); pack.setEFactoryInstance(new ChronoEFactory()); for (EPackage subPackage : pack.getESubpackages()) { ePackagesToVisit.push(subPackage); } } this.isSealed = true; } // ================================================================================================================= // HELPER METHODS // ================================================================================================================= private void assertNotSealed() { if (this.isSealed) { throw new IllegalStateException( "ChronoEPackage is already sealed off! No modifications are allowed anymore."); } } private EClass getRegisteredEClassforEClassViaEPackage(final EClass eClass) { EPackage registeredEPackage = this.getEPackage(eClass.getEPackage().getNsURI()); if (registeredEPackage == null) { // the ePackage is not registered... return null; } EClass registeredClass = (EClass) registeredEPackage.getEClassifier(eClass.getName()); return registeredClass; } }
9,883
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectToGraphMapperImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/impl/EObjectToGraphMapperImpl.java
package org.chronos.chronosphere.internal.ogm.impl; import static com.google.common.base.Preconditions.*; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.internal.api.SphereTransactionContext; import org.chronos.chronosphere.internal.ogm.api.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.chronos.chronosphere.internal.ogm.api.EObjectToGraphMapper; import org.chronos.chronosphere.internal.ogm.api.VertexKind; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EReference; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class EObjectToGraphMapperImpl implements EObjectToGraphMapper { // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public EObjectToGraphMapperImpl() { } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public Vertex getOrCreatePlainVertexForEObject(final SphereTransactionContext ctx, final ChronoEObject eObject) { checkNotNull(ctx, "Precondition violation - argument 'ctx' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); ChronoGraph graph = ctx.getGraph(); Vertex vertex = Iterators.getOnlyElement(graph.vertices(eObject.getId()), null); if (vertex == null) { // we don't know that object yet; create a new vertex for it vertex = graph.addVertex(T.id, eObject.getId()); ChronoSphereGraphFormat.setVertexKind(vertex, VertexKind.EOBJECT); return vertex; } else { // the object was already persisted once, we already have a vertex for it return vertex; } } @Override public void mapAllEObjectPropertiesToGraph(final SphereTransactionContext ctx, final ChronoEObject eObject) { checkNotNull(ctx, "Precondition violation - argument 'ctx' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkNotNull(eObject.eClass(), "Precondition violation - argument 'eObject' has no 'eClass' assigned!"); // iterate over the attributes and assign them to the vertex one by one for (EAttribute attribute : eObject.eClass().getEAllAttributes()) { this.mapEAttributeToGraph(ctx, eObject, attribute); } } @Override public void mapAllEObjectReferencesToGraph(final SphereTransactionContext session, final ChronoEObject eObject) { checkNotNull(session, "Precondition violation - argument 'ctx' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkNotNull(eObject.eClass(), "Precondition violation - argument 'eObject' has no 'eClass' assigned!"); // make sure that we actually HAVE a vertex for the EObject this.getOrCreatePlainVertexForEObject(session, eObject); // iterate over the references and assign them to the vertex one by one for (EReference reference : eObject.eClass().getEAllReferences()) { this.mapEReferenceToGraph(session, eObject, reference); } } @Override public void mapEAttributeToGraph(final SphereTransactionContext ctx, final ChronoEObject eObject, final EAttribute attribute) { checkNotNull(ctx, "Precondition violation - argument 'ctx' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkNotNull(attribute, "Precondition violation - argument 'attribute' must not be NULL!"); // make sure that we actually HAVE a vertex for the EObject Vertex vertex = this.getOrCreatePlainVertexForEObject(ctx, eObject); ChronoEPackageRegistry cep = ctx.getChronoEPackage(); // check if we are dealing with a multiplicity-one or a multiplicity-many feature if (attribute.isMany()) { // multiplicity-many feature Collection<?> values = (Collection<?>) eObject.eGet(attribute); ChronoSphereGraphFormat.setEAttributeValues(cep, vertex, attribute, values); } else { // multiplicity-one feature Object value = eObject.eGet(attribute); ChronoSphereGraphFormat.setEAttributeValue(cep, vertex, attribute, value); } } @Override public void mapEReferenceToGraph(final SphereTransactionContext ctx, final ChronoEObject eObject, final EReference reference) { checkNotNull(ctx, "Precondition violation - argument 'ctx' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); checkNotNull(reference, "Precondition violation - argument 'reference' must not be NULL!"); ChronoGraph graph = ctx.getGraph(); // make sure that we actually HAVE a vertex for the EObject Vertex vertex = this.getOrCreatePlainVertexForEObject(ctx, eObject); // prepare the ChronoEPackage for later use ChronoEPackageRegistry cep = ctx.getChronoEPackage(); // calculate the label for the reference String label = ChronoSphereGraphFormat.createReferenceEdgeLabel(cep, reference); // check if we are dealing with a multiplicity-one or a multiplicity-many reference if (reference.isMany() == false) { // get the target of the reference ChronoEObject target = (ChronoEObject) eObject.eGet(reference, true); Vertex targetVertex = ChronoSphereGraphFormat.getVertexForEObject(graph, target); // make sure that an edge exists between the source and target vertices GremlinUtils.setEdgeTarget(vertex, label, targetVertex); } else { // get the targets of the reference @SuppressWarnings("unchecked") List<ChronoEObject> targets = (List<ChronoEObject>) eObject.eGet(reference, true); // FIXME CORRECTNESS: what if the EReference is non-unique!? // resolve the target vertices Map<ChronoEObject, Vertex> targetEObjectToVertex = Maps.newHashMap(); for (ChronoEObject target : targets) { Vertex targetVertex = ChronoSphereGraphFormat.getVertexForEObject(graph, target); targetEObjectToVertex.put(target, targetVertex); } // set the target vertices GremlinUtils.setEdgeTargets(vertex, label, Sets.newHashSet(targetEObjectToVertex.values())); if (reference.isOrdered()) { // assign ordering properties int orderIndex = 0; for (ChronoEObject target : targets) { // get the vertex that represents this target Vertex targetVertex = targetEObjectToVertex.get(target); // get the edge between source and target Edge edge = GremlinUtils.getEdge(vertex, label, targetVertex); // set the order ChronoSphereGraphFormat.setEReferenceEdgeOrder(edge, orderIndex); orderIndex++; } } } } @Override public void mapEContainerReferenceToGraph(final SphereTransactionContext ctx, final ChronoEObject eObject) { checkNotNull(ctx, "Precondition violation - argument 'ctx' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); ChronoGraph graph = ctx.getGraph(); // make sure that we actually HAVE a vertex for the EObject Vertex vertex = this.getOrCreatePlainVertexForEObject(ctx, eObject); // get the EContainer ChronoEObject eContainer = (ChronoEObject) eObject.eContainer(); // get the vertex for the eContainer Vertex eContainerVertex = ChronoSphereGraphFormat.getVertexForEObject(graph, eContainer); // get the label String label = ChronoSphereGraphFormat.createEContainerReferenceEdgeLabel(); // assign the edge target GremlinUtils.setEdgeTarget(vertex, label, eContainerVertex); } @Override public void mapEClassReferenceToGraph(final SphereTransactionContext ctx, final ChronoEObject eObject) { checkNotNull(ctx, "Precondition violation - argument 'ctx' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); // make sure that we actually HAVE a vertex for the EObject Vertex vertex = this.getOrCreatePlainVertexForEObject(ctx, eObject); // get the ChronoEPackage that contains the EClass-to-ID mapping ChronoEPackageRegistry cep = ctx.getChronoEPackage(); // get the EClass from the EObject EClass eClass = eObject.eClass(); // fetch the ID String eClassId = cep.getEClassID(eClass); // set the property value vertex.property(ChronoSphereGraphFormat.V_PROP__ECLASS_ID, eClassId); } }
8,923
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEPackageRegistry.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/ChronoEPackageRegistry.java
package org.chronos.chronosphere.internal.ogm.api; import static com.google.common.base.Preconditions.*; import java.util.Set; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; public interface ChronoEPackageRegistry { public boolean existsEPackage(String namespaceURI); public EPackage getEPackage(String namespaceURI); public Set<EClass> getEClasses(); public EClass getEClassByID(String chronoEClassID); public String getEClassID(EClass eClass); public EAttribute getEAttributeByID(String chronoEAttributeID); public String getEAttributeID(EAttribute eAttribute); public EReference getEReferenceByID(String chronoEReferenceID); public String getEReferenceID(EReference eReference); public Set<EPackage> getEPackages(); @SuppressWarnings("unchecked") public default <T extends EStructuralFeature> T getRegisteredEStructuralFeature(final T eStructuralFeature) { checkNotNull(eStructuralFeature, "Precondition violation - argument 'eStructuralFeature' must not be NULL!"); if (eStructuralFeature instanceof EAttribute) { EAttribute eAttribute = (EAttribute) eStructuralFeature; String id = this.getEAttributeID(eAttribute); if (id == null) { return null; } return (T) this.getEAttributeByID(id); } else if (eStructuralFeature instanceof EReference) { EReference eReference = (EReference) eStructuralFeature; String id = this.getEReferenceID(eReference); if (id == null) { return null; } return (T) this.getEReferenceByID(id); } else { throw new IllegalArgumentException( "Unknown subclass of EStructuralFeature: '" + eStructuralFeature.getClass().getName() + "'!"); } } }
1,814
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
VertexKind.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/VertexKind.java
package org.chronos.chronosphere.internal.ogm.api; import static com.google.common.base.Preconditions.*; public enum VertexKind { EOBJECT("eObject"), ECLASS("eClass"), EATTRIBUTE("eAttribute"), EREFERENCE("eReference"), EPACKAGE( "ePackage"), EPACKAGE_REGISTRY("ePackageRegistry"), EPACKAGE_BUNDLE("ePackageBundle"); // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final String literal; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== private VertexKind(final String literal) { checkNotNull(literal, "Precondition violation - argument 'literal' must not be NULL!"); this.literal = literal; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public String toString() { return this.literal; } public static VertexKind fromString(final String literal) { checkNotNull(literal, "Precondition violation - argument 'literal' must not be NULL!"); String string = literal.trim(); for (VertexKind kind : VertexKind.values()) { if (kind.literal.equalsIgnoreCase(string)) { return kind; } } return null; } }
1,692
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
GraphToEcoreMapper.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/GraphToEcoreMapper.java
package org.chronos.chronosphere.internal.ogm.api; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.eclipse.emf.ecore.EObject; public interface GraphToEcoreMapper { // ===================================================================================================================== // LOAD METHODS // ===================================================================================================================== public EObject mapVertexToEObject(Vertex vertex); }
500
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EPackageBundle.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/EPackageBundle.java
package org.chronos.chronosphere.internal.ogm.api; import static com.google.common.base.Preconditions.*; import java.util.List; import org.chronos.chronosphere.internal.ogm.impl.EPackageBundleImpl; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EcorePackage; /** * An {@link EPackageBundle} is a collection of {@link EPackage}s that is self-contained, i.e. does not reference any * elements that are not contained in the bundle. * * <p> * The {@link EcorePackage} is an implicit member of any {@link EPackageBundle}. It will not be contained in * {@link #getContents()}, and will not be returned by the {@linkplain #iterator() iterator}. * * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface EPackageBundle extends Iterable<EPackage> { // ===================================================================================================================== // FACTORY METHODS // ===================================================================================================================== /** * Creates and returns a new {@link EPackageBundle}, consisting of the given EPackages. * * @param ePackages * The EPackages to be contained in the new bundle. Must not be <code>null</code>, must not be empty. * @return The newly created bundle. Never <code>null</code>. */ public static EPackageBundle of(final Iterable<? extends EPackage> ePackages) { checkNotNull(ePackages, "Precondition violation - argument 'ePackages' must not be NULL!"); checkArgument(ePackages.iterator().hasNext(), "Precondition violation - argument 'EPackages' must not be empty!"); return new EPackageBundleImpl(ePackages); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== /** * Returns a list of {@link EPackage}s that are contained in this bundle. * * @return An unmodifiable view on the EPackages contained in this bundle. */ public List<EPackage> getContents(); /** * Checks if this bundle contains an {@link EPackage} with the given {@linkplain EPackage#getNsURI() namespace URI}. * * <p> * This method will only check the root-level EPackages, sub-packages will <b>not</b> be checked. * * @param ePackageNsURI * The namespace URI to find. Must not be <code>null</code>. * * @return <code>true</code> if this bundle contains an EPackage with the given namespace URI, otherwise * <code>false</code>. */ public default boolean containsEPackageWithNsURI(final String ePackageNsURI) { checkNotNull(ePackageNsURI, "Precondition violation - argument 'ePackageNsURI' must not be NULL!"); return this.getEPackageByNsURI(ePackageNsURI) != null; } /** * Returns a contained {@link EPackage} by its {@linkplain EPackage#getNsURI() namespace URI}. * * <p> * This method will only check the root-level EPackages, sub-packages will <b>not</b> be checked. * * @param ePackageNsURI * The namespace URI to get the EPackage for. Must not be <code>null</code>. * * @return The EPackage with the given namespace URI, or <code>null</code> if this bundle contains no such EPackage. */ public EPackage getEPackageByNsURI(String ePackageNsURI); }
3,433
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectToGraphMapper.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/EObjectToGraphMapper.java
package org.chronos.chronosphere.internal.ogm.api; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.internal.api.SphereTransactionContext; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EReference; public interface EObjectToGraphMapper { public Vertex getOrCreatePlainVertexForEObject(SphereTransactionContext ctx, ChronoEObject eObject); public void mapAllEObjectPropertiesToGraph(SphereTransactionContext ctx, ChronoEObject eObject); public void mapAllEObjectReferencesToGraph(SphereTransactionContext ctx, ChronoEObject eObject); public void mapEAttributeToGraph(SphereTransactionContext ctx, ChronoEObject eObject, EAttribute attribute); public void mapEReferenceToGraph(SphereTransactionContext ctx, ChronoEObject eObject, EReference reference); public void mapEContainerReferenceToGraph(SphereTransactionContext ctx, ChronoEObject eObject); public void mapEClassReferenceToGraph(SphereTransactionContext ctx, ChronoEObject eObject); }
1,073
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoEPackageRegistryInternal.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/ChronoEPackageRegistryInternal.java
package org.chronos.chronosphere.internal.ogm.api; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; public interface ChronoEPackageRegistryInternal extends ChronoEPackageRegistry { public void registerEPackage(final EPackage ePackage); public void registerEClassID(final EClass eClass, final String chronoEClassID); public void registerEAttributeID(final EAttribute eAttribute, final String chronoEAttributeID); public void registerEReferenceID(final EReference eReference, final String chronoEReferenceID); public void seal(); }
651
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereGraphFormat.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/ChronoSphereGraphFormat.java
package org.chronos.chronosphere.internal.ogm.api; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.exceptions.EObjectPersistenceException; import org.chronos.chronosphere.api.exceptions.StorageBackendCorruptedException; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.internal.util.EMFUtils; import org.chronos.chronosphere.internal.ogm.impl.GremlinUtils; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.ENamedElement; 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 java.util.Collection; import java.util.Collections; 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 ChronoSphereGraphFormat { // ===================================================================================================================== // CONSTANTS // ===================================================================================================================== /** * The vertex property that contains the vertex kind. Value is one of the {@link VertexKind} literals. */ public static final String V_PROP__KIND = "kind"; /** * the vertex property that contains the ID of the EClass. */ public static final String V_PROP__ECLASS_ID = "eClass"; /** * The common prefix for vertex properties that represent {@link EAttribute} values. */ public static final String V_PROP_PREFIX__EATTRIBUTE_VALUE = "eAttr_"; /** * The vertex property that contains the {@linkplain EPackage#getNsURI() namespace URI} of an {@link EPackage}. */ public static final String V_PROP__NS_URI = "nsURI"; /** * The vertex property that contains the {@linkplain EPackage#getNsPrefix() namespace prefix} of an {@link EPackage} * . */ public static final String V_PROP__NS_PREFIX = "nsPrefix"; /** * The vertex property that contains the {@linkplain ENamedElement#getName() name} of {@link EPackage}s, * {@link EClass}es and {@link EStructuralFeature}s. */ public static final String V_PROP__NAME = "name"; /** * The vertex property that allows a {@link Vertex} representing an {@link EPackage} to hold the XMI contents of the * EPackage. */ public static final String V_PROP__XMI_CONTENTS = "xmiContents"; /** * The vertex property that holds the numeric Ecore ID of the {@link EObject#eContainingFeature()}. */ public static final String V_PROP__ECONTAININGFEATUREID = "eContainingFeatureID"; /** * The edge label that marks the connections between the central EPackage Registry and the registered bundles. */ public static final String E_LABEL__EPACKAGE_REGISTRY_OWNED_BUNDLE = "ownedBundle"; /** * The edge label that marks the connections between an EPackage Bundle and its contained EPackages. */ public static final String E_LABEL__BUNDLE_OWNED_EPACKAGE = "ownedEPackage"; /** * The edge label that marks the "eContainer" reference. */ public static final String E_LABEL__ECONTAINER = "eContainer"; /** * The label for edges that connect an {@link EClass} vertex to the owning {@link EPackage} vertex. */ public static final String E_LABEL__EPACKAGE_OWNED_CLASSIFIERS = "classifier"; /** * The label for edges that connect an {@link EClass} vertex to an owned {@link EAttribute} vertex. */ public static final String E_LABEL__ECLASS_OWNED_EATTRIBUTE = "eAttribute"; /** * The label for edges that connect an {@link EClass} vertex to an owned {@link EReference} vertex. */ public static final String E_LABEL__ECLASS_OWNED_EREFERENCE = "eReference"; /** * The label for edges that connect an {@link EClass} vertex to one of its {@link EClass#getESuperTypes() supertype} * vertices. */ public static final String E_LABEL__ECLASS_ESUPERTYPE = "eSuperType"; /** * The label for edges that connect an {@link EPackage} vertex with the vertices representing the sub-EPackages. */ public static final String E_LABEL__ESUBPACKAGE = "eSubPackage"; /** * The common prefix for labels on edges that represent {@link EReference} links. */ public static final String E_LABEL_PREFIX__EREFERENCE = "eRef_"; /** * The edge property that contains the ordering for multiplicity-many {@link EReference} links. */ public static final String E_PROP__ORDER = "eRefOrder"; public static final String V_ID__EPACKAGE_REGISTRY = "EPackageRegistry_ca68f96b-676c-49de-a260-ac6628a7c455"; /** * Graph Variable Name: The version of the graph format used by this instance. */ public static final String VARIABLES__GRAPH_FORMAT_VERSION = "chronosphere.graphformat.version"; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= private ChronoSphereGraphFormat() { throw new UnsupportedOperationException("Do not instantiate this class!"); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== /** * Returns the {@linkplain VertexKind kind} of the vertex. * * @param vertex The vertex to check. Must not be <code>null</code>. * @return The vertex kind, or <code>null</code> if no kind is set. */ public static VertexKind getVertexKind(final Vertex vertex) { checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); String vertexKind = (String) vertex.property(V_PROP__KIND).orElse(null); return VertexKind.fromString(vertexKind); } /** * Sets the {@linkplain VertexKind kind} of the vertex. * * @param vertex The vertex to assign the new vertex kind to. Must not be <code>null</code>. * @param kind The vertex kind to assign to the vertex. Must not be <code>null</code>. */ public static void setVertexKind(final Vertex vertex, final VertexKind kind) { checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkNotNull(kind, "Precondition violation - argument 'kind' must not be NULL!"); vertex.property(V_PROP__KIND, kind.toString()); } /** * Creates the {@link Property} key for a {@link Vertex} that needs to store a value for the given * {@link EAttribute}. * * @param registry The {@link ChronoEPackageRegistry} to use. Must not be <code>null</code>. * @param eAttribute The EAttribute to generate the property key for. Must not be <code>null</code>. * @return The property key. Never <code>null</code>. */ public static String createVertexPropertyKey(final ChronoEPackageRegistry registry, final EAttribute eAttribute) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); String featureID = registry.getEAttributeID(eAttribute); if (featureID == null) { throw new IllegalStateException("Could not generate Vertex Property Key for EAttribute '" + eAttribute.getName() + "'! Did you forget to register or update an EPackage?"); } return V_PROP_PREFIX__EATTRIBUTE_VALUE + featureID; } /** * Creates the label for an {@link Edge} that represents an instance of the given {@link EReference}. * * @param registry The {@link ChronoEPackageRegistry} to use. Must not be <code>null</code>. * @param eReference The EReference to generate the edge label for. Must not be <code>null</code>. * @return The edge label. Never <code>null</code>. */ public static String createReferenceEdgeLabel(final ChronoEPackageRegistry registry, final EReference eReference) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); String eReferenceID = registry.getEReferenceID(eReference); if (eReferenceID == null) { throw new IllegalStateException("Could not generate Edge Label for EReference '" + eReference.getName() + "'! Did you forget to register or update an EPackage?"); } return E_LABEL_PREFIX__EREFERENCE + eReferenceID; } /** * Creates and returns the edge label for the {@link ChronoEObject#eContainer() eContainer} reference edge. * * @return The edge label for the eContainer reference edge. Never <code>null</code>. */ public static String createEContainerReferenceEdgeLabel() { return E_LABEL__ECONTAINER; } /** * Sets the given multiplicity-many {@linkplain EAttribute attribute} value in the given {@link Vertex}. * * @param registry The {@link ChronoEPackageRegistry} to use. Must not be <code>null</code>. * @param vertex The vertex to write the values to. Must not be <code>null</code>. * @param attribute The attribute to write. Must not be <code>null</code>, must be {@linkplain EAttribute#isMany() * many-valued}. * @param values The collection of values to assign to the vertex property. May be <code>null</code> or empty to clear * the property. * @return The modified property, or <code>null</code> if the property was cleared. */ public static Property<?> setEAttributeValues(final ChronoEPackageRegistry registry, final Vertex vertex, final EAttribute attribute, final Collection<?> values) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkNotNull(attribute, "Precondition violation - argument 'attribute' must not be NULL!"); checkArgument(attribute.isMany(), "Precondition violation - argument 'attribute' is multiplicity-one!"); // generate the property key String propertyKey = createVertexPropertyKey(registry, attribute); if (values == null || values.isEmpty()) { // we don't have any values for this attribute; delete the property vertex.property(propertyKey).remove(); return null; } else { // create a duplicate of the values collection such that we have a "clean" value to persist, // i.e. we don't want to store an EList or anything that is a notifier or has some EMF connectoins. Collection<?> valueToStore = Lists.newArrayList(values).stream() // for each entry, convert it into a persistable form .map(value -> convertSingleEAttributeValueToPersistableObject(attribute, value)) // collect the results in a list .collect(Collectors.toList()); // store the value in the vertex vertex.property(propertyKey, valueToStore); return vertex.property(propertyKey); } } /** * Returns the values for the given multiplicity-many {@linkplain EAttribute attribute} in the given {@link Vertex}. * * @param registry The {@link ChronoEPackageRegistry} to use. Must not be <code>null</code>. * @param vertex The vertex to read the value from. Must not be <code>null</code>. * @param attribute The attribute to read from the vertex. Must not be <code>null</code>, must be * {@linkplain EAttribute#isMany() many-valued}. * @return The collection of values assigned to the vertex for the given attribute. May be empty, but never * <code>null</code>. */ public static Collection<?> getEAttributeValues(final ChronoEPackageRegistry registry, final Vertex vertex, final EAttribute attribute) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkNotNull(attribute, "Precondition violation - argument 'attribute' must not be NULL!"); checkArgument(attribute.isMany(), "Precondition violation - argument 'attribute' is multiplicity-one!"); // generate the property key String propertyKey = createVertexPropertyKey(registry, attribute); // extract the value from the vertex Collection<?> storedValue = (Collection<?>) vertex.property(propertyKey).orElse(Lists.newArrayList()); List<?> resultList = storedValue.stream() // for each entry, convert it back from the persistable format into the EObject format .map(value -> convertSinglePersistableObjectToEAttributeValue(attribute, attribute)) // collect the results in a list .collect(Collectors.toList()); // return the result return Collections.unmodifiableCollection(resultList); } /** * Sets the given multiplicity-one {@linkplain EAttribute attribute} value in the given {@link Vertex}. * * @param registry The {@link ChronoEPackageRegistry} to use. Must not be <code>null</code>. * @param vertex The vertex to write the value to. Must not be <code>null</code>. * @param attribute The attribute to write. Must not be <code>null</code>, must not be {@linkplain EAttribute#isMany() * many-valued}. * @param value The value to assign to the vertex property. May be <code>null</code> or empty to clear the property. * @return The modified property, or <code>null</code> if the property was cleared. */ public static Property<?> setEAttributeValue(final ChronoEPackageRegistry registry, final Vertex vertex, final EAttribute attribute, final Object value) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkNotNull(attribute, "Precondition violation - argument 'attribute' must not be NULL!"); checkArgument(!attribute.isMany(), "Precondition violation - argument 'attribute' is multiplicity-many!"); // generate the property key String propertyKey = createVertexPropertyKey(registry, attribute); if (value != null) { // store the value in the vertex Object persistentValue = convertSingleEAttributeValueToPersistableObject(attribute, value); vertex.property(propertyKey, persistentValue); return vertex.property(propertyKey); } else { // no value given; clear the property vertex.property(propertyKey).remove(); return null; } } /** * Returns the value for the given multiplicity-one {@linkplain EAttribute attribute} in the given {@link Vertex}. * * @param registry The {@link ChronoEPackageRegistry} to use. Must not be <code>null</code>. * @param vertex The vertex to read the value from. Must not be <code>null</code>. * @param attribute The attribute to read from the vertex. Must not be <code>null</code>, must not be * {@linkplain EAttribute#isMany() many-valued}. * @return The value assigned to the vertex for the given attribute. May be <code>null</code> if no value is set on * the vertex for the given attribute. */ public static Object getEAttributeValue(final ChronoEPackageRegistry registry, final Vertex vertex, final EAttribute attribute) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkNotNull(attribute, "Precondition violation - argument 'attribute' must not be NULL!"); checkArgument(!attribute.isMany(), "Precondition violation - argument 'attribute' is multiplicity-many!"); // generate the property key String propertyKey = createVertexPropertyKey(registry, attribute); // fetch the value Object persistentValue = vertex.property(propertyKey).orElse(null); return convertSinglePersistableObjectToEAttributeValue(attribute, persistentValue); } /** * Sets the <code>order</code> property of the given {@link Edge} that represents an {@link EReference} link to the * given value. * * @param edge The edge to set the order index for. Must not be <code>null</code>. * @param orderIndex The oder index to set. Must not be negative. */ public static void setEReferenceEdgeOrder(final Edge edge, final int orderIndex) { checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!"); checkArgument(orderIndex >= 0, "Precondition violation - argument 'orderIndex' must not be negative!"); edge.property(E_PROP__ORDER, orderIndex); } /** * Returns the <code>order</code> property of the given {@link Edge} that represents an {@link EReference} link. * * @param edge The edge to get the order property for. Must not be <code>null</code>. * @return The order, as an integer. If no order is set, -1 will be returned. */ public static int getEReferenceEdgeOrder(final Edge edge) { checkNotNull(edge, "Precondition violation - argument 'edge' must not be NULL!"); return (int) edge.property(E_PROP__ORDER).orElse(-1); } /** * Returns the single target of the given {@link EReference} on the given {@link EObject} vertex. * * @param registry The {@linkplain ChronoEPackageRegistry package} to work with. Must not be <code>null</code>. * @param eObjectVertex The vertex that represents the EObject to get the reference target for. Must not be <code>null</code>. * @param eReference The EReference to get the target for. Must not be <code>null</code>. Must not be many-valued. * @return The target vertex, or <code>null</code> if none is set. */ public static Vertex getEReferenceTarget(final ChronoEPackageRegistry registry, final Vertex eObjectVertex, final EReference eReference) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(eObjectVertex, "Precondition violation - argument 'eObjectVertex' must not be NULL!"); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); checkArgument(!eReference.isMany(), "Precondition violation - argument 'eReference' must not be many-valued!"); String edgeLabel = createReferenceEdgeLabel(registry, eReference); Iterator<Vertex> targets = eObjectVertex.vertices(Direction.OUT, edgeLabel); if (!targets.hasNext()) { return null; } Vertex target = targets.next(); if (targets.hasNext()) { throw new IllegalStateException("Found multiple targets for EObject '" + eObjectVertex.id() + "#" + eReference.getName() + " (multiplicity one)!"); } return target; } /** * Returns the targets of the given {@link EReference} on the given {@link EObject} vertex. * * @param registry The {@linkplain ChronoEPackageRegistry package} to work with. Must not be <code>null</code>. * @param eObjectVertex The vertex that represents the EObject to get the reference target for. Must not be <code>null</code>. * @param eReference The EReference to get the target for. Must not be <code>null</code>. Must be many-valued. * @return The target vertices (in the correct order), or <code>null</code> if none is set. */ public static List<Vertex> getEReferenceTargets(final ChronoEPackageRegistry registry, final Vertex eObjectVertex, final EReference eReference) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(eObjectVertex, "Precondition violation - argument 'eObjectVertex' must not be NULL!"); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); checkArgument(eReference.isMany(), "Precondition violation - argument 'eReference' must be many-valued!"); String edgeLabel = createReferenceEdgeLabel(registry, eReference); if (eReference.isOrdered()) { // get the reference edges (as they contain the ordering) List<Edge> edges = Lists.newArrayList(eObjectVertex.edges(Direction.OUT, edgeLabel)); // sort the edges by their ordering edges.sort((e1, e2) -> { int order1 = getEReferenceEdgeOrder(e1); int order2 = getEReferenceEdgeOrder(e2); return Integer.compare(order1, order2); }); // for each edge, get the target vertex return edges.stream().map(edge -> edge.inVertex()).collect(Collectors.toList()); } else { return Lists.newArrayList(eObjectVertex.vertices(Direction.OUT, edgeLabel)); } } /** * Sets the target of the given {@link EReference} on the given {@link EObject} vertex to the given target vertex. * * @param registry The {@linkplain ChronoEPackageRegistry package} to work with. Must not be <code>null</code>. * @param eObjectVertex The vertex representing the EObject to change the reference target for (i.e. the reference owner). * Must not be <code>null</code>. * @param eReference The EReference to set. Must not be <code>null</code>, must not be many-valued. * @param target The vertex representing the target EObject. May be <code>null</code> to clear the reference. */ public static void setEReferenceTarget(final ChronoEPackageRegistry registry, final Vertex eObjectVertex, final EReference eReference, final Vertex target) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(eObjectVertex, "Precondition violation - argument 'eObjectVertex' must not be NULL!"); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); checkArgument(!eReference.isMany(), "Precondition violation - argument 'eReference' must not be many-valued!"); String edgeLabel = createReferenceEdgeLabel(registry, eReference); if (target == null) { // remove the edge(s) eObjectVertex.edges(Direction.OUT, edgeLabel).forEachRemaining(Edge::remove); } else { // set the edges GremlinUtils.setEdgeTarget(eObjectVertex, edgeLabel, target); } } /** * Sets the target of the given {@link EReference} on the given {@link EObject} vertex to the given target vertices. * * @param registry The {@linkplain ChronoEPackageRegistry package} to work with. Must not be <code>null</code>. * @param eObjectVertex The vertex representing the EObject to change the reference target for (i.e. the reference owner). * Must not be <code>null</code>. * @param eReference The EReference to set. Must not be <code>null</code>, must be many-valued. * @param targets The vertices representing the target EObjects. May be <code>null</code> or empty to clear the * reference. */ public static void setEReferenceTargets(final ChronoEPackageRegistry registry, final Vertex eObjectVertex, final EReference eReference, final List<Vertex> targets) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(eObjectVertex, "Precondition violation - argument 'eObjectVertex' must not be NULL!"); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); checkArgument(eReference.isMany(), "Precondition violation - argument 'eReference' must be many-valued!"); String edgeLabel = createReferenceEdgeLabel(registry, eReference); if (targets == null || targets.isEmpty()) { // remove the edge(s) eObjectVertex.edges(Direction.OUT, edgeLabel).forEachRemaining(Edge::remove); } else { // set the targets List<Edge> edges = GremlinUtils.setEdgeTargets(eObjectVertex, edgeLabel, targets); int order = 0; for (Edge edge : edges) { setEReferenceEdgeOrder(edge, order); order++; } } } /** * Returns the {@link Vertex} that represents the given {@link EClass} in the given {@link ChronoGraph graph}. * * @param registry The {@link ChronoEPackageRegistry} to use. Must not be <code>null</code>. * @param graph The graph to search in. Must not be <code>null</code>. * @param eClass The EClass to get the vertex for. Must not be <code>null</code>. * @return The vertex that represents the given EClass, or <code>null</code> if there is no such vertex. */ public static Vertex getVertexForEClass(final ChronoEPackageRegistry registry, final ChronoGraph graph, final EClass eClass) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); String id = registry.getEClassID(eClass); if (id == null) { throw new IllegalStateException( "There is no ID for EClass '" + eClass.getName() + "'! Did you forget to register an EPackage?"); } Iterator<Vertex> vertices = graph.vertices(id); if (vertices == null || !vertices.hasNext()) { return null; } return Iterators.getOnlyElement(vertices); } /** * Attempts to find the {@link Vertex} that represents the given {@link EClass} in the graph. * <p> * <p> * In contrast to {@link #getVertexForEClass(ChronoEPackageRegistry, ChronoGraph, EClass)}, this method does not * rely on IDs, but rather on the graph structure itself and on the name of the {@link EClass}. * <p> * <p> * This method should <b>not</b> be used outside of a package initialization process! * * @param graph The graph to search in. Must not be <code>null</code>. * @param eClass The EClass to search the vertex for. Must not be <code>null</code>. * @return The vertex that represents the given EClass, or <code>null</code> if no vertex is found. */ public static Vertex getVertexForEClassRaw(final ChronoGraph graph, final EClass eClass) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); Vertex ePackageVertex = getVertexForEPackage(graph, eClass.getEPackage()); if (ePackageVertex == null) { // ePackage is not mapped -> eClass can't be mapped return null; } Iterator<Vertex> eClassVertices = graph.traversal() // start at the ePackage .V(ePackageVertex) // follow the "owned classifiers" edges .out(E_LABEL__EPACKAGE_OWNED_CLASSIFIERS) // filter only EClass vertices .has(V_PROP__KIND, VertexKind.ECLASS.toString()) // filter the vertices by the name of the EClass .has(V_PROP__NAME, eClass.getName()); if (eClassVertices.hasNext() == false) { // no result found, eClass is not mapped return null; } return Iterators.getOnlyElement(eClassVertices); } /** * Returns the {@linkplain Vertex vertex} from the given {@linkplain ChronoGraph graph} that represents the given * {@linkplain ChronoEObject EObject}. * * @param graph The graph to search in. Must not be <code>null</code>. * @param eObject The EObject to search the vertex for. Must not be <code>null</code>. * @return The vertex for the EObject, or <code>null</code> if none was found. */ public static Vertex getVertexForEObject(final ChronoGraph graph, final ChronoEObject eObject) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); Iterator<Vertex> vertices = graph.vertices(eObject.getId()); if (vertices == null || vertices.hasNext() == false) { return null; } return Iterators.getOnlyElement(vertices); } /** * Returns the {@link Vertex} in the given {@link ChronoGraph} that represents the {@link ChronoEObject} with the * given ID. * * @param graph The graph to search in. Must not be <code>null</code>. * @param eObjectId The ID of the ChronoEObject to search for. Must not be <code>null</code>. * @return The vertex, or <code>null</code> if there is no ChronoEObject in the graph with the given ID. */ public static Vertex getVertexForEObject(final ChronoGraph graph, final String eObjectId) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(eObjectId, "Precondition violation - argument 'eObjectId' must not be NULL!"); Iterator<Vertex> iterator = graph.vertices(eObjectId); if (iterator == null || iterator.hasNext() == false) { return null; } return Iterators.getOnlyElement(iterator); } private static Vertex getOrCreateEPackageRegistryVertex(final ChronoGraph graph) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); Iterator<Vertex> vertices = graph.vertices(V_ID__EPACKAGE_REGISTRY); if (vertices == null || vertices.hasNext() == false) { // create the root epackage registry vertex Vertex vertex = graph.addVertex(T.id, V_ID__EPACKAGE_REGISTRY); setVertexKind(vertex, VertexKind.EPACKAGE_REGISTRY); return vertex; } else { return Iterators.getOnlyElement(vertices); } } /** * Returns the {@link Vertex} that represents the given {@link EPackage}. * * @param graph The graph to search in. Must not be <code>null</code>. * @param ePackage The ePackage to get the vertex for. Must not be <code>null</code>. * @return The vertex, or <code>null</code> if none exists. */ public static Vertex getVertexForEPackage(final ChronoGraph graph, final EPackage ePackage) { checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); Vertex ePackageRegistryVertex = getOrCreateEPackageRegistryVertex(graph); Iterator<Vertex> vertices = graph.traversal() // ePackages are reflected in the graph as vertices. Start at the EPackage Registry vertex .V(ePackageRegistryVertex) // go to the bundles .out(E_LABEL__EPACKAGE_REGISTRY_OWNED_BUNDLE) // go to the EPackages .out(E_LABEL__BUNDLE_OWNED_EPACKAGE) // we are only interested in EPackages .has(V_PROP__KIND, VertexKind.EPACKAGE.toString()) // the namespace URI and the namespace prefix must match .has(V_PROP__NS_URI, ePackage.getNsURI()).has(V_PROP__NS_PREFIX, ePackage.getNsPrefix()) // the epackage name must also match .has(V_PROP__NAME, ePackage.getName()); if (vertices.hasNext() == false) { // no EPackage vertex found return null; } // we should have exactly one vertex now return Iterators.getOnlyElement(vertices); } /** * Creates a vertex in the given graph for the given {@link EPackage}. * <p> * <p> * This method will also create the corresponding edges and set the appropriate vertex properties on the newly * created vertex. * * @param graph The graph to work on. Must not be <code>null</code>. * @param ePackage The EPackage to create the vertex for. Must not be <code>null</code>. Must not exist in the graph yet. * @return The newly created vertex. Never <code>null</code>. * @throws IllegalStateException Thrown if there is already a vertex in the graph for the given EPackage. */ public static Vertex createVertexForEPackage(final ChronoGraph graph, final EPackage ePackage) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(ePackage, "Precondition violation - argument 'ePackage' must not be NULL!"); if (getVertexForEPackage(graph, ePackage) != null) { throw new IllegalStateException("There already is a vertex for Root EPackage '" + ePackage.getName() + "' (URI: '" + ePackage.getNsURI() + "')!"); } Vertex ePackageVertex = graph.addVertex(T.id, UUID.randomUUID().toString()); setVertexKind(ePackageVertex, VertexKind.EPACKAGE); setVertexName(ePackageVertex, ePackage.getName()); setNsURI(ePackageVertex, ePackage.getNsURI()); setNsPrefix(ePackageVertex, ePackage.getNsPrefix()); if (ePackage.getESuperPackage() != null) { // we are dealing with a sub-package; create an edge to the parent package Vertex superPackageVertex = getVertexForEPackage(graph, ePackage.getESuperPackage()); if (superPackageVertex == null) { throw new IllegalArgumentException("EPackage '" + ePackage.getName() + "' (URI: '" + ePackage.getNsURI() + "') has no Vertex representation of its super EPackage!"); } superPackageVertex.addEdge(E_LABEL__ESUBPACKAGE, ePackageVertex); } return ePackageVertex; } /** * Creates a new {@link Vertex} for the given {@link EPackageBundle}. * * @param graph The graph to modify. Must not be <code>null</code>. * @param bundle The {@link EPackageBundle} to represent in the graph. Must not be <code>null</code>. * @return The newly created vertex representing the bundle. Never <code>null</code>. */ public static Vertex createVertexForEPackageBundle(final ChronoGraph graph, final EPackageBundle bundle) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(bundle, "Precondition violation - argument 'bundle' must not be NULL!"); Vertex bundleVertex = graph.addVertex(); setVertexKind(bundleVertex, VertexKind.EPACKAGE_BUNDLE); String xmi = EMFUtils.writeEPackagesToXMI(bundle); setXMIContents(bundleVertex, xmi); Vertex ePackageRegistryVertex = getOrCreateEPackageRegistryVertex(graph); ePackageRegistryVertex.addEdge(E_LABEL__EPACKAGE_REGISTRY_OWNED_BUNDLE, bundleVertex); return bundleVertex; } /** * Updates the contents of the {@link Vertex} to reflect the given {@link EPackageBundle}. * * @param bundleVertex The bundle vertex to update. Must not be <code>null</code>. * @param bundle The {@link EPackageBundle} to get the data from. Must not be <code>null</code>. */ public static void updateEPackageBundleVertex(final Vertex bundleVertex, final EPackageBundle bundle) { checkNotNull(bundleVertex, "Precondition violation - argument 'bundleVertex' must not be NULL!"); checkNotNull(bundle, "Precondition violation - argument 'bundle' must not be NULL!"); checkArgument(VertexKind.EPACKAGE_BUNDLE.equals(getVertexKind(bundleVertex)), "Precondition violation - argument 'bundleVertex' is not an EPackageBundle vertex!"); String xmi = EMFUtils.writeEPackagesToXMI(bundle); setXMIContents(bundleVertex, xmi); } /** * Sets the name of the given vertex to the given value. * <p> * <p> * Please note that not all vertices are meant to have a name. In particular, regular {@link EObject} vertices don't * use this property. It is meant primarily for meta-elements, such as vertices that represent {@link EPackage}s, * {@link EClass}es, {@link EAttribute}s and {@link EReference}s. * * @param vertex The vertex to set the name for. Must not be <code>null</code>. * @param name The name to assign to the vertex. May be <code>null</code> to clear the name. */ public static void setVertexName(final Vertex vertex, final String name) { checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); if (name == null) { // clear the name property vertex.property(V_PROP__NAME).remove(); } else { // set the name property vertex.property(V_PROP__NAME, name); } } /** * Sets the {@link EPackage#getNsURI() namespace URI} for the given {@link EPackage} vertex. * * @param ePackageVertex The vertex to modify. Must not be <code>null</code>. * @param nsURI The namespace URI to set. May be <code>null</code> to clear the namespace URI property. */ public static void setNsURI(final Vertex ePackageVertex, final String nsURI) { checkNotNull(ePackageVertex, "Precondition violation - argument 'ePackageVertex' must not be NULL!"); if (nsURI == null) { ePackageVertex.property(V_PROP__NS_URI).remove(); } else { ePackageVertex.property(V_PROP__NS_URI, nsURI); } } /** * Returns the {@link EPackage#getNsURI() namespace URI} stored in the given {@link EPackage} vertex. * * @param ePackageVertex The vertex to read the namespace URI from. Must not be <code>null</code>. * @return The namespace URI, or <code>null</code> if none is set. */ public static String getNsURI(final Vertex ePackageVertex) { checkNotNull(ePackageVertex, "Precondition violation - argument 'ePackageVertex' must not be NULL!"); return (String) ePackageVertex.property(V_PROP__NS_URI).orElse(null); } /** * Sets the {@link EPackage#getNsPrefix() namespace prefix} for the given {@link EPackage} vertex. * * @param ePackageVertex The vertex to modify. Must not be <code>null</code>. * @param nsPrefix The namespace prefix to set. May be <code>null</code> to clear the namespace Prefix property. */ public static void setNsPrefix(final Vertex ePackageVertex, final String nsPrefix) { checkNotNull(ePackageVertex, "Precondition violation - argument 'ePackageVertex' must not be NULL!"); if (nsPrefix == null) { ePackageVertex.property(V_PROP__NS_PREFIX).remove(); } else { ePackageVertex.property(V_PROP__NS_PREFIX, nsPrefix); } } /** * Returns the {@link EPackage#getNsPrefix() namespace Prefix} stored in the given {@link EPackage} vertex. * * @param ePackageVertex The vertex to read the namespace Prefix from. Must not be <code>null</code>. * @return The namespace Prefix, or <code>null</code> if none is set. */ public static String getNsPrefix(final Vertex ePackageVertex) { checkNotNull(ePackageVertex, "Precondition violation - argument 'ePackageVertex' must not be NULL!"); return (String) ePackageVertex.property(V_PROP__NS_PREFIX).orElse(null); } /** * Returns the name of the given vertex. * <p> * <p> * Please note that not all vertices are meant to have a name. In particular, regular {@link EObject} vertices don't * use this property. It is meant primarily for meta-elements, such as vertices that represent {@link EPackage}s, * {@link EClass}es, {@link EAttribute}s and {@link EReference}s. * * @param vertex The vertex to return the name property for. Must not be <code>null</code>. * @return The name, or <code>null</code> if the given vertex doesn't have a name assigned. */ public static String getVertexName(final Vertex vertex) { checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); return (String) vertex.property(V_PROP__NAME).orElse(null); } /** * Sets the XMI contents of the given {@link Vertex}. * <p> * <p> * Please note that this is intended exclusively for vertices that represent {@link EPackage}s. * * @param vertex The vertex to set the XMI contents for. Must not be <code>null</code>. * @param xmiContents The XMI contents to store in the vertex. May be <code>null</code> to clear. */ public static void setXMIContents(final Vertex vertex, final String xmiContents) { checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); if (xmiContents == null || xmiContents.trim().isEmpty()) { // clear the property vertex.property(V_PROP__XMI_CONTENTS).remove(); } else { // store the XMI contents vertex.property(V_PROP__XMI_CONTENTS, xmiContents); } } /** * Returns the XMI contents stored in the given {@link Vertex}. * <p> * <p> * Please note that this is intended exclusively for vertices that represent {@link EPackage}s. * * @param vertex The vertex to get the XMI data from. Must not be <code>null</code>. * @return The XMI data stored in the vertex, or <code>null</code> if the vertex contains no XMI data. */ public static String getXMIContents(final Vertex vertex) { checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); return (String) vertex.property(V_PROP__XMI_CONTENTS).orElse(null); } /** * Returns the {@link Vertex} that represents the given {@link EAttribute} and is attached to the given * {@link EClass} vertex. * * @param eClassVertex The vertex that represents the EClass that owns the EAttribute. Must not be <code>null</code>. * @param eAttribute The EAttribute to get the vertex for. Must not be <code>null</code>. * @return The vertex that represents the given EAttribute within the given EClass. May be <code>null</code> if no * vertex for the given EAttribute was found. */ public static Vertex getVertexForEAttributeRaw(final Vertex eClassVertex, final EAttribute eAttribute) { checkNotNull(eClassVertex, "Precondition violation - argument 'eClassVertex' must not be NULL!"); checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); Graph graph = eClassVertex.graph(); Iterator<Vertex> eAttributeVertices = graph.traversal() // start with the eClass vertex .V(eClassVertex) // follow the "owned eAttribute" label .out(E_LABEL__ECLASS_OWNED_EATTRIBUTE) // filter only EAttributes .has(V_PROP__KIND, VertexKind.EATTRIBUTE.toString()) // filter by name .has(V_PROP__NAME, eAttribute.getName()); if (eAttributeVertices.hasNext() == false) { // we did not find a vertex that represents the given EAttribute return null; } return Iterators.getOnlyElement(eAttributeVertices); } /** * Returns the {@link Vertex} that represents the given {@link EReference} and is attached to the given * {@link EClass} vertex. * * @param eClassVertex The vertex that represents the EClass that owns the EAttribute. Must not be <code>null</code>. * @param eReference The EReference to get the vertex for. Must not be <code>null</code>. * @return The vertex that represents the given EReference within the given EClass. May be <code>null</code> if no * vertex for the given EReference was found. */ public static Vertex getVertexForEReferenceRaw(final Vertex eClassVertex, final EReference eReference) { checkNotNull(eClassVertex, "Precondition violation - argument 'eClassVertex' must not be NULL!"); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); Graph graph = eClassVertex.graph(); Iterator<Vertex> eReferenceVertices = graph.traversal() // start with the eClass vertex .V(eClassVertex) // follow the "owned eReference" label .out(E_LABEL__ECLASS_OWNED_EREFERENCE) // filter only EReferences .has(V_PROP__KIND, VertexKind.EREFERENCE.toString()) // filter by name .has(V_PROP__NAME, eReference.getName()); if (eReferenceVertices.hasNext() == false) { // we did not find a vertex that represents the given EReference return null; } return Iterators.getOnlyElement(eReferenceVertices); } /** * Returns the {@link EClass} that acts as the classifier for the {@link EObject} represented by the given * {@link Vertex}. * * @param registry The {@linkplain ChronoEPackageRegistry package} to work with. Must not be <code>null</code>. * @param vertex The vertex representing the EObject to get the EClass for. Must not be <code>null</code>. * @return The EClass, or <code>null</code> if none is found. */ public static EClass getEClassForEObjectVertex(final ChronoEPackageRegistry registry, final Vertex vertex) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); String eClassID = (String) vertex.property(V_PROP__ECLASS_ID).orElse(null); EClass eClass = registry.getEClassByID(eClassID); return eClass; } /** * Sets the EClass for the EObject represented by the given vertex. * * @param registry The {@linkplain ChronoEPackageRegistry package} to work with. Must not be <code>null</code>. * @param vertex The vertex representing the EObject to set the EClass for. Must not be <code>null</code>. * @param eClass The eClass to use. Must be part of the given package. Must not be <code>null</code>. */ public static void setEClassForEObjectVertex(final ChronoEPackageRegistry registry, final Vertex vertex, final EClass eClass) { checkNotNull(registry, "Precondition violation - argument 'registry' must not be NULL!"); checkNotNull(vertex, "Precondition violation - argument 'vertex' must not be NULL!"); checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); ChronoGraph graph = (ChronoGraph) vertex.graph(); Vertex eClassVertex = getVertexForEClass(registry, graph, eClass); if (eClassVertex == null) { throw new IllegalStateException("There is no Vertex in the Graph representing EClass '" + eClass.getName() + "'!"); } vertex.property(V_PROP__ECLASS_ID, (String) eClassVertex.id()); } /** * Sets the {@link EObject#eContainer() eContainer()} of the {@link EObject} represented by the given source vertex * to the EObject represented by the given target vertex. * * @param sourceVertex The source vertex that should be relocated to the new container. Must not be <code>null</code>. * @param targetVertex The target vertex that should act as the new container. May be <code>null</code> to clear the * eContainer of the source vertex. */ public static void setEContainer(final Vertex sourceVertex, final Vertex targetVertex) { checkNotNull(sourceVertex, "Precondition violation - argument 'sourceVertex' must not be NULL!"); if (targetVertex == null) { sourceVertex.edges(Direction.OUT, E_LABEL__ECONTAINER).forEachRemaining(edge -> edge.remove()); } else { GremlinUtils.setEdgeTarget(sourceVertex, E_LABEL__ECONTAINER, targetVertex); } } /** * Returns the vertex representing the {@link EObject} that acts as the {@link EObject#eContainer() eContainer()} of * the given EObject. * * @param eObjectVertex The vertex that represents the eObject to get the eContainer for. Must not be <code>null</code>. * @return The vertex representing the EObject that is the eContainer of the given eObject. May be <code>null</code> * if no eContainer is present. */ public static Vertex getEContainer(final Vertex eObjectVertex) { checkNotNull(eObjectVertex, "Precondition violation - argument 'eObjectVertex' must not be NULL!"); return Iterators.getOnlyElement(eObjectVertex.vertices(Direction.OUT, E_LABEL__ECONTAINER), null); } /** * Sets the numeric Ecore ID of the {@linkplain EObject#eContainingFeature() eContainingFeature} on the EObject * represented by the given vertex. * * @param eObjectVertex The vertex representing the EObject where the eContainingFeatureID should be changed. Must not be * <code>null</code>. * @param containingFeatureId The new eContainingFeatureID to use. May be <code>null</code> to clear it. */ public static void setEContainingFeatureId(final Vertex eObjectVertex, final Integer containingFeatureId) { checkNotNull(eObjectVertex, "Precondition violation - argument 'eObjectVertex' must not be NULL!"); if (containingFeatureId == null) { eObjectVertex.property(V_PROP__ECONTAININGFEATUREID).remove(); } else { eObjectVertex.property(V_PROP__ECONTAININGFEATUREID, containingFeatureId); } } /** * Returns the numeric Ecore ID of the {@linkplain EObject#eContainingFeature() eContainingFeature} on the EObject * represented by the given vertex. * * @param eObjectVertex The vertex representing the EObject where the eContainingFeatureID should be retrieved. Must not be * <code>null</code>. * @return The eContainingFeatureID (which may be negative according to the Ecore standard), or <code>null</code> if * no eContainingFeatureID is set. */ public static Integer getEContainingFeatureId(final Vertex eObjectVertex) { checkNotNull(eObjectVertex, "Precondition violation - argument 'eObjectVertex' must not be NULL!"); return (Integer) eObjectVertex.property(V_PROP__ECONTAININGFEATUREID).orElse(null); } /** * Returns the {@link Vertex} that represents the root of the {@link EPackage} hierarchy that contains the * {@link EClass} represented by the given vertex. * * @param eClassVertex The vertex that represents the EClass. Must not be <code>null</code>. * @return The vertex that represents the root EPackage that contains the given EPackage vertex. Never * <code>null</code>. */ public static Vertex getRootEPackageVertexForEClassVertex(final Vertex eClassVertex) { checkNotNull(eClassVertex, "Precondition violation - argument 'ePackageVertex' must not be NULL!"); checkArgument(VertexKind.ECLASS.equals(getVertexKind(eClassVertex)), "Precondition violation - argument 'ePackageVertex' must have a VertexKind of ECLASS!"); Vertex ePackageVertex = getEPackageVertexForEClassVertex(eClassVertex); return getRootEPackageVertexForEPackageVertex(ePackageVertex); } /** * Returns the {@link Vertex} that represents the root of the {@link EPackage} hierarchy that contains the * {@link EPackage} represented by the given vertex. * * @param ePackageVertex The vertex that represents the EPackage. Must not be <code>null</code>. * @return The vertex that represents the root EPackage that contains the given EPackage vertex. Never * <code>null</code>. */ public static Vertex getRootEPackageVertexForEPackageVertex(final Vertex ePackageVertex) { checkNotNull(ePackageVertex, "Precondition violation - argument 'ePackageVertex' must not be NULL!"); checkArgument(VertexKind.EPACKAGE.equals(getVertexKind(ePackageVertex)), "Precondition violation - argument 'ePackageVertex' must have a VertexKind of EPACKAGE!"); Vertex v = ePackageVertex; // navigate upwards the containment hierarchy to find the root EPackage Iterator<Vertex> superPackageVertices = v.vertices(Direction.IN, E_LABEL__ESUBPACKAGE); while (superPackageVertices.hasNext()) { v = Iterators.getOnlyElement(superPackageVertices); superPackageVertices = v.vertices(Direction.IN, E_LABEL__ESUBPACKAGE); } return v; } /** * Returns the {@link Vertex} that represents the {@link EPackage} that contains the {@link EClass} represented by * the given vertex. * * @param eClassVertex The vertex that represents the EClass. Must not be <code>null</code>. * @return The vertex that represents the root EPackage that contains the given EClass vertex. Never * <code>null</code>. */ public static Vertex getEPackageVertexForEClassVertex(final Vertex eClassVertex) { checkNotNull(eClassVertex, "Precondition violation - argument 'eClassVertex' must not be NULL!"); checkArgument(VertexKind.ECLASS.equals(getVertexKind(eClassVertex)), "Precondition violation - argument 'eClassVertex' must have a VertexKind of ECLASS!"); Iterator<Vertex> owningEPackageVertices = eClassVertex.vertices(Direction.IN, E_LABEL__EPACKAGE_OWNED_CLASSIFIERS); if (owningEPackageVertices.hasNext() == false) { throw new StorageBackendCorruptedException( "The vertex that represents EClass " + getVertexName(eClassVertex) + " has no owning EPackage!"); } // get the EPackage vertex (may be a sub-package) Vertex ePackageVertex = Iterators.getOnlyElement(owningEPackageVertices); return ePackageVertex; } /** * Returns the set of {@linkplain Vertex vertices} that represent {@link EPackageBundle}s. * * @param graph The graph to search in. Must not be <code>null</code>. * @return The set of vertices that represent the mapped bundles. May be empty, but never <code>null</code>. */ public static Set<Vertex> getEpackageBundleVertices(final ChronoGraph graph) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); Set<Vertex> vertices = graph.traversal() // start with all vertices .V() // limit to the ones that have 'kind' equal to 'bundle' .has(V_PROP__KIND, VertexKind.EPACKAGE_BUNDLE.toString()) // put result into a set .toSet(); return vertices; } // ===================================================================================================================== // HELPER METHODS // ===================================================================================================================== private static Object convertSingleEAttributeValueToPersistableObject(final EAttribute eAttribute, final Object value) { if (value instanceof EEnumLiteral) { // for EEnumLiterals, we store the 'literal' representation EEnumLiteral enumLiteral = (EEnumLiteral) value; return enumLiteral.getLiteral(); } else { // all other types of attributes don't need conversions return value; } } private static Object convertSinglePersistableObjectToEAttributeValue(final EAttribute eAttribute, final Object value) { if (value == null) { // null is always null, conversions make no sense here return null; } if (eAttribute.getEAttributeType() instanceof EEnum) { // for EEnums, we store the 'literal' representation, so we have to convert back now EEnum eEnum = (EEnum) eAttribute.getEAttributeType(); if (value instanceof String == false) { throw new EObjectPersistenceException("Tried to deserialize value for EEnum-typed EAttribute '" + eAttribute.getEContainingClass().getName() + "#" + eAttribute.getName() + "', but the stored object (class: '" + value.getClass().getName() + "' is not a literal string: '" + value + "'!"); } EEnumLiteral enumLiteral = eEnum.getEEnumLiteralByLiteral((String) value); if (enumLiteral == null) { throw new EObjectPersistenceException("Tried to deserialize a value for EEnum-typed EAttribute '" + eAttribute.getEContainingClass().getName() + "#" + eAttribute.getName() + "', but the stored literal '" + value + "' has no representation in the EEnum '" + eEnum.getName() + "'!"); } return enumLiteral; } // anything else remains as-is return value; } }
59,282
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EPackageToGraphMapper.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/ogm/api/EPackageToGraphMapper.java
package org.chronos.chronosphere.internal.ogm.api; import org.chronos.chronograph.api.structure.ChronoGraph; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; /** * This class is a utility capable of mapping {@link EPackage}s to the graph, and reading the * {@link ChronoEPackageRegistry} from the graph. * * @author martin.haeusler@uibk.ac.at -- Initial Contribution and API * */ public interface EPackageToGraphMapper { /** * Maps the contents of the given {@link EPackageBundle} into the given {@link ChronoGraph}. * * <p> * After this operation, the contents of the graph will fully reflect the contents of the given * {@link EPackageBundle}. The graph will be adapted, the bundle is treated as read-only. * * <p> * <b>/!\ WARNING:</b> If an EClass or (sub-) package was removed, the instances will be deleted as well! * * @param graph * The graph to map the EPackageBundle into. Must not be <code>null</code>. Must be self-contained. * @param bundle * The bundle to synchronize with the graph. Will be treated as read-only. Must not be <code>null</code>. */ void mapToGraph(ChronoGraph graph, EPackageBundle bundle); /** * Reads the contents of the given {@link ChronoEPackageRegistry} from the graph. * * @param graph * The graph to read from. Must not be <code>null</code>. * @return The {@link ChronoEPackageRegistry}. Never <code>null</code>. */ public ChronoEPackageRegistry readChronoEPackageRegistryFromGraph(ChronoGraph graph); /** * Removes the graph representation of the given {@link EPackageBundle}, as well as all {@link EObject}s that are * instances of the classifiers contained within the bundle. * * <p> * This is an expensive operation. Use with care. * * @param graph * The graph to perform the deletion in. Must not be <code>null</code>. * @param bundle * The {@link EPackageBundle} to delete in the graph. Must not be <code>null</code>. */ public void deleteInGraph(ChronoGraph graph, EPackageBundle bundle); }
2,098
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractChronoSphereBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/builder/repository/impl/AbstractChronoSphereBuilder.java
package org.chronos.chronosphere.internal.builder.repository.impl; import org.chronos.common.builder.AbstractChronoBuilder; import org.chronos.common.builder.ChronoBuilder; public abstract class AbstractChronoSphereBuilder<SELF extends ChronoBuilder<?>> extends AbstractChronoBuilder<SELF> implements ChronoBuilder<SELF> { }
329
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereBaseBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/builder/repository/impl/ChronoSphereBaseBuilderImpl.java
package org.chronos.chronosphere.internal.builder.repository.impl; import static com.google.common.base.Preconditions.*; import java.io.File; import java.util.Properties; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.MapConfiguration; import org.chronos.chronosphere.api.builder.repository.ChronoSphereBaseBuilder; import org.chronos.chronosphere.api.builder.repository.ChronoSphereInMemoryBuilder; import org.chronos.chronosphere.api.builder.repository.ChronoSpherePropertyFileBuilder; public class ChronoSphereBaseBuilderImpl extends AbstractChronoSphereBuilder<ChronoSphereBaseBuilderImpl> implements ChronoSphereBaseBuilder { @Override public ChronoSphereInMemoryBuilder inMemoryRepository() { return new ChronoSphereInMemoryBuilderImpl(); } @Override public ChronoSpherePropertyFileBuilder fromPropertiesFile(final File file) { checkNotNull(file, "Precondition violation - argument 'file' must not be NULL!"); checkArgument(file.exists(), "Precondition violation - argument 'file' must refer to an existing file!"); checkArgument(file.isFile(), "Precondition violation - argument 'file' must refer to a file (not a directory)!"); return new ChronoSpherePropertyFileBuilderImpl(file); } @Override public ChronoSpherePropertyFileBuilder fromPropertiesFile(final String filePath) { checkNotNull(filePath, "Precondition violation - argument 'filePath' must not be NULL!"); File file = new File(filePath); return this.fromPropertiesFile(file); } @Override public ChronoSpherePropertyFileBuilder fromConfiguration(final Configuration configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); return new ChronoSpherePropertyFileBuilderImpl(configuration); } @Override public ChronoSpherePropertyFileBuilder fromProperties(final Properties properties) { checkNotNull(properties, "Precondition violation - argument 'properties' must not be NULL!"); Configuration configuration = new MapConfiguration(properties); return this.fromConfiguration(configuration); } }
2,126
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSpherePropertyFileBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/builder/repository/impl/ChronoSpherePropertyFileBuilderImpl.java
package org.chronos.chronosphere.internal.builder.repository.impl; import com.google.common.collect.Sets; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.chronos.chronosphere.api.builder.repository.ChronoSpherePropertyFileBuilder; import org.chronos.chronosphere.api.exceptions.ChronoSphereConfigurationException; import java.io.File; import java.io.FileReader; import java.util.Set; import static com.google.common.base.Preconditions.*; public class ChronoSpherePropertyFileBuilderImpl extends AbstractChronoSphereFinalizableBuilder<ChronoSpherePropertyFileBuilder> implements ChronoSpherePropertyFileBuilder { public ChronoSpherePropertyFileBuilderImpl(final File propertiesFile) { checkNotNull(propertiesFile, "Precondition violation - argument 'propertiesFile' must not be NULL!"); checkArgument(propertiesFile.exists(), "Precondition violation - argument 'propertiesFile' must refer to an existing file!"); checkArgument(propertiesFile.isFile(), "Precondition violation - argument 'propertiesFile' must refer to a file (not a directory)!"); try { PropertiesConfiguration configuration = new PropertiesConfiguration(); try(FileReader reader = new FileReader(propertiesFile)){ configuration.read(reader); } this.applyConfiguration(configuration); } catch (Exception e) { throw new ChronoSphereConfigurationException( "Failed to read properties file '" + propertiesFile.getAbsolutePath() + "'!", e); } } public ChronoSpherePropertyFileBuilderImpl(final Configuration configuration) { checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); try { this.applyConfiguration(configuration); } catch (Exception e) { throw new ChronoSphereConfigurationException("Failed to apply the given configuration'!", e); } } private void applyConfiguration(final Configuration configuration) { Set<String> keys = Sets.newHashSet(configuration.getKeys()); for (String key : keys) { this.withProperty(key, configuration.getProperty(key).toString()); } } }
2,153
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractChronoSphereFinalizableBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/builder/repository/impl/AbstractChronoSphereFinalizableBuilder.java
package org.chronos.chronosphere.internal.builder.repository.impl; import org.apache.commons.configuration2.Configuration; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration; import org.chronos.chronosphere.api.ChronoSphere; import org.chronos.chronosphere.api.builder.repository.ChronoSphereFinalizableBuilder; import org.chronos.chronosphere.impl.StandardChronoSphere; public abstract class AbstractChronoSphereFinalizableBuilder<SELF extends ChronoSphereFinalizableBuilder<?>> extends AbstractChronoSphereBuilder<SELF> implements ChronoSphereFinalizableBuilder<SELF> { @Override public ChronoSphere build() { // always disable auto-TX in the graph for ChronoSphere this.withProperty(ChronoGraphConfiguration.TRANSACTION_AUTO_OPEN, "false"); Configuration config = this.getPropertiesAsConfiguration(); ChronoGraph graph = ChronoGraph.FACTORY.create().fromConfiguration(config).build(); return new StandardChronoSphere(graph, config); } }
1,048
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereInMemoryBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/internal/builder/repository/impl/ChronoSphereInMemoryBuilderImpl.java
package org.chronos.chronosphere.internal.builder.repository.impl; import org.chronos.chronodb.inmemory.InMemoryChronoDB; import org.chronos.chronodb.internal.api.ChronoDBConfiguration; import org.chronos.chronosphere.api.builder.repository.ChronoSphereInMemoryBuilder; public class ChronoSphereInMemoryBuilderImpl extends AbstractChronoSphereFinalizableBuilder<ChronoSphereInMemoryBuilder> implements ChronoSphereInMemoryBuilder { public ChronoSphereInMemoryBuilderImpl() { this.withProperty(ChronoDBConfiguration.STORAGE_BACKEND, InMemoryChronoDB.BACKEND_NAME); } }
578
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereFactoryImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/ChronoSphereFactoryImpl.java
package org.chronos.chronosphere.impl; import org.chronos.chronosphere.api.ChronoSphereFactory; import org.chronos.chronosphere.api.builder.repository.ChronoSphereBaseBuilder; import org.chronos.chronosphere.internal.builder.repository.impl.ChronoSphereBaseBuilderImpl; public class ChronoSphereFactoryImpl implements ChronoSphereFactory { @Override public ChronoSphereBaseBuilder create() { return new ChronoSphereBaseBuilderImpl(); } }
447
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereEPackageManagerImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/ChronoSphereEPackageManagerImpl.java
package org.chronos.chronosphere.impl; import static com.google.common.base.Preconditions.*; import java.util.Iterator; import java.util.List; import java.util.Set; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.api.MetaModelEvolutionController; import org.chronos.chronosphere.api.MetaModelEvolutionIncubator; import org.chronos.chronosphere.emf.impl.ChronoEFactory; import org.chronos.chronosphere.impl.evolution.MetaModelEvolutionProcess; import org.chronos.chronosphere.internal.api.ChronoSphereEPackageManagerInternal; 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.EPackageBundle; import org.eclipse.emf.ecore.EPackage; import com.google.common.collect.Lists; public class ChronoSphereEPackageManagerImpl implements ChronoSphereEPackageManagerInternal { // ================================================================================================================= // FIELDS // ================================================================================================================= private ChronoSphereInternal owningSphere; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public ChronoSphereEPackageManagerImpl(final ChronoSphereInternal owningSphere) { checkNotNull(owningSphere, "Precondition violation - argument 'owningSphere' must not be NULL!"); this.owningSphere = owningSphere; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public void registerOrUpdateEPackages(final Iterator<? 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!"); // throw the EPackages into a collection List<EPackage> packages = Lists.newArrayList(); ePackages.forEachRemaining(pack -> packages.add(pack)); EPackageBundle bundle = EPackageBundle.of(packages); try (ChronoGraph txGraph = this.owningSphere.getRootGraph().tx().createThreadedTx(branchName)) { this.owningSphere.getEPackageToGraphMapper().mapToGraph(txGraph, bundle); txGraph.tx().commit(); } // make sure that the EPackage uses the correct EFactory packages.forEach(ePackage -> { ePackage.setEFactoryInstance(new ChronoEFactory()); }); } @Override public void deleteEPackages(final Iterator<? 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!"); // throw the EPackages into a collection List<EPackage> packages = Lists.newArrayList(); ePackages.forEachRemaining(pack -> packages.add(pack)); EPackageBundle bundle = EPackageBundle.of(packages); try (ChronoGraph txGraph = this.owningSphere.getRootGraph().tx().createThreadedTx(branchName)) { this.owningSphere.getEPackageToGraphMapper().deleteInGraph(txGraph, bundle); txGraph.tx().commit(); } } @Override public Set<EPackage> getRegisteredEPackages(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkArgument(this.owningSphere.getBranchManager().existsBranch(branchName), "Precondition violation - argument 'branchName' must refer to an existing branch!"); try (ChronoGraph txGraph = this.owningSphere.getRootGraph().tx().createThreadedTx(branchName)) { ChronoEPackageRegistry registry = this.owningSphere.getEPackageToGraphMapper() .readChronoEPackageRegistryFromGraph(txGraph); return registry.getEPackages(); } } @Override public void evolveMetamodel(final String branch, final MetaModelEvolutionController controller, final Iterable<? extends EPackage> newEPackages) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(controller, "Precondition violation - argument 'controller' must not be NULL!"); checkNotNull(newEPackages, "Precondition violation - argument 'newEPackages' must not be NULL!"); ChronoSphereInternal repo = this.owningSphere; MetaModelEvolutionProcess.execute(repo, branch, controller, newEPackages); } @Override public void evolveMetamodel(final String branch, final MetaModelEvolutionIncubator incubator, final Iterable<? extends EPackage> newEPackages) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkNotNull(incubator, "Precondition violation - argument 'incubator' must not be NULL!"); checkNotNull(newEPackages, "Precondition violation - argument 'newEPackages' must not be NULL!"); ChronoSphereInternal repo = this.owningSphere; MetaModelEvolutionProcess.execute(repo, branch, incubator, newEPackages); } // ================================================================================================================= // INTERNAL API // ================================================================================================================= @Override public void overrideEPackages(final ChronoSphereTransaction transaction, final Iterable<? extends EPackage> newEPackages) { checkNotNull(transaction, "Precondition violation - argument 'transaction' must not be NULL!"); checkNotNull(newEPackages, "Precondition violation - argument 'newEPackages' must not be NULL!"); ChronoSphereTransactionInternal tx = (ChronoSphereTransactionInternal) transaction; // get the graph ChronoGraph graph = tx.getGraph(); // create a bundle from the packages EPackageBundle bundle = EPackageBundle.of(newEPackages); // map them down this.owningSphere.getEPackageToGraphMapper().mapToGraph(graph, bundle); // reload them in the transaction tx.reloadEPackageRegistryFromGraph(); } }
6,497
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
SphereBranchImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/SphereBranchImpl.java
package org.chronos.chronosphere.impl; import static com.google.common.base.Preconditions.*; import java.util.List; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronograph.api.branch.GraphBranch; import org.chronos.chronosphere.api.SphereBranch; import com.google.common.collect.Lists; public class SphereBranchImpl implements SphereBranch { // ===================================================================================================================== // STATIC FACTORY METHODS // ===================================================================================================================== public static SphereBranchImpl createMasterBranch(final GraphBranch backingMasterBranch) { checkNotNull(backingMasterBranch, "Precondition violation - argument 'backingMasterBranch' must not be NULL!"); checkArgument(backingMasterBranch.getName().equals(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER), "Precondition violation - the backing branch is not the master branch!"); checkArgument(backingMasterBranch.getOrigin() == null, "Precondition violation - the backing branch is not the master branch!"); return new SphereBranchImpl(backingMasterBranch, null); } public static SphereBranchImpl createBranch(final GraphBranch backingBranch, final SphereBranch origin) { checkNotNull(backingBranch, "Precondition violation - argument 'backingMasterBranch' must not be NULL!"); checkNotNull(origin, "Precondition violation - argument 'origin' must not be NULL!"); checkArgument(backingBranch.getOrigin().getName().equals(origin.getName()), "Precondition violation - the arguments do not refer to the same branch!"); return new SphereBranchImpl(backingBranch, origin); } // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final GraphBranch backingBranch; private final SphereBranch origin; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== protected SphereBranchImpl(final GraphBranch backingBranch, final SphereBranch origin) { checkNotNull(backingBranch, "Precondition violation - argument 'backingBranch' must not be NULL!"); this.backingBranch = backingBranch; this.origin = origin; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public String getName() { return this.backingBranch.getName(); } @Override public SphereBranch getOrigin() { return this.origin; } @Override public long getBranchingTimestamp() { return this.backingBranch.getBranchingTimestamp(); } @Override public List<SphereBranch> getOriginsRecursive() { if (this.origin == null) { // we are the master branch; by definition, we return an empty list (see JavaDoc). return Lists.newArrayList(); } else { // we are not the master branch. Ask the origin to create the list for us List<SphereBranch> origins = this.getOrigin().getOriginsRecursive(); // ... and add our immediate parent to it. origins.add(this.getOrigin()); return origins; } } @Override public long getNow() { return this.backingBranch.getNow(); } // ===================================================================================================================== // HASH CODE & EQUALS // ===================================================================================================================== @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.backingBranch == null ? 0 : this.backingBranch.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } SphereBranchImpl other = (SphereBranchImpl) obj; if (this.backingBranch == null) { if (other.backingBranch != null) { return false; } } else if (!this.backingBranch.equals(other.backingBranch)) { return false; } return true; } }
4,575
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereIndexManagerImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/ChronoSphereIndexManagerImpl.java
package org.chronos.chronosphere.impl; import static com.google.common.base.Preconditions.*; import org.chronos.chronograph.api.index.ChronoGraphIndex; import org.chronos.chronograph.api.index.ChronoGraphIndexManager; import org.chronos.chronosphere.api.ChronoSphereIndexManager; import org.chronos.chronosphere.api.ChronoSphereTransaction; import org.chronos.chronosphere.api.SphereBranch; 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.eclipse.emf.ecore.EAttribute; import java.util.Set; public class ChronoSphereIndexManagerImpl implements ChronoSphereIndexManager { // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final ChronoSphereInternal owningSphere; private final SphereBranch owningBranch; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public ChronoSphereIndexManagerImpl(final ChronoSphereInternal owningSphere, final SphereBranch owningBranch) { checkNotNull(owningSphere, "Precondition violation - argument 'owningSphere' must not be NULL!"); this.owningSphere = owningSphere; this.owningBranch = owningBranch; } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public boolean createIndexOn(final EAttribute eAttribute) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); try (ChronoSphereTransaction tx = this.owningSphere.tx(this.owningBranch.getName())) { ChronoEPackageRegistry registry = ((ChronoSphereTransactionInternal) tx).getEPackageRegistry(); String propertyKey = ChronoSphereGraphFormat.createVertexPropertyKey(registry, eAttribute); if (propertyKey == null) { throw new IllegalArgumentException("The given EAttribute '" + eAttribute.getName() + "' is not part of a registered EPackage! Please register the EPackage first."); } if (this.getGraphIndexManager().isVertexPropertyIndexedAtAnyPointInTime(propertyKey)) { // index already exists return false; } else { // index does not exist, create it this.getGraphIndexManager().create().stringIndex().onVertexProperty(propertyKey).acrossAllTimestamps().build(); return true; } } } @Override public boolean existsIndexOn(final EAttribute eAttribute) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); try (ChronoSphereTransaction tx = this.owningSphere.tx(this.owningBranch.getName())) { ChronoEPackageRegistry registry = ((ChronoSphereTransactionInternal) tx).getEPackageRegistry(); String propertyKey = ChronoSphereGraphFormat.createVertexPropertyKey(registry, eAttribute); if (propertyKey == null) { throw new IllegalArgumentException("The given EAttribute '" + eAttribute.getName() + "' is not part of a registered EPackage! Please register the EPackage first."); } return this.getGraphIndexManager().isVertexPropertyIndexedAtAnyPointInTime(propertyKey); } } @Override public boolean dropIndexOn(final EAttribute eAttribute) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); try (ChronoSphereTransaction tx = this.owningSphere.tx(this.owningBranch.getName())) { ChronoEPackageRegistry registry = ((ChronoSphereTransactionInternal) tx).getEPackageRegistry(); String propertyKey = ChronoSphereGraphFormat.createVertexPropertyKey(registry, eAttribute); if (propertyKey == null) { throw new IllegalArgumentException("The given EAttribute '" + eAttribute.getName() + "' is not part of a registered EPackage! Please register the EPackage first."); } Set<ChronoGraphIndex> indices = this.getGraphIndexManager().getVertexIndicesAtAnyPointInTime(propertyKey); if (indices.isEmpty()) { // no index existed return false; } else { // index exists, drop it for(ChronoGraphIndex graphIndex : indices){ this.getGraphIndexManager().dropIndex(graphIndex); } return true; } } } @Override public void reindexAll() { this.getGraphIndexManager().reindexAll(); } @Override public void reindex(final EAttribute eAttribute) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); try (ChronoSphereTransaction tx = this.owningSphere.tx(this.owningBranch.getName())) { ChronoEPackageRegistry registry = ((ChronoSphereTransactionInternal) tx).getEPackageRegistry(); String propertyKey = ChronoSphereGraphFormat.createVertexPropertyKey(registry, eAttribute); if (propertyKey == null) { throw new IllegalArgumentException("The given EAttribute '" + eAttribute.getName() + "' is not part of a registered EPackage! Please register the EPackage first."); } this.getGraphIndexManager().reindexAll(); } } @Override public boolean isIndexDirty(final EAttribute eAttribute) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); try (ChronoSphereTransaction tx = this.owningSphere.tx(this.owningBranch.getName())) { ChronoEPackageRegistry registry = ((ChronoSphereTransactionInternal) tx).getEPackageRegistry(); String propertyKey = ChronoSphereGraphFormat.createVertexPropertyKey(registry, eAttribute); if (propertyKey == null) { throw new IllegalArgumentException("The given EAttribute '" + eAttribute.getName() + "' is not part of a registered EPackage! Please register the EPackage first."); } return this.getGraphIndexManager().getDirtyIndicesAtAnyPointInTime().stream().anyMatch(idx -> idx.getIndexedProperty().equals(propertyKey)); } } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== protected ChronoGraphIndexManager getGraphIndexManager() { return this.owningSphere.getRootGraph().getIndexManagerOnBranch(this.owningBranch.getName()); } }
6,805
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ChronoSphereBranchManagerImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/ChronoSphereBranchManagerImpl.java
package org.chronos.chronosphere.impl; import static com.google.common.base.Preconditions.*; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.chronos.chronograph.api.branch.ChronoGraphBranchManager; import org.chronos.chronograph.api.branch.GraphBranch; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.ChronoSphereBranchManager; import org.chronos.chronosphere.api.SphereBranch; import com.google.common.collect.Maps; public class ChronoSphereBranchManagerImpl implements ChronoSphereBranchManager { // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final ChronoGraph graph; private final Map<GraphBranch, SphereBranch> backingBranchToSphereBranch; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public ChronoSphereBranchManagerImpl(final ChronoGraph graph) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); this.graph = graph; this.backingBranchToSphereBranch = Maps.newHashMap(); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public SphereBranch createBranch(final String branchName) { GraphBranch branch = this.getChronoGraphBranchManager().createBranch(branchName); return this.getOrCreateSphereBranch(branch); } @Override public SphereBranch createBranch(final String branchName, final long branchingTimestamp) { GraphBranch branch = this.getChronoGraphBranchManager().createBranch(branchName, branchingTimestamp); return this.getOrCreateSphereBranch(branch); } @Override public SphereBranch createBranch(final String parentName, final String newBranchName) { GraphBranch branch = this.getChronoGraphBranchManager().createBranch(parentName, newBranchName); return this.getOrCreateSphereBranch(branch); } @Override public SphereBranch createBranch(final String parentName, final String newBranchName, final long branchingTimestamp) { GraphBranch branch = this.getChronoGraphBranchManager().createBranch(parentName, newBranchName, branchingTimestamp); return this.getOrCreateSphereBranch(branch); } @Override public boolean existsBranch(final String branchName) { return this.getChronoGraphBranchManager().existsBranch(branchName); } @Override public SphereBranch getBranch(final String branchName) { GraphBranch backingBranch = this.getChronoGraphBranchManager().getBranch(branchName); return this.getOrCreateSphereBranch(backingBranch); } @Override public Set<String> getBranchNames() { return this.getChronoGraphBranchManager().getBranchNames(); } @Override public Set<SphereBranch> getBranches() { Set<GraphBranch> branches = this.getChronoGraphBranchManager().getBranches(); return branches.stream() // map each backing branch to a graph branch .map(backingBranch -> this.getOrCreateSphereBranch(backingBranch)) // return the result as a set .collect(Collectors.toSet()); } // ===================================================================================================================== // INTERNAL HELPER METHODS // ===================================================================================================================== private ChronoGraphBranchManager getChronoGraphBranchManager() { return this.graph.getBranchManager(); } private SphereBranch getOrCreateSphereBranch(final GraphBranch backingBranch) { checkNotNull(backingBranch, "Precondition violation - argument 'backingBranch' must not be NULL!"); // check if we already know that branch... SphereBranch graphBranch = this.backingBranchToSphereBranch.get(backingBranch); if (graphBranch != null) { // use the cached instance return graphBranch; } // we don't know that branch yet; construct it if (backingBranch.getOrigin() == null) { // no origin -> we are dealing with the master branch graphBranch = SphereBranchImpl.createMasterBranch(backingBranch); } else { // regular branch SphereBranch originBranch = this.getOrCreateSphereBranch(backingBranch.getOrigin()); graphBranch = SphereBranchImpl.createBranch(backingBranch, originBranch); } // remember the graph branch in our cache this.backingBranchToSphereBranch.put(backingBranch, graphBranch); return graphBranch; } }
4,892
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
StandardChronoSphere.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/StandardChronoSphere.java
package org.chronos.chronosphere.impl; import com.google.common.collect.Maps; import org.apache.commons.configuration2.Configuration; import org.chronos.chronodb.api.ChronoDBConstants; import org.chronos.chronodb.api.Order; import org.chronos.chronodb.internal.impl.engines.base.ChronosInternalCommitMetadata; import org.chronos.chronograph.api.index.ChronoGraphIndex; import org.chronos.chronograph.api.index.ChronoGraphIndexManager; import org.chronos.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.*; import org.chronos.chronosphere.api.exceptions.ChronoSphereConfigurationException; import org.chronos.chronosphere.impl.transaction.ChronoSphereTransactionImpl; import org.chronos.chronosphere.internal.api.ChronoSphereInternal; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.chronos.chronosphere.internal.configuration.api.ChronoSphereConfiguration; import org.chronos.chronosphere.internal.configuration.impl.ChronoSphereConfigurationImpl; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.chronos.chronosphere.internal.ogm.api.EObjectToGraphMapper; import org.chronos.chronosphere.internal.ogm.api.EPackageToGraphMapper; import org.chronos.chronosphere.internal.ogm.impl.EObjectToGraphMapperImpl; import org.chronos.chronosphere.internal.ogm.impl.EPackageToGraphMapperImpl; import org.chronos.common.configuration.ChronosConfigurationUtil; import org.chronos.common.version.ChronosVersion; import org.eclipse.emf.ecore.EObject; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import static com.google.common.base.Preconditions.*; public class StandardChronoSphere implements ChronoSphere, ChronoSphereInternal { // ===================================================================================================================== // FIELDS // ===================================================================================================================== private final ChronoGraph graph; private final ChronoSphereConfiguration configuration; private final ChronoSphereBranchManager branchManager; private final ChronoSphereEPackageManager ePackageManager; private final EObjectToGraphMapper eObjectToGraphMapper; private final EPackageToGraphMapper ePackageToGraphMapper; private final Object branchLock; private final Map<SphereBranch, ChronoSphereIndexManager> branchToIndexManager; // ===================================================================================================================== // CONSTRUCTOR // ===================================================================================================================== public StandardChronoSphere(final ChronoGraph graph, final Configuration configuration) { checkNotNull(graph, "Precondition violation - argument 'graph' must not be NULL!"); checkNotNull(configuration, "Precondition violation - argument 'configuration' must not be NULL!"); this.graph = graph; this.configuration = ChronosConfigurationUtil.build(configuration, ChronoSphereConfigurationImpl.class); this.eObjectToGraphMapper = new EObjectToGraphMapperImpl(); this.ePackageToGraphMapper = new EPackageToGraphMapperImpl(); this.branchManager = new ChronoSphereBranchManagerImpl(graph); this.ePackageManager = new ChronoSphereEPackageManagerImpl(this); this.branchLock = new Object(); this.branchToIndexManager = Maps.newHashMap(); // ensure that the graph format is correct this.ensureGraphFormatIsCompatible(); // make sure that the graph has the default indices registered this.setUpDefaultGraphIndicesIfNecessary(); } // ===================================================================================================================== // [PUBLIC API] CLOSE HANDLING // ===================================================================================================================== @Override public ChronoSphereConfiguration getConfiguration() { return this.configuration; } @Override public void close() { this.graph.close(); } @Override public boolean isClosed() { return this.graph.isClosed(); } // ===================================================================================================================== // [PUBLIC API] BRANCH MANAGEMENT // ===================================================================================================================== @Override public ChronoSphereBranchManager getBranchManager() { return this.branchManager; } // ================================================================================================================= // [PUBLIC API] EPACKAGE MANAGEMENT // ================================================================================================================= @Override public ChronoSphereEPackageManager getEPackageManager() { return this.ePackageManager; } // ===================================================================================================================== // [PUBLIC API] INDEX MANAGEMENT // ===================================================================================================================== @Override public ChronoSphereIndexManager getIndexManager(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); SphereBranch branch = this.getBranchManager().getBranch(branchName); synchronized (this.branchLock){ ChronoSphereIndexManager indexManager = this.branchToIndexManager.get(branch); if (indexManager != null) { // index manager already exists return indexManager; } else { // no index manager exists yet; create one indexManager = new ChronoSphereIndexManagerImpl(this, branch); this.branchToIndexManager.put(branch, indexManager); return indexManager; } } } // ===================================================================================================================== // [PUBLIC API] TRANSACTION HANDLING // ===================================================================================================================== @Override public ChronoSphereTransaction tx() { ChronoGraph txGraph = this.getRootGraph().tx().createThreadedTx(); return new ChronoSphereTransactionImpl(this, txGraph); } @Override public ChronoSphereTransaction tx(final long timestamp) { checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); ChronoGraph txGraph = this.getRootGraph().tx().createThreadedTx(timestamp); return new ChronoSphereTransactionImpl(this, txGraph); } @Override public ChronoSphereTransaction tx(final Date date) { checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!"); return this.tx(date.getTime()); } @Override public ChronoSphereTransaction tx(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); ChronoGraph txGraph = this.getRootGraph().tx().createThreadedTx(branchName); return new ChronoSphereTransactionImpl(this, txGraph); } @Override public ChronoSphereTransaction tx(final String branchName, final long timestamp) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); ChronoGraph txGraph = this.getRootGraph().tx().createThreadedTx(branchName, timestamp); return new ChronoSphereTransactionImpl(this, txGraph); } @Override public ChronoSphereTransaction tx(final String branchName, final Date date) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); checkNotNull(date, "Precondition violation - argument 'date' must not be NULL!"); return this.tx(branchName, date.getTime()); } // ===================================================================================================================== // [PUBLIC API] BATCH INSERTION // ===================================================================================================================== @Override public void batchInsertModelData(final String branch, final Iterator<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!"); try (ChronoSphereTransactionInternal tx = (ChronoSphereTransactionInternal) this.tx(branch)) { tx.commitIncremental(); tx.batchInsert(model); tx.commit(); } } // ================================================================================================================= // [PUBLIC API] HISTORY ANALYSIS // ================================================================================================================= @Override public long getNow(final String branchName) { checkNotNull(branchName, "Precondition violation - argument 'branchName' must not be NULL!"); return this.graph.getNow(branchName); } @Override public Object getCommitMetadata(final String branch, final long timestamp) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(timestamp >= 0, "Precondition violation - argument 'timestamp' must not be negative!"); checkArgument(timestamp <= this.getNow(branch), "Precondition violation - argument 'timestamp' must not be larger than the latest commit timestamp!"); return this.graph.getCommitMetadata(branch, timestamp); } @Override public Iterator<Long> getCommitTimestampsBetween(final String branch, final long from, final long to, final Order order) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); return this.graph.getCommitTimestampsBetween(branch, from, to, order); } @Override public Iterator<Entry<Long, Object>> getCommitMetadataBetween(final String branch, final long from, final long to, final Order order) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); return this.graph.getCommitMetadataBetween(branch, from, to, order); } @Override public Iterator<Long> getCommitTimestampsPaged(final String branch, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(pageSize > 0, "Precondition violation - argument 'pageSize' must be greater than zero!"); checkArgument(pageIndex >= 0, "Precondition violation - argument 'pageIndex' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); return this.graph.getCommitTimestampsPaged(branch, minTimestamp, maxTimestamp, pageSize, pageIndex, order); } @Override public Iterator<Entry<Long, Object>> getCommitMetadataPaged(final String branch, final long minTimestamp, final long maxTimestamp, final int pageSize, final int pageIndex, final Order order) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(minTimestamp >= 0, "Precondition violation - argument 'minTimestamp' must not be negative!"); checkArgument(maxTimestamp >= 0, "Precondition violation - argument 'maxTimestamp' must not be negative!"); checkArgument(pageSize > 0, "Precondition violation - argument 'pageSize' must be greater than zero!"); checkArgument(pageIndex >= 0, "Precondition violation - argument 'pageIndex' must not be negative!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); return this.graph.getCommitMetadataPaged(branch, minTimestamp, maxTimestamp, pageSize, pageIndex, order); } @Override public int countCommitTimestampsBetween(final String branch, final long from, final long to) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); checkArgument(from >= 0, "Precondition violation - argument 'from' must not be negative!"); checkArgument(to >= 0, "Precondition violation - argument 'to' must not be negative!"); return this.graph.countCommitTimestampsBetween(branch, from, to); } @Override public int countCommitTimestamps(final String branch) { checkNotNull(branch, "Precondition violation - argument 'branch' must not be NULL!"); return this.graph.countCommitTimestamps(branch); } // ===================================================================================================================== // INTERNAL API // ===================================================================================================================== @Override public ChronoGraph getRootGraph() { return this.graph; } @Override public EObjectToGraphMapper getEObjectToGraphMapper() { return this.eObjectToGraphMapper; } @Override public EPackageToGraphMapper getEPackageToGraphMapper() { return this.ePackageToGraphMapper; } // ===================================================================================================================== // HELPER METHODS // ===================================================================================================================== private void setUpDefaultGraphIndicesIfNecessary() { ChronoGraphIndexManager indexManager = this.getRootGraph().getIndexManagerOnMaster(); Set<ChronoGraphIndex> kindIndices = indexManager.getVertexIndicesAtAnyPointInTime(ChronoSphereGraphFormat.V_PROP__KIND); if (kindIndices.isEmpty()) { indexManager.create().stringIndex().onVertexProperty(ChronoSphereGraphFormat.V_PROP__KIND).acrossAllTimestamps().build(); } Set<ChronoGraphIndex> classIndices = indexManager.getVertexIndicesAtAnyPointInTime(ChronoSphereGraphFormat.V_PROP__ECLASS_ID); if (classIndices.isEmpty()) { indexManager.create().stringIndex().onVertexProperty(ChronoSphereGraphFormat.V_PROP__ECLASS_ID).acrossAllTimestamps().build(); } } private void ensureGraphFormatIsCompatible() { try(ChronoGraph txGraph = this.graph.tx().createThreadedTx()) { String formatVersionString = (String) txGraph.variables().get(ChronoSphereGraphFormat.VARIABLES__GRAPH_FORMAT_VERSION).orElse(null); ChronosVersion currentVersion = ChronosVersion.getCurrentVersion(); if (formatVersionString == null) { // no format version present boolean isEmpty = txGraph.getCommitMetadataAfter(0L, Integer.MAX_VALUE).stream().allMatch(m -> m.getValue() instanceof ChronosInternalCommitMetadata); if (isEmpty && this.graph.getBranchManager().getBranchNames().equals(Collections.singleton(ChronoDBConstants.MASTER_BRANCH_IDENTIFIER))) { // the graph is empty, write the current format into the graph txGraph.variables().set(ChronoSphereGraphFormat.VARIABLES__GRAPH_FORMAT_VERSION, currentVersion.toString()); txGraph.tx().commit("ChronoSphere Graph Format version update to " + currentVersion); return; } else { throw new ChronoSphereConfigurationException("This instance of ChronoSphere was created by a ChronoSphere version " + "lower than 0.9.x. A persistence format change has occurred since then. To migrate your data, please export your " + "model to XMI and re-import it into a blank 0.9.x (or newer) ChronoSphere instance."); } } ChronosVersion formatVersion = ChronosVersion.parse(formatVersionString); if (currentVersion.isSmallerThan(formatVersion)) { throw new ChronoSphereConfigurationException("This instance of ChronoSphere was created by ChronoSphere " + formatVersion + ", it cannot be opened by the current (older) version (" + currentVersion + ")!"); } else if (formatVersion.isSmallerThan(currentVersion)) { // the graph is empty, write the current format into the graph txGraph.variables().set(ChronoSphereGraphFormat.VARIABLES__GRAPH_FORMAT_VERSION, currentVersion.toString()); txGraph.tx().commit("ChronoSphere Graph Format version update from " + formatVersion + " to " + currentVersion); } } } }
18,721
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
ObjectQueryStepBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/ObjectQueryStepBuilderImpl.java
package org.chronos.chronosphere.impl.query; import org.chronos.chronosphere.api.query.EObjectQueryStepBuilder; import org.chronos.chronosphere.api.query.NumericQueryStepBuilder; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.api.query.UntypedQueryStepBuilder; import org.chronos.chronosphere.impl.query.steps.eobject.EObjectQueryAsEObjectStepBuilder; import org.chronos.chronosphere.impl.query.steps.numeric.*; import org.chronos.chronosphere.impl.query.steps.object.ObjectQueryAsBooleanStepBuilder; import org.chronos.chronosphere.impl.query.steps.object.ObjectQueryAsCharacterStepBuilder; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import java.util.function.Predicate; public abstract class ObjectQueryStepBuilderImpl<S, I, E> extends AbstractQueryStepBuilder<S, I, E> implements UntypedQueryStepBuilder<S, E> { public ObjectQueryStepBuilderImpl(final TraversalChainElement previous) { super(previous); } // ===================================================================================================================== // PUBLIC API // ===================================================================================================================== @Override public EObjectQueryStepBuilder<S> asEObject() { return new EObjectQueryAsEObjectStepBuilder<>(this); } @Override public QueryStepBuilder<S, Boolean> asBoolean() { return new ObjectQueryAsBooleanStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Byte> asByte() { return new NumericQueryAsByteStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Short> asShort() { return new NumericQueryAsShortStepBuilder<>(this); } @Override public QueryStepBuilder<S, Character> asCharacter() { return new ObjectQueryAsCharacterStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Integer> asInteger() { return new NumericQueryAsIntegerStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Long> asLong() { return new NumericQueryAsLongStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Float> asFloat() { return new NumericQueryAsFloatStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Double> asDouble() { return new NumericQueryAsDoubleStepBuilder<>(this); } @Override public UntypedQueryStepBuilder<S, E> filter(final Predicate<E> predicate) { return (UntypedQueryStepBuilder<S, E>) super.filter(predicate); } }
2,685
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryStepBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/EObjectQueryStepBuilderImpl.java
package org.chronos.chronosphere.impl.query; import com.google.common.base.Objects; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.api.query.*; import org.chronos.chronosphere.impl.query.steps.eobject.*; import org.chronos.chronosphere.impl.query.steps.object.*; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.impl.query.traversal.TraversalTransformer; import org.eclipse.emf.ecore.*; 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; import static com.google.common.base.Preconditions.*; public abstract class EObjectQueryStepBuilderImpl<S, I> implements EObjectQueryStepBuilder<S>, QueryStepBuilderInternal<S, EObject>, TraversalTransformer<S, I, Vertex> { private TraversalChainElement previous; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= public EObjectQueryStepBuilderImpl(final TraversalChainElement previous) { this.previous = previous; } @Override public EObjectQueryStepBuilder<S> orderBy(final Comparator<EObject> comparator) { checkNotNull(comparator, "Precondition violation - argument 'comparator' must not be NULL!"); ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(this); ObjectQueryOrderByStepBuilder<Object, EObject> ordered = new ObjectQueryOrderByStepBuilder<>(reified, comparator); return new EObjectQueryAsEObjectStepBuilder<>(ordered); } @Override public EObjectQueryStepBuilder<S> orderBy(final EAttribute eAttribute, final Order order) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); // TODO this could be optimized by implementing the orderBy() on graph-level rather than // resolving the actual EObjects. return this.orderBy(new EObjectAttributeComparator(eAttribute, order)); } @Override public EObjectQueryStepBuilder<S> distinct() { return new EObjectQueryDistinctStepBuilder<>(this); } @Override public <T> UntypedQueryStepBuilder<S, T> map(final Function<EObject, T> function) { checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); // the map function is specified on EObject API level, so we first have to transform // our vertices into EObjects ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(this); return new ObjectQueryMapStepBuilder<>(reified, function); } @Override public <T> UntypedQueryStepBuilder<S, T> flatMap(final Function<EObject, Iterator<T>> function) { checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); // the map function is specified on EObject API level, so we first have to transform // our vertices into EObjects ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(this); return new ObjectQueryFlatMapStepBuilder<>(reified, function); } @Override public Set<EObject> toSet() { QueryStepBuilderInternal<S, EObject> finalStep = this.reifyEObjects(); GraphTraversal<S, EObject> traversal = QueryUtils.prepareTerminalOperation(finalStep, true); return traversal.toSet(); } @Override public List<EObject> toList() { QueryStepBuilderInternal<S, EObject> finalStep = this.reifyEObjects(); GraphTraversal<S, EObject> traversal = QueryUtils.prepareTerminalOperation(finalStep, true); return traversal.toList(); } @Override public Iterator<EObject> toIterator() { QueryStepBuilderInternal<S, EObject> finalStep = this.reifyEObjects(); GraphTraversal<S, EObject> traversal = QueryUtils.prepareTerminalOperation(finalStep, true); return traversal; } @Override public Stream<EObject> toStream() { QueryStepBuilderInternal<S, EObject> finalStep = this.reifyEObjects(); GraphTraversal<S, EObject> traversal = QueryUtils.prepareTerminalOperation(finalStep, true); return traversal.toStream(); } @Override public long count() { GraphTraversal<S, EObject> traversal = QueryUtils.prepareTerminalOperation(this, false); return traversal.count().next(); } @Override public EObjectQueryStepBuilder<S> limit(final long limit) { checkArgument(limit >= 0, "Precondition violation - argument 'limit' must not be negative!"); return new EObjectQueryLimitStepBuilder<>(this, limit); } @Override public EObjectQueryStepBuilder<S> notNull() { return new EObjectQueryNonNullStepBuilder<>(this); } @Override public EObjectQueryStepBuilder<S> has(final String eStructuralFeatureName, final Object value) { checkNotNull(eStructuralFeatureName, "Precondition violation - argument 'eStructuralFeatureName' must not be NULL!"); // we have to apply this on the EObject API, sadly ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(this); 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 Objects.equal(eObject.eGet(feature), value); })); return new EObjectQueryAsEObjectStepBuilder<>(filtered); } @Override public EObjectQueryStepBuilder<S> has(final EStructuralFeature eStructuralFeature, final Object value) { checkNotNull(eStructuralFeature, "Precondition violation - argument 'eStructuralFeature' must not be NULL!"); return new EObjectQueryHasFeatureValueStepBuilder<>(this, eStructuralFeature, value); } @Override public EObjectQueryStepBuilder<S> isInstanceOf(final EClass eClass) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); return this.isInstanceOf(eClass, true); } @Override public EObjectQueryStepBuilder<S> isInstanceOf(final EClass eClass, final boolean allowSubclasses) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); return new EObjectQueryInstanceOfEClassStepBuilder<>(this, eClass, allowSubclasses); } @Override public EObjectQueryStepBuilder<S> isInstanceOf(final String eClassName) { checkNotNull(eClassName, "Precondition violation - argument 'eClassName' must not be NULL!"); return this.isInstanceOf(eClassName, true); } @Override public EObjectQueryStepBuilder<S> isInstanceOf(final String eClassName, final boolean allowSubclasses) { checkNotNull(eClassName, "Precondition violation - argument 'eClassName' must not be NULL!"); return new EObjectQueryInstanceOfEClassNameStepBuilder<>(this, eClassName, allowSubclasses); } @Override @SuppressWarnings("unchecked") public UntypedQueryStepBuilder<S, Object> eGet(final String eStructuralFeatureName) { checkNotNull(eStructuralFeatureName, "Precondition violation - argument 'eStructuralFeatureName' must not be NULL!"); return new ObjectQueryEGetByNameStepBuilder<>(this, eStructuralFeatureName); } @Override public EObjectQueryStepBuilder<S> eGet(final EReference eReference) { checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); return new EObjectQueryEGetReferenceStepBuilder<>(this, eReference); } @Override public EObjectQueryStepBuilder<S> eGetInverse(final EReference eReference) { checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); return new EObjectQueryEGetInverseByReferenceStepBuilder<>(this, eReference); } @Override public EObjectQueryStepBuilder<S> eGetInverse(final String referenceName) { checkNotNull(referenceName, "Precondition violation - argument 'referenceName' must not be NULL!"); return new EObjectQueryEGetInverseByNameStepBuilder<>(this, referenceName); } @Override public UntypedQueryStepBuilder<S, Object> eGet(final EAttribute eAttribute) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); return new ObjectQueryEGetAttributeStepBuilder<>(this, eAttribute); } @Override public EObjectQueryStepBuilder<S> eContainer() { return new EObjectQueryEContainerStepBuilder<>(this); } @Override public EObjectQueryStepBuilder<S> eContents() { return new EObjectQueryEContentsStepBuilder<>(this); } @Override public EObjectQueryStepBuilder<S> eAllContents() { return new EObjectQueryEAllContentsStepBuilder<>(this); } @Override public EObjectQueryStepBuilder<S> allReferencingEObjects() { return new EObjectQueryAllReferencingEObjectsQueryStep<>(this); } @Override public EObjectQueryStepBuilder<S> named(final String name) { checkNotNull(name, "Precondition violation - argument 'name' must not be NULL!"); // the content of the named steps are reified EObjects, not vertices. We therefore // have to transform our vertices into EObjects, apply the except step, and then transform // back into Vertex representation. ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(this); ObjectQueryNamedStepBuilder<Object, EObject> except = new ObjectQueryNamedStepBuilder<>(reified, name); return new EObjectQueryAsEObjectStepBuilder<>(except); } @Override public UntypedQueryStepBuilder<S, Object> back(final String stepName) { checkNotNull(stepName, "Precondition violation - argument 'stepName' must not be NULL!"); return new ObjectQueryEObjectBackStepBuilder<>(this, stepName); } @Override public EObjectQueryStepBuilder<S> except(final String stepName) { checkNotNull(stepName, "Precondition violation - argument 'stepName' must not be NULL!"); // the content of the named steps are reified EObjects, not vertices. We therefore // have to transform our vertices into EObjects, apply the except step, and then transform // back into Vertex representation. ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(this); ObjectQueryExceptNamedStepBuilder<Object, EObject> except = new ObjectQueryExceptNamedStepBuilder<>(reified, stepName); return new EObjectQueryAsEObjectStepBuilder<>(except); } @Override public EObjectQueryStepBuilder<S> except(final Set<?> elementsToExclude) { checkNotNull(elementsToExclude, "Precondition violation - argument 'elementsToExclude' must not be NULL!"); return new EObjectQueryExceptObjectsStepBuilder<>(this, elementsToExclude); } @Override public UntypedQueryStepBuilder<S, Object> union(final QueryStepBuilder<EObject, ?>... subqueries) { checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); checkArgument(subqueries.length > 0, "Precondition violation - argument 'subqueries' must not be an empty array!"); return new ObjectQueryEObjectUnionStepBuilder<>(this, subqueries); } @Override public EObjectQueryStepBuilder<S> and(final QueryStepBuilder<EObject, ?>... subqueries) { checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); checkArgument(subqueries.length > 0, "Precondition violation - argument 'subqueries' must not be an empty array!"); return new EObjectQueryAndStepBuilder<>(this, subqueries); } @Override public EObjectQueryStepBuilder<S> or(final QueryStepBuilder<EObject, ?>... subqueries) { checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); checkArgument(subqueries.length > 0, "Precondition violation - argument 'subqueries' must not be an empty array!"); return new EObjectQueryOrStepBuilder<>(this, subqueries); } @Override public EObjectQueryStepBuilder<S> not(final QueryStepBuilder<EObject, ?> subquery) { checkNotNull(subquery, "Precondition violation - argument 'subquery' must not be NULL!"); return new EObjectQueryNotStepBuilder<>(this, subquery); } @Override public EObjectQueryStepBuilder<S> filter(final Predicate<EObject> predicate) { checkNotNull(predicate, "Precondition violation - argument 'predicate' must not be NULL!"); // the predicate is formulated based on the EObject API. We are dealing with vertices // here internally, so we first have to reify the EObject, test the predicate, and then // transform the remaining EObjects back into Vertex representation, because the next // query step expects vertices as input again. ObjectQueryEObjectReifyStepBuilder<Object> reified = new ObjectQueryEObjectReifyStepBuilder<>(this); ObjectQueryFilterStepBuilder<Object, EObject> filtered = new ObjectQueryFilterStepBuilder<>(reified, predicate); return new EObjectQueryAsEObjectStepBuilder<>(filtered); } @Override public EObjectQueryStepBuilder<S> closure(final EReference eReference, Direction direction) { checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); checkNotNull(direction, "Precondition violation - argument 'direction' must not be NULL!"); return new EObjectQueryClosureStepBuilder<>(this, eReference, direction); } // ================================================================================================================= // INTERNAL API // ================================================================================================================= @Override public TraversalChainElement getPrevious() { return this.previous; } @Override public void setPrevious(final TraversalChainElement previous) { checkNotNull(previous, "Precondition violation - argument 'previous' must not be NULL!"); this.previous = previous; } // ===================================================================================================================== // HELPER METHODS // ===================================================================================================================== protected QueryStepBuilderInternal<S, EObject> reifyEObjects() { return new ObjectQueryEObjectReifyStepBuilder<>(this); } }
15,830
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryUtils.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/QueryUtils.java
package org.chronos.chronosphere.impl.query; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; 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.chronograph.api.structure.ChronoGraph; import org.chronos.chronosphere.api.ChronoSphereTransaction; 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.emf.api.ChronoEObject; import org.chronos.chronosphere.impl.query.steps.eobject.EObjectQueryAsEObjectStepBuilder; import org.chronos.chronosphere.impl.query.steps.object.ObjectQueryEObjectReifyStepBuilder; import org.chronos.chronosphere.impl.query.steps.object.ObjectQueryTerminalConverterStepBuilder; import org.chronos.chronosphere.impl.query.traversal.TraversalBaseSource; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.impl.query.traversal.TraversalSource; import org.chronos.chronosphere.impl.query.traversal.TraversalTransformer; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import org.eclipse.emf.ecore.EObject; import java.util.List; import java.util.ListIterator; import java.util.function.Function; public class QueryUtils { public static QueryStepBuilderInternal<?, ?> getFirstBuilderInChain(QueryStepBuilder<?, ?> builder) { QueryStepBuilderInternal<?, ?> current = (QueryStepBuilderInternal<?, ?>) builder; while (true) { TraversalChainElement previous = current.getPrevious(); if (previous instanceof QueryStepBuilderInternal) { current = (QueryStepBuilderInternal<?, ?>) previous; } else { return current; } } } public static ChronoSphereTransactionInternal getTransactionFromTraversalBaseSourceOf(QueryStepBuilder<?, ?> builder) { TraversalChainElement current = (TraversalChainElement) builder; while (current instanceof QueryStepBuilderInternal) { TraversalChainElement previous = ((QueryStepBuilderInternal) current).getPrevious(); current = previous; } if (current instanceof TraversalBaseSource) { TraversalBaseSource baseSource = (TraversalBaseSource) current; return baseSource.getTransaction(); } throw new IllegalStateException("Calling a terminating method on a traversal which was created by a SubQuery method is invalid! Subqueries cannot be evaluated as standalone queries!"); } @SuppressWarnings("unchecked") public static <S, E> GraphTraversal<S, E> resolveTraversalChain(QueryStepBuilder<S, E> builder, ChronoSphereTransactionInternal tx, boolean forceReifyEObjectsAtEnd) { List<TraversalChainElement> chainElements = Lists.newArrayList(); TraversalChainElement currentBuilder = (TraversalChainElement) builder; while (currentBuilder != null) { chainElements.add(currentBuilder); if (currentBuilder instanceof QueryStepBuilderInternal) { QueryStepBuilderInternal stepBuilder = (QueryStepBuilderInternal) currentBuilder; currentBuilder = stepBuilder.getPrevious(); } else { // end of chain: there is no previous element currentBuilder = null; } } chainElements = Lists.reverse(chainElements); if (chainElements.isEmpty()) { throw new IllegalStateException("At least one element must be on the query chain!"); } TraversalChainElement first = chainElements.get(0); if (first instanceof TraversalSource == false) { throw new IllegalStateException("There is no traversal source for this query chain!"); } TraversalSource source = (TraversalSource) first; optimizeTraversalChain(chainElements); if (forceReifyEObjectsAtEnd) { TraversalChainElement last = Iterables.getLast(chainElements); // if the last element of a chain is an EObjectQueryStep (i.e. it operates on vertices), then // we append a reify step to make sure that only EObjects exit the stream, not vertices. if (last instanceof EObjectQueryStepBuilder) { chainElements.add(new ObjectQueryTerminalConverterStepBuilder<>(last)); } } GraphTraversal traversal = source.createTraversal(); for (int i = 1; i < chainElements.size(); i++) { TraversalChainElement element = chainElements.get(i); if (element instanceof TraversalTransformer == false) { throw new IllegalStateException("Illegal traversal chain: there are multiple traversal sources!"); } TraversalTransformer transformer = (TraversalTransformer) element; traversal = transformer.transformTraversal(tx, traversal); } return traversal; } private static void optimizeTraversalChain(final List<TraversalChainElement> chainElements) { // if we find the following sequence: // ReifyEObject (vertex to eobject) -> AsEObject (eobject as vertex) // ... we eliminate both steps because they cancel each other out. // also if we find the following sequence: // AsEObject (eObject as vertex) -> ReifyEObjects (vertex to eobject) // ... we eliminate both steps because they cancel each other out. ListIterator<TraversalChainElement> listIterator = chainElements.listIterator(); while (listIterator.hasNext()) { TraversalChainElement current = listIterator.next(); if (listIterator.hasNext() == false) { // this is the last element in our chain, we are done break; } TraversalChainElement next = listIterator.next(); // move back after "peeking" listIterator.previous(); if (current instanceof ObjectQueryEObjectReifyStepBuilder && next instanceof EObjectQueryAsEObjectStepBuilder) { // eliminate them both listIterator.previous(); listIterator.remove(); listIterator.next(); listIterator.remove(); } else if (current instanceof EObjectQueryAsEObjectStepBuilder && next instanceof ObjectQueryEObjectReifyStepBuilder) { // eliminate them both listIterator.previous(); listIterator.remove(); listIterator.next(); listIterator.remove(); } } } @SuppressWarnings("unchecked") public static GraphTraversal<Vertex, Object>[] subQueriesToVertexTraversals(final ChronoSphereTransactionInternal tx, final QueryStepBuilder<?, ?>[] subqueries, boolean forceReifyEObjectsAtEnd) { List<GraphTraversal<?, ?>> innerTraversals = Lists.newArrayList(); for (QueryStepBuilder<?, ?> subquery : subqueries) { QueryStepBuilderInternal<?, ?> firstBuilder = getFirstBuilderInChain(subquery); if (firstBuilder instanceof EObjectQueryStepBuilder == false) { // the first step is NOT an EObject step, therefore it does NOT accept vertices. // In order for this subquery to be successful on a vertex stream input, we need // to prepend it with a step that reifies the Vertices in the stream into EObjects. TraversalSource<?, ?> source = (TraversalSource<?, ?>) firstBuilder.getPrevious(); ObjectQueryEObjectReifyStepBuilder<Object> reifyStep = new ObjectQueryEObjectReifyStepBuilder<>(source); firstBuilder.setPrevious(reifyStep); } GraphTraversal<?, ?> traversal = resolveTraversalChain(subquery, tx, forceReifyEObjectsAtEnd); innerTraversals.add(traversal); } return innerTraversals.toArray((GraphTraversal<Vertex, Object>[]) new GraphTraversal[innerTraversals.size()]); } @SuppressWarnings("unchecked") public static GraphTraversal<Object, Object>[] subQueriesToObjectTraversals(final ChronoSphereTransactionInternal tx, final QueryStepBuilder<?, ?>[] subqueries, boolean forceReifyEObjectsAtEnd) { List<GraphTraversal<?, ?>> innerTraversals = Lists.newArrayList(); for (QueryStepBuilder<?, ?> subquery : subqueries) { QueryStepBuilderInternal<?, ?> firstBuilder = getFirstBuilderInChain(subquery); if (firstBuilder instanceof EObjectQueryStepBuilder) { // the first step is an EObject step, therefore it does accept vertices. // In order for this subquery to be successful on an EObject stream input, we need // to prepend it with a step that transforms the EObjects in the stream into Vertices. TraversalSource<?, ?> source = (TraversalSource<?, ?>) firstBuilder.getPrevious(); EObjectQueryAsEObjectStepBuilder<Object, EObject> transformStep = new EObjectQueryAsEObjectStepBuilder<>(source); firstBuilder.setPrevious(transformStep); } GraphTraversal<?, ?> traversal = resolveTraversalChain(subquery, tx, forceReifyEObjectsAtEnd); innerTraversals.add(traversal); } return innerTraversals.toArray((GraphTraversal<Object, Object>[]) new GraphTraversal[innerTraversals.size()]); } public static <S, C> GraphTraversal<S, C> castTraversalTo(GraphTraversal<S, ?> traversal, final Class<C> clazz) { return traversal.filter(t -> clazz.isInstance(t.get())).map(t -> clazz.cast(t.get())); } public static <S, C> GraphTraversal<S, C> castTraversalToNumeric(GraphTraversal<S, ?> traversal, final Function<Number, C> conversion) { return traversal.filter(t -> t.get() instanceof Number).map(t -> conversion.apply((Number) t.get())); } public static <S, E> GraphTraversal<S, E> prepareTerminalOperation(QueryStepBuilderInternal<S, E> builder, boolean forceReifyEObjectsAtEnd) { ChronoSphereTransactionInternal tx = getTransactionFromTraversalBaseSourceOf(builder); return resolveTraversalChain(builder, tx, forceReifyEObjectsAtEnd); } public static EObject mapVertexToEObject(final ChronoSphereTransaction tx, final Traverser<Vertex> traverser) { return mapVertexToEObject(tx, traverser.get()); } public static EObject mapVertexToEObject(final ChronoSphereTransaction tx, final Vertex vertex) { if (vertex == null) { return null; } return tx.getEObjectById((String) vertex.id()); } public static Vertex mapEObjectToVertex(final ChronoSphereTransaction tx, final EObject eObject) { ChronoGraph graph = ((ChronoSphereTransactionInternal) tx).getGraph(); return mapEObjectToVertex(graph, eObject); } public static Vertex mapEObjectToVertex(final ChronoGraph graph, final EObject eObject) { if (eObject == null) { return null; } ChronoEObject cEObject = (ChronoEObject) eObject; if (graph == null) { throw new IllegalStateException("Graph is NULL!"); } return Iterators.getOnlyElement(graph.vertices(cEObject.getId()), null); } }
11,619
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectAttributeComparator.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/EObjectAttributeComparator.java
package org.chronos.chronosphere.impl.query; import static com.google.common.base.Preconditions.*; import java.util.Comparator; import org.chronos.chronosphere.api.query.Order; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EObject; public class EObjectAttributeComparator implements Comparator<EObject> { private final EAttribute eAttribute; private final Order order; public EObjectAttributeComparator(final EAttribute eAttribute, final Order order) { checkNotNull(eAttribute, "Precondition violation - argument 'eAttribute' must not be NULL!"); checkNotNull(order, "Precondition violation - argument 'order' must not be NULL!"); this.eAttribute = eAttribute; this.order = order; } @Override public int compare(final EObject o1, final EObject o2) { int comparison = this.compareInternal(o1, o2); if (this.order.equals(Order.DESC)) { return comparison * -1; } else { return comparison; } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected int compareInternal(final EObject o1, final EObject o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 == null && o2 != null) { return 1; } else if (o1 != null && o2 == null) { return -1; } Object val1 = o1.eGet(this.eAttribute); Object val2 = o2.eGet(this.eAttribute); if (val1 == null && val2 == null) { return 0; } else if (val1 != null && val2 == null) { return 1; } else if (val1 == null && val2 != null) { return -1; } if (val1 instanceof Comparable == false) { throw new IllegalStateException( "Cannot execute comparison! Value '" + val1 + "' (class: '" + val1.getClass().getCanonicalName() + "') retrieved via EAttribute '" + this.eAttribute.getName() + "' is not Comparable!"); } if (val2 instanceof Comparable == false) { throw new IllegalStateException( "Cannot execute comparison! Value '" + val2 + "' (class: '" + val2.getClass().getCanonicalName() + "') retrieved via EAttribute '" + this.eAttribute.getName() + "' is not Comparable!"); } Comparable compVal1 = (Comparable) val1; Comparable compVal2 = (Comparable) val2; return compVal1.compareTo(compVal2); } }
2,181
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
AbstractQueryStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/AbstractQueryStepBuilder.java
package org.chronos.chronosphere.impl.query; import org.chronos.chronosphere.api.query.QueryStepBuilder; import org.chronos.chronosphere.api.query.QueryStepBuilderInternal; import org.chronos.chronosphere.api.query.UntypedQueryStepBuilder; import org.chronos.chronosphere.impl.query.steps.object.*; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.impl.query.traversal.TraversalTransformer; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.google.common.base.Preconditions.*; public abstract class AbstractQueryStepBuilder<S, I, E> implements QueryStepBuilderInternal<S, E>, TraversalTransformer<S, I, E> { // ================================================================================================================= // FIELDS // ================================================================================================================= protected TraversalChainElement previous; // ================================================================================================================= // CONSTRUCTOR // ================================================================================================================= protected AbstractQueryStepBuilder(final TraversalChainElement previous) { checkNotNull(previous, "Precondition violation - argument 'previous' must not be NULL!"); this.previous = previous; } // ================================================================================================================= // PUBLIC API // ================================================================================================================= @Override public QueryStepBuilder<S, E> filter(final Predicate<E> predicate) { checkNotNull(predicate, "Precondition violation - argument 'predicate' must not be NULL!"); return new ObjectQueryFilterStepBuilder<>(this, predicate); } @Override public QueryStepBuilder<S, E> limit(final long limit) { checkArgument(limit >= 0, "Precondition violation - argument 'limit' must not be negative!"); return new ObjectQueryLimitStepBuilder<>(this, limit); } @Override public QueryStepBuilder<S, E> orderBy(final Comparator<E> comparator) { checkNotNull(comparator, "Precondition violation - argument 'comparator' must not be NULL!"); return new ObjectQueryOrderByStepBuilder<>(this, comparator); } @Override public QueryStepBuilder<S, E> distinct() { return new ObjectQueryDistinctStepBuilder<>(this); } @Override public <T> UntypedQueryStepBuilder<S, T> map(final Function<E, T> function) { checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); return new ObjectQueryMapStepBuilder<>(this, function); } @Override public <T> UntypedQueryStepBuilder<S, T> flatMap(final Function<E, Iterator<T>> function) { checkNotNull(function, "Precondition violation - argument 'function' must not be NULL!"); return new ObjectQueryFlatMapStepBuilder<>(this, function); } @Override public QueryStepBuilder<S, E> notNull() { return this.filter(Objects::nonNull); } @Override public QueryStepBuilder<S, E> named(final String stepName) { checkNotNull(stepName, "Precondition violation - argument 'stepName' must not be NULL!"); return new ObjectQueryNamedStepBuilder<>(this, stepName); } @Override public UntypedQueryStepBuilder<S, Object> back(final String stepName) { checkNotNull(stepName, "Precondition violation - argument 'stepName' must not be NULL!"); return new ObjectQueryBackStepBuilder<>(this, stepName); } @Override public QueryStepBuilder<S, E> except(final String stepName) { checkNotNull(stepName, "Precondition violation - argument 'stepName' must not be NULL!"); return new ObjectQueryExceptNamedStepBuilder<>(this, stepName); } @Override public QueryStepBuilder<S, E> except(final Set<?> elementsToExclude) { checkNotNull(elementsToExclude, "Precondition violation - argument 'elementsToExclude' must not be NULL!"); return new ObjectQueryExceptSetStepBuilder<>(this, elementsToExclude); } @Override public UntypedQueryStepBuilder<S, Object> union(final QueryStepBuilder<E, ?>... subqueries) { checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); checkArgument(subqueries.length > 0, "Precondition violation - argument 'subqueries' must not be an empty array!"); return new ObjectQueryUnionStepBuilder<>(this, subqueries); } @Override public QueryStepBuilder<S, E> and(final QueryStepBuilder<E, ?>... subqueries) { checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); checkArgument(subqueries.length > 0, "Precondition violation - argument 'subqueries' must not be an empty array!"); return new ObjectQueryAndStepBuilder<>(this, subqueries); } @Override public QueryStepBuilder<S, E> or(final QueryStepBuilder<E, ?>... subqueries) { checkNotNull(subqueries, "Precondition violation - argument 'subqueries' must not be NULL!"); checkArgument(subqueries.length > 0, "Precondition violation - argument 'subqueries' must not be an empty array!"); return new ObjectQueryOrStepBuilder<>(this, subqueries); } @Override public QueryStepBuilder<S, E> not(final QueryStepBuilder<E, ?> subquery) { checkNotNull(subquery, "Precondition violation - argument 'subquery' must not be NULL!"); return new ObjectQueryNotStepBuilder<>(this, subquery); } @Override public Set<E> toSet() { return QueryUtils.prepareTerminalOperation(this, true).toSet(); } @Override public List<E> toList() { return QueryUtils.prepareTerminalOperation(this, true).toList(); } @Override public Stream<E> toStream() { return QueryUtils.prepareTerminalOperation(this, true).toStream(); } @Override public long count() { return QueryUtils.prepareTerminalOperation(this, true).count().next(); } @Override public Iterator<E> toIterator() { // "toIterator()" does not exist in gremlin; the query itself is // the iterator, therefore we do not have a real "terminating" operation here. return QueryUtils.prepareTerminalOperation(this, true); } // ================================================================================================================= // INTERNAL API // ================================================================================================================= @Override public TraversalChainElement getPrevious() { return this.previous; } @Override public void setPrevious(final TraversalChainElement previous) { checkNotNull(previous, "Precondition violation - argument 'previous' must not be NULL!"); this.previous = previous; } }
7,283
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
QueryStepBuilderStarterImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/QueryStepBuilderStarterImpl.java
package org.chronos.chronosphere.impl.query; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.api.query.EObjectQueryStepBuilder; import org.chronos.chronosphere.api.query.QueryStepBuilderStarter; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.emf.internal.api.ChronoEObjectInternal; import org.chronos.chronosphere.impl.query.steps.eobject.EObjectQueryIdentityStepBuilder; import org.chronos.chronosphere.impl.query.traversal.TraversalBaseSource; 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.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import java.util.Iterator; import java.util.List; import java.util.UUID; import static com.google.common.base.Preconditions.*; public class QueryStepBuilderStarterImpl implements QueryStepBuilderStarter { private ChronoSphereTransactionInternal owningTransaction; public QueryStepBuilderStarterImpl(final ChronoSphereTransactionInternal owningTransaction) { checkNotNull(owningTransaction, "Precondition violation - argument 'owningTransaction' must not be NULL!"); this.owningTransaction = owningTransaction; } @Override public EObjectQueryStepBuilder<EObject> startingFromAllEObjects() { TraversalBaseSource<Vertex, Vertex> source = new TraversalBaseSource<> (this.owningTransaction, g -> g.traversal() // start with all vertices .V() // restrict to those of kind "EObject" .has(ChronoSphereGraphFormat.V_PROP__KIND, VertexKind.EOBJECT.toString()) ); return this.createEQueryStepBuilderFromTraversalSource(source); } @Override public EObjectQueryStepBuilder<EObject> startingFromInstancesOf(final EClass eClass) { checkNotNull(eClass, "Precondition violation - argument 'eClass' must not be NULL!"); String id = this.owningTransaction.getEPackageRegistry().getEClassID(eClass); TraversalBaseSource<Vertex, Vertex> source = new TraversalBaseSource<> (this.owningTransaction, g -> g.traversal() // start with all vertices .V() // restrict to the instances of the given eclass .has(ChronoSphereGraphFormat.V_PROP__ECLASS_ID, id) // restrict to EObjects only .has(ChronoSphereGraphFormat.V_PROP__KIND, VertexKind.EOBJECT.toString()) ); return this.createEQueryStepBuilderFromTraversalSource(source); } @Override public EObjectQueryStepBuilder<EObject> startingFromInstancesOf(final String eClassName) { checkNotNull(eClassName, "Precondition violation - argument 'eClassName' must not be NULL!"); // try to get the EClass via qualified name EClass eClass = this.owningTransaction.getEClassByQualifiedName(eClassName); if (eClass == null) { // try to get it via simple name eClass = this.owningTransaction.getEClassBySimpleName(eClassName); } return this.startingFromInstancesOf(eClass); } @Override public EObjectQueryStepBuilder<EObject> startingFromEObjectsWith(final EAttribute attribute, final Object value) { checkNotNull(attribute, "Precondition violation - argument 'attribute' must not be NULL!"); ChronoEPackageRegistry registry = this.owningTransaction.getEPackageRegistry(); String vertexPropertyKey = ChronoSphereGraphFormat.createVertexPropertyKey(registry, attribute); TraversalBaseSource<Vertex, Vertex> source = new TraversalBaseSource<> (this.owningTransaction, g -> g.traversal() // start with all vertices .V() // restrict to EObject vertices only .has(ChronoSphereGraphFormat.V_PROP__KIND, VertexKind.EOBJECT.toString()) // restrict to EObject vertices that have the given attribute set to the given value .has(vertexPropertyKey, value) ); return this.createEQueryStepBuilderFromTraversalSource(source); } @Override public EObjectQueryStepBuilder<EObject> startingFromEObject(final EObject eObject) { checkNotNull(eObject, "Precondition violation - argument 'eObject' must not be NULL!"); ChronoEObjectInternal chronoEObject = (ChronoEObjectInternal) eObject; if (chronoEObject.isAttached() == false) { throw new IllegalArgumentException( "The given EObject is not attached to the repository - cannot start a query from it!"); } TraversalBaseSource<Vertex, Vertex> source = new TraversalBaseSource<> (this.owningTransaction, g -> g.traversal() // start the traversal from the vertex that represents the EObject .V(chronoEObject.getId()) ); return this.createEQueryStepBuilderFromTraversalSource(source); } @Override public EObjectQueryStepBuilder<EObject> startingFromEObjects(final Iterable<? extends EObject> eObjects) { checkNotNull(eObjects, "Precondition violation - argument 'eObjects' must not be NULL!"); Iterable<? extends EObject> filteredEObjects = Iterables.filter(eObjects, eObject -> { ChronoEObjectInternal chronoEObject = (ChronoEObjectInternal) eObject; if (chronoEObject.isAttached() == false) { throw new IllegalArgumentException( "One of the given EObjects is not attached to the repository - cannot start a query from them!"); } return chronoEObject.exists(); }); List<String> ids = Lists.newArrayList(); filteredEObjects.forEach(eObject -> { ids.add(((ChronoEObject) eObject).getId()); }); String[] idsArray = ids.toArray(new String[ids.size()]); TraversalBaseSource<Vertex, Vertex> source; if (ids.isEmpty()) { // neither of the given EObjects exists, or the iterable has been empty source = new TraversalBaseSource<>(this.owningTransaction, g -> // start at a random UUID to enforce an empty traversal g.traversal().V(UUID.randomUUID()) ); } else { // start from the given IDs source = new TraversalBaseSource<>(this.owningTransaction, g -> g.traversal().V((Object[]) idsArray) ); } return this.createEQueryStepBuilderFromTraversalSource(source); } @Override public EObjectQueryStepBuilder<EObject> startingFromEObjects(final Iterator<? extends EObject> eObjects) { checkNotNull(eObjects, "Precondition violation - argument 'eObjects' must not be NULL!"); List<EObject> list = Lists.newArrayList(eObjects); return this.startingFromEObjects(list); } // ===================================================================================================================== // HELPER METHODS // ===================================================================================================================== private EObjectQueryStepBuilder<EObject> createEQueryStepBuilderFromTraversalSource(final TraversalBaseSource<Vertex, Vertex> source) { return new EObjectQueryIdentityStepBuilder<>(source); } }
7,840
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryStepBuilderImpl.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/NumericQueryStepBuilderImpl.java
package org.chronos.chronosphere.impl.query; import org.chronos.chronosphere.api.query.NumericQueryStepBuilder; import org.chronos.chronosphere.impl.query.steps.numeric.*; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import java.util.Iterator; import java.util.Optional; public abstract class NumericQueryStepBuilderImpl<S, I, E extends Number> extends AbstractQueryStepBuilder<S, I, E> implements NumericQueryStepBuilder<S, E> { public NumericQueryStepBuilderImpl(final TraversalChainElement previous) { super(previous); } @Override public Optional<Double> sumAsDouble() { Iterator<E> iterator = QueryUtils.prepareTerminalOperation(this, true); Double sum = null; while (iterator.hasNext()) { E next = iterator.next(); if (next == null) { continue; } if (sum != null) { sum += next.doubleValue(); } else { sum = next.doubleValue(); } } return Optional.ofNullable(sum); } @Override public Optional<Long> sumAsLong() { Iterator<E> iterator = QueryUtils.prepareTerminalOperation(this, true); Long sum = null; while (iterator.hasNext()) { E next = iterator.next(); if (next == null) { continue; } if (sum != null) { sum += next.longValue(); } else { sum = next.longValue(); } } return Optional.ofNullable(sum); } @Override public Optional<Double> average() { Iterator<E> iterator = QueryUtils.prepareTerminalOperation(this, true); Double sum = null; long count = 0L; while (iterator.hasNext()) { count++; E next = iterator.next(); if (next == null) { continue; } if (sum != null) { sum += next.doubleValue(); } else { sum = next.doubleValue(); } } if (count == 0) { return Optional.empty(); } return Optional.of(sum / count); } @Override public Optional<Double> maxAsDouble() { Iterator<E> iterator = QueryUtils.prepareTerminalOperation(this, true); Double max = null; while (iterator.hasNext()) { E element = iterator.next(); if (element == null) { continue; } if (max == null || element.doubleValue() > max) { max = element.doubleValue(); } } return Optional.ofNullable(max); } @Override public Optional<Long> maxAsLong() { Iterator<E> iterator = QueryUtils.prepareTerminalOperation(this, true); Long max = null; while (iterator.hasNext()) { E element = iterator.next(); if (element == null) { continue; } if (max == null || element.longValue() > max) { max = element.longValue(); } } return Optional.ofNullable(max); } @Override public Optional<Double> minAsDouble() { Iterator<E> iterator = QueryUtils.prepareTerminalOperation(this, true); Double min = null; while (iterator.hasNext()) { E element = iterator.next(); if (element == null) { continue; } if (min == null || element.doubleValue() < min) { min = element.doubleValue(); } } return Optional.ofNullable(min); } @Override public Optional<Long> minAsLong() { Iterator<E> iterator = QueryUtils.prepareTerminalOperation(this, true); Long min = null; while (iterator.hasNext()) { E element = iterator.next(); if (element == null) { continue; } if (min == null || element.longValue() < min) { min = element.longValue(); } } return Optional.ofNullable(min); } @Override public NumericQueryStepBuilder<S, Long> round() { return new NumericQueryRoundStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Integer> roundToInt() { return new NumericQueryRoundToIntStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Long> floor() { return new NumericQueryFloorStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Long> ceil() { return new NumericQueryCeilStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Byte> asByte() { return new NumericQueryAsByteStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Short> asShort() { return new NumericQueryAsShortStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Integer> asInteger() { return new NumericQueryAsIntegerStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Long> asLong() { return new NumericQueryAsLongStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Float> asFloat() { return new NumericQueryAsFloatStepBuilder<>(this); } @Override public NumericQueryStepBuilder<S, Double> asDouble() { return new NumericQueryAsDoubleStepBuilder<>(this); } }
5,584
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TraversalBaseSource.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/traversal/TraversalBaseSource.java
package org.chronos.chronosphere.impl.query.traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Graph; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; import java.util.function.Function; import static com.google.common.base.Preconditions.*; public class TraversalBaseSource<S, E> implements TraversalSource<S, E> { private final ChronoSphereTransactionInternal tx; private final Function<Graph, GraphTraversal<S, E>> generator; public TraversalBaseSource(ChronoSphereTransactionInternal tx, Function<Graph, GraphTraversal<S, E>> generator) { checkNotNull(generator, "Precondition violation - argument 'generator' must not be NULL!"); this.tx = tx; this.generator = generator; } @Override public GraphTraversal<S, E> createTraversal() { return this.generator.apply(this.tx.getGraph()); } public ChronoSphereTransactionInternal getTransaction() { return this.tx; } }
1,065
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TraversalTransformer.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/traversal/TraversalTransformer.java
package org.chronos.chronosphere.impl.query.traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; @FunctionalInterface public interface TraversalTransformer<S, I, E> extends TraversalChainElement { public GraphTraversal<S, E> transformTraversal(ChronoSphereTransactionInternal tx, GraphTraversal<S, I> traversal); public static <S, E> TraversalTransformer<S, E, E> identity() { return (tx, traversal) -> traversal; } }
558
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
TraversalSource.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/traversal/TraversalSource.java
package org.chronos.chronosphere.impl.query.traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; @FunctionalInterface public interface TraversalSource<S, E> extends TraversalChainElement { public GraphTraversal<S, E> createTraversal(); public static <S, E> TraversalSource<S, E> createAnonymousSource() { return () -> (GraphTraversal<S, E>) __.identity(); } }
490
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryAsByteStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryAsByteStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryAsByteStepBuilder<S> extends NumericQueryStepBuilderImpl<S, Object, Byte> { public NumericQueryAsByteStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Byte> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalToNumeric(traversal, Number::byteValue); } }
880
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryRoundToIntStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryRoundToIntStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryRoundToIntStepBuilder<S, N extends Number> extends NumericQueryStepBuilderImpl<S, N, Integer> { public NumericQueryRoundToIntStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Integer> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, N> traversal) { return traversal.map(traverser -> { if (traverser == null || traverser.get() == null) { // skip NULL values return null; } Number element = traverser.get(); if (element == null) { return null; } return (int) Math.round(element.doubleValue()); }); } }
1,150
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryFloorStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryFloorStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryFloorStepBuilder<S, N extends Number> extends NumericQueryStepBuilderImpl<S, N, Long> { public NumericQueryFloorStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Long> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, N> traversal) { return traversal.map(traverser -> { if (traverser == null || traverser.get() == null) { // skip NULL values return null; } N element = traverser.get(); if (element instanceof Float || element instanceof Double) { return (long) Math.floor(element.doubleValue()); } else { // in any other case, we already have a "whole" number return element.longValue(); } }); } }
1,279
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryAsIntegerStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryAsIntegerStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryAsIntegerStepBuilder<S> extends NumericQueryStepBuilderImpl<S, Object, Integer> { public NumericQueryAsIntegerStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Integer> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalToNumeric(traversal, Number::intValue); } }
891
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryAsShortStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryAsShortStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryAsShortStepBuilder<S> extends NumericQueryStepBuilderImpl<S, Object, Short> { public NumericQueryAsShortStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Short> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalToNumeric(traversal, Number::shortValue); } }
885
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryRoundStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryRoundStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryRoundStepBuilder<S, N extends Number> extends NumericQueryStepBuilderImpl<S, N, Long> { public NumericQueryRoundStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Long> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, N> traversal) { return traversal.map(traverser -> { if (traverser == null || traverser.get() == null) { // skip NULL values return null; } Number element = traverser.get(); if (element == null) { return null; } return Math.round(element.doubleValue()); }); } }
1,128
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryCeilStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryCeilStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryCeilStepBuilder<S, N extends Number> extends NumericQueryStepBuilderImpl<S, N, Long> { public NumericQueryCeilStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Long> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, N> traversal) { return traversal.map(traverser -> { if (traverser == null || traverser.get() == null) { // skip NULL values return null; } N element = traverser.get(); if (element instanceof Float || element instanceof Double) { return (long) Math.ceil(element.doubleValue()); } else { // in any other case, we already have a "whole" number return element.longValue(); } }); } }
1,276
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryAsLongStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryAsLongStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryAsLongStepBuilder<S> extends NumericQueryStepBuilderImpl<S, Object, Long> { public NumericQueryAsLongStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Long> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalToNumeric(traversal, Number::longValue); } }
880
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryAsFloatStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryAsFloatStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryAsFloatStepBuilder<S> extends NumericQueryStepBuilderImpl<S, Object, Float> { public NumericQueryAsFloatStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Float> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalToNumeric(traversal, Number::floatValue); } }
885
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
NumericQueryAsDoubleStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/numeric/NumericQueryAsDoubleStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.numeric; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.chronos.chronosphere.impl.query.NumericQueryStepBuilderImpl; import org.chronos.chronosphere.impl.query.QueryUtils; import org.chronos.chronosphere.impl.query.traversal.TraversalChainElement; import org.chronos.chronosphere.internal.api.ChronoSphereTransactionInternal; public class NumericQueryAsDoubleStepBuilder<S> extends NumericQueryStepBuilderImpl<S, Object, Double> { public NumericQueryAsDoubleStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Double> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Object> traversal) { return QueryUtils.castTraversalToNumeric(traversal, Number::doubleValue); } }
890
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryClosureStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryClosureStepBuilder.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.Direction; 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.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.chronos.common.exceptions.UnknownEnumLiteralException; import org.eclipse.emf.ecore.EReference; import static com.google.common.base.Preconditions.*; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*; public class EObjectQueryClosureStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final EReference eReference; private final Direction direction; public EObjectQueryClosureStepBuilder(final TraversalChainElement previous, final EReference eReference, Direction direction) { super(previous); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); checkNotNull(direction, "Precondition violation - argument 'direction' must not be NULL!"); this.eReference = eReference; this.direction = direction; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { ChronoEPackageRegistry registry = tx.getEPackageRegistry(); String label = ChronoSphereGraphFormat.createReferenceEdgeLabel(registry, this.eReference); GraphTraversal<Vertex, Vertex> closureTraversal; switch (this.direction) { case INCOMING: closureTraversal = in(label); break; case OUTGOING: closureTraversal = out(label); break; case BOTH: closureTraversal = both(label); break; default: throw new UnknownEnumLiteralException(this.direction); } return traversal.repeat(closureTraversal.simplePath()).emit().until(t -> false).dedup(); } }
2,388
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryIdentityStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryIdentityStepBuilder.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; public class EObjectQueryIdentityStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { public EObjectQueryIdentityStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { // well, it's an identity step ;) return traversal; } }
867
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryAndStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryAndStepBuilder.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.QueryStepBuilder; import org.chronos.chronosphere.impl.query.EObjectQueryStepBuilderImpl; 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 EObjectQueryAndStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final QueryStepBuilder<EObject, ?>[] subqueries; @SafeVarargs public EObjectQueryAndStepBuilder(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, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.and(subQueriesToVertexTraversals(tx, this.subqueries, false)); } }
1,363
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryDistinctStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryDistinctStepBuilder.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; public class EObjectQueryDistinctStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { public EObjectQueryDistinctStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.dedup(); } }
833
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryAsEObjectStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryAsEObjectStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import com.google.common.base.Objects; import com.google.common.collect.Iterators; 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.chronos.chronosphere.internal.ogm.api.VertexKind; import org.eclipse.emf.ecore.EObject; import java.util.Collections; public class EObjectQueryAsEObjectStepBuilder<S, I> extends EObjectQueryStepBuilderImpl<S, I> { public EObjectQueryAsEObjectStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, I> traversal) { return traversal.flatMap(traverser -> { Object value = traverser.get(); if (value instanceof EObject) { // return the vertex that represents the EObject return Iterators.singletonIterator(QueryUtils.mapEObjectToVertex(tx, (EObject) value)); } else if (value instanceof Vertex) { Vertex vertex = (Vertex) value; VertexKind kind = ChronoSphereGraphFormat.getVertexKind(vertex); if (Objects.equal(kind, VertexKind.EOBJECT)) { // this vertex represents an EObject return Iterators.singletonIterator(vertex); } else { // whatever this vertex is, it's not an EObject return Collections.emptyIterator(); } } else { return Collections.emptyIterator(); } }); } }
2,072
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryLimitStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryLimitStepBuilder.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; public class EObjectQueryLimitStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final long limit; public EObjectQueryLimitStepBuilder(final TraversalChainElement previous, final long limit) { super(previous); this.limit = limit; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.limit(this.limit); } }
914
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryOrStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryOrStepBuilder.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.QueryStepBuilder; import org.chronos.chronosphere.impl.query.EObjectQueryStepBuilderImpl; 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 EObjectQueryOrStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final QueryStepBuilder<EObject, ?>[] subqueries; @SafeVarargs public EObjectQueryOrStepBuilder(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, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.or(subQueriesToVertexTraversals(tx, this.subqueries, false)); } }
1,361
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryExceptObjectsStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryExceptObjectsStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import com.google.common.collect.Sets; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.emf.api.ChronoEObject; import org.chronos.chronosphere.impl.query.EObjectQueryStepBuilderImpl; 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 EObjectQueryExceptObjectsStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final Set<String> eObjectIDsToExclude; public EObjectQueryExceptObjectsStepBuilder(final TraversalChainElement previous, final Set<?> elementsToExclude) { super(previous); checkNotNull(elementsToExclude, "Precondition violation - argument 'elementsToExclude' must not be NULL!"); this.eObjectIDsToExclude = Sets.newHashSet(); for (Object element : elementsToExclude) { if (element instanceof ChronoEObject == false) { // ignore this object continue; } ChronoEObject cEObject = (ChronoEObject) element; this.eObjectIDsToExclude.add(cEObject.getId()); } } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.filter(t -> { Vertex vertex = t.get(); if (vertex == null) { return false; } return this.eObjectIDsToExclude.contains(vertex.id()) == false; }); } }
1,800
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryEGetReferenceStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryEGetReferenceStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import com.google.common.collect.Iterators; 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.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.eclipse.emf.ecore.EReference; import java.util.List; import static com.google.common.base.Preconditions.*; public class EObjectQueryEGetReferenceStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final EReference eReference; public EObjectQueryEGetReferenceStepBuilder(final TraversalChainElement previous, EReference eReference) { super(previous); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); this.eReference = eReference; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { ChronoEPackageRegistry registry = tx.getEPackageRegistry(); String edgeLabel = ChronoSphereGraphFormat.createReferenceEdgeLabel(registry, this.eReference); if (this.eReference.isOrdered()) { return traversal.flatMap(traverser -> { Vertex vertex = traverser.get(); if (this.eReference.isMany()) { List<Vertex> eReferenceTargets = ChronoSphereGraphFormat.getEReferenceTargets(registry, vertex, this.eReference); return eReferenceTargets.iterator(); } else { Vertex target = ChronoSphereGraphFormat.getEReferenceTarget(registry, vertex, this.eReference); return Iterators.singletonIterator(target); } }); } else { return traversal.out(edgeLabel); } } }
2,192
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryEContentsStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryEContentsStepBuilder.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; public class EObjectQueryEContentsStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { public EObjectQueryEContentsStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.in(ChronoSphereGraphFormat.E_LABEL__ECONTAINER); } }
949
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryInstanceOfEClassNameStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryInstanceOfEClassNameStepBuilder.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.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 EObjectQueryInstanceOfEClassNameStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final String eClassName; private final boolean allowSubclasses; public EObjectQueryInstanceOfEClassNameStepBuilder(final TraversalChainElement previous, String eClassName, boolean allowSubclasses) { super(previous); checkNotNull(eClassName, "Precondition violation - argument 'eClassName' must not be NULL!"); this.eClassName = eClassName; this.allowSubclasses = allowSubclasses; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { // try to find the EClass by qualified name EClass eClass = tx.getEClassByQualifiedName(this.eClassName); if (eClass == null) { // try again, by simple name eClass = tx.getEClassBySimpleName(this.eClassName); } if (eClass == null) { throw new IllegalArgumentException("Could not find EClass with name '" + this.eClassName + "'!"); } EClass finalClass = eClass; if (this.allowSubclasses == false) { String eClassID = tx.getEPackageRegistry().getEClassID(finalClass); 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 // we need to reify the EObject... .map(t -> QueryUtils.mapVertexToEObject(tx, t)) // ... check the condition... .filter(t -> { EObject eObject = t.get(); if (eObject == null) { return false; } return finalClass.isInstance(eObject); }) // ... and transform back .map(t -> QueryUtils.mapEObjectToVertex(tx.getGraph(), t.get())); } } }
2,851
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryNonNullStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryNonNullStepBuilder.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; public class EObjectQueryNonNullStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { public EObjectQueryNonNullStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.filter(t -> t.get() != null); } }
852
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryEContainerStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryEContainerStepBuilder.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; public class EObjectQueryEContainerStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { public EObjectQueryEContainerStepBuilder(final TraversalChainElement previous) { super(previous); } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { return traversal.out(ChronoSphereGraphFormat.E_LABEL__ECONTAINER); } }
953
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryEGetInverseByNameStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryEGetInverseByNameStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import com.google.common.base.Objects; import com.google.common.collect.SetMultimap; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.chronos.chronosphere.emf.internal.util.EMFUtils; 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.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EReference; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.*; public class EObjectQueryEGetInverseByNameStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final String referenceName; public EObjectQueryEGetInverseByNameStepBuilder(final TraversalChainElement previous, String referenceName) { super(previous); checkNotNull(referenceName, "Precondition violation - argument 'referenceName' must not be NULL!"); this.referenceName = referenceName; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { // get the registry ChronoEPackageRegistry registry = tx.getEPackageRegistry(); // get the mapping from EClass to incoming EReferences SetMultimap<EClass, EReference> eClassToIncomingReferences = EMFUtils .eClassToIncomingEReferences(registry.getEPackages()); // filter the references by name Set<EReference> eReferences = eClassToIncomingReferences.values().stream().filter(ref -> Objects.equal(ref.getName(), this.referenceName)).collect(Collectors.toSet()); // generate an array of graph edge labels that correspond to these EReferences List<String> labelList = eReferences.stream().map(ref -> ChronoSphereGraphFormat.createReferenceEdgeLabel(registry, ref)).collect(Collectors.toList()); String[] labels = labelList.toArray(new String[labelList.size()]); // navigate along the incoming edges return traversal.in(labels); } }
2,465
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryHasFeatureValueStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryHasFeatureValueStepBuilder.java
package org.chronos.chronosphere.impl.query.steps.eobject; import com.google.common.base.Objects; 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.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import static com.google.common.base.Preconditions.*; public class EObjectQueryHasFeatureValueStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final EStructuralFeature feature; private final Object value; public EObjectQueryHasFeatureValueStepBuilder(final TraversalChainElement previous, EStructuralFeature feature, Object value) { super(previous); checkNotNull(feature, "Precondition violation - argument 'feature' must not be NULL!"); this.feature = feature; this.value = value; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { ChronoEPackageRegistry registry = tx.getEPackageRegistry(); EStructuralFeature storedFeature = registry.getRegisteredEStructuralFeature(this.feature); if (storedFeature instanceof EAttribute) { // for EAttributes, we can use what's in the graph directly String key = ChronoSphereGraphFormat.createVertexPropertyKey(registry, (EAttribute) storedFeature); return traversal.has(key, this.value); } else { // it's an EReference. return traversal // we need to reify the EObject... .map(t -> QueryUtils.mapVertexToEObject(tx, t)) // ... check the condition... .filter(t -> { EObject eObject = t.get(); if (eObject == null) { return false; } EClass eClass = eObject.eClass(); if (eClass.getEAllStructuralFeatures().contains(storedFeature) == false) { // EClass doesn't support this feature return false; } return Objects.equal(eObject.eGet(storedFeature), this.value); }) // ... and transform back .map(t -> QueryUtils.mapEObjectToVertex(tx.getGraph(), t.get())); } } }
2,936
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z
EObjectQueryEGetInverseByReferenceStepBuilder.java
/FileExtraction/Java_unseen/Txture_chronos/org.chronos.chronosphere/src/main/java/org/chronos/chronosphere/impl/query/steps/eobject/EObjectQueryEGetInverseByReferenceStepBuilder.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.ChronoEPackageRegistry; import org.chronos.chronosphere.internal.ogm.api.ChronoSphereGraphFormat; import org.eclipse.emf.ecore.EReference; import static com.google.common.base.Preconditions.*; public class EObjectQueryEGetInverseByReferenceStepBuilder<S> extends EObjectQueryStepBuilderImpl<S, Vertex> { private final EReference eReference; public EObjectQueryEGetInverseByReferenceStepBuilder(final TraversalChainElement previous, EReference eReference) { super(previous); checkNotNull(eReference, "Precondition violation - argument 'eReference' must not be NULL!"); this.eReference = eReference; } @Override public GraphTraversal<S, Vertex> transformTraversal(final ChronoSphereTransactionInternal tx, final GraphTraversal<S, Vertex> traversal) { ChronoEPackageRegistry registry = tx.getEPackageRegistry(); String edgeLabel = ChronoSphereGraphFormat.createReferenceEdgeLabel(registry, this.eReference); return traversal.in(edgeLabel); } }
1,488
Java
.java
Txture/chronos
26
3
0
2020-05-19T17:35:13Z
2023-03-10T16:19:01Z