index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/EntityType.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.controller.response;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Label;
import ai.grakn.util.Schema;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.EntityType}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class EntityType extends Type{
@JsonCreator
public static EntityType create(
@JsonProperty("id") ConceptId id,
@JsonProperty("@id") Link selfLink,
@JsonProperty("label") Label label,
@JsonProperty("implicit") Boolean implicit,
@JsonProperty("super") EmbeddedSchemaConcept sup,
@JsonProperty("subs") Link subs,
@JsonProperty("abstract") Boolean isAbstract,
@JsonProperty("plays") Link plays,
@JsonProperty("attributes") Link attributes,
@JsonProperty("keys") Link keys,
@JsonProperty("instances") Link instances){
return new AutoValue_EntityType(Schema.BaseType.ENTITY_TYPE.name(), id, selfLink, label, implicit, sup, subs, isAbstract, plays, attributes, keys, instances);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/ExplanationBuilder.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.controller.response;
import ai.grakn.graql.admin.Explanation;
import ai.grakn.graql.answer.ConceptMap;
import ai.grakn.graql.admin.Unifier;
import ai.grakn.graql.internal.query.answer.ConceptMapImpl;
import ai.grakn.graql.internal.reasoner.UnifierType;
import ai.grakn.graql.internal.reasoner.atom.Atom;
import ai.grakn.graql.internal.reasoner.explanation.RuleExplanation;
import ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery;
import ai.grakn.graql.internal.reasoner.query.ReasonerQueries;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* Builds the explanation for a given series of {@link Answer}s
* </p>
*
* @author Marco Scoppetta
*/
public class ExplanationBuilder {
public static List<Answer> buildExplanation(ConceptMap queryAnswer) {
final List<Answer> explanation = new ArrayList<>();
queryAnswer.explanation().getAnswers().forEach(answer -> {
Explanation expl = answer.explanation();
Atom atom = ((ReasonerAtomicQuery) expl.getQuery()).getAtom();
ConceptMap inferredAnswer = new ConceptMapImpl();
if (expl.isLookupExplanation()){
ReasonerAtomicQuery rewrittenQuery = ReasonerQueries.atomic(atom.isResource()? atom : atom.rewriteWithRelationVariable());
inferredAnswer = ReasonerQueries.atomic(rewrittenQuery, answer).getQuery().stream()
.findFirst().orElse(new ConceptMapImpl());
} else if (expl.isRuleExplanation()) {
Atom headAtom = ((RuleExplanation) expl).getRule().getHead().getAtom();
ReasonerAtomicQuery rewrittenQuery = ReasonerQueries.atomic(headAtom.isResource()? headAtom : headAtom.rewriteWithRelationVariable());
inferredAnswer = headAtom.getMultiUnifier(atom, UnifierType.RULE).stream()
.map(Unifier::inverse)
.flatMap(unifier -> rewrittenQuery.materialise(answer.unify(unifier)))
.findFirst().orElse(new ConceptMapImpl());
}
explanation.add(Answer.create(inferredAnswer));
});
return explanation;
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Keyspace.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.controller.response;
import ai.grakn.API;
import ai.grakn.engine.Jacksonisable;
import ai.grakn.util.REST;
import ai.grakn.util.REST.WebPath;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.CheckReturnValue;
/**
* <p>
* Response object representing {@link ai.grakn.Keyspace}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class Keyspace implements Jacksonisable {
@API
@CheckReturnValue
public abstract ai.grakn.Keyspace value();
@API
@CheckReturnValue
@JsonCreator
public static Keyspace of(ai.grakn.Keyspace value){
return new AutoValue_Keyspace(value);
}
@API
@CheckReturnValue
@JsonProperty("@id")
public String id(){
return REST.resolveTemplate(WebPath.KB_KEYSPACE, name());
}
@API
@CheckReturnValue
@JsonProperty
public String name(){
return value().getValue();
}
@API
@CheckReturnValue
@JsonProperty
public String types(){
return REST.resolveTemplate(WebPath.KEYSPACE_TYPE, name());
}
@API
@CheckReturnValue
@JsonProperty
public String roles(){
return REST.resolveTemplate(WebPath.KEYSPACE_ROLE, name());
}
@API
@CheckReturnValue
@JsonProperty
public String rules(){
return REST.resolveTemplate(WebPath.KEYSPACE_RULE, name());
}
@API
@CheckReturnValue
@JsonProperty
public String graql(){
return REST.resolveTemplate(WebPath.KEYSPACE_GRAQL, name());
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Keyspaces.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.controller.response;
import ai.grakn.API;
import ai.grakn.engine.Jacksonisable;
import ai.grakn.util.REST;
import ai.grakn.util.REST.WebPath;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.CheckReturnValue;
import java.util.Set;
/**
* <p>
* Response object representing a collection of {@link Keyspace}s
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
@JsonIgnoreProperties(value={"@id", "keyspace"}, allowGetters=true)
public abstract class Keyspaces implements Jacksonisable{
@API
@CheckReturnValue
@JsonProperty
public abstract Set<Keyspace> keyspaces();
@API
@CheckReturnValue
@JsonCreator
public static Keyspaces of(@JsonProperty("keyspaces") Set<Keyspace> keyspaces){
return new AutoValue_Keyspaces(keyspaces);
}
@API
@CheckReturnValue
@JsonProperty("keyspace")
public final Link keyspace() {
return Link.create(REST.reformatTemplate(WebPath.KB_KEYSPACE));
}
@API
@CheckReturnValue
@JsonProperty("@id")
public String id(){
return WebPath.KB;
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Link.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.controller.response;
import ai.grakn.engine.Jacksonisable;
import ai.grakn.kb.internal.concept.SchemaConceptImpl;
import ai.grakn.util.REST;
import ai.grakn.util.REST.WebPath;
import ai.grakn.util.Schema;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableMap;
import java.util.Locale;
import java.util.Map;
import static java.util.stream.Collectors.joining;
/**
* <p>
* A helper class used to represent a link between different wrapper {@link Concept}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class Link implements Jacksonisable{
@JsonValue
public abstract String id();
@JsonCreator
public static Link create(String id){
return new AutoValue_Link(id);
}
public static Link create(Link link, Map<String, Object> params){
String id = link.id() + "?" + params.entrySet().stream().map(Link::paramString).collect(joining("&"));
return new AutoValue_Link(id);
}
private static String paramString(Map.Entry<String, Object> e) {
return e.getKey() + "=" + e.getValue();
}
public static Link create(ai.grakn.concept.Thing thing){
String id = REST.resolveTemplate(
WebPath.CONCEPT_LINK,
thing.keyspace().getValue(),
Schema.BaseType.CONCEPT.name().toLowerCase(Locale.getDefault()),
thing.id().getValue());
return create(id);
}
public static Link create(ai.grakn.concept.SchemaConcept schemaConcept){
String type;
if(schemaConcept.isType()){
type = Schema.BaseType.TYPE.name().toLowerCase(Locale.getDefault());
} else {
type = SchemaConceptImpl.from(schemaConcept).baseType().name().toLowerCase(Locale.getDefault());
}
String id = REST.resolveTemplate(
WebPath.CONCEPT_LINK,
schemaConcept.keyspace().getValue(),
type,
schemaConcept.label().getValue());
return create(id);
}
/**
* Creates a link to fetch all the {@link EmbeddedAttribute}s of a {@link Thing}
*/
public static Link createAttributesLink(ai.grakn.concept.Thing thing){
return create(REST.resolveTemplate(WebPath.CONCEPT_ATTRIBUTES, thing.keyspace().getValue(), thing.id().getValue()));
}
/**
* Creates a link to fetch all the {@link EmbeddedAttribute}s of a {@link Thing}
*/
public static Link createKeysLink(ai.grakn.concept.Thing thing){
return create(REST.resolveTemplate(WebPath.CONCEPT_KEYS, thing.keyspace().getValue(), thing.id().getValue()));
}
/**
* Creates a link to fetch all the {@link Relationship)s of a {@link Thing}
*/
public static Link createRelationshipsLink(ai.grakn.concept.Thing thing){
return create(REST.resolveTemplate(WebPath.CONCEPT_RELATIONSHIPS, thing.keyspace().getValue(), thing.id().getValue()));
}
/**
* Creates a link to fetch the instances of a {@link Type}
*/
public static Link createInstanceLink(ai.grakn.concept.Type type){
String id = REST.resolveTemplate(
WebPath.TYPE_INSTANCES,
type.keyspace().getValue(),
type.label().getValue());
return create(id);
}
/**
* Creates a link to get all the paged instances of a {@link Type}
*/
public static Link createInstanceLink(ai.grakn.concept.Type type, int offset, int limit){
ImmutableMap<String, Object> params = ImmutableMap.of(
REST.Request.OFFSET_PARAMETER, offset, REST.Request.LIMIT_PARAMETER, limit
);
return create(createInstanceLink(type), params);
}
/**
* Creates a link to get all the subs of a {@link SchemaConcept}
*/
public static Link createSubsLink(ai.grakn.concept.SchemaConcept schemaConcept){
String keyspace = schemaConcept.keyspace().getValue();
String label = schemaConcept.label().getValue();
if(schemaConcept.isType()) {
return create(REST.resolveTemplate(WebPath.TYPE_SUBS, keyspace, label));
} else if (schemaConcept.isRole()){
return create(REST.resolveTemplate(WebPath.ROLE_SUBS, keyspace, label));
} else {
return create(REST.resolveTemplate(WebPath.RULE_SUBS, keyspace, label));
}
}
/**
* Creates a link to get all the plays of a {@link Type}
*/
public static Link createPlaysLink(ai.grakn.concept.Type type){
return create(REST.resolveTemplate(WebPath.TYPE_PLAYS, type.keyspace().getValue(), type.label().getValue()));
}
/**
* Creates a link to get all the attributes of a {@link Type}
*/
public static Link createAttributesLink(ai.grakn.concept.Type type){
return create(REST.resolveTemplate(WebPath.TYPE_ATTRIBUTES, type.keyspace().getValue(), type.label().getValue()));
}
/**
* Creates a link to get all the keys of a {@link Type}
*/
public static Link createKeysLink(ai.grakn.concept.Type type){
return create(REST.resolveTemplate(WebPath.TYPE_KEYS, type.keyspace().getValue(), type.label().getValue()));
}
/**
* Creates a link to get all the instances of a {@link Type}
*/
public static Link createInstancesLink(ai.grakn.concept.Type type){
return create(REST.resolveTemplate(WebPath.TYPE_INSTANCES, type.keyspace().getValue(), type.label().getValue()));
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/ListResource.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.controller.response;
import ai.grakn.util.CommonUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* <p>
* Wraps a list of items with a self-link and a custom named key
* </p>
*
* <p>
* This uses a custom serializer and deserializer because the {@link ListResource#key()} can be dynamically
* specified. This reduces a lot of boilerplate response interfaces.
* </p>
*
* @param <T> The type of things the list contains
*
* @author Felix Chapman
*/
@AutoValue
@JsonDeserialize(using=ListResource.Deserializer.class)
public abstract class ListResource<T> extends JsonSerializable.Base {
public abstract Link selfLink();
/**
* The key for the items in the serialized JSON object.
*/
public abstract String key();
public abstract List<T> items();
public static <T> ListResource<T> create(Link selfLink, String key, List<T> items) {
return new AutoValue_ListResource<>(selfLink, key, ImmutableList.copyOf(items));
}
@Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeObjectField("@id", selfLink());
gen.writeObjectField(key(), items());
gen.writeEndObject();
}
@Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer)
throws IOException {
// TODO: maybe we need to do some other jackson wizardry here?
serialize(gen, serializers);
}
static class Deserializer<T> extends JsonDeserializer<ListResource<T>> {
private static final ImmutableSet<String> RECOGNISED_KEYS = ImmutableSet.of("@id");
@Override
public ListResource<T> deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
JsonNode node = parser.getCodec().readTree(parser);
// Find the first unrecognised field that is an array
Optional<Map.Entry<String, JsonNode>> field = CommonUtil.stream(node.fields())
.filter(f -> !RECOGNISED_KEYS.contains(f.getKey()))
.filter(f -> f.getValue().isArray())
// There might be multiple fields that are arrays, so we pick the first one and ignore the others
.sorted().findFirst();
if (!field.isPresent()) {
throw InvalidFormatException.from(parser, ListResource.class, "Expected a field containing a list");
}
String key = field.get().getKey();
JsonNode value = field.get().getValue();
List<T> items = value.traverse().readValueAs(new TypeReference<List<T>>(){});
Link selfLink = node.get("@id").traverse().readValueAs(Link.class);
return ListResource.create(selfLink, key, items);
}
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/MetaConcept.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.controller.response;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Label;
import ai.grakn.util.Schema;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
/**
* <p>
* Special wrapper class for the top meta concept {@link ai.grakn.util.Schema.MetaSchema#THING};
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@JsonIgnoreProperties(value={ "abstract", "plays", "attributes", "keys", "implicit" }, allowGetters=true)
@AutoValue
public abstract class MetaConcept extends Type{
@JsonCreator
public static MetaConcept create(
@JsonProperty("id") ConceptId id,
@JsonProperty("@id") Link selfLink,
@JsonProperty("label") Label label,
@JsonProperty("super") @Nullable EmbeddedSchemaConcept sup,
@JsonProperty("subs") Link subs,
@JsonProperty("plays") Link plays,
@JsonProperty("attributes") Link attributes,
@JsonProperty("keys") Link keys,
@JsonProperty("instances") Link instances
){
return new AutoValue_MetaConcept(Schema.BaseType.TYPE.name(), id, selfLink, label, false, sup, subs, true, plays, attributes, keys, instances);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Relationship.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.controller.response;
import ai.grakn.concept.ConceptId;
import ai.grakn.util.Schema;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
import java.util.Set;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.Relationship}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class Relationship extends Thing {
@JsonProperty
public abstract Set<RolePlayer> roleplayers();
@JsonCreator
public static Relationship create(
@JsonProperty("id") ConceptId id,
@JsonProperty("@id") Link selfLink,
@JsonProperty("type") EmbeddedSchemaConcept type,
@JsonProperty("attributes") Link attributes,
@JsonProperty("keys") Link keys,
@JsonProperty("relationships") Link relationships,
@JsonProperty("inferred") boolean inferred,
@Nullable @JsonProperty("explanation-query") String explanation,
@JsonProperty("roleplayers") Set<RolePlayer> roleplayers){
return new AutoValue_Relationship(Schema.BaseType.RELATIONSHIP.name(), id, selfLink, type, attributes, keys, relationships, inferred, explanation, roleplayers);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/RelationshipType.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.controller.response;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Label;
import ai.grakn.util.Schema;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import java.util.Set;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.RelationshipType}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class RelationshipType extends Type{
@JsonProperty
public abstract Set<Link> relates();
@JsonCreator
public static RelationshipType create(
@JsonProperty("id") ConceptId id,
@JsonProperty("@id") Link selfLink,
@JsonProperty("label") Label label,
@JsonProperty("implicit") Boolean implicit,
@JsonProperty("super") EmbeddedSchemaConcept sup,
@JsonProperty("subs") Link subs,
@JsonProperty("abstract") Boolean isAbstract,
@JsonProperty("plays") Link plays,
@JsonProperty("attributes") Link attributes,
@JsonProperty("keys") Link keys,
@JsonProperty("instances") Link instances,
@JsonProperty("relates") Set<Link> relates){
return new AutoValue_RelationshipType(Schema.BaseType.RELATIONSHIP_TYPE.name(), id, selfLink, label, implicit, sup, subs, isAbstract, plays, attributes, keys, instances, relates);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Role.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.controller.response;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Label;
import ai.grakn.util.Schema;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
import java.util.Set;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.Role}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class Role extends SchemaConcept{
@JsonProperty
public abstract Set<Link> relationships();
@JsonProperty
public abstract Set<Link> roleplayers();
@JsonCreator
public static Role create(
@JsonProperty("id") ConceptId id,
@JsonProperty("@id") Link selfLink,
@JsonProperty("label") Label label,
@JsonProperty("implicit") Boolean implicit,
@JsonProperty("super") @Nullable EmbeddedSchemaConcept sup,
@JsonProperty("subs") Link subs,
@JsonProperty("relationships") Set<Link> relationships,
@JsonProperty("roleplayers") Set<Link> roleplayers){
return new AutoValue_Role(Schema.BaseType.ROLE.name(), id, selfLink, label, implicit, sup, subs, relationships, roleplayers);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/RolePlayer.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.controller.response;
import ai.grakn.engine.Jacksonisable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
/**
* <p>
* Wrapper class for wrapping a {@link ai.grakn.concept.Role} and {@link ai.grakn.concept.Thing}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class RolePlayer implements Jacksonisable{
@JsonProperty
public abstract Link role();
@JsonProperty
public abstract Link thing();
@JsonCreator
public static RolePlayer create(@JsonProperty("role") Link role, @JsonProperty("thing") Link thing){
return new AutoValue_RolePlayer(role, thing);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Root.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.controller.response;
import ai.grakn.engine.Jacksonisable;
import ai.grakn.util.REST;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
/**
* @author Felix Chapman
*/
@AutoValue
public abstract class Root implements Jacksonisable {
public static Root create() {
return create(Link.create(REST.WebPath.ROOT), Link.create(REST.WebPath.KB));
}
@JsonCreator
public static Root create(@JsonProperty("@id") Link selfLink, @JsonProperty("keyspaces") Link kb) {
return new AutoValue_Root(selfLink, kb);
}
@JsonProperty("@id")
public abstract Link selfLink();
@JsonProperty("keyspaces")
public abstract Link kb();
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Rule.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.controller.response;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Label;
import ai.grakn.util.Schema;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.Rule}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
public abstract class Rule extends SchemaConcept{
@Nullable
@JsonProperty
public abstract String when();
@Nullable
@JsonProperty
public abstract String then();
@JsonCreator
public static Rule create(
@JsonProperty("id") ConceptId id,
@JsonProperty("@id") Link selfLink,
@JsonProperty("label") Label label,
@JsonProperty("implicit") Boolean implicit,
@JsonProperty("super") EmbeddedSchemaConcept sup,
@JsonProperty("subs") Link subs,
@Nullable @JsonProperty("when") String when,
@Nullable @JsonProperty("then") String then){
return new AutoValue_Rule(Schema.BaseType.RULE.name(), id, selfLink, label, implicit, sup, subs, when, then);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/SchemaConcept.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.controller.response;
import ai.grakn.concept.Label;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.Nullable;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.SchemaConcept}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
public abstract class SchemaConcept extends Concept{
@JsonProperty
public abstract Label label();
@JsonProperty
public abstract Boolean implicit();
@Nullable
@JsonProperty("super")
public abstract EmbeddedSchemaConcept sup();
@JsonProperty
public abstract Link subs();
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Thing.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.controller.response;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.annotation.Nullable;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.Thing}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
public abstract class Thing extends Concept {
@JsonProperty
public abstract EmbeddedSchemaConcept type();
@JsonProperty
public abstract Link attributes();
@JsonProperty
public abstract Link keys();
@JsonProperty
public abstract Link relationships();
@JsonProperty
public abstract boolean inferred();
@Nullable
@JsonProperty("explanation-query")
public abstract String explanation();
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Things.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.controller.response;
import ai.grakn.engine.Jacksonisable;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
import java.util.List;
/**
* <p>
* Wraps the {@link Thing}s of a {@link Type} with some metadata
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
@AutoValue
@JsonInclude(Include.NON_NULL)
public abstract class Things implements Jacksonisable{
@JsonProperty("@id")
public abstract Link selfLink();
@JsonProperty
public abstract List<Thing> instances();
@JsonProperty
@Nullable
public abstract Link next();
@JsonProperty
@Nullable
public abstract Link previous();
public static Things create(
@JsonProperty("@id") Link selfLink,
@JsonProperty("instances") List<Thing> instances,
@Nullable @JsonProperty("next") Link next,
@Nullable @JsonProperty("previous") Link previous
){
return new AutoValue_Things(selfLink, instances, next, previous);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/response/Type.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.controller.response;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* <p>
* Wrapper class for {@link ai.grakn.concept.Type}
* </p>
*
* @author Filipe Peliz Pinto Teixeira
*/
public abstract class Type extends SchemaConcept{
@JsonProperty("abstract")
public abstract Boolean isAbstract();
@JsonProperty
public abstract Link plays();
@JsonProperty
public abstract Link attributes();
@JsonProperty
public abstract Link keys();
@JsonProperty
public abstract Link instances();
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/controller/util/Requests.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.controller.util;
import ai.grakn.engine.controller.response.Link;
import ai.grakn.exception.GraknServerException;
import mjson.Json;
import spark.Request;
import java.util.Arrays;
import java.util.function.Function;
/**
* Utility class for handling http requests
*
* @author Grakn Warriors
*/
public class Requests {
/**
* Given a {@link Request} object retrieve the value of the {@param parameter} argument. If it is not present
* in the request query, return a 400 to the client.
*
* @param request information about the HTTP request
* @param parameter value to retrieve from the HTTP request
* @return value of the given parameter
*/
public static String mandatoryQueryParameter(Request request, String parameter){
return mandatoryQueryParameter(p -> queryParameter(request, p), parameter);
}
/**
* Given a {@link Function}, retrieve the value of the {@param parameter} by applying that function
* @param extractParameterFunction function used to extract the parameter
* @param parameter value to retrieve from the HTTP request
* @return value of the given parameter
*/
public static String mandatoryQueryParameter(Function<String, String> extractParameterFunction, String parameter) {
String result = extractParameterFunction.apply(parameter);
if (result == null) throw GraknServerException.requestMissingParameters(parameter);
return result;
}
/**
* Given a {@link Request}, retrieve the value of the {@param parameter}
* @param request information about the HTTP request
* @param parameter value to retrieve from the HTTP request
* @return value of the given parameter
*/
public static String queryParameter(Request request, String parameter){
return request.queryParams(parameter);
}
/**
* Given a {@link Request), retreive the value of the request body. If the request does not have a body,
* return a 400 (missing parameter) to the client.
*
* @param request information about the HTTP request
* @return value of the request body as a string
*/
public static String mandatoryBody(Request request){
if (request.body() == null || request.body().isEmpty()) throw GraknServerException.requestMissingBody();
return request.body();
}
public static Link selfLink(Request request) {
return Link.create(request.pathInfo());
}
/**
* Given a {@link Function}, retrieve the value of the {@param parameter} by applying that function
* @param parameter value to retrieve from the HTTP request
* @return value of the given parameter
*/
public static String mandatoryPathParameter(Request request, String parameter) {
// TODO: add new method GraknServerException.requestMissingPathParameters
String parameterValue = request.params(parameter);
if (parameterValue == null) throw GraknServerException.requestMissingParameters(parameter);
return parameterValue;
}
/**
* Given a {@link Json} object, attempt to extract a single field as supplied,
* or throw a user-friendly exception clearly indicating the missing field
* @param json the {@link Json} object containing the field to be extracted
* @param fieldPath String varargs representing the path of the field to be extracted
* @return the extracted {@link Json} object
* @throws {@link GraknServerException} with a clear indication of the missing field
*/
public static Json extractJsonField(Json json, String... fieldPath) {
Json currentField = json;
for (String field : fieldPath) {
Json tmp = currentField.at(field);
if (tmp != null) {
currentField = tmp;
} else {
throw GraknServerException.requestMissingBodyParameters(field);
}
}
return currentField;
}
/**
* Checks that the Request is of the valid type
*
* @param request
* @param contentTypes
*/
public static void validateRequest(Request request, String... contentTypes){
String acceptType = getAcceptType(request);
if(!Arrays.asList(contentTypes).contains(acceptType)){
throw GraknServerException.unsupportedContentType(acceptType);
}
}
/**
* Gets the accepted type of the request
*
* @param request
* @return
*/
public static String getAcceptType(Request request) {
// TODO - we are not handling multiple values here and we should!
String header = request.headers("Accept");
return header == null ? "" : request.headers("Accept").split(",")[0];
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/factory/EngineGraknTxFactory.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.factory;
import ai.grakn.GraknSession;
import ai.grakn.GraknTx;
import ai.grakn.GraknTxType;
import ai.grakn.Keyspace;
import ai.grakn.engine.GraknConfig;
import ai.grakn.engine.KeyspaceStore;
import ai.grakn.engine.lock.LockProvider;
import ai.grakn.factory.EmbeddedGraknSession;
import ai.grakn.factory.GraknTxFactoryBuilder;
import ai.grakn.kb.internal.EmbeddedGraknTx;
import com.google.common.annotations.VisibleForTesting;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
/**
* <p>
* Engine's internal {@link GraknTx} Factory
* </p>
* <p>
* <p>
* This internal factory is used to produce {@link GraknTx}s.
* </p>
*
* @author fppt
*/
public class EngineGraknTxFactory {
private final GraknConfig engineConfig;
private final KeyspaceStore keyspaceStore;
private final Map<Keyspace, EmbeddedGraknSession> openedSessions;
private final LockProvider lockProvider;
public static EngineGraknTxFactory create(LockProvider lockProvider, GraknConfig engineConfig, KeyspaceStore keyspaceStore) {
return new EngineGraknTxFactory(engineConfig, lockProvider, keyspaceStore);
}
private EngineGraknTxFactory(GraknConfig engineConfig, LockProvider lockProvider, KeyspaceStore keyspaceStore) {
this.openedSessions = new HashMap<>();
this.engineConfig = engineConfig;
this.lockProvider = lockProvider;
this.keyspaceStore = keyspaceStore;
}
//Should only be used for testing
@VisibleForTesting
public synchronized void refreshConnections(){
GraknTxFactoryBuilder.refresh();
}
public EmbeddedGraknTx<?> tx(Keyspace keyspace, GraknTxType type) {
if (!keyspaceStore.containsKeyspace(keyspace)) {
initialiseNewKeyspace(keyspace);
}
return session(keyspace).transaction(type);
}
/**
* Retrieves the {@link GraknSession} needed to open the {@link GraknTx}.
* This will open a new one {@link GraknSession} if it hasn't been opened before
*
* @param keyspace The {@link Keyspace} of the {@link GraknSession} to retrieve
* @return a new or existing {@link GraknSession} connecting to the provided {@link Keyspace}
*/
private EmbeddedGraknSession session(Keyspace keyspace){
if(!openedSessions.containsKey(keyspace)){
openedSessions.put(keyspace, EmbeddedGraknSession.createEngineSession(keyspace, engineConfig, GraknTxFactoryBuilder.getInstance()));
}
return openedSessions.get(keyspace);
}
/**
* Initialise a new {@link Keyspace} by opening and closing a transaction on it.
*
* @param keyspace the new {@link Keyspace} we want to create
*/
private void initialiseNewKeyspace(Keyspace keyspace) {
//If the keyspace does not exist lock and create it
Lock lock = lockProvider.getLock(getLockingKey(keyspace));
lock.lock();
try {
// Create new empty keyspace in db
session(keyspace).transaction(GraknTxType.WRITE).close();
// Add current keyspace to list of available Grakn keyspaces
keyspaceStore.addKeyspace(keyspace);
} finally {
lock.unlock();
}
}
private static String getLockingKey(Keyspace keyspace) {
return "/creating-new-keyspace-lock/" + keyspace.getValue();
}
public void closeSessions(){
this.openedSessions.values().forEach(EmbeddedGraknSession::close);
}
public GraknConfig config() {
return engineConfig;
}
public KeyspaceStore keyspaceStore() {
return keyspaceStore;
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/loader/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/>.
*/
/**
* Implements MutatorTask.
*/
package ai.grakn.engine.loader;
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/lock/LockProvider.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.lock;
import java.util.concurrent.locks.Lock;
/**
* Distributed lock interface
*
* @author Domenico Corapi
*/
public interface LockProvider {
Lock getLock(String lockName);
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/lock/ProcessWideLockProvider.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.lock;
import com.google.common.util.concurrent.Striped;
import java.util.concurrent.locks.Lock;
/**
*
* <p>
* Simple locking meachanism that can be used in case of single engine execution
* </p>
*
* @author alexandraorth
*/
public class ProcessWideLockProvider implements LockProvider {
private Striped<Lock> locks = Striped.lazyWeakLock(128);
public ProcessWideLockProvider(){
}
public Lock getLock(String lockToObtain){
return locks.get(lockToObtain);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/printer/JacksonPrinter.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.printer;
import ai.grakn.concept.Concept;
import ai.grakn.engine.controller.response.Answer;
import ai.grakn.engine.controller.response.ConceptBuilder;
import ai.grakn.graql.answer.AnswerGroup;
import ai.grakn.graql.answer.ConceptMap;
import ai.grakn.graql.answer.ConceptSetMeasure;
import ai.grakn.graql.internal.printer.Printer;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* This class is used to convert the responses from graql queries into objects which can be Jacksonised into their
* correct Json representation.
*
* @author Grakn Warriors
*/
public class JacksonPrinter extends Printer<Object> {
private static ObjectMapper mapper = new ObjectMapper();
public static JacksonPrinter create(){
return new JacksonPrinter();
}
@Override
protected String complete(Object object) {
try {
return mapper.writeValueAsString(object);
} catch (IOException e) {
throw new RuntimeException(String.format("Error during serialising {%s}", object), e);
}
}
@Override
protected Object concept(Concept concept) {
return ConceptBuilder.build(concept);
}
@Override
protected Object answerGroup(AnswerGroup<?> answer) {
return new HashMap.SimpleEntry<>(answer.owner(), build(answer.answers()));
}
@Override
protected Object conceptMap(ConceptMap answer) {
return Answer.create(answer);
}
@Override
protected Object conceptSetMeasure(ConceptSetMeasure answer) {
return new HashMap.SimpleEntry<>(answer.measurement(), answer.set());
}
@Override
protected Object bool(boolean bool) {
return bool;
}
@Override
protected Object object(Object object) {
return object;
}
@Override
protected Object map(Map map) {
Stream<Map.Entry> entries = map.<Map.Entry>entrySet().stream();
return entries.collect(Collectors.toMap(
entry -> build(entry.getKey()),
entry -> build(entry.getValue())
));
}
@Override
protected Object collection(Collection collection) {
return collection.stream().map(object -> build(object)).collect(Collectors.toList());
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/rpc/ConceptMethod.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.rpc;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Entity;
import ai.grakn.concept.Label;
import ai.grakn.exception.GraqlQueryException;
import ai.grakn.graql.Pattern;
import ai.grakn.kb.internal.EmbeddedGraknTx;
import ai.grakn.rpc.proto.ConceptProto;
import ai.grakn.rpc.proto.SessionProto;
import ai.grakn.rpc.proto.SessionProto.Transaction;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* Wrapper for describing methods on {@link ai.grakn.concept.Concept}s that can be executed over gRPC.
* This unifies client and server behaviour for each possible method on a concept.
* This class maps one-to-one with the gRPC message {@link ai.grakn.rpc.proto.ConceptProto.Method.Req}.
*/
public class ConceptMethod {
public static Transaction.Res run(ai.grakn.concept.Concept concept, ConceptProto.Method.Req req,
SessionService.Iterators iterators, EmbeddedGraknTx tx) {
ConceptHolder con = new ConceptHolder(concept, tx, iterators);
switch (req.getReqCase()) {
// Concept methods
case CONCEPT_DELETE_REQ:
return con.asConcept().delete();
// SchemaConcept methods
case SCHEMACONCEPT_ISIMPLICIT_REQ:
return con.asSchemaConcept().isImplicit();
case SCHEMACONCEPT_GETLABEL_REQ:
return con.asSchemaConcept().label();
case SCHEMACONCEPT_SETLABEL_REQ:
return con.asSchemaConcept().label(req.getSchemaConceptSetLabelReq().getLabel());
case SCHEMACONCEPT_GETSUP_REQ:
return con.asSchemaConcept().sup();
case SCHEMACONCEPT_SETSUP_REQ:
return con.asSchemaConcept().sup(req.getSchemaConceptSetSupReq().getSchemaConcept());
case SCHEMACONCEPT_SUPS_REQ:
return con.asSchemaConcept().sups();
case SCHEMACONCEPT_SUBS_REQ:
return con.asSchemaConcept().subs();
// Rule methods
case RULE_WHEN_REQ:
return con.asRule().when();
case RULE_THEN_REQ:
return con.asRule().then();
// Role methods
case ROLE_RELATIONS_REQ:
return con.asRole().relations();
case ROLE_PLAYERS_REQ:
return con.asRole().players();
// Type methods
case TYPE_INSTANCES_REQ:
return con.asType().instances();
case TYPE_ISABSTRACT_REQ:
return con.asType().isAbstract();
case TYPE_SETABSTRACT_REQ:
return con.asType().isAbstract(req.getTypeSetAbstractReq().getAbstract());
case TYPE_KEYS_REQ:
return con.asType().keys();
case TYPE_ATTRIBUTES_REQ:
return con.asType().attributes();
case TYPE_PLAYING_REQ:
return con.asType().playing();
case TYPE_KEY_REQ:
return con.asType().key(req.getTypeKeyReq().getAttributeType());
case TYPE_HAS_REQ:
return con.asType().has(req.getTypeHasReq().getAttributeType());
case TYPE_PLAYS_REQ:
return con.asType().plays(req.getTypePlaysReq().getRole());
case TYPE_UNKEY_REQ:
return con.asType().unkey(req.getTypeUnkeyReq().getAttributeType());
case TYPE_UNHAS_REQ:
return con.asType().unhas(req.getTypeUnhasReq().getAttributeType());
case TYPE_UNPLAY_REQ:
return con.asType().unplay(req.getTypeUnplayReq().getRole());
// EntityType methods
case ENTITYTYPE_CREATE_REQ:
return con.asEntityType().create();
// RelationshipType methods
case RELATIONTYPE_CREATE_REQ:
return con.asRelationshipType().create();
case RELATIONTYPE_ROLES_REQ:
return con.asRelationshipType().roles();
case RELATIONTYPE_RELATES_REQ:
return con.asRelationshipType().relates(req.getRelationTypeRelatesReq().getRole());
case RELATIONTYPE_UNRELATE_REQ:
return con.asRelationshipType().unrelate(req.getRelationTypeUnrelateReq().getRole());
// AttributeType methods
case ATTRIBUTETYPE_CREATE_REQ:
return con.asAttributeType().create(req.getAttributeTypeCreateReq().getValue());
case ATTRIBUTETYPE_ATTRIBUTE_REQ:
return con.asAttributeType().attribute(req.getAttributeTypeAttributeReq().getValue());
case ATTRIBUTETYPE_DATATYPE_REQ:
return con.asAttributeType().dataType();
case ATTRIBUTETYPE_GETREGEX_REQ:
return con.asAttributeType().regex();
case ATTRIBUTETYPE_SETREGEX_REQ:
return con.asAttributeType().regex(req.getAttributeTypeSetRegexReq().getRegex());
// Thing methods
case THING_ISINFERRED_REQ:
return con.asThing().isInferred();
case THING_TYPE_REQ:
return con.asThing().type();
case THING_KEYS_REQ:
return con.asThing().keys(req.getThingKeysReq().getAttributeTypesList());
case THING_ATTRIBUTES_REQ:
return con.asThing().attributes(req.getThingAttributesReq().getAttributeTypesList());
case THING_RELATIONS_REQ:
return con.asThing().relations(req.getThingRelationsReq().getRolesList());
case THING_ROLES_REQ:
return con.asThing().roles();
case THING_RELHAS_REQ:
return con.asThing().relhas(req.getThingRelhasReq().getAttribute());
case THING_UNHAS_REQ:
return con.asThing().unhas(req.getThingUnhasReq().getAttribute());
// Relationship methods
case RELATION_ROLEPLAYERSMAP_REQ:
return con.asRelationship().rolePlayersMap();
case RELATION_ROLEPLAYERS_REQ:
return con.asRelationship().rolePlayers(req.getRelationRolePlayersReq().getRolesList());
case RELATION_ASSIGN_REQ:
return con.asRelationship().assign(req.getRelationAssignReq());
case RELATION_UNASSIGN_REQ:
return con.asRelationship().unassign(req.getRelationUnassignReq());
// Attribute Methods
case ATTRIBUTE_VALUE_REQ:
return con.asAttribute().value();
case ATTRIBUTE_OWNERS_REQ:
return con.asAttribute().owners();
default:
case REQ_NOT_SET:
throw new IllegalArgumentException("Unrecognised " + req);
}
}
/**
* A utility class to hold on to the concept in the method request will be applied to
*/
public static class ConceptHolder {
private ai.grakn.concept.Concept concept;
private EmbeddedGraknTx tx;
private SessionService.Iterators iterators;
ConceptHolder(ai.grakn.concept.Concept concept, EmbeddedGraknTx tx, SessionService.Iterators iterators) {
this.concept = concept;
this.tx = tx;
this.iterators = iterators;
}
private ai.grakn.concept.Concept convert(ConceptProto.Concept protoConcept) {
return tx.getConcept(ConceptId.of(protoConcept.getId()));
}
Concept asConcept() {
return new Concept();
}
SchemaConcept asSchemaConcept() {
return new SchemaConcept();
}
Rule asRule() {
return new Rule();
}
Role asRole() {
return new Role();
}
Type asType() {
return new Type();
}
EntityType asEntityType() {
return new EntityType();
}
RelationshipType asRelationshipType() {
return new RelationshipType();
}
AttributeType asAttributeType() {
return new AttributeType();
}
Thing asThing() {
return new Thing();
}
Relationship asRelationship() {
return new Relationship();
}
Attribute asAttribute() {
return new Attribute();
}
private static SessionProto.Transaction.Res transactionRes(ConceptProto.Method.Res response) {
return SessionProto.Transaction.Res.newBuilder()
.setConceptMethodRes(SessionProto.Transaction.ConceptMethod.Res.newBuilder()
.setResponse(response)).build();
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.Concept}
*/
private class Concept {
private Transaction.Res delete() {
concept.delete();
return null;
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.SchemaConcept}
*/
private class SchemaConcept {
private Transaction.Res isImplicit() {
Boolean implicit = concept.asSchemaConcept().isImplicit();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setSchemaConceptIsImplicitRes(ConceptProto.SchemaConcept.IsImplicit.Res.newBuilder()
.setImplicit(implicit)).build();
return transactionRes(response);
}
private Transaction.Res label() {
Label label = concept.asSchemaConcept().label();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setSchemaConceptGetLabelRes(ConceptProto.SchemaConcept.GetLabel.Res.newBuilder()
.setLabel(label.getValue())).build();
return transactionRes(response);
}
private Transaction.Res label(String label) {
concept.asSchemaConcept().label(Label.of(label));
return null;
}
private Transaction.Res sup() {
ai.grakn.concept.Concept superConcept = concept.asSchemaConcept().sup();
ConceptProto.SchemaConcept.GetSup.Res.Builder responseConcept = ConceptProto.SchemaConcept.GetSup.Res.newBuilder();
if (superConcept == null) responseConcept.setNull(ConceptProto.Null.getDefaultInstance());
else responseConcept.setSchemaConcept(ResponseBuilder.Concept.concept(superConcept));
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setSchemaConceptGetSupRes(responseConcept).build();
return transactionRes(response);
}
private Transaction.Res sup(ConceptProto.Concept superConcept) {
// Make the second argument the super of the first argument
// @throws GraqlQueryException if the types are different, or setting the super to be a meta-type
ai.grakn.concept.SchemaConcept sup = convert(superConcept).asSchemaConcept();
ai.grakn.concept.SchemaConcept sub = concept.asSchemaConcept();
if (sup.isEntityType()) {
sub.asEntityType().sup(sup.asEntityType());
} else if (sup.isRelationshipType()) {
sub.asRelationshipType().sup(sup.asRelationshipType());
} else if (sup.isRole()) {
sub.asRole().sup(sup.asRole());
} else if (sup.isAttributeType()) {
sub.asAttributeType().sup(sup.asAttributeType());
} else if (sup.isRule()) {
sub.asRule().sup(sup.asRule());
} else {
throw GraqlQueryException.insertMetaType(sub.label(), sup);
}
return null;
}
private Transaction.Res sups() {
Stream<? extends ai.grakn.concept.SchemaConcept> concepts = concept.asSchemaConcept().sups();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setSchemaConceptSupsIterRes(ConceptProto.SchemaConcept.Sups.Iter.Res.newBuilder()
.setSchemaConcept(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setSchemaConceptSupsIter(ConceptProto.SchemaConcept.Sups.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res subs() {
Stream<? extends ai.grakn.concept.SchemaConcept> concepts = concept.asSchemaConcept().subs();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setSchemaConceptSubsIterRes(ConceptProto.SchemaConcept.Subs.Iter.Res.newBuilder()
.setSchemaConcept(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setSchemaConceptSubsIter(ConceptProto.SchemaConcept.Subs.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.Rule}
*/
private class Rule {
private Transaction.Res when() {
Pattern pattern = concept.asRule().when();
ConceptProto.Rule.When.Res.Builder whenRes = ConceptProto.Rule.When.Res.newBuilder();
if (pattern == null) whenRes.setNull(ConceptProto.Null.getDefaultInstance());
else whenRes.setPattern(pattern.toString());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRuleWhenRes(whenRes).build();
return transactionRes(response);
}
private Transaction.Res then() {
Pattern pattern = concept.asRule().then();
ConceptProto.Rule.Then.Res.Builder thenRes = ConceptProto.Rule.Then.Res.newBuilder();
if (pattern == null) thenRes.setNull(ConceptProto.Null.getDefaultInstance());
else thenRes.setPattern(pattern.toString());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRuleThenRes(thenRes).build();
return transactionRes(response);
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.Role}
*/
private class Role {
private Transaction.Res relations() {
Stream<ai.grakn.concept.RelationshipType> concepts = concept.asRole().relationships();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setRoleRelationsIterRes(ConceptProto.Role.Relations.Iter.Res.newBuilder()
.setRelationType(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRoleRelationsIter(ConceptProto.Role.Relations.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res players() {
Stream<ai.grakn.concept.Type> concepts = concept.asRole().players();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setRolePlayersIterRes(ConceptProto.Role.Players.Iter.Res.newBuilder()
.setType(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRolePlayersIter(ConceptProto.Role.Players.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.Type}
*/
private class Type {
private Transaction.Res instances() {
Stream<? extends ai.grakn.concept.Thing> concepts = concept.asType().instances();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setTypeInstancesIterRes(ConceptProto.Type.Instances.Iter.Res.newBuilder()
.setThing(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setTypeInstancesIter(ConceptProto.Type.Instances.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res isAbstract() {
Boolean isAbstract = concept.asType().isAbstract();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setTypeIsAbstractRes(ConceptProto.Type.IsAbstract.Res.newBuilder()
.setAbstract(isAbstract)).build();
return transactionRes(response);
}
private Transaction.Res isAbstract(boolean isAbstract) {
concept.asType().isAbstract(isAbstract);
return null;
}
private Transaction.Res keys() {
Stream<ai.grakn.concept.AttributeType> concepts = concept.asType().keys();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setTypeKeysIterRes(ConceptProto.Type.Keys.Iter.Res.newBuilder()
.setAttributeType(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setTypeKeysIter(ConceptProto.Type.Keys.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res attributes() {
Stream<ai.grakn.concept.AttributeType> concepts = concept.asType().attributes();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setTypeAttributesIterRes(ConceptProto.Type.Attributes.Iter.Res.newBuilder()
.setAttributeType(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setTypeAttributesIter(ConceptProto.Type.Attributes.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res playing() {
Stream<ai.grakn.concept.Role> concepts = concept.asType().playing();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setTypePlayingIterRes(ConceptProto.Type.Playing.Iter.Res.newBuilder()
.setRole(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setTypePlayingIter(ConceptProto.Type.Playing.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res key(ConceptProto.Concept protoKey) {
ai.grakn.concept.AttributeType<?> attributeType = convert(protoKey).asAttributeType();
concept.asType().key(attributeType);
return null;
}
private Transaction.Res has(ConceptProto.Concept protoAttribute) {
ai.grakn.concept.AttributeType<?> attributeType = convert(protoAttribute).asAttributeType();
concept.asType().has(attributeType);
return null;
}
private Transaction.Res plays(ConceptProto.Concept protoRole) {
ai.grakn.concept.Role role = convert(protoRole).asRole();
concept.asType().plays(role);
return null;
}
private Transaction.Res unkey(ConceptProto.Concept protoKey) {
ai.grakn.concept.AttributeType<?> attributeType = convert(protoKey).asAttributeType();
concept.asType().unkey(attributeType);
return null;
}
private Transaction.Res unhas(ConceptProto.Concept protoAttribute) {
ai.grakn.concept.AttributeType<?> attributeType = convert(protoAttribute).asAttributeType();
concept.asType().unhas(attributeType);
return null;
}
private Transaction.Res unplay(ConceptProto.Concept protoRole) {
ai.grakn.concept.Role role = convert(protoRole).asRole();
concept.asType().unplay(role);
return null;
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.EntityType}
*/
private class EntityType {
private Transaction.Res create() {
Entity entity = concept.asEntityType().create();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setEntityTypeCreateRes(ConceptProto.EntityType.Create.Res.newBuilder()
.setEntity(ResponseBuilder.Concept.concept(entity))).build();
return transactionRes(response);
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.RelationshipType}
*/
private class RelationshipType {
private Transaction.Res create() {
ai.grakn.concept.Relationship relationship = concept.asRelationshipType().create();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRelationTypeCreateRes(ConceptProto.RelationType.Create.Res.newBuilder()
.setRelation(ResponseBuilder.Concept.concept(relationship))).build();
return transactionRes(response);
}
private Transaction.Res roles() {
Stream<ai.grakn.concept.Role> roles = concept.asRelationshipType().roles();
Stream<SessionProto.Transaction.Res> responses = roles.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setRelationTypeRolesIterRes(ConceptProto.RelationType.Roles.Iter.Res.newBuilder()
.setRole(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRelationTypeRolesIter(ConceptProto.RelationType.Roles.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res relates(ConceptProto.Concept protoRole) {
ai.grakn.concept.Role role = convert(protoRole).asRole();
concept.asRelationshipType().relates(role);
return null;
}
private Transaction.Res unrelate(ConceptProto.Concept protoRole) {
ai.grakn.concept.Role role = convert(protoRole).asRole();
concept.asRelationshipType().unrelate(role);
return null;
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.AttributeType}
*/
private class AttributeType {
private Transaction.Res create(ConceptProto.ValueObject protoValue) {
Object value = protoValue.getAllFields().values().iterator().next();
ai.grakn.concept.Attribute<?> attribute = concept.asAttributeType().create(value);
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setAttributeTypeCreateRes(ConceptProto.AttributeType.Create.Res.newBuilder()
.setAttribute(ResponseBuilder.Concept.concept(attribute))).build();
return transactionRes(response);
}
private Transaction.Res attribute(ConceptProto.ValueObject protoValue) {
Object value = protoValue.getAllFields().values().iterator().next();
ai.grakn.concept.Attribute<?> attribute = concept.asAttributeType().attribute(value);
ConceptProto.AttributeType.Attribute.Res.Builder methodResponse = ConceptProto.AttributeType.Attribute.Res.newBuilder();
if (attribute == null) methodResponse.setNull(ConceptProto.Null.getDefaultInstance()).build();
else methodResponse.setAttribute(ResponseBuilder.Concept.concept(attribute)).build();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setAttributeTypeAttributeRes(methodResponse).build();
return transactionRes(response);
}
private Transaction.Res dataType() {
ai.grakn.concept.AttributeType.DataType<?> dataType = concept.asAttributeType().dataType();
ConceptProto.AttributeType.DataType.Res.Builder methodResponse =
ConceptProto.AttributeType.DataType.Res.newBuilder();
if (dataType == null) methodResponse.setNull(ConceptProto.Null.getDefaultInstance()).build();
else methodResponse.setDataType(ResponseBuilder.Concept.DATA_TYPE(dataType)).build();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setAttributeTypeDataTypeRes(methodResponse).build();
return transactionRes(response);
}
private Transaction.Res regex() {
String regex = concept.asAttributeType().regex();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setAttributeTypeGetRegexRes(ConceptProto.AttributeType.GetRegex.Res.newBuilder()
.setRegex((regex != null) ? regex : "")).build();
return transactionRes(response);
}
private Transaction.Res regex(String regex) {
if (regex.isEmpty()) {
concept.asAttributeType().regex(null);
} else {
concept.asAttributeType().regex(regex);
}
return null;
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.Thing}
*/
private class Thing {
private Transaction.Res isInferred() {
Boolean inferred = concept.asThing().isInferred();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setThingIsInferredRes(ConceptProto.Thing.IsInferred.Res.newBuilder()
.setInferred(inferred)).build();
return transactionRes(response);
}
private Transaction.Res type() {
ai.grakn.concept.Concept type = concept.asThing().type();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setThingTypeRes(ConceptProto.Thing.Type.Res.newBuilder()
.setType(ResponseBuilder.Concept.concept(type))).build();
return transactionRes(response);
}
private Transaction.Res keys(List<ConceptProto.Concept> protoTypes) {
ai.grakn.concept.AttributeType<?>[] keyTypes = protoTypes.stream()
.map(rpcConcept -> convert(rpcConcept))
.toArray(ai.grakn.concept.AttributeType[]::new);
Stream<ai.grakn.concept.Attribute<?>> concepts = concept.asThing().keys(keyTypes);
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setThingKeysIterRes(ConceptProto.Thing.Keys.Iter.Res.newBuilder()
.setAttribute(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setThingKeysIter(ConceptProto.Thing.Keys.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res attributes(List<ConceptProto.Concept> protoTypes) {
ai.grakn.concept.AttributeType<?>[] attributeTypes = protoTypes.stream()
.map(rpcConcept -> convert(rpcConcept))
.toArray(ai.grakn.concept.AttributeType[]::new);
Stream<ai.grakn.concept.Attribute<?>> concepts = concept.asThing().attributes(attributeTypes);
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setThingAttributesIterRes(ConceptProto.Thing.Attributes.Iter.Res.newBuilder()
.setAttribute(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setThingAttributesIter(ConceptProto.Thing.Attributes.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res relations(List<ConceptProto.Concept> protoRoles) {
ai.grakn.concept.Role[] roles = protoRoles.stream()
.map(rpcConcept -> convert(rpcConcept))
.toArray(ai.grakn.concept.Role[]::new);
Stream<ai.grakn.concept.Relationship> concepts = concept.asThing().relationships(roles);
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setThingRelationsIterRes(ConceptProto.Thing.Relations.Iter.Res.newBuilder()
.setRelation(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setThingRelationsIter(ConceptProto.Thing.Relations.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res roles() {
Stream<ai.grakn.concept.Role> concepts = concept.asThing().roles();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setThingRolesIterRes(ConceptProto.Thing.Roles.Iter.Res.newBuilder()
.setRole(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setThingRolesIter(ConceptProto.Thing.Roles.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res relhas(ConceptProto.Concept protoAttribute) {
ai.grakn.concept.Attribute<?> attribute = convert(protoAttribute).asAttribute();
ai.grakn.concept.Relationship relationship = ConceptHolder.this.concept.asThing().relhas(attribute);
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setThingRelhasRes(ConceptProto.Thing.Relhas.Res.newBuilder()
.setRelation(ResponseBuilder.Concept.concept(relationship))).build();
return transactionRes(response);
}
private Transaction.Res unhas(ConceptProto.Concept protoAttribute) {
ai.grakn.concept.Attribute<?> attribute = convert(protoAttribute).asAttribute();
concept.asThing().unhas(attribute);
return null;
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.Relationship}
*/
private class Relationship {
private Transaction.Res rolePlayersMap() {
Map<ai.grakn.concept.Role, Set<ai.grakn.concept.Thing>> rolePlayersMap = concept.asRelationship().rolePlayersMap();
Stream.Builder<SessionProto.Transaction.Res> responses = Stream.builder();
for (Map.Entry<ai.grakn.concept.Role, Set<ai.grakn.concept.Thing>> rolePlayers : rolePlayersMap.entrySet()) {
for (ai.grakn.concept.Thing player : rolePlayers.getValue()) {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setRelationRolePlayersMapIterRes(ConceptProto.Relation.RolePlayersMap.Iter.Res.newBuilder()
.setRole(ResponseBuilder.Concept.concept(rolePlayers.getKey()))
.setPlayer(ResponseBuilder.Concept.concept(player))).build();
responses.add(ResponseBuilder.Transaction.Iter.conceptMethod(res));
}
}
int iteratorId = iterators.add(responses.build().iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRelationRolePlayersMapIter(ConceptProto.Relation.RolePlayersMap.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res rolePlayers(List<ConceptProto.Concept> protoRoles) {
ai.grakn.concept.Role[] roles = protoRoles.stream()
.map(rpcConcept -> convert(rpcConcept))
.toArray(ai.grakn.concept.Role[]::new);
Stream<ai.grakn.concept.Thing> concepts = concept.asRelationship().rolePlayers(roles);
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setRelationRolePlayersIterRes(ConceptProto.Relation.RolePlayers.Iter.Res.newBuilder()
.setThing(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setRelationRolePlayersIter(ConceptProto.Relation.RolePlayers.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
private Transaction.Res assign(ConceptProto.Relation.Assign.Req request) {
ai.grakn.concept.Role role = convert(request.getRole()).asRole();
ai.grakn.concept.Thing player = convert(request.getPlayer()).asThing();
concept.asRelationship().assign(role, player);
return null;
}
private Transaction.Res unassign(ConceptProto.Relation.Unassign.Req request) {
ai.grakn.concept.Role role = convert(request.getRole()).asRole();
ai.grakn.concept.Thing player = convert(request.getPlayer()).asThing();
concept.asRelationship().unassign(role, player);
return null;
}
}
/**
* A utility class to execute methods on {@link ai.grakn.concept.Attribute}
*/
private class Attribute {
private Transaction.Res value() {
Object value = concept.asAttribute().value();
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setAttributeValueRes(ConceptProto.Attribute.Value.Res.newBuilder()
.setValue(ResponseBuilder.Concept.attributeValue(value))).build();
return transactionRes(response);
}
private Transaction.Res owners() {
Stream<ai.grakn.concept.Thing> concepts = concept.asAttribute().owners();
Stream<SessionProto.Transaction.Res> responses = concepts.map(con -> {
ConceptProto.Method.Iter.Res res = ConceptProto.Method.Iter.Res.newBuilder()
.setAttributeOwnersIterRes(ConceptProto.Attribute.Owners.Iter.Res.newBuilder()
.setThing(ResponseBuilder.Concept.concept(con))).build();
return ResponseBuilder.Transaction.Iter.conceptMethod(res);
});
int iteratorId = iterators.add(responses.iterator());
ConceptProto.Method.Res response = ConceptProto.Method.Res.newBuilder()
.setAttributeOwnersIter(ConceptProto.Attribute.Owners.Iter.newBuilder()
.setId(iteratorId)).build();
return transactionRes(response);
}
}
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/rpc/KeyspaceService.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.rpc;
import ai.grakn.Keyspace;
import ai.grakn.engine.KeyspaceStore;
import ai.grakn.rpc.proto.KeyspaceProto;
import ai.grakn.rpc.proto.KeyspaceServiceGrpc;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.util.stream.Collectors;
/**
* Grakn RPC Keyspace Service
*/
public class KeyspaceService extends KeyspaceServiceGrpc.KeyspaceServiceImplBase {
private final KeyspaceStore keyspaceStore;
public KeyspaceService(KeyspaceStore keyspaceStore) {
this.keyspaceStore = keyspaceStore;
}
@Override
public void create(KeyspaceProto.Keyspace.Create.Req request, StreamObserver<KeyspaceProto.Keyspace.Create.Res> response) {
response.onError(new StatusRuntimeException(Status.UNIMPLEMENTED));
}
@Override
public void retrieve(KeyspaceProto.Keyspace.Retrieve.Req request, StreamObserver<KeyspaceProto.Keyspace.Retrieve.Res> response) {
try {
Iterable<String> list = keyspaceStore.keyspaces().stream().map(Keyspace::getValue)
.collect(Collectors.toSet());
response.onNext(KeyspaceProto.Keyspace.Retrieve.Res.newBuilder().addAllNames(list).build());
response.onCompleted();
} catch (RuntimeException e) {
response.onError(ResponseBuilder.exception(e));
}
}
@Override
public void delete(KeyspaceProto.Keyspace.Delete.Req request, StreamObserver<KeyspaceProto.Keyspace.Delete.Res> response) {
try {
keyspaceStore.deleteKeyspace(Keyspace.of(request.getName()));
response.onNext(KeyspaceProto.Keyspace.Delete.Res.getDefaultInstance());
response.onCompleted();
} catch (RuntimeException e) {
response.onError(ResponseBuilder.exception(e));
}
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/rpc/OpenRequest.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.rpc;
import ai.grakn.kb.internal.EmbeddedGraknTx;
import ai.grakn.rpc.proto.SessionProto;
/**
* A request transaction opener for RPC Services
*/
public interface OpenRequest {
EmbeddedGraknTx<?> open(SessionProto.Transaction.Open.Req request);
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/rpc/ResponseBuilder.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.rpc;
import ai.grakn.concept.AttributeType;
import ai.grakn.concept.ConceptId;
import ai.grakn.exception.GraknBackendException;
import ai.grakn.exception.GraknException;
import ai.grakn.exception.GraknTxOperationException;
import ai.grakn.exception.GraqlQueryException;
import ai.grakn.exception.GraqlSyntaxException;
import ai.grakn.exception.InvalidKBException;
import ai.grakn.exception.PropertyNotUniqueException;
import ai.grakn.exception.TemporaryWriteException;
import ai.grakn.graql.admin.Explanation;
import ai.grakn.graql.answer.AnswerGroup;
import ai.grakn.graql.answer.ConceptList;
import ai.grakn.graql.answer.ConceptMap;
import ai.grakn.graql.answer.ConceptSet;
import ai.grakn.graql.answer.ConceptSetMeasure;
import ai.grakn.graql.answer.Value;
import ai.grakn.rpc.proto.AnswerProto;
import ai.grakn.rpc.proto.ConceptProto;
import ai.grakn.rpc.proto.SessionProto;
import ai.grakn.util.CommonUtil;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import javax.annotation.Nullable;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.stream.Collectors;
/**
* A utility class to build RPC Responses from a provided set of Grakn concepts.
*/
public class ResponseBuilder {
/**
* An RPC Response Builder class for Transaction responses
*/
public static class Transaction {
static SessionProto.Transaction.Res open() {
return SessionProto.Transaction.Res.newBuilder()
.setOpenRes(SessionProto.Transaction.Open.Res.getDefaultInstance())
.build();
}
static SessionProto.Transaction.Res commit() {
return SessionProto.Transaction.Res.newBuilder()
.setCommitRes(SessionProto.Transaction.Commit.Res.getDefaultInstance())
.build();
}
static SessionProto.Transaction.Res queryIterator(int iteratorId) {
return SessionProto.Transaction.Res.newBuilder()
.setQueryIter(SessionProto.Transaction.Query.Iter.newBuilder().setId(iteratorId))
.build();
}
static SessionProto.Transaction.Res getSchemaConcept(@Nullable ai.grakn.concept.Concept concept) {
SessionProto.Transaction.GetSchemaConcept.Res.Builder res = SessionProto.Transaction.GetSchemaConcept.Res.newBuilder();
if (concept == null) {
res.setNull(ConceptProto.Null.getDefaultInstance());
} else {
res.setSchemaConcept(ResponseBuilder.Concept.concept(concept));
}
return SessionProto.Transaction.Res.newBuilder().setGetSchemaConceptRes(res).build();
}
static SessionProto.Transaction.Res getConcept(@Nullable ai.grakn.concept.Concept concept) {
SessionProto.Transaction.GetConcept.Res.Builder res = SessionProto.Transaction.GetConcept.Res.newBuilder();
if (concept == null) {
res.setNull(ConceptProto.Null.getDefaultInstance());
} else {
res.setConcept(ResponseBuilder.Concept.concept(concept));
}
return SessionProto.Transaction.Res.newBuilder().setGetConceptRes(res).build();
}
static SessionProto.Transaction.Res getAttributesIterator(int iteratorId) {
SessionProto.Transaction.GetAttributes.Iter.Builder res = SessionProto.Transaction.GetAttributes.Iter.newBuilder()
.setId(iteratorId);
return SessionProto.Transaction.Res.newBuilder().setGetAttributesIter(res).build();
}
static SessionProto.Transaction.Res putEntityType(ai.grakn.concept.Concept concept) {
SessionProto.Transaction.PutEntityType.Res.Builder res = SessionProto.Transaction.PutEntityType.Res.newBuilder()
.setEntityType(ResponseBuilder.Concept.concept(concept));
return SessionProto.Transaction.Res.newBuilder().setPutEntityTypeRes(res).build();
}
static SessionProto.Transaction.Res putAttributeType(ai.grakn.concept.Concept concept) {
SessionProto.Transaction.PutAttributeType.Res.Builder res = SessionProto.Transaction.PutAttributeType.Res.newBuilder()
.setAttributeType(ResponseBuilder.Concept.concept(concept));
return SessionProto.Transaction.Res.newBuilder().setPutAttributeTypeRes(res).build();
}
static SessionProto.Transaction.Res putRelationshipType(ai.grakn.concept.Concept concept) {
SessionProto.Transaction.PutRelationType.Res.Builder res = SessionProto.Transaction.PutRelationType.Res.newBuilder()
.setRelationType(ResponseBuilder.Concept.concept(concept));
return SessionProto.Transaction.Res.newBuilder().setPutRelationTypeRes(res).build();
}
static SessionProto.Transaction.Res putRole(ai.grakn.concept.Concept concept) {
SessionProto.Transaction.PutRole.Res.Builder res = SessionProto.Transaction.PutRole.Res.newBuilder()
.setRole(ResponseBuilder.Concept.concept(concept));
return SessionProto.Transaction.Res.newBuilder().setPutRoleRes(res).build();
}
static SessionProto.Transaction.Res putRule(ai.grakn.concept.Concept concept) {
SessionProto.Transaction.PutRule.Res.Builder res = SessionProto.Transaction.PutRule.Res.newBuilder()
.setRule(ResponseBuilder.Concept.concept(concept));
return SessionProto.Transaction.Res.newBuilder().setPutRuleRes(res).build();
}
/**
* An RPC Response Builder class for Transaction iterator responses
*/
static class Iter {
static SessionProto.Transaction.Res query(Object object) {
return SessionProto.Transaction.Res.newBuilder()
.setIterateRes(SessionProto.Transaction.Iter.Res.newBuilder()
.setQueryIterRes(SessionProto.Transaction.Query.Iter.Res.newBuilder()
.setAnswer(Answer.answer(object)))).build();
}
static SessionProto.Transaction.Res getAttributes(ai.grakn.concept.Concept concept) {
return SessionProto.Transaction.Res.newBuilder()
.setIterateRes(SessionProto.Transaction.Iter.Res.newBuilder()
.setGetAttributesIterRes(SessionProto.Transaction.GetAttributes.Iter.Res.newBuilder()
.setAttribute(Concept.concept(concept)))).build();
}
static SessionProto.Transaction.Res conceptMethod(ConceptProto.Method.Iter.Res methodResponse) {
return SessionProto.Transaction.Res.newBuilder()
.setIterateRes(SessionProto.Transaction.Iter.Res.newBuilder()
.setConceptMethodIterRes(methodResponse)).build();
}
}
}
/**
* An RPC Response Builder class for Concept responses
*/
public static class Concept {
public static ConceptProto.Concept concept(ai.grakn.concept.Concept concept) {
return ConceptProto.Concept.newBuilder()
.setId(concept.id().getValue())
.setBaseType(getBaseType(concept))
.build();
}
private static ConceptProto.Concept.BASE_TYPE getBaseType(ai.grakn.concept.Concept concept) {
if (concept.isEntityType()) {
return ConceptProto.Concept.BASE_TYPE.ENTITY_TYPE;
} else if (concept.isRelationshipType()) {
return ConceptProto.Concept.BASE_TYPE.RELATION_TYPE;
} else if (concept.isAttributeType()) {
return ConceptProto.Concept.BASE_TYPE.ATTRIBUTE_TYPE;
} else if (concept.isEntity()) {
return ConceptProto.Concept.BASE_TYPE.ENTITY;
} else if (concept.isRelationship()) {
return ConceptProto.Concept.BASE_TYPE.RELATION;
} else if (concept.isAttribute()) {
return ConceptProto.Concept.BASE_TYPE.ATTRIBUTE;
} else if (concept.isRole()) {
return ConceptProto.Concept.BASE_TYPE.ROLE;
} else if (concept.isRule()) {
return ConceptProto.Concept.BASE_TYPE.RULE;
} else if (concept.isType()) {
return ConceptProto.Concept.BASE_TYPE.META_TYPE;
} else {
throw CommonUtil.unreachableStatement("Unrecognised concept " + concept);
}
}
static ConceptProto.AttributeType.DATA_TYPE DATA_TYPE(AttributeType.DataType<?> dataType) {
if (dataType.equals(AttributeType.DataType.STRING)) {
return ConceptProto.AttributeType.DATA_TYPE.STRING;
} else if (dataType.equals(AttributeType.DataType.BOOLEAN)) {
return ConceptProto.AttributeType.DATA_TYPE.BOOLEAN;
} else if (dataType.equals(AttributeType.DataType.INTEGER)) {
return ConceptProto.AttributeType.DATA_TYPE.INTEGER;
} else if (dataType.equals(AttributeType.DataType.LONG)) {
return ConceptProto.AttributeType.DATA_TYPE.LONG;
} else if (dataType.equals(AttributeType.DataType.FLOAT)) {
return ConceptProto.AttributeType.DATA_TYPE.FLOAT;
} else if (dataType.equals(AttributeType.DataType.DOUBLE)) {
return ConceptProto.AttributeType.DATA_TYPE.DOUBLE;
} else if (dataType.equals(AttributeType.DataType.DATE)) {
return ConceptProto.AttributeType.DATA_TYPE.DATE;
} else {
throw CommonUtil.unreachableStatement("Unrecognised " + dataType);
}
}
public static AttributeType.DataType<?> DATA_TYPE(ConceptProto.AttributeType.DATA_TYPE dataType) {
switch (dataType) {
case STRING:
return AttributeType.DataType.STRING;
case BOOLEAN:
return AttributeType.DataType.BOOLEAN;
case INTEGER:
return AttributeType.DataType.INTEGER;
case LONG:
return AttributeType.DataType.LONG;
case FLOAT:
return AttributeType.DataType.FLOAT;
case DOUBLE:
return AttributeType.DataType.DOUBLE;
case DATE:
return AttributeType.DataType.DATE;
default:
case UNRECOGNIZED:
throw new IllegalArgumentException("Unrecognised " + dataType);
}
}
static ConceptProto.ValueObject attributeValue(Object value) {
ConceptProto.ValueObject.Builder builder = ConceptProto.ValueObject.newBuilder();
if (value instanceof String) {
builder.setString((String) value);
} else if (value instanceof Boolean) {
builder.setBoolean((boolean) value);
} else if (value instanceof Integer) {
builder.setInteger((int) value);
} else if (value instanceof Long) {
builder.setLong((long) value);
} else if (value instanceof Float) {
builder.setFloat((float) value);
} else if (value instanceof Double) {
builder.setDouble((double) value);
} else if (value instanceof LocalDateTime) {
builder.setDate(((LocalDateTime) value).atZone(ZoneId.of("Z")).toInstant().toEpochMilli());
} else {
throw CommonUtil.unreachableStatement("Unrecognised " + value);
}
return builder.build();
}
}
/**
* An RPC Response Builder class for Answer responses
*/
public static class Answer {
public static AnswerProto.Answer answer(Object object) {
AnswerProto.Answer.Builder answer = AnswerProto.Answer.newBuilder();
if (object instanceof AnswerGroup) {
answer.setAnswerGroup(answerGroup((AnswerGroup) object));
} else if (object instanceof ConceptMap) {
answer.setConceptMap(conceptMap((ConceptMap) object));
} else if (object instanceof ConceptList) {
answer.setConceptList(conceptList((ConceptList) object));
} else if (object instanceof ConceptSetMeasure) {
answer.setConceptSetMeasure(conceptSetMeasure((ConceptSetMeasure) object));
} else if (object instanceof ConceptSet) {
answer.setConceptSet(conceptSet((ConceptSet) object));
} else if (object instanceof Value) {
answer.setValue(value((Value) object));
}
return answer.build();
}
static AnswerProto.Explanation explanation(Explanation explanation) {
AnswerProto.Explanation.Builder builder = AnswerProto.Explanation.newBuilder()
.addAllAnswers(explanation.getAnswers().stream().map(Answer::conceptMap)
.collect(Collectors.toList()));
if (explanation.getQuery() != null) builder.setPattern(explanation.getQuery().getPattern().toString());
return builder.build();
}
static AnswerProto.AnswerGroup answerGroup(AnswerGroup<?> answer) {
AnswerProto.AnswerGroup.Builder answerGroupProto = AnswerProto.AnswerGroup.newBuilder()
.setOwner(ResponseBuilder.Concept.concept(answer.owner()))
.addAllAnswers(answer.answers().stream().map(Answer::answer).collect(Collectors.toList()));
// TODO: answer.explanation should return null, rather than an instance where .getQuery() returns null
if (answer.explanation() != null && !answer.explanation().isEmpty()) {
answerGroupProto.setExplanation(explanation(answer.explanation()));
}
return answerGroupProto.build();
}
static AnswerProto.ConceptMap conceptMap(ConceptMap answer) {
AnswerProto.ConceptMap.Builder conceptMapProto = AnswerProto.ConceptMap.newBuilder();
answer.map().forEach((var, concept) -> {
ConceptProto.Concept conceptProto = ResponseBuilder.Concept.concept(concept);
conceptMapProto.putMap(var.getValue(), conceptProto);
});
// TODO: answer.explanation should return null, rather than an instance where .getQuery() returns null
if (answer.explanation() != null && !answer.explanation().isEmpty()) {
conceptMapProto.setExplanation(explanation(answer.explanation()));
}
return conceptMapProto.build();
}
static AnswerProto.ConceptList conceptList(ConceptList answer) {
AnswerProto.ConceptList.Builder conceptListProto = AnswerProto.ConceptList.newBuilder();
conceptListProto.setList(conceptIds(answer.list()));
// TODO: answer.explanation should return null, rather than an instance where .getQuery() returns null
if (answer.explanation() != null && !answer.explanation().isEmpty()) {
conceptListProto.setExplanation(explanation(answer.explanation()));
}
return conceptListProto.build();
}
static AnswerProto.ConceptSet conceptSet(ConceptSet answer) {
AnswerProto.ConceptSet.Builder conceptSetProto = AnswerProto.ConceptSet.newBuilder();
conceptSetProto.setSet(conceptIds(answer.set()));
// TODO: answer.explanation should return null, rather than an instance where .getQuery() returns null
if (answer.explanation() != null && !answer.explanation().isEmpty()) {
conceptSetProto.setExplanation(explanation(answer.explanation()));
}
return conceptSetProto.build();
}
static AnswerProto.ConceptSetMeasure conceptSetMeasure(ConceptSetMeasure answer) {
AnswerProto.ConceptSetMeasure.Builder conceptSetMeasureProto = AnswerProto.ConceptSetMeasure.newBuilder();
conceptSetMeasureProto.setSet(conceptIds(answer.set()));
conceptSetMeasureProto.setMeasurement(number(answer.measurement()));
if (answer.explanation() != null && !answer.explanation().isEmpty()) {
conceptSetMeasureProto.setExplanation(explanation(answer.explanation()));
}
return conceptSetMeasureProto.build();
}
static AnswerProto.Value value(Value answer) {
AnswerProto.Value.Builder valueProto = AnswerProto.Value.newBuilder();
valueProto.setNumber(number(answer.number()));
// TODO: answer.explanation should return null, rather than an instance where .getQuery() returns null
if (answer.explanation() != null && !answer.explanation().isEmpty()) {
valueProto.setExplanation(explanation(answer.explanation()));
}
return valueProto.build();
}
static AnswerProto.Number number(Number number) {
return AnswerProto.Number.newBuilder().setValue(number.toString()).build();
}
private static AnswerProto.ConceptIds conceptIds(Collection<ConceptId> conceptIds) {
AnswerProto.ConceptIds.Builder conceptIdsRPC = AnswerProto.ConceptIds.newBuilder();
conceptIdsRPC.addAllIds(conceptIds.stream()
.map(id -> id.getValue())
.collect(Collectors.toList()));
return conceptIdsRPC.build();
}
}
public static StatusRuntimeException exception(Throwable e) {
if (e instanceof GraknException) {
GraknException ge = (GraknException) e;
String message = ge.getName() + "-" + ge.getMessage();
if (e instanceof TemporaryWriteException) {
return exception(Status.RESOURCE_EXHAUSTED, message);
} else if (e instanceof GraknBackendException) {
return exception(Status.INTERNAL, message);
} else if (e instanceof PropertyNotUniqueException) {
return exception(Status.ALREADY_EXISTS, message);
} else if (e instanceof GraknTxOperationException | e instanceof GraqlQueryException |
e instanceof GraqlSyntaxException | e instanceof InvalidKBException) {
return exception(Status.INVALID_ARGUMENT, message);
}
} else if (e instanceof StatusRuntimeException) {
return (StatusRuntimeException) e;
}
return exception(Status.UNKNOWN, e.getMessage());
}
private static StatusRuntimeException exception(Status status, String message) {
return exception(status.withDescription(message + ". Please check server logs for the stack trace."));
}
public static StatusRuntimeException exception(Status status) {
return new StatusRuntimeException(status);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/rpc/ServerOpenRequest.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.rpc;
import ai.grakn.GraknTxType;
import ai.grakn.Keyspace;
import ai.grakn.engine.factory.EngineGraknTxFactory;
import ai.grakn.kb.internal.EmbeddedGraknTx;
import ai.grakn.rpc.proto.SessionProto;
/**
* A request transaction opener for RPC Services. It requires the keyspace and transaction type from the argument object
* to open a new transaction.
*/
public class ServerOpenRequest implements OpenRequest {
private final EngineGraknTxFactory txFactory;
public ServerOpenRequest(EngineGraknTxFactory txFactory) {
this.txFactory = txFactory;
}
@Override
public EmbeddedGraknTx<?> open(SessionProto.Transaction.Open.Req request) {
Keyspace keyspace = Keyspace.of(request.getKeyspace());
GraknTxType txType = GraknTxType.of(request.getType().getNumber());
return txFactory.tx(keyspace, txType);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/rpc/SessionService.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.rpc;
import ai.grakn.concept.Attribute;
import ai.grakn.concept.AttributeType;
import ai.grakn.concept.Concept;
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.concept.Rule;
import ai.grakn.engine.ServerRPC;
import ai.grakn.engine.attribute.deduplicator.AttributeDeduplicatorDaemon;
import ai.grakn.graql.Graql;
import ai.grakn.graql.Pattern;
import ai.grakn.graql.Query;
import ai.grakn.kb.internal.EmbeddedGraknTx;
import ai.grakn.rpc.proto.SessionProto;
import ai.grakn.rpc.proto.SessionProto.Transaction;
import ai.grakn.rpc.proto.SessionServiceGrpc;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
/**
* Grakn RPC Session Service
*/
public class SessionService extends SessionServiceGrpc.SessionServiceImplBase {
private final OpenRequest requestOpener;
private AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon;
public SessionService(OpenRequest requestOpener, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon) {
this.requestOpener = requestOpener;
this.AttributeDeduplicatorDaemon = AttributeDeduplicatorDaemon;
}
public StreamObserver<Transaction.Req> transaction(StreamObserver<Transaction.Res> responseSender) {
return TransactionListener.create(responseSender, requestOpener, AttributeDeduplicatorDaemon);
}
/**
* A {@link StreamObserver} that implements the transaction-handling behaviour for {@link ServerRPC}.
* Receives a stream of {@link Transaction.Req}s and returning a stream of {@link Transaction.Res}s.
*/
static class TransactionListener implements StreamObserver<Transaction.Req> {
final Logger LOG = LoggerFactory.getLogger(TransactionListener.class);
private final StreamObserver<Transaction.Res> responseSender;
private final AtomicBoolean terminated = new AtomicBoolean(false);
private final ExecutorService threadExecutor;
private final OpenRequest requestOpener;
private AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon;
private final Iterators iterators = Iterators.create();
@Nullable
private EmbeddedGraknTx<?> tx = null;
private TransactionListener(StreamObserver<Transaction.Res> responseSender, ExecutorService threadExecutor, OpenRequest requestOpener, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon) {
this.responseSender = responseSender;
this.threadExecutor = threadExecutor;
this.requestOpener = requestOpener;
this.AttributeDeduplicatorDaemon = AttributeDeduplicatorDaemon;
}
public static TransactionListener create(StreamObserver<Transaction.Res> responseSender, OpenRequest requestOpener, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon) {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("transaction-listener-%s").build();
ExecutorService threadExecutor = Executors.newSingleThreadExecutor(threadFactory);
return new TransactionListener(responseSender, threadExecutor, requestOpener, AttributeDeduplicatorDaemon);
}
private static <T> T nonNull(@Nullable T item) {
if (item == null) {
throw ResponseBuilder.exception(Status.FAILED_PRECONDITION);
} else {
return item;
}
}
@Override
public void onNext(Transaction.Req request) {
try {
submit(() -> handleRequest(request));
} catch (RuntimeException e) {
close(e);
}
}
@Override
public void onError(Throwable t) {
close(t);
}
@Override
public void onCompleted() {
close(null);
}
private void handleRequest(Transaction.Req request) {
switch (request.getReqCase()) {
case OPEN_REQ:
open(request.getOpenReq());
break;
case COMMIT_REQ:
commit();
break;
case QUERY_REQ:
query(request.getQueryReq());
break;
case ITERATE_REQ:
next(request.getIterateReq());
break;
case GETSCHEMACONCEPT_REQ:
getSchemaConcept(request.getGetSchemaConceptReq());
break;
case GETCONCEPT_REQ:
getConcept(request.getGetConceptReq());
break;
case GETATTRIBUTES_REQ:
getAttributes(request.getGetAttributesReq());
break;
case PUTENTITYTYPE_REQ:
putEntityType(request.getPutEntityTypeReq());
break;
case PUTATTRIBUTETYPE_REQ:
putAttributeType(request.getPutAttributeTypeReq());
break;
case PUTRELATIONTYPE_REQ:
putRelationshipType(request.getPutRelationTypeReq());
break;
case PUTROLE_REQ:
putRole(request.getPutRoleReq());
break;
case PUTRULE_REQ:
putRule(request.getPutRuleReq());
break;
case CONCEPTMETHOD_REQ:
conceptMethod(request.getConceptMethodReq());
break;
default:
case REQ_NOT_SET:
throw ResponseBuilder.exception(Status.INVALID_ARGUMENT);
}
}
public void close(@Nullable Throwable error) {
submit(() -> {
if (tx != null) {
tx.close();
}
});
if (!terminated.getAndSet(true)) {
if (error != null) {
LOG.error("Runtime Exception in RPC TransactionListener: ", error);
responseSender.onError(ResponseBuilder.exception(error));
} else {
responseSender.onCompleted();
}
}
threadExecutor.shutdown();
}
private void submit(Runnable runnable) {
try {
threadExecutor.submit(runnable).get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
throw new RuntimeException(cause);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void open(SessionProto.Transaction.Open.Req request) {
if (tx != null) {
throw ResponseBuilder.exception(Status.FAILED_PRECONDITION);
}
tx = requestOpener.open(request);
responseSender.onNext(ResponseBuilder.Transaction.open());
}
private void commit() {
tx().commitAndGetLogs().ifPresent(commitLog ->
commitLog.attributes().forEach((attributeIndex, conceptIds) ->
conceptIds.forEach(id -> AttributeDeduplicatorDaemon.markForDeduplication(commitLog.keyspace(), attributeIndex, id))
));
responseSender.onNext(ResponseBuilder.Transaction.commit());
}
private void query(SessionProto.Transaction.Query.Req request) {
Query<?> query = tx().graql()
.infer(request.getInfer().equals(Transaction.Query.INFER.TRUE))
.parse(request.getQuery());
Stream<Transaction.Res> responseStream = query.stream().map(ResponseBuilder.Transaction.Iter::query);
Transaction.Res response = ResponseBuilder.Transaction.queryIterator(iterators.add(responseStream.iterator()));
responseSender.onNext(response);
}
private void getSchemaConcept(SessionProto.Transaction.GetSchemaConcept.Req request) {
Concept concept = tx().getSchemaConcept(Label.of(request.getLabel()));
responseSender.onNext(ResponseBuilder.Transaction.getSchemaConcept(concept));
}
private void getConcept(SessionProto.Transaction.GetConcept.Req request) {
Concept concept = tx().getConcept(ConceptId.of(request.getId()));
responseSender.onNext(ResponseBuilder.Transaction.getConcept(concept));
}
private void getAttributes(SessionProto.Transaction.GetAttributes.Req request) {
Object value = request.getValue().getAllFields().values().iterator().next();
Collection<Attribute<Object>> attributes = tx().getAttributesByValue(value);
Iterator<Transaction.Res> iterator = attributes.stream().map(ResponseBuilder.Transaction.Iter::getAttributes).iterator();
int iteratorId = iterators.add(iterator);
responseSender.onNext(ResponseBuilder.Transaction.getAttributesIterator(iteratorId));
}
private void putEntityType(SessionProto.Transaction.PutEntityType.Req request) {
EntityType entityType = tx().putEntityType(Label.of(request.getLabel()));
responseSender.onNext(ResponseBuilder.Transaction.putEntityType(entityType));
}
private void putAttributeType(SessionProto.Transaction.PutAttributeType.Req request) {
Label label = Label.of(request.getLabel());
AttributeType.DataType<?> dataType = ResponseBuilder.Concept.DATA_TYPE(request.getDataType());
AttributeType<?> attributeType = tx().putAttributeType(label, dataType);
responseSender.onNext(ResponseBuilder.Transaction.putAttributeType(attributeType));
}
private void putRelationshipType(SessionProto.Transaction.PutRelationType.Req request) {
RelationshipType relationshipType = tx().putRelationshipType(Label.of(request.getLabel()));
responseSender.onNext(ResponseBuilder.Transaction.putRelationshipType(relationshipType));
}
private void putRole(SessionProto.Transaction.PutRole.Req request) {
Role role = tx().putRole(Label.of(request.getLabel()));
responseSender.onNext(ResponseBuilder.Transaction.putRole(role));
}
private void putRule(SessionProto.Transaction.PutRule.Req request) {
Label label = Label.of(request.getLabel());
Pattern when = Graql.parser().parsePattern(request.getWhen());
Pattern then = Graql.parser().parsePattern(request.getThen());
Rule rule = tx().putRule(label, when, then);
responseSender.onNext(ResponseBuilder.Transaction.putRule(rule));
}
private EmbeddedGraknTx<?> tx() {
return nonNull(tx);
}
private void conceptMethod(SessionProto.Transaction.ConceptMethod.Req request) {
Concept concept = nonNull(tx().getConcept(ConceptId.of(request.getId())));
Transaction.Res response = ConceptMethod.run(concept, request.getMethod(), iterators, tx());
responseSender.onNext(response);
}
private void next(SessionProto.Transaction.Iter.Req iterate) {
int iteratorId = iterate.getId();
Transaction.Res response = iterators.next(iteratorId);
if (response == null) throw ResponseBuilder.exception(Status.FAILED_PRECONDITION);
responseSender.onNext(response);
}
}
/**
* Contains a mutable map of iterators of {@link Transaction.Res}s for gRPC. These iterators are used for returning
* lazy, streaming responses such as for Graql query results.
*/
public static class Iterators {
private final AtomicInteger iteratorIdCounter = new AtomicInteger(1);
private final Map<Integer, Iterator<Transaction.Res>> iterators = new ConcurrentHashMap<>();
public static Iterators create() {
return new Iterators();
}
public int add(Iterator<Transaction.Res> iterator) {
int iteratorId = iteratorIdCounter.getAndIncrement();
iterators.put(iteratorId, iterator);
return iteratorId;
}
public Transaction.Res next(int iteratorId) {
Iterator<Transaction.Res> iterator = iterators.get(iteratorId);
if (iterator == null) return null;
Transaction.Res response;
if (iterator.hasNext()) {
response = iterator.next();
} else {
response = SessionProto.Transaction.Res.newBuilder()
.setIterateRes(SessionProto.Transaction.Iter.Res.newBuilder()
.setDone(true)).build();
stop(iteratorId);
}
return response;
}
public void stop(int iteratorId) {
iterators.remove(iteratorId);
}
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/util/AutoValue_EngineID.java
|
package ai.grakn.engine.util;
import com.fasterxml.jackson.annotation.JsonValue;
import javax.annotation.CheckReturnValue;
import javax.annotation.Generated;
@Generated("com.google.auto.value.processor.AutoValueProcessor")
final class AutoValue_EngineID extends EngineID {
private final String value;
AutoValue_EngineID(
String value) {
if (value == null) {
throw new NullPointerException("Null value");
}
this.value = value;
}
@CheckReturnValue
@JsonValue
@Override
public String getValue() {
return value;
}
@Override
public String toString() {
return "EngineID{"
+ "value=" + value
+ "}";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof EngineID) {
EngineID that = (EngineID) o;
return (this.value.equals(that.getValue()));
}
return false;
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= this.value.hashCode();
return h;
}
private static final long serialVersionUID = 8846772120873129437L;
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/util/EngineID.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.util;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.auto.value.AutoValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.CheckReturnValue;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;
/**
* <p>
* Assigns a random ID to the current instance of Engine.
* </p>
*
* @author Denis Lobanov, Felix Chapman
*/
@AutoValue
public abstract class EngineID implements Serializable {
private static final long serialVersionUID = 8846772120873129437L;
private static final Logger LOG = LoggerFactory.getLogger(EngineID.class);
@CheckReturnValue
@JsonValue
public abstract String getValue();
@CheckReturnValue
public static EngineID of(String value) {
return new AutoValue_EngineID(value);
}
@CheckReturnValue
public static EngineID me() {
String hostName = "";
try {
hostName = InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e) {
LOG.error("Could not get system hostname: ", e);
}
String value = hostName+"-"+UUID.randomUUID().toString();
return EngineID.of(value);
}
}
|
0
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine
|
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/util/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/>.
*/
/**
* Implementation of internal engine utilities.
*/
package ai.grakn.engine.util;
|
0
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn/factory/JanusPreviousPropertyStep.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.factory;
import org.apache.tinkerpop.gremlin.process.traversal.Pop;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.step.Scoping;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.FlatMapStep;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.structure.util.StringFactory;
import org.janusgraph.core.JanusGraphTransaction;
import org.janusgraph.core.JanusGraphVertex;
import org.janusgraph.graphdb.tinkerpop.optimize.JanusGraphTraversalUtil;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import static java.util.Collections.emptyIterator;
/**
* Optimise a particular traversal in Janus:
* <p>
* <code>
* g.V().outE().values(c).as(b).V().filter(__.properties(a).where(P.eq(b)));
* </code>
* <p>
* This step can be used in place of {@code V().filter(..)} since we are referring to a previously visited property in
* the traversal.
*
* @author Felix Chapman
*/
class JanusPreviousPropertyStep<S> extends FlatMapStep<S, JanusGraphVertex> implements Scoping {
private static final long serialVersionUID = -8906462828437711078L;
private final String propertyKey;
private final String stepLabel;
/**
* @param traversal the traversal that contains this step
* @param propertyKey the property key that we are looking up
* @param stepLabel
* the step label that refers to a previously visited value in the traversal.
* e.g. in {@code g.V().as(b)}, {@code b} is a step label.
*/
JanusPreviousPropertyStep(Traversal.Admin traversal, String propertyKey, String stepLabel) {
super(traversal);
this.propertyKey = Objects.requireNonNull(propertyKey);
this.stepLabel = Objects.requireNonNull(stepLabel);
}
@Override
protected Iterator<JanusGraphVertex> flatMap(Traverser.Admin<S> traverser) {
JanusGraphTransaction tx = JanusGraphTraversalUtil.getTx(this.traversal);
// Retrieve property value to look-up, that is identified in the traversal by the `stepLabel`
Object value = getNullableScopeValue(Pop.first, stepLabel, traverser);
return value != null ? verticesWithProperty(tx, value) : emptyIterator();
}
/**
* Look up vertices in Janus which have a property {@link JanusPreviousPropertyStep#propertyKey} with the given
* value.
* @param tx the Janus transaction to read from
* @param value the value that the property should have
*/
private Iterator<JanusGraphVertex> verticesWithProperty(JanusGraphTransaction tx, Object value) {
return tx.query().has(propertyKey, value).vertices().iterator();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
JanusPreviousPropertyStep<?> that = (JanusPreviousPropertyStep<?>) o;
return propertyKey.equals(that.propertyKey) && stepLabel.equals(that.stepLabel);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + propertyKey.hashCode();
result = 31 * result + stepLabel.hashCode();
return result;
}
@Override
public String toString() {
return StringFactory.stepString(this, propertyKey, stepLabel);
}
@Override
public Set<String> getScopeKeys() {
return Collections.singleton(stepLabel);
}
@Override
public Set<TraverserRequirement> getRequirements() {
// This step requires being able to access previously visited properties in the traversal,
// so it needs `LABELED_PATH`.
return EnumSet.of(TraverserRequirement.LABELED_PATH);
}
}
|
0
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn/factory/JanusPreviousPropertyStepStrategy.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.factory;
import org.apache.tinkerpop.gremlin.process.traversal.Compare;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.Step;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy.ProviderOptimizationStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.TraversalFilterStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.filter.WherePredicateStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.PropertiesStep;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.AbstractTraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.List;
import java.util.Optional;
/**
* Optimisation applied to use Janus indices in the following additional case:
* <p>
* <code>
* g.V().outE().values(c).as(b).V().filter(__.properties(a).where(P.eq(b)));
* </code>
* <p>
* In this instance, the vertex can be looked up directly in Janus, joining the {@code V().filter(..)}
* steps together.
*
* @author Felix Chapman
*/
public class JanusPreviousPropertyStepStrategy
extends AbstractTraversalStrategy<ProviderOptimizationStrategy> implements ProviderOptimizationStrategy {
private static final long serialVersionUID = 6888929702831948298L;
@Override
public void apply(Traversal.Admin<?, ?> traversal) {
// Retrieve all graph (`V()`) steps - this is the step the strategy should replace
List<GraphStep> graphSteps = TraversalHelper.getStepsOfAssignableClass(GraphStep.class, traversal);
for (GraphStep graphStep : graphSteps) {
// For each graph step, confirm it follows this pattern:
// `V().filter(__.properties(a).where(P.eq(b)))`
if (!(graphStep.getNextStep() instanceof TraversalFilterStep)) continue;
TraversalFilterStep<Vertex> filterStep = (TraversalFilterStep<Vertex>) graphStep.getNextStep();
// Retrieve the filter steps e.g. `__.properties(a).where(P.eq(b))`
List<Step> steps = stepsFromFilterStep(filterStep);
if (steps.size() < 2) continue;
Step propertiesStep = steps.get(0); // This is `properties(a)`
Step whereStep = steps.get(1); // This is `filter(__.where(P.eq(b)))`
// Get the property key `a`
if (!(propertiesStep instanceof PropertiesStep)) continue;
Optional<String> propertyKey = propertyFromPropertiesStep((PropertiesStep<Vertex>) propertiesStep);
if (!propertyKey.isPresent()) continue;
// Get the step label `b`
if (!(whereStep instanceof WherePredicateStep)) continue;
Optional<String> label = labelFromWhereEqPredicate((WherePredicateStep<Vertex>) whereStep);
if (!label.isPresent()) continue;
executeStrategy(traversal, graphStep, filterStep, propertyKey.get(), label.get());
}
}
private List<Step> stepsFromFilterStep(TraversalFilterStep<Vertex> filterStep) {
// TraversalFilterStep always has exactly one child, so this is safe
return filterStep.getLocalChildren().get(0).getSteps();
}
private Optional<String> propertyFromPropertiesStep(PropertiesStep<Vertex> propertiesStep) {
String[] propertyKeys = propertiesStep.getPropertyKeys();
if (propertyKeys.length != 1) return Optional.empty();
return Optional.of(propertyKeys[0]);
}
private Optional<String> labelFromWhereEqPredicate(WherePredicateStep<Vertex> whereStep) {
Optional<P<?>> optionalPredicate = whereStep.getPredicate();
return optionalPredicate.flatMap(predicate -> {
if (!predicate.getBiPredicate().equals(Compare.eq)) return Optional.empty();
return Optional.of((String) predicate.getValue());
});
}
/**
* Replace the {@code graphStep} and {@code filterStep} with a new {@link JanusPreviousPropertyStep} in the given
* {@code traversal}.
*/
private void executeStrategy(
Traversal.Admin<?, ?> traversal, GraphStep<?, ?> graphStep, TraversalFilterStep<Vertex> filterStep,
String propertyKey, String label) {
JanusPreviousPropertyStep newStep = new JanusPreviousPropertyStep(traversal, propertyKey, label);
traversal.removeStep(filterStep);
TraversalHelper.replaceStep(graphStep, newStep, traversal);
}
}
|
0
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn/factory/TxFactoryJanus.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.factory;
import ai.grakn.GraknConfigKey;
import ai.grakn.GraknTx;
import ai.grakn.kb.internal.GraknTxJanus;
import ai.grakn.util.ErrorMessage;
import ai.grakn.util.Schema;
import com.google.common.collect.ImmutableMap;
import org.apache.tinkerpop.gremlin.process.traversal.Order;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.LazyBarrierStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.PathRetractionStrategy;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Transaction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.EdgeLabel;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.Namifiable;
import org.janusgraph.core.PropertyKey;
import org.janusgraph.core.RelationType;
import org.janusgraph.core.VertexLabel;
import org.janusgraph.core.schema.JanusGraphIndex;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.janusgraph.graphdb.database.StandardJanusGraph;
import org.janusgraph.graphdb.transaction.StandardJanusGraphTx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static java.util.Arrays.stream;
/**
* <p>
* A {@link GraknTx} on top of {@link JanusGraph}
* </p>
*
* <p>
* This produces a grakn graph on top of {@link JanusGraph}.
* The base construction process defined by {@link TxFactoryAbstract} ensures the graph factories are singletons.
* </p>
*
* @author fppt
*/
final public class TxFactoryJanus extends TxFactoryAbstract<GraknTxJanus, JanusGraph> {
private final static Logger LOG = LoggerFactory.getLogger(TxFactoryJanus.class);
private static final AtomicBoolean strategiesApplied = new AtomicBoolean(false);
private static final String JANUS_PREFIX = "janusmr.ioformat.conf.";
private static final String STORAGE_BACKEND = "storage.backend";
private static final String STORAGE_HOSTNAME = GraknConfigKey.STORAGE_HOSTNAME.name();
private static final String STORAGE_KEYSPACE = GraknConfigKey.STORAGE_KEYSPACE.name();
private static final String STORAGE_BATCH_LOADING = GraknConfigKey.STORAGE_BATCH_LOADING.name();
private static final String STORAGE_REPLICATION_FACTOR = GraknConfigKey.STORAGE_REPLICATION_FACTOR.name();
//These properties are loaded in by default and can optionally be overwritten
private static final Properties DEFAULT_PROPERTIES;
static {
String DEFAULT_CONFIG = "default-configs.properties";
DEFAULT_PROPERTIES = new Properties();
try (InputStream in = TxFactoryJanus.class.getClassLoader().getResourceAsStream(DEFAULT_CONFIG)) {
DEFAULT_PROPERTIES.load(in);
in.close();
} catch (IOException e) {
throw new RuntimeException(ErrorMessage.INVALID_PATH_TO_CONFIG.getMessage(DEFAULT_CONFIG), e);
}
}
public static Properties getDefaultProperties() {
return DEFAULT_PROPERTIES;
}
/**
* This map is used to override hidden config files.
* The key of the map refers to the key of the properties file that gets passed in which provides the value to be injected.
* The value of the map specifies the key to inject into.
*/
private static final Map<String, String> overrideMap = ImmutableMap.of(
STORAGE_BACKEND, JANUS_PREFIX + STORAGE_BACKEND,
STORAGE_HOSTNAME, JANUS_PREFIX + STORAGE_HOSTNAME,
STORAGE_REPLICATION_FACTOR, JANUS_PREFIX + STORAGE_REPLICATION_FACTOR
);
//This maps the storage backend to the needed value
private static final Map<String, String> storageBackendMapper = ImmutableMap.of("grakn-production", "cassandra");
TxFactoryJanus(EmbeddedGraknSession session) {
super(session);
}
@Override
public JanusGraph getGraphWithNewTransaction(JanusGraph graph, boolean batchloading){
if(graph.isClosed()) graph = buildTinkerPopGraph(batchloading);
if(!graph.tx().isOpen()){
graph.tx().open();
}
return graph;
}
@Override
protected GraknTxJanus buildGraknTxFromTinkerGraph(JanusGraph graph) {
return new GraknTxJanus(session(), graph);
}
@Override
protected JanusGraph buildTinkerPopGraph(boolean batchLoading) {
return newJanusGraph(batchLoading);
}
private synchronized JanusGraph newJanusGraph(boolean batchLoading){
JanusGraph JanusGraph = configureGraph(batchLoading);
buildJanusIndexes(JanusGraph);
JanusGraph.tx().onClose(Transaction.CLOSE_BEHAVIOR.ROLLBACK);
if (!strategiesApplied.getAndSet(true)) {
TraversalStrategies strategies = TraversalStrategies.GlobalCache.getStrategies(StandardJanusGraph.class);
strategies = strategies.clone().addStrategies(new JanusPreviousPropertyStepStrategy());
//TODO: find out why Tinkerpop added these strategies. They result in many NoOpBarrier steps which slowed down our queries so we had to remove them.
strategies.removeStrategies(PathRetractionStrategy.class, LazyBarrierStrategy.class);
TraversalStrategies.GlobalCache.registerStrategies(StandardJanusGraph.class, strategies);
TraversalStrategies.GlobalCache.registerStrategies(StandardJanusGraphTx.class, strategies);
}
return JanusGraph;
}
private JanusGraph configureGraph(boolean batchLoading){
JanusGraphFactory.Builder builder = JanusGraphFactory.build().
set(STORAGE_HOSTNAME, session().config().uri()).
set(STORAGE_KEYSPACE, session().keyspace().getValue()).
set(STORAGE_BATCH_LOADING, batchLoading);
//Load Defaults
DEFAULT_PROPERTIES.forEach((key, value) -> builder.set(key.toString(), value));
//Load Passed in properties
session().config().properties().forEach((key, value) -> {
//Overwrite storage
if(key.equals(STORAGE_BACKEND)){
value = storageBackendMapper.get(value);
}
//Inject properties into other default properties
if(overrideMap.containsKey(key)){
builder.set(overrideMap.get(key), value);
}
builder.set(key.toString(), value);
});
LOG.debug("Opening graph {}", session().keyspace().getValue());
return builder.open();
}
private static void buildJanusIndexes(JanusGraph graph) {
JanusGraphManagement management = graph.openManagement();
makeVertexLabels(management);
makeEdgeLabels(management);
makePropertyKeys(management);
makeIndicesVertexCentric(management);
makeIndicesComposite(management);
management.commit();
}
private static void makeEdgeLabels(JanusGraphManagement management){
for (Schema.EdgeLabel edgeLabel : Schema.EdgeLabel.values()) {
EdgeLabel label = management.getEdgeLabel(edgeLabel.getLabel());
if(label == null) {
management.makeEdgeLabel(edgeLabel.getLabel()).make();
}
}
}
private static void makeVertexLabels(JanusGraphManagement management){
for (Schema.BaseType baseType : Schema.BaseType.values()) {
VertexLabel foundLabel = management.getVertexLabel(baseType.name());
if(foundLabel == null) {
management.makeVertexLabel(baseType.name()).make();
}
}
}
private static void makeIndicesVertexCentric(JanusGraphManagement management){
ResourceBundle keys = ResourceBundle.getBundle("indices-edges");
Set<String> edgeLabels = keys.keySet();
for(String edgeLabel : edgeLabels){
String[] propertyKeyStrings = keys.getString(edgeLabel).split(",");
//Get all the property keys we need
Set<PropertyKey> propertyKeys = stream(propertyKeyStrings).map(keyId ->{
PropertyKey key = management.getPropertyKey(keyId);
if (key == null) {
throw new RuntimeException("Trying to create edge index on label [" + edgeLabel + "] but the property [" + keyId + "] does not exist");
}
return key;
}).collect(Collectors.toSet());
//Get the edge and indexing information
RelationType relationType = management.getRelationType(edgeLabel);
EdgeLabel label = management.getEdgeLabel(edgeLabel);
//Create index on each property key
for (PropertyKey key : propertyKeys) {
if (management.getRelationIndex(relationType, edgeLabel + "by" + key.name()) == null) {
management.buildEdgeIndex(label, edgeLabel + "by" + key.name(), Direction.BOTH, Order.decr, key);
}
}
//Create index on all property keys
String propertyKeyId = propertyKeys.stream().map(Namifiable::name).collect(Collectors.joining("_"));
if (management.getRelationIndex(relationType, edgeLabel + "by" + propertyKeyId) == null) {
PropertyKey [] allKeys = propertyKeys.toArray(new PropertyKey[propertyKeys.size()]);
management.buildEdgeIndex(label, edgeLabel + "by" + propertyKeyId, Direction.BOTH, Order.decr, allKeys);
}
}
}
private static void makePropertyKeys(JanusGraphManagement management){
stream(Schema.VertexProperty.values()).forEach(property ->
makePropertyKey(management, property.name(), property.getDataType()));
stream(Schema.EdgeProperty.values()).forEach(property ->
makePropertyKey(management, property.name(), property.getDataType()));
}
private static void makePropertyKey(JanusGraphManagement management, String propertyKey, Class type){
if (management.getPropertyKey(propertyKey) == null) {
management.makePropertyKey(propertyKey).dataType(type).make();
}
}
private static void makeIndicesComposite(JanusGraphManagement management){
ResourceBundle keys = ResourceBundle.getBundle("indices-composite");
Set<String> keyString = keys.keySet();
for(String propertyKeyLabel : keyString){
String indexLabel = "by" + propertyKeyLabel;
JanusGraphIndex index = management.getGraphIndex(indexLabel);
if(index == null) {
boolean isUnique = Boolean.parseBoolean(keys.getString(propertyKeyLabel));
PropertyKey key = management.getPropertyKey(propertyKeyLabel);
JanusGraphManagement.IndexBuilder indexBuilder = management.buildIndex(indexLabel, Vertex.class).addKey(key);
if (isUnique) {
indexBuilder.unique();
}
indexBuilder.buildCompositeIndex();
}
}
}
}
|
0
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn/factory/TxFactoryJanusHadoop.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.factory;
import ai.grakn.GraknConfigKey;
import ai.grakn.kb.internal.EmbeddedGraknTx;
import ai.grakn.util.ErrorMessage;
import com.google.common.collect.ImmutableMap;
import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph;
import org.apache.tinkerpop.gremlin.structure.util.GraphFactory;
import java.util.Map;
/**
* <p>
* A {@link ai.grakn.GraknTx} on top of {@link HadoopGraph}
* </p>
*
* <p>
* This produces a graph on top of {@link HadoopGraph}.
* The base construction process defined by {@link TxFactoryAbstract} 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 TxFactoryJanusHadoop extends TxFactoryAbstract<EmbeddedGraknTx<HadoopGraph>, HadoopGraph> {
/**
* This map is used to override hidden config files.
* The key of the map refers to the Janus configuration to be overridden
* The value of the map specifies the value that will be injected
*/
private static Map<String, String> overrideMap(EmbeddedGraknSession session) {
// Janus configurations
String mrPrefixConf = "janusmr.ioformat.conf.";
String graphMrPrefixConf = "janusgraphmr.ioformat.conf.";
String inputKeyspaceConf = "cassandra.input.keyspace";
String keyspaceConf = "storage.cassandra.keyspace";
String hostnameConf = "storage.hostname";
// Values
String keyspaceValue = session.keyspace().getValue();
String hostnameValue = session.config().getProperty(GraknConfigKey.STORAGE_HOSTNAME);
// build override map
return ImmutableMap.of(
mrPrefixConf + keyspaceConf, keyspaceValue,
mrPrefixConf + hostnameConf, hostnameValue,
graphMrPrefixConf + hostnameConf, hostnameValue,
graphMrPrefixConf + keyspaceConf, keyspaceValue,
inputKeyspaceConf, keyspaceValue
);
}
TxFactoryJanusHadoop(EmbeddedGraknSession session) {
super(session);
overrideMap(session()).forEach((k, v) -> session().config().properties().setProperty(k, v));
}
@Override
protected EmbeddedGraknTx<HadoopGraph> buildGraknTxFromTinkerGraph(HadoopGraph graph) {
throw new UnsupportedOperationException(ErrorMessage.CANNOT_PRODUCE_TX.getMessage(HadoopGraph.class.getName()));
}
@Override
protected HadoopGraph buildTinkerPopGraph(boolean batchLoading) {
//Load Defaults
TxFactoryJanus.getDefaultProperties().forEach((key, value) -> {
if(!session().config().properties().containsKey(key)){
session().config().properties().put(key, value);
}
});
return (HadoopGraph) GraphFactory.open(session().config().properties());
}
//TODO: Get rid of the need for batch loading parameter
@Override
protected HadoopGraph getGraphWithNewTransaction(HadoopGraph graph, boolean batchloading) {
return graph;
}
}
|
0
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn/kb
|
java-sources/ai/grakn/grakn-factory/1.4.3/ai/grakn/kb/internal/GraknTxJanus.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;
import ai.grakn.GraknTx;
import ai.grakn.GraknTxType;
import ai.grakn.concept.ConceptId;
import ai.grakn.exception.GraknBackendException;
import ai.grakn.exception.TemporaryWriteException;
import ai.grakn.factory.EmbeddedGraknSession;
import ai.grakn.kb.internal.structure.VertexElement;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphElement;
import org.janusgraph.core.JanusGraphException;
import org.janusgraph.core.util.JanusGraphCleanup;
import org.janusgraph.diskstorage.BackendException;
import org.janusgraph.diskstorage.locking.PermanentLockingException;
import org.janusgraph.diskstorage.locking.TemporaryLockingException;
import org.janusgraph.graphdb.database.StandardJanusGraph;
import java.util.function.Supplier;
/**
* <p>
* A {@link GraknTx} using {@link JanusGraph} as a vendor backend.
* </p>
*
* <p>
* Wraps up a {@link JanusGraph} as a method of storing the {@link GraknTx} object Model.
* With this vendor some issues to be aware of:
* 1. Whenever a transaction is closed if none remain open then the connection to the graph is closed permanently.
* 2. Clearing the graph explicitly closes the connection as well.
* </p>
*
* @author fppt
*/
public class GraknTxJanus extends EmbeddedGraknTx<JanusGraph> {
public GraknTxJanus(EmbeddedGraknSession session, JanusGraph graph){
super(session, graph);
}
@Override
public void openTransaction(GraknTxType txType){
super.openTransaction(txType);
if(getTinkerPopGraph().isOpen() && !getTinkerPopGraph().tx().isOpen()) getTinkerPopGraph().tx().open();
}
@Override
public boolean isTinkerPopGraphClosed() {
return getTinkerPopGraph().isClosed();
}
@Override
public int numOpenTx() {
return ((StandardJanusGraph) getTinkerPopGraph()).getOpenTransactions().size();
}
@Override
public void clearGraph() {
try {
JanusGraphCleanup.clear(getTinkerPopGraph());
} catch (BackendException e) {
throw new RuntimeException(e);
}
}
@Override
public void commitTransactionInternal(){
executeLockingMethod(() -> {
super.commitTransactionInternal();
return null;
});
}
@Override
public VertexElement addVertexElement(Schema.BaseType baseType, ConceptId... conceptIds){
return executeLockingMethod(() -> super.addVertexElement(baseType, conceptIds));
}
/**
* Executes a method which has the potential to throw a {@link TemporaryLockingException} or a {@link PermanentLockingException}.
* If the exception is thrown it is wrapped in a {@link GraknBackendException} so that the transaction can be retried.
*
* @param method The locking method to execute
*/
private <X> X executeLockingMethod(Supplier<X> method){
try {
return method.get();
} catch (JanusGraphException e){
if(e.isCausedBy(TemporaryLockingException.class) || e.isCausedBy(PermanentLockingException.class)){
throw TemporaryWriteException.temporaryLock(e);
} else {
throw GraknBackendException.unknown(e);
}
}
}
@Override
public boolean isValidElement(Element element) {
return super.isValidElement(element) && !((JanusGraphElement) element).isRemoved();
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/factory/AbstractInternalFactory.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.GraknGraph;
import ai.grakn.GraknTxType;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.graph.internal.AbstractGraknGraph;
import org.apache.tinkerpop.gremlin.structure.Graph;
import javax.annotation.CheckReturnValue;
import java.util.Objects;
import java.util.Properties;
import static javax.annotation.meta.When.NEVER;
/**
* <p>
* Defines the construction of Grakn Graphs
* <p/>
*
* <p>
* Defines the abstract construction of Grakn graphs on top of Tinkerpop Graphs.
* For this factory to function a vendor specific implementation of a graph extending
* {@link AbstractGraknGraph} must be provided. This must be provided with a matching TinkerPop {@link Graph}
* which is wrapped within the Grakn Graph
* </p>
*
* @author fppt
*
* @param <M> A Graph Graph extending {@link AbstractGraknGraph} and wrapping a Tinkerpop Graph
* @param <G> A vendor implementation of a Tinkerpop {@link Graph}
*/
abstract class AbstractInternalFactory<M extends AbstractGraknGraph<G>, G extends Graph> implements InternalFactory<G> {
protected final String keyspace;
protected final String engineUrl;
protected final Properties properties;
protected M graknGraph = null;
private M batchLoadingGraknGraph = null;
protected G graph = null;
private G batchLoadingGraph = null;
AbstractInternalFactory(String keyspace, String engineUrl, Properties properties){
Objects.requireNonNull(keyspace);
this.keyspace = keyspace.toLowerCase();
this.engineUrl = engineUrl;
this.properties = properties;
}
abstract M buildGraknGraphFromTinker(G graph);
abstract G buildTinkerPopGraph(boolean batchLoading);
@Override
public synchronized M open(GraknTxType txType){
if(GraknTxType.BATCH.equals(txType)){
checkOtherGraphOpen(graknGraph);
batchLoadingGraknGraph = getGraph(batchLoadingGraknGraph, txType);
return batchLoadingGraknGraph;
} else {
checkOtherGraphOpen(batchLoadingGraknGraph);
graknGraph = getGraph(graknGraph, txType);
return graknGraph;
}
}
private void checkOtherGraphOpen(GraknGraph otherGraph){
if(otherGraph != null && !otherGraph.isClosed()) throw GraphOperationException.transactionOpen(otherGraph);
}
protected M getGraph(M graknGraph, GraknTxType txType){
boolean batchLoading = GraknTxType.BATCH.equals(txType);
if(graknGraph == null){
graknGraph = buildGraknGraphFromTinker(getTinkerPopGraph(batchLoading));
} else {
if(!graknGraph.isClosed()) throw GraphOperationException.transactionOpen(graknGraph);
if(graknGraph.isSessionClosed()){
graknGraph = buildGraknGraphFromTinker(getTinkerPopGraph(batchLoading));
}
}
graknGraph.openTransaction(txType);
return graknGraph;
}
@Override
public synchronized G getTinkerPopGraph(boolean batchLoading){
if(batchLoading){
batchLoadingGraph = getTinkerPopGraph(batchLoadingGraph, true);
return batchLoadingGraph;
} else {
graph = getTinkerPopGraph(graph, false);
return graph;
}
}
protected G getTinkerPopGraph(G graph, boolean batchLoading){
if(graph == null){
return buildTinkerPopGraph(batchLoading);
}
return getGraphWithNewTransaction(graph, batchLoading);
}
@CheckReturnValue(when=NEVER)
protected abstract G getGraphWithNewTransaction(G graph, boolean batchloading);
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/factory/FactoryBuilder.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.util.ErrorMessage;
import org.apache.tinkerpop.shaded.minlog.Log;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
* <p>
* Builds a Grakn Graph {@link InternalFactory}
* </p>
*
* <p>
* Builds a Grakn Graph Factory which is locked to a specific keyspace and engine URL.
* This uses refection in order to dynamically build any vendor specific factory which implements the
* {@link InternalFactory} API.
*
* The factories in this class are treated as singletons.
* </p>
*
* @author fppt
*/
public class FactoryBuilder {
public static final String FACTORY_TYPE = "factory.internal";
private static final Map<String, InternalFactory<?>> openFactories = new ConcurrentHashMap<>();
private FactoryBuilder(){
throw new UnsupportedOperationException();
}
public static InternalFactory<?> getFactory(String keyspace, String engineUrl, Properties properties){
try{
String factoryType = properties.get(FACTORY_TYPE).toString();
return getFactory(factoryType, keyspace, engineUrl, properties);
} catch(MissingResourceException e){
throw new IllegalArgumentException(ErrorMessage.MISSING_FACTORY_DEFINITION.getMessage());
}
}
/**
*
* @param factoryType The string defining which factory should be used for creating the grakn graph.
* A valid example includes: ai.grakn.factory.TinkerInternalFactory
* @return A graph factory which produces the relevant expected graph.
*/
static InternalFactory<?> getFactory(String factoryType, String keyspace, String engineUrl, Properties properties){
String key = factoryType + keyspace.toLowerCase();
Log.debug("Get factory for " + key);
InternalFactory<?> factory = openFactories.get(key);
if (factory != null) {
return factory;
}
return newFactory(key, factoryType, keyspace, engineUrl, properties);
}
/**
*
* @param key A unique string identifying this factory
* @param factoryType The type of the factory to initialise. Any factory which implements {@link InternalFactory}
* @param keyspace The keyspace of the graph
* @param engineUrl The location of the running engine instance
* @param properties Additional properties to apply to the graph
* @return A new factory bound to a specific keyspace
*/
private static synchronized InternalFactory<?> newFactory(String key, String factoryType, String keyspace, String engineUrl, Properties properties){
InternalFactory<?> internalFactory;
try {
internalFactory = (InternalFactory<?>) Class.forName(factoryType)
.getDeclaredConstructor(String.class, String.class, Properties.class)
.newInstance(keyspace, engineUrl, properties);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
throw new IllegalArgumentException(ErrorMessage.INVALID_FACTORY.getMessage(factoryType), e);
}
openFactories.put(key, internalFactory);
Log.debug("New factory created " + internalFactory);
return internalFactory;
}
/**
* Clears all connections.
*/
//TODO Should this close each of the factories (and wait for all open transactions to be closed?)
//TODO Calling this from within the code causes a memory leak
public static void refresh(){
openFactories.clear();
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/factory/GraknSessionImpl.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.GraknComputer;
import ai.grakn.GraknGraph;
import ai.grakn.GraknSession;
import ai.grakn.GraknTxType;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.graph.internal.AbstractGraknGraph;
import ai.grakn.graph.internal.GraknComputerImpl;
import ai.grakn.util.ErrorMessage;
import ai.grakn.util.REST;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import static ai.grakn.util.EngineCommunicator.contactEngine;
import static ai.grakn.util.REST.Request.GRAPH_CONFIG_PARAM;
import static ai.grakn.util.REST.Request.KEYSPACE_PARAM;
import static ai.grakn.util.REST.WebPath.System.INITIALISE;
import static mjson.Json.read;
/**
* <p>
* Builds a Grakn Graph factory
* </p>
*
* <p>
* This class facilitates the construction of Grakn Graphs by determining which factory should be built.
* It does this by either defaulting to an in memory graph {@link ai.grakn.graph.internal.GraknTinkerGraph} or by
* retrieving the factory definition from engine.
*
* The deployer of engine decides on the backend and this class will handle producing the correct graphs.
* </p>
*
* @author fppt
*/
public class GraknSessionImpl implements GraknSession {
private final Logger LOG = LoggerFactory.getLogger(GraknSessionImpl.class);
private final String location;
private final String keyspace;
//References so we don't have to open a graph just to check the count of the transactions
private AbstractGraknGraph<?> graph = null;
private AbstractGraknGraph<?> graphBatch = null;
//This constructor must remain public because it is accessed via reflection
public GraknSessionImpl(String keyspace, String location){
this.location = location;
this.keyspace = keyspace;
}
@Override
public GraknGraph open(GraknTxType transactionType) {
final InternalFactory<?> factory = getConfiguredFactory();
switch (transactionType){
case READ:
case WRITE:
graph = factory.open(transactionType);
return graph;
case BATCH:
graphBatch = factory.open(transactionType);
return graphBatch;
default:
throw GraphOperationException.transactionInvalid(transactionType);
}
}
private InternalFactory<?> getConfiguredFactory(){
return configureGraphFactory(keyspace, location, REST.GraphConfig.DEFAULT);
}
/**
* @return A new or existing grakn graph compute with the defined name
*/
@Override
public GraknComputer getGraphComputer() {
InternalFactory<?> configuredFactory = configureGraphFactory(keyspace, location, REST.GraphConfig.COMPUTER);
Graph graph = configuredFactory.getTinkerPopGraph(false);
return new GraknComputerImpl(graph);
}
@Override
public void close() throws GraphOperationException {
int openTransactions = openTransactions(graph) + openTransactions(graphBatch);
if(openTransactions > 0){
LOG.warn(ErrorMessage.TRANSACTIONS_OPEN.getMessage(this.keyspace, openTransactions));
}
//Close the main graph connections
if(graph != null) graph.admin().closeSession();
if(graphBatch != null) graphBatch.admin().closeSession();
}
private int openTransactions(AbstractGraknGraph<?> graph){
if(graph == null) return 0;
return graph.numOpenTx();
}
/**
* @param keyspace The keyspace of the graph
* @param location The of where the graph is stored
* @param graphType The type of graph to produce, default, batch, or compute
* @return A new or existing grakn graph factory with the defined name connecting to the specified remote location
*/
static InternalFactory<?> configureGraphFactory(String keyspace, String location, String graphType){
if(Grakn.IN_MEMORY.equals(location)){
return configureGraphFactoryInMemory(keyspace);
} else {
return configureGraphFactoryRemote(keyspace, location, graphType);
}
}
/**
*
* @param keyspace The keyspace of the graph
* @param engineUrl The url of engine to get the graph factory config from
* @param graphType The type of graph to produce, default, batch, or compute
* @return A new or existing grakn graph factory with the defined name connecting to the specified remote location
*/
private static InternalFactory<?> configureGraphFactoryRemote(String keyspace, String engineUrl, String graphType){
String restFactoryUri = engineUrl + INITIALISE + "?" + GRAPH_CONFIG_PARAM + "=" + graphType + "&" + KEYSPACE_PARAM + "=" + keyspace;
Properties properties = new Properties();
properties.putAll(read(contactEngine(restFactoryUri, REST.HttpConn.GET_METHOD)).asMap());
return FactoryBuilder.getFactory(keyspace, engineUrl, properties);
}
/**
*
* @param keyspace The keyspace of the graph
* @return A new or existing grakn graph factory with the defined name holding the graph in memory
*/
private static InternalFactory<?> configureGraphFactoryInMemory(String keyspace){
Properties inMemoryProperties = new Properties();
inMemoryProperties.put(AbstractGraknGraph.SHARDING_THRESHOLD, 100_000);
inMemoryProperties.put(AbstractGraknGraph.NORMAL_CACHE_TIMEOUT_MS, 30_000);
inMemoryProperties.put(FactoryBuilder.FACTORY_TYPE, TinkerInternalFactory.class.getName());
return FactoryBuilder.getFactory(TinkerInternalFactory.class.getName(), keyspace, Grakn.IN_MEMORY, inMemoryProperties);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/factory/InternalFactory.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.GraknTxType;
import ai.grakn.graph.internal.AbstractGraknGraph;
import org.apache.tinkerpop.gremlin.structure.Graph;
/**
* <p>
* Graph Building Interface
* </p>
*
* <p>
* The interface used to build new graphs from different vendors.
* Adding new vendor support means implementing this interface.
* </p>
*
* @author fppt
*
* @param <T> A vendor implementation of a Tinkerpop {@link Graph}
*/
public interface InternalFactory<T extends Graph> {
/**
*
* @param txType The type of transaction to open on the graph
* @return An instance of Grakn graph
*/
AbstractGraknGraph<T> open(GraknTxType txType);
/**
*
* @param batchLoading A flag which indicates if the graph has batch loading enabled or not.
* @return An instance of a tinker graph
*/
T getTinkerPopGraph(boolean batchLoading);
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/factory/TinkerInternalFactory.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.GraknTinkerGraph;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import java.util.Properties;
/**
* <p>
* A Grakn Graph on top of {@link TinkerGraph}
* </p>
*
* <p>
* This produces an in memory grakn graph on top of {@link TinkerGraph}.
* The base construction process defined by {@link AbstractInternalFactory} ensures the graph factories are singletons.
* </p>
*
* @author fppt
*/
public class TinkerInternalFactory extends AbstractInternalFactory<GraknTinkerGraph, TinkerGraph> {
TinkerInternalFactory(String keyspace, String engineUrl, Properties properties){
super(keyspace, engineUrl, properties);
}
boolean isClosed(TinkerGraph innerGraph) {
return !innerGraph.traversal().V().has(Schema.VertexProperty.ONTOLOGY_LABEL.name(), Schema.MetaSchema.ENTITY.getLabel().getValue()).hasNext();
}
@Override
GraknTinkerGraph buildGraknGraphFromTinker(TinkerGraph graph) {
return new GraknTinkerGraph(graph, super.keyspace, super.engineUrl, properties);
}
@Override
TinkerGraph buildTinkerPopGraph(boolean batchLoading) {
return TinkerGraph.open();
}
@Override
protected TinkerGraph getTinkerPopGraph(TinkerGraph graph, boolean batchLoading){
if(super.graph == null || isClosed(super.graph)){
super.graph = buildTinkerPopGraph(batchLoading);
}
return super.graph;
}
@Override
protected TinkerGraph getGraphWithNewTransaction(TinkerGraph graph, boolean batchLoading) {
return graph;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/factory/package-info.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>.
*/
/**
* Provides graph accessors for different backends.
*/
package ai.grakn.factory;
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/AbstractElement.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.concept.Concept;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.exception.PropertyNotUniqueException;
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>
* Graph 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>
*
* @author fppt
*
*/
abstract class AbstractElement<E extends Element, P extends Enum> {
private final String prefix;
private final E element;
private final AbstractGraknGraph graknGraph;
AbstractElement(AbstractGraknGraph graknGraph, E element, String prefix){
this.graknGraph = graknGraph;
this.element = element;
this.prefix = prefix;
}
E element(){
return element;
}
ElementId id(){
return ElementId.of(prefix + element().id());
}
/**
* Deletes the element from the graph
*/
void delete(){
element().remove();
}
/**
*
* @param key The key of the property to mutate
* @param value The value to commit into the property
*/
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;
}
Boolean propertyBoolean(P key){
Boolean value = property(key);
if(value == null) return false;
return value;
}
/**
*
* @return The grakn graph this concept is bound to.
*/
protected AbstractGraknGraph<?> graph() {
return graknGraph;
}
/**
*
* @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
*/
void propertyUnique(P key, String value){
if(!graph().isBatchGraph()) {
GraphTraversal<Vertex, Vertex> traversal = graph().getTinkerTraversal().V().has(key.name(), value);
if(traversal.hasNext()) throw PropertyNotUniqueException.cannotChangeProperty(element(), traversal.next(), 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
*/
<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 GraphOperationException.immutableProperty(foundValue, newValue, property);
}
} else {
property(property, converter.apply(newValue));
}
}
<X> void propertyImmutable(P property, X newValue, X foundValue){
propertyImmutable(property, newValue, foundValue, Function.identity());
}
/**
*
* @return the label of the element in the graph.
*/
String label(){
return element().label();
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/AbstractGraknGraph.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.Grakn;
import ai.grakn.GraknGraph;
import ai.grakn.GraknTxType;
import ai.grakn.concept.Concept;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.EntityType;
import ai.grakn.concept.Label;
import ai.grakn.concept.LabelId;
import ai.grakn.concept.OntologyConcept;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Resource;
import ai.grakn.concept.ResourceType;
import ai.grakn.concept.Role;
import ai.grakn.concept.RuleType;
import ai.grakn.concept.Thing;
import ai.grakn.concept.Type;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.exception.InvalidGraphException;
import ai.grakn.exception.PropertyNotUniqueException;
import ai.grakn.graph.admin.GraknAdmin;
import ai.grakn.graph.internal.computer.GraknSparkComputer;
import ai.grakn.graql.QueryBuilder;
import ai.grakn.util.EngineCommunicator;
import ai.grakn.util.ErrorMessage;
import ai.grakn.util.REST;
import ai.grakn.util.Schema;
import mjson.Json;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import static java.util.stream.Collectors.toSet;
/**
* <p>
* The Grakn Graph Base Implementation
* </p>
*
* <p>
* This defines how a grakn graph sits on top of a Tinkerpop {@link Graph}.
* It mostly act as a construction object which ensure the resulting graph conforms to the Grakn Object model.
* </p>
*
* @author fppt
*
* @param <G> A vendor specific implementation of a Tinkerpop {@link Graph}.
*/
public abstract class AbstractGraknGraph<G extends Graph> implements GraknGraph, GraknAdmin {
protected final Logger LOG = LoggerFactory.getLogger(AbstractGraknGraph.class);
private static final String QUERY_BUILDER_CLASS_NAME = "ai.grakn.graql.internal.query.QueryBuilderImpl";
//TODO: Is this the correct place for these config paths
//----------------------------- Config Paths
public static final String SHARDING_THRESHOLD = "graph.sharding-threshold";
public static final String NORMAL_CACHE_TIMEOUT_MS = "graph.ontology-cache-timeout-ms";
//----------------------------- Graph Shared Variable
private final String keyspace;
private final String engineUri;
private final Properties properties;
private final G graph;
private final ElementFactory elementFactory;
private final GraphCache graphCache;
private static Constructor<?> queryConstructor = null;
static {
try {
queryConstructor = Class.forName(QUERY_BUILDER_CLASS_NAME).getConstructor(GraknGraph.class);
} catch (NoSuchMethodException | SecurityException | ClassNotFoundException e) {
queryConstructor = null;
}
}
//----------------------------- Transaction Specific
private final ThreadLocal<TxCache> localConceptLog = new ThreadLocal<>();
public AbstractGraknGraph(G graph, String keyspace, String engineUri, Properties properties) {
this.graph = graph;
this.keyspace = keyspace;
this.engineUri = engineUri;
this.properties = properties;
elementFactory = new ElementFactory(this);
//Initialise Graph Caches
graphCache = new GraphCache(properties);
//Initialise Graph
txCache().openTx(GraknTxType.WRITE);
if(initialiseMetaConcepts()) close(true, false);
}
@Override
public LabelId convertToId(Label label){
if(txCache().isLabelCached(label)){
return txCache().convertLabelToId(label);
}
return LabelId.invalid();
}
/**
* Gets and increments the current available type id.
*
* @return the current available Grakn id which can be used for types
*/
private LabelId getNextId(){
TypeImpl<?, ?> metaConcept = (TypeImpl<?, ?>) getMetaConcept();
Integer currentValue = metaConcept.vertex().property(Schema.VertexProperty.CURRENT_LABEL_ID);
if(currentValue == null){
currentValue = Schema.MetaSchema.values().length + 1;
} else {
currentValue = currentValue + 1;
}
//Vertex is used directly here to bypass meta type mutation check
metaConcept.property(Schema.VertexProperty.CURRENT_LABEL_ID, currentValue);
return LabelId.of(currentValue);
}
/**
*
* @return The graph cache which contains all the data cached and accessible by all transactions.
*/
GraphCache getGraphCache(){
return graphCache;
}
/**
* @param concept A concept in the graph
* @return True if the concept has been modified in the transaction
*/
public abstract boolean isConceptModified(Concept concept);
/**
*
* @return The number of open transactions currently.
*/
public abstract int numOpenTx();
/**
* Opens the thread bound transaction
*/
public void openTransaction(GraknTxType txType){
txCache().openTx(txType);
}
@Override
public String getEngineUrl(){
return engineUri;
}
Properties getProperties(){
return properties;
}
@Override
public String getKeyspace(){
return keyspace;
}
TxCache txCache() {
TxCache txCache = localConceptLog.get();
if(txCache == null){
localConceptLog.set(txCache = new TxCache(getGraphCache()));
}
if(txCache.isTxOpen() && txCache.ontologyNotCached()){
txCache.refreshOntologyCache();
}
return txCache;
}
@Override
public boolean isClosed(){
return !txCache().isTxOpen();
}
public abstract boolean isSessionClosed();
@Override
public boolean isReadOnly(){
return GraknTxType.READ.equals(txCache().txType());
}
@Override
public GraknAdmin admin(){
return this;
}
@Override
public <T extends Concept> T buildConcept(Vertex vertex) {
return factory().buildConcept(vertex);
}
@Override
public <T extends Concept> T buildConcept(Edge edge){
return factory().buildConcept(edge);
}
@Override
public boolean isBatchGraph(){
return GraknTxType.BATCH.equals(txCache().txType());
}
@SuppressWarnings("unchecked")
private boolean initialiseMetaConcepts(){
boolean ontologyInitialised = false;
if(isMetaOntologyNotInitialised()){
VertexElement type = addTypeVertex(Schema.MetaSchema.THING.getId(), Schema.MetaSchema.THING.getLabel(), Schema.BaseType.TYPE);
VertexElement entityType = addTypeVertex(Schema.MetaSchema.ENTITY.getId(), Schema.MetaSchema.ENTITY.getLabel(), Schema.BaseType.ENTITY_TYPE);
VertexElement relationType = addTypeVertex(Schema.MetaSchema.RELATION.getId(), Schema.MetaSchema.RELATION.getLabel(), Schema.BaseType.RELATION_TYPE);
VertexElement resourceType = addTypeVertex(Schema.MetaSchema.RESOURCE.getId(), Schema.MetaSchema.RESOURCE.getLabel(), Schema.BaseType.RESOURCE_TYPE);
VertexElement role = addTypeVertex(Schema.MetaSchema.ROLE.getId(), Schema.MetaSchema.ROLE.getLabel(), Schema.BaseType.ROLE);
VertexElement ruleType = addTypeVertex(Schema.MetaSchema.RULE.getId(), Schema.MetaSchema.RULE.getLabel(), Schema.BaseType.RULE_TYPE);
VertexElement inferenceRuleType = addTypeVertex(Schema.MetaSchema.INFERENCE_RULE.getId(), Schema.MetaSchema.INFERENCE_RULE.getLabel(), Schema.BaseType.RULE_TYPE);
VertexElement constraintRuleType = addTypeVertex(Schema.MetaSchema.CONSTRAINT_RULE.getId(), Schema.MetaSchema.CONSTRAINT_RULE.getLabel(), Schema.BaseType.RULE_TYPE);
relationType.property(Schema.VertexProperty.IS_ABSTRACT, true);
role.property(Schema.VertexProperty.IS_ABSTRACT, true);
resourceType.property(Schema.VertexProperty.IS_ABSTRACT, true);
ruleType.property(Schema.VertexProperty.IS_ABSTRACT, true);
entityType.property(Schema.VertexProperty.IS_ABSTRACT, true);
relationType.addEdge(type, Schema.EdgeLabel.SUB);
ruleType.addEdge(type, Schema.EdgeLabel.SUB);
resourceType.addEdge(type, Schema.EdgeLabel.SUB);
entityType.addEdge(type, Schema.EdgeLabel.SUB);
inferenceRuleType.addEdge(ruleType, Schema.EdgeLabel.SUB);
constraintRuleType.addEdge(ruleType, Schema.EdgeLabel.SUB);
//Manual creation of shards on meta types which have instances
createMetaShard(inferenceRuleType);
createMetaShard(constraintRuleType);
ontologyInitialised = true;
}
//Copy entire ontology to the graph cache. This may be a bad idea as it will slow down graph initialisation
copyToCache(getMetaConcept());
//Role has to be copied separately due to not being connected to meta ontology
copyToCache(getMetaRole());
return ontologyInitialised;
}
private void createMetaShard(VertexElement metaNode){
VertexElement metaShard = addVertex(Schema.BaseType.SHARD);
metaShard.addEdge(metaNode, Schema.EdgeLabel.SHARD);
metaNode.property(Schema.VertexProperty.CURRENT_SHARD, metaShard.id().toString());
}
/**
* Copies the {@link OntologyConcept} and it's subs into the {@link TxCache}.
* This is important as lookups for {@link OntologyConcept}s based on {@link Label} depend on this caching.
*
* @param ontologyConcept the {@link OntologyConcept} to be copied into the {@link TxCache}
*/
private void copyToCache(OntologyConcept ontologyConcept){
ontologyConcept.subs().forEach(concept -> {
getGraphCache().cacheLabel(concept.getLabel(), concept.getLabelId());
getGraphCache().cacheType(concept.getLabel(), concept);
});
}
private boolean isMetaOntologyNotInitialised(){
return getMetaConcept() == null;
}
public G getTinkerPopGraph(){
return graph;
}
@Override
public GraphTraversalSource getTinkerTraversal(){
operateOnOpenGraph(() -> null); //This is to check if the graph is open
ReadOnlyStrategy readOnlyStrategy = ReadOnlyStrategy.instance();
return getTinkerPopGraph().traversal().asBuilder().with(readOnlyStrategy).create(getTinkerPopGraph());
}
@Override
public QueryBuilder graql(){
if(queryConstructor == null){
throw new RuntimeException("The query builder implementation " + QUERY_BUILDER_CLASS_NAME +
" must be accessible in the classpath and have a one argument constructor taking a GraknGraph");
}
try {
return (QueryBuilder) queryConstructor.newInstance(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
ElementFactory factory(){
return elementFactory;
}
//----------------------------------------------General Functionality-----------------------------------------------
@Override
public <T extends Concept> T getConcept(Schema.VertexProperty key, Object value) {
Iterator<Vertex> vertices = getTinkerTraversal().V().has(key.name(), value);
if(vertices.hasNext()){
Vertex vertex = vertices.next();
if(vertices.hasNext()) {
LOG.warn(ErrorMessage.TOO_MANY_CONCEPTS.getMessage(key.name(), value));
}
return factory().buildConcept(vertex);
} else {
return null;
}
}
private Set<Concept> getConcepts(Schema.VertexProperty key, Object value){
Set<Concept> concepts = new HashSet<>();
getTinkerTraversal().V().has(key.name(), value).
forEachRemaining(v -> concepts.add(factory().buildConcept(v)));
return concepts;
}
void checkOntologyMutationAllowed(){
checkMutationAllowed();
if(isBatchGraph()) throw GraphOperationException.ontologyMutation();
}
void checkMutationAllowed(){
if(isReadOnly()) throw GraphOperationException.transactionReadOnly(this);
}
//----------------------------------------------Concept Functionality-----------------------------------------------
//------------------------------------ Construction
@Nullable
VertexElement addVertex(Schema.BaseType baseType){
Vertex vertex = operateOnOpenGraph(() -> getTinkerPopGraph().addVertex(baseType.name()));
vertex.property(Schema.VertexProperty.ID.name(), Schema.PREFIX_VERTEX + vertex.id().toString());
return factory().buildVertexElement(vertex);
}
VertexElement addVertex(Schema.BaseType baseType, ConceptId conceptId){
Vertex vertex = operateOnOpenGraph(() -> getTinkerPopGraph().addVertex(baseType.name()));
vertex.property(Schema.VertexProperty.ID.name(), conceptId.getValue());
return factory().buildVertexElement(vertex);
}
private VertexElement putVertex(Label label, Schema.BaseType baseType){
VertexElement vertex;
ConceptImpl concept = getOntologyConcept(convertToId(label));
if(concept == null) {
vertex = addTypeVertex(getNextId(), label, baseType);
} else {
if(!baseType.equals(concept.baseType())) {
throw PropertyNotUniqueException.cannotCreateProperty(concept, Schema.VertexProperty.ONTOLOGY_LABEL, label);
}
vertex = concept.vertex();
}
return vertex;
}
/**
* Adds a new type vertex which occupies a grakn id. This result in the grakn id count on the meta concept to be
* incremented.
*
* @param label The label of the new type vertex
* @param baseType The base type of the new type
* @return The new type vertex
*/
private VertexElement addTypeVertex(LabelId id, Label label, Schema.BaseType baseType){
VertexElement vertexElement = addVertex(baseType);
vertexElement.property(Schema.VertexProperty.ONTOLOGY_LABEL, label.getValue());
vertexElement.property(Schema.VertexProperty.LABEL_ID, id.getValue());
return vertexElement;
}
/**
* An operation on the graph which requires it to be open.
*
* @param supplier The operation to be performed on the graph
* @throws GraphOperationException if the graph is closed.
* @return The result of the operation on the graph.
*/
private <X> X operateOnOpenGraph(Supplier<X> supplier){
if(isClosed()) throw GraphOperationException.transactionClosed(this, txCache().getClosedReason());
return supplier.get();
}
@Override
public EntityType putEntityType(String label) {
return putEntityType(Label.of(label));
}
@Override
public EntityType putEntityType(Label label) {
return putOntologyElement(label, Schema.BaseType.ENTITY_TYPE,
v -> factory().buildEntityType(v, getMetaEntityType()));
}
private <T extends OntologyConcept> T putOntologyElement(Label label, Schema.BaseType baseType, Function<VertexElement, T> factory){
checkOntologyMutationAllowed();
OntologyConcept ontologyConcept = buildOntologyElement(label, () -> factory.apply(putVertex(label, baseType)));
T finalType = validateOntologyElement(ontologyConcept, baseType, () -> {
if(Schema.MetaSchema.isMetaLabel(label)) throw GraphOperationException.reservedLabel(label);
throw PropertyNotUniqueException.cannotCreateProperty(ontologyConcept, Schema.VertexProperty.ONTOLOGY_LABEL, label);
});
//Automatic shard creation - If this type does not have a shard create one
if(!Schema.MetaSchema.isMetaLabel(label) && !OntologyConceptImpl.from(ontologyConcept).vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.SHARD).findAny().isPresent()){
OntologyConceptImpl.from(ontologyConcept).createShard();
}
return finalType;
}
private <T extends Concept> T validateOntologyElement(Concept concept, Schema.BaseType baseType, Supplier<T> invalidHandler){
if(concept != null && baseType.getClassType().isInstance(concept)){
//noinspection unchecked
return (T) concept;
} else {
return invalidHandler.get();
}
}
/**
* A helper method which either retrieves the type from the cache or builds it using a provided supplier
*
* @param label The label of the type to retrieve or build
* @param dbBuilder A method which builds the type via a DB read or write
*
* @return The type which was either cached or built via a DB read or write
*/
private OntologyConcept buildOntologyElement(Label label, Supplier<OntologyConcept> dbBuilder){
if(txCache().isTypeCached(label)){
return txCache().getCachedOntologyElement(label);
} else {
return dbBuilder.get();
}
}
@Override
public RelationType putRelationType(String label) {
return putRelationType(Label.of(label));
}
@Override
public RelationType putRelationType(Label label) {
return putOntologyElement(label, Schema.BaseType.RELATION_TYPE,
v -> factory().buildRelationType(v, getMetaRelationType(), Boolean.FALSE));
}
RelationType putRelationTypeImplicit(Label label) {
return putOntologyElement(label, Schema.BaseType.RELATION_TYPE,
v -> factory().buildRelationType(v, getMetaRelationType(), Boolean.TRUE));
}
@Override
public Role putRole(String label) {
return putRole(Label.of(label));
}
@Override
public Role putRole(Label label) {
return putOntologyElement(label, Schema.BaseType.ROLE,
v -> factory().buildRole(v, getMetaRole(), Boolean.FALSE));
}
Role putRoleTypeImplicit(Label label) {
return putOntologyElement(label, Schema.BaseType.ROLE,
v -> factory().buildRole(v, getMetaRole(), Boolean.TRUE));
}
@Override
public <V> ResourceType<V> putResourceType(String label, ResourceType.DataType<V> dataType) {
return putResourceType(Label.of(label), dataType);
}
@SuppressWarnings("unchecked")
@Override
public <V> ResourceType<V> putResourceType(Label label, ResourceType.DataType<V> dataType) {
@SuppressWarnings("unchecked")
ResourceType<V> resourceType = putOntologyElement(label, Schema.BaseType.RESOURCE_TYPE,
v -> factory().buildResourceType(v, getMetaResourceType(), dataType));
//These checks is needed here because caching will return a type by label without checking the datatype
if(Schema.MetaSchema.isMetaLabel(label)) {
throw GraphOperationException.metaTypeImmutable(label);
} else if(!dataType.equals(resourceType.getDataType())){
throw GraphOperationException.immutableProperty(resourceType.getDataType(), dataType, Schema.VertexProperty.DATA_TYPE);
}
return resourceType;
}
@Override
public RuleType putRuleType(String label) {
return putRuleType(Label.of(label));
}
@Override
public RuleType putRuleType(Label label) {
return putOntologyElement(label, Schema.BaseType.RULE_TYPE,
v -> factory().buildRuleType(v, getMetaRuleType()));
}
//------------------------------------ Lookup
@Override
public <T extends Concept> T getConcept(ConceptId id) {
return operateOnOpenGraph(() -> {
if (txCache().isConceptCached(id)) {
return txCache().getCachedConcept(id);
} else {
if (id.getValue().startsWith(Schema.PREFIX_EDGE)) {
T concept = getConceptEdge(id);
if (concept != null) return concept;
}
return getConcept(Schema.VertexProperty.ID, id.getValue());
}
});
}
private <T extends Concept>T getConceptEdge(ConceptId id){
String edgeId = id.getValue().substring(1);
GraphTraversal<Edge, Edge> traversal = getTinkerTraversal().E(edgeId);
if(traversal.hasNext()){
return factory().buildConcept(factory().buildEdgeElement(traversal.next()));
}
return null;
}
private <T extends OntologyConcept> T getOntologyConcept(Label label, Schema.BaseType baseType){
operateOnOpenGraph(() -> null); //Makes sure the graph is open
OntologyConcept ontologyConcept = buildOntologyElement(label, ()-> getOntologyConcept(convertToId(label)));
return validateOntologyElement(ontologyConcept, baseType, () -> null);
}
@Nullable
<T extends OntologyConcept> T getOntologyConcept(LabelId id){
if(!id.isValid()) return null;
return getConcept(Schema.VertexProperty.LABEL_ID, id.getValue());
}
@Override
public <V> Collection<Resource<V>> getResourcesByValue(V value) {
if(value == null) return Collections.emptySet();
//Make sure you trying to retrieve supported data type
if(!ResourceType.DataType.SUPPORTED_TYPES.containsKey(value.getClass().getName())){
throw GraphOperationException.unsupportedDataType(value);
}
HashSet<Resource<V>> resources = new HashSet<>();
ResourceType.DataType dataType = ResourceType.DataType.SUPPORTED_TYPES.get(value.getClass().getTypeName());
//noinspection unchecked
getConcepts(dataType.getVertexProperty(), dataType.getPersistenceValue(value)).forEach(concept -> {
if(concept != null && concept.isResource()) {
//noinspection unchecked
resources.add(concept.asResource());
}
});
return resources;
}
@Override
public <T extends OntologyConcept> T getOntologyConcept(Label label) {
return getOntologyConcept(label, Schema.BaseType.ONTOLOGY_ELEMENT);
}
@Override
public <T extends Type> T getType(Label label) {
return getOntologyConcept(label, Schema.BaseType.TYPE);
}
@Override
public EntityType getEntityType(String label) {
return getOntologyConcept(Label.of(label), Schema.BaseType.ENTITY_TYPE);
}
@Override
public RelationType getRelationType(String label) {
return getOntologyConcept(Label.of(label), Schema.BaseType.RELATION_TYPE);
}
@Override
public <V> ResourceType<V> getResourceType(String label) {
return getOntologyConcept(Label.of(label), Schema.BaseType.RESOURCE_TYPE);
}
@Override
public Role getRole(String label) {
return getOntologyConcept(Label.of(label), Schema.BaseType.ROLE);
}
@Override
public RuleType getRuleType(String label) {
return getOntologyConcept(Label.of(label), Schema.BaseType.RULE_TYPE);
}
@Override
public OntologyConcept getMetaConcept() {
return getOntologyConcept(Schema.MetaSchema.THING.getId());
}
@Override
public RelationType getMetaRelationType() {
return getOntologyConcept(Schema.MetaSchema.RELATION.getId());
}
@Override
public Role getMetaRole() {
return getOntologyConcept(Schema.MetaSchema.ROLE.getId());
}
@Override
public ResourceType getMetaResourceType() {
return getOntologyConcept(Schema.MetaSchema.RESOURCE.getId());
}
@Override
public EntityType getMetaEntityType() {
return getOntologyConcept(Schema.MetaSchema.ENTITY.getId());
}
@Override
public RuleType getMetaRuleType(){
return getOntologyConcept(Schema.MetaSchema.RULE.getId());
}
@Override
public RuleType getMetaRuleInference() {
return getOntologyConcept(Schema.MetaSchema.INFERENCE_RULE.getId());
}
@Override
public RuleType getMetaRuleConstraint() {
return getOntologyConcept(Schema.MetaSchema.CONSTRAINT_RULE.getId());
}
void putShortcutEdge(Thing toThing, RelationReified fromRelation, Role roleType){
boolean exists = getTinkerTraversal().V().has(Schema.VertexProperty.ID.name(), fromRelation.getId().getValue()).
outE(Schema.EdgeLabel.SHORTCUT.getLabel()).
has(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID.name(), fromRelation.type().getLabelId().getValue()).
has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), roleType.getLabelId().getValue()).inV().
has(Schema.VertexProperty.ID.name(), toThing.getId()).hasNext();
if(!exists){
EdgeElement edge = fromRelation.addEdge(ConceptVertex.from(toThing), Schema.EdgeLabel.SHORTCUT);
edge.property(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID, fromRelation.type().getLabelId().getValue());
edge.property(Schema.EdgeProperty.ROLE_LABEL_ID, roleType.getLabelId().getValue());
txCache().trackForValidation(factory().buildCasting(edge));
}
}
@Override
public void delete() {
closeSession();
clearGraph();
txCache().closeTx(ErrorMessage.CLOSED_CLEAR.getMessage());
//TODO We should not hit the REST endpoint when deleting keyspaces through a graph
// retrieved from and EngineGraknGraphFactory
//Remove the graph from the system keyspace
EngineCommunicator.contactEngine(getDeleteKeyspaceEndpoint(), REST.HttpConn.DELETE_METHOD);
}
//This is overridden by vendors for more efficient clearing approaches
protected void clearGraph(){
getTinkerPopGraph().traversal().V().drop().iterate();
}
@Override
public void closeSession(){
try {
txCache().closeTx(ErrorMessage.SESSION_CLOSED.getMessage(getKeyspace()));
getTinkerPopGraph().close();
} catch (Exception e) {
throw GraphOperationException.closingGraphFailed(this, e);
}
}
@Override
public void close(){
close(false, false);
}
@Override
public void abort(){
close();
}
@Override
public void commit() throws InvalidGraphException{
close(true, true);
}
private Optional<String> close(boolean commitRequired, boolean submitLogs){
Optional<String> logs = Optional.empty();
if(isClosed()) {
return logs;
}
String closeMessage = ErrorMessage.GRAPH_CLOSED_ON_ACTION.getMessage("closed", getKeyspace());
try{
if(commitRequired) {
closeMessage = ErrorMessage.GRAPH_CLOSED_ON_ACTION.getMessage("committed", getKeyspace());
logs = commitWithLogs();
if(logs.isPresent() && submitLogs) {
String logsToUpload = logs.get();
new Thread(() -> LOG.debug("Response from engine [" + EngineCommunicator.contactEngine(getCommitLogEndPoint(), REST.HttpConn.POST_METHOD, logsToUpload) + "]")).start();
}
txCache().writeToGraphCache(true);
} else {
txCache().writeToGraphCache(isReadOnly());
}
} finally {
closeTransaction(closeMessage);
}
return logs;
}
private void closeTransaction(String closedReason){
try {
// TODO: We check `isOpen` because of a Titan bug which decrements the transaction counter even if the transaction is closed
if (graph.tx().isOpen()) {
graph.tx().close();
}
} catch (UnsupportedOperationException e) {
//Ignored for Tinker
} finally {
txCache().closeTx(closedReason);
}
}
/**
* Commits to the graph without submitting any commit logs.
*
* @throws InvalidGraphException when the graph does not conform to the object concept
*/
@Override
public Optional<String> commitNoLogs() throws InvalidGraphException {
return close(true, false);
}
private Optional<String> commitWithLogs() throws InvalidGraphException {
validateGraph();
boolean submissionNeeded = !txCache().getShardingCount().isEmpty() ||
!txCache().getModifiedResources().isEmpty();
Json conceptLog = txCache().getFormattedLog();
LOG.trace("Graph is valid. Committing graph . . . ");
commitTransactionInternal();
//TODO: Kill when analytics no longer needs this
GraknSparkComputer.refresh();
LOG.trace("Graph committed.");
if(submissionNeeded) {
return Optional.of(conceptLog.toString());
}
return Optional.empty();
}
void commitTransactionInternal(){
try {
getTinkerPopGraph().tx().commit();
} catch (UnsupportedOperationException e){
//IGNORED
}
}
void validateGraph() throws InvalidGraphException {
Validator validator = new Validator(this);
if (!validator.validate()) {
List<String> errors = validator.getErrorsFound();
if(!errors.isEmpty()) throw InvalidGraphException.validationErrors(errors);
}
}
private String getCommitLogEndPoint(){
if(Grakn.IN_MEMORY.equals(engineUri)) {
return Grakn.IN_MEMORY;
}
return engineUri + REST.WebPath.COMMIT_LOG_URI + "?" + REST.Request.KEYSPACE_PARAM + "=" + keyspace;
}
private String getDeleteKeyspaceEndpoint(){
if(Grakn.IN_MEMORY.equals(engineUri)) {
return Grakn.IN_MEMORY;
}
return engineUri + REST.WebPath.System.DELETE_KEYSPACE + "?" + REST.Request.KEYSPACE_PARAM + "=" + keyspace;
}
public void validVertex(Vertex vertex){
if(vertex == null) {
throw new IllegalStateException("The provided vertex is null");
}
}
//------------------------------------------ Fixing Code for Postprocessing ----------------------------------------
/**
* Returns the duplicates of the given concept
* @param mainConcept primary concept - this one is returned by the index and not considered a duplicate
* @param conceptIds Set of Ids containing potential duplicates of the main concept
* @return a set containing the duplicates of the given concept
*/
private <X extends ConceptImpl> Set<X> getDuplicates(X mainConcept, Set<ConceptId> conceptIds){
Set<X> duplicated = conceptIds.stream()
.map(this::<X>getConcept)
//filter non-null, will be null if previously deleted/merged
.filter(Objects::nonNull)
.collect(toSet());
duplicated.remove(mainConcept);
return duplicated;
}
/**
* Check if the given index has duplicates to merge
* @param index Index of the potentially duplicated resource
* @param resourceVertexIds Set of vertex ids containing potential duplicates
* @return true if there are duplicate resources amongst the given set and PostProcessing should proceed
*/
@Override
public boolean duplicateResourcesExist(String index, Set<ConceptId> resourceVertexIds){
//This is done to ensure we merge into the indexed casting.
ResourceImpl<?> mainResource = getConcept(Schema.VertexProperty.INDEX, index);
return getDuplicates(mainResource, resourceVertexIds).size() > 0;
}
/**
*
* @param resourceVertexIds The resource vertex ids which need to be merged.
* @return True if a commit is required.
*/
@Override
public boolean fixDuplicateResources(String index, Set<ConceptId> resourceVertexIds){
//This is done to ensure we merge into the indexed casting.
ResourceImpl<?> mainResource = this.getConcept(Schema.VertexProperty.INDEX, index);
Set<ResourceImpl> duplicates = getDuplicates(mainResource, resourceVertexIds);
if(duplicates.size() > 0) {
//Remove any resources associated with this index that are not the main resource
for (Resource otherResource : duplicates) {
Collection<Relation> otherRelations = otherResource.relations();
//Copy the actual relation
for (Relation otherRelation : otherRelations) {
copyRelation(mainResource, otherResource, otherRelation);
}
//Delete the node
ResourceImpl.from(otherResource).deleteNode();
}
//Restore the index
String newIndex = mainResource.getIndex();
//NOTE: Vertex Element is used directly here otherwise property is not actually restored!
//NOTE: Remove or change this line at your own peril!
mainResource.vertex().element().property(Schema.VertexProperty.INDEX.name(), newIndex);
return true;
}
return false;
}
/**
*
* @param main The main instance to possibly acquire a new relation
* @param other The other instance which already posses the relation
* @param otherRelation The other relation to potentially be absorbed
*/
private void copyRelation(Resource main, Resource other, Relation otherRelation){
//Gets the other resource index and replaces all occurrences of the other resource id with the main resource id
//This allows us to find relations far more quickly.
Optional<RelationReified> reifiedRelation = ((RelationImpl) otherRelation).reified();
if(reifiedRelation.isPresent()) {
copyRelation(main, other, otherRelation, reifiedRelation.get());
} else {
copyRelation(main, other, otherRelation, (RelationEdge) RelationImpl.from(otherRelation).structure());
}
}
/**
* Copy a relation which has been reified - {@link RelationReified}
*/
private void copyRelation(Resource main, Resource other, Relation otherRelation, RelationReified reifiedRelation){
String newIndex = reifiedRelation.getIndex().replaceAll(other.getId().getValue(), main.getId().getValue());
Relation foundRelation = txCache().getCachedRelation(newIndex);
if(foundRelation == null) foundRelation = getConcept(Schema.VertexProperty.INDEX, newIndex);
if (foundRelation != null) {//If it exists delete the other one
reifiedRelation.deleteNode(); //Raw deletion because the castings should remain
} else { //If it doesn't exist transfer the edge to the relevant casting node
foundRelation = otherRelation;
//Now that we know the relation needs to be copied we need to find the roles the other casting is playing
otherRelation.allRolePlayers().forEach((roleType, instances) -> {
Optional<RelationReified> relationReified = RelationImpl.from(otherRelation).reified();
if(instances.contains(other) && relationReified.isPresent()) putShortcutEdge(main, relationReified.get(), roleType);
});
}
//Explicitly track this new relation so we don't create duplicates
txCache().getRelationIndexCache().put(newIndex, foundRelation);
}
/**
* Copy a relation which is an edge - {@link RelationEdge}
*/
private void copyRelation(Resource main, Resource other, Relation otherRelation, RelationEdge relationEdge){
ConceptVertex newOwner;
ConceptVertex newValue;
if(relationEdge.owner().equals(other)){//The resource owns another resource which it needs to replace
newOwner = ConceptVertex.from(main);
newValue = ConceptVertex.from(relationEdge.value());
} else {//The resource is owned by another Entity
newOwner = ConceptVertex.from(relationEdge.owner());
newValue = ConceptVertex.from(main);
}
EdgeElement edge = newOwner.vertex().putEdge(newValue.vertex(), Schema.EdgeLabel.RESOURCE);
factory().buildRelation(edge, relationEdge.type(), relationEdge.ownerRole(), relationEdge.valueRole());
}
@Override
public void updateConceptCounts(Map<ConceptId, Long> typeCounts){
typeCounts.entrySet().forEach(entry -> {
if(entry.getValue() != 0) {
ConceptImpl concept = getConcept(entry.getKey());
concept.setShardCount(concept.getShardCount() + entry.getValue());
}
});
}
@Override
public void shard(ConceptId conceptId){
ConceptImpl type = getConcept(conceptId);
if(type == null) {
LOG.warn("Cannot shard concept [" + conceptId + "] due to it not existing in the graph");
} else {
type.createShard();
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/Cache.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.concept.Role;
import javax.annotation.Nullable;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* <p>
* An internal cached element
* </p>
*
* <p>
* An internal cached object which hits the database only when it needs to.
* This is used to cache the components of ontological concepts. i.e. the fields of {@link ai.grakn.concept.Type},
* {@link ai.grakn.concept.RelationType}, and {@link Role}.
* </p>
*
* @param <V> The object it is caching
*
* @author fppt
*
*/
class Cache<V> {
//If no cache can produce the data then the database is read
private final Supplier<V> databaseReader;
//Transaction bound. If this is not set it does not yet exist in the scope of the transaction.
private ThreadLocal<V> cachedValue = new ThreadLocal<>();
//Graph bound value which has already been persisted and acts as a shared component cache
private Optional<V> sharedValue = Optional.empty();
Cache(Supplier<V> databaseReader){
this.databaseReader = databaseReader;
}
/**
* Retrieves the object in the cache. If nothing is cached the database is read.
*
* @return The cached object.
*/
@Nullable
public V get(){
V value = cachedValue.get();
if(value != null) return value;
if(sharedValue.isPresent()) value = sharedValue.get();
if(value == null) value = databaseReader.get();
if(value == null) return null;
cachedValue.set(value);
return cachedValue.get();
}
/**
* Clears the cache.
*/
public void clear(){
cachedValue.remove();
}
/**
* Explicitly set the cache to a provided value
*
* @param value the value to be cached
*/
public void set(@Nullable V value){
cachedValue.set(value);
}
/**
*
* @return true if there is anything stored in the cache
*/
public boolean isPresent(){
return cachedValue.get() != null || sharedValue.isPresent();
}
/**
* Mutates the cached value if something is cached. Otherwise does nothing.
*
* @param modifier the mutator function.
*/
void ifPresent(Consumer<V> modifier){
if(isPresent()){
modifier.accept(get());
}
}
/**
* Takes the current value in the transaction cache if it is present and puts it in the sharedValue reference so
* that it can be accessed via all transactions.
*/
void flush(){
if(isPresent()) sharedValue = Optional.of(get());
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/Casting.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.concept.LabelId;
import ai.grakn.concept.Role;
import ai.grakn.concept.Thing;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Edge;
/**
* <p>
* Represents An Thing Playing a Role
* </p>
*
* <p>
* Wraps the shortcut {@link Edge} which contains the information unifying an {@link Thing},
* {@link Relation} and {@link Role}.
* </p>
*
* @author fppt
*/
class Casting {
private final EdgeElement edgeElement;
private final Cache<Role> cachedRoleType = new Cache<>(() -> (Role) edge().graph().getOntologyConcept(LabelId.of(edge().property(Schema.EdgeProperty.ROLE_LABEL_ID))));
private final Cache<RelationType> cachedRelationType = new Cache<>(() -> (RelationType) edge().graph().getOntologyConcept(LabelId.of(edge().property(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID))));
private final Cache<Thing> cachedInstance = new Cache<>(() -> edge().graph().factory().buildConcept(edge().target()));
private final Cache<Relation> cachedRelation = new Cache<>(() -> edge().graph().factory().buildConcept(edge().source()));
Casting(EdgeElement edgeElement){
this.edgeElement = edgeElement;
}
EdgeElement edge(){
return edgeElement;
}
/**
*
* @return The role the instance is playing
*/
public Role getRoleType(){
return cachedRoleType.get();
}
/**
*
* @return The relation type the instance is taking part in
*/
public RelationType getRelationType(){
return cachedRelationType.get();
}
/**
*
* @return The relation which is linking the role and the instance
*/
public Relation getRelation(){
return cachedRelation.get();
}
/**
*
* @return The instance playing the role
*/
public Thing getInstance(){
return cachedInstance.get();
}
/**
*
* @return The hash code of the underlying vertex
*/
public int hashCode() {
return edge().id().hashCode();
}
/**
*
* @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-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ConceptImpl.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.concept.Concept;
import ai.grakn.concept.ConceptId;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.Set;
import java.util.stream.Collectors;
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
*
*/
abstract class ConceptImpl implements Concept, ConceptVertex {
private final Cache<ConceptId> conceptId = new Cache<>(() -> ConceptId.of(vertex().property(Schema.VertexProperty.ID)));
private final VertexElement vertexElement;
@SuppressWarnings("unchecked")
<X extends Concept> X getThis(){
return (X) this;
}
ConceptImpl(VertexElement vertexElement){
this.vertexElement = vertexElement;
}
@Override
public VertexElement vertex() {
return vertexElement;
}
/**
* Deletes the concept.
* @throws GraphOperationException Throws an exception if the node has any edges attached to it.
*/
@Override
public void delete() throws GraphOperationException {
deleteNode();
}
/**
* Deletes the node and adds it neighbours for validation
*/
void deleteNode(){
vertex().graph().txCache().remove(this);
vertex().delete();
}
/**
*
* @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.of(
vertex().graph().factory().buildConcept(edge.source()),
vertex().graph().factory().buildConcept(edge.target())
));
case IN:
return vertex().getEdgesOfType(direction, label).map(edge ->
vertex().graph().factory().buildConcept(edge.source())
);
case OUT:
return vertex().getEdgesOfType(direction, label).map(edge ->
vertex().graph().factory().buildConcept(edge.target())
);
default:
throw GraphOperationException.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
*/
Schema.BaseType baseType(){
return Schema.BaseType.valueOf(vertex().label());
}
/**
*
* @return A string representing the concept's unique id.
*/
@Override
public ConceptId getId(){
return conceptId.get();
}
@Override public int hashCode() {
return getId().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 getId().equals(concept.getId());
}
@Override
public final String toString(){
try {
vertex().graph().validVertex(vertex().element());
return innerToString();
} catch (RuntimeException e){
// Vertex is broken somehow. Most likely deleted.
return "Id [" + getId() + "]";
}
}
protected String innerToString() {
String message = "Base Type [" + baseType() + "] ";
if(getId() != null) {
message = message + "- Id [" + getId() + "] ";
}
return message;
}
@Override
public int compareTo(Concept o) {
return this.getId().compareTo(o.getId());
}
//----------------------------------- Sharding Functionality
void createShard(){
VertexElement shardVertex = vertex().graph().addVertex(Schema.BaseType.SHARD);
Shard shard = vertex().graph().factory().buildShard(this, shardVertex);
vertex().property(Schema.VertexProperty.CURRENT_SHARD, shard.id());
}
Set<Shard> shards(){
return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.SHARD).map(edge ->
vertex().graph().factory().buildShard(edge.source())).collect(Collectors.toSet());
}
Shard currentShard(){
String currentShardId = vertex().property(Schema.VertexProperty.CURRENT_SHARD);
Vertex shardVertex = vertex().graph().getTinkerTraversal().V().has(Schema.VertexProperty.ID.name(), currentShardId).next();
return vertex().graph().factory().buildShard(shardVertex);
}
long getShardCount(){
Long value = vertex().property(Schema.VertexProperty.SHARD_COUNT);
if(value == null) return 0L;
return value;
}
void setShardCount(Long instanceCount){
vertex().property(Schema.VertexProperty.SHARD_COUNT, instanceCount);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ConceptVertex.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.concept.Concept;
/**
* <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
*
*/
interface ConceptVertex {
VertexElement vertex();
static ConceptVertex from(Concept concept){
return (ConceptVertex) concept;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/EdgeElement.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.Schema;
import org.apache.tinkerpop.gremlin.structure.Edge;
import javax.annotation.Nullable;
/**
* <p>
* Represent an Edge in a Grakn Graph
* </p>
*
* <p>
* Wraps a tinkerpop {@link Edge} constraining it to the Grakn Object Model.
* </p>
*
* @author fppt
*/
class EdgeElement extends AbstractElement<Edge, Schema.EdgeProperty> {
EdgeElement(AbstractGraknGraph 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());
}
/**
*
* @return The source of the edge.
*/
@Nullable
public VertexElement source(){
return graph().factory().buildVertexElement(element().outVertex());
}
/**
*
* @return The target of the edge
*/
@Nullable
public VertexElement target(){
return graph().factory().buildVertexElement(element().inVertex());
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ElementFactory.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.concept.Concept;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.EntityType;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.ResourceType;
import ai.grakn.concept.Role;
import ai.grakn.concept.RuleType;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.graql.Pattern;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.Optional;
import java.util.function.Function;
import static ai.grakn.util.Schema.BaseType.RELATION_TYPE;
import static ai.grakn.util.Schema.BaseType.RULE_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
*/
final class ElementFactory {
private final Logger LOG = LoggerFactory.getLogger(ElementFactory.class);
private final AbstractGraknGraph graknGraph;
ElementFactory(AbstractGraknGraph graknGraph){
this.graknGraph = graknGraph;
}
private <X extends Concept, E extends AbstractElement> X getOrBuildConcept(E element, ConceptId conceptId, Function<E, X> conceptBuilder){
if(!graknGraph.txCache().isConceptCached(conceptId)){
X newConcept = conceptBuilder.apply(element);
graknGraph.txCache().cacheConcept(newConcept);
}
X concept = graknGraph.txCache().getCachedConcept(conceptId);
//Only track concepts which have been modified.
if(graknGraph.isConceptModified(concept)) {
graknGraph.txCache().trackForValidation(concept);
}
return concept;
}
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 Resource Types -----------------------------------------------
<V> ResourceTypeImpl<V> buildResourceType(VertexElement vertex, ResourceType<V> type, ResourceType.DataType<V> dataType){
return getOrBuildConcept(vertex, (v) -> new ResourceTypeImpl<>(v, type, dataType));
}
// ------------------------------------------ Building Resources
<V> ResourceImpl <V> buildResource(VertexElement vertex, ResourceType<V> type, Object persitedValue){
return getOrBuildConcept(vertex, (v) -> new ResourceImpl<>(v, type, persitedValue));
}
// ---------------------------------------- Building Relation Types -----------------------------------------------
RelationTypeImpl buildRelationType(VertexElement vertex, RelationType type, Boolean isImplicit){
return getOrBuildConcept(vertex, (v) -> new RelationTypeImpl(v, type, isImplicit));
}
// -------------------------------------------- Building Relations
RelationImpl buildRelation(VertexElement vertex, RelationType type){
return getOrBuildConcept(vertex, (v) -> new RelationImpl(buildRelationReified(v, type)));
}
RelationImpl buildRelation(EdgeElement edge, RelationType type, Role owner, Role value){
return getOrBuildConcept(edge, (e) -> new RelationImpl(new RelationEdge(type, owner, value, edge)));
}
RelationImpl buildRelation(EdgeElement edge){
return getOrBuildConcept(edge, (e) -> new RelationImpl(new RelationEdge(edge)));
}
RelationReified buildRelationReified(VertexElement vertex, RelationType type){
return new RelationReified(vertex, type);
}
// ----------------------------------------- Building Entity Types ------------------------------------------------
EntityTypeImpl buildEntityType(VertexElement vertex, EntityType type){
return getOrBuildConcept(vertex, (v) -> new EntityTypeImpl(v, type));
}
// ------------------------------------------- Building Entities
EntityImpl buildEntity(VertexElement vertex, EntityType type){
return getOrBuildConcept(vertex, (v) -> new EntityImpl(v, type));
}
// ----------------------------------------- Building Rule Types --------------------------------------------------
RuleTypeImpl buildRuleType(VertexElement vertex, RuleType type){
return getOrBuildConcept(vertex, (v) -> new RuleTypeImpl(v, type));
}
// -------------------------------------------- Building Rules
RuleImpl buildRule(VertexElement vertex, RuleType type, Pattern when, Pattern then){
return getOrBuildConcept(vertex, (v) -> new RuleImpl(v, type, when, then));
}
// ------------------------------------------ Building Roles Types ------------------------------------------------
RoleImpl buildRole(VertexElement vertex, Role type, Boolean isImplicit){
return getOrBuildConcept(vertex, (v) -> new RoleImpl(v, type, isImplicit));
}
/**
* Constructors are called directly because this is only called when reading a known vertex or concept.
* Thus tracking the concept can be skipped.
*
* @param v A vertex of an unknown type
* @return A concept built to the correct type
*/
@Nullable
<X extends Concept> X buildConcept(Vertex v){
return buildConcept(buildVertexElement(v));
}
@Nullable
<X extends Concept> X buildConcept(VertexElement vertexElement){
Schema.BaseType type;
try {
type = getBaseType(vertexElement);
} catch (IllegalStateException e){
LOG.warn("Invalid vertex [" + vertexElement + "] due to " + e.getMessage(), e);
return null;
}
ConceptId conceptId = ConceptId.of(vertexElement.property(Schema.VertexProperty.ID));
if(!graknGraph.txCache().isConceptCached(conceptId)){
Concept concept;
switch (type) {
case RELATION:
concept = new RelationImpl(new RelationReified(vertexElement));
break;
case TYPE:
concept = new TypeImpl<>(vertexElement);
break;
case ROLE:
concept = new RoleImpl(vertexElement);
break;
case RELATION_TYPE:
concept = new RelationTypeImpl(vertexElement);
break;
case ENTITY:
concept = new EntityImpl(vertexElement);
break;
case ENTITY_TYPE:
concept = new EntityTypeImpl(vertexElement);
break;
case RESOURCE_TYPE:
concept = new ResourceTypeImpl<>(vertexElement);
break;
case RESOURCE:
concept = new ResourceImpl<>(vertexElement);
break;
case RULE:
concept = new RuleImpl(vertexElement);
break;
case RULE_TYPE:
concept = new RuleTypeImpl(vertexElement);
break;
default:
throw GraphOperationException.unknownConcept(type.name());
}
graknGraph.txCache().cacheConcept(concept);
}
return graknGraph.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
*/
@Nullable
<X extends Concept> X buildConcept(Edge edge){
return buildConcept(buildEdgeElement(edge));
}
@Nullable
<X extends Concept> X buildConcept(EdgeElement edgeElement){
Schema.EdgeLabel label;
try {
label = Schema.EdgeLabel.valueOf(edgeElement.label().toUpperCase());
} catch (IllegalStateException e){
LOG.warn("Invalid edge [" + edgeElement + "] due to " + e.getMessage(), e);
return null;
}
ConceptId conceptId = ConceptId.of(edgeElement.id().getValue());
if(!graknGraph.txCache().isConceptCached(conceptId)){
Concept concept;
switch (label) {
case RESOURCE:
concept = new RelationImpl(new RelationEdge(edgeElement));
break;
default:
throw GraphOperationException.unknownConcept(label.name());
}
graknGraph.txCache().cacheConcept(concept);
}
return graknGraph.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<EdgeElement> type = vertex.getEdgesOfType(Direction.OUT, Schema.EdgeLabel.SHARD).findAny();
if(type.isPresent()){
String label = type.get().target().label();
if(label.equals(Schema.BaseType.ENTITY_TYPE.name())) return Schema.BaseType.ENTITY;
if(label.equals(RELATION_TYPE.name())) return Schema.BaseType.RELATION;
if(label.equals(Schema.BaseType.RESOURCE_TYPE.name())) return Schema.BaseType.RESOURCE;
if(label.equals(RULE_TYPE.name())) return Schema.BaseType.RULE;
}
}
throw new IllegalStateException("Could not determine the base type of vertex [" + vertex + "]");
}
// ---------------------------------------- Non Concept Construction -----------------------------------------------
EdgeElement buildEdgeElement(Edge edge){
return new EdgeElement(graknGraph, edge);
}
Casting buildCasting(Edge edge){
return buildCasting(buildEdgeElement(edge));
}
Casting buildCasting(EdgeElement edge) {
return new Casting(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));
}
@Nullable
VertexElement buildVertexElement(Vertex vertex){
try {
graknGraph.validVertex(vertex);
} catch (IllegalStateException e){
LOG.warn("Invalid vertex [" + vertex + "] due to " + e.getMessage(), e);
return null;
}
return new VertexElement(graknGraph, vertex);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ElementId.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 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 ai.grakn.GraknGraph}.
* Also contains a static method for producing {@link AbstractElement} IDs from Strings.
* </p>
*
* @author fppt
*/
class ElementId implements Serializable {
private static final long serialVersionUID = 6688475951939464790L;
private 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-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/EntityImpl.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.concept.Entity;
import ai.grakn.concept.EntityType;
/**
* <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 ai.grakn.concept.Resource} and their links to
* other entities via {@link ai.grakn.concept.Relation}
* </p>
*
* @author fppt
*/
class EntityImpl extends ThingImpl<Entity, EntityType> implements Entity {
EntityImpl(VertexElement vertexElement) {
super(vertexElement);
}
EntityImpl(VertexElement vertexElement, EntityType type) {
super(vertexElement, type);
}
public static EntityImpl from(Entity entity){
return (EntityImpl) entity;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/EntityTypeImpl.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.concept.Entity;
import ai.grakn.concept.EntityType;
import ai.grakn.util.Schema;
/**
* <p>
* Ontology element used to represent categories.
* </p>
*
* <p>
* An ontological element which represents categories instances can fall within.
* Any instance of a Entity Type is called an {@link Entity}.
* </p>
*
* @author fppt
*
*/
class EntityTypeImpl extends TypeImpl<EntityType, Entity> implements EntityType{
EntityTypeImpl(VertexElement vertexElement) {
super(vertexElement);
}
EntityTypeImpl(VertexElement vertexElement, EntityType type) {
super(vertexElement, type);
}
@Override
public Entity addEntity() {
return addInstance(Schema.BaseType.ENTITY, (vertex, type) -> vertex().graph().factory().buildEntity(vertex, type), true);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/GraknComputerImpl.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.GraknComputer;
import ai.grakn.graph.internal.computer.GraknSparkComputer;
import ai.grakn.util.ErrorMessage;
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.structure.Graph;
import org.apache.tinkerpop.gremlin.tinkergraph.process.computer.TinkerGraphComputer;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import java.util.concurrent.ExecutionException;
/**
* <p>
* Graph Computer Used For Analytics Algorithms
* </p>
* <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>
* A {@link VertexProgram} is a computation executed on each vertex in parallel.
* Vertices communicate with each other through message passing.
* <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;
public GraknComputerImpl(Graph graph) {
this.graph = graph;
if(graph instanceof TinkerGraph){
graphComputerClass = TinkerGraphComputer.class;
} else {
graphComputerClass = GraknSparkComputer.class;
}
}
@Override
public ComputerResult compute(VertexProgram program, MapReduce... mapReduces) {
try {
graphComputer = getGraphComputer().program(program);
for (MapReduce mapReduce : mapReduces)
graphComputer = graphComputer.mapReduce(mapReduce);
return graphComputer.submit().get();
} catch (InterruptedException | ExecutionException e) {
throw asRuntimeException(e);
}
}
@Override
public ComputerResult compute(MapReduce mapReduce) {
try {
graphComputer = getGraphComputer().mapReduce(mapReduce);
return graphComputer.submit().get();
} catch (InterruptedException | ExecutionException e) {
throw asRuntimeException(e);
}
}
@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 instanceof RuntimeException) {
return (RuntimeException) cause;
} else {
return new RuntimeException(cause);
}
}
/**
* @return A graph compute supported by this grakn graph
*/
@SuppressWarnings("unchecked")
protected Class<? extends GraphComputer> getGraphComputerClass(String graphComputerType) {
try {
return (Class<? extends GraphComputer>) Class.forName(graphComputerType);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(ErrorMessage.INVALID_COMPUTER.getMessage(graphComputerType));
}
}
protected GraphComputer getGraphComputer() {
return graph.compute(this.graphComputerClass);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/GraknTinkerGraph.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.concept.Concept;
import ai.grakn.util.ErrorMessage;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import java.util.Properties;
/**
* <p>
* A Grakn Graph using {@link TinkerGraph} as a vendor backend.
* </p>
*
* <p>
* Wraps up a {@link TinkerGraph} as a method of storing the Grakn Graph object Model.
* With this vendor some exceptions are in place:
* 1. Transactions do not exists and all threads work on the same graph at the same time.
* </p>
*
* @author fppt
*/
public class GraknTinkerGraph extends AbstractGraknGraph<TinkerGraph> {
private final TinkerGraph rootGraph;
public GraknTinkerGraph(TinkerGraph tinkerGraph, String name, String engineUrl, Properties properties){
super(tinkerGraph, name, engineUrl, properties);
rootGraph = tinkerGraph;
}
/**
*
* @param concept A concept in the graph
* @return true all the time. There is no way to know if a
* {@link org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerVertex} has been modified or not.
*/
@Override
public boolean isConceptModified(Concept concept) {
return true;
}
@Override
public int numOpenTx() {
return 1;
}
@Override
public boolean isSessionClosed() {
return !rootGraph.traversal().V().has(Schema.VertexProperty.ONTOLOGY_LABEL.name(), Schema.MetaSchema.ENTITY.getLabel().getValue()).hasNext();
}
@Override
public void commit(){
LOG.warn(ErrorMessage.TRANSACTIONS_NOT_SUPPORTED.getMessage(TinkerGraph.class.getName(), "committed"));
super.commit();
}
@Override
public void abort(){
LOG.warn(ErrorMessage.TRANSACTIONS_NOT_SUPPORTED.getMessage(TinkerGraph.class.getName(), "aborted"));
super.abort();
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/GraphCache.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.concept.Label;
import ai.grakn.concept.LabelId;
import ai.grakn.concept.OntologyConcept;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* <p>
* Tracks Graph Specific Variables
* </p>
*
* <p>
* Caches Graph or Session specific data which is shared across transactions:
* <ol>
* <li>Ontology Cache - All the types which make up the ontology. This cache expires</li>
* <li>
* Label Cache - All the labels which make up the ontology. This can never expire and is needed in order
* to perform fast lookups. Essentially it is used for mapping labels to ids.
* </li>
* <ol/>
* </p>
*
* @author fppt
*
*/
class GraphCache {
//Caches
private final Cache<Label, OntologyConcept> cachedTypes;
private final Map<Label, LabelId> cachedLabels;
GraphCache(Properties properties){
cachedLabels = new ConcurrentHashMap<>();
int cacheTimeout = Integer.parseInt(properties.get(AbstractGraknGraph.NORMAL_CACHE_TIMEOUT_MS).toString());
cachedTypes = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterAccess(cacheTimeout, TimeUnit.MILLISECONDS)
.build();
}
/**
* Caches a type so that we can retrieve ontological concepts without making a DB read.
*
* @param label The label of the type to cache
* @param type The type to cache
*/
void cacheType(Label label, OntologyConcept type){
cachedTypes.put(label, type);
}
/**
* Caches a label so we can map type labels to type ids. This is necesssary so we can make fast indexed lookups.
*
* @param label The label of the type to cache
* @param id The id of the type to cache
*/
void cacheLabel(Label label, LabelId id){
cachedLabels.put(label, id);
}
/**
* Reads the types and their labels currently in the transaction cache into the graph cache.
* This usually happens when a commit occurs and allows us to track Ontology mutations without having to read
* the graph.
*
* @param txCache The transaction cache
*/
void readTxCache(TxCache txCache){
//TODO: The difference between the caches need to be taken into account. For example if a type is delete then it should be removed from the cachedLabels
cachedLabels.putAll(txCache.getLabelCache());
cachedTypes.putAll(txCache.getOntologyConceptCache());
//Flush All The Internal Transaction Caches
txCache.getOntologyConceptCache().values().forEach(ontologyConcept
-> OntologyConceptImpl.from(ontologyConcept).txCacheFlush());
}
/**
* A copy of the cached labels. This is used when creating a new transaction.
*
* @return an immutable copy of the cached labels.
*/
Map<Label, LabelId> getCachedLabels(){
return ImmutableMap.copyOf(cachedLabels);
}
/**
* A copy of the cached ontology. This is used when creating a new transaction.
*
* @return an immutable copy of the cached ontology.
*/
Map<Label, OntologyConcept> getCachedTypes(){
return ImmutableMap.copyOf(cachedTypes.asMap());
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/OntologyConceptImpl.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.concept.EntityType;
import ai.grakn.concept.Label;
import ai.grakn.concept.LabelId;
import ai.grakn.concept.OntologyConcept;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Rule;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.exception.PropertyNotUniqueException;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import static scala.tools.scalap.scalax.rules.scalasig.NoSymbol.isAbstract;
/**
* <p>
* Ontology or Schema Specific Element
* </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 RelationType} or {@link Role}
*/
abstract class OntologyConceptImpl<T extends OntologyConcept> extends ConceptImpl implements OntologyConcept {
private final Cache<Label> cachedLabel = new Cache<>(() -> Label.of(vertex().property(Schema.VertexProperty.ONTOLOGY_LABEL)));
private final Cache<LabelId> cachedLabelId = new Cache<>(() -> LabelId.of(vertex().property(Schema.VertexProperty.LABEL_ID)));
private final Cache<T> cachedSuperType = new Cache<>(() -> this.<T>neighbours(Direction.OUT, Schema.EdgeLabel.SUB).findFirst().orElse(null));
private final Cache<Set<T>> cachedDirectSubTypes = new Cache<>(() -> this.<T>neighbours(Direction.IN, Schema.EdgeLabel.SUB).collect(Collectors.toSet()));
private final Cache<Boolean> cachedIsImplicit = new Cache<>(() -> vertex().propertyBoolean(Schema.VertexProperty.IS_IMPLICIT));
OntologyConceptImpl(VertexElement vertexElement) {
super(vertexElement);
}
OntologyConceptImpl(VertexElement vertexElement, T superType) {
this(vertexElement);
if(sup() == null) sup(superType);
}
OntologyConceptImpl(VertexElement vertexElement, T superType, Boolean isImplicit) {
this(vertexElement, superType);
vertex().propertyImmutable(Schema.VertexProperty.IS_IMPLICIT, isImplicit, vertex().property(Schema.VertexProperty.IS_IMPLICIT));
cachedIsImplicit.set(isImplicit);
}
public T setLabel(Label label){
try {
vertex().graph().txCache().remove(this);
vertex().propertyUnique(Schema.VertexProperty.ONTOLOGY_LABEL, label.getValue());
cachedLabel.set(label);
vertex().graph().txCache().cacheConcept(this);
return getThis();
} catch (PropertyNotUniqueException exception){
vertex().graph().txCache().cacheConcept(this);
throw GraphOperationException.labelTaken(label);
}
}
/**
*
* @return The internal id which is used for fast lookups
*/
@Override
public LabelId getLabelId(){
return cachedLabelId.get();
}
/**
*
* @return The label of this ontological element
*/
@Override
public Label getLabel() {
return cachedLabel.get();
}
/**
* Flushes the internal transaction caches so they can refresh with persisted graph
*/
public void txCacheFlush(){
cachedSuperType.flush();
cachedDirectSubTypes.flush();
cachedIsImplicit.flush();
}
/**
* Clears the internal transaction caches
*/
void txCacheClear(){
cachedSuperType.clear();
cachedDirectSubTypes.clear();
cachedIsImplicit.clear();
}
/**
*
* @return The super of this Ontology Element
*/
public T sup() {
return cachedSuperType.get();
}
/**
*
* @return All outgoing sub parents including itself
*/
Set<T> superSet() {
Set<T> superSet= new HashSet<>();
superSet.add(getThis());
T superParent = sup();
while(superParent != null && !Schema.MetaSchema.THING.getLabel().equals(superParent.getLabel())){
superSet.add(superParent);
//noinspection unchecked
superParent = (T) superParent.sup();
}
return superSet;
}
/**
*
* @return returns true if the type was created implicitly through the resource syntax
*/
@Override
public Boolean isImplicit(){
return cachedIsImplicit.get();
}
/**
* Deletes the concept as an Ontology Element
*/
@Override
public void delete(){
if(deletionAllowed()){
//Force load of linked concepts whose caches need to be updated
//noinspection unchecked
cachedSuperType.get();
deleteNode();
//Update neighbouring caches
//noinspection unchecked
((OntologyConceptImpl<OntologyConcept>) cachedSuperType.get()).deleteCachedDirectedSubType(getThis());
//Clear internal caching
txCacheClear();
//Clear Global Cache
vertex().graph().txCache().remove(this);
} else {
throw GraphOperationException.cannotBeDeleted(this);
}
}
boolean deletionAllowed(){
checkOntologyMutationAllowed();
return !neighbours(Direction.IN, Schema.EdgeLabel.SUB).findAny().isPresent();
}
/**
*
* @return All the subs of this concept including itself
*/
@Override
public Collection<T> subs(){
return Collections.unmodifiableCollection(nextSubLevel(this));
}
/**
* 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 Ontology Element
* @return All the sub children of the root. Effectively calls the cache {@link OntologyConceptImpl#cachedDirectSubTypes} recursively
*/
@SuppressWarnings("unchecked")
private Set<T> nextSubLevel(OntologyConceptImpl<T> root){
Set<T> results = new HashSet<>();
results.add((T) root);
Set<T> children = root.cachedDirectSubTypes.get();
for(T child: children){
results.addAll(nextSubLevel((OntologyConceptImpl<T>) child));
}
return results;
}
/**
* Checks if we are mutating an ontology element in a valid way. Ontology mutations are valid if:
* 1. The Ontology Element is not a meta-type
* 2. The graph is not batch loading
*/
void checkOntologyMutationAllowed(){
vertex().graph().checkOntologyMutationAllowed();
if(Schema.MetaSchema.isMetaLabel(getLabel())){
throw GraphOperationException.metaTypeImmutable(getLabel());
}
}
/**
* 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));
}
/**
* Adds another subtype to this type
*
* @param type The sub type of this type
* @return The Type itself
*/
public T sub(T type){
//noinspection unchecked
((TypeImpl) type).sup(this);
return getThis();
}
/**
*
* @param newSuperType This type's super type
* @return The Type itself
*/
public T sup(T newSuperType) {
checkOntologyMutationAllowed();
T oldSuperType = sup();
if(oldSuperType == null || (!oldSuperType.equals(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 GraphOperationException.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
((OntologyConceptImpl<T>) oldSuperType).deleteCachedDirectedSubType(getThis());
}
//Add this as the subtype to the supertype
//noinspection unchecked - Casting is needed to access {addCachedDirectSubTypes} method
((OntologyConceptImpl<T>) newSuperType).addCachedDirectSubType(getThis());
//Track any existing data if there is some
trackRolePlayers();
}
return getThis();
}
/**
* Method which performs tasks needed in order to track super changes properly
*/
abstract void trackRolePlayers();
private boolean superLoops(){
//Check For Loop
HashSet<OntologyConcept> foundTypes = new HashSet<>();
OntologyConcept 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 OntologyConcept} serves as a hypothesis
*/
@Override
public Collection<Rule> getRulesOfHypothesis() {
Set<Rule> rules = new HashSet<>();
neighbours(Direction.IN, Schema.EdgeLabel.HYPOTHESIS).forEach(concept -> rules.add(concept.asRule()));
return Collections.unmodifiableCollection(rules);
}
/**
*
* @return A collection of {@link Rule} for which this {@link OntologyConcept} serves as a conclusion
*/
@Override
public Collection<Rule> getRulesOfConclusion() {
Set<Rule> rules = new HashSet<>();
neighbours(Direction.IN, Schema.EdgeLabel.CONCLUSION).forEach(concept -> rules.add(concept.asRule()));
return Collections.unmodifiableCollection(rules);
}
@Override
public String innerToString(){
String message = super.innerToString();
message = message + " - Label [" + getLabel() + "] - Abstract [" + isAbstract() + "] ";
return message;
}
public static OntologyConceptImpl from(OntologyConcept ontologyConcept){
return (OntologyConceptImpl) ontologyConcept;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RelationEdge.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.concept.ConceptId;
import ai.grakn.concept.LabelId;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Thing;
import ai.grakn.util.Schema;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* <p>
* Encapsulates The {@link Relation} as a {@link EdgeElement}
* </p>
*
* <p>
* This wraps up a {@link Relation} as a {@link EdgeElement}. It is used to represent any binary {@link Relation}.
* This also includes the ability to automatically reify a {@link RelationEdge} into a {@link RelationReified}.
* </p>
*
* @author fppt
*
*/
class RelationEdge implements RelationStructure{
private final EdgeElement edgeElement;
private final Cache<RelationType> relationType = new Cache<>(() ->
edge().graph().getOntologyConcept(LabelId.of(edge().property(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID))));
private final Cache<Role> ownerRole = new Cache<>(() -> edge().graph().getOntologyConcept(LabelId.of(
edge().property(Schema.EdgeProperty.RELATION_ROLE_OWNER_LABEL_ID))));
private final Cache<Role> valueRole = new Cache<>(() -> edge().graph().getOntologyConcept(LabelId.of(
edge().property(Schema.EdgeProperty.RELATION_ROLE_VALUE_LABEL_ID))));
private final Cache<Thing> owner = new Cache<>(() -> edge().graph().factory().buildConcept(edge().source()));
private final Cache<Thing> value = new Cache<>(() -> edge().graph().factory().buildConcept(edge().target()));
RelationEdge(EdgeElement edgeElement) {
this.edgeElement = edgeElement;
}
RelationEdge(RelationType relationType, Role ownerRole, Role valueRole, EdgeElement edgeElement) {
this(edgeElement);
edgeElement.propertyImmutable(Schema.EdgeProperty.RELATION_ROLE_OWNER_LABEL_ID, ownerRole, null, o -> o.getLabelId().getValue());
edgeElement.propertyImmutable(Schema.EdgeProperty.RELATION_ROLE_VALUE_LABEL_ID, valueRole, null, v -> v.getLabelId().getValue());
edgeElement.propertyImmutable(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID, relationType, null, t -> t.getLabelId().getValue());
this.relationType.set(relationType);
this.ownerRole.set(ownerRole);
this.valueRole.set(valueRole);
}
EdgeElement edge(){
return edgeElement;
}
@Override
public ConceptId getId() {
return ConceptId.of(edge().id().getValue());
}
@Override
public RelationReified reify() {
//Build the Relation Vertex
VertexElement relationVertex = edge().graph().addVertex(Schema.BaseType.RELATION, getId());
RelationReified relationReified = edge().graph().factory().buildRelationReified(relationVertex, type());
//Delete the old edge
delete();
return relationReified;
}
@Override
public boolean isReified() {
return false;
}
@Override
public RelationType 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 Collection<Thing> rolePlayers(Role... roles) {
if(roles.length == 0){
return Sets.newHashSet(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;
}
Role ownerRole(){
return ownerRole.get();
}
Thing owner(){
return owner.get();
}
Role valueRole(){
return valueRole.get();
}
Thing value(){
return value.get();
}
@Override
public void delete() {
edge().delete();
}
@Override
public String toString(){
return "ID [" + getId() + "] Type [" + type().getLabel() + "] Roles and Role Players: \n" +
"Role [" + ownerRole().getLabel() + "] played by [" + owner().getId() + "] \n" +
"Role [" + valueRole().getLabel() + "] played by [" + value().getId() + "] \n";
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RelationImpl.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.concept.Concept;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Resource;
import ai.grakn.concept.ResourceType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Thing;
import com.google.common.collect.Iterables;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
/**
* <p>
* Encapsulates relationships between {@link Thing}
* </p>
*
* <p>
* A relation which is an instance of a {@link RelationType} defines how instances may relate to one another.
* </p>
*
* @author fppt
*
*/
class RelationImpl implements Relation, ConceptVertex {
private RelationStructure relationStructure;
RelationImpl(RelationStructure relationStructure) {
this.relationStructure = relationStructure;
}
/**
* Gets the {@link RelationReified} if the {@link Relation} has been reified.
* To reify the {@link Relation} you use {@link RelationImpl#reify()}.
*
* NOTE: This approach is done to make sure that only write operations will cause the {@link Relation} to reify
*
* @return The {@link RelationReified} if the {@link Relation} has been reified
*/
Optional<RelationReified> reified(){
if(!relationStructure.isReified()) return Optional.empty();
return Optional.of(relationStructure.reify());
}
/**
* Reifys and returns the {@link RelationReified}
*/
RelationReified reify(){
if(relationStructure.isReified()) return relationStructure.reify();
//Get the role players to transfer
Map<Role, Set<Thing>> rolePlayers = structure().allRolePlayers();
//Now Reify
relationStructure = relationStructure.reify();
//Transfer relationships
rolePlayers.forEach((role, things) -> {
Thing thing = Iterables.getOnlyElement(things);
addRolePlayer(role, thing);
});
return relationStructure.reify();
}
RelationStructure structure(){
return relationStructure;
}
@Override
public Relation resource(Resource resource) {
reify().resource(resource);
return this;
}
@Override
public Collection<Resource<?>> resources(ResourceType[] resourceTypes) {
return readFromReified((relationReified) -> relationReified.resources(resourceTypes));
}
@Override
public RelationType type() {
return structure().type();
}
@Override
public Collection<Relation> relations(Role... roles) {
return readFromReified((relationReified) -> relationReified.relations(roles));
}
@Override
public Collection<Role> plays() {
return readFromReified(ThingImpl::plays);
}
/**
* Reads some data from a {@link RelationReified}. If the {@link Relation} has not been reified then an empty
* collection is returned.
*/
private <X> Collection<X> readFromReified(Function<RelationReified, Collection<X>> producer){
return reified().map(producer).orElseGet(Collections::emptyList);
}
/**
* Retrieve a list of all {@link Thing} involved in the {@link Relation}, 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 Relation}.
*/
@Override
public Map<Role, Set<Thing>> allRolePlayers(){
return structure().allRolePlayers();
}
@Override
public Collection<Thing> rolePlayers(Role... roles) {
return structure().rolePlayers(roles);
}
/**
* Expands this Relation to include a new role player which is playing a specific role.
* @param role The role of the new role player.
* @param thing The new role player.
* @return The Relation itself
*/
@Override
public Relation addRolePlayer(Role role, Thing thing) {
reify().addRolePlayer(role, thing);
vertex().graph().txCache().trackForValidation(this); //This is so we can reassign the hash if needed
return this;
}
/**
* When a relation is deleted this cleans up any solitary casting and resources.
*/
void cleanUp() {
boolean performDeletion = true;
Collection<Thing> rolePlayers = rolePlayers();
for(Thing thing : rolePlayers){
if(thing != null && (thing.getId() != null )){
performDeletion = false;
}
}
if(performDeletion){
delete();
}
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
return getId().equals(((RelationImpl) object).getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public String toString(){
return structure().toString();
}
@Override
public ConceptId getId() {
return structure().getId();
}
@Override
public void delete() {
structure().delete();
}
@Override
public int compareTo(Concept o) {
return getId().compareTo(o.getId());
}
@Override
public VertexElement vertex() {
return reify().vertex();
}
public static RelationImpl from(Relation relation){
return (RelationImpl) relation;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RelationReified.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.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Thing;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <p>
* Encapsulates The {@link Relation} as a {@link VertexElement}
* </p>
*
* <p>
* This wraps up a {@link Relation} as a {@link VertexElement}. It is used to represent any {@link Relation} which
* has been reified.
* </p>
*
* @author fppt
*
*/
public class RelationReified extends ThingImpl<Relation, RelationType> implements RelationStructure {
RelationReified(VertexElement vertexElement) {
super(vertexElement);
}
RelationReified(VertexElement vertexElement, RelationType type) {
super(vertexElement, type);
}
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().relates().forEach(roleType -> roleMap.put(roleType, new HashSet<>()));
castingsRelation().forEach(rp -> roleMap.computeIfAbsent(rp.getRoleType(), (k) -> new HashSet<>()).add(rp.getInstance()));
return roleMap;
}
public Collection<Thing> rolePlayers(Role... roles) {
return castingsRelation(roles).map(Casting::getInstance).collect(Collectors.toSet());
}
public void addRolePlayer(Role role, Thing thing) {
Objects.requireNonNull(role);
Objects.requireNonNull(thing);
if(Schema.MetaSchema.isMetaLabel(role.getLabel())) throw GraphOperationException.metaTypeImmutable(role.getLabel());
//Do the actual put of the role and role player
vertex().graph().putShortcutEdge(thing, this, role);
}
/**
* Sets the internal hash in order to perform a faster lookup
*/
void setHash(){
vertex().propertyUnique(Schema.VertexProperty.INDEX, generateNewHash(type(), allRolePlayers()));
}
/**
*
* @param relationType The type of this relation
* @param roleMap The roles and their corresponding role players
* @return A unique hash identifying this relation
*/
static String generateNewHash(RelationType relationType, Map<Role, Set<Thing>> roleMap){
SortedSet<Role> sortedRoleIds = new TreeSet<>(roleMap.keySet());
StringBuilder hash = new StringBuilder();
hash.append("RelationType_").append(relationType.getId().getValue().replace("_", "\\_")).append("_Relation");
for(Role role: sortedRoleIds){
hash.append("_").append(role.getId().getValue().replace("_", "\\_"));
roleMap.get(role).forEach(instance -> {
if(instance != null){
hash.append("_").append(instance.getId().getValue().replace("_", "\\_"));
}
});
}
return hash.toString();
}
/**
* Castings are retrieved from the perspective of the {@link Relation}
*
* @param roles The role which the instances are playing
* @return The {@link Casting} which unify a {@link Role} and {@link Thing} with this {@link Relation}
*/
Stream<Casting> castingsRelation(Role... roles){
if(roles.length == 0){
return vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.SHORTCUT).
map(edge -> vertex().graph().factory().buildCasting(edge));
}
//Traversal is used so we can potentially optimise on the index
Set<Integer> roleTypesIds = Arrays.stream(roles).map(r -> r.getLabelId().getValue()).collect(Collectors.toSet());
return vertex().graph().getTinkerTraversal().V().
has(Schema.VertexProperty.ID.name(), getId().getValue()).
outE(Schema.EdgeLabel.SHORTCUT.getLabel()).
has(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID.name(), type().getLabelId().getValue()).
has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), P.within(roleTypesIds)).
toStream().map(edge -> vertex().graph().factory().buildCasting(edge));
}
@Override
public String innerToString(){
StringBuilder description = new StringBuilder();
description.append("ID [").append(getId()).append("] Type [").append(type().getLabel()).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().getLabel()).append("] not played by any instance \n");
} else {
StringBuilder instancesString = new StringBuilder();
for (Thing thing : entry.getValue()) {
instancesString.append(thing.getId()).append(",");
}
description.append(" Role [").append(entry.getKey().getLabel()).append("] played by [").
append(instancesString.toString()).append("] \n");
}
}
return description.toString();
}
@Override
public RelationReified reify() {
return this;
}
@Override
public boolean isReified() {
return true;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RelationStructure.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.concept.ConceptId;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Thing;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* <p>
* Encapsulates The structure of a {@link Relation}.
* </p>
*
* <p>
* This wraps up the structure of a {@link Relation} as either a {@link RelationReified} or a TODO
* It contains methods which can be accessed regardless of the {@link Relation} being a represented by a
* {@link VertexElement} or an {@link EdgeElement}
* </p>
*
* @author fppt
*
*/
interface RelationStructure {
/**
*
* @return The {@link ConceptId} of the {@link Relation}
*/
ConceptId getId();
/**
*
* @return The relation structure which has been reified
*/
RelationReified reify();
/**
*
* @return true if the {@link Relation} has been reified meaning it can support n-ary relationships
*/
boolean isReified();
/**
*
* @return The {@link RelationType} of the {@link Relation}
*/
RelationType 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
*/
Collection<Thing> rolePlayers(Role... roles);
/**
* Deletes the {@link VertexElement} or {@link EdgeElement} used to represent this {@link Relation}
*/
void delete();
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RelationTypeImpl.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.concept.Concept;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.Collection;
import java.util.Collections;
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
*
*/
class RelationTypeImpl extends TypeImpl<RelationType, Relation> implements RelationType {
private Cache<Set<Role>> cachedRelates = new Cache<>(() -> this.<Role>neighbours(Direction.OUT, Schema.EdgeLabel.RELATES).collect(Collectors.toSet()));
RelationTypeImpl(VertexElement vertexElement) {
super(vertexElement);
}
RelationTypeImpl(VertexElement vertexElement, RelationType type, Boolean isImplicit) {
super(vertexElement, type, isImplicit);
}
@Override
public Relation addRelation() {
return addInstance(Schema.BaseType.RELATION,
(vertex, type) -> vertex().graph().factory().buildRelation(vertex, type), true);
}
@Override
public void txCacheFlush(){
super.txCacheFlush();
cachedRelates.flush();
}
@Override
public void txCacheClear(){
super.txCacheFlush();
cachedRelates.clear();
}
/**
*
* @return A list of the Role Types which make up this Relation Type.
*/
@Override
public Collection<Role> relates() {
return Collections.unmodifiableCollection(cachedRelates.get());
}
/**
*
* @param role A new role which is part of this relationship.
* @return The Relation Type itself.
*/
@Override
public RelationType relates(Role role) {
checkOntologyMutationAllowed();
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);
//Put all the instance back in for tracking because their unique hashes need to be regenerated
instances().forEach(instance -> vertex().graph().txCache().trackForValidation(instance));
return this;
}
/**
*
* @param role The role type to delete from this relationship.
* @return The Relation Type itself.
*/
@Override
public RelationType deleteRelates(Role role) {
checkOntologyMutationAllowed();
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().graph().txCache().trackForValidation(rolePlayer));
//Add the Role Type itself
vertex().graph().txCache().trackForValidation(roleTypeImpl);
//Add the Relation Type
vertex().graph().txCache().trackForValidation(roleTypeImpl);
//Remove from internal cache
cachedRelates.ifPresent(set -> set.remove(role));
//Remove from roleTypeCache
((RoleImpl) role).deleteCachedRelationType(this);
//Put all the instance back in for tracking because their unique hashes need to be regenerated
instances().forEach(instance -> vertex().graph().txCache().trackForValidation(instance));
return this;
}
@Override
public void delete(){
//Force load the cache
cachedRelates.get();
super.delete();
//Update the cache of the connected role types
cachedRelates.get().forEach(r -> {
RoleImpl role = ((RoleImpl) r);
vertex().graph().txCache().trackForValidation(role);
((RoleImpl) r).deleteCachedRelationType(this);
});
}
@Override
void trackRolePlayers(){
instances().forEach(concept -> {
RelationImpl relation = RelationImpl.from(concept);
if(relation.reified().isPresent()){
relation.reified().get().castingsRelation().forEach(rolePlayer -> vertex().graph().txCache().trackForValidation(rolePlayer));
}
});
}
@Override
public Stream<Relation> instancesDirect(){
Stream<Relation> 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<Relation> relationEdges(){
//Unfortunately this is a slow process
return relates().stream().
flatMap(role -> role.playedByTypes().stream()).
flatMap(type ->{
//Traversal is used here to take advantage of vertex centric index
return vertex().graph().getTinkerTraversal().V().
has(Schema.VertexProperty.ID.name(), type.getId().getValue()).
in(Schema.EdgeLabel.SHARD.getLabel()).
in(Schema.EdgeLabel.ISA.getLabel()).
outE(Schema.EdgeLabel.RESOURCE.getLabel()).
has(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID.name(), getLabelId().getValue()).
toStream().
map(edge -> vertex().graph().factory().buildConcept(edge).asRelation());
});
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ResourceImpl.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.concept.Resource;
import ai.grakn.concept.ResourceType;
import ai.grakn.concept.Thing;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
/**
* <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 ResourceType} based on it's value.
* 2. It has a {@link ai.grakn.concept.ResourceType.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}
*/
class ResourceImpl<D> extends ThingImpl<Resource<D>, ResourceType<D>> implements Resource<D> {
ResourceImpl(VertexElement vertexElement) {
super(vertexElement);
}
ResourceImpl(VertexElement vertexElement, ResourceType<D> type, Object value) {
super(vertexElement, type);
setValue(value);
}
/**
*
* @return The data type of this Resource's type.
*/
@Override
public ResourceType.DataType<D> dataType() {
return type().getDataType();
}
/**
* @return The list of all Instances which posses this resource
*/
@Override
public Collection<Thing> ownerInstances() {
//Get Owner via implicit structure
Set<Thing> owners = getShortcutNeighbours().stream().
filter(concept -> !concept.isResource()).
collect(Collectors.toSet());
//Get owners via edges
neighbours(Direction.IN, Schema.EdgeLabel.RESOURCE).forEach(concept -> owners.add(concept.asThing()));
return owners;
}
@Override
public Thing owner() {
Collection<Thing> owners = ownerInstances();
if(owners.isEmpty()) {
return null;
} else {
return owners.iterator().next();
}
}
/**
*
* @param value The value to store on the resource
* @return The Resource itself
*/
private Resource<D> setValue(Object value) {
Schema.VertexProperty property = dataType().getVertexProperty();
//noinspection unchecked
vertex().propertyImmutable(property, value, vertex().property(property));
return getThis();
}
/**
*
* @return The value casted to the correct type
*/
@Override
public D getValue(){
return dataType().getValue(vertex().property(dataType().getVertexProperty()));
}
@Override
public String innerToString(){
return super.innerToString() + "- Value [" + getValue() + "] ";
}
public static ResourceImpl from(Resource resource){
return (ResourceImpl) resource;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ResourceTypeImpl.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.concept.Resource;
import ai.grakn.concept.ResourceType;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.util.ErrorMessage;
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 Resource} 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 ai.grakn.concept.ResourceType.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 ResourceType 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}
*/
class ResourceTypeImpl<D> extends TypeImpl<ResourceType<D>, Resource<D>> implements ResourceType<D> {
ResourceTypeImpl(VertexElement vertexElement) {
super(vertexElement);
}
ResourceTypeImpl(VertexElement vertexElement, ResourceType<D> type, DataType<D> dataType) {
super(vertexElement, type);
vertex().propertyImmutable(Schema.VertexProperty.DATA_TYPE, dataType, getDataType(), DataType::getName);
}
/**
* 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 ResourceType<D> sup(ResourceType<D> superType){
((ResourceTypeImpl<D>) superType).superSet().forEach(st -> checkInstancesMatchRegex(st.getRegex()));
return super.sup(superType);
}
/**
* @param regex The regular expression which instances of this resource must conform to.
* @return The Resource Type itself.
*/
@Override
public ResourceType<D> setRegex(String regex) {
if(getDataType() == null || !getDataType().equals(DataType.STRING)){
throw new UnsupportedOperationException(ErrorMessage.REGEX_NOT_STRING.getMessage(getLabel()));
}
checkInstancesMatchRegex(regex);
return property(Schema.VertexProperty.REGEX, regex);
}
/**
* Checks that existing instances match the provided regex.
*
* @throws GraphOperationException 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);
Matcher matcher;
for (Resource<D> resource : instances()) {
String value = (String) resource.getValue();
matcher = pattern.matcher(value);
if(!matcher.matches()){
throw GraphOperationException.regexFailure(this, value, regex);
}
}
}
}
@SuppressWarnings("unchecked")
@Override
public Resource<D> putResource(D value) {
Objects.requireNonNull(value);
BiFunction<VertexElement, ResourceType<D>, Resource<D>> instanceBuilder = (vertex, type) -> {
if(getDataType().equals(DataType.STRING)) checkConformsToRegexes(value);
Object persistenceValue = castValue(value);
ResourceImpl<D> resource = vertex().graph().factory().buildResource(vertex, type, persistenceValue);
resource.vertex().propertyUnique(Schema.VertexProperty.INDEX, Schema.generateResourceIndex(getLabel(), value.toString()));
return resource;
};
return putInstance(Schema.BaseType.RESOURCE,
() -> getResource(value), instanceBuilder);
}
/**
* 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 Object castValue(D value){
ResourceType.DataType<D> dataType = getDataType();
try {
if (dataType.equals(ResourceType.DataType.DOUBLE)) {
return ((Number) value).doubleValue();
} else if (dataType.equals(ResourceType.DataType.LONG)) {
if (value instanceof Double) {
throw new ClassCastException();
}
return ((Number) value).longValue();
} else {
return dataType.getPersistenceValue(value);
}
} catch (ClassCastException e) {
throw GraphOperationException.invalidResourceValue(value, dataType);
}
}
/**
* Checks if all the regex's of the types of this resource conforms to the value provided.
*
* @throws GraphOperationException 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.
for (ResourceType rt : superSet()) {
String regex = rt.getRegex();
if (regex != null && !Pattern.matches(regex, (String) value)) {
throw GraphOperationException.regexFailure(this, (String) value, regex);
}
}
}
@Override
public Resource<D> getResource(D value) {
String index = Schema.generateResourceIndex(getLabel(), value.toString());
return vertex().graph().getConcept(Schema.VertexProperty.INDEX, index);
}
/**
* @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> getDataType() {
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 getRegex() {
return vertex().property(Schema.VertexProperty.REGEX);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RoleImpl.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.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Type;
import ai.grakn.util.CommonUtil;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <p>
* An ontological element which defines a role which can be played in a relation type.
* </p>
*
* <p>
* This ontological element defines the roles which make up a {@link RelationType}.
* It behaves similarly to {@link Type} when relating to other types.
* It has some additional functionality:
* 1. It cannot play a role to itself.
* 2. It is special in that it is unique to relation types.
* </p>
*
* @author fppt
*
*/
class RoleImpl extends OntologyConceptImpl<Role> implements Role {
private Cache<Set<Type>> cachedDirectPlayedByTypes = new Cache<>(() -> this.<Type>neighbours(Direction.IN, Schema.EdgeLabel.PLAYS).collect(Collectors.toSet()));
private Cache<Set<RelationType>> cachedRelationTypes = new Cache<>(() -> this.<RelationType>neighbours(Direction.IN, Schema.EdgeLabel.RELATES).collect(Collectors.toSet()));
RoleImpl(VertexElement vertexElement) {
super(vertexElement);
}
RoleImpl(VertexElement vertexElement, Role type, Boolean isImplicit) {
super(vertexElement, type, isImplicit);
}
@Override
public void txCacheFlush(){
super.txCacheFlush();
cachedDirectPlayedByTypes.flush();
cachedRelationTypes.flush();
}
@Override
public void txCacheClear(){
super.txCacheClear();
cachedDirectPlayedByTypes.clear();
cachedRelationTypes.clear();
}
/**
*
* @return The Relation Type which this role takes part in.
*/
@Override
public Collection<RelationType> relationTypes() {
return Collections.unmodifiableCollection(cachedRelationTypes.get());
}
/**
* 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 newRelationType The new relation type to cache in the role.
*/
void addCachedRelationType(RelationType newRelationType){
cachedRelationTypes.ifPresent(set -> set.add(newRelationType));
}
/**
* 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 oldRelationType The new relation type to cache in the role.
*/
void deleteCachedRelationType(RelationType oldRelationType){
cachedRelationTypes.ifPresent(set -> set.remove(oldRelationType));
}
/**
*
* @return A list of all the Concept Types which can play this role.
*/
@Override
public Collection<Type> playedByTypes() {
Set<Type> playedByTypes = new HashSet<>();
cachedDirectPlayedByTypes.get().forEach(type -> playedByTypes.addAll(type.subs()));
return Collections.unmodifiableCollection(playedByTypes);
}
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 relationTypes().stream().
flatMap(relationType -> relationType.instances().stream()).
map(relation -> RelationImpl.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-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RuleImpl.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.concept.OntologyConcept;
import ai.grakn.concept.Rule;
import ai.grakn.concept.RuleType;
import ai.grakn.concept.Thing;
import ai.grakn.concept.Type;
import ai.grakn.graql.Pattern;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Direction;
import java.util.Collection;
import java.util.HashSet;
/**
* <p>
* A rule which defines how implicit knowledge can extracted.
* </p>
*
* <p>
* It can behave like any other {@link Thing} but primarily serves as a way of extracting
* implicit data from the graph. By defining the LHS (if statment) and RHS (then conclusion) it is possible to
* automatically materialise new concepts based on these rules.
* </p>
*
* @author fppt
*
*/
class RuleImpl extends ThingImpl<Rule, RuleType> implements Rule {
RuleImpl(VertexElement vertexElement) {
super(vertexElement);
}
RuleImpl(VertexElement vertexElement, RuleType type, Pattern when, Pattern then) {
super(vertexElement, type);
vertex().propertyImmutable(Schema.VertexProperty.RULE_WHEN, when, getWhen(), Pattern::toString);
vertex().propertyImmutable(Schema.VertexProperty.RULE_THEN, then, getThen(), Pattern::toString);
vertex().propertyUnique(Schema.VertexProperty.INDEX, generateRuleIndex(type(), when, then));
}
/**
*
* @return A string representing the left hand side GraQL query.
*/
@Override
public Pattern getWhen() {
return parsePattern(vertex().property(Schema.VertexProperty.RULE_WHEN));
}
/**
*
* @return A string representing the right hand side GraQL query.
*/
@Override
public Pattern getThen() {
return parsePattern(vertex().property(Schema.VertexProperty.RULE_THEN));
}
private Pattern parsePattern(String value){
if(value == null) {
return null;
} else {
return vertex().graph().graql().parsePattern(value);
}
}
/**
*
* @param ontologyConcept The {@link OntologyConcept} which this {@link Rule} applies to.
* @return The {@link Rule} itself
*/
Rule addHypothesis(OntologyConcept ontologyConcept) {
putEdge(ConceptVertex.from(ontologyConcept), Schema.EdgeLabel.HYPOTHESIS);
return getThis();
}
/**
*
* @param ontologyConcept The {@link OntologyConcept} which is the conclusion of this {@link Rule}.
* @return The {@link Rule} itself
*/
Rule addConclusion(OntologyConcept ontologyConcept) {
putEdge(ConceptVertex.from(ontologyConcept), Schema.EdgeLabel.CONCLUSION);
return getThis();
}
/**
*
* @return A collection of Concept Types that constitute a part of the hypothesis of the rule
*/
@Override
public Collection<Type> getHypothesisTypes() {
Collection<Type> types = new HashSet<>();
neighbours(Direction.OUT, Schema.EdgeLabel.HYPOTHESIS).forEach(concept -> types.add(concept.asType()));
return types;
}
/**
*
* @return A collection of Concept Types that constitute a part of the conclusion of the rule
*/
@Override
public Collection<Type> getConclusionTypes() {
Collection<Type> types = new HashSet<>();
neighbours(Direction.OUT, Schema.EdgeLabel.CONCLUSION).forEach(concept -> types.add(concept.asType()));
return types;
}
/**
* Generate the internal hash in order to perform a faster lookups and ensure rules are unique
*/
static String generateRuleIndex(RuleType type, Pattern when, Pattern then){
return "RuleType_" + type.getLabel().getValue() + "_LHS:" + when.hashCode() + "_RHS:" + then.hashCode();
}
public static RuleImpl from(Rule rule){
return (RuleImpl) rule;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/RuleTypeImpl.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.concept.Rule;
import ai.grakn.concept.RuleType;
import ai.grakn.graph.admin.GraknAdmin;
import ai.grakn.graql.Pattern;
import ai.grakn.util.Schema;
import javax.annotation.Nullable;
import java.util.Objects;
/**
* <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}.
* Currently supported rules include {@link GraknAdmin#getMetaRuleInference()} and {@link GraknAdmin#getMetaRuleConstraint()}
* </p>
*
* @author fppt
*/
class RuleTypeImpl extends TypeImpl<RuleType, Rule> implements RuleType {
RuleTypeImpl(VertexElement vertexElement) {
super(vertexElement);
}
RuleTypeImpl(VertexElement vertexElement, RuleType type) {
super(vertexElement, type);
}
@Override
public Rule putRule(Pattern when, Pattern then) {
Objects.requireNonNull(when);
Objects.requireNonNull(then);
return putInstance(Schema.BaseType.RULE,
() -> getRule(when, then), (vertex, type) -> vertex().graph().factory().buildRule(vertex, type, when, then));
}
@Nullable
private Rule getRule(Pattern when, Pattern then) {
String index = RuleImpl.generateRuleIndex(this, when, then);
return vertex().graph().getConcept(Schema.VertexProperty.INDEX, index);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/Shard.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.concept.Thing;
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
*/
class Shard {
private final VertexElement vertexElement;
Shard(ConceptImpl owner, VertexElement vertexElement){
this(vertexElement);
owner(owner);
}
Shard(VertexElement vertexElement){
this.vertexElement = vertexElement;
}
VertexElement vertex(){
return vertexElement;
}
/**
*
* @return The id of this shard. Strings are used because shards are looked up via the string index.
*/
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
*/
void link(ConceptImpl concept){
concept.vertex().putEdge(vertex(), Schema.EdgeLabel.ISA);
}
/**
*
* @return All the concept linked to this shard
*/
<V extends Thing> Stream<V> links(){
return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.ISA).
map(EdgeElement::source).
map(vertexElement -> vertex().graph().factory().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-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ThingImpl.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.concept.Concept;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Label;
import ai.grakn.concept.LabelId;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Resource;
import ai.grakn.concept.ResourceType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Thing;
import ai.grakn.concept.Type;
import ai.grakn.exception.GraphOperationException;
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.Vertex;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* <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 Relation}
* </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 Relation}.
* @param <V> The type of the concept which extends {@link Type} of the concept.
* For example {@link ai.grakn.concept.EntityType} or {@link RelationType}
*/
abstract class ThingImpl<T extends Thing, V extends Type> extends ConceptImpl implements Thing {
private final Cache<Label> cachedInternalType = new Cache<>(() -> {
int typeId = vertex().property(Schema.VertexProperty.THING_TYPE_LABEL_ID);
Type type = vertex().graph().getConcept(Schema.VertexProperty.LABEL_ID, typeId);
return type.getLabel();
});
private final Cache<V> cachedType = new Cache<>(() -> {
Optional<EdgeElement> typeEdge = vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ISA).
flatMap(edge -> edge.target().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.SHARD)).findAny();
if(!typeEdge.isPresent()) {
throw GraphOperationException.noType(this);
}
return vertex().graph().factory().buildConcept(typeEdge.get().target());
});
ThingImpl(VertexElement vertexElement) {
super(vertexElement);
}
ThingImpl(VertexElement vertexElement, V type) {
this(vertexElement);
type((TypeImpl) type);
}
/**
* Deletes the concept as an Thing
*/
@Override
public void delete() {
Set<Relation> relations = castingsInstance().map(Casting::getRelation).collect(Collectors.toSet());
vertex().graph().txCache().removedInstance(type().getId());
deleteNode();
relations.forEach(relation -> {
if(relation.type().isImplicit()){//For now implicit relations die
relation.delete();
} else {
RelationImpl rel = (RelationImpl) relation;
vertex().graph().txCache().trackForValidation(rel);
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);
}
/**
*
* @return All the {@link Resource} that this Thing is linked with
*/
public Collection<Resource<?>> resources(ResourceType... resourceTypes) {
Set<ConceptId> resourceTypesIds = Arrays.stream(resourceTypes).map(Concept::getId).collect(Collectors.toSet());
Set<Resource<?>> resources = new HashSet<>();
//Get Resources Attached Via Implicit Relations
getShortcutNeighbours().forEach(concept -> {
if(concept.isResource() && !equals(concept)) {
Resource<?> resource = concept.asResource();
if(resourceTypesIds.isEmpty() || resourceTypesIds.contains(resource.type().getId())) {
resources.add(resource);
}
}
});
//Get Resources Attached Via resource edge
neighbours(Direction.OUT, Schema.EdgeLabel.RESOURCE).forEach(resource -> {
if(resourceTypesIds.isEmpty() || resourceTypesIds.contains(resource.asThing().type().getId())) {
resources.add(resource.asResource());
}
});
return resources;
}
/**
* Castings are retrieved from the perspective of the {@link Thing} which is a role player in a {@link Relation}
*
* @return All the {@link Casting} which this instance is cast into the role
*/
Stream<Casting> castingsInstance(){
return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.SHORTCUT).
map(edge -> vertex().graph().factory().buildCasting(edge));
}
<X extends Thing> Set<X> getShortcutNeighbours(){
Set<X> foundNeighbours = new HashSet<X>();
vertex().graph().getTinkerTraversal().V().
has(Schema.VertexProperty.ID.name(), getId().getValue()).
in(Schema.EdgeLabel.SHORTCUT.getLabel()).
out(Schema.EdgeLabel.SHORTCUT.getLabel()).
forEachRemaining(vertex -> foundNeighbours.add(vertex().graph().buildConcept(vertex)));
return foundNeighbours;
}
/**
*
* @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 Collection<Relation> relations(Role... roles) {
Set<Relation> relations = reifiedRelations(roles);
relations.addAll(edgeRelations(roles));
return relations;
}
private Set<Relation> reifiedRelations(Role... roles){
Set<Relation> relations = new HashSet<>();
GraphTraversal<Vertex, Vertex> traversal = vertex().graph().getTinkerTraversal().V().
has(Schema.VertexProperty.ID.name(), getId().getValue());
if(roles.length == 0){
traversal.in(Schema.EdgeLabel.SHORTCUT.getLabel());
} else {
Set<Integer> roleTypesIds = Arrays.stream(roles).map(r -> r.getLabelId().getValue()).collect(Collectors.toSet());
traversal.inE(Schema.EdgeLabel.SHORTCUT.getLabel()).
has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), P.within(roleTypesIds)).outV();
}
traversal.forEachRemaining(v -> relations.add(vertex().graph().buildConcept(v)));
return relations;
}
private Set<Relation> edgeRelations(Role... roles){
Set<Role> roleSet = new HashSet<>(Arrays.asList(roles));
Set<Relation> relations = new HashSet<>();
vertex().getEdgesOfType(Direction.BOTH, Schema.EdgeLabel.RESOURCE).forEach(edge -> {
if (roleSet.isEmpty()) {
relations.add(vertex().graph().factory().buildRelation(edge));
} else {
Role roleOwner = vertex().graph().getOntologyConcept(LabelId.of(edge.property(Schema.EdgeProperty.RELATION_ROLE_OWNER_LABEL_ID)));
if(roleSet.contains(roleOwner)){
relations.add(vertex().graph().factory().buildRelation(edge));
}
}
});
return relations;
}
/**
*
* @return A set of all the Role Types which this instance plays.
*/
@Override
public Collection<Role> plays() {
return castingsInstance().map(Casting::getRoleType).collect(Collectors.toSet());
}
/**
* Creates a relation from this instance to the provided resource.
* @param resource The resource to creating a relationship to
* @return The instance itself
*/
@Override
public T resource(Resource resource){
Schema.ImplicitType has = Schema.ImplicitType.HAS;
Schema.ImplicitType hasValue = Schema.ImplicitType.HAS_VALUE;
Schema.ImplicitType hasOwner = Schema.ImplicitType.HAS_OWNER;
//Is this resource a key to me?
if(type().keys().contains(resource.type())){
has = Schema.ImplicitType.KEY;
hasValue = Schema.ImplicitType.KEY_VALUE;
hasOwner = Schema.ImplicitType.KEY_OWNER;
}
Label label = resource.type().getLabel();
RelationType hasResource = vertex().graph().getOntologyConcept(has.getLabel(label));
Role hasResourceOwner = vertex().graph().getOntologyConcept(hasOwner.getLabel(label));
Role hasResourceValue = vertex().graph().getOntologyConcept(hasValue.getLabel(label));
if(hasResource == null || hasResourceOwner == null || hasResourceValue == null || !type().plays().contains(hasResourceOwner)){
throw GraphOperationException.hasNotAllowed(this, resource);
}
EdgeElement resourceEdge = putEdge(ResourceImpl.from(resource), Schema.EdgeLabel.RESOURCE);
vertex().graph().factory().buildRelation(resourceEdge, hasResource, hasResourceOwner, hasResourceValue);
return getThis();
}
/**
*
* @return The type of the concept casted to the correct interface
*/
public V type() {
return cachedType.get();
}
/**
*
* @param type The type of this concept
* @return The concept itself casted to the correct interface
*/
protected T type(TypeImpl type) {
if(type != null){
type.currentShard().link(this);
setInternalType(type());
}
return getThis();
}
/**
*
* @param type The type of this concept
*/
private void setInternalType(Type type){
cachedInternalType.set(type.getLabel());
vertex().property(Schema.VertexProperty.THING_TYPE_LABEL_ID, type.getLabelId().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-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/TxCache.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.GraknTxType;
import ai.grakn.concept.Concept;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.Entity;
import ai.grakn.concept.Label;
import ai.grakn.concept.LabelId;
import ai.grakn.concept.OntologyConcept;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Resource;
import ai.grakn.concept.Role;
import ai.grakn.concept.Rule;
import ai.grakn.concept.Thing;
import ai.grakn.util.REST;
import ai.grakn.util.Schema;
import mjson.Json;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* <p>
* Tracks Graph Transaction Specific Variables
* </p>
*
* <p>
* Caches Transaction specific data this includes:
* <ol>
* <li>Validation Concepts - Concepts which need to undergo validation.</li>
* <li>Built Concepts - Prevents rebuilding when the same vertex is encountered</li>
* <li>The Ontology - Optimises validation checks by preventing db read. </li>
* <li>Type Labels - Allows mapping type labels to type Ids</li>
* <li>Transaction meta Data - Allows transactions to function in different ways</li>
* <ol/>
* </p>
*
* @author fppt
*
*/
class TxCache {
//Graph cache which is shared across multiple transactions
private final GraphCache graphCache;
//Caches any concept which has been touched before
private final Map<ConceptId, Concept> conceptCache = new HashMap<>();
private final Map<Label, OntologyConcept> ontologyConceptCache = new HashMap<>();
private final Map<Label, LabelId> labelCache = new HashMap<>();
//Elements Tracked For Validation
private final Set<Entity> modifiedEntities = new HashSet<>();
private final Set<Role> modifiedRoles = new HashSet<>();
private final Set<Casting> modifiedCastings = new HashSet<>();
private final Set<RelationType> modifiedRelationTypes = new HashSet<>();
private final Set<Relation> modifiedRelations = new HashSet<>();
private final Set<Rule> modifiedRules = new HashSet<>();
private final Set<Resource> modifiedResources = new HashSet<>();
//We Track Relations so that we can look them up before they are completely defined and indexed on commit
private final Map<String, Relation> relationIndexCache = new HashMap<>();
//We Track the number of concept connections which have been made which may result in a new shard
private final Map<ConceptId, Long> shardingCount = new HashMap<>();
//Transaction Specific Meta Data
private boolean isTxOpen = false;
private GraknTxType txType;
private String closedReason = null;
TxCache(GraphCache graphCache) {
this.graphCache = graphCache;
}
/**
* A helper method which writes back into the graph cache at the end of a transaction.
*
* @param isSafe true only if it is safe to copy the cache completely without any checks
*/
void writeToGraphCache(boolean isSafe){
//When a commit has occurred or a graph is read only all types can be overridden this is because we know they are valid.
if(isSafe) graphCache.readTxCache(this);
//When a commit has not occurred some checks are required
//TODO: Fill our cache when not committing and when not read only graph.
}
/**
*
* @return true if ths ontology labels have been cached. The graph cannot operate if this is false.
*/
boolean ontologyNotCached(){
return labelCache.isEmpty();
}
/**
* Refreshes the transaction ontology cache by reading the central ontology cache is read into this transaction cache.
* This method performs this operation whilst making a deep clone of the cached concepts to ensure transactions
* do not accidentally break the central ontology cache.
*
*/
void refreshOntologyCache(){
Map<Label, OntologyConcept> cachedOntologySnapshot = graphCache.getCachedTypes();
Map<Label, LabelId> cachedLabelsSnapshot = graphCache.getCachedLabels();
//Read central cache into txCache cloning only base concepts. Sets clones later
for (OntologyConcept type : cachedOntologySnapshot.values()) {
cacheConcept((ConceptImpl) type);
}
//Load Labels Separately. We do this because the TypeCache may have expired.
cachedLabelsSnapshot.forEach(this::cacheLabel);
}
/**
*
* @param concept The element to be later validated
*/
void trackForValidation(Concept concept) {
if (concept.isEntity()) {
modifiedEntities.add(concept.asEntity());
} else if (concept.isRole()) {
modifiedRoles.add(concept.asRole());
} else if (concept.isRelationType()) {
modifiedRelationTypes.add(concept.asRelationType());
} else if (concept.isRelation()){
Relation relation = concept.asRelation();
modifiedRelations.add(relation);
//Caching of relations in memory so they can be retrieved without needing a commit
relationIndexCache.put(RelationReified.generateNewHash(relation.type(), relation.allRolePlayers()), relation);
} else if (concept.isRule()){
modifiedRules.add(concept.asRule());
} else if (concept.isResource()){
modifiedResources.add(concept.asResource());
}
}
void trackForValidation(Casting casting) {
modifiedCastings.add(casting);
}
/**
*
* @return All the relations which have been affected in the transaction
*/
Map<String, Relation> getRelationIndexCache(){
return relationIndexCache;
}
/**
*
* @return All the types that have gained or lost instances and by how much
*/
Map<ConceptId, Long> getShardingCount(){
return shardingCount;
}
/**
*
* @return All the types currently cached in the transaction. Used for
*/
Map<Label, OntologyConcept> getOntologyConceptCache(){
return ontologyConceptCache;
}
/**
*
* @return All the types labels currently cached in the transaction.
*/
Map<Label, LabelId> getLabelCache(){
return labelCache;
}
/**
*
* @return All the concepts which have been accessed in this transaction
*/
Map<ConceptId, Concept> getConceptCache() {
return conceptCache;
}
/**
*
* @param concept The concept to no longer track
*/
@SuppressWarnings("SuspiciousMethodCalls")
void remove(Concept concept){
modifiedEntities.remove(concept);
modifiedRoles.remove(concept);
modifiedRelationTypes.remove(concept);
modifiedRelations.remove(concept);
modifiedRules.remove(concept);
modifiedResources.remove(concept);
conceptCache.remove(concept.getId());
if (concept.isOntologyConcept()) {
Label label = ((OntologyConceptImpl) concept).getLabel();
ontologyConceptCache.remove(label);
labelCache.remove(label);
}
}
/**
* Gets a cached relation by index. This way we can find non committed relations quickly.
*
* @param index The current index of the relation
*/
Relation getCachedRelation(String index){
return relationIndexCache.get(index);
}
/**
* Caches a concept so it does not have to be rebuilt later.
*
* @param concept The concept to be cached.
*/
void cacheConcept(Concept concept){
conceptCache.put(concept.getId(), concept);
if(concept.isOntologyConcept()){
OntologyConceptImpl ontologyElement = (OntologyConceptImpl) concept;
ontologyConceptCache.put(ontologyElement.getLabel(), ontologyElement);
labelCache.put(ontologyElement.getLabel(), ontologyElement.getLabelId());
}
}
/**
* Caches the mapping of a type label to a type id. This is necessary in order for ANY types to be looked up.
*
* @param label The type label to cache
* @param id Its equivalent id which can be looked up quickly in the graph
*/
private void cacheLabel(Label label, LabelId id){
labelCache.put(label, id);
}
/**
* Checks if the concept has been built before and is currently cached
*
* @param id The id of the concept
* @return true if the concept is cached
*/
boolean isConceptCached(ConceptId id){
return conceptCache.containsKey(id);
}
/**
*
* @param label The label of the type to cache
* @return true if the concept is cached
*/
boolean isTypeCached(Label label){
return ontologyConceptCache.containsKey(label);
}
/**
*
* @param label the type label which may be in the cache
* @return true if the label is cached and has a valid mapping to a id
*/
boolean isLabelCached(Label label){
return labelCache.containsKey(label);
}
/**
* Returns a previously built concept
*
* @param id The id of the concept
* @param <X> The type of the concept
* @return The cached concept
*/
<X extends Concept> X getCachedConcept(ConceptId id){
//noinspection unchecked
return (X) conceptCache.get(id);
}
/**
* Returns a previously built type
*
* @param label The label of the type
* @param <X> The type of the type
* @return The cached type
*/
<X extends OntologyConcept> X getCachedOntologyElement(Label label){
//noinspection unchecked
return (X) ontologyConceptCache.get(label);
}
LabelId convertLabelToId(Label label){
return labelCache.get(label);
}
void addedInstance(ConceptId conceptId){
shardingCount.compute(conceptId, (key, value) -> value == null ? 1 : value + 1);
cleanupShardingCount(conceptId);
}
void removedInstance(ConceptId conceptId){
shardingCount.compute(conceptId, (key, value) -> value == null ? -1 : value - 1);
cleanupShardingCount(conceptId);
}
private void cleanupShardingCount(ConceptId conceptId){
if(shardingCount.get(conceptId) == 0) shardingCount.remove(conceptId);
}
Json getFormattedLog(){
//Concepts In Need of Inspection
Json conceptsForInspection = Json.object();
conceptsForInspection.set(Schema.BaseType.RESOURCE.name(), loadConceptsForFixing(getModifiedResources()));
//Types with instance changes
Json typesWithInstanceChanges = Json.array();
getShardingCount().forEach((key, value) -> {
Json jsonObject = Json.object();
jsonObject.set(REST.Request.COMMIT_LOG_CONCEPT_ID, key.getValue());
jsonObject.set(REST.Request.COMMIT_LOG_SHARDING_COUNT, value);
typesWithInstanceChanges.add(jsonObject);
});
//Final Commit Log
Json formattedLog = Json.object();
formattedLog.set(REST.Request.COMMIT_LOG_FIXING, conceptsForInspection);
formattedLog.set(REST.Request.COMMIT_LOG_COUNTING, typesWithInstanceChanges);
return formattedLog;
}
private <X extends Thing> Json loadConceptsForFixing(Set<X> instances){
Map<String, Set<String>> conceptByIndex = new HashMap<>();
instances.forEach(thing ->
conceptByIndex.computeIfAbsent(((ThingImpl) thing).getIndex(), (e) -> new HashSet<>()).add(thing.getId().getValue()));
return Json.make(conceptByIndex);
}
//--------------------------------------- Concepts Needed For Validation -------------------------------------------
Set<Entity> getModifiedEntities() {
return modifiedEntities;
}
Set<Role> getModifiedRoles() {
return modifiedRoles;
}
Set<RelationType> getModifiedRelationTypes() {
return modifiedRelationTypes;
}
Set<Relation> getModifiedRelations() {
return modifiedRelations;
}
Set<Rule> getModifiedRules() {
return modifiedRules;
}
Set<Resource> getModifiedResources() {
return modifiedResources;
}
Set<Casting> getModifiedCastings() {
return modifiedCastings;
}
//--------------------------------------- Transaction Specific Meta Data -------------------------------------------
void closeTx(String closedReason){
isTxOpen = false;
this.closedReason = closedReason;
modifiedEntities.clear();
modifiedRoles.clear();
modifiedRelationTypes.clear();
modifiedRelations.clear();
modifiedRules.clear();
modifiedResources.clear();
modifiedCastings.clear();
relationIndexCache.clear();
shardingCount.clear();
conceptCache.clear();
ontologyConceptCache.clear();
labelCache.clear();
}
void openTx(GraknTxType txType){
isTxOpen = true;
this.txType = txType;
closedReason = null;
}
boolean isTxOpen(){
return isTxOpen;
}
GraknTxType txType(){
return txType;
}
String getClosedReason(){
return closedReason;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/TypeImpl.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.concept.Concept;
import ai.grakn.concept.Label;
import ai.grakn.concept.OntologyConcept;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.ResourceType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Thing;
import ai.grakn.concept.Type;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Direction;
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.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 RelationType}
* @param <V> The instance of this type. For example {@link ai.grakn.concept.Entity} or {@link ai.grakn.concept.Relation}
*/
class TypeImpl<T extends Type, V extends Thing> extends OntologyConceptImpl<T> implements Type{
protected final Logger LOG = LoggerFactory.getLogger(TypeImpl.class);
private final Cache<Boolean> cachedIsAbstract = new Cache<>(() -> vertex().propertyBoolean(Schema.VertexProperty.IS_ABSTRACT));
private final Cache<Set<T>> cachedShards = new Cache<>(() -> this.<T>neighbours(Direction.IN, Schema.EdgeLabel.SHARD).collect(Collectors.toSet()));
//This cache is different in order to keep track of which plays are required
private final Cache<Map<Role, Boolean>> cachedDirectPlays = new Cache<>(() -> {
Map<Role, Boolean> roleTypes = new HashMap<>();
vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.PLAYS).forEach(edge -> {
Role role = vertex().graph().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);
}
TypeImpl(VertexElement vertexElement, T superType, Boolean isImplicit) {
super(vertexElement, superType, isImplicit);
}
/**
* Flushes the internal transaction caches so they can refresh with persisted graph
*/
@Override
public void txCacheFlush(){
super.txCacheFlush();
cachedIsAbstract.flush();
cachedShards.flush();
cachedDirectPlays.flush();
}
/**
* Clears the internal transaction caches
*/
@Override
public void txCacheClear(){
super.txCacheClear();
cachedIsAbstract.clear();
cachedShards.clear();
cachedDirectPlays.clear();
}
/**
* 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) {
preCheckForInstanceCreation();
V instance = finder.get();
if(instance == null) instance = addInstance(instanceBaseType, producer, false);
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 checkNeeded){
if(checkNeeded) preCheckForInstanceCreation();
if(isAbstract()) throw GraphOperationException.addingInstancesToAbstractType(this);
VertexElement instanceVertex = vertex().graph().addVertex(instanceBaseType);
if(!Schema.MetaSchema.isMetaLabel(getLabel())) {
vertex().graph().txCache().addedInstance(getId());
}
return producer.apply(instanceVertex, getThis());
}
/**
* 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 a resource to a meta type
*/
void preCheckForInstanceCreation(){
vertex().graph().checkMutationAllowed();
if(Schema.MetaSchema.isMetaLabel(getLabel()) && !Schema.MetaSchema.INFERENCE_RULE.getLabel().equals(getLabel()) && !Schema.MetaSchema.CONSTRAINT_RULE.getLabel().equals(getLabel())){
throw GraphOperationException.metaTypeImmutable(getLabel());
}
}
/**
*
* @return A list of all the roles this Type is allowed to play.
*/
@Override
public Collection<Role> plays() {
Set<Role> allRoles = new HashSet<>();
//Get the immediate plays which may be cached
allRoles.addAll(directPlays().keySet());
//Now get the super type plays (Which may also be cached locally within their own context
Set<T> superSet = superSet();
superSet.remove(this); //We already have the plays from ourselves
superSet.forEach(superParent -> allRoles.addAll(((TypeImpl<?,?>) superParent).directPlays().keySet()));
return Collections.unmodifiableCollection(allRoles);
}
@Override
public Collection<ResourceType> resources() {
Collection<ResourceType> resources = resources(Schema.ImplicitType.HAS_OWNER);
resources.addAll(keys());
return resources;
}
@Override
public Collection<ResourceType> keys() {
return resources(Schema.ImplicitType.KEY_OWNER);
}
private Collection<ResourceType> resources(Schema.ImplicitType implicitType){
//TODO: Make this less convoluted
String [] implicitIdentifiers = implicitType.getLabel("").getValue().split("--");
String prefix = implicitIdentifiers[0] + "-";
String suffix = "-" + implicitIdentifiers[1];
Set<ResourceType> resourceTypes = new HashSet<>();
//A traversal is not used in this caching so that ontology caching can be taken advantage of.
plays().forEach(roleType -> roleType.relationTypes().forEach(relationType -> {
String roleTypeLabel = roleType.getLabel().getValue();
if(roleTypeLabel.startsWith(prefix) && roleTypeLabel.endsWith(suffix)){ //This is the implicit type we want
String resourceTypeLabel = roleTypeLabel.replace(prefix, "").replace(suffix, "");
resourceTypes.add(vertex().graph().getResourceType(resourceTypeLabel));
}
}));
return resourceTypes;
}
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 subs of this concept including itself
*/
@Override
public Collection<T> subs(){
return Collections.unmodifiableCollection(super.subs());
}
/**
*
* @return All the instances of this type.
*/
@SuppressWarnings("unchecked")
@Override
public Collection<V> instances() {
Set<V> instances = new HashSet<>();
//TODO: Clean this up. Maybe remove role from the meta ontology
//OntologyConcept is used here because when calling `graph.admin().getMataConcept().instances()` a role can appear
//When that happens this leads to a crash
for (OntologyConcept sub : subs()) {
if (!sub.isRole()) {
TypeImpl<?, V> typeImpl = (TypeImpl) sub;
typeImpl.instancesDirect().forEach(instances::add);
}
}
return Collections.unmodifiableCollection(instances);
}
Stream<V> instancesDirect(){
return vertex().getEdgesOfType(Direction.IN, Schema.EdgeLabel.SHARD).
map(edge -> vertex().graph().factory().buildShard(edge.source())).
flatMap(Shard::<V>links);
}
/**
*
* @return returns true if the type is set to be abstract.
*/
@Override
public Boolean isAbstract() {
return cachedIsAbstract.get();
}
/**
*
* @return A list of the Instances which scope this Relation
*/
@Override
public Set<Thing> scopes() {
HashSet<Thing> scopes = new HashSet<>();
neighbours(Direction.OUT, Schema.EdgeLabel.HAS_SCOPE).forEach(concept -> scopes.add(concept.asThing()));
return scopes;
}
/**
*
* @param thing A new thing which can scope this concept
* @return The concept itself
*/
@Override
public T scope(Thing thing) {
putEdge(ConceptVertex.from(thing), Schema.EdgeLabel.HAS_SCOPE);
return getThis();
}
/**
* @param scope A concept which is currently scoping this concept.
* @return The Relation itself
*/
@Override
public T deleteScope(Thing scope) {
deleteEdge(Direction.OUT, Schema.EdgeLabel.HAS_SCOPE, (Concept) scope);
return getThis();
}
void trackRolePlayers(){
instances().forEach(concept -> ((ThingImpl<?, ?>)concept).castingsInstance().forEach(
rolePlayer -> vertex().graph().txCache().trackForValidation(rolePlayer)));
}
T plays(Role role, boolean required) {
checkOntologyMutationAllowed();
//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 plays(role, false);
}
/**
*
* @param role The Role Type which the instances of this Type should no longer be allowed to play.
* @return The Type itself.
*/
@Override
public T deletePlays(Role role) {
checkOntologyMutationAllowed();
deleteEdge(Direction.OUT, Schema.EdgeLabel.PLAYS, (Concept) role);
cachedDirectPlays.ifPresent(set -> set.remove(role));
((RoleImpl) role).deleteCachedDirectPlaysByType(this);
trackRolePlayers();
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 setAbstract(Boolean isAbstract) {
if(!Schema.MetaSchema.isMetaLabel(getLabel()) && isAbstract && instancesDirect().findAny().isPresent()){
throw GraphOperationException.addingInstancesToAbstractType(this);
}
property(Schema.VertexProperty.IS_ABSTRACT, isAbstract);
cachedIsAbstract.set(isAbstract);
return getThis();
}
T property(Schema.VertexProperty key, Object value){
if(!Schema.VertexProperty.CURRENT_LABEL_ID.equals(key)) checkOntologyMutationAllowed();
vertex().property(key, value);
return getThis();
}
/**
* Creates a relation type which allows this type and a resource type to be linked.
* @param resourceType The resource type 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 resource type
* @param hasOwner the implicit role type to build for the type
* @param required Indicates if the resource is required on the entity
* @return The Type itself
*/
public T has(ResourceType resourceType, Schema.ImplicitType has, Schema.ImplicitType hasValue, Schema.ImplicitType hasOwner, boolean required){
//Check if this is a met type
checkOntologyMutationAllowed();
//Check if resource type is the meta
if(Schema.MetaSchema.RESOURCE.getLabel().equals(resourceType.getLabel())){
throw GraphOperationException.metaTypeImmutable(resourceType.getLabel());
}
Label resourceLabel = resourceType.getLabel();
Role ownerRole = vertex().graph().putRoleTypeImplicit(hasOwner.getLabel(resourceLabel));
Role valueRole = vertex().graph().putRoleTypeImplicit(hasValue.getLabel(resourceLabel));
RelationType relationType = vertex().graph().putRelationTypeImplicit(has.getLabel(resourceLabel)).
relates(ownerRole).
relates(valueRole);
//Linking with ako structure if present
ResourceType resourceTypeSuper = resourceType.sup();
Label superLabel = resourceTypeSuper.getLabel();
if(!Schema.MetaSchema.RESOURCE.getLabel().equals(superLabel)) { //Check to make sure we dont add plays edges to meta types accidentally
Role ownerRoleSuper = vertex().graph().putRoleTypeImplicit(hasOwner.getLabel(superLabel));
Role valueRoleSuper = vertex().graph().putRoleTypeImplicit(hasValue.getLabel(superLabel));
RelationType relationTypeSuper = vertex().graph().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);
relationType.sup(relationTypeSuper);
//Make sure the supertype resource is linked with the role as well
((ResourceTypeImpl) resourceTypeSuper).plays(valueRoleSuper);
}
this.plays(ownerRole, required);
//TODO: Use explicit cardinality of 0-1 rather than just false
((ResourceTypeImpl) resourceType).plays(valueRole, false);
return getThis();
}
/**
* Creates a relation type which allows this type and a resource type to be linked.
* @param resourceType The resource type which instances of this type should be allowed to play.
* @return The Type itself
*/
@Override
public T resource(ResourceType resourceType){
checkNonOverlapOfImplicitRelations(Schema.ImplicitType.KEY_OWNER, resourceType);
return has(resourceType, Schema.ImplicitType.HAS, Schema.ImplicitType.HAS_VALUE, Schema.ImplicitType.HAS_OWNER, false);
}
@Override
public T key(ResourceType resourceType) {
checkNonOverlapOfImplicitRelations(Schema.ImplicitType.HAS_OWNER, resourceType);
return has(resourceType, Schema.ImplicitType.KEY, Schema.ImplicitType.KEY_VALUE, Schema.ImplicitType.KEY_OWNER, true);
}
/**
* Checks if the provided resource type is already used in an other implicit relation.
*
* @param implicitType The implicit relation to check against.
* @param resourceType The resource type which should not be in that implicit relation
*
* @throws GraphOperationException when the resource type is already used in another implicit relation
*/
private void checkNonOverlapOfImplicitRelations(Schema.ImplicitType implicitType, ResourceType resourceType){
if(resources(implicitType).contains(resourceType)) {
throw GraphOperationException.duplicateHas(this, resourceType);
}
}
public static TypeImpl from(Type type){
return (TypeImpl) type;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/ValidateGlobalRules.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.GraknGraph;
import ai.grakn.concept.Label;
import ai.grakn.concept.OntologyConcept;
import ai.grakn.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Rule;
import ai.grakn.concept.Thing;
import ai.grakn.concept.Type;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.graql.Pattern;
import ai.grakn.graql.admin.Atomic;
import ai.grakn.graql.admin.Conjunction;
import ai.grakn.graql.admin.ReasonerQuery;
import ai.grakn.graql.admin.VarPatternAdmin;
import ai.grakn.util.ErrorMessage;
import ai.grakn.util.Schema;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static ai.grakn.util.ErrorMessage.VALIDATION_CASTING;
import static ai.grakn.util.ErrorMessage.VALIDATION_INSTANCE;
import static ai.grakn.util.ErrorMessage.VALIDATION_RELATION_CASTING_LOOP_FAIL;
import static ai.grakn.util.ErrorMessage.VALIDATION_RELATION_DUPLICATE;
import static ai.grakn.util.ErrorMessage.VALIDATION_RELATION_MORE_CASTING_THAN_ROLES;
import static ai.grakn.util.ErrorMessage.VALIDATION_RELATION_TYPE;
import static ai.grakn.util.ErrorMessage.VALIDATION_RELATION_TYPES_ROLES_SCHEMA;
import static ai.grakn.util.ErrorMessage.VALIDATION_REQUIRED_RELATION;
import static ai.grakn.util.ErrorMessage.VALIDATION_ROLE_TYPE_MISSING_RELATION_TYPE;
import static ai.grakn.util.ErrorMessage.VALIDATION_TOO_MANY_KEYS;
/**
* <p>
* Specific Validation Rules
* </p>
*
* <p>
* This class contains the implementation for the following validation rules:
* 1. Plays Validation which ensures that a {@link Thing} is allowed to play the {@link Role}
* it has been assigned to.
* 2. Relates Validation which ensures that every {@link Role} which is not abstract is
* assigned to a {@link RelationType} via {@link RelationType#relates(Role)}.
* 3. Minimum Role Validation which ensures that every {@link RelationType} has at least 2 {@link Role}
* assigned to it via {@link RelationType#relates(Role)}.
* 4. Relation Structure Validation which ensures that each {@link ai.grakn.concept.Relation} has the
* correct structure.
* 5. Abstract Type Validation which ensures that each abstract {@link Type} has no {@link Thing}.
* 6. Relation Type Hierarchy Validation which ensures that {@link RelationType} with a hierarchical structure
* have a valid matching {@link Role} hierarchical structure.
* 7. Required Resources validation which ensures that each {@link Thing} with required
* {@link ai.grakn.concept.Resource} has a valid {@link ai.grakn.concept.Relation} to that Resource.
* 8. Unique Relation Validation which ensures that no duplicate {@link ai.grakn.concept.Relation} are created.
* </p>
*
* @author fppt
*/
class ValidateGlobalRules {
private ValidateGlobalRules() {
throw new UnsupportedOperationException();
}
/**
* This method checks if the plays edge has been added successfully. It does so By checking
* Casting -CAST-> ConceptInstance -ISA-> Concept -PLAYS-> X =
* Casting -ISA-> X
* @param casting The casting to be validated
* @return A specific error if one is found.
*/
static Optional<String> validatePlaysStructure(Casting casting) {
Thing thing = casting.getInstance();
TypeImpl<?, ?> currentConcept = (TypeImpl<?, ?>) thing.type();
Role role = casting.getRoleType();
boolean satisfiesPlays = false;
while(currentConcept != null){
Map<Role, Boolean> plays = currentConcept.directPlays();
for (Map.Entry<Role, Boolean> playsEntry : plays.entrySet()) {
Role rolePlayed = playsEntry.getKey();
Boolean required = playsEntry.getValue();
if(rolePlayed.getLabel().equals(role.getLabel())){
satisfiesPlays = true;
// Assert unique relation for this role type
if (required && thing.relations(role).size() != 1) {
return Optional.of(VALIDATION_REQUIRED_RELATION.getMessage(thing.getId(), thing.type().getLabel(), role.getLabel(), thing.relations(role).size()));
}
}
}
currentConcept = (TypeImpl) currentConcept.sup();
}
if(satisfiesPlays) {
return Optional.empty();
} else {
return Optional.of(VALIDATION_CASTING.getMessage(thing.type().getLabel(), thing.getId(), casting.getRoleType().getLabel()));
}
}
/**
*
* @param role The Role to validate
* @return An error message if the relates does not have a single incoming RELATES edge
*/
static Optional<String> validateHasSingleIncomingRelatesEdge(Role role){
if(role.relationTypes().isEmpty()) {
return Optional.of(VALIDATION_ROLE_TYPE_MISSING_RELATION_TYPE.getMessage(role.getLabel()));
}
return Optional.empty();
}
/**
*
* @param relationType The RelationType to validate
* @return An error message if the relationTypes does not have at least 2 roles
*/
static Optional<String> validateHasMinimumRoles(RelationType relationType) {
if(relationType.isAbstract() || relationType.relates().size() >= 1){
return Optional.empty();
} else {
return Optional.of(VALIDATION_RELATION_TYPE.getMessage(relationType.getLabel()));
}
}
/**
*
* @param relation The assertion to validate
* @return An error message indicating if the relation has an incorrect structure. This includes checking if there an equal
* number of castings and roles as well as looping the structure to make sure castings lead to the same relation type.
*/
static Optional<String> validateRelationshipStructure(RelationReified relation){
RelationType relationType = relation.type();
Collection<Casting> castings = relation.castingsRelation().collect(Collectors.toSet());
Collection<Role> roles = relationType.relates();
Set<Role> rolesViaRolePlayers = castings.stream().map(Casting::getRoleType).collect(Collectors.toSet());
if(rolesViaRolePlayers.size() > roles.size()) {
return Optional.of(VALIDATION_RELATION_MORE_CASTING_THAN_ROLES.getMessage(relation.getId(), rolesViaRolePlayers.size(), relationType.getLabel(), roles.size()));
}
for(Casting casting : castings){
boolean notFound = true;
for (RelationType innerRelationType : casting.getRoleType().relationTypes()) {
if(innerRelationType.getLabel().equals(relationType.getLabel())){
notFound = false;
break;
}
}
if(notFound) {
return Optional.of(VALIDATION_RELATION_CASTING_LOOP_FAIL.getMessage(relation.getId(), casting.getRoleType().getLabel(), relationType.getLabel()));
}
}
return Optional.empty();
}
/**
*
* @param relationType the relation type to be validated
* @return Error messages if the role type sub structure does not match the relation type sub structure
*/
static Set<String> validateRelationTypesToRolesSchema(RelationType relationType){
RelationTypeImpl superRelationType = (RelationTypeImpl) relationType.sup();
if(Schema.MetaSchema.isMetaLabel(superRelationType.getLabel())){ //If super type is a meta type no validation needed
return Collections.emptySet();
}
Set<String> errorMessages = new HashSet<>();
Collection<Role> superRelates = superRelationType.relates();
Collection<Role> relates = relationType.relates();
Set<Label> relatesLabels = relates.stream().map(OntologyConcept::getLabel).collect(Collectors.toSet());
//TODO: Determine if this check is redundant
//Check 1) Every role of relationTypes is the sub of a role which is in the relates of it's supers
if(!superRelationType.isAbstract()) {
Set<Label> allSuperRolesPlayed = new HashSet<>();
superRelationType.superSet().forEach(rel -> rel.relates().forEach(roleType -> allSuperRolesPlayed.add(roleType.getLabel())));
for (Role relate : relates) {
boolean validRoleTypeFound = false;
Set<Role> superRoles = ((RoleImpl) relate).superSet();
for (Role superRole : superRoles) {
if(allSuperRolesPlayed.contains(superRole.getLabel())){
validRoleTypeFound = true;
break;
}
}
if(!validRoleTypeFound){
errorMessages.add(VALIDATION_RELATION_TYPES_ROLES_SCHEMA.getMessage(relate.getLabel(), relationType.getLabel(), "super", "super", superRelationType.getLabel()));
}
}
}
//Check 2) Every role of superRelationType has a sub role which is in the relates of relationTypes
for (Role superRelate : superRelates) {
boolean subRoleNotFoundInRelates = true;
for (Role subRole : superRelate.subs()) {
if(relatesLabels.contains(subRole.getLabel())){
subRoleNotFoundInRelates = false;
break;
}
}
if(subRoleNotFoundInRelates){
errorMessages.add(VALIDATION_RELATION_TYPES_ROLES_SCHEMA.getMessage(superRelate.getLabel(), superRelationType.getLabel(), "sub", "sub", relationType.getLabel()));
}
}
return errorMessages;
}
/**
*
* @param thing The thing to be validated
* @return An error message if the thing does not have all the required resources
*/
static Optional<String> validateInstancePlaysAllRequiredRoles(Thing thing) {
TypeImpl<?, ?> currentConcept = (TypeImpl) thing.type();
while(currentConcept != null){
Map<Role, Boolean> plays = currentConcept.directPlays();
for (Map.Entry<Role, Boolean> playsEntry : plays.entrySet()) {
if(playsEntry.getValue()){
Role role = playsEntry.getKey();
// Assert there is a relation for this type
Collection<Relation> relations = thing.relations(role);
if (relations.isEmpty()) {
return Optional.of(VALIDATION_INSTANCE.getMessage(thing.getId(), thing.type().getLabel(), role.getLabel()));
} else if(relations.size() > 1){
Label resourceTypeLabel = Schema.ImplicitType.explicitLabel(role.getLabel());
return Optional.of(VALIDATION_TOO_MANY_KEYS.getMessage(thing.getId(), resourceTypeLabel));
}
}
}
currentConcept = (TypeImpl) currentConcept.sup();
}
return Optional.empty();
}
/**
* @param graph graph used to ensure the relation is unique
* @param relationReified The relation whose hash needs to be set.
* @return An error message if the relation is not unique.
*/
static Optional<String> validateRelationIsUnique(AbstractGraknGraph<?> graph, RelationReified relationReified){
RelationImpl foundRelation = graph.getConcept(Schema.VertexProperty.INDEX, RelationReified.generateNewHash(relationReified.type(), relationReified.allRolePlayers()));
if(foundRelation == null){
relationReified.setHash();
} else if(foundRelation.reified().isPresent() && !foundRelation.reified().get().equals(relationReified)){
return Optional.of(VALIDATION_RELATION_DUPLICATE.getMessage(relationReified));
}
return Optional.empty();
}
/**
* @param graph graph used to ensure the rule is a valid Horn clause
* @param rule the rule to be validated
* @return Error messages if the rule is not a valid Horn clause (in implication form, conjunction in the body, single-atom conjunction in the head)
*/
static Set<String> validateRuleIsValidHornClause(GraknGraph graph, Rule rule){
Set<String> errors = new HashSet<>();
if (rule.getWhen().admin().isDisjunction()){
errors.add(ErrorMessage.VALIDATION_RULE_DISJUNCTION_IN_BODY.getMessage(rule.getId(), rule.type().getLabel()));
}
errors.addAll(checkRuleHeadInvalid(graph, rule, rule.getThen()));
return errors;
}
/**
* NB: this only gets checked if the rule obeys the Horn clause form
* @param graph graph used to ensure the rule is a valid Horn clause
* @param rule the rule to be validated ontologically
* @return Error messages if the rule has ontological inconsistencies
*/
static Set<String> validateRuleOntologically(GraknGraph graph, Rule rule) {
Set<String> errors = new HashSet<>();
//both body and head refer to the same graph and have to be valid with respect to the ontology that governs it
//as a result the rule can be ontologically validated by combining them into a conjunction
//this additionally allows to cross check body-head references
ReasonerQuery combined = rule
.getWhen()
.and(rule.getThen())
.admin().getDisjunctiveNormalForm().getPatterns().iterator().next()
.toReasonerQuery(graph);
errors.addAll(combined.validateOntologically());
return errors;
}
/**
* @param graph graph used to ensure the rule head is valid
* @param rule the rule to be validated
* @param head head of the rule of interest
* @return Error messages if the rule head is invalid - is not a single-atom conjunction, doesn't contain illegal atomics and is ontologically valid
*/
private static Set<String> checkRuleHeadInvalid(GraknGraph graph, Rule rule, Pattern head) {
Set<String> errors = new HashSet<>();
Set<Conjunction<VarPatternAdmin>> patterns = head.admin().getDisjunctiveNormalForm().getPatterns();
if (patterns.size() != 1){
errors.add(ErrorMessage.VALIDATION_RULE_DISJUNCTION_IN_HEAD.getMessage(rule.getId(), rule.type().getLabel()));
} else {
ReasonerQuery headQuery = patterns.iterator().next().toReasonerQuery(graph);
Set<Atomic> allowed = headQuery.getAtoms().stream()
.filter(Atomic::isAllowedToFormRuleHead).collect(Collectors.toSet());
if (allowed.size() > 1) {
errors.add(ErrorMessage.VALIDATION_RULE_HEAD_NON_ATOMIC.getMessage(rule.getId(), rule.type().getLabel()));
}
else if (allowed.isEmpty()){
errors.add(ErrorMessage.VALIDATION_RULE_ILLEGAL_ATOMIC_IN_HEAD.getMessage(rule.getId(), rule.type().getLabel()));
}
}
return errors;
}
/**
*
* @param rule The rule to be validated
* @return Error messages if the when or then of a rule refers to a non existent type
*/
static Set<String> validateRuleOntologyElementsExist(GraknGraph graph, Rule rule){
Set<String> errors = new HashSet<>();
errors.addAll(checkRuleSideInvalid(graph, rule, Schema.VertexProperty.RULE_WHEN, rule.getWhen()));
errors.addAll(checkRuleSideInvalid(graph, rule, Schema.VertexProperty.RULE_THEN, rule.getThen()));
return errors;
}
/**
*
* @param graph The graph to query against
* @param rule The rule the pattern was extracted from
* @param side The side from which the pattern was extracted
* @param pattern The pattern from which we will extract the types in the pattern
* @return A list of errors if the pattern refers to any non-existent types in the graph
*/
private static Set<String> checkRuleSideInvalid(GraknGraph graph, Rule rule, Schema.VertexProperty side, Pattern pattern) {
Set<String> errors = new HashSet<>();
pattern.admin().getVars().stream()
.flatMap(v -> v.getInnerVars().stream())
.flatMap(v -> v.getTypeLabels().stream()).forEach(typeLabel -> {
OntologyConcept ontologyConcept = graph.getOntologyConcept(typeLabel);
if(ontologyConcept == null){
errors.add(ErrorMessage.VALIDATION_RULE_MISSING_ELEMENTS.getMessage(side, rule.getId(), rule.type().getLabel(), typeLabel));
} else {
if(Schema.VertexProperty.RULE_WHEN.equals(side)){
RuleImpl.from(rule).addHypothesis(ontologyConcept);
} else if (Schema.VertexProperty.RULE_THEN.equals(side)){
RuleImpl.from(rule).addConclusion(ontologyConcept);
} else {
throw GraphOperationException.invalidPropertyUse(rule, side);
}
}
});
return errors;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/Validator.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.concept.Relation;
import ai.grakn.concept.RelationType;
import ai.grakn.concept.Role;
import ai.grakn.concept.Rule;
import ai.grakn.concept.Thing;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* <p>
* Ensures each concept undergoes the correct type of validation.
* </p>
*
* <p>
* Handles calling the relevant validation defined in {@link ValidateGlobalRules} depending on the
* type of the concept.
* </p>
*
* @author fppt
*
*/
class Validator {
private final AbstractGraknGraph<?> graknGraph;
private final List<String> errorsFound = new ArrayList<>();
public Validator(AbstractGraknGraph graknGraph){
this.graknGraph = graknGraph;
}
/**
*
* @return Any errors found during validation
*/
public List<String> getErrorsFound(){
return errorsFound;
}
/**
*
* @return True if the data and schema conforms to our concept.
*/
public boolean validate(){
//Validate Entity Types
//Not Needed
//Validate Entities
graknGraph.txCache().getModifiedEntities().forEach(this::validateThing);
//Validate RoleTypes
graknGraph.txCache().getModifiedRoles().forEach(this::validateRole);
//Validate Role Players
graknGraph.txCache().getModifiedCastings().forEach(this::validateCasting);
//Validate Relation Types
graknGraph.txCache().getModifiedRelationTypes().forEach(this::validateRelationType);
//Validate Relations
graknGraph.txCache().getModifiedRelations().forEach(relation -> validateRelation(graknGraph, relation));
//Validate Rule Types
//Not Needed
//Validate Rules
graknGraph.txCache().getModifiedRules().forEach(rule -> validateRule(graknGraph, rule));
//Validate Resource Types
//Not Needed
//Validate Resource
graknGraph.txCache().getModifiedResources().forEach(this::validateThing);
return errorsFound.size() == 0;
}
/**
* Validation rules exclusive to rules
* @param graph the graph to query against
* @param rule the rule which needs to be validated
*/
private void validateRule(AbstractGraknGraph<?> graph, Rule rule){
Set<String> labelErrors = ValidateGlobalRules.validateRuleOntologyElementsExist(graph, rule);
errorsFound.addAll(labelErrors);
errorsFound.addAll(ValidateGlobalRules.validateRuleIsValidHornClause(graph, rule));
if (labelErrors.isEmpty()){
errorsFound.addAll(ValidateGlobalRules.validateRuleOntologically(graph, rule));
}
}
/**
* Validation rules exclusive to relations
* @param relation The relation to validate
*/
private void validateRelation(AbstractGraknGraph<?> graph, Relation relation){
validateThing(relation);
Optional<RelationReified> relationReified = ((RelationImpl) relation).reified();
//TODO: We need new validation mechanisms for non-reified relations
if(relationReified.isPresent()) {
ValidateGlobalRules.validateRelationshipStructure(relationReified.get()).ifPresent(errorsFound::add);
ValidateGlobalRules.validateRelationIsUnique(graph, relationReified.get()).ifPresent(errorsFound::add);
}
}
/**
* Validation rules exclusive to role players
* @param casting The Role player to validate
*/
private void validateCasting(Casting casting){
ValidateGlobalRules.validatePlaysStructure(casting).ifPresent(errorsFound::add);
}
/**
* Validation rules exclusive to role
* @param role The {@link Role} to validate
*/
private void validateRole(Role role){
ValidateGlobalRules.validateHasSingleIncomingRelatesEdge(role).ifPresent(errorsFound::add);
}
/**
* Validation rules exclusive to relation types
* @param relationType The relationTypes to validate
*/
private void validateRelationType(RelationType relationType){
ValidateGlobalRules.validateHasMinimumRoles(relationType).ifPresent(errorsFound::add);
errorsFound.addAll(ValidateGlobalRules.validateRelationTypesToRolesSchema(relationType));
}
/**
* Validation rules exclusive to instances
* @param thing The {@link Thing} to validate
*/
private void validateThing(Thing thing) {
ValidateGlobalRules.validateInstancePlaysAllRequiredRoles(thing).ifPresent(errorsFound::add);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/VertexElement.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.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 Vertex in a Grakn Graph
* </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
*/
class VertexElement extends AbstractElement<Vertex, Schema.VertexProperty>{
VertexElement(AbstractGraknGraph graknGraph, Vertex element) {
super(graknGraph, 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
*/
Stream<EdgeElement> getEdgesOfType(Direction direction, Schema.EdgeLabel label){
Iterable<Edge> iterable = () -> element().edges(direction, label.getLabel());
return StreamSupport.stream(iterable.spliterator(), false).
map(edge -> graph().factory().buildEdgeElement(edge));
}
/**
*
* @param to the target {@link VertexElement}
* @param type the type of the edge to create
* @return The edge created
*/
EdgeElement addEdge(VertexElement to, Schema.EdgeLabel type) {
return graph().factory().buildEdgeElement(element().addEdge(type.getLabel(), to.element()));
}
/**
* @param to the target {@link VertexElement}
* @param type the type of the edge to create
*/
EdgeElement putEdge(VertexElement to, Schema.EdgeLabel type){
GraphTraversal<Vertex, Edge> traversal = graph().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 graph().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
*/
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-graph/0.16.0/ai/grakn/graph
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/package-info.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>.
*/
/**
* Internal implementation of Grakn graph.
*/
package ai.grakn.graph.internal;
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/computer/GraknSparkComputer.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.computer;
import org.apache.commons.configuration.ConfigurationUtils;
import org.apache.commons.configuration.FileConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;
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.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.launcher.SparkLauncher;
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.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.spark.process.computer.payload.ViewIncomingPayload;
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.structure.io.Storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
/**
* <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 static GraknGraphRDD graknGraphRDD = null;
private org.apache.commons.configuration.Configuration apacheConfiguration = null;
private Configuration hadoopConfiguration = null;
private String jobGroupId = null;
public GraknSparkComputer(final HadoopGraph hadoopGraph) {
super(hadoopGraph);
this.sparkConfiguration = new HadoopConfiguration();
ConfigurationUtils.copy(this.hadoopGraph.configuration(), this.sparkConfiguration);
this.apacheConfiguration = new HadoopConfiguration(this.sparkConfiguration);
apacheConfiguration.setProperty(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES, false);
hadoopConfiguration = ConfUtil.makeHadoopConfiguration(apacheConfiguration);
if (hadoopConfiguration.get(Constants.GREMLIN_SPARK_GRAPH_INPUT_RDD, null) == null &&
hadoopConfiguration.get(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT, null) != null &&
FileInputFormat.class.isAssignableFrom(hadoopConfiguration
.getClass(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT, InputFormat.class))) {
try {
final String inputLocation = FileSystem.get(hadoopConfiguration)
.getFileStatus(new Path(hadoopConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION)))
.getPath().toString();
apacheConfiguration.setProperty(Constants.MAPREDUCE_INPUT_FILEINPUTFORMAT_INPUTDIR, inputLocation);
hadoopConfiguration.set(Constants.MAPREDUCE_INPUT_FILEINPUTFORMAT_INPUTDIR, inputLocation);
} catch (final IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
@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 Future<ComputerResult> submit() {
this.validateStatePriorToExecution();
return ComputerSubmissionHelper
.runWithBackgroundThread(this::submitWithExecutor, "SparkSubmitter");
}
public void cancelJobs() {
if (jobGroupId != null && graknGraphRDD != null && graknGraphRDD.sparkContext != null) {
graknGraphRDD.sparkContext.cancelJobGroup(jobGroupId);
}
}
private Future<ComputerResult> submitWithExecutor(Executor exec) {
getGraphRDD(this);
jobGroupId = Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE));
String jobDescription = this.vertexProgram == null ? this.mapReducers.toString() :
this.vertexProgram + "+" + this.mapReducers;
this.sparkConfiguration.setProperty(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION,
this.sparkConfiguration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION) + "/" + jobGroupId);
this.apacheConfiguration.setProperty(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION,
this.sparkConfiguration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
this.hadoopConfiguration.set(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION,
this.sparkConfiguration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
// create the completable future
return CompletableFuture.supplyAsync(() -> {
graknGraphRDD.sparkContext.setJobGroup(jobGroupId, jobDescription);
final long startTime = System.currentTimeMillis();
GraknSparkMemory memory = null;
JavaPairRDD<Object, VertexWritable> computedGraphRDD = null;
JavaPairRDD<Object, ViewIncomingPayload<Object>> viewIncomingRDD = null;
////////////////////////////////
// process the vertex program //
////////////////////////////////
if (null != this.vertexProgram) {
// set up the vertex program and wire up configurations
this.mapReducers.addAll(this.vertexProgram.getMapReducers());
memory = new GraknSparkMemory(this.vertexProgram, this.mapReducers, graknGraphRDD.sparkContext);
this.vertexProgram.setup(memory);
memory.broadcastMemory(graknGraphRDD.sparkContext);
final HadoopConfiguration vertexProgramConfiguration = new HadoopConfiguration();
this.vertexProgram.storeState(vertexProgramConfiguration);
ConfigurationUtils.copy(vertexProgramConfiguration, apacheConfiguration);
ConfUtil.mergeApacheIntoHadoopConfiguration(vertexProgramConfiguration, hadoopConfiguration);
// execute the vertex program
while (true) {
memory.setInTask(true);
viewIncomingRDD = GraknSparkExecutor.executeVertexProgramIteration(
graknGraphRDD.loadedGraphRDD, viewIncomingRDD, memory, vertexProgramConfiguration);
memory.setInTask(false);
if (this.vertexProgram.terminate(memory)) break;
else {
memory.incrIteration();
memory.broadcastMemory(graknGraphRDD.sparkContext);
}
}
// write the computed graph to the respective output (rdd or output format)
final String[] elementComputeKeys = this.vertexProgram.getElementComputeKeys().toArray(
new String[this.vertexProgram.getElementComputeKeys().size()]);
computedGraphRDD = GraknSparkExecutor.prepareFinalGraphRDD(
graknGraphRDD.loadedGraphRDD, viewIncomingRDD, elementComputeKeys);
if ((hadoopConfiguration.get(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT, null) != null ||
hadoopConfiguration.get(Constants.GREMLIN_SPARK_GRAPH_OUTPUT_RDD, null) != null) &&
!this.persist.equals(Persist.NOTHING)) {
try {
hadoopConfiguration
.getClass(Constants.GREMLIN_SPARK_GRAPH_OUTPUT_RDD,
OutputFormatRDD.class, OutputRDD.class)
.newInstance()
.writeGraphRDD(apacheConfiguration, computedGraphRDD);
} catch (final InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
final boolean computedGraphCreated = computedGraphRDD != null;
if (!computedGraphCreated) {
computedGraphRDD = graknGraphRDD.loadedGraphRDD;
}
final Memory.Admin finalMemory = null == memory ? new MapMemory() : new MapMemory(memory);
//////////////////////////////
// process the map reducers //
//////////////////////////////
if (!this.mapReducers.isEmpty()) {
for (final MapReduce mapReduce : this.mapReducers) {
// execute the map reduce job
final HadoopConfiguration newApacheConfiguration = new HadoopConfiguration(apacheConfiguration);
mapReduce.storeState(newApacheConfiguration);
// map
final JavaPairRDD mapRDD = GraknSparkExecutor
.executeMap(computedGraphRDD, 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
try {
mapReduce.addResultToMemory(finalMemory, hadoopConfiguration
.getClass(Constants.GREMLIN_SPARK_GRAPH_OUTPUT_RDD,
OutputFormatRDD.class, OutputRDD.class)
.newInstance()
.writeMemoryRDD(apacheConfiguration, mapReduce.getMemoryKey(), reduceRDD));
} catch (final InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
// unpersist the computed graph if it will not be used again (no PersistedOutputRDD)
if (!graknGraphRDD.outputToSpark || this.persist.equals(GraphComputer.Persist.NOTHING)) {
computedGraphRDD.unpersist();
}
// delete any file system or rdd data if persist nothing
String outputPath = sparkConfiguration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION);
if (null != outputPath && this.persist.equals(GraphComputer.Persist.NOTHING)) {
if (graknGraphRDD.outputToHDFS) {
graknGraphRDD.fileSystemStorage.rm(outputPath);
}
if (graknGraphRDD.outputToSpark) {
graknGraphRDD.sparkContextStorage.rm(outputPath);
}
}
// update runtime and return the newly computed graph
finalMemory.setRuntime(System.currentTimeMillis() - startTime);
return new DefaultComputerResult(InputOutputHelper.getOutputGraph(
apacheConfiguration, this.resultGraph, this.persist), finalMemory.asImmutable());
}, exec);
}
/////////////////
private static void loadJars(final JavaSparkContext sparkContext,
final Configuration hadoopConfiguration) {
if (hadoopConfiguration.getBoolean(Constants.GREMLIN_HADOOP_JARS_IN_DISTRIBUTED_CACHE, true)) {
final String hadoopGremlinLocalLibs = null == System.getProperty(Constants.HADOOP_GREMLIN_LIBS) ?
System.getenv(Constants.HADOOP_GREMLIN_LIBS) : System.getProperty(Constants.HADOOP_GREMLIN_LIBS);
if (null == hadoopGremlinLocalLibs) {
LOGGER.warn(Constants.HADOOP_GREMLIN_LIBS + " is not set -- proceeding regardless");
} else {
final String[] paths = hadoopGremlinLocalLibs.split(":");
for (final String path : paths) {
final File file = new File(path);
if (file.exists()) {
Stream.of(file.listFiles())
.filter(f -> f.getName().endsWith(Constants.DOT_JAR))
.forEach(f -> sparkContext.addJar(f.getAbsolutePath()));
} else {
LOGGER.warn(path + " does not reference a valid directory -- proceeding regardless");
}
}
}
}
}
/**
* 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 SparkConf sparkConfiguration) {
/*
* 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) {
if (sparkConfiguration.contains(propertyName)) {
String propertyValue = sparkConfiguration.get(propertyName);
LOGGER.info("Setting Thread Local SparkContext Property - "
+ propertyName + " : " + propertyValue);
sparkContext.setLocalProperty(propertyName, sparkConfiguration.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();
}
private static synchronized void getGraphRDD(GraknSparkComputer graknSparkComputer) {
if (graknGraphRDD == null || GraknGraphRDD.commit || graknGraphRDD.sparkContext == null) {
LOGGER.info("Creating a new Grakn Graph RDD");
graknGraphRDD = new GraknGraphRDD(graknSparkComputer);
}
}
public static void refresh() {
if (!GraknGraphRDD.commit) {
setCommitFlag();
LOGGER.debug("Graph commit flag set!!!");
}
}
private static synchronized void setCommitFlag() {
if (!GraknGraphRDD.commit) {
GraknGraphRDD.commit = true;
}
}
public static synchronized void clear() {
if (graknGraphRDD != null) {
graknGraphRDD.loadedGraphRDD = null;
graknGraphRDD = null;
}
Spark.close();
}
private static class GraknGraphRDD {
private static boolean commit = false;
private Storage fileSystemStorage;
private Storage sparkContextStorage;
private boolean outputToHDFS;
private boolean outputToSpark;
private String outputLocation;
private SparkConf sparkConf;
private JavaSparkContext sparkContext;
private JavaPairRDD<Object, VertexWritable> loadedGraphRDD;
private boolean inputFromSpark;
private GraknGraphRDD(GraknSparkComputer graknSparkComputer) {
fileSystemStorage = FileSystemStorage.open(graknSparkComputer.hadoopConfiguration);
sparkContextStorage = SparkContextStorage.open(graknSparkComputer.apacheConfiguration);
inputFromSpark = PersistedInputRDD.class.isAssignableFrom(graknSparkComputer.
hadoopConfiguration.getClass(Constants.GREMLIN_SPARK_GRAPH_INPUT_RDD, Object.class));
outputToHDFS = FileOutputFormat.class.isAssignableFrom(graknSparkComputer.
hadoopConfiguration.getClass(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT, Object.class));
outputToSpark = PersistedOutputRDD.class.isAssignableFrom(graknSparkComputer.
hadoopConfiguration.getClass(Constants.GREMLIN_SPARK_GRAPH_OUTPUT_RDD, Object.class));
// delete output location
outputLocation = graknSparkComputer.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);
}
}
// wire up a spark context
sparkConf = new SparkConf();
sparkConf.setAppName(Constants.GREMLIN_HADOOP_SPARK_JOB_PREFIX);
// create the spark configuration from the graph computer configuration
graknSparkComputer.hadoopConfiguration.forEach(entry -> sparkConf.set(entry.getKey(), entry.getValue()));
sparkContext = new JavaSparkContext(SparkContext.getOrCreate(sparkConf));
loadJars(sparkContext, graknSparkComputer.hadoopConfiguration);
Spark.create(sparkContext.sc()); // this is the context RDD holder that prevents GC
updateLocalConfiguration(sparkContext, sparkConf);
boolean partitioned = false;
try {
loadedGraphRDD = graknSparkComputer.hadoopConfiguration
.getClass(Constants.GREMLIN_SPARK_GRAPH_INPUT_RDD, InputFormatRDD.class, InputRDD.class)
.newInstance()
.readGraphRDD(graknSparkComputer.apacheConfiguration, sparkContext);
if (loadedGraphRDD.partitioner().isPresent()) {
LOGGER.info(
"Using the existing partitioner associated with the loaded graphRDD: " +
loadedGraphRDD.partitioner().get());
} else {
loadedGraphRDD = loadedGraphRDD.partitionBy(new HashPartitioner(graknSparkComputer.workersSet ?
graknSparkComputer.workers : loadedGraphRDD.partitions().size()));
partitioned = true;
}
assert loadedGraphRDD.partitioner().isPresent();
if (graknSparkComputer.workersSet) {
// ensures that the loaded graphRDD does not have more partitions than workers
if (loadedGraphRDD.partitions().size() > graknSparkComputer.workers) {
loadedGraphRDD = loadedGraphRDD.coalesce(graknSparkComputer.workers);
} else if (loadedGraphRDD.partitions().size() < graknSparkComputer.workers) {
loadedGraphRDD = loadedGraphRDD.repartition(graknSparkComputer.workers);
}
}
if (!inputFromSpark || partitioned) {
loadedGraphRDD = loadedGraphRDD.persist(
StorageLevel.fromString(graknSparkComputer.hadoopConfiguration.get(
Constants.GREMLIN_SPARK_GRAPH_STORAGE_LEVEL, "MEMORY_AND_DISK_SER")));
}
GraknGraphRDD.commit = false;
} catch (final InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/computer/GraknSparkExecutor.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.computer;
import com.google.common.base.Optional;
import org.apache.commons.configuration.Configuration;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.tinkerpop.gremlin.hadoop.structure.HadoopGraph;
import org.apache.tinkerpop.gremlin.hadoop.structure.io.HadoopPools;
import org.apache.tinkerpop.gremlin.hadoop.structure.io.VertexWritable;
import org.apache.tinkerpop.gremlin.process.computer.MapReduce;
import org.apache.tinkerpop.gremlin.process.computer.MessageCombiner;
import org.apache.tinkerpop.gremlin.process.computer.VertexProgram;
import org.apache.tinkerpop.gremlin.process.computer.util.ComputerGraph;
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.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.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 static final String[] EMPTY_ARRAY = new String[0];
private GraknSparkExecutor() {
}
////////////////////
// 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 apacheConfiguration) {
// the graphRDD and the viewRDD must have the same partitioner
if (null != viewIncomingRDD) 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 -> {
HadoopPools.initialize(apacheConfiguration);
final VertexProgram<M> workerVertexProgram = VertexProgram.<VertexProgram<M>>createVertexProgram(HadoopGraph.open(apacheConfiguration), apacheConfiguration); // each partition(Spark)/worker(TP3) has a local copy of the vertex program (a worker's task)
final Set<String> elementComputeKeys = workerVertexProgram.getElementComputeKeys(); // the compute keys as a set
final String[] elementComputeKeysArray = elementComputeKeys.size() == 0 ? EMPTY_ARRAY : elementComputeKeys.toArray(new String[elementComputeKeys.size()]); // 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
synchronized (vertex) {
// drop any computed properties that are cached in memory
if (elementComputeKeysArray.length > 0) {
vertex.dropVertexProperties(elementComputeKeysArray);
}
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() : Collections.emptyList();
final List<M> incomingMessages = hasViewAndMessages ? vertexViewIncoming._2()._2().get().getIncomingMessages() : Collections.emptyList();
previousView.forEach(property -> property.attach(Attachable.Method.create(vertex))); // attach the view to the vertex
// previousView.clear(); // no longer needed so kill it from memory
///
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
// incomingMessages.clear(); // no longer needed so kill it from memory
///
final List<DetachedVertexProperty<Object>> nextView = elementComputeKeysArray.length == 0 ? // not all vertex programs have compute keys
Collections.emptyList() :
IteratorUtils.list(IteratorUtils.map(vertex.properties(elementComputeKeysArray), property -> DetachedFactory.detach(property, true)));
final List<Tuple2<Object, M>> outgoingMessages = messenger.getOutgoingMessages(); // get the outgoing messages
// if no more vertices in the partition, end the worker's iteration
if (!partitionIterator.hasNext()) {
workerVertexProgram.workerIterationEnd(memory.asImmutable());
}
return new Tuple2<>(vertex.id(), new ViewOutgoingPayload<>(nextView, outgoingMessages));
}
});
}, true)); // true means that the partition is preserved
// the graphRDD and the viewRDD must have the same partitioner
assert graphRDD.partitioner().get().equals(viewOutgoingRDD.partitioner().get());
// "message pass" by reducing on the vertex object id of the view and message payloads
final MessageCombiner<M> messageCombiner = VertexProgram.<VertexProgram<M>>createVertexProgram(HadoopGraph.open(apacheConfiguration), apacheConfiguration).getMessageCombiner().orElse(null);
final JavaPairRDD<Object, ViewIncomingPayload<M>> newViewIncomingRDD = viewOutgoingRDD
.flatMapToPair(tuple -> () -> IteratorUtils.<Tuple2<Object, Payload>>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()))))) // emit the outgoing message payloads one by one
.reduceByKey(graphRDD.partitioner().get(), (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;
}
})
.filter(payload -> !(payload._2() instanceof MessagePayload)) // this happens if there is a message to a vertex that does not exist
.filter(payload -> !((payload._2() instanceof ViewIncomingPayload) && !((ViewIncomingPayload<M>) payload._2()).hasView())) // this happens if there are many messages to a vertex that does not exist
.mapValues(payload -> payload instanceof ViewIncomingPayload ?
(ViewIncomingPayload<M>) payload : // this happens if there is a vertex with incoming messages
new ViewIncomingPayload<>((ViewPayload) payload)); // this happens if there is a vertex with no incoming messages
// the graphRDD and the viewRDD must have the same partitioner
assert graphRDD.partitioner().get().equals(newViewIncomingRDD.partitioner().get());
newViewIncomingRDD
.foreachPartition(partitionIterator -> {
HadoopPools.initialize(apacheConfiguration);
}); // 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 String[] elementComputeKeys) {
// the graphRDD and the viewRDD must have the same partitioner
assert (graphRDD.partitioner().get().equals(viewIncomingRDD.partitioner().get()));
// attach the final computed view to the cached graph
return graphRDD.leftOuterJoin(viewIncomingRDD)
.mapValues(tuple -> {
final StarGraph.StarVertex vertex = tuple._1().get();
vertex.dropVertexProperties(elementComputeKeys);
final List<DetachedVertexProperty<Object>> view = tuple._2().isPresent() ? tuple._2().get().getView() : Collections.emptyList();
view.forEach(property -> property.attach(Attachable.Method.create(vertex)));
// view.clear(); // no longer needed so kill it from memory
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 apacheConfiguration) {
JavaPairRDD<K, V> mapRDD = graphRDD.mapPartitionsToPair(partitionIterator -> {
HadoopPools.initialize(apacheConfiguration);
return () -> new MapIterator<>(MapReduce.<MapReduce<K, V, ?, ?, ?>>createMapReduce(HadoopGraph.open(apacheConfiguration), apacheConfiguration), 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 apacheConfiguration) {
return mapRDD.mapPartitionsToPair(partitionIterator -> {
HadoopPools.initialize(apacheConfiguration);
return () -> new CombineIterator<>(MapReduce.<MapReduce<K, V, OK, OV, ?>>createMapReduce(HadoopGraph.open(apacheConfiguration), apacheConfiguration), 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 apacheConfiguration) {
JavaPairRDD<OK, OV> reduceRDD = mapOrCombineRDD.groupByKey().mapPartitionsToPair(partitionIterator -> {
HadoopPools.initialize(apacheConfiguration);
return () -> new ReduceIterator<>(MapReduce.<MapReduce<K, V, OK, OV, ?>>createMapReduce(HadoopGraph.open(apacheConfiguration), apacheConfiguration), partitionIterator);
});
if (mapReduce.getReduceKeySort().isPresent()) {
reduceRDD = reduceRDD.sortByKey(mapReduce.getReduceKeySort().get(), true, 1);
}
return reduceRDD;
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/graph/internal/computer/GraknSparkMemory.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.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.process.computer.util.Rule;
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.MemoryHelper;
import org.apache.tinkerpop.gremlin.spark.process.computer.RuleAccumulator;
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 Set<String> memoryKeys = new HashSet<>();
private final AtomicInteger iteration = new AtomicInteger(0); // do these need to be atomics?
private final AtomicLong runtime = new AtomicLong(0l);
private final Map<String, Accumulator<Rule>> memory = new HashMap<>();
private Broadcast<Map<String, Object>> broadcast;
private boolean inTask = false;
public GraknSparkMemory(final VertexProgram<?> vertexProgram,
final Set<MapReduce> mapReducers,
final JavaSparkContext sparkContext) {
if (null != vertexProgram) {
for (final String key : vertexProgram.getMemoryComputeKeys()) {
MemoryHelper.validateKey(key);
this.memoryKeys.add(key);
}
}
for (final MapReduce mapReduce : mapReducers) {
this.memoryKeys.add(mapReduce.getMemoryKey());
}
for (final String key : this.memoryKeys) {
this.memory.put(key,
sparkContext.accumulator(new Rule(Rule.Operation.NO_OP, null), key, new RuleAccumulator()));
}
this.broadcast = sparkContext.broadcast(new HashMap<>());
}
@Override
public Set<String> keys() {
if (this.inTask) {
return this.broadcast.getValue().keySet();
} else {
final Set<String> trueKeys = new HashSet<>();
this.memory.forEach((key, value) -> {
if (value.value().getObject() != null) 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 {
final R r = this.getValue(key);
if (null == r) {
throw Memory.Exceptions.memoryDoesNotExist(key);
} else {
return r;
}
}
@Override
public void incr(final String key, final long delta) {
checkKeyValue(key, delta);
if (this.inTask) {
this.memory.get(key).add(new Rule(Rule.Operation.INCR, delta));
} else {
this.memory.get(key).setValue(new Rule(Rule.Operation.INCR, this.<Long>getValue(key) + delta));
}
}
@Override
public void and(final String key, final boolean bool) {
checkKeyValue(key, bool);
if (this.inTask) {
this.memory.get(key).add(new Rule(Rule.Operation.AND, bool));
} else {
this.memory.get(key).setValue(new Rule(Rule.Operation.AND, this.<Boolean>getValue(key) && bool));
}
}
@Override
public void or(final String key, final boolean bool) {
checkKeyValue(key, bool);
if (this.inTask) {
this.memory.get(key).add(new Rule(Rule.Operation.OR, bool));
} else {
this.memory.get(key).setValue(new Rule(Rule.Operation.OR, this.<Boolean>getValue(key) || bool));
}
}
@Override
public void set(final String key, final Object value) {
checkKeyValue(key, value);
if (this.inTask) {
this.memory.get(key).add(new Rule(Rule.Operation.SET, value));
} else {
this.memory.get(key).setValue(new Rule(Rule.Operation.SET, value));
}
}
@Override
public String toString() {
return StringFactory.memoryString(this);
}
protected void setInTask(final boolean inTask) {
this.inTask = inTask;
}
protected void broadcastMemory(final JavaSparkContext sparkContext) {
this.broadcast.destroy(true); // do we need to block?
final Map<String, Object> toBroadcast = new HashMap<>();
this.memory.forEach((key, rule) -> {
if (null != rule.value().getObject()) {
toBroadcast.put(key, rule.value().getObject());
}
});
this.broadcast = sparkContext.broadcast(toBroadcast);
}
private void checkKeyValue(final String key, final Object value) {
if (!this.memoryKeys.contains(key)) {
throw GraphComputer.Exceptions.providedKeyIsNotAMemoryComputeKey(key);
}
MemoryHelper.validateValue(value);
}
private <R> R getValue(final String key) {
return this.inTask ? (R) this.broadcast.value().get(key) : (R) this.memory.get(key).value().getObject();
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/util/EngineCommunicator.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.util;
import ai.grakn.Grakn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* <p>
* Establishes communication between the graph and engine
* </p>
*
* <p>
* Class dedicated to talking with Grakn Engine. Currently used to retrieve factory config and submit commit logs.
*
* The communication with engine is bypassed whenever the engineURL provided is a in-memory location.
* </p>
*
* @author fppt
*/
public class EngineCommunicator {
private static final Logger LOG = LoggerFactory.getLogger(EngineCommunicator.class);
private static final String DEFAULT_PROTOCOL = "http://";
private static final int MAX_RETRY = 5;
/**
*
* @param engineUrl The location of engine.
* @param restType The type of request to make to engine.
* @param body The body to attach to the request
* @return The result of the request
*/
public static String contactEngine(String engineUrl, String restType, @Nullable String body){
if(engineUrl.equals(Grakn.IN_MEMORY)) {
return "Engine not contacted due to in memory graph being used";
}
for(int i = 0; i < MAX_RETRY; i++) {
try {
URL url = new URL(DEFAULT_PROTOCOL + engineUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod(restType);
if (body != null) {
connection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.write(body.getBytes(StandardCharsets.UTF_8));
}
}
if (connection.getResponseCode() != 200) {
throw new IllegalArgumentException(ErrorMessage.INVALID_ENGINE_RESPONSE.getMessage(engineUrl, connection.getResponseCode()));
}
//Reading from Connection
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
sb.append("\n").append(line);
}
}
return sb.toString();
} catch (IOException e) {
LOG.error(ErrorMessage.COULD_NOT_REACH_ENGINE.getMessage(engineUrl), e);
}
}
throw new RuntimeException(ErrorMessage.COULD_NOT_REACH_ENGINE.getMessage(engineUrl));
}
/**
*
* @param engineUrl The location of engine.
* @param restType The type of resquest to make to engine.
* @return The result of the request
*/
public static String contactEngine(String engineUrl, String restType){
return contactEngine(engineUrl, restType, null);
}
}
|
0
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn
|
java-sources/ai/grakn/grakn-graph/0.16.0/ai/grakn/util/GraphLoader.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.util;
import ai.grakn.Grakn;
import ai.grakn.GraknGraph;
import ai.grakn.GraknSystemProperty;
import ai.grakn.GraknTxType;
import ai.grakn.exception.GraphOperationException;
import ai.grakn.exception.InvalidGraphException;
import ai.grakn.factory.FactoryBuilder;
import ai.grakn.factory.InternalFactory;
import ai.grakn.graph.internal.GraknTinkerGraph;
import ai.grakn.graql.Query;
import com.google.common.base.StandardSystemProperty;
import com.google.common.io.Files;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* <p>
* Builds {@link ai.grakn.GraknGraph} bypassing engine.
* </p>
*
* <p>
* A helper class which is used to build grakn graphs 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 GraphLoader {
private static final AtomicBoolean propertiesLoaded = new AtomicBoolean(false);
private static Properties graphConfig;
private final InternalFactory<?> factory;
private @Nullable Consumer<GraknGraph> preLoad;
private boolean graphLoaded = false;
private GraknGraph graph;
protected GraphLoader(@Nullable Consumer<GraknGraph> preLoad){
factory = FactoryBuilder.getFactory(randomKeyspace(), Grakn.IN_MEMORY, properties());
this.preLoad = preLoad;
}
public static GraphLoader empty(){
return new GraphLoader(null);
}
public static GraphLoader preLoad(Consumer<GraknGraph> build){
return new GraphLoader(build);
}
public static GraphLoader preLoad(String [] files){
return new GraphLoader((graknGraph) -> {
for (String file : files) {
loadFromFile(graknGraph, file);
}
});
}
public GraknGraph graph(){
if(graph == null || graph.isClosed()){
//Load the graph if we need to
if(!graphLoaded) {
try(GraknGraph graph = factory.open(GraknTxType.WRITE)){
load(graph);
graph.commit();
graphLoaded = true;
}
}
graph = factory.open(GraknTxType.WRITE);
}
return graph;
}
public void load(Consumer<GraknGraph> preLoad){
this.preLoad = preLoad;
graphLoaded = false;
graph();
}
public void rollback() {
if (graph instanceof GraknTinkerGraph) {
graph.admin().delete();
graphLoaded = false;
} else if (!graph.isClosed()) {
graph.close();
}
graph = graph();
}
/**
* Loads the graph using the specified Preloaders
*/
private void load(GraknGraph graph){
if(preLoad != null) preLoad.accept(graph);
}
/**
* Using system properties the graph config is directly read from file.
*
* @return The properties needed to build a graph.
*/
//TODO Use this method in GraknEngineConfig (It's a duplicate)
private static Properties properties(){
if(propertiesLoaded.compareAndSet(false, true)){
String configFilePath = GraknSystemProperty.CONFIGURATION_FILE.value();
if (!Paths.get(configFilePath).isAbsolute()) {
configFilePath = getProjectPath() + configFilePath;
}
graphConfig = new Properties();
try (FileInputStream inputStream = new FileInputStream(configFilePath)){
graphConfig.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
throw GraphOperationException.invalidGraphConfig(configFilePath);
}
}
return graphConfig;
}
/**
* @return The project path. If it is not specified as a JVM parameter it will be set equal to
* user.dir folder.
*/
//TODO Use this method in GraknEngineConfig (It's a duplicate)
private static String getProjectPath() {
if (GraknSystemProperty.CURRENT_DIRECTORY.value() == null) {
GraknSystemProperty.CURRENT_DIRECTORY.set(StandardSystemProperty.USER_DIR.value());
}
return GraknSystemProperty.CURRENT_DIRECTORY.value() + "/";
}
public static String randomKeyspace(){
// Embedded Casandra has problems dropping keyspaces that start with a number
return "a"+ UUID.randomUUID().toString().replaceAll("-", "");
}
public static void loadFromFile(GraknGraph graph, String file) {
try {
File graql = new File(file);
graph.graql()
.parseList(Files.readLines(graql, StandardCharsets.UTF_8).stream().collect(Collectors.joining("\n")))
.forEach(Query::execute);
} catch (IOException |InvalidGraphException e){
throw new RuntimeException(e);
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/Autocomplete.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.graql;
import ai.grakn.graql.internal.antlr.GraqlLexer;
import com.google.common.collect.ImmutableSet;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.Token;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;
import static ai.grakn.graql.internal.util.StringConverter.GRAQL_KEYWORDS;
import static ai.grakn.util.CommonUtil.toImmutableSet;
/**
* An autocomplete result suggesting keywords, types and variables that the user may wish to type
*
* @author Grakn Warriors
*/
public class Autocomplete {
private final ImmutableSet<String> candidates;
private final int cursorPosition;
/**
* @param types a set of type IDs to autocomplete
* @param query the query to autocomplete
* @param cursorPosition the cursor position in the query
* @return an autocomplete object containing potential candidates and cursor position to autocomplete from
*/
@CheckReturnValue
public static Autocomplete create(Set<String> types, String query, int cursorPosition) {
return new Autocomplete(types, query, cursorPosition);
}
/**
* @return all candidate autocomplete words
*/
@CheckReturnValue
public Set<String> getCandidates() {
return candidates;
}
/**
* @return the cursor position that autocompletions should start from
*/
@CheckReturnValue
public int getCursorPosition() {
return cursorPosition;
}
/**
* @param types a set of type IDs to autocomplete
* @param query the query to autocomplete
* @param cursorPosition the cursor position in the query
*/
private Autocomplete(Set<String> types, String query, int cursorPosition) {
Token token = getCursorToken(query, cursorPosition);
candidates = findCandidates(types, query, token);
this.cursorPosition = findCursorPosition(cursorPosition, token);
}
/**
* @param types the graph to find types in
* @param query a graql query
* @param token the token the cursor is on in the query
* @return a set of potential autocomplete words
*/
private static ImmutableSet<String> findCandidates(Set<String> types, String query, Token token) {
ImmutableSet<String> allCandidates = Stream.of(GRAQL_KEYWORDS.stream(), types.stream(), getVariables(query))
.flatMap(Function.identity()).collect(toImmutableSet());
if (token != null) {
ImmutableSet<String> candidates = allCandidates.stream()
.filter(candidate -> candidate.startsWith(token.getText()))
.collect(toImmutableSet());
if (candidates.size() == 1 && candidates.iterator().next().equals(token.getText())) {
return ImmutableSet.of(" ");
} else {
return candidates;
}
} else {
return allCandidates;
}
}
/**
* @param cursorPosition the current cursor position
* @param token the token the cursor is on in the query
* @return the new cursor position to start autocompleting from
*/
private int findCursorPosition(int cursorPosition, Token token) {
if (!candidates.contains(" ") && token != null) return token.getStartIndex();
else return cursorPosition;
}
/**
* @param query a graql query
* @return all variable names occurring in the query
*/
private static Stream<String> getVariables(String query) {
List<? extends Token> allTokens = getTokens(query);
if (allTokens.size() > 0) allTokens.remove(allTokens.size() - 1);
return allTokens.stream()
.filter(t -> t.getType() == GraqlLexer.VARIABLE)
.map(Token::getText);
}
/**
* @param query a graql query
* @param cursorPosition the cursor position in the query
* @return the token at the cursor position in the given graql query
*/
@Nullable
private static Token getCursorToken(String query, int cursorPosition) {
if (query == null) return null;
return getTokens(query).stream()
.filter(t -> t.getChannel() != Token.HIDDEN_CHANNEL)
.filter(t -> t.getStartIndex() <= cursorPosition && t.getStopIndex() >= cursorPosition - 1)
.findFirst().orElse(null);
}
/**
* @param query a graql query
* @return a list of tokens from running the lexer on the query
*/
private static List<? extends Token> getTokens(String query) {
ANTLRInputStream input = new ANTLRInputStream(query);
GraqlLexer lexer = new GraqlLexer(input);
// Ignore syntax errors
lexer.removeErrorListeners();
lexer.addErrorListener(new BaseErrorListener());
return lexer.getAllTokens();
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/Graql.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.graql;
import ai.grakn.concept.Label;
import ai.grakn.concept.SchemaConcept;
import ai.grakn.graql.admin.PatternAdmin;
import ai.grakn.graql.answer.Answer;
import ai.grakn.graql.answer.AnswerGroup;
import ai.grakn.graql.answer.ConceptMap;
import ai.grakn.graql.answer.Value;
import ai.grakn.graql.internal.pattern.Patterns;
import ai.grakn.graql.internal.query.QueryBuilderImpl;
import ai.grakn.graql.internal.query.aggregate.Aggregates;
import ai.grakn.graql.internal.query.predicate.Predicates;
import ai.grakn.graql.internal.util.AdminConverter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import javax.annotation.CheckReturnValue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;
import static ai.grakn.util.GraqlSyntax.Compute.Method;
import static java.util.stream.Collectors.toSet;
/**
* Main class containing static methods for creating Graql queries.
*
* It is recommended you statically import these methods.
*
* @author Felix Chapman
*/
public class Graql {
private Graql() {}
// QUERY BUILDING
/**
* @return a query builder without a specified graph
*/
@CheckReturnValue
public static QueryBuilder withoutGraph() {
return new QueryBuilderImpl();
}
/**
* @param patterns an array of patterns to match in the graph
* @return a {@link Match} that will find matches of the given patterns
*/
@CheckReturnValue
public static Match match(Pattern... patterns) {
return withoutGraph().match(patterns);
}
/**
* @param patterns a collection of patterns to match in the graph
* @return a {@link Match} that will find matches of the given patterns
*/
@CheckReturnValue
public static Match match(Collection<? extends Pattern> patterns) {
return withoutGraph().match(patterns);
}
/**
* @param varPatterns an array of variable patterns to insert into the graph
* @return an insert query that will insert the given variable patterns into the graph
*/
@CheckReturnValue
public static InsertQuery insert(VarPattern... varPatterns) {
return withoutGraph().insert(varPatterns);
}
/**
* @param varPatterns a collection of variable patterns to insert into the graph
* @return an insert query that will insert the given variable patterns into the graph
*/
@CheckReturnValue
public static InsertQuery insert(Collection<? extends VarPattern> varPatterns) {
return withoutGraph().insert(varPatterns);
}
/**
* @param varPatterns an array of {@link VarPattern}s defining {@link SchemaConcept}s
* @return a {@link DefineQuery} that will apply the changes described in the {@code patterns}
*/
@CheckReturnValue
public static DefineQuery define(VarPattern... varPatterns) {
return withoutGraph().define(varPatterns);
}
/**
* @param varPatterns a collection of {@link VarPattern}s defining {@link SchemaConcept}s
* @return a {@link DefineQuery} that will apply the changes described in the {@code patterns}
*/
@CheckReturnValue
public static DefineQuery define(Collection<? extends VarPattern> varPatterns) {
return withoutGraph().define(varPatterns);
}
/**
* @param varPatterns an array of {@link VarPattern}s undefining {@link SchemaConcept}s
* @return a {@link UndefineQuery} that will remove the changes described in the {@code patterns}
*/
@CheckReturnValue
public static UndefineQuery undefine(VarPattern... varPatterns) {
return withoutGraph().undefine(varPatterns);
}
/**
* @param varPatterns a collection of {@link VarPattern}s undefining {@link SchemaConcept}s
* @return a {@link UndefineQuery} that will remove the changes described in the {@code patterns}
*/
@CheckReturnValue
public static UndefineQuery undefine(Collection<? extends VarPattern> varPatterns) {
return withoutGraph().undefine(varPatterns);
}
@CheckReturnValue
public static <T extends Answer> ComputeQuery<T> compute(Method<T> method) {
return withoutGraph().compute(method);
}
/**
* Get a {@link QueryParser} for parsing queries from strings
*/
public static QueryParser parser() {
return withoutGraph().parser();
}
/**
* @param queryString a string representing a query
* @return a query, the type will depend on the type of query.
*/
@CheckReturnValue
public static <T extends Query<?>> T parse(String queryString) {
return withoutGraph().parse(queryString);
}
// PATTERNS AND VARS
/**
* @param name the name of the variable
* @return a new query variable
*/
@CheckReturnValue
public static Var var(String name) {
return Patterns.var(name);
}
/**
* @return a new, anonymous query variable
*/
@CheckReturnValue
public static Var var() {
return Patterns.var();
}
/**
* @param label the label of a concept
* @return a variable pattern that identifies a concept by label
*/
@CheckReturnValue
public static VarPattern label(Label label) {
return var().label(label);
}
/**
* @param label the label of a concept
* @return a variable pattern that identifies a concept by label
*/
@CheckReturnValue
public static VarPattern label(String label) {
return var().label(label);
}
/**
* @param patterns an array of patterns to match
* @return a pattern that will match only when all contained patterns match
*/
@CheckReturnValue
public static Pattern and(Pattern... patterns) {
return and(Arrays.asList(patterns));
}
/**
* @param patterns a collection of patterns to match
* @return a pattern that will match only when all contained patterns match
*/
@CheckReturnValue
public static Pattern and(Collection<? extends Pattern> patterns) {
Collection<PatternAdmin> patternAdmins = AdminConverter.getPatternAdmins(patterns);
return Patterns.conjunction(Sets.newHashSet(patternAdmins));
}
/**
* @param patterns an array of patterns to match
* @return a pattern that will match when any contained pattern matches
*/
@CheckReturnValue
public static Pattern or(Pattern... patterns) {
return or(Arrays.asList(patterns));
}
/**
* @param patterns a collection of patterns to match
* @return a pattern that will match when any contained pattern matches
*/
@CheckReturnValue
public static Pattern or(Collection<? extends Pattern> patterns) {
// Simplify representation when there is only one alternative
if (patterns.size() == 1) {
return Iterables.getOnlyElement(patterns);
}
Collection<PatternAdmin> patternAdmins = AdminConverter.getPatternAdmins(patterns);
return Patterns.disjunction(Sets.newHashSet(patternAdmins));
}
// AGGREGATES
/**
* Create an aggregate that will count the results of a query.
*/
@CheckReturnValue
public static Aggregate<Value> count(String... vars) {
return Aggregates.count(Arrays.stream(vars).map(Graql::var).collect(toSet()));
}
/**
* Create an aggregate that will sum the values of a variable.
*/
@CheckReturnValue
public static Aggregate<Value> sum(String var) {
return Aggregates.sum(Graql.var(var));
}
/**
* Create an aggregate that will find the minimum of a variable's values.
* @param var the variable to find the maximum of
*/
@CheckReturnValue
public static Aggregate<Value> min(String var) {
return Aggregates.min(Graql.var(var));
}
/**
* Create an aggregate that will find the maximum of a variable's values.
* @param var the variable to find the maximum of
*/
@CheckReturnValue
public static Aggregate<Value> max(String var) {
return Aggregates.max(Graql.var(var));
}
/**
* Create an aggregate that will find the mean of a variable's values.
* @param var the variable to find the mean of
*/
@CheckReturnValue
public static Aggregate<Value> mean(String var) {
return Aggregates.mean(Graql.var(var));
}
/**
* Create an aggregate that will find the median of a variable's values.
* @param var the variable to find the median of
*/
@CheckReturnValue
public static Aggregate<Value> median(String var) {
return Aggregates.median(Graql.var(var));
}
/**
* Create an aggregate that will find the unbiased sample standard deviation of a variable's values.
* @param var the variable to find the standard deviation of
*/
@CheckReturnValue
public static Aggregate<Value> std(String var) {
return Aggregates.std(Graql.var(var));
}
/**
* Create an aggregate that will group a query by a variable.
* @param var the variable to group results by
*/
@CheckReturnValue
public static Aggregate<AnswerGroup<ConceptMap>> group(String var) {
return group(var, Aggregates.list());
}
/**
* Create an aggregate that will group a query by a variable and apply the given aggregate to each group
* @param var the variable to group results by
* @param aggregate the aggregate to apply to each group
* @param <T> the type the aggregate returns
*/
@CheckReturnValue
public static <T extends Answer> Aggregate<AnswerGroup<T>> group(String var, Aggregate<T> aggregate) {
return Aggregates.group(Graql.var(var), aggregate);
}
// PREDICATES
/**
* @param value the value
* @return a predicate that is true when a value equals the specified value
*/
@CheckReturnValue
public static ValuePredicate eq(Object value) {
Objects.requireNonNull(value);
return Predicates.eq(value);
}
/**
* @param varPattern the variable pattern representing a resource
* @return a predicate that is true when a value equals the specified value
*/
@CheckReturnValue
public static ValuePredicate eq(VarPattern varPattern) {
Objects.requireNonNull(varPattern);
return Predicates.eq(varPattern);
}
/**
* @param value the value
* @return a predicate that is true when a value does not equal the specified value
*/
@CheckReturnValue
public static ValuePredicate neq(Object value) {
Objects.requireNonNull(value);
return Predicates.neq(value);
}
/**
* @param varPattern the variable pattern representing a resource
* @return a predicate that is true when a value does not equal the specified value
*/
@CheckReturnValue
public static ValuePredicate neq(VarPattern varPattern) {
Objects.requireNonNull(varPattern);
return Predicates.neq(varPattern);
}
/**
* @param value the value
* @return a predicate that is true when a value is strictly greater than the specified value
*/
@CheckReturnValue
public static ValuePredicate gt(Comparable value) {
Objects.requireNonNull(value);
return Predicates.gt(value);
}
/**
* @param varPattern the variable pattern representing a resource
* @return a predicate that is true when a value is strictly greater than the specified value
*/
@CheckReturnValue
public static ValuePredicate gt(VarPattern varPattern) {
Objects.requireNonNull(varPattern);
return Predicates.gt(varPattern);
}
/**
* @param value the value
* @return a predicate that is true when a value is greater or equal to the specified value
*/
@CheckReturnValue
public static ValuePredicate gte(Comparable value) {
Objects.requireNonNull(value);
return Predicates.gte(value);
}
/**
* @param varPattern the variable pattern representing a resource
* @return a predicate that is true when a value is greater or equal to the specified value
*/
@CheckReturnValue
public static ValuePredicate gte(VarPattern varPattern) {
Objects.requireNonNull(varPattern);
return Predicates.gte(varPattern);
}
/**
* @param value the value
* @return a predicate that is true when a value is strictly less than the specified value
*/
@CheckReturnValue
public static ValuePredicate lt(Comparable value) {
Objects.requireNonNull(value);
return Predicates.lt(value);
}
/**
* @param varPattern the variable pattern representing a resource
* @return a predicate that is true when a value is strictly less than the specified value
*/
@CheckReturnValue
public static ValuePredicate lt(VarPattern varPattern) {
Objects.requireNonNull(varPattern);
return Predicates.lt(varPattern);
}
/**
* @param value the value
* @return a predicate that is true when a value is less or equal to the specified value
*/
@CheckReturnValue
public static ValuePredicate lte(Comparable value) {
Objects.requireNonNull(value);
return Predicates.lte(value);
}
/**
* @param varPattern the variable pattern representing a resource
* @return a predicate that is true when a value is less or equal to the specified value
*/
@CheckReturnValue
public static ValuePredicate lte(VarPattern varPattern) {
Objects.requireNonNull(varPattern);
return Predicates.lte(varPattern);
}
/**
* @param pattern a regex pattern
* @return a predicate that returns true when a value matches the given regular expression
*/
@CheckReturnValue
public static ValuePredicate regex(String pattern) {
Objects.requireNonNull(pattern);
return Predicates.regex(pattern);
}
/**
* @param substring a substring to match
* @return a predicate that returns true when a value contains the given substring
*/
@CheckReturnValue
public static ValuePredicate contains(String substring) {
Objects.requireNonNull(substring);
return Predicates.contains(substring);
}
/**
* @param varPattern the variable pattern representing a resource
* @return a predicate that returns true when a value contains the given substring
*/
@CheckReturnValue
public static ValuePredicate contains(VarPattern varPattern) {
Objects.requireNonNull(varPattern);
return Predicates.contains(varPattern.admin());
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/ClusterMemberMapReduce.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.graql.internal.analytics;
import ai.grakn.concept.ConceptId;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import static ai.grakn.graql.internal.analytics.Utility.reduceSet;
/**
* The MapReduce program for collecting the result of a clustering query.
* <p>
* It returns a map, the key being the cluster id, the value being a vertex id set containing all the vertices
* in the given cluster
* <p>
*
* @author Jason Liu
* @author Sheldon Hall
*/
public class ClusterMemberMapReduce extends GraknMapReduce<Set<ConceptId>> {
private static final String CLUSTER_LABEL = "clusterMemberMapReduce.clusterLabel";
private static final String CLUSTER_SIZE = "clusterMemberMapReduce.size";
// Needed internally for OLAP tasks
public ClusterMemberMapReduce() {
}
public ClusterMemberMapReduce(String clusterLabel) {
this(clusterLabel, null);
}
public ClusterMemberMapReduce(String clusterLabel, @Nullable Long clusterSize) {
this.persistentProperties.put(CLUSTER_LABEL, clusterLabel);
if (clusterSize != null) this.persistentProperties.put(CLUSTER_SIZE, clusterSize);
}
@Override
public void safeMap(final Vertex vertex, final MapEmitter<Serializable, Set<ConceptId>> emitter) {
if (vertex.property((String) persistentProperties.get(CLUSTER_LABEL)).isPresent()) {
String clusterPropertyKey = (String) persistentProperties.get(CLUSTER_LABEL);
String clusterId = vertex.value(clusterPropertyKey);
ConceptId conceptId = ConceptId.of(vertex.value(Schema.VertexProperty.ID.name()));
Set<ConceptId> cluster = Collections.singleton(conceptId);
emitter.emit(clusterId, cluster);
} else {
emitter.emit(NullObject.instance(), Collections.emptySet());
}
}
@Override
Set<ConceptId> reduceValues(Iterator<Set<ConceptId>> values) {
return reduceSet(values);
}
@Override
public Map<Serializable, Set<ConceptId>> generateFinalResult(Iterator<KeyValue<Serializable, Set<ConceptId>>> keyValues) {
if (this.persistentProperties.containsKey(CLUSTER_SIZE)) {
long clusterSize = (long) persistentProperties.get(CLUSTER_SIZE);
keyValues = IteratorUtils.filter(keyValues, pair -> Long.valueOf(pair.getValue().size()).equals(clusterSize));
}
final Map<Serializable, Set<ConceptId>> clusterPopulation = Utility.keyValuesToMap(keyValues);
clusterPopulation.remove(NullObject.instance());
return clusterPopulation;
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/ClusterSizeMapReduce.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.graql.internal.analytics;
import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
/**
* The MapReduce program for collecting the result of a clustering query.
* <p>
* It returns a map, the key being the cluster id, the value being the number of vertices the given cluster has.
* <p>
*
* @author Jason Liu
* @author Sheldon Hall
*/
public class ClusterSizeMapReduce extends GraknMapReduce<Long> {
private static final String CLUSTER_LABEL = "clusterSizeMapReduce.clusterLabel";
private static final String CLUSTER_SIZE = "clusterSizeMapReduce.size";
// Needed internally for OLAP tasks
public ClusterSizeMapReduce() {
}
public ClusterSizeMapReduce(String clusterLabel) {
this(clusterLabel, null);
}
public ClusterSizeMapReduce(String clusterLabel, @Nullable Long clusterSize) {
this.persistentProperties.put(CLUSTER_LABEL, clusterLabel);
if (clusterSize != null) this.persistentProperties.put(CLUSTER_SIZE, clusterSize);
}
@Override
public void safeMap(final Vertex vertex, final MapEmitter<Serializable, Long> emitter) {
if (vertex.property((String) persistentProperties.get(CLUSTER_LABEL)).isPresent()) {
emitter.emit(vertex.value((String) persistentProperties.get(CLUSTER_LABEL)), 1L);
} else {
emitter.emit(NullObject.instance(), 0L);
}
}
@Override
Long reduceValues(Iterator<Long> values) {
return IteratorUtils.reduce(values, 0L, (a, b) -> a + b);
}
@Override
public Map<Serializable, Long> generateFinalResult(Iterator<KeyValue<Serializable, Long>> keyValues) {
if (this.persistentProperties.containsKey(CLUSTER_SIZE)) {
long clusterSize = (long) persistentProperties.get(CLUSTER_SIZE);
keyValues = IteratorUtils.filter(keyValues, pair -> pair.getValue().equals(clusterSize));
}
final Map<Serializable, Long> clusterPopulation = Utility.keyValuesToMap(keyValues);
clusterPopulation.remove(NullObject.instance());
return clusterPopulation;
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/CommonOLAP.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.graql.internal.analytics;
import ai.grakn.concept.LabelId;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Core Grakn implementation of the common methods on the MapReduce and VertexProgram interfaces.
* <p>
*
* @author Jason Liu
* @author Sheldon Hall
*/
public abstract class CommonOLAP {
static final Logger LOGGER = LoggerFactory.getLogger(CommonOLAP.class);
private static final String PREFIX_SELECTED_TYPE_KEY = "SELECTED_TYPE";
private static final String PREFIX_PERSISTENT_PROPERTIES = "PERSISTENT";
/**
* The types that define a subgraph.
*/
Set<LabelId> selectedTypes = new HashSet<>();
/**
* Properties that will be reloaded whenever the class is instantiated in a spark executor.
*/
final Map<String, Object> persistentProperties = new HashMap<>();
/**
* Store <code>persistentProperties</code> and any hard coded fields in an apache config object for propagation to
* spark executors.
*
* @param configuration the apache config object that will be propagated
*/
public void storeState(final Configuration configuration) {
// clear properties from vertex program
Set<String> oldKeys = new HashSet<>();
configuration.subset(PREFIX_SELECTED_TYPE_KEY).getKeys()
.forEachRemaining(key -> oldKeys.add(PREFIX_SELECTED_TYPE_KEY + "." + key));
oldKeys.forEach(configuration::clearProperty);
// store selectedTypes
selectedTypes.forEach(typeId ->
configuration.addProperty(PREFIX_SELECTED_TYPE_KEY + "." + typeId, typeId));
// store user specified properties
persistentProperties.forEach((key, value) ->
configuration.addProperty(PREFIX_PERSISTENT_PROPERTIES + "." + key, value));
}
/**
* Load <code>persistentProperties</code> and any hard coded fields from an apache config object for use by the
* spark executor.
*
* @param graph the tinker graph
* @param configuration the apache config object containing the values
*/
public void loadState(final Graph graph, final Configuration configuration) {
// load selected types
configuration.subset(PREFIX_SELECTED_TYPE_KEY).getKeys().forEachRemaining(key ->
selectedTypes.add((LabelId) configuration.getProperty(PREFIX_SELECTED_TYPE_KEY + "." + key)));
// load user specified properties
configuration.subset(PREFIX_PERSISTENT_PROPERTIES).getKeys().forEachRemaining(key ->
persistentProperties.put(key, configuration.getProperty(PREFIX_PERSISTENT_PROPERTIES + "." + key)));
}
public String toString() {
return this.getClass().getSimpleName();
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/ConnectedComponentVertexProgram.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.graql.internal.analytics;
import ai.grakn.concept.ConceptId;
import ai.grakn.exception.GraqlQueryException;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MemoryComputeKey;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey;
import org.apache.tinkerpop.gremlin.process.traversal.Operator;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.Collections;
import java.util.Set;
import static ai.grakn.graql.internal.analytics.ConnectedComponentsVertexProgram.CLUSTER_LABEL;
/**
* The vertex program for computing connected components of a give instance.
*
* @author Jason Liu
*/
public class ConnectedComponentVertexProgram extends GraknVertexProgram<Boolean> {
private static final int MAX_ITERATION = 100;
private static final String VOTE_TO_HALT = "connectedComponentVertexProgram.voteToHalt";
private static final String SOURCE = "connectedComponentVertexProgram.source";
private static final Boolean MESSAGE = true; // just a random message
private static final Set<MemoryComputeKey> MEMORY_COMPUTE_KEYS =
Collections.singleton(MemoryComputeKey.of(VOTE_TO_HALT, Operator.and, false, true));
@SuppressWarnings("unused")// Needed internally for OLAP tasks
public ConnectedComponentVertexProgram() {
}
public ConnectedComponentVertexProgram(ConceptId sourceId) {
this.persistentProperties.put(SOURCE, sourceId.getValue());
}
@Override
public Set<VertexComputeKey> getVertexComputeKeys() {
return Collections.singleton(VertexComputeKey.of(CLUSTER_LABEL, false));
}
@Override
public Set<MemoryComputeKey> getMemoryComputeKeys() {
return MEMORY_COMPUTE_KEYS;
}
@Override
public void setup(final Memory memory) {
LOGGER.debug("ConnectedComponentVertexProgram Started !!!!!!!!");
memory.set(VOTE_TO_HALT, true);
}
@Override
public void safeExecute(final Vertex vertex, Messenger<Boolean> messenger, final Memory memory) {
if (memory.isInitialIteration()) {
if (vertex.<String>value(Schema.VertexProperty.ID.name()).equals(persistentProperties.get(SOURCE))) {
update(vertex, messenger, memory, (String) persistentProperties.get(SOURCE));
}
} else {
if (messenger.receiveMessages().hasNext() && !vertex.property(CLUSTER_LABEL).isPresent()) {
update(vertex, messenger, memory, (String) persistentProperties.get(SOURCE));
}
}
}
private static void update(Vertex vertex, Messenger<Boolean> messenger, Memory memory, String label) {
messenger.sendMessage(messageScopeIn, MESSAGE);
messenger.sendMessage(messageScopeOut, MESSAGE);
vertex.property(CLUSTER_LABEL, label);
memory.add(VOTE_TO_HALT, false);
}
@Override
public boolean terminate(final Memory memory) {
LOGGER.debug("Finished Iteration " + memory.getIteration());
if (memory.isInitialIteration()) return false;
if (memory.<Boolean>get(VOTE_TO_HALT)) {
return true;
}
if (memory.getIteration() == MAX_ITERATION) {
LOGGER.debug("Reached Max Iteration: " + MAX_ITERATION + " !!!!!!!!");
throw GraqlQueryException.maxIterationsReached(this.getClass());
}
memory.set(VOTE_TO_HALT, true);
return false;
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/ConnectedComponentsVertexProgram.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.graql.internal.analytics;
import ai.grakn.exception.GraqlQueryException;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MemoryComputeKey;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey;
import org.apache.tinkerpop.gremlin.process.traversal.Operator;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Collections;
import java.util.Set;
/**
* The vertex program for computing connected components.
*
* @author Jason Liu
*/
public class ConnectedComponentsVertexProgram extends GraknVertexProgram<String> {
private static final int MAX_ITERATION = 100;
public static final String CLUSTER_LABEL = "connectedComponentVertexProgram.clusterLabel";
private static final String VOTE_TO_HALT = "connectedComponentVertexProgram.voteToHalt";
private static final Set<MemoryComputeKey> MEMORY_COMPUTE_KEYS =
Collections.singleton(MemoryComputeKey.of(VOTE_TO_HALT, Operator.and, false, true));
public ConnectedComponentsVertexProgram() {
}
@Override
public Set<VertexComputeKey> getVertexComputeKeys() {
return Collections.singleton(VertexComputeKey.of(CLUSTER_LABEL, false));
}
@Override
public Set<MemoryComputeKey> getMemoryComputeKeys() {
return MEMORY_COMPUTE_KEYS;
}
@Override
public void setup(final Memory memory) {
LOGGER.debug("ConnectedComponentsVertexProgram Started !!!!!!!!");
memory.set(VOTE_TO_HALT, true);
}
@Override
public void safeExecute(final Vertex vertex, Messenger<String> messenger, final Memory memory) {
if (memory.isInitialIteration()) {
String id = vertex.value(Schema.VertexProperty.ID.name());
vertex.property(CLUSTER_LABEL, id);
messenger.sendMessage(messageScopeIn, id);
messenger.sendMessage(messageScopeOut, id);
} else {
updateClusterLabel(vertex, messenger, memory);
}
}
private static void updateClusterLabel(Vertex vertex, Messenger<String> messenger, Memory memory) {
String currentMax = vertex.value(CLUSTER_LABEL);
String max = IteratorUtils.reduce(messenger.receiveMessages(), currentMax,
(a, b) -> a.compareTo(b) > 0 ? a : b);
if (max.compareTo(currentMax) > 0) {
vertex.property(CLUSTER_LABEL, max);
messenger.sendMessage(messageScopeIn, max);
messenger.sendMessage(messageScopeOut, max);
memory.add(VOTE_TO_HALT, false);
}
}
@Override
public boolean terminate(final Memory memory) {
LOGGER.debug("Finished Iteration " + memory.getIteration());
if (memory.getIteration() < 2) return false;
if (memory.<Boolean>get(VOTE_TO_HALT)) {
return true;
}
if (memory.getIteration() == MAX_ITERATION) {
LOGGER.debug("Reached Max Iteration: " + MAX_ITERATION + " !!!!!!!!");
throw GraqlQueryException.maxIterationsReached(this.getClass());
}
memory.set(VOTE_TO_HALT, true);
return false;
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/CorenessVertexProgram.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.graql.internal.analytics;
import ai.grakn.exception.GraqlQueryException;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MemoryComputeKey;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey;
import org.apache.tinkerpop.gremlin.process.traversal.Operator;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.Set;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.IMPLICIT_MESSAGE_COUNT;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.K;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.K_CORE_EXIST;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.K_CORE_LABEL;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.K_CORE_STABLE;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.MESSAGE_COUNT;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.atRelationships;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.filterByDegree;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.relayOrSaveMessages;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.sendMessage;
import static ai.grakn.graql.internal.analytics.KCoreVertexProgram.updateEntityAndAttribute;
import static com.google.common.collect.Sets.newHashSet;
/**
* The vertex program for computing coreness using k-core.
* <p>
* https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)#k-Cores
* </p>
*
* @author Jason Liu
*/
public class CorenessVertexProgram extends GraknVertexProgram<String> {
private static final int MAX_ITERATION = 200;
private static final String EMPTY_MESSAGE = "";
public static final String CORENESS = "corenessVertexProgram.coreness";
private static final String PERSIST_CORENESS = "corenessVertexProgram.persistCoreness";
private static final Set<MemoryComputeKey> MEMORY_COMPUTE_KEYS = newHashSet(
MemoryComputeKey.of(K_CORE_STABLE, Operator.and, false, true),
MemoryComputeKey.of(K_CORE_EXIST, Operator.or, false, true),
MemoryComputeKey.of(PERSIST_CORENESS, Operator.assign, true, true),
MemoryComputeKey.of(K, Operator.assign, true, true));
private static final Set<VertexComputeKey> VERTEX_COMPUTE_KEYS = newHashSet(
VertexComputeKey.of(CORENESS, false),
VertexComputeKey.of(K_CORE_LABEL, true),
VertexComputeKey.of(MESSAGE_COUNT, true),
VertexComputeKey.of(IMPLICIT_MESSAGE_COUNT, true));
@SuppressWarnings("unused")// Needed internally for OLAP tasks
public CorenessVertexProgram() {
}
public CorenessVertexProgram(long minK) {
this.persistentProperties.put(K, minK);
}
@Override
public Set<VertexComputeKey> getVertexComputeKeys() {
return VERTEX_COMPUTE_KEYS;
}
@Override
public Set<MemoryComputeKey> getMemoryComputeKeys() {
return MEMORY_COMPUTE_KEYS;
}
@Override
public void setup(final Memory memory) {
LOGGER.debug("KCoreVertexProgram Started !!!!!!!!");
// K_CORE_STABLE is true by default, and we reset it after each odd iteration.
memory.set(K_CORE_STABLE, false);
memory.set(K_CORE_EXIST, false);
memory.set(PERSIST_CORENESS, false);
memory.set(K, persistentProperties.get(K));
}
@Override
public void safeExecute(final Vertex vertex, Messenger<String> messenger, final Memory memory) {
switch (memory.getIteration()) {
case 0:
sendMessage(messenger, EMPTY_MESSAGE);
break;
case 1: // get degree first, as degree must >= k
filterByDegree(vertex, messenger, memory, false);
break;
default:
if (memory.<Boolean>get(PERSIST_CORENESS) && vertex.property(K_CORE_LABEL).isPresent()) {
// persist coreness
vertex.property(CORENESS, memory.<Long>get(K) - 1L);
// check if the vertex should included for the next k value
if (vertex.<Long>value(MESSAGE_COUNT) < memory.<Long>get(K)) {
vertex.property(K_CORE_LABEL).remove();
break;
}
}
// relay message through relationship vertices in even iterations
// send message from regular entities in odd iterations
if (atRelationships(memory)) {
relayOrSaveMessages(vertex, messenger);
} else {
updateEntityAndAttribute(vertex, messenger, memory, true);
}
break;
}
}
@Override
public boolean terminate(final Memory memory) {
if (memory.isInitialIteration()) {
LOGGER.debug("Finished Iteration " + memory.getIteration());
return false;
}
if (memory.getIteration() == MAX_ITERATION) {
LOGGER.debug("Reached Max Iteration: " + MAX_ITERATION + " !!!!!!!!");
throw GraqlQueryException.maxIterationsReached(this.getClass());
}
if (memory.<Boolean>get(PERSIST_CORENESS)) {
memory.set(PERSIST_CORENESS, false);
}
if (!atRelationships(memory)) {
LOGGER.debug("UpdateEntityAndAttribute... Finished Iteration " + memory.getIteration());
if (!memory.<Boolean>get(K_CORE_EXIST)) {
LOGGER.debug("KCoreVertexProgram Finished !!!!!!!!");
return true;
} else {
if (memory.<Boolean>get(K_CORE_STABLE)) {
LOGGER.debug("Found Core Areas K = " + memory.<Long>get(K) + "\n");
memory.set(K, memory.<Long>get(K) + 1L);
memory.set(PERSIST_CORENESS, true);
} else {
memory.set(K_CORE_STABLE, true);
}
memory.set(K_CORE_EXIST, false);
return false;
}
} else {
LOGGER.debug("RelayOrSaveMessage... Finished Iteration " + memory.getIteration());
return false; // can not end after relayOrSaveMessages
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/CountMapReduce.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.graql.internal.analytics;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.io.Serializable;
import java.util.Iterator;
/**
* The MapReduce program for counting the number of instances excluding attributes and implicit relationships
*
* @author Jason Liu
* @author Sheldon Hall
*/
public class CountMapReduce extends GraknMapReduce<Long> {
// Needed internally for OLAP tasks
public CountMapReduce() {
}
@Override
public void safeMap(final Vertex vertex, final MapEmitter<Serializable, Long> emitter) {
emitter.emit(vertex.value(Schema.VertexProperty.THING_TYPE_LABEL_ID.name()), 1L);
}
@Override
Long reduceValues(Iterator<Long> values) {
return IteratorUtils.reduce(values, 0L, (a, b) -> a + b);
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/CountMapReduceWithAttribute.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.graql.internal.analytics;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.io.Serializable;
/**
* The MapReduce program for counting the number of instances
*
* @author Jason Liu
*/
public class CountMapReduceWithAttribute extends CountMapReduce {
@SuppressWarnings("unused")// Needed internally for OLAP tasks
public CountMapReduceWithAttribute() {
}
@Override
public void safeMap(final Vertex vertex, final MapEmitter<Serializable, Long> emitter) {
if (vertex.property(CountVertexProgram.EDGE_COUNT).isPresent()) {
emitter.emit(RESERVED_TYPE_LABEL_KEY,
vertex.value(CountVertexProgram.EDGE_COUNT));
}
emitter.emit(vertex.value(Schema.VertexProperty.THING_TYPE_LABEL_ID.name()), 1L);
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/CountVertexProgram.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.graql.internal.analytics;
import ai.grakn.util.CommonUtil;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MessageScope;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.Collections;
import java.util.Set;
/**
* The vertex program for counting concepts.
* <p>
*
* @author Jason Liu
*/
public class CountVertexProgram extends GraknVertexProgram<Long> {
public static final String EDGE_COUNT = "countVertexProgram.edgeCount";
// Needed internally for OLAP tasks
public CountVertexProgram() {
}
@Override
public Set<VertexComputeKey> getVertexComputeKeys() {
return Collections.singleton(VertexComputeKey.of(EDGE_COUNT, false));
}
@Override
public Set<MessageScope> getMessageScopes(final Memory memory) {
return memory.isInitialIteration() ? messageScopeSetInAndOut : Collections.emptySet();
}
@Override
public void safeExecute(final Vertex vertex, Messenger<Long> messenger, final Memory memory) {
switch (memory.getIteration()) {
case 0:
messenger.sendMessage(messageScopeOut, 1L);
break;
case 1:
if (messenger.receiveMessages().hasNext()) {
vertex.property(EDGE_COUNT, getMessageCount(messenger));
}
break;
default:
throw CommonUtil.unreachableStatement("Exceeded expected maximum number of iterations");
}
}
@Override
public boolean terminate(final Memory memory) {
LOGGER.debug("Finished Count Iteration " + memory.getIteration());
return memory.getIteration() == 1;
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/DegreeDistributionMapReduce.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.graql.internal.analytics;
import ai.grakn.concept.ConceptId;
import ai.grakn.concept.LabelId;
import ai.grakn.util.Schema;
import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import static ai.grakn.graql.internal.analytics.Utility.reduceSet;
import static ai.grakn.graql.internal.analytics.Utility.vertexHasSelectedTypeId;
/**
* The MapReduce program for collecting the result of a degree query.
* <p>
* It returns a map, the key being the degree, the value being a vertex id set containing all the vertices
* with the given degree.
* <p>
*
* @author Jason Liu
* @author Sheldon Hall
*/
public class DegreeDistributionMapReduce extends GraknMapReduce<Set<ConceptId>> {
// Needed internally for OLAP tasks
public DegreeDistributionMapReduce() {
}
public DegreeDistributionMapReduce(Set<LabelId> selectedLabelIds, String degreePropertyKey) {
super(selectedLabelIds);
this.persistentProperties.put(DegreeVertexProgram.DEGREE, degreePropertyKey);
}
@Override
public void safeMap(final Vertex vertex, final MapEmitter<Serializable, Set<ConceptId>> emitter) {
if (vertex.property((String) persistentProperties.get(DegreeVertexProgram.DEGREE)).isPresent() &&
vertexHasSelectedTypeId(vertex, selectedTypes)) {
String degreePropertyKey = (String) persistentProperties.get(DegreeVertexProgram.DEGREE);
Long centralityCount = vertex.value(degreePropertyKey);
ConceptId conceptId = ConceptId.of(vertex.value(Schema.VertexProperty.ID.name()));
emitter.emit(centralityCount, Collections.singleton(conceptId));
} else {
emitter.emit(NullObject.instance(), Collections.emptySet());
}
}
@Override
Set<ConceptId> reduceValues(Iterator<Set<ConceptId>> values) {
return reduceSet(values);
}
@Override
public Map<Serializable, Set<ConceptId>> generateFinalResult(Iterator<KeyValue<Serializable, Set<ConceptId>>> keyValues) {
LOGGER.debug("MapReduce Finished !!!!!!!!");
final Map<Serializable, Set<ConceptId>> clusterPopulation = Utility.keyValuesToMap(keyValues);
clusterPopulation.remove(NullObject.instance());
return clusterPopulation;
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/DegreeStatisticsVertexProgram.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.graql.internal.analytics;
import ai.grakn.concept.LabelId;
import ai.grakn.util.CommonUtil;
import ai.grakn.util.Schema;
import com.google.common.collect.Sets;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MessageScope;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.Collections;
import java.util.Set;
import static ai.grakn.graql.internal.analytics.Utility.vertexHasSelectedTypeId;
/**
* The vertex program for computing the degree in statistics.
* <p>
*
* @author Jason Liu
*/
public class DegreeStatisticsVertexProgram extends DegreeVertexProgram {
@SuppressWarnings("unused")// Needed internally for OLAP tasks
public DegreeStatisticsVertexProgram() {
}
public DegreeStatisticsVertexProgram(Set<LabelId> ofLabelIDs) {
super(ofLabelIDs);
}
@Override
public void safeExecute(final Vertex vertex, Messenger<Long> messenger, final Memory memory) {
switch (memory.getIteration()) {
case 0:
degreeStatisticsStepResourceOwner(vertex, messenger, ofLabelIds);
break;
case 1:
degreeStatisticsStepResourceRelation(vertex, messenger, ofLabelIds);
break;
case 2:
degreeStatisticsStepResource(vertex, messenger, ofLabelIds);
break;
default:
throw CommonUtil.unreachableStatement("Exceeded expected maximum number of iterations");
}
}
@Override
public Set<MessageScope> getMessageScopes(final Memory memory) {
switch (memory.getIteration()) {
case 0:
return Sets.newHashSet(messageScopeShortcutIn, messageScopeResourceOut);
case 1:
return Collections.singleton(messageScopeShortcutOut);
default:
return Collections.emptySet();
}
}
@Override
public boolean terminate(final Memory memory) {
LOGGER.debug("Finished Degree Iteration " + memory.getIteration());
return memory.getIteration() == 2;
}
static void degreeStatisticsStepResourceOwner(Vertex vertex, Messenger<Long> messenger, Set<LabelId> ofLabelIds) {
LabelId labelId = Utility.getVertexTypeId(vertex);
if (labelId.isValid() && !ofLabelIds.contains(labelId)) {
messenger.sendMessage(messageScopeShortcutIn, 1L);
messenger.sendMessage(messageScopeResourceOut, 1L);
}
}
static void degreeStatisticsStepResourceRelation(Vertex vertex, Messenger<Long> messenger, Set<LabelId> ofLabelIds) {
if (messenger.receiveMessages().hasNext()) {
if (vertex.label().equals(Schema.BaseType.RELATIONSHIP.name())) {
messenger.sendMessage(messageScopeOut, 1L);
} else if (ofLabelIds.contains(Utility.getVertexTypeId(vertex))) {
vertex.property(DEGREE, getMessageCount(messenger));
}
}
}
static void degreeStatisticsStepResource(Vertex vertex, Messenger<Long> messenger,
Set<LabelId> ofLabelIds) {
if (vertexHasSelectedTypeId(vertex, ofLabelIds)) {
vertex.property(DEGREE, vertex.property(DEGREE).isPresent() ?
getMessageCount(messenger) + (Long) vertex.value(DEGREE) : getMessageCount(messenger));
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/DegreeVertexProgram.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.graql.internal.analytics;
import ai.grakn.concept.LabelId;
import ai.grakn.util.CommonUtil;
import com.google.common.collect.Sets;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MessageScope;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static ai.grakn.graql.internal.analytics.Utility.vertexHasSelectedTypeId;
/**
* The vertex program for computing the degree.
* <p>
*
* @author Jason Liu
* @author Sheldon Hall
*/
public class DegreeVertexProgram extends GraknVertexProgram<Long> {
public static final String DEGREE = "degreeVertexProgram.degree";
private static final String OF_LABELS = "degreeVertexProgram.ofLabelIds";
Set<LabelId> ofLabelIds = new HashSet<>();
// Needed internally for OLAP tasks
public DegreeVertexProgram() {
}
public DegreeVertexProgram(Set<LabelId> ofLabelIds) {
this.ofLabelIds = ofLabelIds;
}
@Override
public void storeState(final Configuration configuration) {
super.storeState(configuration);
ofLabelIds.forEach(type -> configuration.addProperty(OF_LABELS + "." + type, type));
}
@Override
public void loadState(final Graph graph, final Configuration configuration) {
super.loadState(graph, configuration);
configuration.subset(OF_LABELS).getKeys().forEachRemaining(key ->
ofLabelIds.add((LabelId) configuration.getProperty(OF_LABELS + "." + key)));
}
@Override
public Set<VertexComputeKey> getVertexComputeKeys() {
return Collections.singleton(VertexComputeKey.of(DEGREE, false));
}
@Override
public Set<MessageScope> getMessageScopes(final Memory memory) {
return memory.isInitialIteration() ?
Sets.newHashSet(messageScopeResourceIn, messageScopeOut) : Collections.emptySet();
}
@Override
public void safeExecute(final Vertex vertex, Messenger<Long> messenger, final Memory memory) {
switch (memory.getIteration()) {
case 0:
degreeMessagePassing(messenger);
break;
case 1:
degreeMessageCounting(messenger, vertex);
break;
default:
throw CommonUtil.unreachableStatement("Exceeded expected maximum number of iterations");
}
}
@Override
public boolean terminate(final Memory memory) {
LOGGER.debug("Finished Degree Iteration " + memory.getIteration());
return memory.getIteration() == 1;
}
private void degreeMessagePassing(Messenger<Long> messenger) {
messenger.sendMessage(messageScopeResourceIn, 1L);
messenger.sendMessage(messageScopeOut, 1L);
}
private void degreeMessageCounting(Messenger<Long> messenger, Vertex vertex) {
if (messenger.receiveMessages().hasNext() &&
(ofLabelIds.isEmpty() || vertexHasSelectedTypeId(vertex, ofLabelIds))) {
vertex.property(DEGREE, getMessageCount(messenger));
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/GraknMapReduce.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.graql.internal.analytics;
import ai.grakn.concept.LabelId;
import ai.grakn.concept.AttributeType;
import ai.grakn.util.CommonUtil;
import ai.grakn.util.Schema;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.process.computer.MapReduce;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A map reduce task specific to Grakn with common method implementations.
* <p>
*
* @param <T> type type of element that is being reduced
* @author Jason Liu
* @author Sheldon Hall
*/
public abstract class GraknMapReduce<T> extends CommonOLAP
implements MapReduce<Serializable, T, Serializable, T, Map<Serializable, T>> {
private static final String RESOURCE_DATA_TYPE_KEY = "RESOURCE_DATA_TYPE_KEY";
// In MapReduce, vertex emits type label id, but has-resource edge can not. Instead, a message is sent via the edge,
// and a vertex property is added. So the resource vertex can emit an extra key value pair, key being this constant.
// Here, -10 is just a number that is not used as a type id.
public static final int RESERVED_TYPE_LABEL_KEY = -10;
GraknMapReduce(Set<LabelId> selectedTypes) {
this.selectedTypes = selectedTypes;
}
GraknMapReduce(Set<LabelId> selectedTypes, AttributeType.DataType resourceDataType) {
this(selectedTypes);
persistentProperties.put(RESOURCE_DATA_TYPE_KEY, resourceDataType.getName());
}
// Needed internally for OLAP tasks
GraknMapReduce() {
}
/**
* An alternative to the execute method when ghost vertices are an issue. Our "Ghostbuster".
*
* @param vertex a vertex that may be a ghost
* @param emitter Tinker emitter object
*/
abstract void safeMap(Vertex vertex, MapEmitter<Serializable, T> emitter);
@Override
public void storeState(final Configuration configuration) {
super.storeState(configuration);
// store class name for reflection on spark executor
configuration.setProperty(MAP_REDUCE, this.getClass().getName());
}
@Override
public final void map(Vertex vertex, MapEmitter<Serializable, T> emitter) {
// try to deal with ghost vertex issues by ignoring them
if (Utility.isAlive(vertex)) {
safeMap(vertex, emitter);
}
}
@Override
public final void reduce(Serializable key, Iterator<T> values, ReduceEmitter<Serializable, T> emitter) {
emitter.emit(key, reduceValues(values));
}
abstract T reduceValues(Iterator<T> values);
@Override
public String getMemoryKey() {
return this.getClass().getName();
}
// super.clone() will always return something of the correct type
@SuppressWarnings("unchecked")
@Override
public MapReduce<Serializable, T, Serializable, T, Map<Serializable, T>> clone() {
try {
return (GraknMapReduce) super.clone();
} catch (final CloneNotSupportedException e) {
throw CommonUtil.unreachableStatement(e);
}
}
@Override
public boolean doStage(final Stage stage) {
return true;
}
@Override
public final void combine(Serializable key, Iterator<T> values, ReduceEmitter<Serializable, T> emitter) {
this.reduce(key, values, emitter);
}
@Override
public Map<Serializable, T> generateFinalResult(Iterator<KeyValue<Serializable, T>> iterator) {
return Utility.keyValuesToMap(iterator);
}
final Number resourceValue(Vertex vertex) {
return usingLong() ? vertex.value(Schema.VertexProperty.VALUE_LONG.name()) :
vertex.value(Schema.VertexProperty.VALUE_DOUBLE.name());
}
final Number minValue() {
return usingLong() ? Long.MIN_VALUE : Double.MIN_VALUE;
}
final Number maxValue() {
return usingLong() ? Long.MAX_VALUE : Double.MAX_VALUE;
}
final boolean usingLong() {
return persistentProperties.get(RESOURCE_DATA_TYPE_KEY).equals(AttributeType.DataType.LONG.getName());
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/GraknVertexProgram.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.graql.internal.analytics;
import ai.grakn.util.CommonUtil;
import ai.grakn.util.Schema;
import com.google.common.collect.Sets;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.process.computer.GraphComputer;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MessageScope;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.process.computer.VertexProgram;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Set;
/**
* A vertex program specific to Grakn with common method implementations.
* <p>
*
* @param <T> the type of messages being sent between vertices
* @author Jason Liu
* @author Sheldon Hall
*/
public abstract class GraknVertexProgram<T> extends CommonOLAP implements VertexProgram<T> {
static final MessageScope.Local<?> messageScopeIn = MessageScope.Local.of(__::inE);
static final MessageScope.Local<?> messageScopeOut = MessageScope.Local.of(__::outE);
static final Set<MessageScope> messageScopeSetInAndOut =
Sets.newHashSet(messageScopeIn, messageScopeOut);
static final MessageScope.Local<?> messageScopeShortcutIn = MessageScope.Local.of(
() -> __.inE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()));
static final MessageScope.Local<?> messageScopeShortcutOut = MessageScope.Local.of(
() -> __.outE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()));
static final MessageScope.Local<?> messageScopeResourceIn = MessageScope.Local.of(
() -> __.inE(Schema.EdgeLabel.ATTRIBUTE.getLabel()));
static final MessageScope.Local<?> messageScopeResourceOut = MessageScope.Local.of(
() -> __.outE(Schema.EdgeLabel.ATTRIBUTE.getLabel()));
@Override
public Set<MessageScope> getMessageScopes(final Memory memory) {
return messageScopeSetInAndOut;
}
@Override
public void storeState(final Configuration configuration) {
super.storeState(configuration);
// store class name for reflection on spark executor
configuration.setProperty(VERTEX_PROGRAM, this.getClass().getName());
}
@Override
public void setup(final Memory memory) {
}
@Override
public void execute(Vertex vertex, Messenger<T> messenger, Memory memory) {
// try to deal with ghost vertex issues by ignoring them
if (Utility.isAlive(vertex)) {
safeExecute(vertex, messenger, memory);
}
}
/**
* An alternative to the execute method when ghost vertices are an issue. Our "Ghostbuster".
*
* @param vertex a vertex that may be a ghost
* @param messenger Tinker message passing object
* @param memory Tinker memory object
*/
abstract void safeExecute(Vertex vertex, Messenger<T> messenger, Memory memory);
@Override
public GraphComputer.ResultGraph getPreferredResultGraph() {
return GraphComputer.ResultGraph.ORIGINAL;
}
@Override
public GraphComputer.Persist getPreferredPersist() {
return GraphComputer.Persist.NOTHING;
}
// super.clone() will always return something of the correct type
@SuppressWarnings("unchecked")
@Override
public GraknVertexProgram<T> clone() {
try {
return (GraknVertexProgram) super.clone();
} catch (final CloneNotSupportedException e) {
throw CommonUtil.unreachableStatement(e);
}
}
static long getMessageCount(Messenger<Long> messenger) {
return IteratorUtils.reduce(messenger.receiveMessages(), 0L, (a, b) -> a + b);
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/KCoreVertexProgram.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.graql.internal.analytics;
import ai.grakn.exception.GraqlQueryException;
import ai.grakn.util.Schema;
import com.google.common.collect.Iterators;
import org.apache.tinkerpop.gremlin.process.computer.Memory;
import org.apache.tinkerpop.gremlin.process.computer.MemoryComputeKey;
import org.apache.tinkerpop.gremlin.process.computer.Messenger;
import org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey;
import org.apache.tinkerpop.gremlin.process.traversal.Operator;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
/**
* The vertex program for computing k-core.
*
* @author Jason Liu
*/
public class KCoreVertexProgram extends GraknVertexProgram<String> {
private static final int MAX_ITERATION = 200;
private static final String EMPTY_MESSAGE = "";
public static final String K_CORE_LABEL = "kCoreVertexProgram.kCoreLabel";
static final String IMPLICIT_MESSAGE_COUNT = "kCoreVertexProgram.implicitMessageCount";
static final String MESSAGE_COUNT = "corenessVertexProgram.messageCount";
static final String K_CORE_STABLE = "kCoreVertexProgram.stable";
static final String K_CORE_EXIST = "kCoreVertexProgram.exist";
static final String K = "kCoreVertexProgram.k";
private static final String CONNECTED_COMPONENT_STARTED = "kCoreVertexProgram.ccStarted";
private static final String VOTE_TO_HALT = "kCoreVertexProgram.voteToHalt";
private static final Set<MemoryComputeKey> MEMORY_COMPUTE_KEYS = newHashSet(
MemoryComputeKey.of(K_CORE_STABLE, Operator.and, false, true),
MemoryComputeKey.of(K_CORE_EXIST, Operator.or, false, true),
MemoryComputeKey.of(CONNECTED_COMPONENT_STARTED, Operator.assign, true, true),
MemoryComputeKey.of(VOTE_TO_HALT, Operator.and, false, true),
MemoryComputeKey.of(K, Operator.assign, true, true));
private static final Set<VertexComputeKey> VERTEX_COMPUTE_KEYS = newHashSet(
VertexComputeKey.of(K_CORE_LABEL, false),
VertexComputeKey.of(IMPLICIT_MESSAGE_COUNT, true));
@SuppressWarnings("unused") //Needed internally for OLAP tasks
public KCoreVertexProgram() {
}
public KCoreVertexProgram(long kValue) {
this.persistentProperties.put(K, kValue);
}
@Override
public Set<VertexComputeKey> getVertexComputeKeys() {
return VERTEX_COMPUTE_KEYS;
}
@Override
public Set<MemoryComputeKey> getMemoryComputeKeys() {
return MEMORY_COMPUTE_KEYS;
}
@Override
public void setup(final Memory memory) {
LOGGER.debug("KCoreVertexProgram Started !!!!!!!!");
// K_CORE_STABLE is true by default, and we reset it after each odd iteration.
memory.set(K_CORE_STABLE, false);
memory.set(K_CORE_EXIST, false);
memory.set(K, persistentProperties.get(K));
memory.set(VOTE_TO_HALT, true);
memory.set(CONNECTED_COMPONENT_STARTED, false);
}
@Override
public void safeExecute(final Vertex vertex, Messenger<String> messenger, final Memory memory) {
switch (memory.getIteration()) {
case 0:
sendMessage(messenger, EMPTY_MESSAGE);
break;
case 1: // get degree first, as degree must >= k
filterByDegree(vertex, messenger, memory, true);
break;
default:
if (memory.<Boolean>get(CONNECTED_COMPONENT_STARTED)) {
if (messenger.receiveMessages().hasNext()) {
if (vertex.property(K_CORE_LABEL).isPresent()) {
updateClusterLabel(vertex, messenger, memory);
} else if (vertex.label().equals(Schema.BaseType.RELATIONSHIP.name())) {
relayClusterLabel(messenger, memory);
}
}
} else {
// relay message through relationship vertices in even iterations
// send message from regular entities in odd iterations
if (atRelationships(memory)) {
relayOrSaveMessages(vertex, messenger);
} else {
updateEntityAndAttribute(vertex, messenger, memory, false);
}
}
break;
}
}
static void filterByDegree(Vertex vertex, Messenger<String> messenger, Memory memory, boolean persistId) {
if ((vertex.label().equals(Schema.BaseType.ENTITY.name()) ||
vertex.label().equals(Schema.BaseType.ATTRIBUTE.name())) &&
Iterators.size(messenger.receiveMessages()) >= memory.<Long>get(K)) {
String id = vertex.value(Schema.VertexProperty.ID.name());
// coreness query doesn't require id
if (persistId) {
vertex.property(K_CORE_LABEL, id);
} else {
vertex.property(K_CORE_LABEL, true);
}
memory.add(K_CORE_EXIST, true);
// send ids from now on, as we want to count connected entities, not relationships
sendMessage(messenger, id);
}
}
static void relayOrSaveMessages(Vertex vertex, Messenger<String> messenger) {
if (messenger.receiveMessages().hasNext()) {
if (vertex.label().equals(Schema.BaseType.RELATIONSHIP.name())) {
// relay the messages
messenger.receiveMessages().forEachRemaining(msg -> sendMessage(messenger, msg));
} else if ((vertex.label().equals(Schema.BaseType.ENTITY.name()) ||
vertex.label().equals(Schema.BaseType.ATTRIBUTE.name())) &&
vertex.property(K_CORE_LABEL).isPresent()) {
// messages received via implicit edge, save the count for next iteration
vertex.property(IMPLICIT_MESSAGE_COUNT, (long) newHashSet(messenger.receiveMessages()).size());
}
}
}
static void updateEntityAndAttribute(Vertex vertex, Messenger<String> messenger,
Memory memory, boolean persistMessageCount) {
if (vertex.property(K_CORE_LABEL).isPresent()) {
String id = vertex.value(Schema.VertexProperty.ID.name());
long messageCount = (long) getMessageCountExcludeSelf(messenger, id);
if (vertex.property(IMPLICIT_MESSAGE_COUNT).isPresent()) {
messageCount += vertex.<Long>value(IMPLICIT_MESSAGE_COUNT);
// need to remove implicit count as the vertex may not receive msg via implicit edge
vertex.property(IMPLICIT_MESSAGE_COUNT).remove();
}
if (messageCount >= memory.<Long>get(K)) {
LOGGER.trace("Sending msg from " + id);
sendMessage(messenger, id);
memory.add(K_CORE_EXIST, true);
if (persistMessageCount) {
// message count may help eliminate unqualified vertex in earlier iterations
vertex.property(MESSAGE_COUNT, messageCount);
}
} else {
LOGGER.trace("Removing label of " + id);
vertex.property(K_CORE_LABEL).remove();
memory.add(K_CORE_STABLE, false);
}
}
}
private static void updateClusterLabel(Vertex vertex, Messenger<String> messenger, Memory memory) {
String currentMax = vertex.value(K_CORE_LABEL);
String max = IteratorUtils.reduce(messenger.receiveMessages(), currentMax,
(a, b) -> a.compareTo(b) > 0 ? a : b);
if (!max.equals(currentMax)) {
LOGGER.trace("Cluster label of " + vertex + " changed from " + currentMax + " to " + max);
vertex.property(K_CORE_LABEL, max);
sendMessage(messenger, max);
memory.add(VOTE_TO_HALT, false);
} else {
LOGGER.trace("Cluster label of " + vertex + " is still " + currentMax);
}
}
private static void relayClusterLabel(Messenger<String> messenger, Memory memory) {
String firstMessage = messenger.receiveMessages().next();
String max = IteratorUtils.reduce(messenger.receiveMessages(), firstMessage,
(a, b) -> a.compareTo(b) > 0 ? a : b);
sendMessage(messenger, max);
memory.add(VOTE_TO_HALT, false);
}
// count the messages from relationships, so need to filter its own msg
private static int getMessageCountExcludeSelf(Messenger<String> messenger, String id) {
Set<String> messageSet = newHashSet(messenger.receiveMessages());
messageSet.remove(id);
return messageSet.size();
}
static void sendMessage(Messenger<String> messenger, String message) {
messenger.sendMessage(messageScopeIn, message);
messenger.sendMessage(messageScopeOut, message);
}
static boolean atRelationships(Memory memory) {
return memory.getIteration() % 2 == 0;
}
@Override
public boolean terminate(final Memory memory) {
LOGGER.debug("Finished Iteration " + memory.getIteration());
if (memory.isInitialIteration()) return false;
if (memory.getIteration() == MAX_ITERATION) {
LOGGER.debug("Reached Max Iteration: " + MAX_ITERATION + " !!!!!!!!");
throw GraqlQueryException.maxIterationsReached(this.getClass());
}
if (memory.<Boolean>get(CONNECTED_COMPONENT_STARTED)) {
if (memory.<Boolean>get(VOTE_TO_HALT)) {
LOGGER.debug("KCoreVertexProgram Finished !!!!!!!!");
return true; // connected component is done
} else {
memory.set(VOTE_TO_HALT, true);
return false;
}
} else {
if (!atRelationships(memory)) {
if (!memory.<Boolean>get(K_CORE_EXIST)) {
LOGGER.debug("KCoreVertexProgram Finished !!!!!!!!");
LOGGER.debug("No Such Core Areas Found !!!!!!!!");
throw new NoResultException();
} else {
if (memory.<Boolean>get(K_CORE_STABLE)) {
memory.set(CONNECTED_COMPONENT_STARTED, true);
LOGGER.debug("Found Core Areas !!!!!!!!");
LOGGER.debug("Starting Connected Components !!!!!!!!");
} else {
memory.set(K_CORE_EXIST, false);
memory.set(K_CORE_STABLE, true);
}
return false;
}
} else {
return false; // can not end after relayOrSaveMessages
}
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/MaxMapReduce.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.graql.internal.analytics;
import ai.grakn.concept.AttributeType;
import ai.grakn.concept.LabelId;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
/**
* The MapReduce program for computing the max value of given resource.
* <p>
*
* @author Jason Liu
* @author Sheldon Hall
*/
public class MaxMapReduce extends StatisticsMapReduce<Number> {
// Needed internally for OLAP tasks
public MaxMapReduce() {
}
public MaxMapReduce(Set<LabelId> selectedLabelIds, AttributeType.DataType resourceDataType, String degreePropertyKey) {
super(selectedLabelIds, resourceDataType, degreePropertyKey);
}
@Override
public void safeMap(final Vertex vertex, final MapEmitter<Serializable, Number> emitter) {
Number value = resourceIsValid(vertex) ? resourceValue(vertex) : minValue();
emitter.emit(NullObject.instance(), value);
}
@Override
Number reduceValues(Iterator<Number> values) {
if (usingLong()) {
return IteratorUtils.reduce(values, Long.MIN_VALUE, (a, b) -> Math.max(a.longValue(), b.longValue()));
} else {
return IteratorUtils.reduce(values, Double.MIN_VALUE, (a, b) -> Math.max(a.doubleValue(), b.doubleValue()));
}
}
}
|
0
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal
|
java-sources/ai/grakn/grakn-graql/1.4.3/ai/grakn/graql/internal/analytics/MeanMapReduce.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.graql.internal.analytics;
import ai.grakn.concept.AttributeType;
import ai.grakn.concept.LabelId;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* The MapReduce program for computing the mean value of given resource.
* <p>
*
* @author Jason Liu
* @author Sheldon Hall
*/
public class MeanMapReduce extends StatisticsMapReduce<Map<String, Double>> {
public static final String COUNT = "C";
public static final String SUM = "S";
// Needed internally for OLAP tasks
public MeanMapReduce() {
}
public MeanMapReduce(Set<LabelId> selectedLabelIds, AttributeType.DataType resourceDataType, String degreeKey) {
super(selectedLabelIds, resourceDataType, degreeKey);
}
@Override
public void safeMap(final Vertex vertex, final MapEmitter<Serializable, Map<String, Double>> emitter) {
if (resourceIsValid(vertex)) {
Map<String, Double> tuple = new HashMap<>(2);
Double degree = ((Long) vertex.value(degreePropertyKey)).doubleValue();
tuple.put(SUM, degree * this.<Double>resourceValue(vertex).doubleValue());
tuple.put(COUNT, degree);
emitter.emit(NullObject.instance(), tuple);
return;
}
Map<String, Double> emptyTuple = new HashMap<>(2);
emptyTuple.put(SUM, 0D);
emptyTuple.put(COUNT, 0D);
emitter.emit(NullObject.instance(), emptyTuple);
}
@Override
Map<String, Double> reduceValues(Iterator<Map<String, Double>> values) {
Map<String, Double> emptyTuple = new HashMap<>(2);
emptyTuple.put(SUM, 0D);
emptyTuple.put(COUNT, 0D);
return IteratorUtils.reduce(values, emptyTuple,
(a, b) -> {
a.put(COUNT, a.get(COUNT) + b.get(COUNT));
a.put(SUM, a.get(SUM) + b.get(SUM));
return a;
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.