index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknBinaryInputFormat.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import org.apache.cassandra.hadoop.ConfigHelper; import org.apache.cassandra.hadoop.cql3.CqlInputFormat; import org.apache.cassandra.thrift.SlicePredicate; import org.apache.cassandra.thrift.SliceRange; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.janusgraph.diskstorage.Entry; import org.janusgraph.diskstorage.StaticBuffer; import org.janusgraph.diskstorage.cassandra.AbstractCassandraStoreManager; import org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration; import org.janusgraph.hadoop.config.JanusGraphHadoopConfiguration; import org.janusgraph.hadoop.formats.util.AbstractBinaryInputFormat; import org.janusgraph.hadoop.formats.util.input.JanusGraphHadoopSetupCommon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; /** * Override JanusGraph's Cassandra3BinaryInputFormat class * * This class removes dependency from columnFamilyInput (which does not exist in Cassandra 3.x) * and instead it relies on the newer CqlInputFormat. */ public class GraknBinaryInputFormat extends AbstractBinaryInputFormat { private static final Logger log = LoggerFactory.getLogger(GraknBinaryInputFormat.class); private static final String INPUT_WIDEROWS_CONFIG = "cassandra.input.widerows"; private static final String RANGE_BATCH_SIZE_CONFIG = "cassandra.range.batch.size"; private final CqlInputFormat cqlInputFormat = new CqlInputFormat(); RecordReader<StaticBuffer, Iterable<Entry>> janusgraphRecordReader; public GraknBinaryInputFormat() { } public RecordReader<StaticBuffer, Iterable<Entry>> getRecordReader() { return this.janusgraphRecordReader; } public List<InputSplit> getSplits(JobContext jobContext) throws IOException { return this.cqlInputFormat.getSplits(jobContext); } public RecordReader<StaticBuffer, Iterable<Entry>> createRecordReader(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { this.janusgraphRecordReader = new GraknCqlBridgeRecordReader(); return this.janusgraphRecordReader; } @Override public void setConf(final Configuration config) { super.setConf(config); // Copy some JanusGraph configuration keys to the Hadoop Configuration keys used by Cassandra's ColumnFamilyInputFormat ConfigHelper.setInputInitialAddress(config, janusgraphConf.get(GraphDatabaseConfiguration.STORAGE_HOSTS)[0]); if (janusgraphConf.has(GraphDatabaseConfiguration.STORAGE_PORT)){ ConfigHelper.setInputRpcPort(config, String.valueOf(janusgraphConf.get(GraphDatabaseConfiguration.STORAGE_PORT))); } if (janusgraphConf.has(GraphDatabaseConfiguration.AUTH_USERNAME)){ ConfigHelper.setInputKeyspaceUserName(config, janusgraphConf.get(GraphDatabaseConfiguration.AUTH_USERNAME)); } if (janusgraphConf.has(GraphDatabaseConfiguration.AUTH_PASSWORD)) { ConfigHelper.setInputKeyspacePassword(config, janusgraphConf.get(GraphDatabaseConfiguration.AUTH_PASSWORD)); } // Copy keyspace, force the CF setting to edgestore, honor widerows when set final boolean wideRows = config.getBoolean(INPUT_WIDEROWS_CONFIG, false); // Use the setInputColumnFamily overload that includes a widerows argument; using the overload without this argument forces it false ConfigHelper.setInputColumnFamily(config, janusgraphConf.get(AbstractCassandraStoreManager.CASSANDRA_KEYSPACE), mrConf.get(JanusGraphHadoopConfiguration.COLUMN_FAMILY_NAME), wideRows); log.debug("Set keyspace: {}", janusgraphConf.get(AbstractCassandraStoreManager.CASSANDRA_KEYSPACE)); // Set the column slice bounds via Faunus' vertex query filter final SlicePredicate predicate = new SlicePredicate(); final int rangeBatchSize = config.getInt(RANGE_BATCH_SIZE_CONFIG, Integer.MAX_VALUE); predicate.setSlice_range(getSliceRange(rangeBatchSize)); // TODO stop slicing the whole row ConfigHelper.setInputSlicePredicate(config, predicate); } private SliceRange getSliceRange(final int limit) { final SliceRange sliceRange = new SliceRange(); sliceRange.setStart(JanusGraphHadoopSetupCommon.DEFAULT_SLICE_QUERY.getSliceStart().asByteBuffer()); sliceRange.setFinish(JanusGraphHadoopSetupCommon.DEFAULT_SLICE_QUERY.getSliceEnd().asByteBuffer()); sliceRange.setCount(Math.min(limit, JanusGraphHadoopSetupCommon.DEFAULT_SLICE_QUERY.getLimit())); return sliceRange; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknCassandra3InputFormat.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import org.janusgraph.hadoop.formats.util.GiraphInputFormat; /** * Override JanusGraph's Cassandra3InputFormat class */ public class GraknCassandra3InputFormat extends GiraphInputFormat { public GraknCassandra3InputFormat() { super(new GraknBinaryInputFormat()); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknComputerImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import ai.grakn.GraknComputer; import ai.grakn.concept.LabelId; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.process.computer.ComputerResult; import org.apache.tinkerpop.gremlin.process.computer.GraphComputer; import org.apache.tinkerpop.gremlin.process.computer.MapReduce; import org.apache.tinkerpop.gremlin.process.computer.VertexProgram; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.tinkergraph.process.computer.TinkerGraphComputer; import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import javax.annotation.Nullable; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; /** * <p> * {@link GraphComputer} Used For Analytics Algorithms * </p> * <p> * Wraps a Tinkerpop {@link GraphComputer} which enables the execution of pregel programs. * These programs are defined either via a {@link MapReduce} or a {@link VertexProgram}. * </p> * <p> * A {@link VertexProgram} is a computation executed on each vertex in parallel. * Vertices communicate with each other through message passing. * </p> * <p> * {@link MapReduce} processed the vertices in a parallel manner by aggregating values emitted by vertices. * MapReduce can be executed alone or used to collect the results after executing a VertexProgram. * </p> * * @author duckofyork * @author sheldonkhall * @author fppt */ public class GraknComputerImpl implements GraknComputer { private final Graph graph; private final Class<? extends GraphComputer> graphComputerClass; private GraphComputer graphComputer = null; private boolean filterAllEdges = false; public GraknComputerImpl(Graph graph) { this.graph = graph; if (graph instanceof TinkerGraph) { graphComputerClass = TinkerGraphComputer.class; } else { graphComputerClass = GraknSparkComputer.class; } } @Override public ComputerResult compute(@Nullable VertexProgram program, @Nullable MapReduce mapReduce, @Nullable Set<LabelId> types, Boolean includesRolePlayerEdges) { try { graphComputer = getGraphComputer(); if (program != null) { graphComputer.program(program); } else { filterAllEdges = true; } if (mapReduce != null) graphComputer.mapReduce(mapReduce); applyFilters(types, includesRolePlayerEdges); return graphComputer.submit().get(); } catch (ExecutionException e) { throw asRuntimeException(e.getCause()); } catch (InterruptedException e) { throw asRuntimeException(e); } } @Override public ComputerResult compute(@Nullable VertexProgram program, @Nullable MapReduce mapReduce, @Nullable Set<LabelId> types) { return compute(program, mapReduce, types, true); } @Override public void killJobs() { if (graphComputer != null && graphComputerClass.equals(GraknSparkComputer.class)) { ((GraknSparkComputer) graphComputer).cancelJobs(); } } private RuntimeException asRuntimeException(Throwable throwable) { Throwable cause = throwable.getCause(); if (cause == null) return new RuntimeException(throwable); if (cause instanceof RuntimeException) { return (RuntimeException) cause; } else { return new RuntimeException(cause); } } protected GraphComputer getGraphComputer() { return graph.compute(this.graphComputerClass); } private void applyFilters(Set<LabelId> types, boolean includesRolePlayerEdge) { if (types == null || types.isEmpty()) return; Set<Integer> labelIds = types.stream().map(LabelId::getValue).collect(Collectors.toSet()); Traversal<Vertex, Vertex> vertexFilter = __.has(Schema.VertexProperty.THING_TYPE_LABEL_ID.name(), P.within(labelIds)); Traversal<Vertex, Edge> edgeFilter; if (filterAllEdges) { edgeFilter = __.<Vertex>bothE().limit(0); } else { edgeFilter = includesRolePlayerEdge ? __.union( __.<Vertex>bothE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()), __.<Vertex>bothE(Schema.EdgeLabel.ATTRIBUTE.getLabel()) .has(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID.name(), P.within(labelIds))) : __.<Vertex>bothE(Schema.EdgeLabel.ATTRIBUTE.getLabel()) .has(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID.name(), P.within(labelIds)); } graphComputer.vertices(vertexFilter).edges(edgeFilter); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknCqlBridgeRecordReader.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ColumnMetadata; import com.datastax.driver.core.Metadata; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.SimpleStatement; import com.datastax.driver.core.TableMetadata; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.hadoop.ColumnFamilySplit; import org.apache.cassandra.hadoop.ConfigHelper; import org.apache.cassandra.hadoop.HadoopCompat; import org.apache.cassandra.hadoop.cql3.CqlConfigHelper; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.janusgraph.diskstorage.Entry; import org.janusgraph.diskstorage.StaticBuffer; import org.janusgraph.diskstorage.util.StaticArrayBuffer; import org.janusgraph.diskstorage.util.StaticArrayEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; /** * <p> Background: The {@link org.apache.cassandra.hadoop.cql3.CqlRecordReader} class has changed * significantly in Cassandra-3 from Cassandra-2. This class acts as a bridge between * CqlRecordReader in Cassandra-2 to Cassandra-3. In essence, this class recreates CqlRecordReader * from Cassandra-3 without referring to it (because otherwise we'd get functionality from * CqlRecordReader on Cassandra-2 and we don't want it). </p> * * @see <a href="https://github.com/JanusGraph/janusgraph/issues/172">Issue 172.</a> */ public class GraknCqlBridgeRecordReader extends RecordReader<StaticBuffer, Iterable<Entry>> { /* Implementation note: This is inspired by Cassandra-3's org/apache/cassandra/hadoop/cql3/CqlRecordReader.java */ private static final Logger log = LoggerFactory.getLogger(GraknCqlBridgeRecordReader.class); private ColumnFamilySplit split; private DistinctKeyIterator distinctKeyIterator; private int totalRowCount; // total number of rows to fetch private String keyspace; private String cfName; private String cqlQuery; private Cluster cluster; private Session session; private IPartitioner partitioner; private String inputColumns; private String userDefinedWhereClauses; private final List<String> partitionKeys = new ArrayList<>(); // partition keys -- key aliases private final LinkedHashMap<String, Boolean> partitionBoundColumns = Maps.newLinkedHashMap(); private int nativeProtocolVersion = 1; // binary type mapping code from CassandraBinaryRecordReader private KV currentKV; GraknCqlBridgeRecordReader() { //package private super(); } @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { this.split = (ColumnFamilySplit) split; Configuration conf = HadoopCompat.getConfiguration(context); totalRowCount = (this.split.getLength() < Long.MAX_VALUE) ? (int) this.split.getLength() : ConfigHelper.getInputSplitSize(conf); cfName = ConfigHelper.getInputColumnFamily(conf); keyspace = ConfigHelper.getInputKeyspace(conf); partitioner = ConfigHelper.getInputPartitioner(conf); inputColumns = CqlConfigHelper.getInputcolumns(conf); userDefinedWhereClauses = CqlConfigHelper.getInputWhereClauses(conf); try { if (cluster != null) { return; } // Previous implementation of this class was instantiating a new Clutser with the following comment: // "disregard the conf as it brings some unforeseen issues." // Cluster.builder().addContactPoints(locations).build(); // The above ignores the config so it's not possible to use it when we need to change default ports // as they won't be correctly propagated. So now we create Cluster using conf. // If this keeps breaking we might need to investigate further. cluster = CqlConfigHelper.getInputCluster(ConfigHelper.getInputInitialAddress(conf).split(","), conf); } catch (Exception e) { throw new RuntimeException("Unable to create cluster for table: " + cfName + ", in keyspace: " + keyspace, e); } // cluster should be represent to a valid cluster now session = cluster.connect(quote(keyspace)); Preconditions.checkState(session != null, "Can't create connection session"); //get negotiated serialization protocol nativeProtocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersion().toInt(); // If the user provides a CQL query then we will use it without validation // otherwise we will fall back to building a query using the: // inputColumns // whereClauses cqlQuery = CqlConfigHelper.getInputCql(conf); // validate that the user hasn't tried to give us a custom query along with input columns // and where clauses if (StringUtils.isNotEmpty(cqlQuery) && (StringUtils.isNotEmpty(inputColumns) || StringUtils.isNotEmpty(userDefinedWhereClauses))) { throw new AssertionError("Cannot define a custom query with input columns and / or where clauses"); } if (StringUtils.isEmpty(cqlQuery)) { cqlQuery = buildQuery(); } log.trace("cqlQuery {}", cqlQuery); distinctKeyIterator = new DistinctKeyIterator(); log.trace("created {}", distinctKeyIterator); } public void close() { if (session != null) { session.close(); } if (cluster != null) { cluster.close(); } } private static class KV { private final StaticArrayBuffer key; private ArrayList<Entry> entries; KV(StaticArrayBuffer key) { this.key = key; } void addEntries(Collection<Entry> toAdd) { if (entries == null) { entries = new ArrayList<>(toAdd.size()); } entries.addAll(toAdd); } } @Override public StaticBuffer getCurrentKey() { return currentKV.key; } @Override public Iterable<Entry> getCurrentValue() throws IOException { return currentKV.entries; } public float getProgress() { if (!distinctKeyIterator.hasNext()) { return 1.0F; } // the progress is likely to be reported slightly off the actual but close enough float progress = ((float) distinctKeyIterator.totalRead / totalRowCount); return progress > 1.0F ? 1.0F : progress; } public boolean nextKeyValue() throws IOException { final Map<StaticArrayBuffer, Map<StaticBuffer, StaticBuffer>> kv = distinctKeyIterator.next(); if (kv == null) { return false; } final Map.Entry<StaticArrayBuffer, Map<StaticBuffer, StaticBuffer>> onlyEntry = Iterables.getOnlyElement(kv.entrySet()); final KV newKV = new KV(onlyEntry.getKey()); final Map<StaticBuffer, StaticBuffer> v = onlyEntry.getValue(); final List<Entry> entries = v.keySet() .stream() .map(column -> StaticArrayEntry.of(column, v.get(column))) .collect(toList()); newKV.addEntries(entries); currentKV = newKV; return true; } /** * Return native version protocol of the cluster connection * * @return serialization protocol version. */ public int getNativeProtocolVersion() { return nativeProtocolVersion; } /** * A non-static nested class that represents an iterator for distinct keys based on the * row iterator from DataStax driver. In the usual case, more than one row will be associated * with a single key in JanusGraph's use of Cassandra. */ private class DistinctKeyIterator implements Iterator<Map<StaticArrayBuffer, Map<StaticBuffer, StaticBuffer>>> { public static final String KEY = "key"; public static final String COLUMN_NAME = "column1"; public static final String VALUE = "value"; private final Iterator<Row> rowIterator; long totalRead; Row previousRow = null; DistinctKeyIterator() { AbstractType type = partitioner.getTokenValidator(); Object startToken = type.compose(type.fromString(split.getStartToken())); Object endToken = type.compose(type.fromString(split.getEndToken())); SimpleStatement statement = new SimpleStatement(cqlQuery, startToken, endToken); rowIterator = session.execute(statement).iterator(); for (ColumnMetadata meta : cluster.getMetadata().getKeyspace(quote(keyspace)).getTable(quote(cfName)).getPartitionKey()) { partitionBoundColumns.put(meta.getName(), Boolean.TRUE); } } @Override public boolean hasNext() { return rowIterator.hasNext(); } /** * <p> * Implements the <i>business logic</i> of the outer class. * Relies on the {@linkplain Iterator} of {@linkplain Row} to get a map of rows that correspond * to the same key. * </p> * <p> * Note: This is not a general purpose iterator. There is no provision of {@linkplain java.util.ConcurrentModificationException} * while iterating using this iterator. * </p> * * @return the next element in the iteration of distinct keys, returns <code>null</code> to indicate * end of iteration */ @Override public Map<StaticArrayBuffer, Map<StaticBuffer, StaticBuffer>> next() { if (!rowIterator.hasNext()) { return null; // null means no more data } Map<StaticArrayBuffer, Map<StaticBuffer, StaticBuffer>> keyColumnValues = new HashMap<>(); // key -> (column1 -> value) Row row; if (previousRow == null) { row = rowIterator.next(); // just the first time, should succeed } else { row = previousRow; } StaticArrayBuffer key = StaticArrayBuffer.of(row.getBytesUnsafe(KEY)); StaticBuffer column1 = StaticArrayBuffer.of(row.getBytesUnsafe(COLUMN_NAME)); StaticBuffer value = StaticArrayBuffer.of(row.getBytesUnsafe(VALUE)); Map<StaticBuffer, StaticBuffer> cvs = new HashMap<>(); cvs.put(column1, value); keyColumnValues.put(key, cvs); while (rowIterator.hasNext()) { Row nextRow = rowIterator.next(); StaticArrayBuffer nextKey = StaticArrayBuffer.of(nextRow.getBytesUnsafe(KEY)); if (!key.equals(nextKey)) { previousRow = nextRow; break; } StaticBuffer nextColumn = StaticArrayBuffer.of(nextRow.getBytesUnsafe(COLUMN_NAME)); StaticBuffer nextValue = StaticArrayBuffer.of(nextRow.getBytesUnsafe(VALUE)); cvs.put(nextColumn, nextValue); totalRead++; } return keyColumnValues; } } /** * Build a query for the reader of the form: * <p> * SELECT * FROM ks>cf token(pk1,...pkn)>? AND token(pk1,...pkn)<=? [AND user where clauses] * [ALLOW FILTERING] */ private String buildQuery() { fetchKeys(); List<String> columns = getSelectColumns(); String selectColumnList = columns.size() == 0 ? "*" : makeColumnList(columns); String partitionKeyList = makeColumnList(partitionKeys); return String.format("SELECT %s FROM %s.%s WHERE token(%s)>? AND token(%s)<=?" + getAdditionalWhereClauses(), selectColumnList, quote(keyspace), quote(cfName), partitionKeyList, partitionKeyList); } private String getAdditionalWhereClauses() { String whereClause = ""; if (StringUtils.isNotEmpty(userDefinedWhereClauses)) { whereClause += " AND " + userDefinedWhereClauses; } if (StringUtils.isNotEmpty(userDefinedWhereClauses)) { whereClause += " ALLOW FILTERING"; } return whereClause; } private List<String> getSelectColumns() { List<String> selectColumns = new ArrayList<>(); if (StringUtils.isNotEmpty(inputColumns)) { // We must select all the partition keys plus any other columns the user wants selectColumns.addAll(partitionKeys); for (String column : Splitter.on(',').split(inputColumns)) { if (!partitionKeys.contains(column)) { selectColumns.add(column); } } } return selectColumns; } private String makeColumnList(Collection<String> columns) { return columns.stream().map(this::quote).collect(Collectors.joining(",")); } private void fetchKeys() { // get CF meta data TableMetadata tableMetadata = session.getCluster() .getMetadata() .getKeyspace(Metadata.quote(keyspace)) .getTable(Metadata.quote(cfName)); if (tableMetadata == null) { throw new RuntimeException("No table metadata found for " + keyspace + "." + cfName); } //Here we assume that tableMetadata.getPartitionKey() always //returns the list of columns in order of component_index for (ColumnMetadata partitionKey : tableMetadata.getPartitionKey()) { partitionKeys.add(partitionKey.getName()); } } private String quote(String identifier) { return "\"" + identifier.replaceAll("\"", "\"\"") + "\""; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknSparkComputer.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import org.apache.commons.configuration.ConfigurationUtils; import org.apache.commons.configuration.FileConfiguration; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.spark.HashPartitioner; import org.apache.spark.Partitioner; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.launcher.SparkLauncher; import org.apache.spark.serializer.KryoSerializer; import org.apache.spark.storage.StorageLevel; import org.apache.tinkerpop.gremlin.hadoop.Constants; import org.apache.tinkerpop.gremlin.hadoop.process.computer.AbstractHadoopGraphComputer; import org.apache.tinkerpop.gremlin.hadoop.process.computer.util.ComputerSubmissionHelper; import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopConfiguration; import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph; import org.apache.tinkerpop.gremlin.hadoop.structure.io.FileSystemStorage; import org.apache.tinkerpop.gremlin.hadoop.structure.io.GraphFilterAware; import org.apache.tinkerpop.gremlin.hadoop.structure.io.HadoopPoolShimService; import org.apache.tinkerpop.gremlin.hadoop.structure.io.VertexWritable; import org.apache.tinkerpop.gremlin.hadoop.structure.util.ConfUtil; import org.apache.tinkerpop.gremlin.process.computer.ComputerResult; import org.apache.tinkerpop.gremlin.process.computer.GraphComputer; import org.apache.tinkerpop.gremlin.process.computer.MapReduce; import org.apache.tinkerpop.gremlin.process.computer.Memory; import org.apache.tinkerpop.gremlin.process.computer.VertexProgram; import org.apache.tinkerpop.gremlin.process.computer.util.DefaultComputerResult; import org.apache.tinkerpop.gremlin.process.computer.util.MapMemory; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies; import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalInterruptedException; import org.apache.tinkerpop.gremlin.spark.process.computer.payload.ViewIncomingPayload; import org.apache.tinkerpop.gremlin.spark.process.computer.traversal.strategy.optimization.SparkInterceptorStrategy; import org.apache.tinkerpop.gremlin.spark.process.computer.traversal.strategy.optimization.SparkSingleIterationStrategy; import org.apache.tinkerpop.gremlin.spark.structure.Spark; import org.apache.tinkerpop.gremlin.spark.structure.io.InputFormatRDD; import org.apache.tinkerpop.gremlin.spark.structure.io.InputOutputHelper; import org.apache.tinkerpop.gremlin.spark.structure.io.InputRDD; import org.apache.tinkerpop.gremlin.spark.structure.io.OutputFormatRDD; import org.apache.tinkerpop.gremlin.spark.structure.io.OutputRDD; import org.apache.tinkerpop.gremlin.spark.structure.io.PersistedInputRDD; import org.apache.tinkerpop.gremlin.spark.structure.io.PersistedOutputRDD; import org.apache.tinkerpop.gremlin.spark.structure.io.SparkContextStorage; import org.apache.tinkerpop.gremlin.spark.structure.io.gryo.GryoRegistrator; import org.apache.tinkerpop.gremlin.spark.structure.io.gryo.kryoshim.unshaded.UnshadedKryoShimService; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.io.IoRegistry; import org.apache.tinkerpop.gremlin.structure.io.Storage; import org.apache.tinkerpop.gremlin.structure.io.gryo.kryoshim.KryoShimServiceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadLocalRandom; /** * <p> * This is a modified version of Spark Computer. * We change its behaviour so it can won't destroy the rdd after every job. * </p> * * @author Jason Liu * @author Marko A. Rodriguez */ public final class GraknSparkComputer extends AbstractHadoopGraphComputer { private static final Logger LOGGER = LoggerFactory.getLogger(GraknSparkComputer.class); private final org.apache.commons.configuration.Configuration sparkConfiguration; private boolean workersSet = false; private final ThreadFactory threadFactoryBoss = new BasicThreadFactory.Builder().namingPattern(GraknSparkComputer.class.getSimpleName() + "-boss").build(); private static final Set<String> KEYS_PASSED_IN_JVM_SYSTEM_PROPERTIES = new HashSet<>(Arrays.asList( KryoShimServiceLoader.KRYO_SHIM_SERVICE, IoRegistry.IO_REGISTRY)); private final ExecutorService computerService = Executors.newSingleThreadExecutor(threadFactoryBoss); static { TraversalStrategies.GlobalCache.registerStrategies(GraknSparkComputer.class, TraversalStrategies.GlobalCache.getStrategies(GraphComputer.class).clone().addStrategies( SparkSingleIterationStrategy.instance(), SparkInterceptorStrategy.instance())); } private String jobGroupId = null; public GraknSparkComputer(final HadoopGraph hadoopGraph) { super(hadoopGraph); this.sparkConfiguration = new HadoopConfiguration(); ConfigurationUtils.copy(this.hadoopGraph.configuration(), this.sparkConfiguration); } @Override public GraphComputer workers(final int workers) { super.workers(workers); if (this.sparkConfiguration.containsKey(SparkLauncher.SPARK_MASTER) && this.sparkConfiguration.getString(SparkLauncher.SPARK_MASTER).startsWith("local")) { this.sparkConfiguration.setProperty(SparkLauncher.SPARK_MASTER, "local[" + this.workers + "]"); } this.workersSet = true; return this; } @Override public GraphComputer configure(final String key, final Object value) { this.sparkConfiguration.setProperty(key, value); return this; } @Override public Future<ComputerResult> submit() { this.validateStatePriorToExecution(); return ComputerSubmissionHelper .runWithBackgroundThread(exec -> submitWithExecutor(), "SparkSubmitter"); } public void cancelJobs() { if (jobGroupId != null) { Spark.getContext().cancelJobGroup(jobGroupId); } } @SuppressWarnings("PMD.UnusedFormalParameter") private Future<ComputerResult> submitWithExecutor() { jobGroupId = Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE)); String jobDescription = this.vertexProgram == null ? this.mapReducers.toString() : this.vertexProgram + "+" + this.mapReducers; // Use different output locations this.sparkConfiguration.setProperty(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION, this.sparkConfiguration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION) + "/" + jobGroupId); updateConfigKeys(sparkConfiguration); final Future<ComputerResult> result = computerService.submit(() -> { final long startTime = System.currentTimeMillis(); ////////////////////////////////////////////////// /////// PROCESS SHIM AND SYSTEM PROPERTIES /////// ////////////////////////////////////////////////// final String shimService = KryoSerializer.class.getCanonicalName().equals(this.sparkConfiguration.getString(Constants.SPARK_SERIALIZER, null)) ? UnshadedKryoShimService.class.getCanonicalName() : HadoopPoolShimService.class.getCanonicalName(); this.sparkConfiguration.setProperty(KryoShimServiceLoader.KRYO_SHIM_SERVICE, shimService); /////////// final StringBuilder params = new StringBuilder(); this.sparkConfiguration.getKeys().forEachRemaining(key -> { if (KEYS_PASSED_IN_JVM_SYSTEM_PROPERTIES.contains(key)) { params.append(" -D").append("tinkerpop.").append(key).append("=").append(this.sparkConfiguration.getProperty(key)); System.setProperty("tinkerpop." + key, this.sparkConfiguration.getProperty(key).toString()); } }); if (params.length() > 0) { this.sparkConfiguration.setProperty(SparkLauncher.EXECUTOR_EXTRA_JAVA_OPTIONS, (this.sparkConfiguration.getString(SparkLauncher.EXECUTOR_EXTRA_JAVA_OPTIONS, "") + params.toString()).trim()); this.sparkConfiguration.setProperty(SparkLauncher.DRIVER_EXTRA_JAVA_OPTIONS, (this.sparkConfiguration.getString(SparkLauncher.DRIVER_EXTRA_JAVA_OPTIONS, "") + params.toString()).trim()); } KryoShimServiceLoader.applyConfiguration(this.sparkConfiguration); ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// // apache and hadoop configurations that are used throughout the graph computer computation final org.apache.commons.configuration.Configuration graphComputerConfiguration = new HadoopConfiguration(this.sparkConfiguration); if (!graphComputerConfiguration.containsKey(Constants.SPARK_SERIALIZER)) { graphComputerConfiguration.setProperty(Constants.SPARK_SERIALIZER, KryoSerializer.class.getCanonicalName()); if (!graphComputerConfiguration.containsKey(Constants.SPARK_KRYO_REGISTRATOR)){ graphComputerConfiguration.setProperty(Constants.SPARK_KRYO_REGISTRATOR, GryoRegistrator.class.getCanonicalName());} } graphComputerConfiguration.setProperty(Constants.GREMLIN_HADOOP_GRAPH_WRITER_HAS_EDGES, this.persist.equals(GraphComputer.Persist.EDGES)); final Configuration hadoopConfiguration = ConfUtil.makeHadoopConfiguration(graphComputerConfiguration); final Storage fileSystemStorage = FileSystemStorage.open(hadoopConfiguration); final boolean inputFromHDFS = FileInputFormat.class.isAssignableFrom( hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_READER, Object.class)); final boolean inputFromSpark = PersistedInputRDD.class.isAssignableFrom( hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_READER, Object.class)); final boolean outputToHDFS = FileOutputFormat.class.isAssignableFrom( hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_WRITER, Object.class)); final boolean outputToSpark = PersistedOutputRDD.class.isAssignableFrom( hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_WRITER, Object.class)); final boolean skipPartitioner = graphComputerConfiguration.getBoolean( Constants.GREMLIN_SPARK_SKIP_PARTITIONER, false); final boolean skipPersist = graphComputerConfiguration.getBoolean( Constants.GREMLIN_SPARK_SKIP_GRAPH_CACHE, false); if (inputFromHDFS) { String inputLocation = Constants .getSearchGraphLocation( hadoopConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION), fileSystemStorage) .orElse(null); if (null != inputLocation) { try { graphComputerConfiguration.setProperty(Constants.MAPREDUCE_INPUT_FILEINPUTFORMAT_INPUTDIR, FileSystem.get(hadoopConfiguration).getFileStatus(new Path(inputLocation)).getPath() .toString()); hadoopConfiguration.set(Constants.MAPREDUCE_INPUT_FILEINPUTFORMAT_INPUTDIR, FileSystem.get(hadoopConfiguration).getFileStatus(new Path(inputLocation)).getPath() .toString()); } catch (final IOException e) { throw new IllegalStateException(e.getMessage(), e); } } } final InputRDD inputRDD; final OutputRDD outputRDD; final boolean filtered; try { inputRDD = InputRDD.class.isAssignableFrom( hadoopConfiguration.getClass( Constants.GREMLIN_HADOOP_GRAPH_READER, Object.class)) ? hadoopConfiguration.getClass( Constants.GREMLIN_HADOOP_GRAPH_READER, InputRDD.class, InputRDD.class).newInstance() : InputFormatRDD.class.newInstance(); outputRDD = OutputRDD.class.isAssignableFrom( hadoopConfiguration.getClass( Constants.GREMLIN_HADOOP_GRAPH_WRITER, Object.class)) ? hadoopConfiguration.getClass( Constants.GREMLIN_HADOOP_GRAPH_WRITER, OutputRDD.class, OutputRDD.class).newInstance() : OutputFormatRDD.class.newInstance(); // if the input class can filter on load, then set the filters if (inputRDD instanceof InputFormatRDD && GraphFilterAware.class.isAssignableFrom(hadoopConfiguration.getClass( Constants.GREMLIN_HADOOP_GRAPH_READER, InputFormat.class, InputFormat.class))) { GraphFilterAware.storeGraphFilter( graphComputerConfiguration, hadoopConfiguration, this.graphFilter); filtered = false; } else if (inputRDD instanceof GraphFilterAware) { ((GraphFilterAware) inputRDD).setGraphFilter(this.graphFilter); filtered = false; } else filtered = this.graphFilter.hasFilter(); } catch (final InstantiationException | IllegalAccessException e) { throw new IllegalStateException(e.getMessage(), e); } // create the spark context from the graph computer configuration final JavaSparkContext sparkContext = new JavaSparkContext(Spark.create(hadoopConfiguration)); final Storage sparkContextStorage = SparkContextStorage.open(); sparkContext.setJobGroup(jobGroupId, jobDescription); GraknSparkMemory memory = null; // delete output location final String outputLocation = hadoopConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION, null); if (null != outputLocation) { if (outputToHDFS && fileSystemStorage.exists(outputLocation)) { fileSystemStorage.rm(outputLocation); } if (outputToSpark && sparkContextStorage.exists(outputLocation)) { sparkContextStorage.rm(outputLocation); } } // the Spark application name will always be set by SparkContextStorage, // thus, INFO the name to make it easier to debug logger.debug(Constants.GREMLIN_HADOOP_SPARK_JOB_PREFIX + (null == this.vertexProgram ? "No VertexProgram" : this.vertexProgram) + "[" + this.mapReducers + "]"); // add the project jars to the cluster this.loadJars(hadoopConfiguration, sparkContext); updateLocalConfiguration(sparkContext, hadoopConfiguration); // create a message-passing friendly rdd from the input rdd boolean partitioned = false; JavaPairRDD<Object, VertexWritable> loadedGraphRDD = inputRDD.readGraphRDD(graphComputerConfiguration, sparkContext); // if there are vertex or edge filters, filter the loaded graph rdd prior to partitioning and persisting if (filtered) { this.logger.debug("Filtering the loaded graphRDD: " + this.graphFilter); loadedGraphRDD = GraknSparkExecutor.applyGraphFilter(loadedGraphRDD, this.graphFilter); } // if the loaded graph RDD is already partitioned use that partitioner, // else partition it with HashPartitioner if (loadedGraphRDD.partitioner().isPresent()) { this.logger.debug("Using the existing partitioner associated with the loaded graphRDD: " + loadedGraphRDD.partitioner().get()); } else { if (!skipPartitioner) { final Partitioner partitioner = new HashPartitioner(this.workersSet ? this.workers : loadedGraphRDD.partitions().size()); this.logger.debug("Partitioning the loaded graphRDD: " + partitioner); loadedGraphRDD = loadedGraphRDD.partitionBy(partitioner); partitioned = true; assert loadedGraphRDD.partitioner().isPresent(); } else { // no easy way to test this with a test case assert skipPartitioner == !loadedGraphRDD.partitioner().isPresent(); this.logger.debug("Partitioning has been skipped for the loaded graphRDD via " + Constants.GREMLIN_SPARK_SKIP_PARTITIONER); } } // if the loaded graphRDD was already partitioned previous, // then this coalesce/repartition will not take place if (this.workersSet) { // ensures that the loaded graphRDD does not have more partitions than workers if (loadedGraphRDD.partitions().size() > this.workers) { loadedGraphRDD = loadedGraphRDD.coalesce(this.workers); } else { // ensures that the loaded graphRDD does not have less partitions than workers if (loadedGraphRDD.partitions().size() < this.workers) { loadedGraphRDD = loadedGraphRDD.repartition(this.workers); } } } // persist the vertex program loaded graph as specified by configuration // or else use default cache() which is MEMORY_ONLY if (!skipPersist && (!inputFromSpark || partitioned || filtered)) { loadedGraphRDD = loadedGraphRDD.persist(StorageLevel.fromString(hadoopConfiguration.get( Constants.GREMLIN_SPARK_GRAPH_STORAGE_LEVEL, "MEMORY_ONLY"))); } // final graph with view // (for persisting and/or mapReducing -- may be null and thus, possible to save space/time) JavaPairRDD<Object, VertexWritable> computedGraphRDD = null; try { //////////////////////////////// // process the vertex program // //////////////////////////////// if (null != this.vertexProgram) { memory = new GraknSparkMemory(this.vertexProgram, this.mapReducers, sparkContext); ///////////////// // if there is a registered VertexProgramInterceptor, use it to bypass the GraphComputer semantics if (graphComputerConfiguration.containsKey(Constants.GREMLIN_HADOOP_VERTEX_PROGRAM_INTERCEPTOR)) { try { final GraknSparkVertexProgramInterceptor<VertexProgram> interceptor = (GraknSparkVertexProgramInterceptor) Class.forName(graphComputerConfiguration.getString( Constants.GREMLIN_HADOOP_VERTEX_PROGRAM_INTERCEPTOR)).newInstance(); computedGraphRDD = interceptor.apply(this.vertexProgram, loadedGraphRDD, memory); } catch (final ClassNotFoundException | IllegalAccessException | InstantiationException e) { throw new IllegalStateException(e.getMessage()); } } else { // standard GraphComputer semantics // get a configuration that will be propagated to all workers final HadoopConfiguration vertexProgramConfiguration = new HadoopConfiguration(); this.vertexProgram.storeState(vertexProgramConfiguration); // set up the vertex program and wire up configurations this.vertexProgram.setup(memory); JavaPairRDD<Object, ViewIncomingPayload<Object>> viewIncomingRDD = null; memory.broadcastMemory(sparkContext); // execute the vertex program while (true) { if (Thread.interrupted()) { sparkContext.cancelAllJobs(); throw new TraversalInterruptedException(); } memory.setInExecute(true); viewIncomingRDD = GraknSparkExecutor.executeVertexProgramIteration( loadedGraphRDD, viewIncomingRDD, memory, graphComputerConfiguration, vertexProgramConfiguration); memory.setInExecute(false); if (this.vertexProgram.terminate(memory)) { break; } else { memory.incrIteration(); memory.broadcastMemory(sparkContext); } } // if the graph will be continued to be used (persisted or mapreduced), // then generate a view+graph if ((null != outputRDD && !this.persist.equals(Persist.NOTHING)) || !this.mapReducers.isEmpty()) { computedGraphRDD = GraknSparkExecutor.prepareFinalGraphRDD( loadedGraphRDD, viewIncomingRDD, this.vertexProgram.getVertexComputeKeys()); assert null != computedGraphRDD && computedGraphRDD != loadedGraphRDD; } else { // ensure that the computedGraphRDD was not created assert null == computedGraphRDD; } } ///////////////// memory.complete(); // drop all transient memory keys // write the computed graph to the respective output (rdd or output format) if (null != outputRDD && !this.persist.equals(Persist.NOTHING)) { // the logic holds that a computeGraphRDD must be created at this point assert null != computedGraphRDD; outputRDD.writeGraphRDD(graphComputerConfiguration, computedGraphRDD); } } final boolean computedGraphCreated = computedGraphRDD != null && computedGraphRDD != loadedGraphRDD; if (!computedGraphCreated) { computedGraphRDD = loadedGraphRDD; } final Memory.Admin finalMemory = null == memory ? new MapMemory() : new MapMemory(memory); ////////////////////////////// // process the map reducers // ////////////////////////////// if (!this.mapReducers.isEmpty()) { // create a mapReduceRDD for executing the map reduce jobs on JavaPairRDD<Object, VertexWritable> mapReduceRDD = computedGraphRDD; if (computedGraphCreated && !outputToSpark) { // drop all the edges of the graph as they are not used in mapReduce processing mapReduceRDD = computedGraphRDD.mapValues(vertexWritable -> { vertexWritable.get().dropEdges(Direction.BOTH); return vertexWritable; }); // if there is only one MapReduce to execute, don't bother wasting the clock cycles. if (this.mapReducers.size() > 1) { mapReduceRDD = mapReduceRDD.persist(StorageLevel.fromString(hadoopConfiguration.get( Constants.GREMLIN_SPARK_GRAPH_STORAGE_LEVEL, "MEMORY_ONLY"))); } } for (final MapReduce mapReduce : this.mapReducers) { // execute the map reduce job final HadoopConfiguration newApacheConfiguration = new HadoopConfiguration(graphComputerConfiguration); mapReduce.storeState(newApacheConfiguration); // map final JavaPairRDD mapRDD = GraknSparkExecutor.executeMap(mapReduceRDD, mapReduce, newApacheConfiguration); // combine final JavaPairRDD combineRDD = mapReduce.doStage(MapReduce.Stage.COMBINE) ? GraknSparkExecutor.executeCombine(mapRDD, newApacheConfiguration) : mapRDD; // reduce final JavaPairRDD reduceRDD = mapReduce.doStage(MapReduce.Stage.REDUCE) ? GraknSparkExecutor.executeReduce(combineRDD, mapReduce, newApacheConfiguration) : combineRDD; // write the map reduce output back to disk and computer result memory if (null != outputRDD) { mapReduce.addResultToMemory(finalMemory, outputRDD.writeMemoryRDD( graphComputerConfiguration, mapReduce.getMemoryKey(), reduceRDD)); } } // if the mapReduceRDD is not simply the computed graph, unpersist the mapReduceRDD if (computedGraphCreated && !outputToSpark) { assert loadedGraphRDD != computedGraphRDD; assert mapReduceRDD != computedGraphRDD; mapReduceRDD.unpersist(); } else { assert mapReduceRDD == computedGraphRDD; } } // unpersist the loaded graph if it will not be used again (no PersistedInputRDD) // if the graphRDD was loaded from Spark, but then partitioned or filtered, its a different RDD if (!inputFromSpark || partitioned || filtered) { loadedGraphRDD.unpersist(); } // unpersist the computed graph if it will not be used again (no PersistedOutputRDD) // if the computed graph is the loadedGraphRDD because it was not mutated and not-unpersisted, // then don't unpersist the computedGraphRDD/loadedGraphRDD if ((!outputToSpark || this.persist.equals(GraphComputer.Persist.NOTHING)) && computedGraphCreated) { computedGraphRDD.unpersist(); } // delete any file system or rdd data if persist nothing if (null != outputLocation && this.persist.equals(GraphComputer.Persist.NOTHING)) { if (outputToHDFS) { fileSystemStorage.rm(outputLocation); } if (outputToSpark) { sparkContextStorage.rm(outputLocation); } } // update runtime and return the newly computed graph finalMemory.setRuntime(System.currentTimeMillis() - startTime); // clear properties that should not be propagated in an OLAP chain graphComputerConfiguration.clearProperty(Constants.GREMLIN_HADOOP_GRAPH_FILTER); graphComputerConfiguration.clearProperty(Constants.GREMLIN_HADOOP_VERTEX_PROGRAM_INTERCEPTOR); graphComputerConfiguration.clearProperty(Constants.GREMLIN_SPARK_SKIP_GRAPH_CACHE); graphComputerConfiguration.clearProperty(Constants.GREMLIN_SPARK_SKIP_PARTITIONER); return new DefaultComputerResult( InputOutputHelper.getOutputGraph(graphComputerConfiguration, this.resultGraph, this.persist), finalMemory.asImmutable()); } catch (Exception e) { // So it throws the same exception as tinker does throw new RuntimeException(e); } }); computerService.shutdown(); return result; } private static void updateConfigKeys(org.apache.commons.configuration.Configuration sparkConfiguration) { Set<String> wrongKeys = new HashSet<>(); sparkConfiguration.getKeys().forEachRemaining(wrongKeys::add); wrongKeys.forEach(key -> { if (key.startsWith("janusmr")) { String newKey = "janusgraphmr" + key.substring(7); sparkConfiguration.setProperty(newKey, sparkConfiguration.getString(key)); } }); } ///////////////// @Override protected void loadJar(final Configuration hadoopConfiguration, final File file, final Object... params) { final JavaSparkContext sparkContext = (JavaSparkContext) params[0]; sparkContext.addJar(file.getAbsolutePath()); } /** * When using a persistent context the running Context's configuration will override a passed * in configuration. Spark allows us to override these inherited properties via * SparkContext.setLocalProperty */ private static void updateLocalConfiguration(final JavaSparkContext sparkContext, final Configuration configuration) { /* * While we could enumerate over the entire SparkConfiguration and copy into the Thread * Local properties of the Spark Context this could cause adverse effects with future * versions of Spark. Since the api for setting multiple local properties at once is * restricted as private, we will only set those properties we know can effect SparkGraphComputer * Execution rather than applying the entire configuration. */ final String[] validPropertyNames = { "spark.job.description", "spark.jobGroup.id", "spark.job.interruptOnCancel", "spark.scheduler.pool" }; for (String propertyName : validPropertyNames) { String propertyValue = configuration.get(propertyName); if (propertyValue != null) { LOGGER.info("Setting Thread Local SparkContext Property - " + propertyName + " : " + propertyValue); sparkContext.setLocalProperty(propertyName, configuration.get(propertyName)); } } } public static void main(final String[] args) throws Exception { final FileConfiguration configuration = new PropertiesConfiguration(args[0]); new GraknSparkComputer(HadoopGraph.open(configuration)) .program(VertexProgram.createVertexProgram(HadoopGraph.open(configuration), configuration)) .submit().get(); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknSparkExecutor.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import org.apache.commons.configuration.Configuration; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.Optional; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.PairFlatMapFunction; import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph; import org.apache.tinkerpop.gremlin.hadoop.structure.io.VertexWritable; import org.apache.tinkerpop.gremlin.process.computer.GraphFilter; import org.apache.tinkerpop.gremlin.process.computer.MapReduce; import org.apache.tinkerpop.gremlin.process.computer.MessageCombiner; import org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey; import org.apache.tinkerpop.gremlin.process.computer.VertexProgram; import org.apache.tinkerpop.gremlin.process.computer.util.ComputerGraph; import org.apache.tinkerpop.gremlin.process.computer.util.VertexProgramHelper; import org.apache.tinkerpop.gremlin.spark.process.computer.CombineIterator; import org.apache.tinkerpop.gremlin.spark.process.computer.MapIterator; import org.apache.tinkerpop.gremlin.spark.process.computer.ReduceIterator; import org.apache.tinkerpop.gremlin.spark.process.computer.SparkMessenger; import org.apache.tinkerpop.gremlin.spark.process.computer.payload.MessagePayload; import org.apache.tinkerpop.gremlin.spark.process.computer.payload.Payload; import org.apache.tinkerpop.gremlin.spark.process.computer.payload.ViewIncomingPayload; import org.apache.tinkerpop.gremlin.spark.process.computer.payload.ViewOutgoingPayload; import org.apache.tinkerpop.gremlin.spark.process.computer.payload.ViewPayload; import org.apache.tinkerpop.gremlin.structure.io.gryo.kryoshim.KryoShimServiceLoader; import org.apache.tinkerpop.gremlin.structure.util.Attachable; import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedFactory; import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertexProperty; import org.apache.tinkerpop.gremlin.structure.util.star.StarGraph; import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils; import scala.Tuple2; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; /** * <p> * This is a modified version of Spark Executor. * We change its behaviour so it can work with our own graph computer. * </p> * * @author Jason Liu * @author Marko A. Rodriguez */ public class GraknSparkExecutor { private GraknSparkExecutor() { } ////////////////// // DATA LOADING // ////////////////// public static JavaPairRDD<Object, VertexWritable> applyGraphFilter(final JavaPairRDD<Object, VertexWritable> graphRDD, final GraphFilter graphFilter) { return graphRDD.mapPartitionsToPair(partitionIterator -> { final GraphFilter gFilter = graphFilter.clone(); return IteratorUtils.filter(partitionIterator, tuple -> (tuple._2().get().applyGraphFilter(gFilter)).isPresent()); }, true); } //////////////////// // VERTEX PROGRAM // //////////////////// public static <M> JavaPairRDD<Object, ViewIncomingPayload<M>> executeVertexProgramIteration( final JavaPairRDD<Object, VertexWritable> graphRDD, final JavaPairRDD<Object, ViewIncomingPayload<M>> viewIncomingRDD, final GraknSparkMemory memory, final Configuration graphComputerConfiguration, // has the Graph/GraphComputer.configuration() information final Configuration vertexProgramConfiguration) { // has the VertexProgram.loadState() information boolean partitionedGraphRDD = graphRDD.partitioner().isPresent(); if (partitionedGraphRDD && null != viewIncomingRDD) // the graphRDD and the viewRDD must have the same partitioner {assert graphRDD.partitioner().get().equals(viewIncomingRDD.partitioner().get());} final JavaPairRDD<Object, ViewOutgoingPayload<M>> viewOutgoingRDD = ((null == viewIncomingRDD) ? graphRDD.mapValues(vertexWritable -> new Tuple2<>(vertexWritable, Optional.<ViewIncomingPayload<M>>absent())) : // first iteration will not have any views or messages graphRDD.leftOuterJoin(viewIncomingRDD)) // every other iteration may have views and messages // for each partition of vertices emit a view and their outgoing messages .mapPartitionsToPair(partitionIterator -> { KryoShimServiceLoader.applyConfiguration(graphComputerConfiguration); // if the partition is empty, return without starting a new VP iteration if (!partitionIterator.hasNext()){ return Collections.emptyIterator();} final VertexProgram<M> workerVertexProgram = VertexProgram.createVertexProgram(HadoopGraph.open(graphComputerConfiguration), vertexProgramConfiguration); // each partition(Spark)/worker(TP3) has a local copy of the vertex program (a worker's task) final String[] vertexComputeKeysArray = VertexProgramHelper.vertexComputeKeysAsArray(workerVertexProgram.getVertexComputeKeys()); // the compute keys as an array final SparkMessenger<M> messenger = new SparkMessenger<>(); workerVertexProgram.workerIterationStart(memory.asImmutable()); // start the worker return IteratorUtils.map(partitionIterator, vertexViewIncoming -> { final StarGraph.StarVertex vertex = vertexViewIncoming._2()._1().get(); // get the vertex from the vertex writable final boolean hasViewAndMessages = vertexViewIncoming._2()._2().isPresent(); // if this is the first iteration, then there are no views or messages final List<DetachedVertexProperty<Object>> previousView = hasViewAndMessages ? vertexViewIncoming._2()._2().get().getView() : memory.isInitialIteration() ? new ArrayList<>() : Collections.emptyList(); // revive compute properties if they already exist if (memory.isInitialIteration() && vertexComputeKeysArray.length > 0){ vertex.properties(vertexComputeKeysArray).forEachRemaining(vertexProperty -> previousView.add(DetachedFactory.detach(vertexProperty, true)));} // drop any computed properties that are cached in memory vertex.dropVertexProperties(vertexComputeKeysArray); final List<M> incomingMessages = hasViewAndMessages ? vertexViewIncoming._2()._2().get().getIncomingMessages() : Collections.emptyList(); IteratorUtils.removeOnNext(previousView.iterator()).forEachRemaining(property -> property.attach(Attachable.Method.create(vertex))); // attach the view to the vertex assert previousView.isEmpty(); // do the vertex's vertex program iteration messenger.setVertexAndIncomingMessages(vertex, incomingMessages); // set the messenger with the incoming messages workerVertexProgram.execute(ComputerGraph.vertexProgram(vertex, workerVertexProgram), messenger, memory); // execute the vertex program on this vertex for this iteration // assert incomingMessages.isEmpty(); // maybe the program didn't read all the messages incomingMessages.clear(); // detached the compute property view from the vertex final List<DetachedVertexProperty<Object>> nextView = vertexComputeKeysArray.length == 0 ? // not all vertex programs have compute keys Collections.emptyList() : IteratorUtils.list(IteratorUtils.map(vertex.properties(vertexComputeKeysArray), vertexProperty -> DetachedFactory.detach(vertexProperty, true))); // drop compute property view as it has now been detached from the vertex vertex.dropVertexProperties(vertexComputeKeysArray); final List<Tuple2<Object, M>> outgoingMessages = messenger.getOutgoingMessages(); // get the outgoing messages being sent by this vertex if (!partitionIterator.hasNext()) { workerVertexProgram.workerIterationEnd(memory.asImmutable()); // if no more vertices in the partition, end the worker's iteration} }return (nextView.isEmpty() && outgoingMessages.isEmpty()) ? null : // if there is no view nor outgoing messages, emit nothing new Tuple2<>(vertex.id(), new ViewOutgoingPayload<>(nextView, outgoingMessages)); // else, emit the vertex id, its view, and its outgoing messages }); }, true) // true means that the partition is preserved .filter(tuple -> null != tuple); // if there are no messages or views, then the tuple is null (memory optimization) // the graphRDD and the viewRDD must have the same partitioner if (partitionedGraphRDD){ assert graphRDD.partitioner().get().equals(viewOutgoingRDD.partitioner().get());} ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// final PairFlatMapFunction<Tuple2<Object, ViewOutgoingPayload<M>>, Object, Payload> messageFunction = tuple -> IteratorUtils.concat( IteratorUtils.of(new Tuple2<>(tuple._1(), tuple._2().getView())), // emit the view payload IteratorUtils.map(tuple._2().getOutgoingMessages().iterator(), message -> new Tuple2<>(message._1(), new MessagePayload<>(message._2())))); final MessageCombiner<M> messageCombiner = VertexProgram.<VertexProgram<M>>createVertexProgram(HadoopGraph.open(vertexProgramConfiguration), vertexProgramConfiguration).getMessageCombiner().orElse(null); final Function2<Payload, Payload, Payload> reducerFunction = (a, b) -> { // reduce the view and outgoing messages into a single payload object representing the new view and incoming messages for a vertex if (a instanceof ViewIncomingPayload) { ((ViewIncomingPayload<M>) a).mergePayload(b, messageCombiner); return a; } else if (b instanceof ViewIncomingPayload) { ((ViewIncomingPayload<M>) b).mergePayload(a, messageCombiner); return b; } else { final ViewIncomingPayload<M> c = new ViewIncomingPayload<>(messageCombiner); c.mergePayload(a, messageCombiner); c.mergePayload(b, messageCombiner); return c; } }; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // "message pass" by reducing on the vertex object id of the view and message payloads final JavaPairRDD<Object, ViewIncomingPayload<M>> newViewIncomingRDD = (partitionedGraphRDD ? viewOutgoingRDD.flatMapToPair(messageFunction).reduceByKey(graphRDD.partitioner().get(), reducerFunction) : viewOutgoingRDD.flatMapToPair(messageFunction).reduceByKey(reducerFunction)) .mapValues(payload -> { // handle various corner cases of when views don't exist, messages don't exist, or neither exists. if (payload instanceof ViewIncomingPayload) {// this happens if there is a vertex view with incoming messages return (ViewIncomingPayload<M>) payload;} else if (payload instanceof ViewPayload) { // this happens if there is a vertex view with no incoming messages return new ViewIncomingPayload<>((ViewPayload) payload);} else { // this happens when there is a single message to a vertex that has no view or outgoing messages return new ViewIncomingPayload<>((MessagePayload<M>) payload);} }); // the graphRDD and the viewRDD must have the same partitioner if (partitionedGraphRDD){ assert graphRDD.partitioner().get().equals(newViewIncomingRDD.partitioner().get());} newViewIncomingRDD .foreachPartition(partitionIterator -> { KryoShimServiceLoader.applyConfiguration(graphComputerConfiguration); }); // need to complete a task so its BSP and the memory for this iteration is updated return newViewIncomingRDD; } public static <M> JavaPairRDD<Object, VertexWritable> prepareFinalGraphRDD( final JavaPairRDD<Object, VertexWritable> graphRDD, final JavaPairRDD<Object, ViewIncomingPayload<M>> viewIncomingRDD, final Set<VertexComputeKey> vertexComputeKeys) { // the graphRDD and the viewRDD must have the same partitioner if (graphRDD.partitioner().isPresent()){ assert (graphRDD.partitioner().get().equals(viewIncomingRDD.partitioner().get()));} final String[] vertexComputeKeysArray = VertexProgramHelper.vertexComputeKeysAsArray(vertexComputeKeys); // the compute keys as an array return graphRDD.leftOuterJoin(viewIncomingRDD) .mapValues(tuple -> { final StarGraph.StarVertex vertex = tuple._1().get(); vertex.dropVertexProperties(vertexComputeKeysArray); // drop all existing compute keys // attach the final computed view to the cached graph final List<DetachedVertexProperty<Object>> view = tuple._2().isPresent() ? tuple._2().get().getView() : Collections.emptyList(); for (final DetachedVertexProperty<Object> property : view) { if (!VertexProgramHelper.isTransientVertexComputeKey(property.key(), vertexComputeKeys)){ property.attach(Attachable.Method.create(vertex));} } return tuple._1(); }); } ///////////////// // MAP REDUCE // //////////////// public static <K, V> JavaPairRDD<K, V> executeMap( final JavaPairRDD<Object, VertexWritable> graphRDD, final MapReduce<K, V, ?, ?, ?> mapReduce, final Configuration graphComputerConfiguration) { JavaPairRDD<K, V> mapRDD = graphRDD.mapPartitionsToPair(partitionIterator -> { KryoShimServiceLoader.applyConfiguration(graphComputerConfiguration); return new MapIterator<>(MapReduce.<MapReduce<K, V, ?, ?, ?>>createMapReduce(HadoopGraph.open(graphComputerConfiguration), graphComputerConfiguration), partitionIterator); }); if (mapReduce.getMapKeySort().isPresent()){ mapRDD = mapRDD.sortByKey(mapReduce.getMapKeySort().get(), true, 1);} return mapRDD; } public static <K, V, OK, OV> JavaPairRDD<OK, OV> executeCombine(final JavaPairRDD<K, V> mapRDD, final Configuration graphComputerConfiguration) { return mapRDD.mapPartitionsToPair(partitionIterator -> { KryoShimServiceLoader.applyConfiguration(graphComputerConfiguration); return new CombineIterator<>(MapReduce.<MapReduce<K, V, OK, OV, ?>>createMapReduce(HadoopGraph.open(graphComputerConfiguration), graphComputerConfiguration), partitionIterator); }); } public static <K, V, OK, OV> JavaPairRDD<OK, OV> executeReduce( final JavaPairRDD<K, V> mapOrCombineRDD, final MapReduce<K, V, OK, OV, ?> mapReduce, final Configuration graphComputerConfiguration) { JavaPairRDD<OK, OV> reduceRDD = mapOrCombineRDD.groupByKey().mapPartitionsToPair(partitionIterator -> { KryoShimServiceLoader.applyConfiguration(graphComputerConfiguration); return new ReduceIterator<>(MapReduce.<MapReduce<K, V, OK, OV, ?>>createMapReduce(HadoopGraph.open(graphComputerConfiguration), graphComputerConfiguration), partitionIterator); }); if (mapReduce.getReduceKeySort().isPresent()){ reduceRDD = reduceRDD.sortByKey(mapReduce.getReduceKeySort().get(), true, 1);} return reduceRDD; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknSparkMemory.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import org.apache.spark.Accumulator; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.broadcast.Broadcast; import org.apache.tinkerpop.gremlin.hadoop.structure.io.ObjectWritable; import org.apache.tinkerpop.gremlin.process.computer.GraphComputer; import org.apache.tinkerpop.gremlin.process.computer.MapReduce; import org.apache.tinkerpop.gremlin.process.computer.Memory; import org.apache.tinkerpop.gremlin.process.computer.MemoryComputeKey; import org.apache.tinkerpop.gremlin.process.computer.VertexProgram; import org.apache.tinkerpop.gremlin.process.computer.util.MemoryHelper; import org.apache.tinkerpop.gremlin.process.traversal.Operator; import org.apache.tinkerpop.gremlin.spark.process.computer.MemoryAccumulator; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * <p> * This is a modified version of Spark Memory. * We change its behaviour so it can work with our own graph computer. * </p> * * @author Jason Liu * @author Marko A. Rodriguez */ public class GraknSparkMemory implements Memory.Admin, Serializable { private static final long serialVersionUID = -3877367965011858056L; public final Map<String, MemoryComputeKey> memoryComputeKeys = new HashMap<>(); private final Map<String, Accumulator<ObjectWritable>> sparkMemory = new HashMap<>(); private final AtomicInteger iteration = new AtomicInteger(0); private final AtomicLong runtime = new AtomicLong(0L); private Broadcast<Map<String, Object>> broadcast; private boolean inExecute = false; public GraknSparkMemory(final VertexProgram<?> vertexProgram, final Set<MapReduce> mapReducers, final JavaSparkContext sparkContext) { if (null != vertexProgram) { for (final MemoryComputeKey key : vertexProgram.getMemoryComputeKeys()) { this.memoryComputeKeys.put(key.getKey(), key); } } for (final MapReduce mapReduce : mapReducers) { this.memoryComputeKeys.put( mapReduce.getMemoryKey(), MemoryComputeKey.of(mapReduce.getMemoryKey(), Operator.assign, false, false)); } for (final MemoryComputeKey memoryComputeKey : this.memoryComputeKeys.values()) { this.sparkMemory.put( memoryComputeKey.getKey(), sparkContext.accumulator(ObjectWritable.empty(), memoryComputeKey.getKey(), new MemoryAccumulator<>(memoryComputeKey))); } this.broadcast = sparkContext.broadcast(Collections.emptyMap()); } @Override public Set<String> keys() { if (this.inExecute) { return this.broadcast.getValue().keySet(); } else { final Set<String> trueKeys = new HashSet<>(); this.sparkMemory.forEach((key, value) -> { if (!value.value().isEmpty()) { trueKeys.add(key); } }); return Collections.unmodifiableSet(trueKeys); } } @Override public void incrIteration() { this.iteration.getAndIncrement(); } @Override public void setIteration(final int iteration) { this.iteration.set(iteration); } @Override public int getIteration() { return this.iteration.get(); } @Override public void setRuntime(final long runTime) { this.runtime.set(runTime); } @Override public long getRuntime() { return this.runtime.get(); } @Override public <R> R get(final String key) throws IllegalArgumentException { if (!this.memoryComputeKeys.containsKey(key)) { throw Memory.Exceptions.memoryDoesNotExist(key); } if (this.inExecute && !this.memoryComputeKeys.get(key).isBroadcast()) { throw Memory.Exceptions.memoryDoesNotExist(key); } final ObjectWritable<R> r = (ObjectWritable<R>) (this.inExecute ? this.broadcast.value().get(key) : this.sparkMemory.get(key).value()); if (null == r || r.isEmpty()) { throw Memory.Exceptions.memoryDoesNotExist(key); } else { return r.get(); } } @Override public void add(final String key, final Object value) { checkKeyValue(key, value); if (this.inExecute) { this.sparkMemory.get(key).add(new ObjectWritable<>(value)); } else { throw Memory.Exceptions.memoryAddOnlyDuringVertexProgramExecute(key); } } @Override public void set(final String key, final Object value) { checkKeyValue(key, value); if (this.inExecute) { throw Memory.Exceptions.memorySetOnlyDuringVertexProgramSetUpAndTerminate(key); } else { this.sparkMemory.get(key).setValue(new ObjectWritable<>(value)); } } @Override public String toString() { return StringFactory.memoryString(this); } protected void complete() { this.memoryComputeKeys.values().stream() .filter(MemoryComputeKey::isTransient) .forEach(memoryComputeKey -> this.sparkMemory.remove(memoryComputeKey.getKey())); } public void setInExecute(final boolean inExecute) { this.inExecute = inExecute; } protected void broadcastMemory(final JavaSparkContext sparkContext) { this.broadcast.destroy(true); // do we need to block? final Map<String, Object> toBroadcast = new HashMap<>(); this.sparkMemory.forEach((key, object) -> { if (!object.value().isEmpty() && this.memoryComputeKeys.get(key).isBroadcast()) { toBroadcast.put(key, object.value()); } }); this.broadcast = sparkContext.broadcast(toBroadcast); } private void checkKeyValue(final String key, final Object value) { if (!this.memoryComputeKeys.containsKey(key)) { throw GraphComputer.Exceptions.providedKeyIsNotAMemoryComputeKey(key); } MemoryHelper.validateValue(value); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/GraknSparkVertexProgramInterceptor.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.computer; import org.apache.spark.api.java.JavaPairRDD; import org.apache.tinkerpop.gremlin.hadoop.structure.io.VertexWritable; import org.apache.tinkerpop.gremlin.process.computer.VertexProgram; import org.apache.tinkerpop.gremlin.process.computer.traversal.strategy.VertexProgramInterceptor; /** * Interceptor interface copied from tinkerpop so we can use our own graph computer * * @param <V> Vertex Program * @author Jason Liu */ public interface GraknSparkVertexProgramInterceptor<V extends VertexProgram> extends VertexProgramInterceptor<V, JavaPairRDD<Object, VertexWritable>, GraknSparkMemory> { }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/computer/package-info.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * Internal implementation of {@link ai.grakn.GraknComputer} */ package ai.grakn.kb.internal.computer;
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/AttributeImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Thing; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.stream.Stream; /** * <p> * Represent a literal resource in the graph. * </p> * * <p> * Acts as an {@link Thing} when relating to other instances except it has the added functionality of: * 1. It is unique to its {@link AttributeType} based on it's value. * 2. It has a {@link AttributeType.DataType} associated with it which constrains the allowed values. * </p> * * @author fppt * * @param <D> The data type of this resource type. * Supported Types include: {@link String}, {@link Long}, {@link Double}, and {@link Boolean} */ public class AttributeImpl<D> extends ThingImpl<Attribute<D>, AttributeType<D>> implements Attribute<D> { private AttributeImpl(VertexElement vertexElement) { super(vertexElement); } private AttributeImpl(VertexElement vertexElement, AttributeType<D> type, Object value) { super(vertexElement, type); setValue(value); } public static <D> AttributeImpl<D> get(VertexElement vertexElement){ return new AttributeImpl<>(vertexElement); } public static <D> AttributeImpl<D> create(VertexElement vertexElement, AttributeType<D> type, Object value) { Object persistenceValue = castValue(type.dataType(), value); AttributeImpl<D> attribute = new AttributeImpl<>(vertexElement, type, persistenceValue); //Generate the index again. Faster than reading String index = Schema.generateAttributeIndex(type.label(), value.toString()); vertexElement.property(Schema.VertexProperty.INDEX, index); //Track the attribute by index vertexElement.tx().txCache().addNewAttribute(index, attribute.id()); return attribute; } /** * This is to handle casting longs and doubles when the type allows for the data type to be a number * @param value The value of the resource * @return The value casted to the correct type */ private static Object castValue(AttributeType.DataType dataType, Object value){ try { if (dataType.equals(AttributeType.DataType.DOUBLE)) { return ((Number) value).doubleValue(); } else if (dataType.equals(AttributeType.DataType.LONG)) { if (value instanceof Double) { throw new ClassCastException(); } return ((Number) value).longValue(); } else if (dataType.equals(AttributeType.DataType.DATE) && (value instanceof Long)){ return value; } else { return dataType.getPersistenceValue(value); } } catch (ClassCastException e) { throw GraknTxOperationException.invalidAttributeValue(value, dataType); } } /** * * @return The data type of this {@link Attribute}'s {@link AttributeType}. */ @Override public AttributeType.DataType<D> dataType() { return type().dataType(); } /** * @return The list of all Instances which possess this resource */ @Override public Stream<Thing> owners() { //Get Owner via implicit structure Stream<Thing> implicitOwners = getShortcutNeighbours(false); //Get owners via edges Stream<Thing> edgeOwners = neighbours(Direction.IN, Schema.EdgeLabel.ATTRIBUTE); return Stream.concat(implicitOwners, edgeOwners); } /** * * @param value The value to store on the resource */ private void setValue(Object value) { Schema.VertexProperty property = dataType().getVertexProperty(); //noinspection unchecked vertex().propertyImmutable(property, value, vertex().property(property)); } /** * * @return The value casted to the correct type */ @Override public D value(){ return dataType().getValue(vertex().property(dataType().getVertexProperty())); } @Override public String innerToString(){ return super.innerToString() + "- Value [" + value() + "] "; } public static AttributeImpl from(Attribute attribute){ return (AttributeImpl) attribute; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/AttributeTypeImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import javax.annotation.Nullable; import java.util.Objects; import java.util.function.BiFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * An ontological element which models and categorises the various {@link Attribute} in the graph. * </p> * * <p> * This ontological element behaves similarly to {@link ai.grakn.concept.Type} when defining how it relates to other * types. It has two additional functions to be aware of: * 1. It has a {@link AttributeType.DataType} constraining the data types of the values it's instances may take. * 2. Any of it's instances are unique to the type. * For example if you have a {@link AttributeType} modelling month throughout the year there can only be one January. * </p> * * @author fppt * * @param <D> The data type of this resource type. * Supported Types include: {@link String}, {@link Long}, {@link Double}, and {@link Boolean} */ public class AttributeTypeImpl<D> extends TypeImpl<AttributeType<D>, Attribute<D>> implements AttributeType<D> { private AttributeTypeImpl(VertexElement vertexElement) { super(vertexElement); } private AttributeTypeImpl(VertexElement vertexElement, AttributeType<D> type, DataType<D> dataType) { super(vertexElement, type); vertex().propertyImmutable(Schema.VertexProperty.DATA_TYPE, dataType, dataType(), DataType::getName); } public static <D> AttributeTypeImpl<D> get(VertexElement vertexElement){ return new AttributeTypeImpl<>(vertexElement); } public static <D> AttributeTypeImpl<D> create(VertexElement vertexElement, AttributeType<D> type, DataType<D> dataType) { return new AttributeTypeImpl<>(vertexElement, type, dataType); } /** * This method is overridden so that we can check that the regex of the new super type (if it has a regex) * can be applied to all the existing instances. */ @Override public AttributeType<D> sup(AttributeType<D> superType){ ((AttributeTypeImpl<D>) superType).sups().forEach(st -> checkInstancesMatchRegex(st.regex())); return super.sup(superType); } /** * @param regex The regular expression which instances of this resource must conform to. * @return The {@link AttributeType} itself. */ @Override public AttributeType<D> regex(String regex) { if(dataType() == null || !dataType().equals(DataType.STRING)) { throw GraknTxOperationException.cannotSetRegex(this); } checkInstancesMatchRegex(regex); return property(Schema.VertexProperty.REGEX, regex); } /** * Checks that existing instances match the provided regex. * * @throws GraknTxOperationException when an instance does not match the provided regex * @param regex The regex to check against */ private void checkInstancesMatchRegex(@Nullable String regex){ if(regex != null) { Pattern pattern = Pattern.compile(regex); instances().forEach(resource -> { String value = (String) resource.value(); Matcher matcher = pattern.matcher(value); if(!matcher.matches()){ throw GraknTxOperationException.regexFailure(this, value, regex); } }); } } @SuppressWarnings("unchecked") @Override public Attribute<D> create(D value) { return putAttribute(value, false); } public Attribute<D> putAttributeInferred(D value) { return putAttribute(value, true); } private Attribute<D> putAttribute(D value, boolean isInferred) { Objects.requireNonNull(value); BiFunction<VertexElement, AttributeType<D>, Attribute<D>> instanceBuilder = (vertex, type) -> { if(dataType().equals(DataType.STRING)) checkConformsToRegexes(value); return vertex().tx().factory().buildAttribute(vertex, type, value); }; return putInstance(Schema.BaseType.ATTRIBUTE, () -> attribute(value), instanceBuilder, isInferred); } /** * Checks if all the regex's of the types of this resource conforms to the value provided. * * @throws GraknTxOperationException when the value does not conform to the regex of its types * @param value The value to check the regexes against. */ private void checkConformsToRegexes(D value){ //Not checking the datatype because the regex will always be null for non strings. this.sups().forEach(sup -> { String regex = sup.regex(); if (regex != null && !Pattern.matches(regex, (String) value)) { throw GraknTxOperationException.regexFailure(this, (String) value, regex); } }); } @Override public Attribute<D> attribute(D value) { String index = Schema.generateAttributeIndex(label(), value.toString()); return vertex().tx().<Attribute<D>>getConcept(Schema.VertexProperty.INDEX, index).orElse(null); } /** * @return The data type which instances of this resource must conform to. */ //This unsafe cast is suppressed because at this stage we do not know what the type is when reading from the rootGraph. @SuppressWarnings({"unchecked", "SuspiciousMethodCalls"}) @Override public DataType<D> dataType() { return (DataType<D>) DataType.SUPPORTED_TYPES.get(vertex().property(Schema.VertexProperty.DATA_TYPE)); } /** * @return The regular expression which instances of this resource must conform to. */ @Override public String regex() { return vertex().property(Schema.VertexProperty.REGEX); } public static AttributeTypeImpl from(AttributeType attributeType){ return (AttributeTypeImpl) attributeType; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/ConceptImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.Keyspace; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.CacheOwner; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.kb.internal.structure.EdgeElement; import ai.grakn.kb.internal.structure.Shard; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; /** * <p> * The base concept implementation. * </p> * * <p> * A concept which can represent anything in the graph which wraps a tinkerpop {@link Vertex}. * This class forms the basis of assuring the graph follows the Grakn object model. * </p> * * @author fppt * */ public abstract class ConceptImpl implements Concept, ConceptVertex, CacheOwner{ private final Set<Cache> registeredCaches = new HashSet<>(); //WARNING: DO not flush the current shard into the central cache. It is not safe to do so in a concurrent environment private final Cache<Shard> currentShard = Cache.createTxCache(this, Cacheable.shard(), () -> { String currentShardId = vertex().property(Schema.VertexProperty.CURRENT_SHARD); Vertex shardVertex = vertex().tx().getTinkerTraversal().V().has(Schema.VertexProperty.ID.name(), currentShardId).next(); return vertex().tx().factory().buildShard(shardVertex); }); private final Cache<Long> shardCount = Cache.createSessionCache(this, Cacheable.number(), () -> shards().count()); private final Cache<ConceptId> conceptId = Cache.createPersistentCache(this, Cacheable.conceptId(), () -> ConceptId.of(vertex().property(Schema.VertexProperty.ID))); private final VertexElement vertexElement; ConceptImpl(VertexElement vertexElement){ this.vertexElement = vertexElement; } @Override public VertexElement vertex() { return vertexElement; } @SuppressWarnings("unchecked") <X extends Concept> X getThis(){ return (X) this; } /** * Deletes the concept. * @throws GraknTxOperationException Throws an exception if the node has any edges attached to it. */ @Override public void delete() throws GraknTxOperationException { deleteNode(); } @Override public Keyspace keyspace(){ return vertex().tx().keyspace(); } @Override public boolean isDeleted() { return vertex().isDeleted(); } /** * Deletes the node and adds it neighbours for validation */ public void deleteNode(){ vertex().tx().txCache().remove(this); vertex().delete(); } @Override public Collection<Cache> caches(){ return registeredCaches; } /** * * @param direction the direction of the neigouring concept to get * @param label The edge label to traverse * @return The neighbouring concepts found by traversing edges of a specific type */ <X extends Concept> Stream<X> neighbours(Direction direction, Schema.EdgeLabel label){ switch (direction){ case BOTH: return vertex().getEdgesOfType(direction, label). flatMap(edge -> Stream.<X>of( vertex().tx().factory().buildConcept(edge.source()), vertex().tx().factory().buildConcept(edge.target())) ); case IN: return vertex().getEdgesOfType(direction, label).map(edge -> vertex().tx().factory().buildConcept(edge.source())); case OUT: return vertex().getEdgesOfType(direction, label).map(edge -> vertex().tx().factory().buildConcept(edge.target())); default: throw GraknTxOperationException.invalidDirection(direction); } } EdgeElement putEdge(ConceptVertex to, Schema.EdgeLabel label){ return vertex().putEdge(to.vertex(), label); } EdgeElement addEdge(ConceptVertex to, Schema.EdgeLabel label){ return vertex().addEdge(to.vertex(), label); } void deleteEdge(Direction direction, Schema.EdgeLabel label, Concept... to) { if (to.length == 0) { vertex().deleteEdge(direction, label); } else{ VertexElement[] targets = new VertexElement[to.length]; for (int i = 0; i < to.length; i++) { targets[i] = ((ConceptImpl)to[i]).vertex(); } vertex().deleteEdge(direction, label, targets); } } /** * * @return The base type of this concept which helps us identify the concept */ public Schema.BaseType baseType(){ return Schema.BaseType.valueOf(vertex().label()); } /** * * @return A string representing the concept's unique id. */ @Override public ConceptId id(){ return conceptId.get(); } @Override public int hashCode() { return id().hashCode(); //Note: This means that concepts across different transactions will be equivalent. } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ConceptImpl concept = (ConceptImpl) object; //based on id because vertex comparisons are equivalent return id().equals(concept.id()); } @Override public final String toString(){ if(vertex().tx().isValidElement(vertex().element())){ return innerToString(); } else { // Vertex has been deleted so all we can do is print the id return "Id [" + vertex().id() + "]"; } } String innerToString() { String message = "Base Type [" + baseType() + "] "; if(id() != null) { message = message + "- Id [" + id() + "] "; } return message; } //----------------------------------- Sharding Functionality public void createShard(){ VertexElement shardVertex = vertex().tx().addVertexElement(Schema.BaseType.SHARD); Shard shard = vertex().tx().factory().buildShard(this, shardVertex); vertex().property(Schema.VertexProperty.CURRENT_SHARD, shard.id()); currentShard.set(shard); //Updated the cached shard count if needed if(shardCount.isPresent()){ shardCount.set(shardCount() + 1); } } public Stream<Shard> shards(){ return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.SHARD). map(EdgeElement::source). map(edge -> vertex().tx().factory().buildShard(edge)); } public Long shardCount(){ return shardCount.get(); } public Shard currentShard(){ return currentShard.get(); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/ConceptVertex.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Concept; import ai.grakn.kb.internal.structure.VertexElement; /** * <p> * A {@link Concept} represented as a {@link VertexElement} * </p> * * <p> * This class is helper used to ensure that any concept which needs to contain a {@link VertexElement} can handle it. * Either by returning an existing one r going through some reification procedure to return a new one. * </p> * * @author fppt * */ public interface ConceptVertex { VertexElement vertex(); static ConceptVertex from(Concept concept){ return (ConceptVertex) concept; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/ElementFactory.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.exception.TemporaryWriteException; import ai.grakn.graql.Pattern; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.kb.internal.structure.AbstractElement; import ai.grakn.kb.internal.structure.EdgeElement; import ai.grakn.kb.internal.structure.Shard; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import static ai.grakn.util.Schema.BaseType.RELATIONSHIP_TYPE; /** * <p> * Constructs Concepts And Edges * </p> * * <p> * This class turns Tinkerpop {@link Vertex} and {@link org.apache.tinkerpop.gremlin.structure.Edge} * into Grakn {@link Concept} and {@link EdgeElement}. * * Construction is only successful if the vertex and edge properties contain the needed information. * A concept must include a label which is a {@link ai.grakn.util.Schema.BaseType}. * An edge must include a label which is a {@link ai.grakn.util.Schema.EdgeLabel}. * </p> * * @author fppt */ public final class ElementFactory { private final EmbeddedGraknTx tx; public ElementFactory(EmbeddedGraknTx tx){ this.tx = tx; } private <X extends Concept, E extends AbstractElement> X getOrBuildConcept(E element, ConceptId conceptId, Function<E, X> conceptBuilder){ if(!tx.txCache().isConceptCached(conceptId)){ X newConcept = conceptBuilder.apply(element); tx.txCache().cacheConcept(newConcept); } return tx.txCache().getCachedConcept(conceptId); } private <X extends Concept> X getOrBuildConcept(VertexElement element, Function<VertexElement, X> conceptBuilder){ ConceptId conceptId = ConceptId.of(element.property(Schema.VertexProperty.ID)); return getOrBuildConcept(element, conceptId, conceptBuilder); } private <X extends Concept> X getOrBuildConcept(EdgeElement element, Function<EdgeElement, X> conceptBuilder){ ConceptId conceptId = ConceptId.of(element.id().getValue()); return getOrBuildConcept(element, conceptId, conceptBuilder); } // ---------------------------------------- Building Attribute Types ----------------------------------------------- public <V> AttributeTypeImpl<V> buildAttributeType(VertexElement vertex, AttributeType<V> type, AttributeType.DataType<V> dataType){ return getOrBuildConcept(vertex, (v) -> AttributeTypeImpl.create(v, type, dataType)); } // ------------------------------------------ Building Attribute <V> AttributeImpl<V> buildAttribute(VertexElement vertex, AttributeType<V> type, Object persitedValue){ return getOrBuildConcept(vertex, (v) -> AttributeImpl.create(v, type, persitedValue)); } // ---------------------------------------- Building Relationship Types ----------------------------------------------- public RelationshipTypeImpl buildRelationshipType(VertexElement vertex, RelationshipType type){ return getOrBuildConcept(vertex, (v) -> RelationshipTypeImpl.create(v, type)); } // -------------------------------------------- Building Relations RelationshipImpl buildRelation(VertexElement vertex, RelationshipType type){ return getOrBuildConcept(vertex, (v) -> RelationshipImpl.create(buildRelationReified(v, type))); } public RelationshipImpl buildRelation(EdgeElement edge, RelationshipType type, Role owner, Role value){ return getOrBuildConcept(edge, (e) -> RelationshipImpl.create(RelationshipEdge.create(type, owner, value, edge))); } RelationshipImpl buildRelation(EdgeElement edge){ return getOrBuildConcept(edge, (e) -> RelationshipImpl.create(RelationshipEdge.get(edge))); } RelationshipReified buildRelationReified(VertexElement vertex, RelationshipType type){ return RelationshipReified.create(vertex, type); } // ----------------------------------------- Building Entity Types ------------------------------------------------ public EntityTypeImpl buildEntityType(VertexElement vertex, EntityType type){ return getOrBuildConcept(vertex, (v) -> EntityTypeImpl.create(v, type)); } // ------------------------------------------- Building Entities EntityImpl buildEntity(VertexElement vertex, EntityType type){ return getOrBuildConcept(vertex, (v) -> EntityImpl.create(v, type)); } // ----------------------------------------- Building Rules -------------------------------------------------- public RuleImpl buildRule(VertexElement vertex, Rule type, Pattern when, Pattern then){ return getOrBuildConcept(vertex, (v) -> RuleImpl.create(v, type, when, then)); } // ------------------------------------------ Building Roles Types ------------------------------------------------ public RoleImpl buildRole(VertexElement vertex, Role type){ return getOrBuildConcept(vertex, (v) -> RoleImpl.create(v, type)); } /** * Constructors are called directly because this is only called when reading a known vertex or concept. * Thus tracking the concept can be skipped. * * @param vertex A vertex of an unknown type * @return A concept built to the correct type */ public <X extends Concept> X buildConcept(Vertex vertex){ return buildConcept(buildVertexElement(vertex)); } public <X extends Concept> X buildConcept(VertexElement vertexElement){ Schema.BaseType type; try { type = getBaseType(vertexElement); } catch (IllegalStateException e){ throw TemporaryWriteException.indexOverlap(vertexElement.element(), e); } ConceptId conceptId = ConceptId.of(vertexElement.property(Schema.VertexProperty.ID)); if(!tx.txCache().isConceptCached(conceptId)){ Concept concept; switch (type) { case RELATIONSHIP: concept = RelationshipImpl.create(RelationshipReified.get(vertexElement)); break; case TYPE: concept = new TypeImpl(vertexElement); break; case ROLE: concept = RoleImpl.get(vertexElement); break; case RELATIONSHIP_TYPE: concept = RelationshipTypeImpl.get(vertexElement); break; case ENTITY: concept = EntityImpl.get(vertexElement); break; case ENTITY_TYPE: concept = EntityTypeImpl.get(vertexElement); break; case ATTRIBUTE_TYPE: concept = AttributeTypeImpl.get(vertexElement); break; case ATTRIBUTE: concept = AttributeImpl.get(vertexElement); break; case RULE: concept = RuleImpl.get(vertexElement); break; default: throw GraknTxOperationException.unknownConcept(type.name()); } tx.txCache().cacheConcept(concept); } return tx.txCache().getCachedConcept(conceptId); } /** * Constructors are called directly because this is only called when reading a known {@link Edge} or {@link Concept}. * Thus tracking the concept can be skipped. * * @param edge A {@link Edge} of an unknown type * @return A concept built to the correct type */ public <X extends Concept> X buildConcept(Edge edge){ return buildConcept(buildEdgeElement(edge)); } public <X extends Concept> X buildConcept(EdgeElement edgeElement){ Schema.EdgeLabel label = Schema.EdgeLabel.valueOf(edgeElement.label().toUpperCase(Locale.getDefault())); ConceptId conceptId = ConceptId.of(edgeElement.id().getValue()); if(!tx.txCache().isConceptCached(conceptId)){ Concept concept; switch (label) { case ATTRIBUTE: concept = RelationshipImpl.create(RelationshipEdge.get(edgeElement)); break; default: throw GraknTxOperationException.unknownConcept(label.name()); } tx.txCache().cacheConcept(concept); } return tx.txCache().getCachedConcept(conceptId); } /** * This is a helper method to get the base type of a vertex. * It first tried to get the base type via the label. * If this is not possible it then tries to get the base type via the Shard Edge. * * @param vertex The vertex to build a concept from * @return The base type of the vertex, if it is a valid concept. */ private Schema.BaseType getBaseType(VertexElement vertex){ try { return Schema.BaseType.valueOf(vertex.label()); } catch (IllegalArgumentException e){ //Base type appears to be invalid. Let's try getting the type via the shard edge Optional<VertexElement> type = vertex.getEdgesOfType(Direction.OUT, Schema.EdgeLabel.SHARD). map(EdgeElement::target).findAny(); if(type.isPresent()){ String label = type.get().label(); if(label.equals(Schema.BaseType.ENTITY_TYPE.name())) return Schema.BaseType.ENTITY; if(label.equals(RELATIONSHIP_TYPE.name())) return Schema.BaseType.RELATIONSHIP; if(label.equals(Schema.BaseType.ATTRIBUTE_TYPE.name())) return Schema.BaseType.ATTRIBUTE; } } throw new IllegalStateException("Could not determine the base type of vertex [" + vertex + "]"); } // ---------------------------------------- Non Concept Construction ----------------------------------------------- public EdgeElement buildEdgeElement(Edge edge){ return new EdgeElement(tx, edge); } Shard buildShard(ConceptImpl shardOwner, VertexElement vertexElement){ return new Shard(shardOwner, vertexElement); } Shard buildShard(VertexElement vertexElement){ return new Shard(vertexElement); } Shard buildShard(Vertex vertex){ return new Shard(buildVertexElement(vertex)); } /** * Builds a {@link VertexElement} from an already existing Vertex. An empty optional is returned if the passed in * vertex is not valid. A vertex is not valid if it is null or has been deleted * * @param vertex A vertex which can possibly be turned into a {@link VertexElement} * @return A {@link VertexElement} of */ public VertexElement buildVertexElement(Vertex vertex){ if(!tx.isValidElement(vertex)){ Objects.requireNonNull(vertex); throw GraknTxOperationException.invalidElement(vertex); } return new VertexElement(tx, vertex); } /** * Creates a new {@link VertexElement} with a {@link ConceptId} which can optionally be set. * * @param baseType The {@link Schema.BaseType} * @param conceptIds the optional {@link ConceptId} to set as the new {@link ConceptId} * @return a new {@link VertexElement} */ public VertexElement addVertexElement(Schema.BaseType baseType, ConceptId ... conceptIds) { Vertex vertex = tx.getTinkerPopGraph().addVertex(baseType.name()); String newConceptId = Schema.PREFIX_VERTEX + vertex.id().toString(); if(conceptIds.length > 1){ throw new IllegalArgumentException("Cannot provide more than one concept id when creating a new concept"); } else if (conceptIds.length == 1){ newConceptId = conceptIds[0].getValue(); } vertex.property(Schema.VertexProperty.ID.name(), newConceptId); tx.txCache().writeOccurred(); return new VertexElement(tx, vertex); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/EntityImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Attribute; import ai.grakn.concept.Entity; import ai.grakn.concept.EntityType; import ai.grakn.concept.Relationship; import ai.grakn.kb.internal.structure.VertexElement; /** * <p> * An instance of Entity Type {@link EntityType} * </p> * * <p> * This represents an entity in the graph. * Entities are objects which are defined by their {@link Attribute} and their links to * other entities via {@link Relationship} * </p> * * @author fppt */ public class EntityImpl extends ThingImpl<Entity, EntityType> implements Entity { private EntityImpl(VertexElement vertexElement) { super(vertexElement); } private EntityImpl(VertexElement vertexElement, EntityType type) { super(vertexElement, type); } public static EntityImpl get(VertexElement vertexElement){ return new EntityImpl(vertexElement); } public static EntityImpl create(VertexElement vertexElement, EntityType type){ return new EntityImpl(vertexElement, type); } public static EntityImpl from(Entity entity){ return (EntityImpl) entity; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/EntityTypeImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Entity; import ai.grakn.concept.EntityType; import ai.grakn.concept.SchemaConcept; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; /** * <p> * {@link SchemaConcept} used to represent categories. * </p> * * <p> * A {@link SchemaConcept} which represents categories instances can fall within. * Any instance of a {@link EntityType} is called an {@link Entity}. * </p> * * @author fppt * */ public class EntityTypeImpl extends TypeImpl<EntityType, Entity> implements EntityType{ private EntityTypeImpl(VertexElement vertexElement) { super(vertexElement); } private EntityTypeImpl(VertexElement vertexElement, EntityType type) { super(vertexElement, type); } public static EntityTypeImpl get(VertexElement vertexElement){ return new EntityTypeImpl(vertexElement); } public static EntityTypeImpl create(VertexElement vertexElement, EntityType type){ return new EntityTypeImpl(vertexElement, type); } @Override public Entity create() { return addInstance(Schema.BaseType.ENTITY, (vertex, type) -> vertex().tx().factory().buildEntity(vertex, type), false, true); } public Entity addEntityInferred() { return addInstance(Schema.BaseType.ENTITY, (vertex, type) -> vertex().tx().factory().buildEntity(vertex, type), true, true); } public static EntityTypeImpl from(EntityType entityType){ return (EntityTypeImpl) entityType; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/RelationshipEdge.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import ai.grakn.concept.LabelId; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.CacheOwner; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.kb.internal.structure.EdgeElement; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.stream.Stream; /** * <p> * Encapsulates The {@link Relationship} as a {@link EdgeElement} * </p> * * <p> * This wraps up a {@link Relationship} as a {@link EdgeElement}. It is used to represent any binary {@link Relationship}. * This also includes the ability to automatically reify a {@link RelationshipEdge} into a {@link RelationshipReified}. * </p> * * @author fppt * */ public class RelationshipEdge implements RelationshipStructure, CacheOwner { private final Set<Cache> registeredCaches = new HashSet<>(); private final Logger LOG = LoggerFactory.getLogger(RelationshipEdge.class); private final EdgeElement edgeElement; private final Cache<RelationshipType> relationType = Cache.createTxCache(this, Cacheable.concept(), () -> edge().tx().getSchemaConcept(LabelId.of(edge().property(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID)))); private final Cache<Role> ownerRole = Cache.createTxCache(this, Cacheable.concept(), () -> edge().tx().getSchemaConcept(LabelId.of( edge().property(Schema.EdgeProperty.RELATIONSHIP_ROLE_OWNER_LABEL_ID)))); private final Cache<Role> valueRole = Cache.createTxCache(this, Cacheable.concept(), () -> edge().tx().getSchemaConcept(LabelId.of( edge().property(Schema.EdgeProperty.RELATIONSHIP_ROLE_VALUE_LABEL_ID)))); private final Cache<Thing> owner = Cache.createTxCache(this, Cacheable.concept(), () -> edge().tx().factory().<Thing>buildConcept(edge().source()) ); private final Cache<Thing> value = Cache.createTxCache(this, Cacheable.concept(), () -> edge().tx().factory().<Thing>buildConcept(edge().target()) ); private RelationshipEdge(EdgeElement edgeElement) { this.edgeElement = edgeElement; } private RelationshipEdge(RelationshipType relationshipType, Role ownerRole, Role valueRole, EdgeElement edgeElement) { this(edgeElement); edgeElement.propertyImmutable(Schema.EdgeProperty.RELATIONSHIP_ROLE_OWNER_LABEL_ID, ownerRole, null, o -> o.labelId().getValue()); edgeElement.propertyImmutable(Schema.EdgeProperty.RELATIONSHIP_ROLE_VALUE_LABEL_ID, valueRole, null, v -> v.labelId().getValue()); edgeElement.propertyImmutable(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID, relationshipType, null, t -> t.labelId().getValue()); this.relationType.set(relationshipType); this.ownerRole.set(ownerRole); this.valueRole.set(valueRole); } public static RelationshipEdge get(EdgeElement edgeElement){ return new RelationshipEdge(edgeElement); } public static RelationshipEdge create(RelationshipType relationshipType, Role ownerRole, Role valueRole, EdgeElement edgeElement) { return new RelationshipEdge(relationshipType, ownerRole, valueRole, edgeElement); } private EdgeElement edge(){ return edgeElement; } @Override public ConceptId id() { return ConceptId.of(edge().id().getValue()); } @Override public Keyspace keyspace() { return edge().tx().keyspace(); } @Override public RelationshipReified reify() { LOG.debug("Reifying concept [" + id() + "]"); //Build the Relationship Vertex VertexElement relationVertex = edge().tx().addVertexElement(Schema.BaseType.RELATIONSHIP, id()); RelationshipReified relationReified = edge().tx().factory().buildRelationReified(relationVertex, type()); //Delete the old edge delete(); return relationReified; } @Override public boolean isReified() { return false; } @Override public RelationshipType type() { return relationType.get(); } @Override public Map<Role, Set<Thing>> allRolePlayers() { HashMap<Role, Set<Thing>> result = new HashMap<>(); result.put(ownerRole(), Collections.singleton(owner())); result.put(valueRole(), Collections.singleton(value())); return result; } @Override public Stream<Thing> rolePlayers(Role... roles) { if(roles.length == 0){ return Stream.of(owner(), value()); } HashSet<Thing> result = new HashSet<>(); for (Role role : roles) { if(role.equals(ownerRole())) { result.add(owner()); } else if (role.equals(valueRole())) { result.add(value()); } } return result.stream(); } public Role ownerRole(){ return ownerRole.get(); } public Thing owner(){ return owner.get(); } public Role valueRole(){ return valueRole.get(); } public Thing value(){ return value.get(); } @Override public void delete() { edge().delete(); } @Override public boolean isDeleted() { return edgeElement.isDeleted(); } @Override public boolean isInferred() { return edge().propertyBoolean(Schema.EdgeProperty.IS_INFERRED); } @Override public String toString(){ return "ID [" + id() + "] Type [" + type().label() + "] Roles and Role Players: \n" + "Role [" + ownerRole().label() + "] played by [" + owner().id() + "] \n" + "Role [" + valueRole().label() + "] played by [" + value().id() + "] \n"; } @Override public Collection<Cache> caches() { return registeredCaches; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/RelationshipImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.Keyspace; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.CacheOwner; import ai.grakn.kb.internal.structure.VertexElement; import com.google.common.collect.Iterables; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Stream; /** * <p> * Encapsulates relationships between {@link Thing} * </p> * * <p> * A relation which is an instance of a {@link RelationshipType} defines how instances may relate to one another. * </p> * * @author fppt * */ public class RelationshipImpl implements Relationship, ConceptVertex, CacheOwner{ private RelationshipStructure relationshipStructure; private RelationshipImpl(RelationshipStructure relationshipStructure) { this.relationshipStructure = relationshipStructure; if(relationshipStructure.isReified()){ relationshipStructure.reify().owner(this); } } public static RelationshipImpl create(RelationshipStructure relationshipStructure) { return new RelationshipImpl(relationshipStructure); } /** * Gets the {@link RelationshipReified} if the {@link Relationship} has been reified. * To reify the {@link Relationship} you use {@link RelationshipImpl#reify()}. * * NOTE: This approach is done to make sure that only write operations will cause the {@link Relationship} to reify * * @return The {@link RelationshipReified} if the {@link Relationship} has been reified */ public Optional<RelationshipReified> reified(){ if(!relationshipStructure.isReified()) return Optional.empty(); return Optional.of(relationshipStructure.reify()); } /** * Reifys and returns the {@link RelationshipReified} */ public RelationshipReified reify(){ if(relationshipStructure.isReified()) return relationshipStructure.reify(); //Get the role players to transfer Map<Role, Set<Thing>> rolePlayers = structure().allRolePlayers(); //Now Reify relationshipStructure = relationshipStructure.reify(); //Transfer relationships rolePlayers.forEach((role, things) -> { Thing thing = Iterables.getOnlyElement(things); assign(role, thing); }); return relationshipStructure.reify(); } public RelationshipStructure structure(){ return relationshipStructure; } @Override public Relationship has(Attribute attribute) { relhas(attribute); return this; } @Override public Relationship relhas(Attribute attribute) { return reify().relhas(attribute); } @Override public Stream<Attribute<?>> attributes(AttributeType[] attributeTypes) { return readFromReified((relationReified) -> relationReified.attributes(attributeTypes)); } @Override public Stream<Attribute<?>> keys(AttributeType[] attributeTypes) { return reified().map(relationshipReified -> relationshipReified.attributes(attributeTypes)).orElseGet(Stream::empty); } @Override public RelationshipType type() { return structure().type(); } @Override public Stream<Relationship> relationships(Role... roles) { return readFromReified((relationReified) -> relationReified.relationships(roles)); } @Override public Stream<Role> roles() { return readFromReified(ThingImpl::roles); } /** * Reads some data from a {@link RelationshipReified}. If the {@link Relationship} has not been reified then an empty * {@link Stream} is returned. */ private <X> Stream<X> readFromReified(Function<RelationshipReified, Stream<X>> producer){ return reified().map(producer).orElseGet(Stream::empty); } /** * Retrieve a list of all {@link Thing} involved in the {@link Relationship}, and the {@link Role} they play. * @see Role * * @return A list of all the {@link Role}s and the {@link Thing}s playing them in this {@link Relationship}. */ @Override public Map<Role, Set<Thing>> rolePlayersMap(){ return structure().allRolePlayers(); } @Override public Stream<Thing> rolePlayers(Role... roles) { return structure().rolePlayers(roles); } /** * Expands this {@link Relationship} to include a new role player which is playing a specific {@link Role}. * @param role The role of the new role player. * @param player The new role player. * @return The {@link Relationship} itself */ @Override public Relationship assign(Role role, Thing player) { reify().addRolePlayer(role, player); return this; } @Override public Relationship unhas(Attribute attribute) { reified().ifPresent(rel -> rel.unhas(attribute)); return this; } @Override public boolean isInferred() { return structure().isInferred(); } @Override public void unassign(Role role, Thing player) { reified().ifPresent(relationshipReified -> relationshipReified.removeRolePlayer(role, player)); } /** * When a relation is deleted this cleans up any solitary casting and resources. */ void cleanUp() { Stream<Thing> rolePlayers = rolePlayers(); boolean performDeletion = rolePlayers.noneMatch(thing -> thing != null && thing.id() != null); if(performDeletion) delete(); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; return id().equals(((RelationshipImpl) object).id()); } @Override public int hashCode() { return id().hashCode(); } @Override public String toString(){ return structure().toString(); } @Override public ConceptId id() { return structure().id(); } @Override public Keyspace keyspace() { return structure().keyspace(); } @Override public void delete() { structure().delete(); } @Override public boolean isDeleted() { return structure().isDeleted(); } @Override public VertexElement vertex() { return reify().vertex(); } public static RelationshipImpl from(Relationship relationship){ return (RelationshipImpl) relationship; } @Override public Collection<Cache> caches() { return structure().caches(); } public Relationship attributeInferred(Attribute attribute) { reify().attributeInferred(attribute); return this; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/RelationshipReified.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.kb.internal.structure.Casting; import ai.grakn.kb.internal.structure.EdgeElement; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import javax.annotation.Nullable; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * <p> * Encapsulates The {@link Relationship} as a {@link VertexElement} * </p> * * <p> * This wraps up a {@link Relationship} as a {@link VertexElement}. It is used to represent any {@link Relationship} which * has been reified. * </p> * * @author fppt * */ public class RelationshipReified extends ThingImpl<Relationship, RelationshipType> implements RelationshipStructure { @Nullable private RelationshipImpl owner; private RelationshipReified(VertexElement vertexElement) { super(vertexElement); } private RelationshipReified(VertexElement vertexElement, RelationshipType type) { super(vertexElement, type); } public static RelationshipReified get(VertexElement vertexElement){ return new RelationshipReified(vertexElement); } public static RelationshipReified create(VertexElement vertexElement, RelationshipType type){ return new RelationshipReified(vertexElement, type); } @Override public Map<Role, Set<Thing>> allRolePlayers() { HashMap<Role, Set<Thing>> roleMap = new HashMap<>(); //We add the role types explicitly so we can return them when there are no roleplayers type().roles().forEach(roleType -> roleMap.put(roleType, new HashSet<>())); //All castings are used here because we need to iterate over all of them anyway castingsRelation().forEach(rp -> roleMap.computeIfAbsent(rp.getRole(), (k) -> new HashSet<>()).add(rp.getRolePlayer())); return roleMap; } @Override public Stream<Thing> rolePlayers(Role... roles) { return castingsRelation(roles).map(Casting::getRolePlayer).distinct(); } void removeRolePlayer(Role role, Thing thing) { castingsRelation().filter(casting -> casting.getRole().equals(role) && casting.getRolePlayer().equals(thing)). findAny(). ifPresent(casting -> { casting.delete(); vertex().tx().txCache().remove(casting); }); } public void addRolePlayer(Role role, Thing thing) { Objects.requireNonNull(role); Objects.requireNonNull(thing); if(Schema.MetaSchema.isMetaLabel(role.label())) throw GraknTxOperationException.metaTypeImmutable(role.label()); //Do the actual put of the role and role player putRolePlayerEdge(role, thing); } /** * If the edge does not exist then it adds a {@link Schema.EdgeLabel#ROLE_PLAYER} edge from * this {@link Relationship} to a target {@link Thing} which is playing some {@link Role}. * * If the edge does exist nothing is done. * * @param role The {@link Role} being played by the {@link Thing} in this {@link Relationship} * @param toThing The {@link Thing} playing a {@link Role} in this {@link Relationship} */ public void putRolePlayerEdge(Role role, Thing toThing) { //Checking if the edge exists GraphTraversal<Vertex, Edge> traversal = vertex().tx().getTinkerTraversal().V(). has(Schema.VertexProperty.ID.name(), this.id().getValue()). outE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()). has(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID.name(), this.type().labelId().getValue()). has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), role.labelId().getValue()). as("edge"). inV(). has(Schema.VertexProperty.ID.name(), toThing.id()). select("edge"); if(traversal.hasNext()){ return; } //Role player edge does not exist create a new one EdgeElement edge = this.addEdge(ConceptVertex.from(toThing), Schema.EdgeLabel.ROLE_PLAYER); edge.property(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID, this.type().labelId().getValue()); edge.property(Schema.EdgeProperty.ROLE_LABEL_ID, role.labelId().getValue()); Casting casting = Casting.create(edge, owner, role, toThing); vertex().tx().txCache().trackForValidation(casting); } /** * Castings are retrieved from the perspective of the {@link Relationship} * * @param roles The {@link Role} which the {@link Thing}s are playing * @return The {@link Casting} which unify a {@link Role} and {@link Thing} with this {@link Relationship} */ public Stream<Casting> castingsRelation(Role... roles){ Set<Role> roleSet = new HashSet<>(Arrays.asList(roles)); if(roleSet.isEmpty()){ return vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ROLE_PLAYER). map(edge -> Casting.withRelationship(edge, owner)); } //Traversal is used so we can potentially optimise on the index Set<Integer> roleTypesIds = roleSet.stream().map(r -> r.labelId().getValue()).collect(Collectors.toSet()); return vertex().tx().getTinkerTraversal().V(). has(Schema.VertexProperty.ID.name(), id().getValue()). outE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()). has(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID.name(), type().labelId().getValue()). has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), P.within(roleTypesIds)). toStream(). map(edge -> vertex().tx().factory().buildEdgeElement(edge)). map(edge -> Casting.withRelationship(edge, owner)); } @Override public String innerToString(){ StringBuilder description = new StringBuilder(); description.append("ID [").append(id()).append("] Type [").append(type().label()).append("] Roles and Role Players: \n"); for (Map.Entry<Role, Set<Thing>> entry : allRolePlayers().entrySet()) { if(entry.getValue().isEmpty()){ description.append(" Role [").append(entry.getKey().label()).append("] not played by any instance \n"); } else { StringBuilder instancesString = new StringBuilder(); for (Thing thing : entry.getValue()) { instancesString.append(thing.id()).append(","); } description.append(" Role [").append(entry.getKey().label()).append("] played by ["). append(instancesString.toString()).append("] \n"); } } return description.toString(); } /** * Sets the owner of this structure to a specific {@link RelationshipImpl}. * This is so that the internal structure can use the {@link Relationship} reference; * * @param relationship the owner of this {@link RelationshipReified} */ public void owner(RelationshipImpl relationship) { owner = relationship; } @Override public RelationshipReified reify() { return this; } @Override public boolean isReified() { return true; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/RelationshipStructure.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.concept.Thing; import ai.grakn.kb.internal.cache.CacheOwner; import ai.grakn.kb.internal.structure.EdgeElement; import ai.grakn.kb.internal.structure.VertexElement; import java.util.Map; import java.util.Set; import java.util.stream.Stream; /** * <p> * Encapsulates The structure of a {@link Relationship}. * </p> * * <p> * This wraps up the structure of a {@link Relationship} as either a {@link RelationshipReified} or a * {@link RelationshipEdge}. * It contains methods which can be accessed regardless of the {@link Relationship} being a represented by a * {@link VertexElement} or an {@link EdgeElement} * </p> * * @author fppt * */ interface RelationshipStructure extends CacheOwner{ /** * * @return The {@link ConceptId} of the {@link Relationship} */ ConceptId id(); /** * Used for determining which {@link Keyspace} a {@link RelationshipStructure} was created in and is bound to. * * @return The {@link Keyspace} this {@link RelationshipStructure} belongs to. */ Keyspace keyspace(); /** * * @return The relation structure which has been reified */ RelationshipReified reify(); /** * * @return true if the {@link Relationship} has been reified meaning it can support n-ary relationships */ boolean isReified(); /** * * @return The {@link RelationshipType} of the {@link Relationship} */ RelationshipType type(); /** * * @return All the {@link Role}s and the {@link Thing}s which play them */ Map<Role, Set<Thing>> allRolePlayers(); /** * * @param roles The {@link Role}s which are played in this relation * @return The {@link Thing}s which play those {@link Role}s */ Stream<Thing> rolePlayers(Role... roles); /** * Deletes the {@link VertexElement} or {@link EdgeElement} used to represent this {@link Relationship} */ void delete(); /** * Return whether the relationship has been deleted. */ boolean isDeleted(); /** * Used to indicate if this {@link Relationship} has been created as the result of a {@link Rule} inference. * @see Rule * * @return true if this {@link Relationship} exists due to a rule */ boolean isInferred(); }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/RelationshipTypeImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Concept; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * <p> * An ontological element which categorises how instances may relate to each other. * </p> * * <p> * A relation type defines how {@link ai.grakn.concept.Type} may relate to one another. * They are used to model and categorise n-ary relationships. * </p> * * @author fppt * */ public class RelationshipTypeImpl extends TypeImpl<RelationshipType, Relationship> implements RelationshipType { private final Cache<Set<Role>> cachedRelates = Cache.createSessionCache(this, Cacheable.set(), () -> this.<Role>neighbours(Direction.OUT, Schema.EdgeLabel.RELATES).collect(Collectors.toSet())); private RelationshipTypeImpl(VertexElement vertexElement) { super(vertexElement); } private RelationshipTypeImpl(VertexElement vertexElement, RelationshipType type) { super(vertexElement, type); } public static RelationshipTypeImpl get(VertexElement vertexElement){ return new RelationshipTypeImpl(vertexElement); } public static RelationshipTypeImpl create(VertexElement vertexElement, RelationshipType type){ RelationshipTypeImpl relationType = new RelationshipTypeImpl(vertexElement, type); vertexElement.tx().txCache().trackForValidation(relationType); return relationType; } @Override public Relationship create() { return addRelationship(false); } public Relationship addRelationshipInferred() { return addRelationship(true); } public Relationship addRelationship(boolean isInferred) { Relationship relationship = addInstance(Schema.BaseType.RELATIONSHIP, (vertex, type) -> vertex().tx().factory().buildRelation(vertex, type), isInferred, true); vertex().tx().txCache().addNewRelationship(relationship); return relationship; } @Override public Stream<Role> roles() { return cachedRelates.get().stream(); } @Override public RelationshipType relates(Role role) { checkSchemaMutationAllowed(); putEdge(ConceptVertex.from(role), Schema.EdgeLabel.RELATES); //TODO: the following lines below this comment should only be executed if the edge is added //Cache the Role internally cachedRelates.ifPresent(set -> set.add(role)); //Cache the relation type in the role ((RoleImpl) role).addCachedRelationType(this); return this; } /** * * @param role The {@link Role} to delete from this {@link RelationshipType}. * @return The {@link Relationship} Type itself. */ @Override public RelationshipType unrelate(Role role) { checkSchemaMutationAllowed(); deleteEdge(Direction.OUT, Schema.EdgeLabel.RELATES, (Concept) role); RoleImpl roleTypeImpl = (RoleImpl) role; //Add roleplayers of role to make sure relations are still valid roleTypeImpl.rolePlayers().forEach(rolePlayer -> vertex().tx().txCache().trackForValidation(rolePlayer)); //Add the Role Type itself vertex().tx().txCache().trackForValidation(roleTypeImpl); //Add the Relationship Type vertex().tx().txCache().trackForValidation(roleTypeImpl); //Remove from internal cache cachedRelates.ifPresent(set -> set.remove(role)); //Remove from roleTypeCache ((RoleImpl) role).deleteCachedRelationType(this); return this; } @Override public void delete(){ cachedRelates.get().forEach(r -> { RoleImpl role = ((RoleImpl) r); vertex().tx().txCache().trackForValidation(role); ((RoleImpl) r).deleteCachedRelationType(this); }); super.delete(); } @Override void trackRolePlayers(){ instances().forEach(concept -> { RelationshipImpl relation = RelationshipImpl.from(concept); if(relation.reified().isPresent()){ relation.reified().get().castingsRelation().forEach(rolePlayer -> vertex().tx().txCache().trackForValidation(rolePlayer)); } }); } @Override public Stream<Relationship> instancesDirect(){ Stream<Relationship> instances = super.instancesDirect(); //If the relation type is implicit then we need to get any relation edges it may have. if(isImplicit()) instances = Stream.concat(instances, relationEdges()); return instances; } private Stream<Relationship> relationEdges(){ //Unfortunately this is a slow process return roles(). flatMap(Role::players). flatMap(type ->{ //Traversal is used here to take advantage of vertex centric index return vertex().tx().getTinkerTraversal().V(). has(Schema.VertexProperty.ID.name(), type.id().getValue()). in(Schema.EdgeLabel.SHARD.getLabel()). in(Schema.EdgeLabel.ISA.getLabel()). outE(Schema.EdgeLabel.ATTRIBUTE.getLabel()). has(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID.name(), labelId().getValue()). toStream(). map(edge -> vertex().tx().factory().<Relationship>buildConcept(edge)); }); } public static RelationshipTypeImpl from(RelationshipType relationshipType){ return (RelationshipTypeImpl) relationshipType; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/RoleImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Type; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.kb.internal.structure.Casting; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.CommonUtil; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * <p> * An {@link ai.grakn.concept.SchemaConcept} which defines a {@link Role} which can be played in a {@link RelationshipType}. * </p> * * <p> * This {@link ai.grakn.concept.SchemaConcept} defines the roles which make up a {@link RelationshipType}. * It has some additional functionality: * 1. It cannot play a {@link Role} to itself. * 2. It is special in that it is unique to {@link RelationshipType}s. * </p> * * @author fppt * */ public class RoleImpl extends SchemaConceptImpl<Role> implements Role { private final Cache<Set<Type>> cachedDirectPlayedByTypes = Cache.createSessionCache(this, Cacheable.set(), () -> this.<Type>neighbours(Direction.IN, Schema.EdgeLabel.PLAYS).collect(Collectors.toSet())); private final Cache<Set<RelationshipType>> cachedRelationTypes = Cache.createSessionCache(this, Cacheable.set(), () -> this.<RelationshipType>neighbours(Direction.IN, Schema.EdgeLabel.RELATES).collect(Collectors.toSet())); private RoleImpl(VertexElement vertexElement) { super(vertexElement); } private RoleImpl(VertexElement vertexElement, Role type) { super(vertexElement, type); } public static RoleImpl get(VertexElement vertexElement){ return new RoleImpl(vertexElement); } public static RoleImpl create(VertexElement vertexElement, Role type) { RoleImpl role = new RoleImpl(vertexElement, type); vertexElement.tx().txCache().trackForValidation(role); return role; } @Override public Stream<RelationshipType> relationships() { return cachedRelationTypes.get().stream(); } /** * Caches a new relation type which this role will be part of. This may result in a DB hit if the cache has not been * initialised. * * @param newRelationshipType The new relation type to cache in the role. */ void addCachedRelationType(RelationshipType newRelationshipType){ cachedRelationTypes.ifPresent(set -> set.add(newRelationshipType)); } /** * Removes an old relation type which this role is no longer part of. This may result in a DB hit if the cache has * not been initialised. * * @param oldRelationshipType The new relation type to cache in the role. */ void deleteCachedRelationType(RelationshipType oldRelationshipType){ cachedRelationTypes.ifPresent(set -> set.remove(oldRelationshipType)); } /** * * @return A list of all the Concept Types which can play this role. */ @Override public Stream<Type> players() { return cachedDirectPlayedByTypes.get().stream().flatMap(Type::subs); } void addCachedDirectPlaysByType(Type newType){ cachedDirectPlayedByTypes.ifPresent(set -> set.add(newType)); } void deleteCachedDirectPlaysByType(Type oldType){ cachedDirectPlayedByTypes.ifPresent(set -> set.remove(oldType)); } /** * * @return Get all the roleplayers of this role type */ public Stream<Casting> rolePlayers(){ return relationships(). flatMap(RelationshipType::instances). map(relation -> RelationshipImpl.from(relation).reified()). flatMap(CommonUtil::optionalToStream). flatMap(relation -> relation.castingsRelation(this)); } @Override boolean deletionAllowed(){ return super.deletionAllowed() && !neighbours(Direction.IN, Schema.EdgeLabel.RELATES).findAny().isPresent() && // This role is not linked t any relation type !neighbours(Direction.IN, Schema.EdgeLabel.PLAYS).findAny().isPresent() && // Nothing can play this role !rolePlayers().findAny().isPresent(); // This role has no role players } @Override void trackRolePlayers() { //TODO: track the super change when the role super changes } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/RuleImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Rule; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.graql.Pattern; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.stream.Stream; /** * <p> * An ontological element used to model and categorise different types of {@link Rule}. * </p> * * <p> * An ontological element used to define different types of {@link Rule}. * </p> * * @author fppt */ public class RuleImpl extends SchemaConceptImpl<Rule> implements Rule { private RuleImpl(VertexElement vertexElement) { super(vertexElement); } private RuleImpl(VertexElement vertexElement, Rule type, Pattern when, Pattern then) { super(vertexElement, type); vertex().propertyImmutable(Schema.VertexProperty.RULE_WHEN, when, when(), Pattern::toString); vertex().propertyImmutable(Schema.VertexProperty.RULE_THEN, then, then(), Pattern::toString); } public static RuleImpl get(VertexElement vertexElement){ return new RuleImpl(vertexElement); } public static RuleImpl create(VertexElement vertexElement, Rule type, Pattern when, Pattern then) { RuleImpl rule = new RuleImpl(vertexElement, type, when, then); vertexElement.tx().txCache().trackForValidation(rule); return rule; } @Override void trackRolePlayers() { //TODO: CLean this up } @Override public Pattern when() { return parsePattern(vertex().property(Schema.VertexProperty.RULE_WHEN)); } @Override public Pattern then() { return parsePattern(vertex().property(Schema.VertexProperty.RULE_THEN)); } @Override public Stream<Type> whenTypes() { return neighbours(Direction.OUT, Schema.EdgeLabel.HYPOTHESIS); } @Override public Stream<Type> thenTypes() { return neighbours(Direction.OUT, Schema.EdgeLabel.CONCLUSION); } /** * * @param type The {@link Type} which this {@link Rule} applies to. */ public void addHypothesis(Type type) { putEdge(ConceptVertex.from(type), Schema.EdgeLabel.HYPOTHESIS); } /** * * @param type The {@link Type} which is the conclusion of this {@link Rule}. */ public void addConclusion(Type type) { putEdge(ConceptVertex.from(type), Schema.EdgeLabel.CONCLUSION); } private Pattern parsePattern(String value){ if(value == null) { return null; } else { return vertex().tx().graql().parser().parsePattern(value); } } public static <X extends Type, Y extends Thing> RuleImpl from(Rule type){ //noinspection unchecked return (RuleImpl) type; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/SchemaConceptImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Concept; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.LabelId; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.exception.PropertyNotUniqueException; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static scala.tools.scalap.scalax.rules.scalasig.NoSymbol.isAbstract; /** * <p> * Schema Specific {@link Concept} * </p> * * <p> * Allows you to create schema or ontological elements. * These differ from normal graph constructs in two ways: * 1. They have a unique {@link Label} which identifies them * 2. You can link them together into a hierarchical structure * </p> * * @author fppt * * @param <T> The leaf interface of the object concept. * For example an {@link EntityType} or {@link RelationshipType} or {@link Role} */ public abstract class SchemaConceptImpl<T extends SchemaConcept> extends ConceptImpl implements SchemaConcept { private final Cache<Label> cachedLabel = Cache.createPersistentCache(this, Cacheable.label(), () -> Label.of(vertex().property(Schema.VertexProperty.SCHEMA_LABEL))); private final Cache<LabelId> cachedLabelId = Cache.createSessionCache(this, Cacheable.labelId(), () -> LabelId.of(vertex().property(Schema.VertexProperty.LABEL_ID))); private final Cache<T> cachedSuperType = Cache.createSessionCache(this, Cacheable.concept(), () -> this.<T>neighbours(Direction.OUT, Schema.EdgeLabel.SUB).findFirst().orElse(null)); private final Cache<Set<T>> cachedDirectSubTypes = Cache.createSessionCache(this, Cacheable.set(), () -> this.<T>neighbours(Direction.IN, Schema.EdgeLabel.SUB).collect(Collectors.toSet())); private final Cache<Boolean> cachedIsImplicit = Cache.createSessionCache(this, Cacheable.bool(), () -> vertex().propertyBoolean(Schema.VertexProperty.IS_IMPLICIT)); SchemaConceptImpl(VertexElement vertexElement) { super(vertexElement); } SchemaConceptImpl(VertexElement vertexElement, T superType) { this(vertexElement); if(sup() == null) sup(superType); } public T label(Label label){ try { vertex().tx().txCache().remove(this); vertex().propertyUnique(Schema.VertexProperty.SCHEMA_LABEL, label.getValue()); cachedLabel.set(label); vertex().tx().txCache().cacheConcept(this); return getThis(); } catch (PropertyNotUniqueException exception){ vertex().tx().txCache().cacheConcept(this); throw GraknTxOperationException.labelTaken(label); } } /** * * @return The internal id which is used for fast lookups */ @Override public LabelId labelId(){ return cachedLabelId.get(); } /** * * @return The label of this ontological element */ @Override public Label label() { return cachedLabel.get(); } /** * * @return The super of this {@link SchemaConcept} */ public T sup() { return cachedSuperType.get(); } @Override public Stream<T> sups() { Set<T> superSet= new HashSet<>(); T superParent = getThis(); while(superParent != null && !Schema.MetaSchema.THING.getLabel().equals(superParent.label())){ superSet.add(superParent); //noinspection unchecked superParent = (T) superParent.sup(); } return superSet.stream(); } /** * * @return returns true if the type was created implicitly through the resource syntax */ @Override public Boolean isImplicit(){ return cachedIsImplicit.get(); } /** * Deletes the concept as a {@link SchemaConcept} */ @Override public void delete(){ if(deletionAllowed()){ //Force load of linked concepts whose caches need to be updated T superConcept = cachedSuperType.get(); deleteNode(); //Update neighbouring caches //noinspection unchecked SchemaConceptImpl.from(superConcept).deleteCachedDirectedSubType(getThis()); //Clear Global Cache vertex().tx().txCache().remove(this); //Clear internal caching txCacheClear(); } else { throw GraknTxOperationException.cannotBeDeleted(this); } } boolean deletionAllowed(){ checkSchemaMutationAllowed(); return !neighbours(Direction.IN, Schema.EdgeLabel.SUB).findAny().isPresent(); } /** * * @return All the subs of this concept including itself */ @Override public Stream<T> subs(){ return nextSubLevel(getThis()); } /** * Adds a new sub type to the currently cached sub types. If no subtypes have been cached then this will hit the database. * * @param newSubType The new subtype */ private void addCachedDirectSubType(T newSubType){ cachedDirectSubTypes.ifPresent(set -> set.add(newSubType)); } /** * * @param root The current {@link SchemaConcept} * @return All the sub children of the root. Effectively calls the cache {@link SchemaConceptImpl#cachedDirectSubTypes} recursively */ @SuppressWarnings("unchecked") private Stream<T> nextSubLevel(T root){ return Stream.concat(Stream.of(root), SchemaConceptImpl.<T>from(root).cachedDirectSubTypes.get().stream().flatMap(this::nextSubLevel)); } /** * Checks if we are mutating a {@link SchemaConcept} in a valid way. {@link SchemaConcept} mutations are valid if: * 1. The {@link SchemaConcept} is not a meta-type * 2. The graph is not batch loading */ void checkSchemaMutationAllowed(){ vertex().tx().checkSchemaMutationAllowed(); if(Schema.MetaSchema.isMetaLabel(label())){ throw GraknTxOperationException.metaTypeImmutable(label()); } } /** * Removes an old sub type from the currently cached sub types. If no subtypes have been cached then this will hit the database. * * @param oldSubType The old sub type which should not be cached anymore */ private void deleteCachedDirectedSubType(T oldSubType){ cachedDirectSubTypes.ifPresent(set -> set.remove(oldSubType)); } /** * * @param newSuperType This type's super type * @return The Type itself */ public T sup(T newSuperType) { T oldSuperType = sup(); if(changingSuperAllowed(oldSuperType, newSuperType)){ //Update the super type of this type in cache cachedSuperType.set(newSuperType); //Note the check before the actual construction if(superLoops()){ cachedSuperType.set(oldSuperType); //Reset if the new super type causes a loop throw GraknTxOperationException.loopCreated(this, newSuperType); } //Modify the graph once we have checked no loop occurs deleteEdge(Direction.OUT, Schema.EdgeLabel.SUB); putEdge(ConceptVertex.from(newSuperType), Schema.EdgeLabel.SUB); //Update the sub types of the old super type if(oldSuperType != null) { //noinspection unchecked - Casting is needed to access {deleteCachedDirectedSubTypes} method ((SchemaConceptImpl<T>) oldSuperType).deleteCachedDirectedSubType(getThis()); } //Add this as the subtype to the supertype //noinspection unchecked - Casting is needed to access {addCachedDirectSubTypes} method ((SchemaConceptImpl<T>) newSuperType).addCachedDirectSubType(getThis()); //Track any existing data if there is some if(oldSuperType != null) trackRolePlayers(); } return getThis(); } /** * Checks if changing the super is allowed. This passed if: * 1. The transaction is not of type {@link ai.grakn.GraknTxType#BATCH} * 2. The <code>newSuperType</code> is different from the old. * * @param oldSuperType the old super * @param newSuperType the new super * @return true if we can set the new super */ boolean changingSuperAllowed(T oldSuperType, T newSuperType){ checkSchemaMutationAllowed(); return oldSuperType == null || !oldSuperType.equals(newSuperType); } /** * Method which performs tasks needed in order to track super changes properly */ abstract void trackRolePlayers(); private boolean superLoops(){ //Check For Loop HashSet<SchemaConcept> foundTypes = new HashSet<>(); SchemaConcept currentSuperType = sup(); while (currentSuperType != null){ foundTypes.add(currentSuperType); currentSuperType = currentSuperType.sup(); if(foundTypes.contains(currentSuperType)){ return true; } } return false; } /** * * @return A collection of {@link Rule} for which this {@link SchemaConcept} serves as a hypothesis */ @Override public Stream<Rule> whenRules() { return neighbours(Direction.IN, Schema.EdgeLabel.HYPOTHESIS); } /** * * @return A collection of {@link Rule} for which this {@link SchemaConcept} serves as a conclusion */ @Override public Stream<Rule> thenRules() { return neighbours(Direction.IN, Schema.EdgeLabel.CONCLUSION); } @Override public String innerToString(){ String message = super.innerToString(); message = message + " - Label [" + label() + "] - Abstract [" + isAbstract() + "] "; return message; } public static <X extends SchemaConcept> SchemaConceptImpl<X> from(SchemaConcept schemaConcept){ //noinspection unchecked return (SchemaConceptImpl<X>) schemaConcept; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/ThingImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.LabelId; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.kb.internal.structure.Casting; import ai.grakn.kb.internal.structure.EdgeElement; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import com.google.common.collect.Sets; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.util.Schema.EdgeProperty.ROLE_LABEL_ID; import static java.util.stream.Collectors.toSet; /** * <p> * A data instance in the graph belonging to a specific {@link Type} * </p> * * <p> * Instances represent data in the graph. * Every instance belongs to a {@link Type} which serves as a way of categorising them. * Instances can relate to one another via {@link Relationship} * </p> * * @author fppt * * @param <T> The leaf interface of the object concept which extends {@link Thing}. * For example {@link ai.grakn.concept.Entity} or {@link Relationship}. * @param <V> The type of the concept which extends {@link Type} of the concept. * For example {@link ai.grakn.concept.EntityType} or {@link RelationshipType} */ public abstract class ThingImpl<T extends Thing, V extends Type> extends ConceptImpl implements Thing { private final Cache<Label> cachedInternalType = Cache.createTxCache(this, Cacheable.label(), () -> { int typeId = vertex().property(Schema.VertexProperty.THING_TYPE_LABEL_ID); Optional<Type> type = vertex().tx().getConcept(Schema.VertexProperty.LABEL_ID, typeId); return type.orElseThrow(() -> GraknTxOperationException.missingType(id())).label(); }); private final Cache<V> cachedType = Cache.createTxCache(this, Cacheable.concept(), () -> { Optional<V> type = vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ISA). map(EdgeElement::target). flatMap(edge -> edge.getEdgesOfType(Direction.OUT, Schema.EdgeLabel.SHARD)). map(EdgeElement::target). map(concept -> vertex().tx().factory().<V>buildConcept(concept)). findAny(); return type.orElseThrow(() -> GraknTxOperationException.noType(this)); }); ThingImpl(VertexElement vertexElement) { super(vertexElement); } ThingImpl(VertexElement vertexElement, V type) { this(vertexElement); type((TypeImpl) type); track(); } /** * This {@link Thing} gets tracked for validation only if it has keys which need to be checked. */ private void track(){ if(type().keys().findAny().isPresent()){ vertex().tx().txCache().trackForValidation(this); } } public boolean isInferred(){ return vertex().propertyBoolean(Schema.VertexProperty.IS_INFERRED); } /** * Deletes the concept as an Thing */ @Override public void delete() { //Remove links to relationships and return them Set<Relationship> relationships = castingsInstance().map(casting -> { Relationship relationship = casting.getRelationship(); Role role = casting.getRole(); relationship.unassign(role, this); return relationship; }).collect(toSet()); vertex().tx().txCache().removedInstance(type().id()); deleteNode(); relationships.forEach(relation -> { if(relation.type().isImplicit()){//For now implicit relationships die relation.delete(); } else { RelationshipImpl rel = (RelationshipImpl) relation; rel.cleanUp(); } }); } /** * This index is used by concepts such as casting and relations to speed up internal lookups * @return The inner index value of some concepts. */ public String getIndex(){ return vertex().property(Schema.VertexProperty.INDEX); } @Override public Stream<Attribute<?>> attributes(AttributeType... attributeTypes) { Set<ConceptId> attributeTypesIds = Arrays.stream(attributeTypes).map(Concept::id).collect(toSet()); return attributes(getShortcutNeighbours(true), attributeTypesIds); } @Override public Stream<Attribute<?>> keys(AttributeType... attributeTypes){ Set<ConceptId> attributeTypesIds = Arrays.stream(attributeTypes).map(Concept::id).collect(toSet()); Set<ConceptId> keyTypeIds = type().keys().map(Concept::id).collect(toSet()); if(!attributeTypesIds.isEmpty()){ keyTypeIds = Sets.intersection(attributeTypesIds, keyTypeIds); } if(keyTypeIds.isEmpty()) return Stream.empty(); return attributes(getShortcutNeighbours(true), keyTypeIds); } /** * Helper class which filters a {@link Stream} of {@link Attribute} to those of a specific set of {@link AttributeType}. * * @param conceptStream The {@link Stream} to filter * @param attributeTypesIds The {@link AttributeType} {@link ConceptId}s to filter to. * @return the filtered stream */ private <X extends Concept> Stream<Attribute<?>> attributes(Stream<X> conceptStream, Set<ConceptId> attributeTypesIds){ Stream<Attribute<?>> attributeStream = conceptStream. filter(concept -> concept.isAttribute() && !this.equals(concept)). map(Concept::asAttribute); if(!attributeTypesIds.isEmpty()){ attributeStream = attributeStream.filter(attribute -> attributeTypesIds.contains(attribute.type().id())); } return attributeStream; } /** * Castings are retrieved from the perspective of the {@link Thing} which is a role player in a {@link Relationship} * * @return All the {@link Casting} which this instance is cast into the role */ Stream<Casting> castingsInstance(){ return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.ROLE_PLAYER). map(edge -> Casting.withThing(edge, this)); } private Set<Integer> implicitLabelsToIds(Set<Label> labels, Set<Schema.ImplicitType> implicitTypes){ return labels.stream() .flatMap(label -> implicitTypes.stream().map(it -> it.getLabel(label))) .map(label -> vertex().tx().convertToId(label)) .filter(id -> !id.equals(LabelId.invalid())) .map(LabelId::getValue) .collect(toSet()); } <X extends Thing> Stream<X> getShortcutNeighbours(boolean ownerToValueOrdering, AttributeType... attributeTypes){ Set<AttributeType> completeAttributeTypes = new HashSet<>(Arrays.asList(attributeTypes)); if (completeAttributeTypes.isEmpty()) completeAttributeTypes.add(vertex().tx().getMetaAttributeType()); Set<Label> attributeHierachyLabels = completeAttributeTypes.stream() .flatMap(t -> (Stream<AttributeType>) t.subs()) .map(SchemaConcept::label) .collect(toSet()); Set<Integer> ownerRoleIds = implicitLabelsToIds( attributeHierachyLabels, Sets.newHashSet( Schema.ImplicitType.HAS_OWNER, Schema.ImplicitType.KEY_OWNER )); Set<Integer> valueRoleIds = implicitLabelsToIds( attributeHierachyLabels, Sets.newHashSet( Schema.ImplicitType.HAS_VALUE, Schema.ImplicitType.KEY_VALUE )); //NB: need extra check cause it seems valid types can still produce invalid ids GraphTraversal<Vertex, Vertex> shortcutTraversal = !(ownerRoleIds.isEmpty() || valueRoleIds.isEmpty())? __.inE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()). as("edge"). has(ROLE_LABEL_ID.name(), P.within(ownerToValueOrdering? ownerRoleIds : valueRoleIds)). outV(). outE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()). has(ROLE_LABEL_ID.name(), P.within(ownerToValueOrdering? valueRoleIds : ownerRoleIds)). where(P.neq("edge")). inV() : __.inE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()). as("edge"). outV(). outE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()). where(P.neq("edge")). inV(); GraphTraversal<Vertex, Vertex> attributeEdgeTraversal = __.outE(Schema.EdgeLabel.ATTRIBUTE.getLabel()).inV(); //noinspection unchecked return vertex().tx().getTinkerTraversal().V(). has(Schema.VertexProperty.ID.name(), id().getValue()). union(shortcutTraversal, attributeEdgeTraversal).toStream(). map(vertex -> vertex().tx().<X>buildConcept(vertex)); } /** * * @param roles An optional parameter which allows you to specify the role of the relations you wish to retrieve. * @return A set of Relations which the concept instance takes part in, optionally constrained by the Role Type. */ @Override public Stream<Relationship> relationships(Role... roles) { return Stream.concat(reifiedRelations(roles), edgeRelations(roles)); } private Stream<Relationship> reifiedRelations(Role... roles){ GraphTraversal<Vertex, Vertex> traversal = vertex().tx().getTinkerTraversal().V(). has(Schema.VertexProperty.ID.name(), id().getValue()); if(roles.length == 0){ traversal.in(Schema.EdgeLabel.ROLE_PLAYER.getLabel()); } else { Set<Integer> roleTypesIds = Arrays.stream(roles).map(r -> r.labelId().getValue()).collect(toSet()); traversal.inE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()). has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), P.within(roleTypesIds)).outV(); } return traversal.toStream().map(vertex -> vertex().tx().<Relationship>buildConcept(vertex)); } private Stream<Relationship> edgeRelations(Role... roles){ Set<Role> roleSet = new HashSet<>(Arrays.asList(roles)); Stream<EdgeElement> stream = vertex().getEdgesOfType(Direction.BOTH, Schema.EdgeLabel.ATTRIBUTE); if(!roleSet.isEmpty()){ stream = stream.filter(edge -> { Role roleOwner = vertex().tx().getSchemaConcept(LabelId.of(edge.property(Schema.EdgeProperty.RELATIONSHIP_ROLE_OWNER_LABEL_ID))); return roleSet.contains(roleOwner); }); } return stream.map(edge -> vertex().tx().factory().buildRelation(edge)); } @Override public Stream<Role> roles() { return castingsInstance().map(Casting::getRole); } @Override public T has(Attribute attribute) { relhas(attribute); return getThis(); } public T attributeInferred(Attribute attribute) { attributeRelationship(attribute, true); return getThis(); } @Override public Relationship relhas(Attribute attribute) { return attributeRelationship(attribute, false); } private Relationship attributeRelationship(Attribute attribute, boolean isInferred) { Schema.ImplicitType has = Schema.ImplicitType.HAS; Schema.ImplicitType hasValue = Schema.ImplicitType.HAS_VALUE; Schema.ImplicitType hasOwner = Schema.ImplicitType.HAS_OWNER; //Is this attribute a key to me? if(type().keys().anyMatch(rt -> rt.equals(attribute.type()))){ has = Schema.ImplicitType.KEY; hasValue = Schema.ImplicitType.KEY_VALUE; hasOwner = Schema.ImplicitType.KEY_OWNER; } Label label = attribute.type().label(); RelationshipType hasAttribute = vertex().tx().getSchemaConcept(has.getLabel(label)); Role hasAttributeOwner = vertex().tx().getSchemaConcept(hasOwner.getLabel(label)); Role hasAttributeValue = vertex().tx().getSchemaConcept(hasValue.getLabel(label)); if(hasAttribute == null || hasAttributeOwner == null || hasAttributeValue == null || type().playing().noneMatch(play -> play.equals(hasAttributeOwner))){ throw GraknTxOperationException.hasNotAllowed(this, attribute); } EdgeElement attributeEdge = addEdge(AttributeImpl.from(attribute), Schema.EdgeLabel.ATTRIBUTE); if(isInferred) attributeEdge.property(Schema.EdgeProperty.IS_INFERRED, true); return vertex().tx().factory().buildRelation(attributeEdge, hasAttribute, hasAttributeOwner, hasAttributeValue); } @Override public T unhas(Attribute attribute){ Role roleHasOwner = vertex().tx().getSchemaConcept(Schema.ImplicitType.HAS_OWNER.getLabel(attribute.type().label())); Role roleKeyOwner = vertex().tx().getSchemaConcept(Schema.ImplicitType.KEY_OWNER.getLabel(attribute.type().label())); Role roleHasValue = vertex().tx().getSchemaConcept(Schema.ImplicitType.HAS_VALUE.getLabel(attribute.type().label())); Role roleKeyValue = vertex().tx().getSchemaConcept(Schema.ImplicitType.KEY_VALUE.getLabel(attribute.type().label())); Stream<Relationship> relationships = relationships(filterNulls(roleHasOwner, roleKeyOwner)); relationships.filter(relationship -> { Stream<Thing> rolePlayers = relationship.rolePlayers(filterNulls(roleHasValue, roleKeyValue)); return rolePlayers.anyMatch(rolePlayer -> rolePlayer.equals(attribute)); }).forEach(Concept::delete); return getThis(); } /** * Returns an array with all the nulls filtered out. */ private Role[] filterNulls(Role ... roles){ return Arrays.stream(roles).filter(Objects::nonNull).toArray(Role[]::new); } /** * * @return The type of the concept casted to the correct interface */ public V type() { return cachedType.get(); } /** * * @param type The type of this concept */ private void type(TypeImpl type) { if(type != null){ //noinspection unchecked cachedType.set((V) type); //We cache the type early because it turns out we use it EVERY time. So this prevents many db reads type.currentShard().link(this); setInternalType(type); } } /** * * @param type The type of this concept */ private void setInternalType(Type type){ cachedInternalType.set(type.label()); vertex().property(Schema.VertexProperty.THING_TYPE_LABEL_ID, type.labelId().getValue()); } /** * * @return The id of the type of this concept. This is a shortcut used to prevent traversals. */ Label getInternalType(){ return cachedInternalType.get(); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/TypeImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.concept; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.Label; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.kb.internal.structure.EdgeElement; import ai.grakn.kb.internal.structure.Shard; import ai.grakn.kb.internal.structure.VertexElement; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * <p> * A Type represents any ontological element in the graph. * </p> * * <p> * Types are used to model the behaviour of {@link Thing} and how they relate to each other. * They also aid in categorising {@link Thing} to different types. * </p> * * @author fppt * * @param <T> The leaf interface of the object concept. For example an {@link ai.grakn.concept.EntityType} or {@link RelationshipType} * @param <V> The instance of this type. For example {@link ai.grakn.concept.Entity} or {@link Relationship} */ public class TypeImpl<T extends Type, V extends Thing> extends SchemaConceptImpl<T> implements Type{ private final Cache<Boolean> cachedIsAbstract = Cache.createSessionCache(this, Cacheable.bool(), () -> vertex().propertyBoolean(Schema.VertexProperty.IS_ABSTRACT)); //This cache is different in order to keep track of which plays are required private final Cache<Map<Role, Boolean>> cachedDirectPlays = Cache.createSessionCache(this, Cacheable.map(), () -> { Map<Role, Boolean> roleTypes = new HashMap<>(); vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.PLAYS).forEach(edge -> { Role role = vertex().tx().factory().buildConcept(edge.target()); Boolean required = edge.propertyBoolean(Schema.EdgeProperty.REQUIRED); roleTypes.put(role, required); }); return roleTypes; }); TypeImpl(VertexElement vertexElement) { super(vertexElement); } TypeImpl(VertexElement vertexElement, T superType) { super(vertexElement, superType); //This constructor is ONLY used when CREATING new types. Which is why we shard here createShard(); } /** * Utility method used to create or find an instance of this type * * @param instanceBaseType The base type of the instances of this type * @param finder The method to find the instrance if it already exists * @param producer The factory method to produce the instance if it doesn't exist * @return A new or already existing instance */ V putInstance(Schema.BaseType instanceBaseType, Supplier<V> finder, BiFunction<VertexElement, T, V> producer, boolean isInferred) { preCheckForInstanceCreation(); V instance = finder.get(); if(instance == null) { instance = addInstance(instanceBaseType, producer, isInferred, false); } else { if(isInferred && !instance.isInferred()){ throw GraknTxOperationException.nonInferredThingExists(instance); } } return instance; } /** * Utility method used to create an instance of this type * * @param instanceBaseType The base type of the instances of this type * @param producer The factory method to produce the instance * @param checkNeeded indicates if a check is necessary before adding the instance * @return A new instance */ V addInstance(Schema.BaseType instanceBaseType, BiFunction<VertexElement, T, V> producer, boolean isInferred, boolean checkNeeded){ if(checkNeeded) preCheckForInstanceCreation(); if(isAbstract()) throw GraknTxOperationException.addingInstancesToAbstractType(this); VertexElement instanceVertex = vertex().tx().addVertexElement(instanceBaseType); if(!Schema.MetaSchema.isMetaLabel(label())) { vertex().tx().txCache().addedInstance(id()); if(isInferred) instanceVertex.property(Schema.VertexProperty.IS_INFERRED, true); } V instance = producer.apply(instanceVertex, getThis()); assert instance != null : "producer should never return null"; return instance; } /** * Checks if an {@link Thing} is allowed to be created and linked to this {@link Type}. * This can fail is the {@link ai.grakn.GraknTxType} is read only. * It can also fail when attempting to attach an {@link ai.grakn.concept.Attribute} to a meta type */ private void preCheckForInstanceCreation(){ vertex().tx().checkMutationAllowed(); if(Schema.MetaSchema.isMetaLabel(label())){ throw GraknTxOperationException.metaTypeImmutable(label()); } } /** * * @return A list of all the roles this Type is allowed to play. */ @Override public Stream<Role> playing() { //Get the immediate plays which may be cached Stream<Role> allRoles = directPlays().keySet().stream(); //Now get the super type plays (Which may also be cached locally within their own context Stream<Role> superSet = this.sups(). filter(sup -> !sup.equals(this)). //We already have the plays from ourselves flatMap(sup -> TypeImpl.from(sup).directPlays().keySet().stream()); return Stream.concat(allRoles, superSet); } @Override public Stream<AttributeType> attributes() { Stream<AttributeType> attributes = attributes(Schema.ImplicitType.HAS_OWNER); return Stream.concat(attributes, keys()); } @Override public Stream<AttributeType> keys() { return attributes(Schema.ImplicitType.KEY_OWNER); } private Stream<AttributeType> attributes(Schema.ImplicitType implicitType){ //TODO: Make this less convoluted String [] implicitIdentifiers = implicitType.getLabel("").getValue().split("--"); String prefix = implicitIdentifiers[0] + "-"; String suffix = "-" + implicitIdentifiers[1]; //A traversal is not used in this so that caching can be taken advantage of. return playing().map(role -> role.label().getValue()). filter(roleLabel -> roleLabel.startsWith(prefix) && roleLabel.endsWith(suffix)). map(roleLabel -> { String attributeTypeLabel = roleLabel.replace(prefix, "").replace(suffix, ""); return vertex().tx().getAttributeType(attributeTypeLabel); }); } public Map<Role, Boolean> directPlays(){ return cachedDirectPlays.get(); } /** * Deletes the concept as type */ @Override public void delete(){ //If the deletion is successful we will need to update the cache of linked concepts. To do this caches must be loaded Map<Role, Boolean> plays = cachedDirectPlays.get(); super.delete(); //Updated caches of linked types plays.keySet().forEach(roleType -> ((RoleImpl) roleType).deleteCachedDirectPlaysByType(getThis())); } @Override boolean deletionAllowed(){ return super.deletionAllowed() && !currentShard().links().findAny().isPresent(); } /** * * @return All the instances of this type. */ @SuppressWarnings("unchecked") @Override public Stream<V> instances() { return subs().flatMap(sub -> TypeImpl.<T, V>from(sub).instancesDirect()); } Stream<V> instancesDirect(){ return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.SHARD). map(EdgeElement::source). map(source -> vertex().tx().factory().buildShard(source)). flatMap(Shard::<V>links); } @Override public Boolean isAbstract() { return cachedIsAbstract.get(); } void trackRolePlayers(){ instances().forEach(concept -> ((ThingImpl<?, ?>)concept).castingsInstance().forEach( rolePlayer -> vertex().tx().txCache().trackForValidation(rolePlayer))); } public T play(Role role, boolean required) { checkSchemaMutationAllowed(); //Update the internal cache of role types played cachedDirectPlays.ifPresent(map -> map.put(role, required)); //Update the cache of types played by the role ((RoleImpl) role).addCachedDirectPlaysByType(this); EdgeElement edge = putEdge(ConceptVertex.from(role), Schema.EdgeLabel.PLAYS); if (required) { edge.property(Schema.EdgeProperty.REQUIRED, true); } return getThis(); } /** * * @param role The Role Type which the instances of this Type are allowed to play. * @return The Type itself. */ public T plays(Role role) { return play(role, false); } /** * This is a temporary patch to prevent accidentally disconnecting implicit {@link RelationshipType}s from their * {@link RelationshipEdge}s. This Disconnection happens because {@link RelationshipType#instances()} depends on the * presence of a direct {@link Schema.EdgeLabel#PLAYS} edge between the {@link Type} and the implicit {@link RelationshipType}. * * When changing the super you may accidentally cause this disconnection. So we prevent it here. * */ //TODO: Remove this when traversing to the instances of an implicit Relationship Type is no longer done via plays edges @Override boolean changingSuperAllowed(T oldSuperType, T newSuperType){ boolean changingSuperAllowed = super.changingSuperAllowed(oldSuperType, newSuperType); if(changingSuperAllowed && oldSuperType != null && !Schema.MetaSchema.isMetaLabel(oldSuperType.label())) { //noinspection unchecked Set<Role> superPlays = oldSuperType.playing().collect(Collectors.toSet()); //Get everything that this can play bot including the supers Set<Role> plays = new HashSet<>(directPlays().keySet()); subs().flatMap(sub -> TypeImpl.from(sub).directPlays().keySet().stream()).forEach(plays::add); superPlays.removeAll(plays); //It is possible to be disconnecting from a role which is no longer in use but checking this will take too long //So we assume the role is in sure and throw if that is the case if(!superPlays.isEmpty() && instancesDirect().findAny().isPresent()){ throw GraknTxOperationException.changingSuperWillDisconnectRole(oldSuperType, newSuperType, superPlays.iterator().next()); } return true; } return changingSuperAllowed; } @Override public T unplay(Role role) { checkSchemaMutationAllowed(); deleteEdge(Direction.OUT, Schema.EdgeLabel.PLAYS, (Concept) role); cachedDirectPlays.ifPresent(set -> set.remove(role)); ((RoleImpl) role).deleteCachedDirectPlaysByType(this); trackRolePlayers(); return getThis(); } @Override public T unhas(AttributeType attributeType){ return deleteAttribute(Schema.ImplicitType.HAS_OWNER, attributes(), attributeType); } @Override public T unkey(AttributeType attributeType){ return deleteAttribute(Schema.ImplicitType.KEY_OWNER, keys(), attributeType); } /** * Helper method to delete a {@link AttributeType} which is possible linked to this {@link Type}. * The link to {@link AttributeType} is removed if <code>attributeToRemove</code> is in the candidate list * <code>attributeTypes</code> * * @param implicitType the {@link Schema.ImplicitType} which specifies which implicit {@link Role} should be removed * @param attributeTypes The list of candidate which potentially contains the {@link AttributeType} to remove * @param attributeToRemove the {@link AttributeType} to remove * @return the {@link Type} itself */ private T deleteAttribute(Schema.ImplicitType implicitType, Stream<AttributeType> attributeTypes, AttributeType attributeToRemove){ if(attributeTypes.anyMatch(a -> a.equals(attributeToRemove))){ Label label = implicitType.getLabel(attributeToRemove.label()); Role role = vertex().tx().getSchemaConcept(label); if(role != null) unplay(role); } return getThis(); } /** * * @param isAbstract Specifies if the concept is abstract (true) or not (false). * If the concept type is abstract it is not allowed to have any instances. * @return The Type itself. */ public T isAbstract(Boolean isAbstract) { if(!Schema.MetaSchema.isMetaLabel(label()) && isAbstract && instancesDirect().findAny().isPresent()){ throw GraknTxOperationException.addingInstancesToAbstractType(this); } property(Schema.VertexProperty.IS_ABSTRACT, isAbstract); cachedIsAbstract.set(isAbstract); if(isAbstract){ vertex().tx().txCache().removeFromValidation(this); } else { vertex().tx().txCache().trackForValidation(this); } return getThis(); } public T property(Schema.VertexProperty key, Object value){ if(!Schema.VertexProperty.CURRENT_LABEL_ID.equals(key)) checkSchemaMutationAllowed(); vertex().property(key, value); return getThis(); } private void updateAttributeRelationHierarchy(AttributeType attributeType, Schema.ImplicitType has, Schema.ImplicitType hasValue, Schema.ImplicitType hasOwner, Role ownerRole, Role valueRole, RelationshipType relationshipType){ AttributeType attributeTypeSuper = attributeType.sup(); Label superLabel = attributeTypeSuper.label(); Role ownerRoleSuper = vertex().tx().putRoleTypeImplicit(hasOwner.getLabel(superLabel)); Role valueRoleSuper = vertex().tx().putRoleTypeImplicit(hasValue.getLabel(superLabel)); RelationshipType relationshipTypeSuper = vertex().tx().putRelationTypeImplicit(has.getLabel(superLabel)). relates(ownerRoleSuper).relates(valueRoleSuper); //Create the super type edges from sub role/relations to super roles/relation ownerRole.sup(ownerRoleSuper); valueRole.sup(valueRoleSuper); relationshipType.sup(relationshipTypeSuper); if (!Schema.MetaSchema.ATTRIBUTE.getLabel().equals(superLabel)) { //Make sure the supertype attribute is linked with the role as well ((AttributeTypeImpl) attributeTypeSuper).plays(valueRoleSuper); updateAttributeRelationHierarchy(attributeTypeSuper, has, hasValue, hasOwner, ownerRoleSuper, valueRoleSuper, relationshipTypeSuper); } } /** * Creates a relation type which allows this type and a {@link ai.grakn.concept.Attribute} type to be linked. * @param attributeType The {@link AttributeType} which instances of this type should be allowed to play. * @param has the implicit relation type to build * @param hasValue the implicit role type to build for the {@link AttributeType} * @param hasOwner the implicit role type to build for the type * @param required Indicates if the {@link ai.grakn.concept.Attribute} is required on the entity * @return The {@link Type} itself */ private T has(AttributeType attributeType, Schema.ImplicitType has, Schema.ImplicitType hasValue, Schema.ImplicitType hasOwner, boolean required){ Label attributeLabel = attributeType.label(); Role ownerRole = vertex().tx().putRoleTypeImplicit(hasOwner.getLabel(attributeLabel)); Role valueRole = vertex().tx().putRoleTypeImplicit(hasValue.getLabel(attributeLabel)); RelationshipType relationshipType = vertex().tx().putRelationTypeImplicit(has.getLabel(attributeLabel)). relates(ownerRole). relates(valueRole); //this plays ownerRole; this.play(ownerRole, required); //TODO: Use explicit cardinality of 0-1 rather than just false //attributeType plays valueRole; ((AttributeTypeImpl) attributeType).play(valueRole, false); updateAttributeRelationHierarchy(attributeType, has, hasValue, hasOwner, ownerRole, valueRole, relationshipType); return getThis(); } @Override public T has(AttributeType attributeType){ checkAttributeAttachmentLegal(Schema.ImplicitType.KEY_OWNER, attributeType); return has(attributeType, Schema.ImplicitType.HAS, Schema.ImplicitType.HAS_VALUE, Schema.ImplicitType.HAS_OWNER, false); } @Override public T key(AttributeType attributeType) { checkAttributeAttachmentLegal(Schema.ImplicitType.HAS_OWNER, attributeType); return has(attributeType, Schema.ImplicitType.KEY, Schema.ImplicitType.KEY_VALUE, Schema.ImplicitType.KEY_OWNER, true); } private void checkAttributeAttachmentLegal(Schema.ImplicitType implicitType, AttributeType attributeType){ checkSchemaMutationAllowed(); checkIfHasTargetMeta(attributeType); checkNonOverlapOfImplicitRelations(implicitType, attributeType); } private void checkIfHasTargetMeta(AttributeType attributeType){ //Check if attribute type is the meta if(Schema.MetaSchema.ATTRIBUTE.getLabel().equals(attributeType.label())){ throw GraknTxOperationException.metaTypeImmutable(attributeType.label()); } } /** * Checks if the provided {@link AttributeType} is already used in an other implicit relation. * * @param implicitType The implicit relation to check against. * @param attributeType The {@link AttributeType} which should not be in that implicit relation * * @throws GraknTxOperationException when the {@link AttributeType} is already used in another implicit relation */ private void checkNonOverlapOfImplicitRelations(Schema.ImplicitType implicitType, AttributeType attributeType){ if(attributes(implicitType).anyMatch(rt -> rt.equals(attributeType))) { throw GraknTxOperationException.duplicateHas(this, attributeType); } } public static <X extends Type, Y extends Thing> TypeImpl<X,Y> from(Type type){ //noinspection unchecked return (TypeImpl<X, Y>) type; } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/concept/package-info.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * Internal implementation of {@link ai.grakn.concept.Concept}s */ package ai.grakn.kb.internal.concept;
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/structure/AbstractElement.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.structure; import ai.grakn.GraknTx; import ai.grakn.concept.Concept; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.exception.PropertyNotUniqueException; import ai.grakn.kb.internal.EmbeddedGraknTx; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import javax.annotation.Nullable; import java.util.Objects; import java.util.function.Function; import static org.apache.tinkerpop.gremlin.structure.T.id; /** * <p> * {@link GraknTx} AbstractElement * </p> * * <p> * Base class used to represent a construct in the graph. This includes exposed constructs such as {@link Concept} * and hidden constructs such as {@link EdgeElement} and {@link Casting} * </p> * * @param <E> The type of the element. Either {@link VertexElement} of {@link EdgeElement} * @param <P> Enum indicating the allowed properties on each type. Either {@link ai.grakn.util.Schema.VertexProperty} or * {@link ai.grakn.util.Schema.EdgeProperty} * * @author fppt * */ public abstract class AbstractElement<E extends Element, P extends Enum> { private final String prefix; private final E element; private final EmbeddedGraknTx tx; AbstractElement(EmbeddedGraknTx tx, E element, String prefix){ this.tx = tx; this.element = element; this.prefix = prefix; } public E element(){ return element; } public ElementId id(){ return ElementId.of(prefix + element().id()); } /** * Deletes the element from the graph */ public void delete(){ element().remove(); } /** * * @param key The key of the property to mutate * @param value The value to commit into the property */ public void property(P key, Object value){ if(value == null) { element().property(key.name()).remove(); } else { Property<Object> foundProperty = element().property(key.name()); if(!foundProperty.isPresent() || !foundProperty.value().equals(value)){ element().property(key.name(), value); } } } /** * * @param key The key of the non-unique property to retrieve * @return The value stored in the property */ @Nullable public <X> X property(P key){ Property<X> property = element().property(key.name()); if(property != null && property.isPresent()) { return property.value(); } return null; } public Boolean propertyBoolean(P key){ Boolean value = property(key); if(value == null) return false; return value; } /** * * @return The grakn graph this concept is bound to. */ public EmbeddedGraknTx<?> tx() { return tx; } /** * * @return The hash code of the underlying vertex */ public int hashCode() { return id.hashCode(); //Note: This means that concepts across different transactions will be equivalent. } /** * * @return true if the elements equal each other */ @Override public boolean equals(Object object) { //Compare Concept //based on id because vertex comparisons are equivalent return this == object || object instanceof AbstractElement && ((AbstractElement) object).id().equals(id()); } /** * Sets the value of a property with the added restriction that no other vertex can have that property. * * @param key The key of the unique property to mutate * @param value The new value of the unique property */ public void propertyUnique(P key, String value){ if(!tx().isBatchTx()) { GraphTraversal<Vertex, Vertex> traversal = tx().getTinkerTraversal().V().has(key.name(), value); if(traversal.hasNext()){ Vertex vertex = traversal.next(); if(!vertex.equals(element()) || traversal.hasNext()){ if(traversal.hasNext()) vertex = traversal.next(); throw PropertyNotUniqueException.cannotChangeProperty(element(), vertex, key, value); } } } property(key, value); } /** * Sets a property which cannot be mutated * * @param property The key of the immutable property to mutate * @param newValue The new value to put on the property (if the property is not set) * @param foundValue The current value of the property * @param converter Helper method to ensure data is persisted in the correct format */ public <X> void propertyImmutable(P property, X newValue, @Nullable X foundValue, Function<X, Object> converter){ Objects.requireNonNull(property); if(foundValue != null){ if(!foundValue.equals(newValue)){ throw GraknTxOperationException.immutableProperty(foundValue, newValue, property); } } else { property(property, converter.apply(newValue)); } } public <X> void propertyImmutable(P property, X newValue, X foundValue){ propertyImmutable(property, newValue, foundValue, Function.identity()); } /** * * @return the label of the element in the graph. */ public String label(){ return element().label(); } public final boolean isDeleted() { return !tx().isValidElement(element()); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/structure/Casting.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.structure; import ai.grakn.concept.LabelId; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.kb.internal.cache.Cache; import ai.grakn.kb.internal.cache.CacheOwner; import ai.grakn.kb.internal.cache.Cacheable; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Edge; import javax.annotation.Nullable; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * <p> * Represents An Thing Playing a Role * </p> * * <p> * Wraps the {@link Schema.EdgeLabel#ROLE_PLAYER} {@link Edge} which contains the information unifying an {@link Thing}, * {@link Relationship} and {@link Role}. * </p> * * @author fppt */ public class Casting implements CacheOwner{ private final Set<Cache> registeredCaches = new HashSet<>(); private final EdgeElement edgeElement; private final Cache<Role> cachedRole = Cache.createTxCache(this, Cacheable.concept(), () -> (Role) edge().tx().getSchemaConcept(LabelId.of(edge().property(Schema.EdgeProperty.ROLE_LABEL_ID)))); private final Cache<Thing> cachedInstance = Cache.createTxCache(this, Cacheable.concept(), () -> edge().tx().factory().<Thing>buildConcept(edge().target())); private final Cache<Relationship> cachedRelationship = Cache.createTxCache(this, Cacheable.concept(), () -> edge().tx().factory().<Thing>buildConcept(edge().source())); private final Cache<RelationshipType> cachedRelationshipType = Cache.createTxCache(this, Cacheable.concept(), () -> { if(cachedRelationship.isPresent()){ return cachedRelationship.get().type(); } else { return (RelationshipType) edge().tx().getSchemaConcept(LabelId.of(edge().property(Schema.EdgeProperty.RELATIONSHIP_TYPE_LABEL_ID))); } }); private Casting(EdgeElement edgeElement, @Nullable Relationship relationship, @Nullable Role role, @Nullable Thing thing){ this.edgeElement = edgeElement; if(relationship != null) this.cachedRelationship.set(relationship); if(role != null) this.cachedRole.set(role); if(thing != null) this.cachedInstance.set(thing); } public static Casting create(EdgeElement edgeElement, Relationship relationship, Role role, Thing thing) { return new Casting(edgeElement, relationship, role, thing); } public static Casting withThing(EdgeElement edgeElement, Thing thing){ return new Casting(edgeElement, null, null, thing); } public static Casting withRelationship(EdgeElement edgeElement, Relationship relationship) { return new Casting(edgeElement, relationship, null, null); } private EdgeElement edge(){ return edgeElement; } @Override public Collection<Cache> caches(){ return registeredCaches; } /** * * @return The {@link Role} the {@link Thing} is playing */ public Role getRole(){ return cachedRole.get(); } /** * * @return The {@link RelationshipType} the {@link Thing} is taking part in */ public RelationshipType getRelationshipType(){ return cachedRelationshipType.get(); } /** * * @return The {@link Relationship} which is linking the {@link Role} and the instance */ public Relationship getRelationship(){ return cachedRelationship.get(); } /** * * @return The {@link Thing} playing the {@link Role} */ public Thing getRolePlayer(){ return cachedInstance.get(); } /** * * @return The hash code of the underlying vertex */ public int hashCode() { return edge().id().hashCode(); } /** * Deletes this {@link Casting} effectively removing a {@link Thing} from playing a {@link Role} in a {@link Relationship} */ public void delete(){ edge().delete(); } /** * * @return true if the elements equal each other */ @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Casting casting = (Casting) object; return edge().id().equals(casting.edge().id()); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/structure/EdgeElement.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.structure; import ai.grakn.GraknTx; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Edge; /** * <p> * Represent an {@link Edge} in a {@link GraknTx} * </p> * * <p> * Wraps a tinkerpop {@link Edge} constraining it to the Grakn Object Model. * </p> * * @author fppt */ public class EdgeElement extends AbstractElement<Edge, Schema.EdgeProperty> { public EdgeElement(EmbeddedGraknTx graknGraph, Edge e){ super(graknGraph, e, Schema.PREFIX_EDGE); } /** * Deletes the edge between two concepts and adds both those concepts for re-validation in case something goes wrong */ public void delete(){ element().remove(); } @Override public int hashCode() { return element().hashCode(); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; EdgeElement edge = (EdgeElement) object; return element().id().equals(edge.id()); } public VertexElement source(){ return tx().factory().buildVertexElement(element().outVertex()); } public VertexElement target(){ return tx().factory().buildVertexElement(element().inVertex()); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/structure/ElementId.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.structure; import ai.grakn.GraknTx; import javax.annotation.CheckReturnValue; import java.io.Serializable; /** * <p> * A Concept Id * </p> * * <p> * A class which represents an id of any {@link AbstractElement} in the {@link GraknTx}. * Also contains a static method for producing {@link AbstractElement} IDs from Strings. * </p> * * @author fppt */ public class ElementId implements Serializable { private static final long serialVersionUID = 6688475951939464790L; private final String elementId; private int hashCode = 0; private ElementId(String conceptId){ this.elementId = conceptId; } @CheckReturnValue public String getValue(){ return elementId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ElementId cast = (ElementId) o; return elementId.equals(cast.elementId); } @Override public int hashCode() { if (hashCode == 0 ){ hashCode = elementId.hashCode(); } return hashCode; } @Override public String toString(){ return getValue(); } /** * * @param value The string which potentially represents a Concept * @return The matching concept ID */ @CheckReturnValue public static ElementId of(String value){ return new ElementId(value); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/structure/Shard.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.structure; import ai.grakn.concept.Thing; import ai.grakn.kb.internal.concept.ConceptImpl; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.structure.Direction; import java.util.stream.Stream; /** * <p> * Represent a Shard of a concept * </p> * * <p> * Wraps a {@link VertexElement} which is a shard of a {@link ai.grakn.concept.Concept}. * This is used to break supernodes apart. For example the instances of a {@link ai.grakn.concept.Type} are * spread across several shards. * </p> * * @author fppt */ public class Shard { private final VertexElement vertexElement; public Shard(ConceptImpl owner, VertexElement vertexElement){ this(vertexElement); owner(owner); } public Shard(VertexElement vertexElement){ this.vertexElement = vertexElement; } public VertexElement vertex(){ return vertexElement; } /** * * @return The id of this shard. Strings are used because shards are looked up via the string index. */ public String id(){ return vertex().property(Schema.VertexProperty.ID); } /** * * @param owner Sets the owner of this shard */ private void owner(ConceptImpl owner){ vertex().putEdge(owner.vertex(), Schema.EdgeLabel.SHARD); } /** * Links a new concept to this shard. * * @param concept The concept to link to this shard */ public void link(ConceptImpl concept){ concept.vertex().addEdge(vertex(), Schema.EdgeLabel.ISA); } /** * * @return All the concept linked to this shard */ public <V extends Thing> Stream<V> links(){ return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.ISA). map(EdgeElement::source). map(vertexElement -> vertex().tx().factory().<V>buildConcept(vertexElement)); } /** * * @return The hash code of the underlying vertex */ public int hashCode() { return id().hashCode(); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Shard shard = (Shard) object; //based on id because vertex comparisons are equivalent return id().equals(shard.id()); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/structure/VertexElement.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.kb.internal.structure; import ai.grakn.GraknTx; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.Arrays; import java.util.Iterator; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * <p> * Represent a {@link Vertex} in a {@link GraknTx} * </p> * * <p> * Wraps a tinkerpop {@link Vertex} constraining it to the Grakn Object Model. * This is used to wrap common functionality between exposed {@link ai.grakn.concept.Concept} and unexposed * internal vertices. * </p> * * @author fppt */ public class VertexElement extends AbstractElement<Vertex, Schema.VertexProperty> { public VertexElement(EmbeddedGraknTx graknTx, Vertex element) { super(graknTx, element, Schema.PREFIX_VERTEX); } /** * * @param direction The direction of the edges to retrieve * @param label The type of the edges to retrieve * @return A collection of edges from this concept in a particular direction of a specific type */ public Stream<EdgeElement> getEdgesOfType(Direction direction, Schema.EdgeLabel label){ Iterable<Edge> iterable = () -> element().edges(direction, label.getLabel()); return StreamSupport.stream(iterable.spliterator(), false). map(edge -> tx().factory().buildEdgeElement(edge)); } /** * * @param to the target {@link VertexElement} * @param type the type of the edge to create * @return The edge created */ public EdgeElement addEdge(VertexElement to, Schema.EdgeLabel type) { tx().txCache().writeOccurred(); return tx().factory().buildEdgeElement(element().addEdge(type.getLabel(), to.element())); } /** * @param to the target {@link VertexElement} * @param type the type of the edge to create */ public EdgeElement putEdge(VertexElement to, Schema.EdgeLabel type){ GraphTraversal<Vertex, Edge> traversal = tx().getTinkerTraversal().V(). has(Schema.VertexProperty.ID.name(), id().getValue()). outE(type.getLabel()).as("edge").otherV(). has(Schema.VertexProperty.ID.name(), to.id().getValue()).select("edge"); if(!traversal.hasNext()) { return addEdge(to, type); } else { return tx().factory().buildEdgeElement(traversal.next()); } } /** * Deletes all the edges of a specific {@link Schema.EdgeLabel} to or from a specific set of targets. * If no targets are provided then all the edges of the specified type are deleted * * @param direction The direction of the edges to delete * @param label The edge label to delete * @param targets An optional set of targets to delete edges from */ public void deleteEdge(Direction direction, Schema.EdgeLabel label, VertexElement... targets){ Iterator<Edge> edges = element().edges(direction, label.getLabel()); if(targets.length == 0){ edges.forEachRemaining(Edge::remove); } else { Set<Vertex> verticesToDelete = Arrays.stream(targets).map(AbstractElement::element).collect(Collectors.toSet()); edges.forEachRemaining(edge -> { boolean delete = false; switch (direction){ case BOTH: delete = verticesToDelete.contains(edge.inVertex()) || verticesToDelete.contains(edge.outVertex()); break; case IN: delete = verticesToDelete.contains(edge.outVertex()); break; case OUT: delete = verticesToDelete.contains(edge.inVertex()); break; } if(delete) edge.remove(); }); } } @Override public String toString(){ StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Vertex [").append(id()).append("] /n"); element().properties().forEachRemaining( p -> stringBuilder.append("Property [").append(p.key()).append("] value [").append(p.value()).append("] /n")); return stringBuilder.toString(); } }
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/kb/internal/structure/package-info.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * Internal implementation of structures embedded in a {@link ai.grakn.GraknTx}. */ package ai.grakn.kb.internal.structure;
0
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-kb/1.4.3/ai/grakn/keyspace/KeyspaceStoreImpl.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.keyspace; import ai.grakn.GraknTx; import ai.grakn.GraknTxType; import ai.grakn.Keyspace; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.Thing; import ai.grakn.engine.GraknConfig; import ai.grakn.engine.KeyspaceStore; import ai.grakn.exception.GraknBackendException; import ai.grakn.exception.InvalidKBException; import ai.grakn.factory.EmbeddedGraknSession; import ai.grakn.factory.GraknTxFactoryBuilder; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.ErrorMessage; import com.google.common.base.Stopwatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** * Default implementation of {@link KeyspaceStore} that uses an {@link EmbeddedGraknSession} to access a knowledge * base and store keyspace information. * * @author Felix Chapman */ public class KeyspaceStoreImpl implements KeyspaceStore { private static final Label KEYSPACE_ENTITY = Label.of("keyspace"); private final static Keyspace SYSTEM_KB_KEYSPACE = Keyspace.of("graknsystem"); private static final Logger LOG = LoggerFactory.getLogger(KeyspaceStore.class); private final Set<Keyspace> existingKeyspaces; private final EmbeddedGraknSession systemKeyspaceSession; private final GraknConfig config; public KeyspaceStoreImpl(GraknConfig config){ this.config = config; this.systemKeyspaceSession = EmbeddedGraknSession.createEngineSession(SYSTEM_KB_KEYSPACE, config, GraknTxFactoryBuilder.getInstance()); this.existingKeyspaces = ConcurrentHashMap.newKeySet(); } /** * Logs a new {@link Keyspace} to the {@link KeyspaceStore}. * * @param keyspace The new {@link Keyspace} we have just created */ @Override public void addKeyspace(Keyspace keyspace){ if(containsKeyspace(keyspace)) return; try (EmbeddedGraknTx<?> tx = systemKeyspaceSession.transaction(GraknTxType.WRITE)) { AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE); if (keyspaceName == null) { throw GraknBackendException.initializationException(keyspace); } Attribute<String> attribute = keyspaceName.create(keyspace.getValue()); if (attribute.owner() == null) { tx.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).create().has(attribute); } tx.commit(); // add to cache existingKeyspaces.add(keyspace); } catch (InvalidKBException e) { throw new RuntimeException("Could not add keyspace [" + keyspace + "] to system graph", e); } } @Override public void closeStore() { this.systemKeyspaceSession.close(); } @Override public boolean containsKeyspace(Keyspace keyspace){ //Check the local cache to see which keyspaces we already have open if(existingKeyspaces.contains(keyspace)){ return true; } try (GraknTx tx = systemKeyspaceSession.transaction(GraknTxType.READ)) { boolean keyspaceExists = (tx.getAttributeType(KEYSPACE_RESOURCE.getValue()).attribute(keyspace) != null); if(keyspaceExists) existingKeyspaces.add(keyspace); return keyspaceExists; } } @Override public boolean deleteKeyspace(Keyspace keyspace){ if(keyspace.equals(SYSTEM_KB_KEYSPACE)){ return false; } EmbeddedGraknSession session = EmbeddedGraknSession.createEngineSession(keyspace, config); session.close(); try(EmbeddedGraknTx tx = session.transaction(GraknTxType.WRITE)){ tx.closeSession(); tx.clearGraph(); tx.txCache().closeTx(ErrorMessage.CLOSED_CLEAR.getMessage()); } return deleteReferenceInSystemKeyspace(keyspace); } private boolean deleteReferenceInSystemKeyspace(Keyspace keyspace){ try (EmbeddedGraknTx<?> tx = systemKeyspaceSession.transaction(GraknTxType.WRITE)) { AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE); Attribute<String> attribute = keyspaceName.attribute(keyspace.getValue()); if(attribute == null) return false; Thing thing = attribute.owner(); if(thing != null) thing.delete(); attribute.delete(); existingKeyspaces.remove(keyspace); tx.commit(); } return true; } @Override public Set<Keyspace> keyspaces() { try (GraknTx graph = systemKeyspaceSession.transaction(GraknTxType.WRITE)) { AttributeType<String> keyspaceName = graph.getSchemaConcept(KEYSPACE_RESOURCE); return graph.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).instances() .flatMap(keyspace -> keyspace.attributes(keyspaceName)) .map(name -> (String) name.value()) .map(Keyspace::of) .collect(Collectors.toSet()); } } @Override public void loadSystemSchema() { Stopwatch timer = Stopwatch.createStarted(); try (EmbeddedGraknTx<?> tx = systemKeyspaceSession.transaction(GraknTxType.WRITE)) { if (tx.getSchemaConcept(KEYSPACE_ENTITY) != null) { return; } LOG.info("Loading schema"); loadSystemSchema(tx); tx.commit(); LOG.info("Loaded system schema to system keyspace. Took: {}", timer.stop()); } catch (RuntimeException e) { LOG.error("Error while loading system schema in {}. The error was: {}", timer.stop(), e.getMessage(), e); throw e; } } /** * Loads the system schema inside the provided {@link GraknTx}. * * @param tx The tx to contain the system schema */ private void loadSystemSchema(GraknTx tx){ //Keyspace data AttributeType<String> keyspaceName = tx.putAttributeType("keyspace-name", AttributeType.DataType.STRING); tx.putEntityType("keyspace").key(keyspaceName); } }
0
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule/GraknModule.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graknmodule; import ai.grakn.graknmodule.http.HttpEndpoint; import ai.grakn.graknmodule.http.HttpBeforeFilter; import java.util.List; /** * An interface for author who wants to implement a Grakn module * * @author Ganeshwara Herawan Hananda */ public interface GraknModule { /** * This method must return the ID of the Grakn Module * @return the ID of the Grakn Module */ String getGraknModuleName(); /** * This method should return the list of {@link HttpBeforeFilter} objects, which are to be applied to Grakn HTTP endpoints * @return list of {@link HttpBeforeFilter} */ List<HttpBeforeFilter> getHttpBeforeFilters(); /** * This method should return the list of {@link HttpEndpoint} objects * @return list of {@link HttpEndpoint} object */ List<HttpEndpoint> getHttpEndpoints(); }
0
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule/http/HttpBeforeFilter.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graknmodule.http; /** * A class representing an HTTP endpoint before filter, supported by a {@link ai.grakn.graknmodule.GraknModule} * * @author Ganeshwara Herawan Hananda */ public interface HttpBeforeFilter { /** * @return the URL pattern of which this HttpBeforeFilter will be applied on */ String getUrlPattern(); /** * The filter which will be applied to the endpoints * @param Http request object * @return {@link HttpBeforeFilterResult} object indicating whether the request should be allowed or denied */ HttpBeforeFilterResult getHttpBeforeFilter(HttpRequest request); }
0
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule/http/HttpBeforeFilterResult.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graknmodule.http; import java.util.Optional; /** * A class representing the result of a {@link HttpBeforeFilter}. * * @author Ganeshwara Herawan Hananda */ public class HttpBeforeFilterResult { /** * Returns a representation indicating that the request is allowed to pass through */ public static HttpBeforeFilterResult allowRequest() { return new HttpBeforeFilterResult(); } /** * Returns a representation indicating that the request is denied */ public static HttpBeforeFilterResult denyRequest(HttpResponse response) { return new HttpBeforeFilterResult(response); } /** * Returns an {@link Optional} containing a {@link HttpResponse} object to be sent in case the request is denied */ public Optional<HttpResponse> getResponseIfDenied() { return responseIfDenied; } private HttpBeforeFilterResult(HttpResponse responseIfDenied) { this.responseIfDenied = Optional.of(responseIfDenied); } private HttpBeforeFilterResult() { this.responseIfDenied = Optional.empty(); } private final Optional<HttpResponse> responseIfDenied; }
0
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule/http/HttpEndpoint.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graknmodule.http; /** * A class representing an HTTP endpoint supported by a {@link ai.grakn.graknmodule.GraknModule} * * @author Ganeshwara Herawan Hananda */ public interface HttpEndpoint { /** * Specifies the HTTP method supported by this endpoint * @return A {@link ai.grakn.graknmodule.http.HttpMethods.HTTP_METHOD} */ HttpMethods.HTTP_METHOD getHttpMethod(); /** * The URL for this endpoint * @return The endpoint's URL */ String getEndpoint(); /** * The request handler for this endpoint * @return A {@link HttpResponse} */ HttpResponse getRequestHandler(HttpRequest request); }
0
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule/http/HttpMethods.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graknmodule.http; /** * A class containing a list of HTTP methods supported by {@link HttpRequest} * * @author Ganeshwara Herawan Hananda */ public class HttpMethods { /** * List of HTTP methods supported by {@link HttpRequest} */ public enum HTTP_METHOD { GET, POST, PUT, DELETE } }
0
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule/http/HttpRequest.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graknmodule.http; import java.util.Map; /** * A class representing an HTTP request * * @author Ganeshwara Herawan Hananda */ public class HttpRequest { private final Map<String, String> headers; private final Map<String, String> queryParameters; private final String requestBody; public HttpRequest(Map<String, String> headers, Map<String, String> queryParameters, String requestBody) { this.headers = headers; this.queryParameters = queryParameters; this.requestBody = requestBody; } /** * Returns the HTTP headers as a {@link Map} * @return HTTP headers */ public Map<String, String> getHeaders() { return headers; } /** * Returns the query parameters as a {@link Map} * @return HTTP query parameters */ public Map<String, String> getQueryParameters() { return queryParameters; } /** * Returns the request body * @return HTTP request body */ public String getRequestBody() { return requestBody; } }
0
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule
java-sources/ai/grakn/grakn-module-sdk/1.0.0/ai/grakn/graknmodule/http/HttpResponse.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. * */ package ai.grakn.graknmodule.http; /** * A class representing an HTTP response * * @author Ganeshwara Herawan Hananda */ public class HttpResponse { public HttpResponse(int statusCode, String body) { this.statusCode = statusCode; this.body = body; } /** * Get the HTTP response status code * @return HTTP response status code */ public int getStatusCode() { return statusCode; } /** * Get the body out of the HTTP response * @return HTTP response body */ public String getBody() { return body; } private final int statusCode; private final String body; }
0
java-sources/ai/grakn/grakn-orientdb-factory/0.10.0/ai/grakn
java-sources/ai/grakn/grakn-orientdb-factory/0.10.0/ai/grakn/factory/OrientDBInternalFactory.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.factory; import ai.grakn.Grakn; import ai.grakn.exception.GraphRuntimeException; import ai.grakn.graph.internal.GraknOrientDBGraph; import ai.grakn.util.ErrorMessage; import ai.grakn.util.Schema; import com.orientechnologies.orient.core.metadata.schema.OImmutableClass; import com.orientechnologies.orient.core.metadata.schema.OType; import org.apache.commons.configuration.BaseConfiguration; import org.apache.tinkerpop.gremlin.orientdb.OrientGraph; import org.apache.tinkerpop.gremlin.orientdb.OrientGraphFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.Set; import static ai.grakn.util.ErrorMessage.INVALID_DATATYPE; public class OrientDBInternalFactory extends AbstractInternalFactory<GraknOrientDBGraph, OrientGraph> { private final Logger LOG = LoggerFactory.getLogger(OrientDBInternalFactory.class); private final Map<String, OrientGraphFactory> openFactories; public OrientDBInternalFactory(String keyspace, String engineUrl, Properties properties) { super(keyspace, engineUrl, properties); openFactories = new HashMap<>(); } @Override boolean isClosed(OrientGraph innerGraph) { return innerGraph.isClosed(); } @Override GraknOrientDBGraph buildGraknGraphFromTinker(OrientGraph graph, boolean batchLoading) { return new GraknOrientDBGraph(graph, super.keyspace, super.engineUrl, batchLoading); } @Override OrientGraph buildTinkerPopGraph(boolean batchLoading) { LOG.warn(ErrorMessage.CONFIG_IGNORED.getMessage("properties", properties)); return configureGraph(super.keyspace, super.engineUrl); } private OrientGraph configureGraph(String name, String address){ boolean schemaDefinitionRequired = false; OrientGraphFactory factory = getFactory(name, address); OrientGraph graph = factory.getNoTx(); //Check if the schema has been created for (Schema.BaseType baseType : Schema.BaseType.values()) { try { graph.database().browseClass(OImmutableClass.VERTEX_CLASS_NAME + "_" + baseType); } catch (IllegalArgumentException e){ schemaDefinitionRequired = true; break; } } //Create the schema if needed if(schemaDefinitionRequired){ graph = createGraphWithSchema(factory, graph); } return graph; } private OrientGraph createGraphWithSchema(OrientGraphFactory factory, OrientGraph graph){ for (Schema.BaseType baseType : Schema.BaseType.values()) { graph.createVertexClass(baseType.name()); } for (Schema.EdgeLabel edgeLabel : Schema.EdgeLabel.values()) { graph.createEdgeClass(edgeLabel.name()); } graph = createIndicesVertex(graph); graph.commit(); return factory.getNoTx(); } private OrientGraph createIndicesVertex(OrientGraph graph){ ResourceBundle keys = ResourceBundle.getBundle("indices-vertices"); Set<String> labels = keys.keySet(); for (String label : labels) { String [] configs = keys.getString(label).split(","); for (String propertyConfig : configs) { String[] propertyConfigs = propertyConfig.split(":"); Schema.ConceptProperty property = Schema.ConceptProperty.valueOf(propertyConfigs[0]); boolean isUnique = Boolean.parseBoolean(propertyConfigs[1]); OType orientDataType = getOrientDataType(property); BaseConfiguration indexConfig = new BaseConfiguration(); indexConfig.setProperty("keytype", orientDataType); //TODO: Figure out why this is not working when the Orient Guys say it should //indexConfig.setProperty("metadata.ignoreNullValues", true); if(isUnique){ indexConfig.setProperty("type", "UNIQUE"); } if(!graph.getVertexIndexedKeys(label).contains(property.name())) { graph.createVertexIndex(property.name(), label, indexConfig); } } } return graph; } private OType getOrientDataType(Schema.ConceptProperty property){ Class propertyDataType = property.getDataType(); if(propertyDataType.equals(String.class)){ return OType.STRING; } else if(propertyDataType.equals(Long.class)){ return OType.LONG; } else if(propertyDataType.equals(Double.class)){ return OType.DOUBLE; } else if(propertyDataType.equals(Boolean.class)){ return OType.BOOLEAN; } else { String options = String.class.getName() + ", " + Long.class.getName() + ", " + Double.class.getName() + ", or " + Boolean.class.getName(); throw new GraphRuntimeException(INVALID_DATATYPE.getMessage(propertyDataType.getName(), options)); } } private OrientGraphFactory getFactory(String name, String address){ if (Grakn.IN_MEMORY.equals(address)){ address = "memory"; //name = "/tmp/" + name; } String key = name + address; if(!openFactories.containsKey(key)){ openFactories.put(key, new OrientGraphFactory(address + ":" + name)); } return openFactories.get(key); } }
0
java-sources/ai/grakn/grakn-orientdb-factory/0.10.0/ai/grakn/graph
java-sources/ai/grakn/grakn-orientdb-factory/0.10.0/ai/grakn/graph/internal/GraknOrientDBGraph.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.graph.internal; import ai.grakn.util.ErrorMessage; import ai.grakn.util.Schema; import org.apache.tinkerpop.gremlin.orientdb.OrientGraph; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; import org.apache.tinkerpop.gremlin.structure.Vertex; public class GraknOrientDBGraph extends AbstractGraknGraph<OrientGraph> { public GraknOrientDBGraph(OrientGraph graph, String name, String engineUrl, boolean batchLoading){ super(graph, name, engineUrl, batchLoading); } @Override protected void commitTx(){ getTinkerPopGraph().commit(); } @Override public GraphTraversal<Vertex, Vertex> getTinkerTraversal(){ Schema.BaseType[] baseTypes = Schema.BaseType.values(); String [] labels = new String [baseTypes.length]; for(int i = 0; i < labels.length; i ++){ labels[i] = baseTypes[i].name(); } return getTinkerPopGraph().traversal().withStrategies(ReadOnlyStrategy.instance()).V().hasLabel(labels); } @Override public void rollback(){ throw new UnsupportedOperationException(ErrorMessage.UNSUPPORTED_GRAPH.getMessage(getTinkerPopGraph().getClass().getName(), "rollback")); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/engine/KeyspaceStoreFake.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.engine; import ai.grakn.Keyspace; import com.google.common.collect.Sets; import java.util.Set; /** * A fake {@link KeyspaceStore} implementation, that follows the correct contract, but operates without a real * knowledge base. * * @author Felix Chapman */ public class KeyspaceStoreFake implements KeyspaceStore { private Set<Keyspace> keyspaces; private KeyspaceStoreFake(Set<Keyspace> keyspaces) { this.keyspaces = keyspaces; } public static KeyspaceStoreFake of(Keyspace... keyspaces) { return new KeyspaceStoreFake(Sets.newHashSet(keyspaces)); } @Override public boolean containsKeyspace(Keyspace keyspace) { return keyspaces.contains(keyspace); } @Override public boolean deleteKeyspace(Keyspace keyspace) { return keyspaces.remove(keyspace); } @Override public Set<Keyspace> keyspaces() { return Sets.newHashSet(keyspaces); } @Override public void loadSystemSchema() { } @Override public void addKeyspace(Keyspace keyspace) { keyspaces.add(keyspace); } @Override public void closeStore() { } public void clear() { keyspaces.clear(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/AbstractGenerator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import java.util.Collection; import java.util.List; import java.util.Set; /** * Abstract class for generating test objects that handles some boilerplate. * * <p> * New generators should extend this class and implement {@link #generate()}. * </p> * * @param <T> the type to generate * * @author Felix Chapman */ public abstract class AbstractGenerator<T> extends Generator<T> { SourceOfRandomness random; GenerationStatus status; AbstractGenerator(Class<T> type) { super(type); } @Override public T generate(SourceOfRandomness random, GenerationStatus status) { this.random = random; this.status = status; return generate(); } protected abstract T generate(); final <S> S gen(Class<S> clazz) { return gen().type(clazz).generate(random, status); } protected <S> Set<S> setOf(Class<S> clazz, int minSize, int maxSize) { return fillWith(Sets.newHashSet(), clazz, minSize, maxSize); } protected <S> List<S> listOf(Class<S> clazz, int minSize, int maxSize) { return fillWith(Lists.newArrayList(), clazz, minSize, maxSize); } private <S, U extends Collection<S>> U fillWith(U collection, Class<S> clazz, int minSize, int maxSize) { for (int i = 0; i < random.nextInt(minSize, maxSize); i ++) { collection.add(gen(clazz)); } return collection; } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/AbstractSchemaConceptGenerator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Label; import ai.grakn.concept.SchemaConcept; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.pholser.junit.quickcheck.generator.GeneratorConfiguration; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Collection; import java.util.Optional; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.util.stream.Collectors.toSet; /** * Abstract class for generating {@link SchemaConcept}s. * * @param <T> the kind of {@link SchemaConcept} to generate * * @author Felix Chapman */ @SuppressWarnings("unused") public abstract class AbstractSchemaConceptGenerator<T extends SchemaConcept> extends FromTxGenerator<T> { private Optional<Boolean> meta = Optional.empty(); AbstractSchemaConceptGenerator(Class<T> type) { super(type); } @Override protected final T generateFromTx() { Collection<T> schemaConcepts; if (!includeNonMeta()) { schemaConcepts = Sets.newHashSet(otherMetaSchemaConcepts()); schemaConcepts.add(metaSchemaConcept()); } else { schemaConcepts = (Collection<T>) metaSchemaConcept().subs().collect(toSet()); } schemaConcepts = schemaConcepts.stream().filter(this::filter).collect(toSet()); if (!includeMeta()) { schemaConcepts.remove(metaSchemaConcept()); schemaConcepts.removeAll(otherMetaSchemaConcepts()); } if (schemaConcepts.isEmpty() && includeNonMeta()) { Label label = genFromTx(Labels.class).mustBeUnused().generate(random, status); assert tx().getSchemaConcept(label) == null; return newSchemaConcept(label); } else { return random.choose(schemaConcepts); } } protected abstract T newSchemaConcept(Label label); protected abstract T metaSchemaConcept(); protected Collection<T> otherMetaSchemaConcepts() { return ImmutableSet.of(); } protected boolean filter(T schemaConcept) { return true; } private final boolean includeMeta() { return meta.orElse(true); } private final boolean includeNonMeta() { return !meta.orElse(false); } final AbstractSchemaConceptGenerator<T> excludeMeta() { meta = Optional.of(false); return this; } public final void configure(@SuppressWarnings("unused") Meta meta) { Preconditions.checkArgument( !this.meta.isPresent() || this.meta.get(), "Cannot specify parameter is both meta and non-meta"); this.meta = Optional.of(true); } public final void configure(@SuppressWarnings("unused") NonMeta nonMeta) { Preconditions.checkArgument( !this.meta.isPresent() || !this.meta.get(), "Cannot specify parameter is both meta and non-meta"); this.meta = Optional.of(false); } /** * Specify whether the generated {@link SchemaConcept} should be a meta concept */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface Meta { } /** * Specify whether the generated {@link SchemaConcept} should not be a meta concept */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface NonMeta { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/AbstractThingGenerator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Label; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.generator.AbstractSchemaConceptGenerator.NonMeta; import com.pholser.junit.quickcheck.generator.GeneratorConfiguration; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Collection; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.util.stream.Collectors.toSet; /** * Abstract class for generating {@link Thing}s. * * @param <T> The kind of {@link Thing} to generate. * @param <S> The {@link Type} of the {@link Thing} being generated. * * @author Felix Chapman */ public abstract class AbstractThingGenerator<T extends Thing, S extends Type> extends FromTxGenerator<T> { private boolean withResource = false; private final Class<? extends AbstractTypeGenerator<S>> generatorClass; AbstractThingGenerator(Class<T> type, Class<? extends AbstractTypeGenerator<S>> generatorClass) { super(type); this.generatorClass = generatorClass; } @Override protected final T generateFromTx() { T thing; S type = genFromTx(generatorClass).makeExcludeAbstractTypes().excludeMeta().generate(random, status); //noinspection unchecked Collection<T> instances = (Collection<T> ) type.instances().collect(toSet()); if (instances.isEmpty()) { thing = newInstance(type); } else { thing = random.choose(instances); } if(withResource && !thing.attributes().findAny().isPresent()){ //A new attribute type is created every time a attribute is lacking. //Existing attribute types and resources of those types are not used because we end up mutating the // the schema in strange ways. This approach is less complex but ensures everything has a attribute // without conflicting with the schema //Create a new attribute type AttributeType.DataType<?> dataType = gen(AttributeType.DataType.class); Label label = genFromTx(Labels.class).mustBeUnused().generate(random, status); AttributeType attributeType = tx().putAttributeType(label, dataType); //Create new attribute Attribute attribute = newResource(attributeType); //Link everything together type.has(attributeType); thing.has(attribute); } return thing; } protected Attribute newResource(AttributeType type) { AttributeType.DataType<?> dataType = type.dataType(); Object value = gen().make(ResourceValues.class).dataType(dataType).generate(random, status); return type.create(value); } @SuppressWarnings("unused") /**Used through annotation {@link NonMeta}*/ public final void configure(@SuppressWarnings("unused") NonMeta nonMeta) { } @SuppressWarnings("unused") /**Used through annotation {@link WithResource}*/ public final void configure(@SuppressWarnings("unused") WithResource withResource) { this.withResource = true; } protected abstract T newInstance(S type); /** * Specify if the generated {@link Thing} should be connected to a {@link Attribute} */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface WithResource { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/AbstractTypeGenerator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Type; import com.google.common.base.Preconditions; import com.pholser.junit.quickcheck.generator.GeneratorConfiguration; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Optional; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Abstract class for generating {@link Type}s. * * @param <T> the kind of {@link Type} to generate * * @author Felix Chapman */ public abstract class AbstractTypeGenerator<T extends Type> extends AbstractSchemaConceptGenerator<T> { private Optional<Boolean> includeAbstract = Optional.empty(); AbstractTypeGenerator(Class<T> type) { super(type); } private boolean willIncludeAbstractTypes(){ return includeAbstract.orElse(true); } final AbstractSchemaConceptGenerator<T> makeExcludeAbstractTypes() { includeAbstract = Optional.of(false); return this; } @SuppressWarnings("unused") /**Used through annotation {@link Abstract}*/ public final void configure(@SuppressWarnings("unused") Abstract abstract_) { Preconditions.checkArgument( !this.includeAbstract.isPresent() || this.includeAbstract.get(), "Cannot specify parameter is both abstract and non-abstract" ); this.includeAbstract = Optional.of(true); } @SuppressWarnings("unused") /**Used through annotation {@link Abstract}*/ public final void configure(@SuppressWarnings("unused") NonAbstract nonAbstract) { Preconditions.checkArgument( !this.includeAbstract.isPresent() || !this.includeAbstract.get(), "Cannot specify parameter is both abstract and non-abstract" ); this.includeAbstract = Optional.of(false); } @Override protected final boolean filter(T schemaConcept) { return willIncludeAbstractTypes() || !schemaConcept.isAbstract(); } /** * Specify that the generated {@link Type} should be abstract */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface Abstract { } /** * Specify that the generated {@link Type} should not be abstract */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface NonAbstract { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/ConceptIds.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.ConceptId; /** * Generator that generates totally random concept IDs * * @author Felix Chapman */ public class ConceptIds extends AbstractGenerator<ConceptId> { public ConceptIds() { super(ConceptId.class); } @Override public ConceptId generate() { return ConceptId.of(gen(String.class)); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/DataTypes.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.AttributeType; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.generator.Generator; import com.pholser.junit.quickcheck.random.SourceOfRandomness; /** * Generator that produces random valid resource data types. * * @author Felix Chapman */ public class DataTypes extends Generator<AttributeType.DataType> { public DataTypes() { super(AttributeType.DataType.class); } @Override public AttributeType.DataType generate(SourceOfRandomness random, GenerationStatus status) { return random.choose(AttributeType.DataType.SUPPORTED_TYPES.values()); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/Entities.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Entity; import ai.grakn.concept.EntityType; /** * Generator that produces {@link Entity}s * * @author Felix Chapman */ public class Entities extends AbstractThingGenerator<Entity, EntityType> { public Entities() { super(Entity.class, EntityTypes.class); } @Override protected Entity newInstance(EntityType type) { return type.create(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/EntityTypes.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; /** * Generator that produces {@link EntityType}s * * @author Felix Chapman */ public class EntityTypes extends AbstractTypeGenerator<EntityType> { public EntityTypes() { super(EntityType.class); } @Override protected EntityType newSchemaConcept(Label label) { return tx().putEntityType(label); } @Override protected EntityType metaSchemaConcept() { return tx().admin().getMetaEntityType(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/FromTxGenerator.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.GraknTx; import com.pholser.junit.quickcheck.generator.GeneratorConfiguration; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.function.Supplier; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Generator for creating things using an existing tx. * * @param <T> the type of thing to generate * * @author Felix Chapman */ public abstract class FromTxGenerator<T> extends AbstractGenerator<T> { private Supplier<GraknTx> txSupplier = () -> gen().make(GraknTxs.class).setOpen(true).generate(random, status); private GraknTx tx; FromTxGenerator(Class<T> type) { super(type); } protected final GraknTx tx() { return tx; } @Override protected final T generate() { tx = txSupplier.get(); return generateFromTx(); } protected abstract T generateFromTx(); protected final <S extends FromTxGenerator<?>> S genFromTx(Class<S> generatorClass) { S generator = gen().make(generatorClass); generator.fromTx(this::tx); return generator; } @SuppressWarnings("unused")/** Used through the {@link FromTx} annotation*/ public final void configure(@SuppressWarnings("unused") FromTx fromTx) { fromLastGeneratedTx(); } final FromTxGenerator<T> fromTx(Supplier<GraknTx> txSupplier) { this.txSupplier = txSupplier; return this; } final FromTxGenerator<T> fromLastGeneratedTx() { fromTx(GraknTxs::lastGeneratedGraph); return this; } /** * Specify that the generated objects should be from the {@link GraknTx} generated in a previous parameter */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface FromTx { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/GraknTxs.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.GraknTx; import ai.grakn.GraknTxType; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.Entity; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.factory.EmbeddedGraknSession; import ai.grakn.kb.internal.EmbeddedGraknTx; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.pholser.junit.quickcheck.MinimalCounterexampleHook; import com.pholser.junit.quickcheck.generator.GeneratorConfiguration; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import static ai.grakn.util.StringUtil.valueToString; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; /** * Generator to create random {@link GraknTx}s. * * <p> * Normally you want the {@link GraknTx} you generate to be open, not already closed. To get an open * {@link GraknTx}, annotate the parameter in your test with {@link Open}. * </p> * * <p> * Additionally, if your property test needs a concept from the {@link GraknTx}, use the annotation * {@link ai.grakn.generator.FromTxGenerator.FromTx}. * </p> * * @author Felix Chapman */ @SuppressWarnings("unchecked") // We're performing random operations. Generics will not constrain us! public class GraknTxs extends AbstractGenerator<GraknTx> implements MinimalCounterexampleHook { private static EmbeddedGraknTx lastGeneratedTx; private static StringBuilder txSummary; private EmbeddedGraknTx tx; private Boolean open = null; public GraknTxs() { super(GraknTx.class); } public static GraknTx lastGeneratedGraph() { return lastGeneratedTx; } /** * Mutate the tx being generated by calling a random method on it. */ private void mutateOnce() { boolean succesfulMutation = false; while (!succesfulMutation) { succesfulMutation = true; try { random.choose(mutators).run(); } catch (UnsupportedOperationException | GraknTxOperationException | KBGeneratorException e) { // We only catch acceptable exceptions for the tx API to throw succesfulMutation = false; } } } @Override public GraknTx generate() { // TODO: Generate more keyspaces // We don't do this now because creating lots of keyspaces seems to slow the system tx String keyspace = gen().make(MetasyntacticStrings.class).generate(random, status); EmbeddedGraknSession factory = EmbeddedGraknSession.inMemory(keyspace); int size = status.size(); startSummary(); txSummary.append("size: ").append(size).append("\n"); closeTx(lastGeneratedTx); // Clear tx before retrieving tx = factory.transaction(GraknTxType.WRITE); tx.clearGraph(); tx.close(); tx = factory.transaction(GraknTxType.WRITE); for (int i = 0; i < size; i++) { mutateOnce(); } // Close transactions randomly, unless parameter is set boolean shouldOpen = open != null ? open : random.nextBoolean(); if (!shouldOpen) tx.close(); setLastGeneratedTx(tx); return tx; } private static void setLastGeneratedTx(EmbeddedGraknTx tx) { lastGeneratedTx = tx; } private void closeTx(GraknTx tx){ if(tx != null && !tx.isClosed()){ tx.close(); } } @SuppressWarnings("unused")/**Used through {@link Open} annotation*/ public void configure(@SuppressWarnings("unused") Open open) { setOpen(open.value()); } public GraknTxs setOpen(boolean open) { this.open = open; return this; } // A list of methods that will mutate the tx in some random way when called private final ImmutableList<Runnable> mutators = ImmutableList.of( () -> { Label label = typeLabel(); EntityType superType = entityType(); EntityType entityType = tx.putEntityType(label).sup(superType); summaryAssign(entityType, "tx", "putEntityType", label); summary(entityType, "superType", superType); }, () -> { Label label = typeLabel(); AttributeType.DataType dataType = gen(AttributeType.DataType.class); AttributeType superType = resourceType(); AttributeType attributeType = tx.putAttributeType(label, dataType).sup(superType); summaryAssign(attributeType, "tx", "putResourceType", label, dataType); summary(attributeType, "superType", superType); }, () -> { Label label = typeLabel(); Role superType = role(); Role role = tx.putRole(label).sup(superType); summaryAssign(role, "tx", "putRole", label); summary(role, "superType", superType); }, () -> { Label label = typeLabel(); RelationshipType superType = relationType(); RelationshipType relationshipType = tx.putRelationshipType(label).sup(superType); summaryAssign(relationshipType, "tx", "putRelationshipType", label); summary(relationshipType, "superType", superType); }, () -> { Type type = type(); Role role = role(); type.plays(role); summary(type, "plays", role); }, () -> { Type type = type(); AttributeType attributeType = resourceType(); type.has(attributeType); summary(type, "resource", attributeType); }, () -> { Type type = type(); AttributeType attributeType = resourceType(); type.key(attributeType); summary(type, "key", attributeType); }, () -> { Type type = type(); boolean isAbstract = random.nextBoolean(); type.isAbstract(isAbstract); summary(type, "isAbstract", isAbstract); }, () -> { EntityType entityType1 = entityType(); EntityType entityType2 = entityType(); entityType1.sup(entityType2); summary(entityType1, "superType", entityType2); }, () -> { EntityType entityType = entityType(); Entity entity = entityType.create(); summaryAssign(entity, entityType, "create"); }, () -> { Role role1 = role(); Role role2 = role(); role1.sup(role2); summary(role1, "superType", role2); }, () -> { RelationshipType relationshipType1 = relationType(); RelationshipType relationshipType2 = relationType(); relationshipType1.sup(relationshipType2); summary(relationshipType1, "superType", relationshipType2); }, () -> { RelationshipType relationshipType = relationType(); Relationship relationship = relationshipType.create(); summaryAssign(relationship, relationshipType, "create"); }, () -> { RelationshipType relationshipType = relationType(); Role role = role(); relationshipType.relates(role); summary(relationshipType, "relates", role); }, () -> { AttributeType attributeType1 = resourceType(); AttributeType attributeType2 = resourceType(); attributeType1.sup(attributeType2); summary(attributeType1, "superType", attributeType2); }, () -> { AttributeType attributeType = resourceType(); Object value = gen().make(ResourceValues.class).generate(random, status); Attribute attribute = attributeType.create(value); summaryAssign(attribute, attributeType, "putResource", valueToString(value)); }, // () -> resourceType().regex(gen(String.class)), // TODO: Enable this when doesn't throw a NPE () -> { Rule rule1 = ruleType(); Rule rule2 = ruleType(); rule1.sup(rule2); summary(rule1, "superType", rule2); }, //TODO: re-enable when grakn-kb can create graql constructs /*() -> { Rule ruleType = ruleType(); Rule rule = ruleType.putRule(graql.parsePattern("$x"), graql.parsePattern("$x"));// TODO: generate more complicated rules summaryAssign(rule, ruleType, "putRule", "var(\"x\")", "var(\"y\")"); },*/ () -> { Thing thing = instance(); Attribute attribute = resource(); thing.has(attribute); summary(thing, "resource", attribute); }, () -> { Relationship relationship = relation(); Role role = role(); Thing thing = instance(); relationship.assign(role, thing); summary(relationship, "assign", role, thing); } ); private static void startSummary() { txSummary = new StringBuilder(); } private void summary(Object target, String methodName, Object... args) { txSummary.append(summaryFormat(target)).append(".").append(methodName).append("("); txSummary.append(Stream.of(args).map(this::summaryFormat).collect(joining(", "))); txSummary.append(");\n"); } private void summaryAssign(Object assign, Object target, String methodName, Object... args) { summary(summaryFormat(assign) + " = " + summaryFormat(target), methodName, args); } private String summaryFormat(Object object) { if (object instanceof SchemaConcept) { return ((SchemaConcept) object).label().getValue().replaceAll("-", "_"); } else if (object instanceof Thing) { Thing thing = (Thing) object; return summaryFormat(thing.type()) + thing.id().getValue(); } else if (object instanceof Label) { return valueToString(((Label) object).getValue()); } else { return object.toString(); } } private Label typeLabel() { return gen().make(Labels.class, gen().make(MetasyntacticStrings.class)).generate(random, status); } private Type type() { Collection<? extends Type> candidates = tx.admin().getMetaConcept().subs().collect(toSet()); return random.choose(candidates); } private EntityType entityType() { return random.choose(tx.admin().getMetaEntityType().subs().collect(toSet())); } private Role role() { return random.choose(tx.admin().getMetaRole().subs().collect(toSet())); } private AttributeType resourceType() { return random.choose((Collection<AttributeType>) tx.admin().getMetaAttributeType().subs().collect(toSet())); } private RelationshipType relationType() { return random.choose(tx.admin().getMetaRelationType().subs().collect(toSet())); } private Rule ruleType() { return random.choose(tx.admin().getMetaRule().subs().collect(toSet())); } private Thing instance() { return chooseOrThrow(allInstancesFrom(tx)); } private Relationship relation() { return chooseOrThrow(tx.admin().getMetaRelationType().instances()); } private Attribute resource() { return chooseOrThrow((Stream<Attribute>) tx.admin().getMetaAttributeType().instances()); } //TODO: re-enable when grakn-kb can create graql constructs // private Rule rule() { // return chooseOrThrow(tx.admin().getMetaRuleType().instances()); // } private <T> T chooseOrThrow(Stream<? extends T> stream) { Set<? extends T> collection = stream.collect(toSet()); if (collection.isEmpty()) { throw new KBGeneratorException(); } else { return random.choose(collection); } } public static List<Concept> allConceptsFrom(GraknTx graph) { List<Concept> concepts = Lists.newArrayList(GraknTxs.allSchemaElementsFrom(graph)); concepts.addAll(allInstancesFrom(graph).collect(toSet())); return concepts; } public static Collection<? extends SchemaConcept> allSchemaElementsFrom(GraknTx graph) { Set<SchemaConcept> allSchemaConcepts = new HashSet<>(); allSchemaConcepts.addAll(graph.admin().getMetaConcept().subs().collect(toSet())); allSchemaConcepts.addAll(graph.admin().getMetaRole().subs().collect(toSet())); allSchemaConcepts.addAll(graph.admin().getMetaRule().subs().collect(toSet())); return allSchemaConcepts; } public static Stream<? extends Thing> allInstancesFrom(GraknTx graph) { return graph.admin().getMetaConcept().instances(); } @Override public void handle(Object[] counterexample, Runnable action) { System.err.println("Graph generated:\n" + txSummary); } /** * Specify whether the generated tx should be open or closed */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface Open { boolean value() default true; } private static class KBGeneratorException extends RuntimeException { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/Labels.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Label; import com.pholser.junit.quickcheck.generator.GeneratorConfiguration; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Generator that generates totally random type names * * @author Felix Chapman */ public class Labels extends FromTxGenerator<Label> { private boolean mustBeUnused = false; public Labels() { super(Label.class); this.fromLastGeneratedTx(); } @Override public Label generateFromTx() { if (mustBeUnused) { Label label; int attempts = 0; do { // After a certain number of attempts, generate truly random strings instead if (attempts < 100) { label = metaSyntacticLabel(); } else { label = trueRandomLabel(); } attempts += 1; } while (tx().getSchemaConcept(label) != null); return label; } else { return metaSyntacticLabel(); } } @SuppressWarnings("unused") /** Used through {@link Unused} annotation*/ public void configure(@SuppressWarnings("unused") Unused unused) { mustBeUnused(); } Labels mustBeUnused() { mustBeUnused = true; return this; } private Label metaSyntacticLabel() { return Label.of(gen().make(MetasyntacticStrings.class).generate(random, status)); } private Label trueRandomLabel() { return Label.of(gen(String.class)); } /** * Specify that the label should be unused in the graph */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface Unused { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/MetaLabels.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Label; import ai.grakn.util.Schema; import com.google.common.collect.ImmutableSet; import java.util.stream.Stream; import static ai.grakn.util.CommonUtil.toImmutableSet; /** * Generator that generates meta type names only * * @author Felix Chapman */ public class MetaLabels extends AbstractGenerator<Label> { private static final ImmutableSet<Label> META_TYPE_LABELS = Stream.of(Schema.MetaSchema.values()).map(Schema.MetaSchema::getLabel).collect(toImmutableSet()); public MetaLabels() { super(Label.class); } @Override public Label generate() { return random.choose(META_TYPE_LABELS); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/MetaTypes.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Type; import ai.grakn.generator.AbstractSchemaConceptGenerator.Meta; /** * This is a generator that just produces the top-level meta-type `thing`. * * Other meta types are still handled from their respective generators, e.g. `EntityTypes` * * @author Felix Chapman */ public class MetaTypes extends FromTxGenerator<Type> { public MetaTypes() { super(Type.class); } @Override protected Type generateFromTx() { return tx().admin().getMetaConcept(); } @SuppressWarnings("unused") /** Used through {@link Meta} annotation*/ public final void configure(@SuppressWarnings("unused") Meta meta) { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/MetasyntacticStrings.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import com.google.common.collect.ImmutableList; /** * Generator for producing a limited set of readable, meaningless strings. * * @author Felix Chapman */ public class MetasyntacticStrings extends AbstractGenerator<String> { public MetasyntacticStrings() { super(String.class); } @Override protected String generate() { return random.choose(ImmutableList.of( "foo", "bar", "baz", "qux", "quux", "corge", "grault", "garply", "waldo", "fred", "plugh", "xyzzy", "thud" )); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/Methods.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import com.pholser.junit.quickcheck.generator.GeneratorConfiguration; import org.mockito.Mockito; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.stream.Stream; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * A generator that produces random {@link Method}s of a given {@link Class} * * @author Felix Chapman */ public class Methods extends AbstractGenerator<Method> { private Class<?> clazz = null; public Methods() { super(Method.class); } @Override protected Method generate() { if (clazz == null) throw new IllegalStateException("Must use annotation MethodOf"); return random.choose(clazz.getMethods()); } @SuppressWarnings("unused") /** Used through {@link MethodOf} annotation*/ public void configure(@SuppressWarnings("unused") MethodOf methodOf) { this.clazz = methodOf.value(); } public static Object[] mockParamsOf(Method method) { return Stream.of(method.getParameters()).map(Parameter::getType).map(Methods::mock).toArray(); } private static <T> T mock(Class<T> clazz) { if (clazz.equals(boolean.class) || clazz.equals(Object.class)) { return (T) Boolean.FALSE; } else if (clazz.equals(String.class)) { return (T) ""; } else { return Mockito.mock(clazz); } } /** * Specify what class to generate methods from */ @Target({PARAMETER, FIELD, ANNOTATION_TYPE, TYPE_USE}) @Retention(RUNTIME) @GeneratorConfiguration public @interface MethodOf { Class<?> value(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/PutSchemaConceptFunctions.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.GraknTx; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Label; import ai.grakn.concept.SchemaConcept; import com.google.common.collect.ImmutableList; import java.util.function.BiFunction; /** * Generator that produces {@link GraknTx} methods that put an {@link SchemaConcept} in the graph, given {@link Label}. * * @author Felix Chapman */ public class PutSchemaConceptFunctions extends AbstractGenerator<BiFunction> { public PutSchemaConceptFunctions() { super(BiFunction.class); } @Override protected BiFunction<GraknTx, Label, SchemaConcept> generate() { return random.choose(ImmutableList.of( GraknTx::putEntityType, (graph, label) -> graph.putAttributeType(label, gen(AttributeType.DataType.class)), GraknTx::putRelationshipType, GraknTx::putRole, //TODO: Make smarter rules (graph, label) -> graph.putRule(label, graph.graql().parser().parsePattern("$x"), graph.graql().parser().parsePattern("$x")) )); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/PutTypeFunctions.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.GraknTx; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Label; import ai.grakn.concept.Type; import com.google.common.collect.ImmutableList; import java.util.function.BiFunction; /** * Generator that produces {@link GraknTx} methods that put a type in the graph, given {@link Label}. * * @author Felix Chapman */ public class PutTypeFunctions extends AbstractGenerator<BiFunction> { public PutTypeFunctions() { super(BiFunction.class); } @Override protected BiFunction<GraknTx, Label, Type> generate() { return random.choose(ImmutableList.of( GraknTx::putEntityType, (graph, label) -> graph.putAttributeType(label, gen(AttributeType.DataType.class)), GraknTx::putRelationshipType )); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/RelationTypes.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Label; /** * A generator that produces {@link RelationshipType}s * * @author Felix Chapman */ public class RelationTypes extends AbstractTypeGenerator<RelationshipType> { public RelationTypes() { super(RelationshipType.class); } @Override protected RelationshipType newSchemaConcept(Label label) { return tx().putRelationshipType(label); } @Override protected RelationshipType metaSchemaConcept() { return tx().admin().getMetaRelationType(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/Relations.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; /** * A generator that produces {@link Relationship}s * * @author Felix Chapman */ public class Relations extends AbstractThingGenerator<Relationship, RelationshipType> { public Relations() { super(Relationship.class, RelationTypes.class); } @Override protected Relationship newInstance(RelationshipType type) { return type.create(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/RelationsFromRolePlayers.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Thing; import java.util.Optional; import java.util.stream.Stream; /** * A generator that produces {@link Relationship}s from existing role-players. * * This means the relation is navigated to from another {@link Thing} attached to it. This will find relations even * if they are not returned by {@link RelationshipType#instances}. * * @author Felix Chapman */ public class RelationsFromRolePlayers extends FromTxGenerator<Relationship> { public RelationsFromRolePlayers() { super(Relationship.class); } @Override protected Relationship generateFromTx() { Stream<? extends Thing> things = tx().admin().getMetaConcept().instances(); Optional<Relationship> relation = things.flatMap(thing -> thing.relationships()).findAny(); if (relation.isPresent()) { return relation.get(); } else { // Give up and fall back to normal generator return genFromTx(Relations.class).generate(random, status); } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/ResourceTypes.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Label; /** * A generator that produces {@link AttributeType}s * * @author Felix Chapman */ public class ResourceTypes extends AbstractTypeGenerator<AttributeType> { public ResourceTypes() { super(AttributeType.class); } @Override protected AttributeType newSchemaConcept(Label label) { AttributeType.DataType<?> dataType = gen(AttributeType.DataType.class); return tx().putAttributeType(label, dataType); } @Override protected AttributeType metaSchemaConcept() { return tx().admin().getMetaAttributeType(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/ResourceValues.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.AttributeType; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; /** * Generator that generates random valid resource values. * * @author Felix Chapman */ public class ResourceValues extends AbstractGenerator<Object> { private AttributeType.DataType<?> dataType = null; public ResourceValues() { super(Object.class); } @Override public Object generate() { String className; if (dataType == null) { className = random.choose(AttributeType.DataType.SUPPORTED_TYPES.keySet()); } else { className = dataType.getName(); } Class<?> clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("Unrecognised class " + className); } if(clazz.equals(LocalDateTime.class)){ return LocalDateTime.ofInstant(Instant.ofEpochMilli(random.nextLong()), ZoneId.systemDefault()); } return gen(clazz); } ResourceValues dataType(AttributeType.DataType<?> dataType) { this.dataType = dataType; return this; } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/Resources.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; /** * A generator that produces {@link Attribute}s <<<<<<< Updated upstream:grakn-test-tools/src/main/java/ai/grakn/generator/Resources.java ======= * * @author Felix Chapman >>>>>>> Stashed changes:grakn-test-tools/src/main/java/ai/grakn/generator/Resources.java */ public class Resources extends AbstractThingGenerator<Attribute, AttributeType> { public Resources() { super(Attribute.class, ResourceTypes.class); } @Override protected Attribute newInstance(AttributeType type) { return newResource(type); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/Roles.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Label; import ai.grakn.concept.Role; /** * A generator that produces random {@link Role}s * * @author Felix Chapman */ public class Roles extends AbstractSchemaConceptGenerator<Role> { public Roles() { super(Role.class); } @Override protected Role newSchemaConcept(Label label) { return tx().putRole(label); } @Override protected Role metaSchemaConcept() { return tx().admin().getMetaRole(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/generator/Rules.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.generator; import ai.grakn.concept.Label; import ai.grakn.concept.Rule; import ai.grakn.graql.QueryBuilder; /** * A generator that produces random {@link Rule}s * * @author Felix Chapman */ public class Rules extends AbstractSchemaConceptGenerator<Rule> { public Rules() { super(Rule.class); } @Override protected Rule newSchemaConcept(Label label) { // TODO: generate more complicated rules QueryBuilder graql = this.tx().graql(); return tx().putRule(label, graql.parser().parsePattern("$x"), graql.parser().parsePattern("$x")); } @Override protected Rule metaSchemaConcept() { return tx().admin().getMetaRule(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/matcher/GraknMatchers.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.matcher; import ai.grakn.concept.Concept; import ai.grakn.concept.Label; import ai.grakn.concept.Thing; import ai.grakn.concept.Type; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.kb.internal.structure.Shard; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.TypeSafeMatcher; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import static ai.grakn.util.Schema.MetaSchema.ATTRIBUTE; import static ai.grakn.util.Schema.MetaSchema.ENTITY; import static ai.grakn.util.Schema.MetaSchema.RULE; import static ai.grakn.util.Schema.MetaSchema.THING; import static java.util.stream.Collectors.toSet; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; /** * Collection of static methods to create {@link Matcher} instances for tests. * * @author Felix Chapman */ public class GraknMatchers { public static final Matcher<MatchableConcept> concept = type(THING.getLabel()); public static final Matcher<MatchableConcept> entity = type(ENTITY.getLabel()); public static final Matcher<MatchableConcept> resource = type(ATTRIBUTE.getLabel()); public static final Matcher<MatchableConcept> rule = rule(RULE.getLabel()); /** * Create a matcher to test against the results of a Graql query. */ public static Matcher<Iterable<? extends ConceptMap>> results( Matcher<? extends Iterable<? extends Map<? extends Var, ? extends MatchableConcept>>> matcher ) { return new PropertyMatcher<Iterable<? extends ConceptMap>, Iterable<? extends Map<? extends Var, ? extends MatchableConcept>>>(matcher) { @Override public String getName() { return "results"; } @Override Iterable<? extends Map<Var, ? extends MatchableConcept>> transform(Iterable<? extends ConceptMap> item) { List<Map<Var, MatchableConcept>> iterable = new ArrayList<>(); item.forEach(m -> iterable.add(Maps.transformValues(m.map(), MatchableConcept::of))); return iterable; } }; } /** * Create matcher to test against a particular variable on every result of a Graql query. */ public static Matcher<Iterable<? extends ConceptMap>> variable( Var var, Matcher<? extends Iterable<? extends MatchableConcept>> matcher ) { return new PropertyMatcher<Iterable<? extends ConceptMap>, Iterable<? extends MatchableConcept>>(matcher) { @Override public String getName() { return "variable"; } @Override Iterable<? extends MatchableConcept> transform(Iterable<? extends ConceptMap> item) { List<MatchableConcept> iterable = new ArrayList<>(); item.forEach(answer -> iterable.add(MatchableConcept.of(answer.get(var)))); return iterable; } }; } /** * Create a matcher to test the value of a resource. */ public static Matcher<MatchableConcept> hasValue(Object expectedValue) { return new PropertyEqualsMatcher<MatchableConcept, Object>(expectedValue) { @Override public String getName() { return "hasValue"; } @Override public Object transform(MatchableConcept item) { return item.get().asAttribute().value(); } }; } /** * Create a matcher to test the type of an instance. */ public static Matcher<MatchableConcept> hasType(Matcher<MatchableConcept> matcher) { return new PropertyMatcher<MatchableConcept, Iterable<? super MatchableConcept>>(hasItem(matcher)) { @Override public String getName() { return "hasType"; } @Override Iterable<? super MatchableConcept> transform(MatchableConcept item) { return getTypes(item.get().asThing()).stream().map(MatchableConcept::of).collect(toSet()); } }; } /** * Create a matcher to test that the concept is a shard. */ public static Matcher<MatchableConcept> isShard() { return new TypeSafeMatcher<MatchableConcept>() { @Override public boolean matchesSafely(MatchableConcept concept) { return concept.get() instanceof Shard; } @Override public void describeTo(Description description) { description.appendText("isShard()"); } }; } /** * Create a matcher to test that the concept is an instance. */ public static Matcher<MatchableConcept> isInstance() { return new TypeSafeMatcher<MatchableConcept>() { @Override public boolean matchesSafely(MatchableConcept concept) { return concept.get().isThing(); } @Override public void describeTo(Description description) { description.appendText("isInstance()"); } }; } /** * Create a matcher to test that the concept has the given type name. */ public static Matcher<MatchableConcept> type(String type) { return type(Label.of(type)); } /** * Create a matcher to test that the concept has the given type name. */ public static Matcher<MatchableConcept> type(Label expectedLabel) { return new PropertyEqualsMatcher<MatchableConcept, Label>(expectedLabel) { @Override public String getName() { return "type"; } @Override Label transform(MatchableConcept item) { Concept concept = item.get(); return concept.isType() ? concept.asType().label() : null; } }; } /** * Create a matcher to test that the concept has the given type name. */ public static Matcher<MatchableConcept> role(String type) { return role(Label.of(type)); } /** * Create a matcher to test that the concept has the given type name. */ public static Matcher<MatchableConcept> role(Label expectedLabel) { return new PropertyEqualsMatcher<MatchableConcept, Label>(expectedLabel) { @Override public String getName() { return "role"; } @Override Label transform(MatchableConcept item) { Concept concept = item.get(); return concept.isRole() ? concept.asRole().label() : null; } }; } /** * Create a matcher to test that the concept has the given type name. */ public static Matcher<MatchableConcept> rule(String type) { return rule(Label.of(type)); } /** * Create a matcher to test that the concept has the given type name. */ public static Matcher<MatchableConcept> rule(Label expectedLabel) { return new PropertyEqualsMatcher<MatchableConcept, Label>(expectedLabel) { @Override public String getName() { return "rule"; } @Override Label transform(MatchableConcept item) { Concept concept = item.get(); return concept.isRule() ? concept.asRule().label() : null; } }; } /** * Create a matcher to test that the concept is an instance with a 'name' resource of the given value. * See {@link MatchableConcept#NAME_TYPES} for possible 'name' resources. */ public static Matcher<MatchableConcept> instance(Object value) { return instance(hasValue(value)); } /** * Create a matcher to test that the concept is an instance with a 'name' resource that matches the given matcher. * See {@link MatchableConcept#NAME_TYPES} for possible 'name' resources. */ private static Matcher<MatchableConcept> instance(Matcher<MatchableConcept> matcher) { return new PropertyMatcher<MatchableConcept, Iterable<? super MatchableConcept>>(hasItem(matcher)) { @Override public String getName() { return "instance"; } @Override Iterable<? super MatchableConcept> transform(MatchableConcept item) { return item.get().asThing().attributes() .filter(resource -> MatchableConcept.NAME_TYPES.contains(resource.type().label())) .map(MatchableConcept::of) .collect(toSet()); } @Override public Matcher<?> innerMatcher() { return matcher; } }; } private static Set<Type> getTypes(Thing thing) { Set<Type> types = Sets.newHashSet(); Type type = thing.type(); while (type != null) { types.add(type); type = type.sup(); } return types; } /** * A matcher for testing properties on objects. */ private static abstract class PropertyEqualsMatcher<T, S> extends PropertyMatcher<T, S> { PropertyEqualsMatcher(S expected) { super(is(expected)); } } /** * A matcher for testing properties on objects. */ private static abstract class PropertyMatcher<T, S> extends TypeSafeDiagnosingMatcher<T> { private final Matcher<? extends S> matcher; PropertyMatcher(Matcher<? extends S> matcher) { this.matcher = matcher; } @Override protected final boolean matchesSafely(T item, Description mismatch) { S transformed = transform(item); if (matcher.matches(transformed)) { return true; } else { mismatch.appendText(getName()).appendText("("); matcher.describeMismatch(transformed, mismatch); mismatch.appendText(")"); return false; } } @Override public final void describeTo(Description description) { description.appendText(getName()).appendText("(").appendDescriptionOf(innerMatcher()).appendText(")"); } public abstract String getName(); public Matcher<?> innerMatcher() { return matcher; } abstract S transform(T item); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/matcher/MatchableConcept.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.matcher; import ai.grakn.concept.Concept; import ai.grakn.concept.Label; import ai.grakn.concept.Attribute; import ai.grakn.concept.Thing; import ai.grakn.util.CommonUtil; import ai.grakn.util.StringUtil; import com.google.common.collect.ImmutableSet; import java.util.Optional; import java.util.stream.Stream; import static ai.grakn.util.StringUtil.valueToString; /** * Wraps a {@link Concept} in order to provide a prettier {@link Object#toString()} representation. This is done using * {@link MatchableConcept#NAME_TYPES}, a hard-coded set of common 'name' variables such as "name" and "title'. * * @author Felix Chapman */ public class MatchableConcept { static final ImmutableSet<Label> NAME_TYPES = ImmutableSet.of(Label.of("name"), Label.of("title")); private final Concept concept; private MatchableConcept(Concept concept) { this.concept = concept; } public static MatchableConcept of(Concept concept) { return new MatchableConcept(concept); } Concept get() { return concept; } @Override public String toString() { if (concept.isAttribute()) { return "hasValue(" + valueToString(concept.asAttribute().value()) + ")"; } else if (concept.isThing()) { Thing thing = concept.asThing(); Stream<Attribute<?>> resources = thing.attributes(); Optional<?> value = resources .filter(resource -> NAME_TYPES.contains(resource.type().label())) .map(Attribute::value).findFirst(); return "instance(" + value.map(StringUtil::valueToString).orElse("") + ") isa " + thing.type().label(); } else if (concept.isType()) { return "type(" + concept.asType().label() + ")"; } else if (concept.isRole()) { return "role(" + concept.asRole().label() + ")"; } else if (concept.isRule()) { return "rule(" + concept.asRule().label() + ")"; } else { throw CommonUtil.unreachableStatement("Unrecognised concept " + concept); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchableConcept that = (MatchableConcept) o; return concept.equals(that.concept); } @Override public int hashCode() { return concept.hashCode(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/matcher/MovieMatchers.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.matcher; import com.google.common.collect.ImmutableSet; import org.hamcrest.Matcher; import static ai.grakn.util.Schema.ImplicitType.HAS; import static org.hamcrest.Matchers.containsInAnyOrder; /** * Matchers for use with the movie dataset. * * @author Felix Chapman */ public class MovieMatchers { public static final Matcher<MatchableConcept> production = GraknMatchers.type("production"); public static final Matcher<MatchableConcept> movie = GraknMatchers.type("movie"); public static final Matcher<MatchableConcept> person = GraknMatchers.type("person"); public static final Matcher<MatchableConcept> genre = GraknMatchers.type("genre"); public static final Matcher<MatchableConcept> character = GraknMatchers.type("character"); public static final Matcher<MatchableConcept> cluster = GraknMatchers.type("cluster"); public static final Matcher<MatchableConcept> language = GraknMatchers.type("language"); public static final Matcher<MatchableConcept> title = GraknMatchers.type("title"); public static final Matcher<MatchableConcept> gender = GraknMatchers.type("gender"); public static final Matcher<MatchableConcept> realName = GraknMatchers.type("real-name"); public static final Matcher<MatchableConcept> name = GraknMatchers.type("name"); public static final Matcher<MatchableConcept> provenance = GraknMatchers.type("provenance"); public static final Matcher<MatchableConcept> tmdbVoteCount = GraknMatchers.type("tmdb-vote-count"); public static final Matcher<MatchableConcept> releaseDate = GraknMatchers.type("release-date"); public static final Matcher<MatchableConcept> runtime = GraknMatchers.type("runtime"); public static final Matcher<MatchableConcept> tmdbVoteAverage = GraknMatchers.type("tmdb-vote-average"); public static final Matcher<MatchableConcept> genreOfProduction = GraknMatchers.role("genre-of-production"); public static final Matcher<MatchableConcept> keyNameOwner = GraknMatchers.role("@key-name-owner"); public static final Matcher<MatchableConcept> materializeRule = GraknMatchers.rule("materialize-rule"); public static final Matcher<MatchableConcept> expectationRule = GraknMatchers.rule("expectation-rule"); public static final Matcher<MatchableConcept> hasTitle = GraknMatchers.type(HAS.getLabel("title")); public static final Matcher<MatchableConcept> godfather = GraknMatchers.instance("Godfather"); public static final Matcher<MatchableConcept> theMuppets = GraknMatchers.instance("The Muppets"); public static final Matcher<MatchableConcept> heat = GraknMatchers.instance("Heat"); public static final Matcher<MatchableConcept> apocalypseNow = GraknMatchers.instance("Apocalypse Now"); public static final Matcher<MatchableConcept> hocusPocus = GraknMatchers.instance("Hocus Pocus"); public static final Matcher<MatchableConcept> spy = GraknMatchers.instance("Spy"); public static final Matcher<MatchableConcept> chineseCoffee = GraknMatchers.instance("Chinese Coffee"); public static final Matcher<MatchableConcept> marlonBrando = GraknMatchers.instance("Marlon Brando"); public static final Matcher<MatchableConcept> alPacino = GraknMatchers.instance("Al Pacino"); public static final Matcher<MatchableConcept> missPiggy = GraknMatchers.instance("Miss Piggy"); public static final Matcher<MatchableConcept> kermitTheFrog = GraknMatchers.instance("Kermit The Frog"); public static final Matcher<MatchableConcept> martinSheen = GraknMatchers.instance("Martin Sheen"); public static final Matcher<MatchableConcept> robertDeNiro = GraknMatchers.instance("Robert de Niro"); public static final Matcher<MatchableConcept> judeLaw = GraknMatchers.instance("Jude Law"); public static final Matcher<MatchableConcept> mirandaHeart = GraknMatchers.instance("Miranda Heart"); public static final Matcher<MatchableConcept> betteMidler = GraknMatchers.instance("Bette Midler"); public static final Matcher<MatchableConcept> sarahJessicaParker = GraknMatchers.instance("Sarah Jessica Parker"); public static final Matcher<MatchableConcept> crime = GraknMatchers.instance("crime"); public static final Matcher<MatchableConcept> drama = GraknMatchers.instance("drama"); public static final Matcher<MatchableConcept> war = GraknMatchers.instance("war"); public static final Matcher<MatchableConcept> action = GraknMatchers.instance("action"); public static final Matcher<MatchableConcept> comedy = GraknMatchers.instance("comedy"); public static final Matcher<MatchableConcept> family = GraknMatchers.instance("family"); public static final Matcher<MatchableConcept> musical = GraknMatchers.instance("musical"); public static final Matcher<MatchableConcept> fantasy = GraknMatchers.instance("fantasy"); public static final Matcher<MatchableConcept> benjaminLWillard = GraknMatchers.instance("Benjamin L. Willard"); public static final Matcher<MatchableConcept> neilMcCauley = GraknMatchers.instance("Neil McCauley"); public static final Matcher<MatchableConcept> sarah = GraknMatchers.instance("Sarah"); public static final Matcher<MatchableConcept> harry = GraknMatchers.instance("Harry"); @SuppressWarnings("unchecked") public static final ImmutableSet<Matcher<? super MatchableConcept>> movies = ImmutableSet.of( godfather, theMuppets, apocalypseNow, heat, hocusPocus, spy, chineseCoffee ); public static final Matcher<Iterable<? extends MatchableConcept>> containsAllMovies = containsInAnyOrder(movies); }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/rpc/GrpcTestUtil.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.rpc; import io.grpc.Metadata; import io.grpc.Status; import io.grpc.StatusRuntimeException; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Objects; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isA; /** * @author Felix Chapman */ public class GrpcTestUtil { public static Matcher<StatusRuntimeException> hasStatus(Status status) { Matcher<Status> hasCode = hasProperty("code", is(status.getCode())); Matcher<Status> statusMatcher; String description = status.getDescription(); if (description == null) { statusMatcher = hasCode; } else { Matcher<Status> hasDescription = hasProperty("description", is(description)); statusMatcher = allOf(hasCode, hasDescription); } return allOf(isA(StatusRuntimeException.class), hasProperty("status", statusMatcher)); } public static <T> Matcher<StatusRuntimeException> hasMetadata(Metadata.Key<T> key, T value) { return new TypeSafeMatcher<StatusRuntimeException>() { @Override protected boolean matchesSafely(StatusRuntimeException item) { return Objects.equals(item.getTrailers().get(key), value); } @Override public void describeTo(Description description) { description.appendValue(String.format("has metadata %s=%s", key.name(), value)); } }; } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/AbstractPathKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.Label; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public abstract class AbstractPathKB extends TestKB { private final Label key; private final String gqlFile; private final int n; private final int m; AbstractPathKB(String gqlFile, Label key, int n, int m){ this.gqlFile = gqlFile; this.key = key; this.n = n; this.m = m; } @Override public Consumer<GraknTx> build(){ return (GraknTx tx) -> { SampleKBLoader.loadFromFile(tx, gqlFile); buildExtensionalDB(tx, n, m); }; } Label getKey(){ return key;} abstract protected void buildExtensionalDB(GraknTx tx, int n, int children); }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/AdmissionsKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.AttributeType; import ai.grakn.concept.EntityType; import ai.grakn.concept.Thing; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; /** * * @author Kasper Piskorski * */ public class AdmissionsKB extends TestKB { private static AttributeType<String> key; private static EntityType applicant; private static AttributeType<Long> TOEFL; private static AttributeType<Double> GPR; private static AttributeType<Long> GRE; private static AttributeType<Long> vGRE; private static AttributeType<String> specialHonours; private static AttributeType<String> degreeOrigin; private static AttributeType<String> transcript; private static AttributeType<String> priorGraduateWork; private static AttributeType<String> languageRequirement; private static AttributeType<String> considerGPR; private static AttributeType<String> admissionStatus; private static AttributeType<String> decisionType; public static SampleKBContext context() { return new AdmissionsKB().makeContext(); } @Override protected void buildSchema(GraknTx tx) { key = tx.putAttributeType("name", AttributeType.DataType.STRING); TOEFL = tx.putAttributeType("TOEFL", AttributeType.DataType.LONG); GRE = tx.putAttributeType("GRE", AttributeType.DataType.LONG); vGRE = tx.putAttributeType("vGRE", AttributeType.DataType.LONG); GPR = tx.putAttributeType("GPR", AttributeType.DataType.DOUBLE); specialHonours = tx.putAttributeType("specialHonours", AttributeType.DataType.STRING); considerGPR = tx.putAttributeType("considerGPR", AttributeType.DataType.STRING); transcript = tx.putAttributeType("transcript", AttributeType.DataType.STRING); priorGraduateWork = tx.putAttributeType("priorGraduateWork", AttributeType.DataType.STRING); languageRequirement= tx.putAttributeType("languageRequirement", AttributeType.DataType.STRING); degreeOrigin = tx.putAttributeType("degreeOrigin", AttributeType.DataType.STRING); admissionStatus = tx.putAttributeType("admissionStatus", AttributeType.DataType.STRING); decisionType = tx.putAttributeType("decisionType", AttributeType.DataType.STRING); applicant = tx.putEntityType("applicant"); applicant.has(TOEFL); applicant.has(GRE); applicant.has(vGRE); applicant.has(GPR); applicant.has(specialHonours); applicant.has(considerGPR); applicant.has(transcript); applicant.has(priorGraduateWork); applicant.has(languageRequirement); applicant.has(degreeOrigin); applicant.has(admissionStatus); applicant.has(decisionType); applicant.has(key); } @Override protected void buildInstances(GraknTx tx) { Thing Alice = putEntityWithResource(tx, "Alice", applicant, key.label()); Thing Bob = putEntityWithResource(tx, "Bob", applicant, key.label()); Thing Charlie = putEntityWithResource(tx, "Charlie", applicant, key.label()); Thing Denis = putEntityWithResource(tx, "Denis", applicant, key.label()); Thing Eva = putEntityWithResource(tx, "Eva", applicant, key.label()); Thing Frank = putEntityWithResource(tx, "Frank", applicant, key.label()); putResource(Alice, TOEFL, 470L); putResource(Alice, degreeOrigin, "nonUS"); putResource(Bob, priorGraduateWork, "none"); putResource(Bob, TOEFL, 520L); putResource(Bob, degreeOrigin, "US"); putResource(Bob, transcript, "unavailable"); putResource(Bob, specialHonours, "none"); putResource(Bob, GRE, 1100L); putResource(Charlie, priorGraduateWork, "none"); putResource(Charlie, TOEFL, 600L); putResource(Charlie, degreeOrigin, "US"); putResource(Charlie, transcript, "available"); putResource(Charlie, specialHonours, "none"); putResource(Charlie, GRE, 1100L); putResource(Charlie, vGRE, 400L); putResource(Charlie, GPR, 2.99); putResource(Denis, priorGraduateWork, "none"); putResource(Denis, degreeOrigin, "US"); putResource(Denis, transcript, "available"); putResource(Denis, specialHonours, "none"); putResource(Denis, GRE, 900L); putResource(Denis, vGRE, 350L); putResource(Denis, GPR, 2.5); putResource(Eva, priorGraduateWork, "completed"); putResource(Eva, specialHonours, "valedictorian"); putResource(Eva, GPR, 3.0); putResource(Frank, TOEFL, 550L); putResource(Frank, degreeOrigin, "US"); putResource(Frank, transcript, "unavailable"); putResource(Frank, specialHonours, "none"); putResource(Frank, GRE, 100L); } @Override protected void buildRelations() { } @Override protected void buildRules(GraknTx tx) { SampleKBLoader.loadFromFile(tx, "admission-rules.gql"); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/CWKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.AttributeType; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.graql.Pattern; import ai.grakn.test.rule.SampleKBContext; /** * * @author Kasper Piskorski * */ public class CWKB extends TestKB { private static AttributeType<String> key; private static EntityType person; private static EntityType rocket; private static EntityType country; private static AttributeType<String> propulsion; private static AttributeType<String> nationality; private static RelationshipType isEnemyOf; private static RelationshipType isPaidBy; private static RelationshipType owns; private static Role enemySource, enemyTarget; private static Role owner, ownedItem; private static Role payee, payer; private static Thing colonelWest, Nono, America, Tomahawk; public static SampleKBContext context() { return new CWKB().makeContext(); } @Override protected void buildSchema(GraknTx tx) { key = tx.putAttributeType("name", AttributeType.DataType.STRING); //Resources nationality = tx.putAttributeType("nationality", AttributeType.DataType.STRING); propulsion = tx.putAttributeType("propulsion", AttributeType.DataType.STRING); AttributeType<String> alignment = tx.putAttributeType("alignment", AttributeType.DataType.STRING); //Roles owner = tx.putRole("item-owner"); ownedItem = tx.putRole("owned-item"); payee = tx.putRole("payee"); payer = tx.putRole("payer"); enemySource = tx.putRole("enemy-source"); enemyTarget = tx.putRole("enemy-target"); Role seller = tx.putRole("seller"); Role buyer = tx.putRole("buyer"); Role transactionItem = tx.putRole("transaction-item"); EntityType baseEntity = tx.putEntityType("baseEntity") .has(key); //Entitites person = tx.putEntityType("person") .sup(baseEntity) .plays(seller) .plays(payee) .has(nationality); tx.putEntityType("criminal") .sup(person); EntityType weapon = tx.putEntityType("weapon") .sup(baseEntity) .plays(transactionItem) .plays(ownedItem); rocket = tx.putEntityType("rocket") .sup(weapon) .has(propulsion); tx.putEntityType("missile") .sup(weapon) //sup(rocket)? .has(propulsion); country = tx.putEntityType("country") .sup(baseEntity) .plays(buyer) .plays(owner) .plays(enemyTarget) .plays(payer) .plays(enemySource) .has(alignment); //Relations owns = tx.putRelationshipType("owns") .relates(owner) .relates(ownedItem); isEnemyOf = tx.putRelationshipType("is-enemy-of") .relates(enemySource) .relates(enemyTarget); tx.putRelationshipType("transaction") .relates(seller) .relates(buyer) .relates(transactionItem); isPaidBy = tx.putRelationshipType("is-paid-by") .relates(payee) .relates(payer); } @Override protected void buildInstances(GraknTx tx) { colonelWest = putEntityWithResource(tx, "colonelWest", person, key.label()); Nono = putEntityWithResource(tx, "Nono", country, key.label()); America = putEntityWithResource(tx, "America", country, key.label()); Tomahawk = putEntityWithResource(tx, "Tomahawk", rocket, key.label()); putResource(colonelWest, nationality, "American"); putResource(Tomahawk, propulsion, "gsp"); } @Override protected void buildRelations() { //Enemy(Nono, America) isEnemyOf.create() .assign(enemySource, Nono) .assign(enemyTarget, America); //Owns(Nono, Missile) owns.create() .assign(owner, Nono) .assign(ownedItem, Tomahawk); //isPaidBy(West, Nono) isPaidBy.create() .assign(payee, colonelWest) .assign(payer, Nono); } @Override protected void buildRules(GraknTx tx) { //R1: "It is a crime for an American to sell weapons to hostile nations" Pattern R1_LHS = tx.graql().parser().parsePattern("{" + "$x isa person;$x has nationality 'American';" + "$y isa weapon;" + "$z isa country;$z has alignment 'hostile';" + "(seller: $x, transaction-item: $y, buyer: $z) isa transaction;}"); Pattern R1_RHS = tx.graql().parser().parsePattern("{$x isa criminal;}"); tx.putRule("R1: It is a crime for an American to sell weapons to hostile nations" , R1_LHS, R1_RHS); //R2: "Missiles are a kind of a weapon" Pattern R2_LHS = tx.graql().parser().parsePattern("{$x isa missile;}"); Pattern R2_RHS = tx.graql().parser().parsePattern("{$x isa weapon;}"); tx.putRule("R2: Missiles are a kind of a weapon\"" , R2_LHS, R2_RHS); //R3: "If a country is an enemy of America then it is hostile" Pattern R3_LHS = tx.graql().parser().parsePattern("{$x isa country;" + "($x, $y) isa is-enemy-of;" + "$y isa country;$y has name 'America';}"); Pattern R3_RHS = tx.graql().parser().parsePattern("{$x has alignment 'hostile';}"); tx.putRule("R3: If a country is an enemy of America then it is hostile" , R3_LHS, R3_RHS); //R4: "If a rocket is self-propelled and guided, it is a missile" Pattern R4_LHS = tx.graql().parser().parsePattern("{$x isa rocket;$x has propulsion 'gsp';}"); Pattern R4_RHS = tx.graql().parser().parsePattern("{$x isa missile;}"); tx.putRule("R4: If a rocket is self-propelled and guided, it is a missile" , R4_LHS, R4_RHS); Pattern R5_LHS = tx.graql().parser().parsePattern("{$x isa person;" + "$y isa country;" + "$z isa weapon;" + "($x, $y) isa is-paid-by;" + "($y, $z) isa owns;}"); Pattern R5_RHS = tx.graql().parser().parsePattern("{(seller: $x, buyer: $y, transaction-item: $z) isa transaction;}"); tx.putRule("R5: If a country pays a person and that country now owns a weapon then the person has sold the country a weapon" , R5_LHS, R5_RHS); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/DiagonalKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class DiagonalKB extends TestKB { private final static Label key = Label.of("name"); private final static String gqlFile = "diagonal-test.gql"; private final int n; private final int m; public DiagonalKB(int n, int m){ this.m = m; this.n = n; } public static SampleKBContext context(int n, int m) { return new DiagonalKB(n, m).makeContext(); } @Override public Consumer<GraknTx> build(){ return (GraknTx graph) -> { SampleKBLoader.loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n, m); }; } private void buildExtensionalDB(GraknTx tx, int n, int m) { Role relFrom = tx.getRole("rel-from"); Role relTo = tx.getRole("rel-to"); EntityType entity1 = tx.getEntityType("entity1"); RelationshipType horizontal = tx.getRelationshipType("horizontal"); RelationshipType vertical = tx.getRelationshipType("vertical"); ConceptId[][] instanceIds = new ConceptId[n][m]; long inserts = 0; for(int i = 0 ; i < n ;i++) { for (int j = 0; j < m; j++) { instanceIds[i][j] = putEntityWithResource(tx, "a" + i + "," + j, entity1, key).id(); inserts++; if (inserts % 100 == 0) System.out.println("inst inserts: " + inserts); } } for(int i = 0 ; i < n ; i++) { for (int j = 0; j < m; j++) { if ( i < n - 1 ) { vertical.create() .assign(relFrom, tx.getConcept(instanceIds[i][j])) .assign(relTo, tx.getConcept(instanceIds[i+1][j])); inserts++; } if ( j < m - 1){ horizontal.create() .assign(relFrom, tx.getConcept(instanceIds[i][j])) .assign(relTo, tx.getConcept(instanceIds[i][j+1])); inserts++; } if (inserts % 100 == 0) System.out.println("rel inserts: " + inserts); } } System.out.println("Extensional DB loaded."); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/DualLinearTransitivityMatrixKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Label; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class DualLinearTransitivityMatrixKB extends TestKB { private final static Label key = Label.of("index"); private final static String gqlFile = "dualLinearTransitivity.gql"; private final int n; private final int m; public DualLinearTransitivityMatrixKB(int n, int m){ this.m = m; this.n = n; } public static SampleKBContext context(int n, int m) { return new DualLinearTransitivityMatrixKB(n, m).makeContext(); } @Override public Consumer<GraknTx> build(){ return (GraknTx graph) -> { SampleKBLoader.loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n, m); }; } private void buildExtensionalDB(GraknTx graph, int n, int m) { Role R1from = graph.getRole("R1-from"); Role R1to = graph.getRole("R1-to"); Role R2from = graph.getRole("R2-from"); Role R2to = graph.getRole("R2-to"); EntityType aEntity = graph.getEntityType("a-entity"); EntityType bEntity = graph.getEntityType("b-entity"); RelationshipType R1 = graph.getRelationshipType("R1"); RelationshipType R2 = graph.getRelationshipType("R2"); ConceptId[] aInstancesIds = new ConceptId[m+1]; ConceptId[][] bInstancesIds = new ConceptId[m][n+1]; aInstancesIds[0] = putEntityWithResource(graph, "a0", graph.getEntityType("start"), key).id(); aInstancesIds[m] = putEntityWithResource(graph, "a" + m, graph.getEntityType("end"), key).id(); for(int i = 1 ; i < m ;i++) { aInstancesIds[i] = putEntityWithResource(graph, "a" + i, aEntity, key).id(); } for(int i = 1 ; i < m ;i++) { for (int j = 1; j <= n; j++) { bInstancesIds[i][j] = putEntityWithResource(graph, "b" + i + j, bEntity, key).id(); } } for (int i = 0; i < m; i++) { R1.create() .assign(R1from, graph.getConcept(aInstancesIds[i])) .assign(R1to, graph.getConcept(aInstancesIds[i + 1])); } for(int j = 1 ; j <= n ;j++) { R2.create() .assign(R2from, graph.getConcept(aInstancesIds[0])) .assign(R2to, graph.getConcept(bInstancesIds[1][j])); R2.create() .assign(R2from, graph.getConcept(bInstancesIds[m-1][j])) .assign(R2to, graph.getConcept(aInstancesIds[m])); for (int i = 1; i < m - 1; i++) { R2.create() .assign(R2from, graph.getConcept(bInstancesIds[i][j])) .assign(R2to, graph.getConcept(bInstancesIds[i + 1][j])); } } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/GenealogyKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class GenealogyKB extends TestKB { final private static String schemaFile = "genealogy/schema.gql"; final private static String dataFile = "genealogy/data.gql"; final private static String rulesFile = "genealogy/rules.gql"; public static SampleKBContext context() { return new GenealogyKB().makeContext(); } public static Consumer<GraknTx> get() { return new GenealogyKB().build(); } @Override public Consumer<GraknTx> build(){ return (GraknTx tx) -> { SampleKBLoader.loadFromFile(tx, schemaFile); SampleKBLoader.loadFromFile(tx, dataFile); SampleKBLoader.loadFromFile(tx, rulesFile); }; } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/GeoKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.AttributeType; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.graql.Pattern; import ai.grakn.test.rule.SampleKBContext; /** * * @author Kasper Piskorski * */ public class GeoKB extends TestKB { private static AttributeType<String> key; private static EntityType university, city, region, country, continent, geographicalObject; private static RelationshipType isLocatedIn; private static Role geoEntity, entityLocation; private static Thing Europe; private static Thing Warsaw, Wroclaw, London, Munich, Paris, Milan; private static Thing Masovia, Silesia, GreaterLondon, Bavaria, IleDeFrance, Lombardy; private static Thing Poland, England, Germany, France, Italy; private static Thing UW; private static Thing PW; private static Thing Imperial; private static Thing UCL; public static SampleKBContext context(){ return new GeoKB().makeContext(); } @Override public void buildSchema(GraknTx tx) { key = tx.putAttributeType("name", AttributeType.DataType.STRING); geoEntity = tx.putRole("geo-entity"); entityLocation = tx.putRole("entity-location"); isLocatedIn = tx.putRelationshipType("is-located-in") .relates(geoEntity).relates(entityLocation); geographicalObject = tx.putEntityType("geoObject") .plays(geoEntity) .plays(entityLocation); geographicalObject.has(key); continent = tx.putEntityType("continent") .sup(geographicalObject) .plays(entityLocation); country = tx.putEntityType("country") .sup(geographicalObject) .plays(geoEntity) .plays(entityLocation); region = tx.putEntityType("region") .sup(geographicalObject) .plays(geoEntity) .plays(entityLocation); city = tx.putEntityType("city") .sup(geographicalObject) .plays(geoEntity) .plays(entityLocation); university = tx.putEntityType("university") .plays(geoEntity); university.has(key); } @Override public void buildInstances(GraknTx tx) { Europe = putEntityWithResource(tx, "Europe", continent, key.label()); Poland = putEntityWithResource(tx, "Poland", country, key.label()); Masovia = putEntityWithResource(tx, "Masovia", region, key.label()); Silesia = putEntityWithResource(tx, "Silesia", region, key.label()); Warsaw = putEntityWithResource(tx, "Warsaw", city, key.label()); Wroclaw = putEntityWithResource(tx, "Wroclaw", city, key.label()); UW = putEntityWithResource(tx, "University-of-Warsaw", university, key.label()); PW = putEntityWithResource(tx, "Warsaw-Polytechnics", university, key.label()); England = putEntityWithResource(tx, "England", country, key.label()); GreaterLondon = putEntityWithResource(tx, "GreaterLondon", region, key.label()); London = putEntityWithResource(tx, "London", city, key.label()); Imperial = putEntityWithResource(tx, "Imperial College London", university, key.label()); UCL = putEntityWithResource(tx, "University College London", university, key.label()); Germany = putEntityWithResource(tx, "Germany", country, key.label()); Bavaria = putEntityWithResource(tx, "Bavaria", region, key.label()); Munich = putEntityWithResource(tx, "Munich", city, key.label()); putEntityWithResource(tx, "University of Munich", university, key.label()); France = putEntityWithResource(tx, "France", country, key.label()); IleDeFrance = putEntityWithResource(tx, "IleDeFrance", region, key.label()); Paris = putEntityWithResource(tx, "Paris", city, key.label()); Italy = putEntityWithResource(tx, "Italy", country, key.label()); Lombardy = putEntityWithResource(tx, "Lombardy", region, key.label()); Milan = putEntityWithResource(tx, "Milan", city, key.label()); } @Override public void buildRelations() { isLocatedIn.create() .assign(geoEntity, Poland) .assign(entityLocation, Europe); isLocatedIn.create() .assign(geoEntity, Masovia) .assign(entityLocation, Poland); isLocatedIn.create() .assign(geoEntity, Warsaw) .assign(entityLocation, Masovia); isLocatedIn.create() .assign(geoEntity, PW) .assign(entityLocation, Warsaw); isLocatedIn.create() .assign(geoEntity, UW) .assign(entityLocation, Warsaw); isLocatedIn.create() .assign(geoEntity, Silesia) .assign(entityLocation, Poland); isLocatedIn.create() .assign(geoEntity, Wroclaw) .assign(entityLocation, Silesia); isLocatedIn.create() .assign(geoEntity, Imperial) .assign(entityLocation, London); isLocatedIn.create() .assign(geoEntity, UCL) .assign(entityLocation, London); isLocatedIn.create() .assign(geoEntity, London) .assign(entityLocation, GreaterLondon); isLocatedIn.create() .assign(geoEntity, GreaterLondon) .assign(entityLocation, England); isLocatedIn.create() .assign(geoEntity, England) .assign(entityLocation, Europe); isLocatedIn.create() .assign(geoEntity, Munich) .assign(entityLocation, Bavaria); isLocatedIn.create() .assign(geoEntity, Bavaria) .assign(entityLocation, Germany); isLocatedIn.create() .assign(geoEntity, Germany) .assign(entityLocation, Europe); isLocatedIn.create() .assign(geoEntity, Milan) .assign(entityLocation, Lombardy); isLocatedIn.create() .assign(geoEntity, Lombardy) .assign(entityLocation, Italy); isLocatedIn.create() .assign(geoEntity, Italy) .assign(entityLocation, Europe); isLocatedIn.create() .assign(geoEntity, Paris) .assign(entityLocation, IleDeFrance); isLocatedIn.create() .assign(geoEntity, IleDeFrance) .assign(entityLocation, France); isLocatedIn.create() .assign(geoEntity, France) .assign(entityLocation, Europe); } @Override public void buildRules(GraknTx tx) { Pattern transitivity_LHS = tx.graql().parser().parsePattern("{(geo-entity: $x, entity-location: $y) isa is-located-in;" + "(geo-entity: $y, entity-location: $z) isa is-located-in;}"); Pattern transitivity_RHS = tx.graql().parser().parsePattern("{(geo-entity: $x, entity-location: $z) isa is-located-in;}"); tx.putRule("Geo Rule", transitivity_LHS, transitivity_RHS); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/LinearTransitivityMatrixKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.concept.RelationshipType; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class LinearTransitivityMatrixKB extends TestKB { private final static Label key = Label.of("index"); private final static String gqlFile = "linearTransitivity.gql"; private final int n; private final int m; private LinearTransitivityMatrixKB(int n, int m){ this.m = m; this.n = n; } public static SampleKBContext context(int n, int m) { return new LinearTransitivityMatrixKB(n, m).makeContext(); } @Override public Consumer<GraknTx> build(){ return (GraknTx graph) -> { SampleKBLoader.loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n, m); }; } private void buildExtensionalDB(GraknTx graph, int n, int m) { Role Qfrom = graph.getRole("Q-from"); Role Qto = graph.getRole("Q-to"); EntityType aEntity = graph.getEntityType("a-entity"); RelationshipType Q = graph.getRelationshipType("Q"); ConceptId[][] aInstancesIds = new ConceptId[n+1][m+1]; Thing aInst = putEntityWithResource(graph, "a", graph.getEntityType("entity2"), key); for(int i = 1 ; i <= n ;i++) { for (int j = 1; j <= m; j++) { aInstancesIds[i][j] = putEntityWithResource(graph, "a" + i + "," + j, aEntity, key).id(); } } Q.create() .assign(Qfrom, aInst) .assign(Qto, graph.getConcept(aInstancesIds[1][1])); for(int i = 1 ; i <= n ; i++) { for (int j = 1; j <= m; j++) { if ( i < n ) { Q.create() .assign(Qfrom, graph.getConcept(aInstancesIds[i][j])) .assign(Qto, graph.getConcept(aInstancesIds[i+1][j])); } if ( j < m){ Q.create() .assign(Qfrom, graph.getConcept(aInstancesIds[i][j])) .assign(Qto, graph.getConcept(aInstancesIds[i][j+1])); } } } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/MovieKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.AttributeType; import ai.grakn.concept.EntityType; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.graql.Pattern; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.Schema; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.function.Consumer; /** * * @author fppt, Felix Chapman */ public class MovieKB extends TestKB { private static EntityType production, movie, person, genre, character, cluster, language; private static AttributeType<String> title, gender, realName, name, provenance; private static AttributeType<Long> tmdbVoteCount, runtime; private static AttributeType<Double> tmdbVoteAverage; private static AttributeType<LocalDateTime> releaseDate; private static RelationshipType hasCast, authoredBy, directedBy, hasGenre, hasCluster; private static Role productionBeingDirected, director, productionWithCast, actor, characterBeingPlayed; private static Role genreOfProduction, productionWithGenre, clusterOfProduction, productionWithCluster; private static Role work, author; private static Thing godfather, theMuppets, heat, apocalypseNow, hocusPocus, spy, chineseCoffee; private static Thing marlonBrando, alPacino, missPiggy, kermitTheFrog, martinSheen, robertDeNiro, judeLaw; private static Thing mirandaHeart, betteMidler, sarahJessicaParker; private static Thing crime, drama, war, action, comedy, family, musical, fantasy; private static Thing donVitoCorleone, michaelCorleone, colonelWalterEKurtz, benjaminLWillard, ltVincentHanna; private static Thing neilMcCauley, bradleyFine, nancyBArtingstall, winifred, sarah, harry; private static Thing cluster0, cluster1; public static Consumer<GraknTx> get(){ return new MovieKB().build(); } public static SampleKBContext context(){ return new MovieKB().makeContext(); } @Override public void buildSchema(GraknTx tx) { work = tx.putRole("work"); author = tx.putRole("author"); authoredBy = tx.putRelationshipType("authored-by").relates(work).relates(author); productionBeingDirected = tx.putRole("production-being-directed").sup(work); director = tx.putRole("director").sup(author); directedBy = tx.putRelationshipType("directed-by").sup(authoredBy) .relates(productionBeingDirected).relates(director); productionWithCast = tx.putRole("production-with-cast"); actor = tx.putRole("actor"); characterBeingPlayed = tx.putRole("character-being-played"); hasCast = tx.putRelationshipType("has-cast") .relates(productionWithCast).relates(actor).relates(characterBeingPlayed); genreOfProduction = tx.putRole("genre-of-production"); productionWithGenre = tx.putRole("production-with-genre"); hasGenre = tx.putRelationshipType("has-genre") .relates(genreOfProduction).relates(productionWithGenre); clusterOfProduction = tx.putRole("cluster-of-production"); productionWithCluster = tx.putRole("production-with-cluster"); hasCluster = tx.putRelationshipType("has-cluster") .relates(clusterOfProduction).relates(productionWithCluster); title = tx.putAttributeType("title", AttributeType.DataType.STRING); title.has(title); tmdbVoteCount = tx.putAttributeType("tmdb-vote-count", AttributeType.DataType.LONG); tmdbVoteAverage = tx.putAttributeType("tmdb-vote-average", AttributeType.DataType.DOUBLE); releaseDate = tx.putAttributeType("release-date", AttributeType.DataType.DATE); runtime = tx.putAttributeType("runtime", AttributeType.DataType.LONG); gender = tx.putAttributeType("gender", AttributeType.DataType.STRING).regex("(fe)?male"); realName = tx.putAttributeType("real-name", AttributeType.DataType.STRING); name = tx.putAttributeType("name", AttributeType.DataType.STRING); provenance = tx.putAttributeType("provenance", AttributeType.DataType.STRING); production = tx.putEntityType("production") .plays(productionWithCluster).plays(productionBeingDirected).plays(productionWithCast) .plays(productionWithGenre); production.has(title); production.has(tmdbVoteCount); production.has(tmdbVoteAverage); production.has(releaseDate); production.has(runtime); movie = tx.putEntityType("movie").sup(production); tx.putEntityType("tv-show").sup(production); person = tx.putEntityType("person") .plays(director).plays(actor).plays(characterBeingPlayed); person.has(gender); person.has(name); person.has(realName); genre = tx.putEntityType("genre").plays(genreOfProduction); genre.key(name); character = tx.putEntityType("character") .plays(characterBeingPlayed); character.has(name); tx.putEntityType("award"); language = tx.putEntityType("language"); language.has(name); cluster = tx.putEntityType("cluster").plays(clusterOfProduction); cluster.has(name); tx.getType(Schema.ImplicitType.HAS.getLabel("title")).has(provenance); } @Override protected void buildInstances(GraknTx tx) { godfather = movie.create(); putResource(godfather, title, "Godfather"); putResource(godfather, tmdbVoteCount, 1000L); putResource(godfather, tmdbVoteAverage, 8.6); putResource(godfather, releaseDate, LocalDate.of(1984, 1, 1).atStartOfDay()); theMuppets = movie.create(); putResource(theMuppets, title, "The Muppets"); putResource(theMuppets, tmdbVoteCount, 100L); putResource(theMuppets, tmdbVoteAverage, 7.6); putResource(theMuppets, releaseDate, LocalDate.of(1985, 2, 2).atStartOfDay()); apocalypseNow = movie.create(); putResource(apocalypseNow, title, "Apocalypse Now"); putResource(apocalypseNow, tmdbVoteCount, 400L); putResource(apocalypseNow, tmdbVoteAverage, 8.4); heat = movie.create(); putResource(heat, title, "Heat"); hocusPocus = movie.create(); putResource(hocusPocus, title, "Hocus Pocus"); putResource(hocusPocus, tmdbVoteCount, 435L); spy = movie.create(); putResource(spy, title, "Spy"); putResource(spy, releaseDate, LocalDate.of(1986, 3, 3).atStartOfDay()); chineseCoffee = movie.create(); putResource(chineseCoffee, title, "Chinese Coffee"); putResource(chineseCoffee, tmdbVoteCount, 5L); putResource(chineseCoffee, tmdbVoteAverage, 3.1d); putResource(chineseCoffee, releaseDate, LocalDate.of(2000, 9, 2).atStartOfDay()); marlonBrando = person.create(); putResource(marlonBrando, name, "Marlon Brando"); alPacino = person.create(); putResource(alPacino, name, "Al Pacino"); missPiggy = person.create(); putResource(missPiggy, name, "Miss Piggy"); kermitTheFrog = person.create(); putResource(kermitTheFrog, name, "Kermit The Frog"); martinSheen = person.create(); putResource(martinSheen, name, "Martin Sheen"); robertDeNiro = person.create(); putResource(robertDeNiro, name, "Robert de Niro"); judeLaw = person.create(); putResource(judeLaw, name, "Jude Law"); mirandaHeart = person.create(); putResource(mirandaHeart, name, "Miranda Heart"); betteMidler = person.create(); putResource(betteMidler, name, "Bette Midler"); sarahJessicaParker = person.create(); putResource(sarahJessicaParker, name, "Sarah Jessica Parker"); crime = genre.create(); putResource(crime, name, "crime"); drama = genre.create(); putResource(drama, name, "drama"); war = genre.create(); putResource(war, name, "war"); action = genre.create(); putResource(action, name, "action"); comedy = genre.create(); putResource(comedy, name, "comedy"); family = genre.create(); putResource(family, name, "family"); musical = genre.create(); putResource(musical, name, "musical"); fantasy = genre.create(); putResource(fantasy, name, "fantasy"); donVitoCorleone = character.create(); putResource(donVitoCorleone, name, "Don Vito Corleone"); michaelCorleone = character.create(); putResource(michaelCorleone, name, "Michael Corleone"); colonelWalterEKurtz = character.create(); putResource(colonelWalterEKurtz, name, "Colonel Walter E. Kurtz"); benjaminLWillard = character.create(); putResource(benjaminLWillard, name, "Benjamin L. Willard"); ltVincentHanna = character.create(); putResource(ltVincentHanna, name, "Lt Vincent Hanna"); neilMcCauley = character.create(); putResource(neilMcCauley, name, "Neil McCauley"); bradleyFine = character.create(); putResource(bradleyFine, name, "Bradley Fine"); nancyBArtingstall = character.create(); putResource(nancyBArtingstall, name, "Nancy B Artingstall"); winifred = character.create(); putResource(winifred, name, "Winifred"); sarah = character.create(); putResource(sarah, name, "Sarah"); harry = character.create(); putResource(harry, name, "Harry"); cluster0 = cluster.create(); cluster1 = cluster.create(); putResource(cluster0, name, "0"); putResource(cluster1, name, "1"); } @Override protected void buildRelations() { directedBy.create() .assign(productionBeingDirected, chineseCoffee) .assign(director, alPacino); hasCast(godfather, marlonBrando, donVitoCorleone); hasCast(godfather, alPacino, michaelCorleone); hasCast(theMuppets, missPiggy, missPiggy); hasCast(theMuppets, kermitTheFrog, kermitTheFrog); hasCast(apocalypseNow, marlonBrando, colonelWalterEKurtz); hasCast(apocalypseNow, martinSheen, benjaminLWillard); hasCast(heat, alPacino, ltVincentHanna); hasCast(heat, robertDeNiro, neilMcCauley); hasCast(spy, judeLaw, bradleyFine); hasCast(spy, mirandaHeart, nancyBArtingstall); hasCast(hocusPocus, betteMidler, winifred); hasCast(hocusPocus, sarahJessicaParker, sarah); hasCast(chineseCoffee, alPacino, harry); hasGenre(godfather, crime); hasGenre(godfather, drama); hasGenre(apocalypseNow, drama); hasGenre(apocalypseNow, war); hasGenre(heat, crime); hasGenre(heat, drama); hasGenre(heat, action); hasGenre(theMuppets, comedy); hasGenre(theMuppets, family); hasGenre(theMuppets, musical); hasGenre(hocusPocus, comedy); hasGenre(hocusPocus, family); hasGenre(hocusPocus, fantasy); hasGenre(spy, comedy); hasGenre(spy, family); hasGenre(spy, musical); hasGenre(chineseCoffee, drama); hasCluster(cluster0, godfather, apocalypseNow, heat); hasCluster(cluster1, theMuppets, hocusPocus); } @Override protected void buildRules(GraknTx tx) { // These rules are totally made up for testing purposes and don't work! Pattern when = tx.graql().parser().parsePattern("$x has name 'expectation-when'"); Pattern then = tx.graql().parser().parsePattern("$x has name 'expectation-then'"); tx.putRule("expectation-rule", when, then); when = tx.graql().parser().parsePattern("$x has name 'materialize-when'"); then = tx.graql().parser().parsePattern("$x has name 'materialize-then'"); tx.putRule("materialize-rule", when, then); } private static void hasCast(Thing movie, Thing person, Thing character) { hasCast.create() .assign(productionWithCast, movie) .assign(actor, person) .assign(characterBeingPlayed, character); } private static void hasGenre(Thing movie, Thing genre) { hasGenre.create() .assign(productionWithGenre, movie) .assign(genreOfProduction, genre); } private static void hasCluster(Thing cluster, Thing... movies) { Relationship relationship = hasCluster.create().assign(clusterOfProduction, cluster); for (Thing movie : movies) { relationship.assign(productionWithCluster, movie); } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/NguyenKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class NguyenKB extends TestKB { private final static Label key = Label.of("index"); private final static String gqlFile = "nguyen-test.gql"; private final int n; public NguyenKB(int n){ this.n = n; } public static SampleKBContext context(int n) { return new NguyenKB(n).makeContext(); } @Override public Consumer<GraknTx> build(){ return (GraknTx graph) -> { SampleKBLoader.loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n); }; } private void buildExtensionalDB(GraknTx graph, int n) { Role Rfrom = graph.getRole("R-rA"); Role Rto = graph.getRole("R-rB"); Role qfrom = graph.getRole("Q-rA"); Role qto = graph.getRole("Q-rB"); Role Pfrom = graph.getRole("P-rA"); Role Pto = graph.getRole("P-rB"); EntityType entity = graph.getEntityType("entity2"); EntityType aEntity = graph.getEntityType("a-entity"); EntityType bEntity = graph.getEntityType("b-entity"); RelationshipType r = graph.getRelationshipType("R"); RelationshipType p = graph.getRelationshipType("P"); RelationshipType q = graph.getRelationshipType("Q"); ConceptId cId = putEntityWithResource(graph, "c", entity, key).id(); ConceptId dId = putEntityWithResource(graph, "d", entity, key).id(); ConceptId eId = putEntityWithResource(graph, "e", entity, key).id(); ConceptId[] aInstancesIds = new ConceptId[n+2]; ConceptId[] bInstancesIds = new ConceptId[n+2]; aInstancesIds[n+1] = putEntityWithResource(graph, "a" + (n+1), aEntity, key).id(); for(int i = 0 ; i <= n ;i++) { aInstancesIds[i] = putEntityWithResource(graph, "a" + i, aEntity, key).id(); bInstancesIds[i] = putEntityWithResource(graph, "b" + i, bEntity, key).id(); } p.create() .assign(Pfrom, graph.getConcept(cId)) .assign(Pto, graph.getConcept(dId)); r.create() .assign(Rfrom, graph.getConcept(dId)) .assign(Rto, graph.getConcept(eId)); q.create() .assign(qfrom, graph.getConcept(eId)) .assign(qto, graph.getConcept(aInstancesIds[0])); for(int i = 0 ; i <= n ;i++){ p.create() .assign(Pfrom, graph.getConcept(bInstancesIds[i])) .assign(Pto, graph.getConcept(cId)); p.create() .assign(Pfrom, graph.getConcept(cId)) .assign(Pto, graph.getConcept(bInstancesIds[i])); q.create() .assign(qfrom, graph.getConcept(aInstancesIds[i])) .assign(qto, graph.getConcept(bInstancesIds[i])); q.create() .assign(qfrom, graph.getConcept(bInstancesIds[i])) .assign(qto, graph.getConcept(aInstancesIds[i+1])); } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/PathMatrixKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.test.rule.SampleKBContext; /** * Defines a KB based on test 6.10 from Cao p. 82, but arranged in a matrix instead of a tree. * * @author Kasper Piskorski * */ public class PathMatrixKB extends AbstractPathKB { private PathMatrixKB(int n, int m){ super("path-test.gql", Label.of("index"), n, m); } public static SampleKBContext context(int n, int m) { return new PathMatrixKB(n, m).makeContext(); } @Override protected void buildExtensionalDB(GraknTx graph, int n, int m) { long startTime = System.currentTimeMillis(); EntityType vertex = graph.getEntityType("vertex"); EntityType startVertex = graph.getEntityType("start-vertex"); Role arcFrom = graph.getRole("arc-from"); Role arcTo = graph.getRole("arc-to"); RelationshipType arc = graph.getRelationshipType("arc"); putEntityWithResource(graph, "a0", startVertex, getKey()); for(int i = 0 ; i < n ;i++) { for (int j = 0; j < m; j++) { putEntityWithResource(graph, "a" + i + "," + j, vertex, getKey()); } } arc.create() .assign(arcFrom, getInstance(graph, "a0")) .assign(arcTo, getInstance(graph, "a0,0")); for(int i = 0 ; i < n ;i++) { for (int j = 0; j < m; j++) { if (j < n - 1) { arc.create() .assign(arcFrom, getInstance(graph, "a" + i + "," + j)) .assign(arcTo, getInstance(graph, "a" + i + "," + (j + 1))); } if (i < m - 1) { arc.create() .assign(arcFrom, getInstance(graph, "a" + i + "," + j)) .assign(arcTo, getInstance(graph, "a" + (i + 1) + "," + j)); } } } long loadTime = System.currentTimeMillis() - startTime; System.out.println("PathKBII loading time: " + loadTime + " ms"); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/PathTreeKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.test.rule.SampleKBContext; import com.google.common.math.IntMath; /** * Defines a KB based on test 6.10 from Cao p. 82. * * @author Kasper Piskorski * */ public class PathTreeKB extends AbstractPathKB { private PathTreeKB(int n, int m){ super("path-test.gql", Label.of("index"), n, m); } PathTreeKB(String gqlFile, Label label, int n, int m){ super(gqlFile, label, n, m); } public static SampleKBContext context(int n, int children) { return new PathTreeKB(n, children).makeContext(); } protected void buildExtensionalDB(GraknTx tx, int n, int children) { buildTree(tx, tx.getRole("arc-from"), tx.getRole("arc-to"), n , children); } void buildTree(GraknTx tx, Role fromRole, Role toRole, int n, int children) { long startTime = System.currentTimeMillis(); EntityType vertex = tx.getEntityType("vertex"); EntityType startVertex = tx.getEntityType("start-vertex"); RelationshipType arc = tx.getRelationshipType("arc"); putEntityWithResource(tx, "a0", startVertex, getKey()); int outputThreshold = 500; for (int i = 1; i <= n; i++) { int m = IntMath.pow(children, i); for (int j = 0; j < m; j++) { putEntityWithResource(tx, "a" + i + "," + j, vertex, getKey()); if (j != 0 && j % outputThreshold == 0) { System.out.println(j + " entities out of " + m + " inserted"); } } } for (int j = 0; j < children; j++) { arc.create() .assign(fromRole, getInstance(tx, "a0")) .assign(toRole, getInstance(tx, "a1," + j)); } for (int i = 1; i < n; i++) { int m = IntMath.pow(children, i); for (int j = 0; j < m; j++) { for (int c = 0; c < children; c++) { arc.create() .assign(fromRole, getInstance(tx, "a" + i + "," + j)) .assign(toRole, getInstance(tx, "a" + (i + 1) + "," + (j * children + c))); } if (j != 0 && j % outputThreshold == 0) { System.out.println("level " + i + "/" + (n - 1) + ": " + j + " entities out of " + m + " connected"); } } } long loadTime = System.currentTimeMillis() - startTime; System.out.println("PathKB loading time: " + loadTime + " ms"); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/PathTreeSymmetricKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.Label; import ai.grakn.concept.Role; import ai.grakn.test.rule.SampleKBContext; /** * * @author Kasper Piskorski * */ public class PathTreeSymmetricKB extends PathTreeKB { private PathTreeSymmetricKB(int n, int m){ super("path-test-symmetric.gql", Label.of("index"), n, m); } public static SampleKBContext context(int n, int m) { return new PathTreeSymmetricKB(n, m).makeContext(); } @Override protected void buildExtensionalDB(GraknTx tx, int n, int children) { Role coordinate = tx.getRole("coordinate"); buildTree(tx, coordinate, coordinate, n , children); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/SNBKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; /** * * @author Sheldon * */ public class SNBKB extends TestKB { public static SampleKBContext context() { return new SNBKB().makeContext(); } @Override protected void buildSchema(GraknTx tx) { SampleKBLoader.loadFromFile(tx, "ldbc-snb-schema.gql"); SampleKBLoader.loadFromFile(tx, "ldbc-snb-product-schema.gql"); } @Override protected void buildRules(GraknTx tx) { SampleKBLoader.loadFromFile(tx, "ldbc-snb-rules.gql"); } @Override protected void buildInstances(GraknTx tx) { SampleKBLoader.loadFromFile(tx, "ldbc-snb-data.gql"); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/TailRecursionKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class TailRecursionKB extends TestKB { private final static Label key = Label.of("index"); private final static String gqlFile = "tail-recursion-test.gql"; private final int n; private final int m; public TailRecursionKB(int n, int m) { this.n = n; this.m = m; } public static SampleKBContext context(int n, int m) { return new TailRecursionKB(n, m).makeContext(); } @Override public Consumer<GraknTx> build(){ return (GraknTx graph) -> { SampleKBLoader.loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n, m); }; } private void buildExtensionalDB(GraknTx graph, int n, int m) { Role qfrom = graph.getRole("Q-from"); Role qto = graph.getRole("Q-to"); EntityType aEntity = graph.getEntityType("a-entity"); EntityType bEntity = graph.getEntityType("b-entity"); RelationshipType q = graph.getRelationshipType("Q"); putEntityWithResource(graph, "a0", aEntity, key); for(int i = 1 ; i <= m + 1 ;i++) { for (int j = 1; j <= n; j++) { putEntityWithResource(graph, "b" + i + "," + j, bEntity, key); } } for (int j = 1; j <= n; j++) { q.create() .assign(qfrom, getInstance(graph, "a0")) .assign(qto, getInstance(graph, "b1" + "," + j)); for(int i = 1 ; i <= m ;i++) { q.create() .assign(qfrom, getInstance(graph, "b" + i + "," + j)) .assign(qto, getInstance(graph, "b" + (i + 1) + "," + j)); } } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/TestKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.Thing; import ai.grakn.test.rule.SampleKBContext; import java.util.Set; import java.util.function.Consumer; import static java.util.stream.Collectors.toSet; /** * Base for all test graphs. * @author borislav * */ public abstract class TestKB { protected void buildSchema(GraknTx tx){}; protected void buildInstances(GraknTx tx){}; protected void buildRelations(){}; protected void buildRules(GraknTx tx){}; public Consumer<GraknTx> build() { return (GraknTx tx) -> { buildSchema(tx); buildInstances(tx); buildRelations(); buildRules(tx); }; } public SampleKBContext makeContext() { return SampleKBContext.load(build()); } public static Thing putEntityWithResource(GraknTx tx, String id, EntityType type, Label key) { Thing inst = type.create(); putResource(inst, tx.getSchemaConcept(key), id); return inst; } public static <T> void putResource(Thing thing, AttributeType<T> attributeType, T resource) { Attribute attributeInstance = attributeType.create(resource); thing.has(attributeInstance); } public static Thing getInstance(GraknTx tx, String id){ Set<Thing> things = tx.getAttributesByValue(id) .stream().flatMap(Attribute::owners).collect(toSet()); if (things.size() != 1) { throw new IllegalStateException("Multiple things with given resource value"); } return things.iterator().next(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/TransitivityChainKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.Thing; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class TransitivityChainKB extends TestKB { private final static Label key = Label.of("index"); private final static String gqlFile = "quadraticTransitivity.gql"; private final int n; public TransitivityChainKB(int n){ this.n = n; } public static SampleKBContext context(int n) { return new TransitivityChainKB(n).makeContext(); } @Override public Consumer<GraknTx> build(){ return (GraknTx graph) -> { SampleKBLoader.loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n); }; } private void buildExtensionalDB(GraknTx graph, int n) { Role qfrom = graph.getRole("Q-from"); Role qto = graph.getRole("Q-to"); EntityType aEntity = graph.getEntityType("a-entity"); RelationshipType q = graph.getRelationshipType("Q"); Thing aInst = putEntityWithResource(graph, "a", graph.getEntityType("entity2"), key); ConceptId[] aInstanceIds = new ConceptId[n]; for(int i = 0 ; i < n ;i++) { aInstanceIds[i] = putEntityWithResource(graph, "a" + i, aEntity, key).id(); } q.create() .assign(qfrom, aInst) .assign(qto, graph.getConcept(aInstanceIds[0])); for(int i = 0 ; i < n - 1 ; i++) { q.create() .assign(qfrom, graph.getConcept(aInstanceIds[i])) .assign(qto, graph.getConcept(aInstanceIds[i+1])); } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/kbs/TransitivityMatrixKB.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.kbs; import ai.grakn.GraknTx; import ai.grakn.concept.ConceptId; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Thing; import ai.grakn.concept.Label; import ai.grakn.test.rule.SampleKBContext; import ai.grakn.util.SampleKBLoader; import java.util.function.Consumer; /** * * @author Kasper Piskorski * */ public class TransitivityMatrixKB extends TestKB { private final static Label key = Label.of("index"); private final static String gqlFile = "quadraticTransitivity.gql"; private final int n; private final int m; public TransitivityMatrixKB(int n, int m){ this.m = m; this.n = n; } public static SampleKBContext context(int n, int m) { return new TransitivityMatrixKB(n, m).makeContext(); } @Override public Consumer<GraknTx> build(){ return (GraknTx graph) -> { SampleKBLoader.loadFromFile(graph, gqlFile); buildExtensionalDB(graph, n, m); }; } private void buildExtensionalDB(GraknTx graph, int n, int m) { Role qfrom = graph.getRole("Q-from"); Role qto = graph.getRole("Q-to"); EntityType aEntity = graph.getEntityType("a-entity"); RelationshipType q = graph.getRelationshipType("Q"); Thing aInst = putEntityWithResource(graph, "a", graph.getEntityType("entity2"), key); ConceptId[][] aInstanceIds = new ConceptId[n][m]; for(int i = 0 ; i < n ;i++) { for (int j = 0; j < m; j++) { aInstanceIds[i][j] = putEntityWithResource(graph, "a" + i + "," + j, aEntity, key).id(); } } q.create() .assign(qfrom, aInst) .assign(qto, graph.getConcept(aInstanceIds[0][0])); for(int i = 0 ; i < n ; i++) { for (int j = 0; j < m ; j++) { if ( i < n - 1 ) { q.create() .assign(qfrom, graph.getConcept(aInstanceIds[i][j])) .assign(qto, graph.getConcept(aInstanceIds[i+1][j])); } if ( j < m - 1){ q.create() .assign(qfrom, graph.getConcept(aInstanceIds[i][j])) .assign(qto, graph.getConcept(aInstanceIds[i][j+1])); } } } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/rule/CompositeTestRule.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.rule; import org.junit.rules.ExternalResource; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import java.util.List; /** * A {@link TestRule} that is composed of other {@link TestRule}s. * * @author Felix Chapman */ public abstract class CompositeTestRule implements TestRule { protected abstract List<TestRule> testRules(); private ExternalResource innerResource = new ExternalResource() { @Override protected void before() throws Throwable { CompositeTestRule.this.before(); } @Override protected void after() { CompositeTestRule.this.after(); } }; /** * Takes all the rules in {@link #testRules()} and applies them to this Test Rule. * This is essential because the composite rule may depend on these rules being executed. */ @Override public final Statement apply(Statement base, Description description) { base = innerResource.apply(base, description); for (TestRule each : testRules()) { base = each.apply(base, description); } return base; } protected void before() throws Throwable { } protected void after() { } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/rule/EmbeddedCassandraContext.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.rule; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.thrift.transport.TTransportException; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.junit.rules.ExternalResource; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * <p> * Starts Embedded Cassandra * </p> * <p> * <p> * Helper class for starting and working with an embedded cassandra. * This should be used for testing purposes only * </p> * * @author fppt */ public class EmbeddedCassandraContext extends ExternalResource { private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(EmbeddedCassandraContext.class); private static final String DEFAULT_YAML_FILE_PATH = "cassandra-embedded.yaml"; private static AtomicBoolean CASSANDRA_RUNNING = new AtomicBoolean(false); private static AtomicInteger IN_CASSANDRA_CONTEXT = new AtomicInteger(0); private String yamlFilePath; private EmbeddedCassandraContext(String yamlFilePath) { this.yamlFilePath = yamlFilePath; } public static EmbeddedCassandraContext create() { return new EmbeddedCassandraContext(DEFAULT_YAML_FILE_PATH); } public static EmbeddedCassandraContext create(String yamlFilePath) { return new EmbeddedCassandraContext(yamlFilePath); } public static boolean inCassandraContext() { return IN_CASSANDRA_CONTEXT.get() > 0; } @Override protected void before() { if (CASSANDRA_RUNNING.compareAndSet(false, true)) { try { LOG.info("starting cassandra..."); EmbeddedCassandraServerHelper.startEmbeddedCassandra(yamlFilePath, 30_000L); //This thread sleep is to give time for cass to startup //TODO: Determine if this is still needed try { Thread.sleep(5000); } catch (InterruptedException ex) { LOG.info("Thread sleep interrupted."); Thread.currentThread().interrupt(); } LOG.info("cassandra started."); } catch (TTransportException | IOException | ConfigurationException e) { throw new RuntimeException("Cannot start Embedded Cassandra", e); } } IN_CASSANDRA_CONTEXT.incrementAndGet(); } @Override protected void after() { IN_CASSANDRA_CONTEXT.decrementAndGet(); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/rule/SampleKBContext.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.rule; import ai.grakn.GraknTx; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.SampleKBLoader; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import org.junit.rules.TestRule; import javax.annotation.Nullable; import java.util.List; import java.util.function.Consumer; /** * <p> * Sets up graphs for testing * </p> * * <p> * Contains utility methods and statically initialized environment variables to control * Grakn unit tests. * * This specific class extend {@link SampleKBLoader} and starts Cassandra instance via * {@link EmbeddedCassandraContext} if needed. * </p> * * @author borislav, fppt * */ public class SampleKBContext extends CompositeTestRule { private final SampleKBLoader loader; private SampleKBContext(SampleKBLoader loader){ this.loader = loader; } public static SampleKBContext empty(){ return getContext(null); } public static SampleKBContext load(Consumer<GraknTx> build){ return getContext(build); } public static SampleKBContext load(String ... files){ return getContext((graknGraph) -> { for (String file : files) { SampleKBLoader.loadFromFile(graknGraph, file); } }); } private static SampleKBContext getContext(@Nullable Consumer<GraknTx> preLoad){ return new SampleKBContext(SampleKBLoader.preLoad(preLoad)); } @Override protected List<TestRule> testRules() { return ImmutableList.of(SessionContext.create()); } public EmbeddedGraknTx<?> tx() { checkInContext(); return loader.tx(); } public void rollback() { checkInContext(); loader.rollback(); } private void checkInContext() { Preconditions.checkState(SessionContext.canUseTx(), "EmbeddedCassandraContext may not have started"); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/test/rule/SessionContext.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.test.rule; import ai.grakn.GraknSession; import ai.grakn.GraknTx; import ai.grakn.factory.EmbeddedGraknSession; import ai.grakn.util.GraknTestUtil; import com.google.common.collect.ImmutableList; import org.junit.rules.TestRule; import java.util.HashSet; import java.util.List; import java.util.Set; import static ai.grakn.util.SampleKBLoader.randomKeyspace; /** * Context for tests that use {@link GraknTx}s and {@link ai.grakn.GraknSession}s. * Will make sure that any dependencies such as cassandra are running * * @author Felix Chapman */ public class SessionContext extends CompositeTestRule { private Set<GraknSession> openedSessions = new HashSet<>(); private SessionContext() { } public static SessionContext create() { return new SessionContext(); } @Override protected List<TestRule> testRules() { if (GraknTestUtil.usingJanus()) { return ImmutableList.of(EmbeddedCassandraContext.create()); } else { return ImmutableList.of(); } } public static boolean canUseTx() { return !GraknTestUtil.usingJanus() || EmbeddedCassandraContext.inCassandraContext(); } public GraknSession newSession() { GraknSession session = (GraknTestUtil.usingJanus()) ? EmbeddedGraknSession.createEngineSession(randomKeyspace()) : EmbeddedGraknSession.inMemory(randomKeyspace()); openedSessions.add(session); return session; } @Override public void after() { openedSessions.forEach(GraknSession::close); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/util/GraknTestUtil.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import ai.grakn.GraknConfigKey; import ai.grakn.GraknSystemProperty; import ai.grakn.engine.GraknConfig; import spark.Service; import java.io.IOException; import java.net.ServerSocket; /** * <p> * Houses common testing methods which are needed between different modules * </p> * * @author Filipe Peliz Pinto Teixeira */ public class GraknTestUtil { private static String CONFIG = GraknSystemProperty.TEST_PROFILE.value(); /** * * @return true if the tests are running on tinker graph */ public static boolean usingTinker() { return "tinker".equals(CONFIG); } /** * * @return true if the tests are running on janus graph. */ public static boolean usingJanus() { return "janus".equals(CONFIG); } /** * Allocates an unused port for Spark. * * <p> * This should always be called <i>immediately</i> before Spark starts in order to minimise a potential race * condition: in between finding an unused port and starting Spark, something else may steal the same port. * </p> * * <p> * The correct way to solve this race condition is to specify the Spark port as 0. Then, Spark will allocate * the port itself. However, there is an issue where {@link Service#port()} will always report 0 even after * Spark has started. * </p> */ public static void allocateSparkPort(GraknConfig config) { config.setConfigProperty(GraknConfigKey.SERVER_PORT, getEphemeralPort()); } /** * Gets a port which a service can bind to. * * <p> * The port returned by this method will be unused at the time of calling. However, at any point afterwards * it is possible that something else will take the port. * </p> */ private static int getEphemeralPort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { throw new RuntimeException(e); } } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/util/GraqlTestUtil.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import ai.grakn.GraknTx; import ai.grakn.graql.GetQuery; import ai.grakn.graql.Pattern; import ai.grakn.graql.QueryBuilder; import java.util.Collection; import org.apache.commons.collections.CollectionUtils; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Helper methods for writing tests for Graql * * @author Felix Chapman */ public class GraqlTestUtil { public static void assertExists(GraknTx tx, Pattern... patterns) { assertExists(tx.graql(), patterns); } public static void assertExists(QueryBuilder qb, Pattern... patterns) { assertExists(qb.match(patterns)); } public static void assertExists(Iterable<?> iterable) { assertTrue(iterable.iterator().hasNext()); } public static void assertNotExists(GraknTx tx, Pattern... patterns) { assertNotExists(tx.graql(), patterns); } public static void assertNotExists(QueryBuilder qb, Pattern... patterns) { assertNotExists(qb.match(patterns)); } public static void assertNotExists(Iterable<?> iterable) { assertFalse(iterable.iterator().hasNext()); } public static <T> void assertCollectionsEqual(Collection<T> c1, Collection<T> c2) { assertTrue(CollectionUtils.isEqualCollection(c1, c2)); } public static void assertQueriesEqual(GetQuery q1, GetQuery q2) { assertCollectionsEqual(q1.execute(), q2.execute()); } }
0
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-test-tools/1.4.3/ai/grakn/util/SampleKBLoader.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import ai.grakn.GraknSystemProperty; import ai.grakn.GraknTx; import ai.grakn.GraknTxType; import ai.grakn.Keyspace; import ai.grakn.factory.EmbeddedGraknSession; import ai.grakn.factory.GraknTxFactoryBuilder; import ai.grakn.factory.TxFactory; import ai.grakn.graql.Query; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.kb.internal.GraknTxTinker; import com.google.common.io.Files; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.UUID; import java.util.function.Consumer; import java.util.stream.Collectors; /** * <p> * Builds {@link GraknTx} bypassing engine. * </p> * * <p> * A helper class which is used to build {@link GraknTx} for testing purposes. * This class bypasses requiring an instance of engine to be running in the background. * Rather it acquires the necessary properties for building a graph directly from system properties. * This does however mean that commit logs are not submitted and no post processing is ran * </p> * * @author fppt */ public class SampleKBLoader { private final TxFactory<?> factory; private @Nullable Consumer<GraknTx> preLoad; private boolean graphLoaded = false; private EmbeddedGraknTx<?> tx; private SampleKBLoader(@Nullable Consumer<GraknTx> preLoad){ EmbeddedGraknSession session = GraknTestUtil.usingTinker() ? EmbeddedGraknSession.inMemory(randomKeyspace()) : EmbeddedGraknSession.createEngineSession(randomKeyspace()); factory = GraknTxFactoryBuilder.getInstance().getFactory(session, false); this.preLoad = preLoad; } public static SampleKBLoader empty(){ return new SampleKBLoader(null); } public static SampleKBLoader preLoad(@Nullable Consumer<GraknTx> build){ return new SampleKBLoader(build); } public EmbeddedGraknTx<?> tx(){ if(tx == null || tx.isClosed()){ //Load the graph if we need to if(!graphLoaded) { try(GraknTx tx = factory.open(GraknTxType.WRITE)){ load(tx); tx.commit(); graphLoaded = true; } } tx = factory.open(GraknTxType.WRITE); } return tx; } public void rollback() { if (tx instanceof GraknTxTinker) { tx.close(); tx.clearGraph(); graphLoaded = false; } else if (!tx.isClosed()) { tx.close(); } tx = tx(); } /** * Loads the graph using the specified Preloaders */ private void load(GraknTx graph){ if(preLoad != null) preLoad.accept(graph); } public static Keyspace randomKeyspace(){ // Embedded Casandra has problems dropping keyspaces that start with a number return Keyspace.of("a"+ UUID.randomUUID().toString().replaceAll("-", "")); } public static void loadFromFile(GraknTx graph, String file) { File graql = new File(GraknSystemProperty.PROJECT_RELATIVE_DIR.value() + "/grakn-test-tools/src/main/graql/" + file); List<String> queries; try { queries = Files.readLines(graql, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } graph.graql().parser().parseList(queries.stream().collect(Collectors.joining("\n"))).forEach(Query::execute); } }
0
java-sources/ai/grakn/grakn-titan-factory/0.10.0/ai/grakn
java-sources/ai/grakn/grakn-titan-factory/0.10.0/ai/grakn/factory/TitanHadoopInternalFactory.java
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.factory; import ai.grakn.graph.internal.AbstractGraknGraph; import ai.grakn.util.ErrorMessage; import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph; import org.apache.tinkerpop.gremlin.structure.util.GraphFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; /** * <p> * A Grakn Graph on top of {@link HadoopGraph} * </p> * * <p> * This produces a graph on top of {@link HadoopGraph}. * The base construction process defined by {@link AbstractInternalFactory} ensures the graph factories are singletons. * With this vendor some exceptions are in places: * 1. The Grakn API cannnot work on {@link HadoopGraph} this is due to not being able to directly write to a * {@link HadoopGraph}. * 2. This factory primarily exists as a means of producing a * {@link org.apache.tinkerpop.gremlin.process.computer.GraphComputer} on of {@link HadoopGraph} * </p> * * @author fppt */ public class TitanHadoopInternalFactory extends AbstractInternalFactory<AbstractGraknGraph<HadoopGraph>, HadoopGraph> { private static final String CLUSTER_KEYSPACE = "titanmr.ioformat.conf.storage.cassandra.keyspace"; private static final String INPUT_KEYSPACE = "cassandra.input.keyspace"; private final Logger LOG = LoggerFactory.getLogger(TitanHadoopInternalFactory.class); TitanHadoopInternalFactory(String keyspace, String engineUrl, Properties properties) { super(keyspace, engineUrl, properties); properties.setProperty(CLUSTER_KEYSPACE, keyspace); properties.setProperty(INPUT_KEYSPACE, keyspace); } @Override InternalFactory<AbstractGraknGraph<HadoopGraph>, HadoopGraph> getSystemFactory(){ return null; } @Override boolean isClosed(HadoopGraph innerGraph) { return false; } @Override AbstractGraknGraph<HadoopGraph> buildGraknGraphFromTinker(HadoopGraph graph, boolean batchLoading) { throw new UnsupportedOperationException(ErrorMessage.CANNOT_PRODUCE_GRAPH.getMessage(HadoopGraph.class.getName())); } @Override HadoopGraph buildTinkerPopGraph(boolean batchLoading) { LOG.warn("Hadoop graph ignores parameter address [" + super.engineUrl + "]"); return (HadoopGraph) GraphFactory.open(properties); } }