index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/Conjunction.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.admin; import ai.grakn.GraknTx; import javax.annotation.CheckReturnValue; import java.util.Set; /** * A class representing a conjunction (and) of patterns. All inner patterns must match in a query * * @param <T> the type of patterns in this conjunction * * @author Felix Chapman */ public interface Conjunction<T extends PatternAdmin> extends PatternAdmin { /** * @return the patterns within this conjunction */ @CheckReturnValue Set<T> getPatterns(); /** * @return the corresponding reasoner query */ @CheckReturnValue ReasonerQuery toReasonerQuery(GraknTx tx); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/DeleteQueryAdmin.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.admin; import ai.grakn.graql.DeleteQuery; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import javax.annotation.CheckReturnValue; import java.util.Set; /** * Admin class for inspecting and manipulating a DeleteQuery * * @author Felix Chapman */ public interface DeleteQueryAdmin extends DeleteQuery { /** * @return the {@link Match} this delete query is operating on */ @CheckReturnValue Match match(); /** * Get the {@link Var}s to delete on each result of {@link #match()}. */ @CheckReturnValue Set<Var> vars(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/Disjunction.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.admin; import javax.annotation.CheckReturnValue; import java.util.Set; /** * A class representing a disjunction (or) of patterns. Any inner pattern must match in a query * * @param <T> the type of patterns in this disjunction * * @author Felix Chapman */ public interface Disjunction<T extends PatternAdmin> extends PatternAdmin { /** * @return the patterns within this disjunction */ @CheckReturnValue Set<T> getPatterns(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/Explanation.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.admin; import ai.grakn.graql.answer.ConceptMap; import com.google.common.collect.ImmutableList; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import java.util.Set; /** * * <p> * Base class for explanation classes. * </p> * * @author Kasper Piskorski * */ public interface Explanation { /** * produce a new explanation with provided query set * @param q query this explanation should be associated with * @return explanation with provided query */ @CheckReturnValue Explanation setQuery(ReasonerQuery q); /** * produce a new explanation with a provided parent answer * @param ans parent answer * @return new explanation with dependent answers */ @CheckReturnValue Explanation childOf(ConceptMap ans); /** * @return query associated with this explanation */ @Nullable @CheckReturnValue ReasonerQuery getQuery(); /** * @return answers this explanation is dependent on */ @CheckReturnValue ImmutableList<ConceptMap> getAnswers(); /** * @return set of answers corresponding to the explicit path */ @CheckReturnValue Set<ConceptMap> explicit(); /** * @return set of all answers taking part in the derivation of this answer */ @CheckReturnValue Set<ConceptMap> deductions(); /** * * @return true if this explanation explains the answer on the basis of database lookup */ @CheckReturnValue boolean isLookupExplanation(); /** * * @return true if this explanation explains the answer on the basis of rule application */ @CheckReturnValue boolean isRuleExplanation(); /** * * @return true if this explanation explains an intermediate answer being a product of a join operation */ @CheckReturnValue boolean isJoinExplanation(); /** * * @return true if this is an empty explanation (explanation wasn't recorded) */ @CheckReturnValue boolean isEmpty(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/InsertQueryAdmin.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.admin; import ai.grakn.concept.SchemaConcept; import ai.grakn.graql.InsertQuery; import ai.grakn.graql.Match; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import java.util.Collection; import java.util.Set; /** * Admin class for inspecting and manipulating an InsertQuery * * @author Grakn Warriors */ public interface InsertQueryAdmin extends InsertQuery { /** * @return the {@link Match} that this insert query is using, if it was provided one */ @Nullable @CheckReturnValue Match match(); /** * @return all concept types referred to explicitly in the query */ @CheckReturnValue Set<SchemaConcept> getSchemaConcepts(); /** * @return the variables to insert in the insert query */ @CheckReturnValue Collection<VarPatternAdmin> varPatterns(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/MatchAdmin.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.admin; import ai.grakn.GraknTx; import ai.grakn.concept.SchemaConcept; import ai.grakn.graql.Match; import ai.grakn.graql.Var; import javax.annotation.CheckReturnValue; import java.util.Set; /** * Admin class for inspecting and manipulating a {@link Match} * * @author Grakn Warriors */ public interface MatchAdmin extends Match { /** * @param tx the {@link GraknTx} to use to get types from * @return all concept types referred to explicitly in the query */ @CheckReturnValue Set<SchemaConcept> getSchemaConcepts(GraknTx tx); /** * @return all concept types referred to explicitly in the query */ @CheckReturnValue Set<SchemaConcept> getSchemaConcepts(); /** * @return the pattern to match in the graph */ @CheckReturnValue Conjunction<PatternAdmin> getPattern(); /** * @return the graph the query operates on, if one was provided */ @CheckReturnValue GraknTx tx(); /** * @return all selected variable names in the query */ @CheckReturnValue Set<Var> getSelectedNames(); /** * @return true if query will involve / set to performing inference */ Boolean inferring(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/MultiUnifier.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.admin; import com.google.common.collect.ImmutableSet; import javax.annotation.CheckReturnValue; import java.util.Iterator; import java.util.stream.Stream; /** * * <p> * Generalisation of the {@link Unifier} accounting for the possibility of existence of more than one unifier between two expressions. * Corresponds to a simple set U = {u1, u2, ..., ui}, where i e N, i >= 0. * The case of i = 0 corresponds to a case where no unifier exists. * </p> * * @author Kasper Piskorski * */ public interface MultiUnifier extends Iterable<Unifier> { /** * @return iterator over unifiers */ @Override @CheckReturnValue default Iterator<Unifier> iterator() { return stream().iterator(); } /** * @return a stream of unifiers */ @CheckReturnValue Stream<Unifier> stream(); /** * @return true if the multiunifier is empty */ @CheckReturnValue boolean isEmpty(); /** * @return unique unifier if exists, throws an exception otherwise */ @CheckReturnValue Unifier getUnifier(); /** * @return a unifier from this unifier */ Unifier getAny(); /** * @return the set of unifiers corresponding to this multiunifier */ @CheckReturnValue ImmutableSet<Unifier> unifiers(); /** * @return multiunifier inverse - multiunifier built of inverses of all constituent unifiers */ @CheckReturnValue MultiUnifier inverse(); /** * * @param u multiunifier to compared with * @return true if for all unifiers ui of u, there exists a unifier in this multiunifier that contains all mappings of ui */ @CheckReturnValue boolean containsAll(MultiUnifier u); /** * @return number of unifiers this multiunifier holds */ @CheckReturnValue int size(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/PatternAdmin.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.admin; import ai.grakn.graql.Pattern; import ai.grakn.graql.Var; import javax.annotation.CheckReturnValue; import java.util.Set; import static java.util.stream.Collectors.toSet; /** * Admin class for inspecting and manipulating a Pattern * * @author Felix Chapman */ public interface PatternAdmin extends Pattern { /** * Get the disjunctive normal form of this pattern group. * This means the pattern group will be transformed into a number of conjunctive patterns, where each is disjunct. * * e.g. * p = (A or B) and (C or D) * p.getDisjunctiveNormalForm() = (A and C) or (A and D) or (B and C) or (B and D) * * @return the pattern group in disjunctive normal form */ @CheckReturnValue Disjunction<Conjunction<VarPatternAdmin>> getDisjunctiveNormalForm(); /** * Get all common, user-defined variable names in the pattern. */ @CheckReturnValue Set<Var> commonVars(); /** * @return true if this Pattern.Admin is a Conjunction */ @CheckReturnValue default boolean isDisjunction() { return false; } /** * @return true if this Pattern.Admin is a Disjunction */ @CheckReturnValue default boolean isConjunction() { return false; } /** * @return true if this {@link PatternAdmin} is a {@link VarPatternAdmin} */ @CheckReturnValue default boolean isVarPattern() { return false; } /** * @return this Pattern.Admin as a Disjunction, if it is one. */ @CheckReturnValue default Disjunction<?> asDisjunction() { throw new UnsupportedOperationException(); } /** * @return this Pattern.Admin as a Conjunction, if it is one. */ @CheckReturnValue default Conjunction<?> asConjunction() { throw new UnsupportedOperationException(); } /** * @return this {@link PatternAdmin} as a {@link VarPatternAdmin}, if it is one. */ @CheckReturnValue default VarPatternAdmin asVarPattern() { throw new UnsupportedOperationException(); } /** * @return all variables referenced in the pattern */ @CheckReturnValue default Set<VarPatternAdmin> varPatterns() { return getDisjunctiveNormalForm().getPatterns().stream() .flatMap(conj -> conj.getPatterns().stream()) .collect(toSet()); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/ReasonerQuery.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.admin; import ai.grakn.GraknTx; import ai.grakn.concept.Type; import ai.grakn.graql.Var; import ai.grakn.graql.answer.ConceptMap; import com.google.common.collect.ImmutableMap; import javax.annotation.CheckReturnValue; import java.util.Set; import java.util.stream.Stream; /** * * <p> * Interface for conjunctive reasoner queries. * </p> * * @author Kasper Piskorski * */ public interface ReasonerQuery{ /** * @param q query to combine * @return a query formed as conjunction of this and provided query */ @CheckReturnValue ReasonerQuery conjunction(ReasonerQuery q); /** * @return {@link GraknTx} associated with this reasoner query */ @CheckReturnValue GraknTx tx(); /** * validate the query wrt transaction it is defined in */ void checkValid(); /** * @return set of variable names present in this reasoner query */ @CheckReturnValue Set<Var> getVarNames(); /** * @return atom set defining this reasoner query */ @CheckReturnValue Set<Atomic> getAtoms(); /** * @return the conjunction pattern that represent this query */ Conjunction<PatternAdmin> getPattern(); /** * @param type the class of {@link Atomic} to return * @param <T> the type of {@link Atomic} to return * @return stream of atoms of specified type defined in this query */ @CheckReturnValue <T extends Atomic> Stream<T> getAtoms(Class<T> type); /** * @return (partial) substitution obtained from all id predicates (including internal) in the query */ @CheckReturnValue ConceptMap getSubstitution(); /** * @return error messages indicating ontological inconsistencies of the query */ @CheckReturnValue Set<String> validateOntologically(); /** * @return true if any of the atoms constituting the query can be resolved through a rule */ @CheckReturnValue boolean isRuleResolvable(); /** * @param typedVar variable of interest * @param parentType which playability in this query is to be checked * @return true if typing the typeVar with type is compatible with role configuration of this query */ @CheckReturnValue boolean isTypeRoleCompatible(Var typedVar, Type parentType); /** * @param parent query we want to unify this query with * @return corresponding multiunifier */ @CheckReturnValue MultiUnifier getMultiUnifier(ReasonerQuery parent); /** * @param parent query we want to unify this query with * @param unifierType unifier type * @return corresponding multiunifier */ @CheckReturnValue MultiUnifier getMultiUnifier(ReasonerQuery parent, UnifierComparison unifierType); /** * resolves the query * @return stream of answers */ @CheckReturnValue Stream<ConceptMap> resolve(); /** * Returns a var-type map local to this query. Map is cached. * @return map of variable name - corresponding type pairs */ @CheckReturnValue ImmutableMap<Var, Type> getVarTypeMap(); /** * @param inferTypes whether types should be inferred from ids * @return map of variable name - corresponding type pairs */ @CheckReturnValue ImmutableMap<Var, Type> getVarTypeMap(boolean inferTypes); /** * Returns a var-type of this query with possible additions coming from supplied partial answer. * @param sub partial answer * @return map of variable name - corresponding type pairs */ @CheckReturnValue ImmutableMap<Var, Type> getVarTypeMap(ConceptMap sub); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/RelationPlayer.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.admin; import com.google.auto.value.AutoValue; import javax.annotation.CheckReturnValue; import java.util.Optional; /** * A pair of role and role player (where the role may not be present) * * @author Felix Chapman */ @AutoValue public abstract class RelationPlayer { /** * A role - role player pair without a role specified * @param rolePlayer the role player of the role - role player pair */ public static RelationPlayer of(VarPatternAdmin rolePlayer) { return new AutoValue_RelationPlayer(Optional.empty(), rolePlayer); } /** * @param role the role of the role - role player pair * @param rolePlayer the role player of the role - role player pair */ public static RelationPlayer of(VarPatternAdmin role, VarPatternAdmin rolePlayer) { return new AutoValue_RelationPlayer(Optional.of(role), rolePlayer); } /** * @return the role, if specified */ @CheckReturnValue public abstract Optional<VarPatternAdmin> getRole(); /** * @return the role player */ @CheckReturnValue public abstract VarPatternAdmin getRolePlayer(); @Override public String toString() { return getRole().map(r -> r.getPrintableName() + ": ").orElse("") + getRolePlayer().getPrintableName(); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/Unifier.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.admin; import ai.grakn.graql.Var; import com.google.common.collect.ImmutableSet; import javax.annotation.CheckReturnValue; import java.util.Collection; import java.util.Map; import java.util.Set; /** * * <p> * Interface for resolution unifier defined as a finite set of mappings between variables xi and terms ti: * * θ = {x1/t1, x2/t2, ..., xi/ti}. * * Both variables and terms are defined in terms of graql Vars. * * For a set of expressions Γ, the unifier θ maps elements from Γ to a single expression φ : Γθ = {φ}. * </p> * * @author Kasper Piskorski * */ public interface Unifier{ /** * @param key specific variable * @return corresponding terms */ @CheckReturnValue Collection<Var> get(Var key); /** * @return true if the set of mappings is empty */ @CheckReturnValue boolean isEmpty(); /** * @return variables present in this unifier */ @CheckReturnValue Set<Var> keySet(); /** * @return terms present in this unifier */ @CheckReturnValue Collection<Var> values(); /** * @return set of mappings constituting this unifier */ @CheckReturnValue ImmutableSet<Map.Entry<Var, Var>> mappings(); /** * @param key variable to be inspected for presence * @return true if specified key is part of a mapping */ @CheckReturnValue boolean containsKey(Var key); /** * @param u unifier to be compared with * @return true if this unifier contains all mappings of u */ @CheckReturnValue boolean containsAll(Unifier u); /** * unifier merging by simple mapping addition (no variable clashes assumed) * @param u unifier to be merged with this unifier * @return merged unifier */ Unifier merge(Unifier u); /** * @return unifier inverse - new unifier with inverted mappings */ @CheckReturnValue Unifier inverse(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/UnifierComparison.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.admin; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.graql.Var; import java.util.Set; /** * * <p> * Interface for defining unifier comparisons. * </p> * * @author Kasper Piskorski * */ public interface UnifierComparison { /** * @param parent {@link SchemaConcept} of parent expression * @param child {@link SchemaConcept} of child expression * @return true if {@link Type}s are compatible */ boolean typeCompatibility(SchemaConcept parent, SchemaConcept child); /** * @param parent {@link Atomic} of parent expression * @param child {@link Atomic} of child expression * @return true if id predicates are compatible */ boolean idCompatibility(Atomic parent, Atomic child); /** * @param parent {@link Atomic} of parent expression * @param child {@link Atomic} of child expression * @return true if value predicates are compatible */ boolean valueCompatibility(Atomic parent, Atomic child); /** * @param query to be checked * @param var variable of interest * @param type which playability is toto be checked * @return true if typing the typeVar with type is compatible with role configuration of the provided query */ boolean typePlayability(ReasonerQuery query, Var var, Type type); /** * * @param parent multipredicate of parent attribute * @param child multipredicate of child attribute * @return true if multipredicates of attributes are compatible */ boolean attributeValueCompatibility(Set<Atomic> parent, Set<Atomic> child); /** * * @param parent {@link Atomic} query * @param child {@link Atomic} query * @param parentVar variable of interest in the parent query * @param childVar variable of interest in the child query * @return true if attributes attached to child var are compatible with attributes attached to parent var */ default boolean attributeCompatibility(ReasonerQuery parent, ReasonerQuery child, Var parentVar, Var childVar){ return true;} }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/UniqueVarProperty.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.admin; import ai.grakn.graql.VarPattern; import javax.annotation.CheckReturnValue; /** * A unique property of a {@link VarPattern}. * * This property is unique in that each {@link VarPattern} may have exactly zero or one of each * {@link UniqueVarProperty}. * * @author Felix Chapman */ public interface UniqueVarProperty extends VarProperty { @CheckReturnValue default boolean isUnique() { return true; } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/VarPatternAdmin.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.admin; import ai.grakn.concept.Label; import ai.grakn.graql.Var; import ai.grakn.graql.VarPattern; import javax.annotation.CheckReturnValue; import java.util.Collection; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; /** * Admin class for inspecting a {@link VarPattern} * * @author Felix Chapman */ public interface VarPatternAdmin extends PatternAdmin, VarPattern { @Override default boolean isVarPattern() { return true; } @Override default VarPatternAdmin asVarPattern() { return this; } /** * @return the variable name of this variable */ @CheckReturnValue Var var(); /** * Get a stream of all properties on this variable */ @CheckReturnValue Stream<VarProperty> getProperties(); /** * Get a stream of all properties of a particular type on this variable * @param type the class of {@link VarProperty} to return * @param <T> the type of {@link VarProperty} to return */ @CheckReturnValue <T extends VarProperty> Stream<T> getProperties(Class<T> type); /** * Get a unique property of a particular type on this variable, if it exists * @param type the class of {@link VarProperty} to return * @param <T> the type of {@link VarProperty} to return */ @CheckReturnValue <T extends UniqueVarProperty> Optional<T> getProperty(Class<T> type); /** * Get whether this {@link VarPattern} has a {@link VarProperty} of the given type * @param type the type of the {@link VarProperty} * @param <T> the type of the {@link VarProperty} * @return whether this {@link VarPattern} has a {@link VarProperty} of the given type */ @CheckReturnValue <T extends VarProperty> boolean hasProperty(Class<T> type); /** * @return the name this variable represents, if it represents something with a specific name */ @CheckReturnValue Optional<Label> getTypeLabel(); /** * @return all variables that this variable references */ @CheckReturnValue Collection<VarPatternAdmin> innerVarPatterns(); /** * Get all inner variables, including implicit variables such as in a has property */ @CheckReturnValue Collection<VarPatternAdmin> implicitInnerVarPatterns(); /** * @return all type names that this variable refers to */ @CheckReturnValue Set<Label> getTypeLabels(); /** * @return the name of this variable, as it would be referenced in a native Graql query (e.g. '$x', 'movie') */ @CheckReturnValue String getPrintableName(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/VarProperty.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.admin; import javax.annotation.CheckReturnValue; import java.util.Set; import java.util.stream.Stream; /** * A property of a {@link VarPatternAdmin}, such as "isa movie" or "has name 'Jim'" * * @author Felix Chapman */ public interface VarProperty { /** * Build a Graql string representation of this property * @param builder a string builder to append to */ void buildString(StringBuilder builder); /** * Get the Graql string representation of this property */ @CheckReturnValue default String graqlString() { StringBuilder builder = new StringBuilder(); buildString(builder); return builder.toString(); } /** * Get a stream of {@link VarPatternAdmin} that must be types. */ @CheckReturnValue Stream<VarPatternAdmin> getTypes(); /** * Get a stream of any inner {@link VarPatternAdmin} within this `VarProperty`. */ @CheckReturnValue Stream<VarPatternAdmin> innerVarPatterns(); /** * Get a stream of any inner {@link VarPatternAdmin} within this `VarProperty`, including any that may have been * implicitly created (such as with "has"). */ @CheckReturnValue Stream<VarPatternAdmin> implicitInnerVarPatterns(); /** * True if there is at most one of these properties for each {@link VarPatternAdmin} */ @CheckReturnValue default boolean isUnique() { return false; } /** * maps this var property to a reasoner atom * @param var {@link VarPatternAdmin} this property belongs to * @param vars VarAdmins constituting the pattern this property belongs to * @param parent reasoner query this atom should belong to * @return created atom */ @CheckReturnValue Atomic mapToAtom(VarPatternAdmin var, Set<VarPatternAdmin> vars, ReasonerQuery parent); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/admin/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/>. */ /** * A collection of interfaces offering more behaviour on Graql objects. */ package ai.grakn.graql.admin;
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/answer/Answer.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.answer; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.graql.Query; import ai.grakn.graql.admin.Explanation; import com.google.common.collect.Sets; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import java.util.Set; /** * An object that contains the answer of every Graql {@link Query} * @param <T> the data structure in which the specific type of Answer is contained in. */ public interface Answer<T> { default AnswerGroup asAnswerGroup() { throw GraknTxOperationException.invalidCasting(this, AnswerGroup.class); } default ConceptList asConceptList() { throw GraknTxOperationException.invalidCasting(this, ConceptList.class); } default ConceptMap asConceptMap() { throw GraknTxOperationException.invalidCasting(this, ConceptMap.class); } default ConceptSet asConceptSet() { throw GraknTxOperationException.invalidCasting(this, ConceptSet.class); } default ConceptSetMeasure asConceptSetMeasure() { throw GraknTxOperationException.invalidCasting(this, ConceptSetMeasure.class); } default Value asValue() { throw GraknTxOperationException.invalidCasting(this, Value.class); } /** * @return an explanation object indicating how this answer was obtained */ @Nullable @CheckReturnValue default Explanation explanation() { return null; } /** * @return all explanations taking part in the derivation of this answer */ @CheckReturnValue default Set<Explanation> explanations() { if (this.explanation() == null) return null; Set<Explanation> explanations = Sets.newHashSet(this.explanation()); this.explanation().getAnswers().forEach(ans -> ans.explanations().forEach(explanations::add)); return explanations; } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/answer/AnswerGroup.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.answer; import ai.grakn.concept.Concept; import ai.grakn.graql.admin.Explanation; import javax.annotation.Nullable; import java.util.List; /** * A type of {@link Answer} object that contains a {@link List} of {@link Answer}s as the members and a {@link Concept} * as the owner. * @param <T> the type of {@link Answer} being grouped */ public class AnswerGroup<T extends Answer> implements Answer<AnswerGroup<T>> { private final Concept owner; private final List<T> answers; private final Explanation explanation; public AnswerGroup(Concept owner, List<T> answers) { this(owner, answers, null); } public AnswerGroup(Concept owner, List<T> answers, Explanation explanation) { this.owner = owner; this.answers = answers; this.explanation = explanation; } @Override public AnswerGroup<T> asAnswerGroup() { return this; } @Nullable @Override public Explanation explanation() { return explanation; } public Concept owner() { return this.owner; } public List<T> answers() { return this.answers; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) return false; AnswerGroup a2 = (AnswerGroup) obj; return this.owner.equals(a2.owner) && this.answers.equals(a2.answers); } @Override public int hashCode(){ int hash = owner.hashCode(); hash = 31 * hash + answers.hashCode(); return hash; } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/answer/ConceptList.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.answer; import ai.grakn.concept.ConceptId; import ai.grakn.graql.admin.Explanation; import com.google.common.collect.ImmutableList; import java.util.List; /** * A type of {@link Answer} object that contains a {@link List}. */ public class ConceptList implements Answer<ConceptList>{ // TODO: change to store List<Concept> once we are able to construct Concept without a database look up private final List<ConceptId> list; private final Explanation explanation; public ConceptList(List<ConceptId> list) { this(list, null); } public ConceptList(List<ConceptId> list, Explanation explanation) { this.list = ImmutableList.copyOf(list); this.explanation = explanation; } @Override public ConceptList asConceptList() { return this; } @Override public Explanation explanation() { return explanation; } public List<ConceptId> list() { return list; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) return false; ConceptList a2 = (ConceptList) obj; return this.list.equals(a2.list); } @Override public int hashCode(){ return list.hashCode(); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/answer/ConceptMap.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.answer; import ai.grakn.concept.Concept; import ai.grakn.concept.Role; import ai.grakn.graql.Var; import ai.grakn.graql.admin.Atomic; import ai.grakn.graql.admin.Explanation; import ai.grakn.graql.admin.MultiUnifier; import ai.grakn.graql.admin.ReasonerQuery; import ai.grakn.graql.admin.Unifier; import javax.annotation.CheckReturnValue; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; /** * A type of Answer object that contains a {@link Map} of {@link Var} to {@link Concept}. */ public interface ConceptMap extends Answer<ConceptMap> { @CheckReturnValue Map<Var, Concept> map(); @CheckReturnValue Set<Var> vars(); @CheckReturnValue Collection<Concept> concepts(); /** * Return the {@link Concept} bound to the given variable name. * * @throws ai.grakn.exception.GraqlQueryException if the {@link Var} is not in this {@link ConceptMap} */ @CheckReturnValue Concept get(String var); /** * Return the {@link Concept} bound to the given {@link Var}. * * @throws ai.grakn.exception.GraqlQueryException if the {@link Var} is not in this {@link ConceptMap} */ @CheckReturnValue Concept get(Var var); @CheckReturnValue boolean containsVar(Var var); @CheckReturnValue boolean containsAll(ConceptMap ans); @CheckReturnValue boolean isEmpty(); @CheckReturnValue int size(); void forEach(BiConsumer<Var, Concept> consumer); /** * perform an answer merge without explanation * NB:assumes answers are compatible (concept corresponding to join vars if any are the same) * * @param a2 answer to be merged with * @return merged answer */ @CheckReturnValue ConceptMap merge(ConceptMap a2); /** * perform an answer merge with optional explanation * NB:assumes answers are compatible (concept corresponding to join vars if any are the same) * * @param a2 answer to be merged with * @param explanation flag for providing explanation * @return merged answer */ @CheckReturnValue ConceptMap merge(ConceptMap a2, boolean explanation); /** * explain this answer by providing explanation with preserving the structure of dependent answers * * @param exp explanation for this answer * @return explained answer */ ConceptMap explain(Explanation exp); /** * @param vars variables defining the projection * @return project the answer retaining the requested variables */ @CheckReturnValue ConceptMap project(Set<Var> vars); /** * @param unifier set of mappings between variables * @return unified answer */ @CheckReturnValue ConceptMap unify(Unifier unifier); /** * @param multiUnifier set of unifiers defining variable mappings * @return stream of unified answers */ @CheckReturnValue Stream<ConceptMap> unify(MultiUnifier multiUnifier); /** * @param toExpand set of variables for which {@link Role} hierarchy should be expanded * @return stream of answers with expanded role hierarchy */ @CheckReturnValue Stream<ConceptMap> expandHierarchies(Set<Var> toExpand); /** * @param parent query context * @return (partial) set of predicates corresponding to this answer */ @CheckReturnValue Set<Atomic> toPredicates(ReasonerQuery parent); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/answer/ConceptSet.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.answer; import ai.grakn.concept.ConceptId; import ai.grakn.graql.admin.Explanation; import com.google.common.collect.ImmutableSet; import java.util.Set; /** * A type of {@link Answer} object that contains a {@link Set}. */ public class ConceptSet implements Answer<ConceptSet>{ // TODO: change to store Set<Concept> once we are able to construct Concept without a database look up private final Set<ConceptId> set; private final Explanation explanation; public ConceptSet(Set<ConceptId> set) { this(set, null); } public ConceptSet(Set<ConceptId> set, Explanation explanation) { this.set = ImmutableSet.copyOf(set); this.explanation = explanation; } @Override public ConceptSet asConceptSet() { return this; } @Override public Explanation explanation() { return explanation; } public Set<ConceptId> set() { return set; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) return false; ConceptSet a2 = (ConceptSet) obj; return this.set.equals(a2.set); } @Override public int hashCode(){ return set.hashCode(); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/answer/ConceptSetMeasure.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.answer; import ai.grakn.concept.ConceptId; import ai.grakn.graql.admin.Explanation; import java.util.Set; /** * A type of {@link Answer} object that contains a {@link Set} and {@link Number}, by extending {@link ConceptSet}. */ public class ConceptSetMeasure extends ConceptSet{ private final Number measurement; public ConceptSetMeasure(Set<ConceptId> set, Number measurement) { this(set, measurement, null); } public ConceptSetMeasure(Set<ConceptId> set, Number measurement, Explanation explanation) { super(set, explanation); this.measurement = measurement; } @Override public ConceptSetMeasure asConceptSetMeasure() { return this; } public Number measurement() { return measurement; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) return false; ConceptSetMeasure a2 = (ConceptSetMeasure) obj; return this.set().equals(a2.set()) && measurement.toString().equals(a2.measurement.toString()); } @Override public int hashCode(){ int hash = super.hashCode(); hash = 31 * hash + measurement.hashCode(); return hash; } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/answer/Value.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.answer; import ai.grakn.graql.admin.Explanation; /** * A type of {@link Answer} object that contains a {@link Number}. */ public class Value implements Answer<Value>{ private final Number number; private final Explanation explanation; public Value(Number number) { this(number, null); } public Value(Number number, Explanation explanation) { this.number = number; this.explanation = explanation; } @Override public Value asValue() { return this; } @Override public Explanation explanation() { return explanation; } public Number number() { return number; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || getClass() != obj.getClass()) return false; Value a2 = (Value) obj; return this.number.toString().equals(a2.number.toString()); } @Override public int hashCode(){ return number.hashCode(); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/macro/Macro.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.macro; import javax.annotation.CheckReturnValue; import java.util.List; /** * A macro function to perform on a template. * * @param <T> the type of result after applying this macro * * @author Alexandra Orth */ public interface Macro<T> { /** * Apply the macro to the given values * @param values Values on which to operate the macro * @return result of the function */ @CheckReturnValue T apply(List<Object> values); @CheckReturnValue String name(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/graql/macro/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/>. */ /** * A collection of macros for Graql template parsing. */ package ai.grakn.graql.macro;
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/kb
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/kb/admin/GraknAdmin.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.admin; import ai.grakn.GraknTx; import ai.grakn.QueryExecutor; import ai.grakn.concept.AttributeType; import ai.grakn.concept.EntityType; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import ai.grakn.util.Schema; import javax.annotation.CheckReturnValue; import java.util.stream.Stream; /** * Admin interface for {@link GraknTx}. * * @author Filipe Teixeira */ public interface GraknAdmin extends GraknTx{ //------------------------------------- Meta Types ---------------------------------- /** * Get the root of all Types. * * @return The meta type -> type. */ @CheckReturnValue default Type getMetaConcept(){ return getSchemaConcept(Schema.MetaSchema.THING.getLabel()); } /** * Get the root of all {@link RelationshipType}. * * @return The meta relation type -> relation-type. */ @CheckReturnValue default RelationshipType getMetaRelationType(){ return getSchemaConcept(Schema.MetaSchema.RELATIONSHIP.getLabel()); } /** * Get the root of all the {@link Role}. * * @return The meta role type -> role-type. */ @CheckReturnValue default Role getMetaRole(){ return getSchemaConcept(Schema.MetaSchema.ROLE.getLabel()); } /** * Get the root of all the {@link AttributeType}. * * @return The meta resource type -> resource-type. */ @CheckReturnValue default AttributeType getMetaAttributeType(){ return getSchemaConcept(Schema.MetaSchema.ATTRIBUTE.getLabel()); } /** * Get the root of all the Entity Types. * * @return The meta entity type -> entity-type. */ @CheckReturnValue default EntityType getMetaEntityType(){ return getSchemaConcept(Schema.MetaSchema.ENTITY.getLabel()); } /** * Get the root of all {@link Rule}s; * * @return The meta {@link Rule} */ @CheckReturnValue default Rule getMetaRule(){ return getSchemaConcept(Schema.MetaSchema.RULE.getLabel()); } //------------------------------------- Admin Specific Operations ---------------------------------- /** * Get all super-concepts of the given {@link SchemaConcept} including itself and including the meta-type * {@link ai.grakn.util.Schema.MetaSchema#THING}. * * <p> * If you want a more precise type that will exclude {@link ai.grakn.util.Schema.MetaSchema#THING}, use * {@link SchemaConcept#sups()}. * </p> */ @CheckReturnValue Stream<SchemaConcept> sups(SchemaConcept schemaConcept); QueryExecutor queryExecutor(); }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/kb
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/kb/log/AutoValue_CommitLog.java
package ai.grakn.kb.log; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import java.util.Set; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_CommitLog extends CommitLog { private final Keyspace keyspace; private final Map<ConceptId, Long> instanceCount; private final Map<String, Set<ConceptId>> attributes; AutoValue_CommitLog( Keyspace keyspace, Map<ConceptId, Long> instanceCount, Map<String, Set<ConceptId>> attributes) { if (keyspace == null) { throw new NullPointerException("Null keyspace"); } this.keyspace = keyspace; if (instanceCount == null) { throw new NullPointerException("Null instanceCount"); } this.instanceCount = instanceCount; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; } @JsonProperty @Override public Keyspace keyspace() { return keyspace; } @JsonProperty(value = "instance-count") @Override public Map<ConceptId, Long> instanceCount() { return instanceCount; } @JsonProperty(value = "new-attributes") @Override public Map<String, Set<ConceptId>> attributes() { return attributes; } @Override public String toString() { return "CommitLog{" + "keyspace=" + keyspace + ", " + "instanceCount=" + instanceCount + ", " + "attributes=" + attributes + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof CommitLog) { CommitLog that = (CommitLog) o; return (this.keyspace.equals(that.keyspace())) && (this.instanceCount.equals(that.instanceCount())) && (this.attributes.equals(that.attributes())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.keyspace.hashCode(); h *= 1000003; h ^= this.instanceCount.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/kb
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/kb/log/CommitLog.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.log; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * <p> * Stores the commit log of a {@link ai.grakn.GraknTx}. * </p> * * <p> * Stores the commit log of a {@link ai.grakn.GraknTx} which is uploaded to the server when the {@link ai.grakn.GraknSession} is closed. * The commit log is also uploaded periodically to make sure that if a failure occurs the counts are still roughly maintained. * </p> * * @author Filipe Peliz Pinto Teixeira */ @AutoValue public abstract class CommitLog { @JsonProperty public abstract Keyspace keyspace(); @JsonProperty("instance-count") public abstract Map<ConceptId, Long> instanceCount(); @JsonProperty("new-attributes") public abstract Map<String, Set<ConceptId>> attributes(); @JsonCreator public static CommitLog create( @JsonProperty("keyspace") Keyspace keyspace, @JsonProperty("instance-count") Map<ConceptId, Long> instanceCount, @JsonProperty("new-attributes") Map<String, Set<ConceptId>> newAttributes ){ return new AutoValue_CommitLog(keyspace, instanceCount, newAttributes); } /** * Creates a {@link CommitLog} which is safe to be mutated by multiple transactions * @return a thread safe {@link CommitLog} */ public static CommitLog createThreadSafe(Keyspace keyspace){ return create(keyspace, new ConcurrentHashMap<>(), new ConcurrentHashMap<>()); } /** * Creates a {@link CommitLog} which should only be used by a single transaction. * @return a simple {@link CommitLog} */ public static CommitLog createDefault(Keyspace keyspace){ return create(keyspace, new HashMap<>(), new HashMap<>()); } public void clear(){ instanceCount().clear(); attributes().clear(); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/CommonUtil.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import ai.grakn.GraknSystemProperty; import com.google.common.base.StandardSystemProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Common utility methods used within Grakn. * * Some of these methods are Grakn-specific, others add important "missing" methods to Java/Guava classes. * * @author Grakn Warriors */ public class CommonUtil { private CommonUtil() {} /** * @return The project path. If it is not specified as a JVM parameter it will be set equal to * user.dir folder. */ public static Path getProjectPath() { if (GraknSystemProperty.CURRENT_DIRECTORY.value() == null) { GraknSystemProperty.CURRENT_DIRECTORY.set(StandardSystemProperty.USER_DIR.value()); } return Paths.get(GraknSystemProperty.CURRENT_DIRECTORY.value()); } /** * @param optional the optional to change into a stream * @param <T> the type in the optional * @return a stream of one item if the optional has an element, else an empty stream */ public static <T> Stream<T> optionalToStream(Optional<T> optional) { return optional.map(Stream::of).orElseGet(Stream::empty); } public static <T> Stream<T> stream(Iterator<T> iterator) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); } /** * Helper which lazily checks if a {@link Stream} contains the number specified * WARNING: This consumes the stream rendering it unusable afterwards * * @param stream the {@link Stream} to check the count against * @param size the expected number of elements in the stream * @return true if the expected size is found */ public static boolean containsOnly(Stream stream, long size){ long count = 0L; Iterator it = stream.iterator(); while(it.hasNext()){ it.next(); if(++count > size) return false; } return size == count; } @CheckReturnValue public static RuntimeException unreachableStatement(Throwable cause) { return unreachableStatement(null, cause); } @CheckReturnValue public static RuntimeException unreachableStatement(String message) { return unreachableStatement(message, null); } @CheckReturnValue public static RuntimeException unreachableStatement(@Nullable String message, Throwable cause) { return new RuntimeException("Statement expected to be unreachable: " + message, cause); } public static <T> Collector<T, ?, ImmutableSet<T>> toImmutableSet() { return new Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>>() { @Override public Supplier<ImmutableSet.Builder<T>> supplier() { return ImmutableSet::builder; } @Override public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() { return ImmutableSet.Builder::add; } @Override public BinaryOperator<ImmutableSet.Builder<T>> combiner() { return (b1, b2) -> b1.addAll(b2.build()); } @Override public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() { return ImmutableSet.Builder::build; } @Override public Set<Characteristics> characteristics() { return ImmutableSet.of(); } }; } public static <T> Collector<T, ?, ImmutableList<T>> toImmutableList() { return new Collector<T, ImmutableList.Builder<T>, ImmutableList<T>>() { @Override public Supplier<ImmutableList.Builder<T>> supplier() { return ImmutableList::builder; } @Override public BiConsumer<ImmutableList.Builder<T>, T> accumulator() { return ImmutableList.Builder::add; } @Override public BinaryOperator<ImmutableList.Builder<T>> combiner() { return (b1, b2) -> b1.addAll(b2.build()); } @Override public Function<ImmutableList.Builder<T>, ImmutableList<T>> finisher() { return ImmutableList.Builder::build; } @Override public Set<Characteristics> characteristics() { return ImmutableSet.of(); } }; } public static <T> Collector<T, ?, ImmutableMultiset<T>> toImmutableMultiset() { return new Collector<T, ImmutableMultiset.Builder<T>, ImmutableMultiset<T>>() { @Override public Supplier<ImmutableMultiset.Builder<T>> supplier() { return ImmutableMultiset::builder; } @Override public BiConsumer<ImmutableMultiset.Builder<T>, T> accumulator() { return ImmutableMultiset.Builder::add; } @Override public BinaryOperator<ImmutableMultiset.Builder<T>> combiner() { return (b1, b2) -> b1.addAll(b2.build()); } @Override public Function<ImmutableMultiset.Builder<T>, ImmutableMultiset<T>> finisher() { return ImmutableMultiset.Builder::build; } @Override public Set<Characteristics> characteristics() { return ImmutableSet.of(); } }; } public static StringBuilder simplifyExceptionMessage(Throwable e) { StringBuilder message = new StringBuilder(e.getMessage()); while(e.getCause() != null) { e = e.getCause(); message.append("\n").append(e.getMessage()); } return message; } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/ConcurrencyUtil.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import rx.Observable; import rx.schedulers.Schedulers; import java.util.Collection; import java.util.List; /** * <p> * Concurrency convenience methogs * </p> * * @author Domenico Corapi */ public class ConcurrencyUtil { static public <T> Observable<List<T>> allObservable(Collection<Observable<T>> tasks) { return Observable.from(tasks) //execute in parallel .flatMap(task -> task.observeOn(Schedulers.computation())) //wait, until all task are executed //be aware, all your observable should emit onComplemete event //otherwise you will wait forever .toList(); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/ErrorMessage.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import javax.annotation.CheckReturnValue; /** * Enum containing error messages. * * Each error message contains a single format string, with a method {@link ErrorMessage#getMessage(Object...)} that * accepts arguments to be passed to the format string. * * @author Filipe Teixeira */ public enum ErrorMessage { //--------------------------------------------- Bootup Errors ----------------------------------------------- GRAKN_PIDFILE_SYSTEM_PROPERTY_UNDEFINED("Unable to find the Java system property 'grakn.pidfile'. Don't forget to specify -Dgrakn.pidfile=/path/to/grakn.pid"), UNSUPPORTED_JAVA_VERSION("Unsupported Java version [%s] found. Grakn needs Java 1.8 in order to run."), UNABLE_TO_START_GRAKN("An error has occurred during boot-up. Please run 'grakn server status' or check the logs located under the 'logs' directory."), UNABLE_TO_START_ENGINE_JAR_NOT_FOUND("Unable to start Engine, No JAR files found! Please re-download the Grakn distribution."), UNABLE_TO_GET_GRAKN_HOME_FOLDER("Unable to find Grakn home folder"), UNABLE_TO_GET_GRAKN_CONFIG_FOLDER("Unable to find Grakn config folder"), UNCAUGHT_EXCEPTION("Uncaught exception at thread [%s]"), PID_ALREADY_EXISTS("Pid file already exists: '[%s]'. Overwriting..."), COULD_NOT_GET_PID("Couldn't get the PID of Grakn Engine. Received '%s'"), //--------------------------------------------- Core Errors ----------------------------------------------- CANNOT_DELETE("Type [%s] cannot be deleted as it still has incoming edges"), SUPER_LOOP_DETECTED("By setting the super of concept [%s] to [%s]. You will be creating a loop. This is prohibited"), INVALID_UNIQUE_PROPERTY_MUTATION("Property [%s] of Concept [%s] cannot be changed to [%s] as it is already taken by Concept [%s]"), UNIQUE_PROPERTY_TAKEN("Property [%s] with value [%s] is already taken by concept [%s]"), INVALID_DATATYPE("The value [%s] must be of datatype [%s]"), INVALID_OBJECT_TYPE("The concept [%s] is not of type [%s]"), REGEX_INSTANCE_FAILURE("The regex [%s] of Attribute Type [%s] cannot be applied because value [%s] " + "does not conform to the regular expression"), REGEX_NOT_STRING("The Attribute Type [%s] is not of type String so it cannot support regular expressions"), CLOSED_CLEAR("The session for graph has been closed due to deleting the graph"), TRANSACTIONS_NOT_SUPPORTED("The graph backend [%s] does not actually support transactions. The transaction was not %s. The graph was actually effected directly"), IMMUTABLE_VALUE("The value [%s] cannot be changed to [%s] due to the property [%s] being immutable"), META_TYPE_IMMUTABLE("The meta type [%s] is immutable"), SCHEMA_LOCKED("Schema cannot be modified when using a batch loading graph"), HAS_INVALID("The type [%s] is not allowed to have an attribute of type [%s]"), BACKEND_EXCEPTION("Backend Exception."), INITIALIZATION_EXCEPTION("Graph for keyspace [%s] not properly initialized. Missing keyspace name resource"), TX_CLOSED("The Transaction for keyspace [%s] is closed"), SESSION_CLOSED("The session for graph [%s] was closed"), TX_CLOSED_ON_ACTION("The transaction was %s and closed [%s]. Use the session to get a new transaction for the graph."), TXS_OPEN("Closed session on graph [%s] with [%s] open transactions"), LOCKING_EXCEPTION("Internal locking exception. Please clear the transaction and try again."), CANNOT_BE_KEY_AND_ATTRIBUTE("The Type [%s] cannot have the Attribute Type [%s] as a key and as an attribute"), TRANSACTION_ALREADY_OPEN("A transaction is already open on this thread for graph [%s]"), TRANSACTION_READ_ONLY("This transaction on graph [%s] is read only"), IS_ABSTRACT("The Type [%s] is abstract and cannot have any instances \n"), CLOSE_FAILURE("Unable to close graph [%s]"), VERSION_MISMATCH("You are attempting to use Grakn Version [%s] with a graph build using version [%s], this is not supported."), NO_TYPE("Concept [%s] does not have a type"), INVALID_DIRECTION("Cannot traverse an edge in direction [%s]"), RESERVED_WORD("The word [%s] is reserved internally and cannot be used"), INVALID_PROPERTY_USE("The concept [%s] cannot contain vertex property [%s]"), UNKNOWN_CONCEPT("Uknown concept type [%s]"), INVALID_IMPLICIT_TYPE("Label [%s] is not an implicit label"), LABEL_TAKEN("The label [%s] has already been used"), BACKGROUND_TASK_UNHANDLED_EXCEPTION("An exception has occurred during the execution of a background task [%s]. Skipping..."), //--------------------------------------------- Validation Errors VALIDATION("A structural validation error has occurred. Please correct the [`%s`] errors found. \n"), VALIDATION_RELATION_CASTING_LOOP_FAIL("The relation [%s] has a role player playing the role [%s] " + "which it's type [%s] is not connecting to via a relates connection \n"), VALIDATION_RELATIONSHIP_WITH_NO_ROLE_PLAYERS("Cannot commit relationship [%s] of type [%s] because it does not have any role players. \n"), VALIDATION_CASTING("The type [%s] of role player [%s] is not allowed to play Role [%s] \n"), VALIDATION_ROLE_TYPE_MISSING_RELATION_TYPE("Role [%s] does not have a relates connection to any Relationship Type. \n"), VALIDATION_RELATION_TYPE("Relationship Type [%s] does not have one or more roles \n"), VALIDATION_NOT_EXACTLY_ONE_KEY("Thing [%s] does not have exactly one key of type [%s] \n"), VALIDATION_RELATION_TYPES_ROLES_SCHEMA("The Role [%s] which is connected to Relationship Type [%s] " + "does not have a %s Role Type which is connected to the %s Relationship Type [%s] \n"), VALIDATION_REQUIRED_RELATION("The role player [%s] of type [%s] can only play the role of [%s] once but is currently doing so [%s] times \n"), //--------------------------------------------- Rule validation Errors VALIDATION_RULE_MISSING_ELEMENTS("The [%s] of rule [%s] refers to type [%s] which does not exist in the graph \n"), VALIDATION_RULE_DISJUNCTION_IN_BODY("The rule [%s] does not form a valid Horn clause, as it contains a disjunction in the body\n"), VALIDATION_RULE_DISJUNCTION_IN_HEAD("The rule [%s] does not form a valid Horn clause, as it contains a disjunction in the head\n"), VALIDATION_RULE_HEAD_NON_ATOMIC("The rule [%s] does not form a valid Horn clause, as it contains a multi-atom head\n"), VALIDATION_RULE_ILLEGAL_ATOMIC_IN_HEAD("Atomic [%s] is not allowed to form a rule head of rule [%s]\n"), VALIDATION_RULE_ILLEGAL_HEAD_ATOM_WITH_UNBOUND_VARIABLE("Atom [%s] is not allowed to form a rule head of rule [%s] as it contains an unbound variable\n"), VALIDATION_RULE_ILLEGAL_HEAD_ATOM_WITH_AMBIGUOUS_SCHEMA_CONCEPT("Atom [%s] is not allowed to form a rule head of rule [%s] as it has an ambiguous schema concept\n"), VALIDATION_RULE_ILLEGAL_HEAD_ATOM_WITH_IMPLICIT_SCHEMA_CONCEPT("Atom [%s] is not allowed to form a rule head of rule [%s] as it has an implicit schema concept\n"), VALIDATION_RULE_ILLEGAL_HEAD_RELATION_WITH_IMPLICIT_ROLE("Relationship [%s] is not allowed to form a rule head of rule [%s] as it has an implicit role\n"), VALIDATION_RULE_ILLEGAL_HEAD_RELATION_WITH_AMBIGUOUS_ROLE("Relationship [%s] is not allowed to form a rule head of rule [%s] as it has an ambiguous (unspecified, variable or meta) role\n"), VALIDATION_RULE_ILLEGAL_HEAD_RESOURCE_WITH_AMBIGUOUS_PREDICATES("Attribute [%s] is not allowed to form a rule head of rule [%s] as it has ambiguous value predicates\n"), VALIDATION_RULE_ILLEGAL_HEAD_RESOURCE_WITH_NONSPECIFIC_PREDICATE("Attribute [%s] is not allowed to form a rule head of rule [%s] as it has a non-specific value predicate\n"), VALIDATION_RULE_INVALID_RELATION_TYPE("Attempting to define a rule containing a relation pattern with type [%s] which is not a relation type\n"), VALIDATION_RULE_INVALID_ATTRIBUTE_TYPE("Attempting to define a rule containing an attribute pattern with type [%s] which is not an attribute type\n"), VALIDATION_RULE_ATTRIBUTE_OWNER_CANNOT_HAVE_ATTRIBUTE("Attempting to define a rule containing an attribute pattern of type [%s] with type [%s] that cannot have this attribute\n"), VALIDATION_RULE_ROLE_CANNOT_BE_PLAYED("Attempting to define a rule containing a relation pattern with role [%s] which cannot be played in relation [%s]\n"), VALIDATION_RULE_TYPE_CANNOT_PLAY_ROLE("Attempting to define a rule containing a relation pattern with type [%s] that cannot play role [%s] in relation [%s]\n"), //--------------------------------------------- Factory Errors INVALID_PATH_TO_CONFIG("Unable to open config file [%s]"), CANNOT_PRODUCE_TX("Cannot produce a Grakn Transaction using the backend [%s]"), CANNOT_FIND_CLASS("The %s implementation %s must be accessible in the classpath"), //--------------------------------------------- Client Errors INVALID_ENGINE_RESPONSE("Grakn Engine located at [%s] returned response [%s], cannot proceed."), INVALID_FACTORY("Graph Factory [%s] is not valid"), MISSING_FACTORY_DEFINITION("Graph Factor Config ['knowledge-base.mode'] missing from provided config. " + "Cannot produce graph"), COULD_NOT_REACH_ENGINE("Could not reach Grakn engine at [%s]"), //--------------------------------------------- Migration Errors ----------------------------------------------- OWL_NOT_SUPPORTED("Owl migration is not supported anymore"), //--------------------------------------------- Graql Errors ----------------------------------------------- NO_TX("no graph provided"), SYNTAX_ERROR_NO_POINTER("syntax error at line %s:\n%s"), SYNTAX_ERROR("syntax error at line %s: \n%s\n%s\n%s"), MUST_BE_ATTRIBUTE_TYPE("type '%s' must be an attribute-type"), ID_NOT_FOUND("id '%s' not found"), LABEL_NOT_FOUND("label '%s' not found"), NOT_A_ROLE_TYPE("'%s' is not a role type. perhaps you meant 'isa %s'?"), NOT_A_RELATION_TYPE("'%s' is not a relation type. perhaps you forgot to separate your statements with a ';'?"), CONFLICTING_PROPERTIES("the following unique properties in '%s' conflict: '%s' and '%s'"), NON_POSITIVE_LIMIT("limit %s should be positive"), NEGATIVE_OFFSET("offset %s should be non-negative"), INVALID_VALUE("unsupported attribute value type %s"), AGGREGATE_ARGUMENT_NUM("aggregate '%s' takes %s arguments, but got %s"), UNKNOWN_AGGREGATE("unknown aggregate '%s'"), VARIABLE_NOT_IN_QUERY("the variable %s is not in the query"), NO_PATTERNS("no patterns have been provided. at least one pattern must be provided"), MATCH_INVALID("cannot match on property of type [%s]"), MULTIPLE_TX("a graph has been specified twice for this query"), INSERT_UNDEFINED_VARIABLE("%s doesn't have an 'isa', a 'sub' or an 'id'"), INSERT_PREDICATE("cannot insert a concept with a predicate"), INSERT_RELATION_WITHOUT_ISA("cannot insert a relation without an isa edge"), INSERT_METATYPE("'%s' cannot be a subtype of '%s'"), INSERT_RECURSIVE("%s should not refer to itself"), INSERT_ABSTRACT_NOT_TYPE("the concept [%s] is not a type and cannot be set to abstract"), INSERT_RELATION_WITHOUT_ROLE_TYPE("attempted to insert a relation without all role types specified"), INVALID_STATEMENT("Value [%s] not of type [%s] in data [%s]"), //Templating TEMPLATE_MISSING_KEY("Key [%s] not present in data: [%s]"), UNEXPECTED_RESULT("the concept [%s] could not be found in results"), ENGINE_STARTUP_ERROR("Could not start Grakn engine: [%s]"), UNAVAILABLE_PROPERTY("Property requested [%s] has not been defined. See configuration file [%s] for configured properties."), MISSING_MANDATORY_REQUEST_PARAMETERS("Missing mandatory query parameter [%s]"), MISSING_MANDATORY_BODY_REQUEST_PARAMETERS("Missing mandatory parameter in body [%s]"), MISSING_REQUEST_BODY("Empty body- it should contain the Graql query to be executed."), UNSUPPORTED_CONTENT_TYPE("Unsupported Content-Type [%s] requested"), CANNOT_DELETE_KEYSPACE("Could not delete keyspace [%s]"), //--------------------------------------------- Reasoner Errors ----------------------------------------------- NON_ATOMIC_QUERY("Addressed query is not atomic: [%s]."), NON_GROUND_NEQ_PREDICATE("Addressed query [%s] leads to a non-ground neq predicate when planning resolution."), INCOMPLETE_RESOLUTION_PLAN("Addressed query [%s] leads to an incomplete resolution plan."), ROLE_PATTERN_ABSENT("Addressed relation [%s] is missing a role pattern."), ROLE_ID_IS_NOT_ROLE("Assignment of non-role id to a role variable in pattern [%s]."), NO_ATOMS_SELECTED("No atoms were selected from query [%s]."), INVALID_CACHE_ENTRY("Query cache entry for query [%s] contains invalid entry."), UNIFICATION_ATOM_INCOMPATIBILITY("Attempted unification on incompatible atoms."), NON_EXISTENT_UNIFIER("Could not proceed with unification as the unifier doesn't exist."), ILLEGAL_ATOM_CONVERSION("Attempted illegal atom conversion of atom [%s] to type [%s]."), CONCEPT_NOT_THING("Attempted concept conversion from concept [%s] that is not a thing."), //--------------------------------------------- Analytics Errors ----------------------------------------------- INVALID_COMPUTE_METHOD("Invalid compute method. " + "The available compute methods are: [%s]."), INVALID_COMPUTE_CONDITION("Invalid condition(s) for 'compute [%s]'. The accepted condition(s) are: [%s]."), MISSING_COMPUTE_CONDITION("Missing condition(s) for 'compute [%s]'. The required condition(s) are: [%s]."), INVALID_COMPUTE_METHOD_ALGORITHM("Invalid algorithm for 'compute [%s]'. The accepted algorithm(s) are: [%s]."), INVALID_COMPUTE_ARGUMENT("Invalid argument(s) 'compute [%s] using [%s]'. The accepted argument(s) are: [%s]."), ATTRIBUTE_TYPE_NOT_SPECIFIED("No attribute type provided for compute query."), K_SMALLER_THAN_TWO("k can't be smaller than 2."), INSTANCE_DOES_NOT_EXIST("Instance does not exist in the subgraph."), MAX_ITERATION_REACHED("Max iteration of [%s] reached."), //--------------------------------------------- Shell Errors --------------------------------------------------- COULD_NOT_CONNECT("Could not connect to Grakn. Have you run 'grakn server start'?"), NO_VARIABLE_IN_QUERY("There was no variable specified in the query. Perhaps you forgot to escape `\\` a `$`?"); private final String message; ErrorMessage(String message) { this.message = message; } @CheckReturnValue public String getMessage(Object... args) { return String.format(message, args); } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/GraknVersion.java
package ai.grakn.util; /** * Class for storing the maven version. The templating-maven-plugin in grakn-core will automatically insert the * project version here. */ public class GraknVersion { public static final String VERSION = "1.4.3"; }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/GraqlSyntax.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import ai.grakn.concept.ConceptId; import ai.grakn.graql.answer.Answer; import ai.grakn.graql.answer.ConceptList; import ai.grakn.graql.answer.ConceptSet; import ai.grakn.graql.answer.ConceptSetMeasure; import ai.grakn.graql.answer.Value; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm.CONNECTED_COMPONENT; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm.DEGREE; import static ai.grakn.util.GraqlSyntax.Compute.Algorithm.K_CORE; import static ai.grakn.util.GraqlSyntax.Compute.Condition.FROM; import static ai.grakn.util.GraqlSyntax.Compute.Condition.IN; import static ai.grakn.util.GraqlSyntax.Compute.Condition.OF; import static ai.grakn.util.GraqlSyntax.Compute.Condition.TO; import static ai.grakn.util.GraqlSyntax.Compute.Condition.USING; import static ai.grakn.util.GraqlSyntax.Compute.Condition.WHERE; import static ai.grakn.util.GraqlSyntax.Compute.Method.CENTRALITY; import static ai.grakn.util.GraqlSyntax.Compute.Method.CLUSTER; import static ai.grakn.util.GraqlSyntax.Compute.Method.COUNT; import static ai.grakn.util.GraqlSyntax.Compute.Method.MAX; import static ai.grakn.util.GraqlSyntax.Compute.Method.MEAN; import static ai.grakn.util.GraqlSyntax.Compute.Method.MEDIAN; import static ai.grakn.util.GraqlSyntax.Compute.Method.MIN; import static ai.grakn.util.GraqlSyntax.Compute.Method.PATH; import static ai.grakn.util.GraqlSyntax.Compute.Method.STD; import static ai.grakn.util.GraqlSyntax.Compute.Method.SUM; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.CONTAINS; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.K; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.MIN_K; import static ai.grakn.util.GraqlSyntax.Compute.Parameter.SIZE; /** * Graql syntax keywords * TODO: the content of this class (the enums) should be moved to inside Graql class, once we move it to this package. * * @author Grakn Warriors */ public class GraqlSyntax { /** * Graql commands to determine the type of query */ public enum Command { MATCH("match"), COMPUTE("compute"); private final String command; Command(String command) { this.command = command; } @Override public String toString() { return this.command; } public static Command of(String value) { for (Command c : Command.values()) { if (c.command.equals(value)) { return c; } } return null; } } /** * Characters available for use in the Graql syntax */ public enum Char { EQUAL("="), SEMICOLON(";"), SPACE(" "), COMMA(","), COMMA_SPACE(", "), SQUARE_OPEN("["), SQUARE_CLOSE("]"), QUOTE("\""); private final String character; Char(String character) { this.character = character; } @Override public String toString() { return this.character; } } /** * Graql Compute keywords to determine the compute method and conditions */ public static class Compute { public final static Collection<Method> METHODS_ACCEPTED = ImmutableList.copyOf(Method.values()); public final static Map<Method, Collection<Condition>> CONDITIONS_REQUIRED = conditionsRequired(); public final static Map<Method, Collection<Condition>> CONDITIONS_OPTIONAL = conditionsOptional(); public final static Map<Method, Collection<Condition>> CONDITIONS_ACCEPTED = conditionsAccepted(); public final static Map<Method, Algorithm> ALGORITHMS_DEFAULT = algorithmsDefault(); public final static Map<Method, Collection<Algorithm>> ALGORITHMS_ACCEPTED = algorithmsAccepted(); public final static Map<Method, Map<Algorithm, Collection<Parameter>>> ARGUMENTS_ACCEPTED = argumentsAccepted(); public final static Map<Method, Map<Algorithm, Map<Parameter, Object>>> ARGUMENTS_DEFAULT = argumentsDefault(); public final static Map<Method, Boolean> INCLUDE_ATTRIBUTES_DEFAULT = includeAttributesDefault(); private static Map<Method, Collection<Condition>> conditionsRequired() { Map<Method, Collection<Condition>> required = new HashMap<>(); required.put(MIN, ImmutableSet.of(OF)); required.put(MAX, ImmutableSet.of(OF)); required.put(MEDIAN, ImmutableSet.of(OF)); required.put(MEAN, ImmutableSet.of(OF)); required.put(STD, ImmutableSet.of(OF)); required.put(SUM, ImmutableSet.of(OF)); required.put(PATH, ImmutableSet.of(FROM, TO)); required.put(CENTRALITY, ImmutableSet.of(USING)); ; required.put(CLUSTER, ImmutableSet.of(USING)); return ImmutableMap.copyOf(required); } private static Map<Method, Collection<Condition>> conditionsOptional() { Map<Method, Collection<Condition>> optional = new HashMap<>(); optional.put(COUNT, ImmutableSet.of(IN)); optional.put(MIN, ImmutableSet.of(IN)); optional.put(MAX, ImmutableSet.of(IN)); optional.put(MEDIAN, ImmutableSet.of(IN)); optional.put(MEAN, ImmutableSet.of(IN)); optional.put(STD, ImmutableSet.of(IN)); optional.put(SUM, ImmutableSet.of(IN)); optional.put(PATH, ImmutableSet.of(IN)); optional.put(CENTRALITY, ImmutableSet.of(OF, IN, WHERE)); optional.put(CLUSTER, ImmutableSet.of(IN, WHERE)); return ImmutableMap.copyOf(optional); } private static Map<Method, Collection<Condition>> conditionsAccepted() { Map<Method, Collection<Condition>> accepted = new HashMap<>(); for (Map.Entry<Method, Collection<Condition>> entry : CONDITIONS_REQUIRED.entrySet()) { accepted.put(entry.getKey(), new HashSet<>(entry.getValue())); } for (Map.Entry<Method, Collection<Condition>> entry : CONDITIONS_OPTIONAL.entrySet()) { if (accepted.containsKey(entry.getKey())) accepted.get(entry.getKey()).addAll(entry.getValue()); else accepted.put(entry.getKey(), entry.getValue()); } return ImmutableMap.copyOf(accepted); } private static Map<Method, Collection<Algorithm>> algorithmsAccepted() { Map<Method, Collection<Algorithm>> accepted = new HashMap<>(); accepted.put(CENTRALITY, ImmutableSet.of(DEGREE, K_CORE)); accepted.put(CLUSTER, ImmutableSet.of(CONNECTED_COMPONENT, K_CORE)); return ImmutableMap.copyOf(accepted); } private static Map<Method, Map<Algorithm, Collection<Parameter>>> argumentsAccepted() { Map<Method, Map<Algorithm, Collection<Parameter>>> accepted = new HashMap<>(); accepted.put(CENTRALITY, ImmutableMap.of(K_CORE, ImmutableSet.of(MIN_K))); accepted.put(CLUSTER, ImmutableMap.of( K_CORE, ImmutableSet.of(K), CONNECTED_COMPONENT, ImmutableSet.of(SIZE, CONTAINS) )); return ImmutableMap.copyOf(accepted); } private static Map<Method, Map<Algorithm, Map<Parameter, Object>>> argumentsDefault() { Map<Method, Map<Algorithm, Map<Parameter, Object>>> defaults = new HashMap<>(); defaults.put(CENTRALITY, ImmutableMap.of(K_CORE, ImmutableMap.of(MIN_K, Argument.DEFAULT_MIN_K))); defaults.put(CLUSTER, ImmutableMap.of(K_CORE, ImmutableMap.of(K, Argument.DEFAULT_K))); return ImmutableMap.copyOf(defaults); } private static Map<Method, Algorithm> algorithmsDefault() { Map<Method, Algorithm> methodAlgorithm = new HashMap<>(); methodAlgorithm.put(CENTRALITY, DEGREE); methodAlgorithm.put(CLUSTER, CONNECTED_COMPONENT); return ImmutableMap.copyOf(methodAlgorithm); } private static Map<Method, Boolean> includeAttributesDefault() { Map<Method, Boolean> map = new HashMap<>(); map.put(COUNT, false); map.put(MIN, true); map.put(MAX, true); map.put(MEDIAN, true); map.put(MEAN, true); map.put(STD, true); map.put(SUM, true); map.put(PATH, false); map.put(CENTRALITY, true); map.put(CLUSTER, false); return ImmutableMap.copyOf(map); } /** * Graql compute method types to determine the type of calculation to execute * @param <T> return type of ComputeQuery */ public static class Method<T extends Answer> { public final static Method<Value> COUNT = new Method<>("count"); public final static Method<Value> MIN = new Method<>("min"); public final static Method<Value> MAX = new Method<>("max"); public final static Method<Value> MEDIAN = new Method<>("median"); public final static Method<Value> MEAN = new Method<>("mean"); public final static Method<Value> STD = new Method<>("std"); public final static Method<Value> SUM = new Method<>("sum"); public final static Method<ConceptList> PATH = new Method<>("path"); public final static Method<ConceptSetMeasure> CENTRALITY = new Method<>("centrality"); public final static Method<ConceptSet> CLUSTER = new Method<>("cluster"); private final static List<Method> list = Arrays.asList(COUNT, MIN, MAX, MEDIAN, MEAN, STD, SUM, PATH, CENTRALITY, CLUSTER); private final String name; Method(String name) { this.name = name; } private static List<Method> values() { return list; } public String name() { return this.name; } @Override public String toString() { return this.name; } public static Method<?> of(String name) { for (Method<?> m : Method.values()) { if (m.name.equals(name)) { return m; } } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Method<?> that = (Method<?>) o; return (this.name().equals(that.name())); } @Override public int hashCode() { int result = 31 * name.hashCode(); return result; } } /** * Graql Compute conditions keyword */ public enum Condition { FROM("from"), TO("to"), OF("of"), IN("in"), USING("using"), WHERE("where"); private final String condition; Condition(String algorithm) { this.condition = algorithm; } @Override public String toString() { return this.condition; } public static Condition of(String value) { for (Condition c : Condition.values()) { if (c.condition.equals(value)) { return c; } } return null; } } /** * Graql Compute algorithm names */ public enum Algorithm { DEGREE("degree"), K_CORE("k-core"), CONNECTED_COMPONENT("connected-component"); private final String algorithm; Algorithm(String algorithm) { this.algorithm = algorithm; } @Override public String toString() { return this.algorithm; } public static Algorithm of(String value) { for (Algorithm a : Algorithm.values()) { if (a.algorithm.equals(value)) { return a; } } return null; } } /** * Graql Compute parameter names */ public enum Parameter { MIN_K("min-k"), K("k"), CONTAINS("contains"), SIZE("size"); private final String param; Parameter(String param) { this.param = param; } @Override public String toString() { return this.param; } public static Parameter of(String value) { for (Parameter p : Parameter.values()) { if (p.param.equals(value)) { return p; } } return null; } } /** * Graql Compute argument objects to be passed into the query * TODO: Move this class over into ComputeQuery (nested) once we replace Graql interfaces with classes * * @param <T> */ public static class Argument<T> { public final static long DEFAULT_MIN_K = 2L; public final static long DEFAULT_K = 2L; private Parameter param; private T arg; private Argument(Parameter param, T arg) { this.param = param; this.arg = arg; } public final Parameter type() { return this.param; } public final T get() { return this.arg; } public static Argument<Long> min_k(long minK) { return new Argument<>(MIN_K, minK); } public static Argument<Long> k(long k) { return new Argument<>(K, k); } public static Argument<Long> size(long size) { return new Argument<>(SIZE, size); } public static Argument<ConceptId> contains(ConceptId conceptId) { return new Argument<>(CONTAINS, conceptId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Argument that = (Argument) o; return (this.type().equals(that.type()) && this.get().equals(that.get())); } @Override public int hashCode() { int result = param.hashCode(); result = 31 * result + arg.hashCode(); return result; } } } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/REST.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; /** * Class containing strings describing the REST API, including URIs and fields. * * @author Marco Scoppetta */ public class REST { public static String resolveTemplate(String pathTemplate, String... pathParams) { // e.g. `/kb/:keyspace/commit_log` -> `/kb/%s/commit_log` String format = pathTemplate.replaceAll(":[^/]+", "%s"); return String.format(format, (Object[]) pathParams); } /** * e.g. /kb/:keyspace/graql -> /kb/{keyspace}/graql */ public static String reformatTemplate(String pathTemplate) { return pathTemplate.replaceAll(":([^/]+)", "{$1}"); } /** * Class containing URIs to REST endpoints. */ public static class WebPath{ public static final String ROOT = "/"; /** * Keyspace Specific Operations */ public static final String KB = "/kb"; public static final String KB_KEYSPACE = "/kb/:keyspace"; public static final String KEYSPACE_TYPE = "/kb/:keyspace/type"; public static final String KEYSPACE_ROLE = "/kb/:keyspace/role"; public static final String KEYSPACE_RULE = "/kb/:keyspace/rule"; public static final String KEYSPACE_GRAQL = "/kb/:keyspace/graql"; public static final String KEYSPACE_EXPLAIN = "/kb/:keyspace/explain"; public static final String COMMIT_LOG_URI = "/kb/:keyspace/commit_log"; /** * Concept Specific operations */ public static final String CONCEPT_LINK = "/kb/:keyspace/:base-type/:id"; public static final String CONCEPT_ID = "/kb/:keyspace/concept/:id"; public static final String CONCEPT_ATTRIBUTES = "/kb/:keyspace/concept/:id/attributes"; public static final String CONCEPT_KEYS = "/kb/:keyspace/concept/:id/keys"; public static final String CONCEPT_RELATIONSHIPS = "/kb/:keyspace/concept/:id/relationships"; public static final String TYPE_LABEL = "/kb/:keyspace/type/:label"; public static final String TYPE_SUBS = "/kb/:keyspace/type/:label/subs"; public static final String TYPE_PLAYS = "/kb/:keyspace/type/:label/plays"; public static final String TYPE_ATTRIBUTES = "/kb/:keyspace/type/:label/attributes"; public static final String TYPE_KEYS = "/kb/:keyspace/type/:label/keys"; public static final String TYPE_INSTANCES = "/kb/:keyspace/type/:label/instances"; public static final String RULE_LABEL = "/kb/:keyspace/rule/:label"; public static final String RULE_SUBS = "/kb/:keyspace/rule/:label/subs"; public static final String ROLE_LABEL = "/kb/:keyspace/role/:label"; public static final String ROLE_SUBS = "/kb/:keyspace/role/:label/subs"; /** * URIs to System Controller endpoints */ public static final String STATUS = "/status"; public static final String VERSION = "/version"; public static final String METRICS = "/metrics"; } /** * Class containing request fields and content types. */ public static class Request { // Request parameters public static final String LABEL_PARAMETER = ":label"; public static final String ID_PARAMETER = ":id"; public static final String KEYSPACE_PARAM = "keyspace"; public static final String LIMIT_PARAMETER = "limit"; public static final String OFFSET_PARAMETER = "offset"; public static final String FORMAT = "format"; /** * Graql controller request parameters */ public static final class Graql { public static final String QUERY = "query"; public static final String EXECUTE_WITH_INFERENCE = "infer"; public static final String ALLOW_MULTIPLE_QUERIES = "multi"; public static final String TX_TYPE = "txType"; public static final String DEFINE_ALL_VARS = "defineAllVars"; public static final String LOADING_DATA = "loading"; } } /** * Class listing possible knowledge base configuration options. */ public static class KBConfig { public static final String DEFAULT = "default"; public static final String COMPUTER = "computer"; } /** * Class listing various HTTP connection strings. */ public static class HttpConn{ public static final String POST_METHOD = "POST"; public static final String PUT_METHOD = "PUT"; public static final String DELETE_METHOD = "DELETE"; } /** * Class listing various strings found in responses from the REST API. */ public static class Response{ public static final String EXCEPTION = "exception"; /** * Response content types */ public static class ContentType { public static final String APPLICATION_TEXT = "application/text"; public static final String APPLICATION_JSON = "application/json"; public static final String APPLICATION_ALL ="*/*"; } } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/Schema.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import ai.grakn.concept.Attribute; import ai.grakn.concept.AttributeType; import ai.grakn.concept.Concept; import ai.grakn.concept.Entity; import ai.grakn.concept.EntityType; import ai.grakn.concept.Label; import ai.grakn.concept.LabelId; import ai.grakn.concept.Relationship; import ai.grakn.concept.RelationshipType; import ai.grakn.concept.Role; import ai.grakn.concept.Rule; import ai.grakn.concept.SchemaConcept; import ai.grakn.concept.Type; import org.apache.tinkerpop.gremlin.structure.Vertex; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; import static ai.grakn.util.ErrorMessage.INVALID_IMPLICIT_TYPE; /** * A type enum which restricts the types of links/concepts which can be created * * @author Filipe Teixeira */ public final class Schema { public final static String PREFIX_VERTEX = "V"; public final static String PREFIX_EDGE = "E"; private Schema() { throw new UnsupportedOperationException(); } /** * The different types of edges between vertices */ public enum EdgeLabel { ISA("isa"), SUB("sub"), RELATES("relates"), PLAYS("plays"), HYPOTHESIS("hypothesis"), CONCLUSION("conclusion"), ROLE_PLAYER("role-player"), ATTRIBUTE("attribute"), SHARD("shard"); private final String label; EdgeLabel(String l) { label = l; } @CheckReturnValue public String getLabel() { return label; } } /** * The concepts which represent our internal schema */ public enum MetaSchema { THING("thing", 1), ENTITY("entity", 2), ROLE("role", 3), ATTRIBUTE("attribute", 4), RELATIONSHIP("relationship", 5), RULE("rule", 6); private final Label label; private final LabelId id; MetaSchema(String s, int i) { label = Label.of(s); id = LabelId.of(i); } @CheckReturnValue public Label getLabel() { return label; } @CheckReturnValue public LabelId getId(){ return id; } @CheckReturnValue public static boolean isMetaLabel(Label label) { return valueOf(label) != null; } @Nullable @CheckReturnValue public static MetaSchema valueOf(Label label){ for (MetaSchema metaSchema : MetaSchema.values()) { if (metaSchema.getLabel().equals(label)) return metaSchema; } return null; } } /** * Base Types reflecting the possible objects in the concept */ public enum BaseType { //Schema Concepts SCHEMA_CONCEPT(SchemaConcept.class), TYPE(Type.class), ENTITY_TYPE(EntityType.class), RELATIONSHIP_TYPE(RelationshipType.class), ATTRIBUTE_TYPE(AttributeType.class), ROLE(Role.class), RULE(Rule.class), //Instances RELATIONSHIP(Relationship.class), ENTITY(Entity.class), ATTRIBUTE(Attribute.class), //Internal SHARD(Vertex.class), CONCEPT(Concept.class);//No concept actually has this base type. This is used to prevent string hardcoding private final Class classType; BaseType(Class classType){ this.classType = classType; } @CheckReturnValue public Class getClassType(){ return classType; } } /** * An enum which defines the non-unique mutable properties of the concept. */ public enum VertexProperty { //Unique Properties SCHEMA_LABEL(String.class), INDEX(String.class), ID(String.class), LABEL_ID(Integer.class), //Other Properties THING_TYPE_LABEL_ID(Integer.class), IS_ABSTRACT(Boolean.class), IS_IMPLICIT(Boolean.class), IS_INFERRED(Boolean.class), REGEX(String.class), DATA_TYPE(String.class), CURRENT_LABEL_ID(Integer.class), RULE_WHEN(String.class), RULE_THEN(String.class), CURRENT_SHARD(String.class), //Supported Data Types VALUE_STRING(String.class), VALUE_LONG(Long.class), VALUE_DOUBLE(Double.class), VALUE_BOOLEAN(Boolean.class), VALUE_INTEGER(Integer.class), VALUE_FLOAT(Float.class), VALUE_DATE(Long.class); private final Class dataType; VertexProperty(Class dataType) { this.dataType = dataType; } @CheckReturnValue public Class getDataType() { return dataType; } } /** * A property enum defining the possible labels that can go on the edge label. */ public enum EdgeProperty { RELATIONSHIP_ROLE_OWNER_LABEL_ID(Integer.class), RELATIONSHIP_ROLE_VALUE_LABEL_ID(Integer.class), ROLE_LABEL_ID(Integer.class), RELATIONSHIP_TYPE_LABEL_ID(Integer.class), REQUIRED(Boolean.class), IS_INFERRED(Boolean.class); private final Class dataType; EdgeProperty(Class dataType) { this.dataType = dataType; } @CheckReturnValue public Class getDataType() { return dataType; } } /** * This stores the schema which is required when implicitly creating roles for the has-{@link Attribute} methods */ public enum ImplicitType { /** * Reserved character used by all implicit {@link Type}s */ RESERVED("@"), /** * The label of the generic has-{@link Attribute} relationship, used for attaching {@link Attribute}s to instances with the 'has' syntax */ HAS("@has-%s"), /** * The label of a role in has-{@link Attribute}, played by the owner of the {@link Attribute} */ HAS_OWNER("@has-%s-owner"), /** * The label of a role in has-{@link Attribute}, played by the {@link Attribute} */ HAS_VALUE("@has-%s-value"), /** * The label of the generic key relationship, used for attaching {@link Attribute}s to instances with the 'has' syntax and additionally constraining them to be unique */ KEY("@key-%s"), /** * The label of a role in key, played by the owner of the key */ KEY_OWNER("@key-%s-owner"), /** * The label of a role in key, played by the {@link Attribute} */ KEY_VALUE("@key-%s-value"); private final String label; ImplicitType(String label) { this.label = label; } @CheckReturnValue public Label getLabel(Label attributeType) { return attributeType.map(attribute -> String.format(label, attribute)); } @CheckReturnValue public Label getLabel(String attributeType) { return Label.of(String.format(label, attributeType)); } @CheckReturnValue public String getValue(){ return label; } /** * Helper method which converts the implicit type label back into the original label from which is was built. * * @param implicitType the implicit type label * @return The original label which was used to build this type */ @CheckReturnValue public static Label explicitLabel(Label implicitType){ if(!implicitType.getValue().startsWith("key") && implicitType.getValue().startsWith("has")){ throw new IllegalArgumentException(INVALID_IMPLICIT_TYPE.getMessage(implicitType)); } int endIndex = implicitType.getValue().length(); if(implicitType.getValue().endsWith("-value") || implicitType.getValue().endsWith("-owner")) { endIndex = implicitType.getValue().lastIndexOf("-"); } //return the Label without the `@has-`or '@key-' prefix return Label.of(implicitType.getValue().substring(5, endIndex)); } } /** * * @param label The {@link AttributeType} label * @param value The value of the {@link Attribute} * @return A unique id for the {@link Attribute} */ @CheckReturnValue public static String generateAttributeIndex(Label label, String value){ return Schema.BaseType.ATTRIBUTE.name() + "-" + label + "-" + value; } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/SimpleURI.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import com.google.common.base.Preconditions; import org.apache.http.HttpHost; import org.apache.http.client.utils.URIBuilder; import java.net.URI; import java.net.URISyntaxException; /** * This Util class just takes care of going from host and port to string and viceversa * The URI class would require a schema * * @author pluraliseseverythings */ public class SimpleURI { private final int port; private final String host; public SimpleURI(String uri) { String[] uriSplit = uri.split(":"); Preconditions.checkArgument( uriSplit.length == 2 || (uriSplit.length == 3 && uriSplit[1].contains("//")), "Malformed URI " + uri); // if it has the schema, we start parsing from after int bias = uriSplit.length == 3 ? 1 : 0; this.host = uriSplit[bias].replace("/", "").trim(); this.port = Integer.parseInt(uriSplit[1 + bias].trim()); } public SimpleURI(String host, int port) { this.port = port; this.host = host; } public int getPort() { return port; } public String getHost() { return host; } @Override public String toString() { return String.format("%s:%d", host, port); } public static SimpleURI withDefaultPort(String uri, int defaultPort) { if (uri.contains(":")) { return new SimpleURI(uri); } else { return new SimpleURI(uri, defaultPort); } } public URI toURI() { try { return new URIBuilder().setScheme(HttpHost.DEFAULT_SCHEME_NAME).setHost(host).setPort(port).build(); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } }
0
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-core/1.4.3/ai/grakn/util/StringUtil.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.util; import org.apache.commons.lang.StringEscapeUtils; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; /** * <p> * Some helper methods in dealing with strings in the context of GRAKN. * </p> * * @author borislav * */ public class StringUtil { /** * @param string the string to unescape * @return the unescaped string, replacing any backslash escapes with the real characters */ public static String unescapeString(String string) { return StringEscapeUtils.unescapeJavaScript(string); } /** * @param string the string to escape * @return the escaped string, replacing any escapable characters with backslashes */ public static String escapeString(String string) { return StringEscapeUtils.escapeJavaScript(string); } /** * @param string a string to quote and escape * @return a string, surrounded with double quotes and escaped */ public static String quoteString(String string) { return "\"" + StringUtil.escapeString(string) + "\""; } /** * @param value a value in the graph * @return the string representation of the value (using quotes if it is already a string) */ public static String valueToString(Object value) { if (value instanceof String) { return quoteString((String) value); } else if (value instanceof Double) { DecimalFormat df = new DecimalFormat("#", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(12); df.setMinimumIntegerDigits(1); return df.format(value); } else { return value.toString(); } } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/Server.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.engine; import ai.grakn.GraknConfigKey; import ai.grakn.engine.attribute.deduplicator.AttributeDeduplicatorDaemon; import ai.grakn.engine.lock.LockProvider; import ai.grakn.engine.util.EngineID; import com.google.common.base.Stopwatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import static org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace; /** * Main class in charge to start a web server and all the REST controllers. * * @author Marco Scoppetta */ public class Server implements AutoCloseable { private static final String LOAD_SYSTEM_SCHEMA_LOCK_NAME = "load-system-schema"; private static final Logger LOG = LoggerFactory.getLogger(Server.class); private final EngineID engineId; private final GraknConfig config; private final ServerStatus serverStatus; private final LockProvider lockProvider; private final ServerHTTP httpHandler; private final AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon; private final KeyspaceStore keyspaceStore; public Server(EngineID engineId, GraknConfig config, ServerStatus serverStatus, LockProvider lockProvider, ServerHTTP httpHandler, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon, KeyspaceStore keyspaceStore) { this.config = config; this.serverStatus = serverStatus; // Redis connection pool // Lock provider this.lockProvider = lockProvider; this.keyspaceStore = keyspaceStore; this.httpHandler = httpHandler; this.engineId = engineId; this.AttributeDeduplicatorDaemon = AttributeDeduplicatorDaemon; } public void start() throws IOException { Stopwatch timer = Stopwatch.createStarted(); logStartMessage( config.getProperty(GraknConfigKey.SERVER_HOST_NAME), config.getProperty(GraknConfigKey.SERVER_PORT)); synchronized (this){ lockAndInitializeSystemSchema(); httpHandler.startHTTP(); } AttributeDeduplicatorDaemon.startDeduplicationDaemon(); serverStatus.setReady(true); LOG.info("Grakn started in {}", timer.stop()); } @Override public void close() { synchronized (this) { try { httpHandler.stopHTTP(); } catch (InterruptedException e){ LOG.error(getFullStackTrace(e)); Thread.currentThread().interrupt(); } AttributeDeduplicatorDaemon.stopDeduplicationDaemon(); } } private void lockAndInitializeSystemSchema() { try { Lock lock = lockProvider.getLock(LOAD_SYSTEM_SCHEMA_LOCK_NAME); if (lock.tryLock(60, TimeUnit.SECONDS)) { try { LOG.info("{} is checking the system schema", this.engineId); keyspaceStore.loadSystemSchema(); } finally { lock.unlock(); } } else { LOG.info("{} found system schema lock already acquired by other engine", this.engineId); } } catch (InterruptedException e) { LOG.warn("{} was interrupted while initializing system schema", this.engineId); Thread.currentThread().interrupt(); } } private void logStartMessage(String host, int port) { String address = "http://" + host + ":" + port; LOG.info("\n=================================================="); LOG.info("\n" + String.format(GraknConfig.GRAKN_ASCII, address)); LOG.info("\n=================================================="); } public ServerHTTP getHttpHandler() { return httpHandler; } public LockProvider lockProvider(){ return lockProvider; } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/ServerFactory.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.engine; import ai.grakn.GraknConfigKey; import ai.grakn.engine.attribute.deduplicator.AttributeDeduplicatorDaemonImpl; import ai.grakn.engine.attribute.deduplicator.AttributeDeduplicatorDaemon; import ai.grakn.engine.controller.HttpController; import ai.grakn.engine.factory.EngineGraknTxFactory; import ai.grakn.engine.lock.ProcessWideLockProvider; import ai.grakn.keyspace.KeyspaceStoreImpl; import ai.grakn.engine.lock.LockProvider; import ai.grakn.engine.rpc.KeyspaceService; import ai.grakn.engine.rpc.ServerOpenRequest; import ai.grakn.engine.rpc.SessionService; import ai.grakn.engine.util.EngineID; import ai.grakn.engine.rpc.OpenRequest; import com.codahale.metrics.MetricRegistry; import io.grpc.ServerBuilder; import spark.Service; import java.util.Collection; import java.util.Collections; /** * This is a factory class which contains methods for instantiating a {@link Server} in different ways. * * @author Michele Orsi */ public class ServerFactory { /** * Create a {@link Server} configured for Grakn Core. Grakn Queue (which is needed for post-processing and distributed locks) is implemented with Redis as the backend store * * @return a {@link Server} instance configured for Grakn Core */ public static Server createServer() { // grakn engine configuration EngineID engineId = EngineID.me(); GraknConfig config = GraknConfig.create(); ServerStatus status = new ServerStatus(); MetricRegistry metricRegistry = new MetricRegistry(); // distributed locks LockProvider lockProvider = new ProcessWideLockProvider(); KeyspaceStore keyspaceStore = new KeyspaceStoreImpl(config); // tx-factory EngineGraknTxFactory engineGraknTxFactory = EngineGraknTxFactory.create(lockProvider, config, keyspaceStore); // post-processing AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon = new AttributeDeduplicatorDaemonImpl(config, engineGraknTxFactory); // http services: spark, http controller, and gRPC server Service sparkHttp = Service.ignite(); Collection<HttpController> httpControllers = Collections.emptyList(); ServerRPC rpcServerRPC = configureServerRPC(config, engineGraknTxFactory, AttributeDeduplicatorDaemon, keyspaceStore); return createServer(engineId, config, status, sparkHttp, httpControllers, rpcServerRPC, engineGraknTxFactory, metricRegistry, lockProvider, AttributeDeduplicatorDaemon, keyspaceStore); } /** * Allows the creation of a {@link Server} instance with various configurations * @return a {@link Server} instance */ public static Server createServer( EngineID engineId, GraknConfig config, ServerStatus serverStatus, Service sparkHttp, Collection<HttpController> httpControllers, ServerRPC rpcServerRPC, EngineGraknTxFactory engineGraknTxFactory, MetricRegistry metricRegistry, LockProvider lockProvider, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon, KeyspaceStore keyspaceStore) { ServerHTTP httpHandler = new ServerHTTP(config, sparkHttp, engineGraknTxFactory, metricRegistry, serverStatus, AttributeDeduplicatorDaemon, rpcServerRPC, httpControllers); Server server = new Server(engineId, config, serverStatus, lockProvider, httpHandler, AttributeDeduplicatorDaemon, keyspaceStore); Thread thread = new Thread(server::close, "grakn-server-shutdown"); Runtime.getRuntime().addShutdownHook(thread); return server; } private static ServerRPC configureServerRPC(GraknConfig config, EngineGraknTxFactory engineGraknTxFactory, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon, KeyspaceStore keyspaceStore){ int grpcPort = config.getProperty(GraknConfigKey.GRPC_PORT); OpenRequest requestOpener = new ServerOpenRequest(engineGraknTxFactory); io.grpc.Server grpcServer = ServerBuilder.forPort(grpcPort) .addService(new SessionService(requestOpener, AttributeDeduplicatorDaemon)) .addService(new KeyspaceService(keyspaceStore)) .build(); return ServerRPC.create(grpcServer); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/ServerHTTP.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.engine; import ai.grakn.GraknConfigKey; import ai.grakn.engine.attribute.deduplicator.AttributeDeduplicatorDaemon; import ai.grakn.engine.controller.ConceptController; import ai.grakn.engine.controller.GraqlController; import ai.grakn.engine.controller.HttpController; import ai.grakn.engine.controller.SystemController; import ai.grakn.engine.factory.EngineGraknTxFactory; import ai.grakn.engine.printer.JacksonPrinter; import ai.grakn.exception.GraknBackendException; import ai.grakn.exception.GraknServerException; import com.codahale.metrics.MetricRegistry; import mjson.Json; import org.apache.http.entity.ContentType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Response; import spark.Service; import java.io.IOException; import java.nio.file.Path; import java.util.Collection; /** * @author Michele Orsi */ public class ServerHTTP { private static final Logger LOG = LoggerFactory.getLogger(ServerHTTP.class); private final GraknConfig prop; private final Service spark; private final EngineGraknTxFactory factory; private final MetricRegistry metricRegistry; private final ServerStatus serverStatus; private final AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon; private final ServerRPC rpcServerRPC; private final Collection<HttpController> additionalCollaborators; public ServerHTTP( GraknConfig prop, Service spark, EngineGraknTxFactory factory, MetricRegistry metricRegistry, ServerStatus serverStatus, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon, ServerRPC rpcServerRPC, Collection<HttpController> additionalCollaborators ) { this.prop = prop; this.spark = spark; this.factory = factory; this.metricRegistry = metricRegistry; this.serverStatus = serverStatus; this.AttributeDeduplicatorDaemon = AttributeDeduplicatorDaemon; this.rpcServerRPC = rpcServerRPC; this.additionalCollaborators = additionalCollaborators; } public void startHTTP() throws IOException { configureSpark(spark, prop); startCollaborators(); rpcServerRPC.start(); // This method will block until all the controllers are ready to serve requests spark.awaitInitialization(); } protected void startCollaborators() { JacksonPrinter printer = JacksonPrinter.create(); // Start all the DEFAULT controllers new GraqlController(factory, AttributeDeduplicatorDaemon, printer, metricRegistry).start(spark); new ConceptController(factory, metricRegistry).start(spark); new SystemController(prop, factory.keyspaceStore(), serverStatus, metricRegistry).start(spark); additionalCollaborators.forEach(httpController -> httpController.start(spark)); } public static void configureSpark(Service spark, GraknConfig prop) { configureSpark(spark, prop.getProperty(GraknConfigKey.SERVER_HOST_NAME), prop.getProperty(GraknConfigKey.SERVER_PORT), prop.getPath(GraknConfigKey.STATIC_FILES_PATH), prop.getProperty(GraknConfigKey.WEBSERVER_THREADS)); } public static void configureSpark(Service spark, String hostName, int port, Path staticFolder, int maxThreads) { // Set host name spark.ipAddress(hostName); // Set port spark.port(port); // Set the external static files folder spark.staticFiles.externalLocation(staticFolder.toString()); spark.threadPool(maxThreads); //Register exception handlers spark.exception(GraknServerException.class, (e, req, res) -> { assert e instanceof GraknServerException; // This is guaranteed by `spark#exception` handleGraknServerError((GraknServerException) e, res); }); spark.exception(Exception.class, (e, req, res) -> handleInternalError(e, res)); } public void stopHTTP() throws InterruptedException { rpcServerRPC.close(); spark.stop(); // Block until server is truly stopped // This occurs when there is no longer a port assigned to the Spark server boolean running = true; while (running) { try { spark.port(); } catch (IllegalStateException e) { LOG.debug("Spark server has been stopped"); running = false; } } } /** * Handle any {@link GraknBackendException} that are thrown by the server. Configures and returns * the correct JSON response. * * @param exception exception thrown by the server * @param response response to the client */ protected static void handleGraknServerError(GraknServerException exception, Response response) { LOG.error("REST error", exception); response.status(exception.getStatus()); response.body(Json.object("exception", exception.getMessage()).toString()); response.type(ContentType.APPLICATION_JSON.getMimeType()); } /** * Handle any exception thrown by the server * * @param exception Exception by the server * @param response response to the client */ protected static void handleInternalError(Exception exception, Response response) { LOG.error("REST error", exception); response.status(500); response.body(Json.object("exception", exception.getMessage()).toString()); response.type(ContentType.APPLICATION_JSON.getMimeType()); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/ServerRPC.java
/* * GRAKN.AI - THE KNOWLEDGE GRAPH * Copyright (C) 2018 Grakn Labs Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ai.grakn.engine; import java.io.IOException; /** * @author Felix Chapman */ public class ServerRPC implements AutoCloseable { private final io.grpc.Server server; private ServerRPC(io.grpc.Server server) { this.server = server; } public static ServerRPC create(io.grpc.Server server) { return new ServerRPC(server); } /** * @throws IOException if unable to bind */ public void start() throws IOException { server.start(); } @Override public void close() throws InterruptedException { server.shutdown(); server.awaitTermination(); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/ServerStatus.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; /** * Contains information on the state of an engine. * * @author Domenico Corapi */ public class ServerStatus { private volatile boolean ready = false; public ServerStatus() {} public boolean isReady() { return ready; } public void setReady(boolean ready) { this.ready = ready; } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/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 the REST controllers, task management and post processing features. */ package ai.grakn.engine;
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/AttributeDeduplicator.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.attribute.deduplicator; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.Schema; import com.google.common.collect.Lists; 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.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; /** * * The class containing the actual de-duplication algorithm. * * @author Ganeshwara Herawan Hananda */ public class AttributeDeduplicator { private static Logger LOG = LoggerFactory.getLogger(AttributeDeduplicator.class); /** * Deduplicate attributes that has the same value. A de-duplication process consists of picking a single attribute * in the duplicates as the "merge target", copying every edges from every "other duplicates" to the merge target, and * finally deleting that other duplicates. * * @param tx the transaction used for accessing the database * @param keyspaceIndexPair the pair containing information about the attribute keyspace and index */ public static void deduplicate(EmbeddedGraknTx tx, KeyspaceIndexPair keyspaceIndexPair) { GraphTraversalSource tinker = tx.getTinkerTraversal(); GraphTraversal<Vertex, Vertex> duplicates = tinker.V().has(Schema.VertexProperty.INDEX.name(), keyspaceIndexPair.index()); Vertex mergeTargetV = duplicates.next(); while (duplicates.hasNext()) { Vertex duplicate = duplicates.next(); try { duplicate.vertices(Direction.IN).forEachRemaining(connectedVertex -> { // merge attribute edge connecting 'duplicate' and 'connectedVertex' to 'mergeTargetV', if exists GraphTraversal<Vertex, Edge> attributeEdge = tinker.V(duplicate).inE(Schema.EdgeLabel.ATTRIBUTE.getLabel()).filter(__.outV().is(connectedVertex)); if (attributeEdge.hasNext()) { mergeAttributeEdge(mergeTargetV, connectedVertex, attributeEdge); } // merge role-player edge connecting 'duplicate' and 'connectedVertex' to 'mergeTargetV', if exists GraphTraversal<Vertex, Edge> rolePlayerEdge = tinker.V(duplicate).inE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()).filter(__.outV().is(connectedVertex)); if (rolePlayerEdge.hasNext()) { mergeRolePlayerEdge(mergeTargetV, rolePlayerEdge); } }); duplicate.remove(); } catch (IllegalStateException vertexAlreadyRemovedException) { LOG.warn("Trying to call the method vertices(Direction.IN) on vertex " + duplicate.id() + " which is already removed."); } } tx.commit(); } private static void mergeRolePlayerEdge(Vertex mergeTargetV, GraphTraversal<Vertex, Edge> rolePlayerEdge) { Edge edge = rolePlayerEdge.next(); Vertex relationshipVertex = edge.outVertex(); Object[] properties = propertiesToArray(Lists.newArrayList(edge.properties())); relationshipVertex.addEdge(Schema.EdgeLabel.ROLE_PLAYER.getLabel(), mergeTargetV, properties); edge.remove(); } private static void mergeAttributeEdge(Vertex mergeTargetV, Vertex ent, GraphTraversal<Vertex, Edge> attributeEdge) { Edge edge = attributeEdge.next(); Object[] properties = propertiesToArray(Lists.newArrayList(edge.properties())); ent.addEdge(Schema.EdgeLabel.ATTRIBUTE.getLabel(), mergeTargetV, properties); edge.remove(); } private static Object[] propertiesToArray(ArrayList<Property<Object>> propertiesAsKeyValue) { ArrayList<Object> propertiesAsObj = new ArrayList<>(); for (Property<Object> property: propertiesAsKeyValue) { propertiesAsObj.add(property.key()); propertiesAsObj.add(property.value()); } return propertiesAsObj.toArray(); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/AttributeDeduplicatorDaemon.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.attribute.deduplicator; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import java.util.concurrent.CompletableFuture; /** * @author Ganeshwara Herawan Hananda */ public interface AttributeDeduplicatorDaemon { void markForDeduplication(Keyspace keyspace, String index, ConceptId conceptId); CompletableFuture<Void> startDeduplicationDaemon(); void stopDeduplicationDaemon(); }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/AttributeDeduplicatorDaemonImpl.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.attribute.deduplicator; import ai.grakn.GraknConfigKey; import ai.grakn.GraknTxType; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import ai.grakn.engine.GraknConfig; import ai.grakn.engine.attribute.deduplicator.queue.Attribute; import ai.grakn.engine.attribute.deduplicator.queue.RocksDbQueue; import ai.grakn.engine.factory.EngineGraknTxFactory; import ai.grakn.kb.internal.EmbeddedGraknTx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static ai.grakn.engine.attribute.deduplicator.AttributeDeduplicator.deduplicate; /** * This class is responsible for de-duplicating attributes. It is done to ensure that every attribute in Grakn stays unique. * * Marking an attribute for deduplication: * When the {@link EmbeddedGraknTx#commit()} is invoked, it will trigger the {@link #markForDeduplication(Keyspace, String, ConceptId)} * which inserts the attribute to an internal queue for deduplication. * * De-duplicating attributes in the de-duplicator daemon: * The de-duplicator daemon is an always-on background thread which performs deduplication on incoming attributes. * When a new attribute is inserted, it will immediately trigger the deduplicate operation, meaning that duplicates are merged in almost real-time speed. * The daemon is started and stopped with {@link #startDeduplicationDaemon()} and {@link #stopDeduplicationDaemon()} * * Fault tolerance: * The de-duplicator daemon is fault-tolerant and will re-process incoming attributes if Grakn crashes in the middle of a deduplication. * * @author Ganeshwara Herawan Hananda */ public class AttributeDeduplicatorDaemonImpl implements AttributeDeduplicatorDaemon { private static Logger LOG = LoggerFactory.getLogger(AttributeDeduplicatorDaemonImpl.class); private static final int QUEUE_GET_BATCH_MAX = 1000; private static final Path queueDataDirRelative = Paths.get("queue"); // path to the queue storage location, relative to the data directory private EngineGraknTxFactory txFactory; private RocksDbQueue queue; private boolean stopDaemon = false; /** * Instantiates {@link AttributeDeduplicatorDaemonImpl} * @param config a reference to an instance of {@link GraknConfig} which is initialised from a grakn.properties. * @param txFactory an {@link EngineGraknTxFactory} instance which provides access to write into the database */ public AttributeDeduplicatorDaemonImpl(GraknConfig config, EngineGraknTxFactory txFactory) { Path dataDir = Paths.get(config.getProperty(GraknConfigKey.DATA_DIR)); Path queueDataDir = dataDir.resolve(queueDataDirRelative); this.queue = new RocksDbQueue(queueDataDir); this.txFactory = txFactory; } /** * Marks an attribute for deduplication. The attribute will be inserted to an internal queue to be processed by the de-duplicator daemon in real-time. * The attribute must have been inserted to the database, prior to calling this method. * * @param keyspace keyspace of the attribute * @param index the value of the attribute * @param conceptId the concept id of the attribute */ @Override public void markForDeduplication(Keyspace keyspace, String index, ConceptId conceptId) { Attribute attribute = Attribute.create(keyspace, index, conceptId); LOG.trace("insert(" + attribute + ")"); queue.insert(attribute); } /** * Starts a daemon which performs deduplication on incoming attributes in real-time. * The thread listens to the {@link RocksDbQueue} queue for incoming attributes and applies * the {@link AttributeDeduplicator#deduplicate(EmbeddedGraknTx, KeyspaceIndexPair)} algorithm. * */ @Override public CompletableFuture<Void> startDeduplicationDaemon() { stopDaemon = false; CompletableFuture<Void> daemon = CompletableFuture.supplyAsync(() -> { LOG.info("startDeduplicationDaemon() - attribute de-duplicator daemon started."); while (!stopDaemon) { try { List<Attribute> attributes = queue.read(QUEUE_GET_BATCH_MAX); LOG.trace("starting a new batch to process these new attributes: " + attributes); // group the attributes into a set of unique (keyspace -> value) pair Set<KeyspaceIndexPair> uniqueKeyValuePairs = attributes.stream() .map(attr -> KeyspaceIndexPair.create(attr.keyspace(), attr.index())) .collect(Collectors.toSet()); // perform deduplicate for each (keyspace -> value) for (KeyspaceIndexPair keyspaceIndexPair : uniqueKeyValuePairs) { try (EmbeddedGraknTx tx = txFactory.tx(keyspaceIndexPair.keyspace(), GraknTxType.WRITE)) { deduplicate(tx, keyspaceIndexPair); } } LOG.trace("new attributes processed."); queue.ack(attributes); } catch (InterruptedException | RuntimeException e) { LOG.error("An exception has occurred in the attribute de-duplicator daemon. ", e); } } LOG.info("startDeduplicationDaemon() - attribute de-duplicator daemon stopped"); return null; }); daemon.exceptionally(e -> { LOG.error("An unhandled exception has occurred in the attribute de-duplicator daemon. ", e); return null; }); return daemon; } /** * Stops the attribute uniqueness daemon */ @Override public void stopDeduplicationDaemon() { LOG.info("stopDeduplicationDaemon() - stopping the attribute de-duplicator daemon..."); stopDaemon = true; } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/AutoValue_KeyspaceIndexPair.java
package ai.grakn.engine.attribute.deduplicator; import ai.grakn.Keyspace; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_KeyspaceIndexPair extends KeyspaceIndexPair { private final Keyspace keyspace; private final String index; AutoValue_KeyspaceIndexPair( Keyspace keyspace, String index) { if (keyspace == null) { throw new NullPointerException("Null keyspace"); } this.keyspace = keyspace; if (index == null) { throw new NullPointerException("Null index"); } this.index = index; } @Override public Keyspace keyspace() { return keyspace; } @Override public String index() { return index; } @Override public String toString() { return "KeyspaceIndexPair{" + "keyspace=" + keyspace + ", " + "index=" + index + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof KeyspaceIndexPair) { KeyspaceIndexPair that = (KeyspaceIndexPair) o; return (this.keyspace.equals(that.keyspace())) && (this.index.equals(that.index())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.keyspace.hashCode(); h *= 1000003; h ^= this.index.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/KeyspaceIndexPair.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.attribute.deduplicator; import ai.grakn.Keyspace; import com.google.auto.value.AutoValue; /** * A class to hold a keyspace and an index together. * * @author Ganeshwara Herawan Hananda */ @AutoValue public abstract class KeyspaceIndexPair { public abstract Keyspace keyspace(); public abstract String index(); public static KeyspaceIndexPair create(Keyspace keyspace, String index) { return new AutoValue_KeyspaceIndexPair(keyspace, index); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/queue/Attribute.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.attribute.deduplicator.queue; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import com.google.auto.value.AutoValue; /** * * @author Ganeshwara Herawan Hananda */ @AutoValue public abstract class Attribute { public abstract Keyspace keyspace(); public abstract String index(); public abstract ConceptId conceptId(); public static Attribute create(Keyspace keyspace, String index, ConceptId conceptId) { return new AutoValue_Attribute(keyspace, index, conceptId); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/queue/AutoValue_Attribute.java
package ai.grakn.engine.attribute.deduplicator.queue; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Attribute extends Attribute { private final Keyspace keyspace; private final String index; private final ConceptId conceptId; AutoValue_Attribute( Keyspace keyspace, String index, ConceptId conceptId) { if (keyspace == null) { throw new NullPointerException("Null keyspace"); } this.keyspace = keyspace; if (index == null) { throw new NullPointerException("Null index"); } this.index = index; if (conceptId == null) { throw new NullPointerException("Null conceptId"); } this.conceptId = conceptId; } @Override public Keyspace keyspace() { return keyspace; } @Override public String index() { return index; } @Override public ConceptId conceptId() { return conceptId; } @Override public String toString() { return "Attribute{" + "keyspace=" + keyspace + ", " + "index=" + index + ", " + "conceptId=" + conceptId + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Attribute) { Attribute that = (Attribute) o; return (this.keyspace.equals(that.keyspace())) && (this.index.equals(that.index())) && (this.conceptId.equals(that.conceptId())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.keyspace.hashCode(); h *= 1000003; h ^= this.index.hashCode(); h *= 1000003; h ^= this.conceptId.hashCode(); return h; } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/queue/RocksDbQueue.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.attribute.deduplicator.queue; import java.nio.file.Path; import java.util.LinkedList; import java.util.List; import ai.grakn.Keyspace; import ai.grakn.concept.ConceptId; import mjson.Json; import org.rocksdb.Options; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; import org.rocksdb.WriteBatch; import org.rocksdb.WriteOptions; import static ai.grakn.engine.attribute.deduplicator.queue.RocksDbQueue.SerialisationUtils.deserialiseAttributeUtf8; import static ai.grakn.engine.attribute.deduplicator.queue.RocksDbQueue.SerialisationUtils.deserializeStringUtf8; import static ai.grakn.engine.attribute.deduplicator.queue.RocksDbQueue.SerialisationUtils.serialiseAttributeUtf8; import static ai.grakn.engine.attribute.deduplicator.queue.RocksDbQueue.SerialisationUtils.serialiseStringUtf8; import static java.nio.charset.StandardCharsets.UTF_8; /** * An implementation of a FIFO queue to support the attribute de-duplication in RocksDB. * It supports three operations: insert, read, and ack. * * The read and ack should be used together in order to provide fault-tolerance. * The attribute de-duplicator can read attributes from the queue and only ack after everything has been processed. * If the de-duplicator crashes during a deduplication, it can resume operation from the last ack-ed attribute. * * @author Ganeshwara Herawan Hananda */ public class RocksDbQueue implements AutoCloseable { private final RocksDB queueDb; /** * Instantiates the class and the queue data directory * * @param path where to persist the queue data */ public RocksDbQueue(Path path) { try { Options options = new Options().setCreateIfMissing(true); queueDb = RocksDB.open(options, path.toAbsolutePath().toString()); } catch (RocksDBException e) { throw new RocksDbQueueException(e); } } /** * insert a new attribute at the end of the queue. * * @param attribute the attribute to be inserted */ public void insert(Attribute attribute) { WriteOptions syncWrite = new WriteOptions().setSync(true); try { queueDb.put(syncWrite, serialiseStringUtf8(attribute.conceptId().getValue()), serialiseAttributeUtf8(attribute)); synchronized (this) { notifyAll(); } } catch (RocksDBException e) { throw new RocksDbQueueException(e); } } /** * Read at most N attributes from the beginning of the queue. Read everything if there are less than N attributes in the queue. * If the queue is empty, the method will block until the queue receives a new attribute. * The attributes won't be removed from the queue until you call {@link #ack(List<Attribute>)} on the returned attributes. * * @param limit the maximum number of items to be returned. * @return a list of {@link Attribute} * @throws InterruptedException * @see #ack(List<Attribute>) */ public List<Attribute> read(int limit) throws InterruptedException { // blocks until the queue contains at least 1 element while (isQueueEmpty(queueDb)) { synchronized (this) { wait(); } } List<Attribute> result = new LinkedList<>(); RocksIterator it = queueDb.newIterator(); it.seekToFirst(); int count = 0; while (it.isValid() && count < limit) { Attribute attr = deserialiseAttributeUtf8(it.value()); result.add(attr); it.next(); count++; } return result; } /** * Remove attributes from the queue. * * @param attributes the attributes which will be removed */ public void ack(List<Attribute> attributes) { WriteBatch acks = new WriteBatch(); // set to false for better performance. at the moment we're setting it to true as the algorithm is untested and we prefer correctness over speed WriteOptions writeOptions = new WriteOptions().setSync(true); for (Attribute attr: attributes) { try { acks.delete(serialiseStringUtf8(attr.conceptId().getValue())); } catch (RocksDBException e) { throw new RocksDbQueueException(e); } } try { queueDb.write(writeOptions, acks); } catch (RocksDBException e) { throw new RocksDbQueueException(e); } } /** * Close the {@link RocksDbQueue} instance. */ public void close() { queueDb.close(); } /** * Check if the queue is empty. * * @param queueDb the queue to be checked * @return true if empty, false otherwise */ private boolean isQueueEmpty(RocksDB queueDb) { RocksIterator it = queueDb.newIterator(); it.seekToFirst(); return !it.isValid(); } /** * Serialisation helpers for the {@link RocksDbQueue}. Don't add any other serialisation methods that are not related to it. */ static class SerialisationUtils { static byte[] serialiseAttributeUtf8(Attribute attribute) { Json json = Json.object( "attribute-keyspace", attribute.keyspace().getValue(), "attribute-index", attribute.index(), "attribute-concept-id", attribute.conceptId().getValue() ); return serialiseStringUtf8(json.toString()); } static Attribute deserialiseAttributeUtf8(byte[] attribute) { Json json = Json.read(deserializeStringUtf8(attribute)); String keyspace = json.at("attribute-keyspace").asString(); String value = json.at("attribute-index").asString(); String conceptId = json.at("attribute-concept-id").asString(); return Attribute.create(Keyspace.of(keyspace), value, ConceptId.of(conceptId)); } static String deserializeStringUtf8(byte[] bytes) { return new String(bytes, UTF_8); } static byte[] serialiseStringUtf8(String string) { return string.getBytes(UTF_8); } } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/attribute/deduplicator/queue/RocksDbQueueException.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.attribute.deduplicator.queue; /** * * @author Ganeshwara Herawan Hananda */ class RocksDbQueueException extends RuntimeException { RocksDbQueueException(Throwable cause) { super(cause); } }
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/bootup/AutoValue_BootupProcessResult.java
package ai.grakn.engine.bootup; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_BootupProcessResult extends BootupProcessResult { private final String stdout; private final String stderr; private final int exitCode; AutoValue_BootupProcessResult( String stdout, String stderr, int exitCode) { if (stdout == null) { throw new NullPointerException("Null stdout"); } this.stdout = stdout; if (stderr == null) { throw new NullPointerException("Null stderr"); } this.stderr = stderr; this.exitCode = exitCode; } @Override public String stdout() { return stdout; } @Override public String stderr() { return stderr; } @Override public int exitCode() { return exitCode; } @Override public String toString() { return "BootupProcessResult{" + "stdout=" + stdout + ", " + "stderr=" + stderr + ", " + "exitCode=" + exitCode + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof BootupProcessResult) { BootupProcessResult that = (BootupProcessResult) o; return (this.stdout.equals(that.stdout())) && (this.stderr.equals(that.stderr())) && (this.exitCode == that.exitCode()); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.stdout.hashCode(); h *= 1000003; h ^= this.stderr.hashCode(); h *= 1000003; h ^= this.exitCode; return h; } }
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/bootup/BootupException.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.bootup; /** * * @author Michele Orsi */ public class BootupException extends RuntimeException { public BootupException() { super(); } public BootupException(String message) { super(message);} public BootupException(Throwable cause) { super(cause); } public BootupException(String message, Throwable cause) { super(message, cause); } }
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/bootup/BootupProcessExecutor.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.bootup; import org.apache.commons.io.FileUtils; import org.zeroturnaround.exec.ProcessExecutor; import org.zeroturnaround.exec.ProcessResult; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeoutException; /** * This class is responsible for spawning process. * * @author Michele Orsi */ public class BootupProcessExecutor { public static final long WAIT_INTERVAL_SECOND = 2; public static final String SH = "/bin/sh"; public CompletableFuture<BootupProcessResult> executeAsync(List<String> command, File workingDirectory) { return CompletableFuture.supplyAsync(() -> executeAndWait(command, workingDirectory)); } public BootupProcessResult executeAndWait(List<String> command, File workingDirectory) { try { ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ProcessResult result = new ProcessExecutor() .readOutput(true) .redirectError(stderr) .directory(workingDirectory).command(command).execute(); return BootupProcessResult.create(result.outputUTF8(), stderr.toString(StandardCharsets.UTF_8.name()), result.getExitValue()); } catch (IOException | InterruptedException | TimeoutException e) { throw new RuntimeException(e); } } public Optional<String> getPidFromFile(Path fileName) { String pid = null; if (fileName.toFile().exists()) { try { pid = new String(Files.readAllBytes(fileName), StandardCharsets.UTF_8).trim(); } catch (IOException e) { // DO NOTHING } } return Optional.ofNullable(pid); } public String getPidFromPsOf(String processName) { return executeAndWait( Arrays.asList(SH, "-c", "ps -ef | grep " + processName + " | grep -v grep | awk '{print $2}' "), null).stdout(); } public String retrievePid(Path pidFile) { if (!pidFile.toFile().exists()) { return null; } try { String pid = new String(Files.readAllBytes(pidFile), StandardCharsets.UTF_8); return pid.trim(); } catch (NumberFormatException | IOException e) { return null; } } public void waitUntilStopped(Path pidFile) { while (isProcessRunning(pidFile)) { System.out.print("."); System.out.flush(); try { Thread.sleep(WAIT_INTERVAL_SECOND * 1000); } catch (InterruptedException e) { // DO NOTHING } } System.out.println("SUCCESS"); FileUtils.deleteQuietly(pidFile.toFile()); } public boolean isProcessRunning(Path pidFile) { String processPid; if (pidFile.toFile().exists()) { try { processPid = new String(Files.readAllBytes(pidFile), StandardCharsets.UTF_8); if (processPid.trim().isEmpty()) { return false; } BootupProcessResult command = executeAndWait(checkPIDRunningCommand(processPid), null); return command.exitCode() == 0; } catch (NumberFormatException | IOException e) { return false; } } return false; } private List<String> checkPIDRunningCommand(String pid) { if (isWindows()) { return Arrays.asList("cmd", "/c", "tasklist /fi \"PID eq " + pid.trim() + "\" | findstr \"" + pid.trim() + "\""); } else { return Arrays.asList(SH, "-c", "ps -p " + pid.trim()); } } public void stopProcessIfRunning(Path pidFile, String programName) { System.out.print("Stopping " + programName + "..."); System.out.flush(); boolean programIsRunning = isProcessRunning(pidFile); if (!programIsRunning) { System.out.println("NOT RUNNING"); } else { stopProcess(pidFile); } } public void processStatus(Path storagePid, String name) { if (isProcessRunning(storagePid)) { System.out.println(name + ": RUNNING"); } else { System.out.println(name + ": NOT RUNNING"); } } private void stopProcess(Path pidFile) { String pid = retrievePid(pidFile); if (pid == null) return; kill(pid); waitUntilStopped(pidFile); } private List<String> killProcessCommand(String pid){ if (isWindows()) { return Arrays.asList("cmd", "/c", "taskkill /F /PID "+ pid.trim()); } else { return Arrays.asList(SH, "-c", "kill " + pid.trim()); } } private void kill(String pid) { executeAndWait(killProcessCommand(pid), null); } private boolean isWindows() { return System.getProperty("os.name").toLowerCase().contains("win"); } }
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/bootup/BootupProcessResult.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.bootup; import com.google.auto.value.AutoValue; /** * * @author Ganeshwara Herawan Hananda * @author Michele Orsi */ @AutoValue public abstract class BootupProcessResult { public static BootupProcessResult create(String stdout, String stderr, int exitCode) { return new AutoValue_BootupProcessResult(stdout, stderr, exitCode); } public boolean success() { return exitCode() == 0; } public abstract String stdout(); public abstract String stderr(); public abstract int exitCode(); }
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/bootup/EngineBootup.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.bootup; import ai.grakn.GraknConfigKey; import ai.grakn.GraknSystemProperty; import ai.grakn.engine.GraknConfig; import ai.grakn.util.REST; import ai.grakn.util.SimpleURI; import javax.ws.rs.core.UriBuilder; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.stream.Stream; import static ai.grakn.engine.bootup.BootupProcessExecutor.WAIT_INTERVAL_SECOND; /** * A class responsible for managing the Engine process, * including starting, stopping, and performing status checks * * @author Ganeshwara Herawan Hananda * @author Michele Orsi */ public class EngineBootup { private static final String DISPLAY_NAME = "Engine"; private static final long ENGINE_STARTUP_TIMEOUT_S = 300; private static final Path ENGINE_PIDFILE = Paths.get(System.getProperty("java.io.tmpdir"), "grakn-engine.pid"); private static final String JAVA_OPTS = GraknSystemProperty.ENGINE_JAVAOPTS.value(); protected final Path graknHome; protected final Path graknPropertiesPath; private final GraknConfig graknProperties; private final Class engineMainClass; private BootupProcessExecutor bootupProcessExecutor; public EngineBootup(BootupProcessExecutor bootupProcessExecutor, Path graknHome, Path graknPropertiesPath, Class engineMainClass) { this.bootupProcessExecutor = bootupProcessExecutor; this.graknHome = graknHome; this.graknPropertiesPath = graknPropertiesPath; this.graknProperties = GraknConfig.read(graknPropertiesPath.toFile()); this.engineMainClass = engineMainClass; } public void startIfNotRunning() { boolean isEngineRunning = bootupProcessExecutor.isProcessRunning(ENGINE_PIDFILE); if (isEngineRunning) { System.out.println(DISPLAY_NAME + " is already running"); } else { start(); } } public void stop() { bootupProcessExecutor.stopProcessIfRunning(ENGINE_PIDFILE, DISPLAY_NAME); } public void status() { bootupProcessExecutor.processStatus(ENGINE_PIDFILE, DISPLAY_NAME); } public void statusVerbose() { System.out.println(DISPLAY_NAME + " pid = '" + bootupProcessExecutor.getPidFromFile(ENGINE_PIDFILE).orElse("") + "' (from " + ENGINE_PIDFILE + "), '" + bootupProcessExecutor.getPidFromPsOf(engineMainClass.getName()) + "' (from ps -ef)"); } public void clean() { System.out.print("Cleaning " + DISPLAY_NAME + "..."); System.out.flush(); Path rootPath = graknHome.resolve("logs"); try (Stream<Path> files = Files.walk(rootPath)) { files.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); Files.createDirectories(graknHome.resolve("logs")); System.out.println("SUCCESS"); } catch (IOException e) { System.out.println("FAILED!"); System.out.println("Unable to clean " + DISPLAY_NAME); } } public boolean isRunning() { return bootupProcessExecutor.isProcessRunning(ENGINE_PIDFILE); } public void start() { System.out.print("Starting " + DISPLAY_NAME + "..."); System.out.flush(); Future<BootupProcessResult> startEngineAsync = bootupProcessExecutor.executeAsync(engineCommand(), graknHome.toFile()); LocalDateTime timeout = LocalDateTime.now().plusSeconds(ENGINE_STARTUP_TIMEOUT_S); while (LocalDateTime.now().isBefore(timeout) && !startEngineAsync.isDone()) { System.out.print("."); System.out.flush(); String host = graknProperties.getProperty(GraknConfigKey.SERVER_HOST_NAME); int port = graknProperties.getProperty(GraknConfigKey.SERVER_PORT); if (bootupProcessExecutor.isProcessRunning(ENGINE_PIDFILE) && isEngineReady(host, port, REST.WebPath.STATUS)) { System.out.println("SUCCESS"); return; } try { Thread.sleep(WAIT_INTERVAL_SECOND * 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.println("FAILED!"); System.err.println("Unable to start " + DISPLAY_NAME + "."); try { String errorMessage = "Process exited with code '" + startEngineAsync.get().exitCode() + "': '" + startEngineAsync.get().stderr() + "'"; System.err.println(errorMessage); throw new BootupException(errorMessage); } catch (InterruptedException | ExecutionException e) { throw new BootupException(e); } } private List<String> engineCommand() { ArrayList<String> engineCommand = new ArrayList<>(); engineCommand.add("java"); engineCommand.add("-cp"); engineCommand.add(getEngineClassPath()); engineCommand.add("-Dgrakn.dir=" + graknHome); engineCommand.add("-Dgrakn.conf=" + graknPropertiesPath); engineCommand.add("-Dgrakn.pidfile=" + ENGINE_PIDFILE); // This is because https://wiki.apache.org/hadoop/WindowsProblems engineCommand.add("-Dhadoop.home.dir="+graknHome.resolve("services").resolve("hadoop")); if (JAVA_OPTS != null && JAVA_OPTS.length() > 0) {//split JAVA OPTS by space and add them to the command engineCommand.addAll(Arrays.asList(JAVA_OPTS.split(" "))); } engineCommand.add(engineMainClass.getName()); return engineCommand; } private String getEngineClassPath() { return graknHome.resolve("services").resolve("lib").toString() + File.separator + "*" + File.pathSeparator + graknHome.resolve("services").resolve("grakn").resolve("server") + File.pathSeparator + graknHome.resolve("conf"); } private boolean isEngineReady(String host, int port, String path) { try { URL engineUrl = UriBuilder.fromUri(new SimpleURI(host, port).toURI()).path(path).build().toURL(); HttpURLConnection connection = (HttpURLConnection) engineUrl.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); return code == 200; } catch (IOException e) { return false; } } }
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/bootup/EnginePidManager.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.bootup; import ai.grakn.util.ErrorMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.management.ManagementFactory; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; /** * * A class responsible for managing the PID file of Engine * * @author Ganeshwara Herawan Hananda * */ public class EnginePidManager { private static final Logger LOG = LoggerFactory.getLogger(EnginePidManager.class); private Path pidFile; public EnginePidManager(Path pidFile) { this.pidFile = pidFile; } public void trackGraknPid() { long pid = getPid(); trackGraknPid(pid); } private long getPid() { String[] pidAndHostnameString = ManagementFactory.getRuntimeMXBean().getName().split("@"); String pidString = pidAndHostnameString[0]; try { return Long.parseLong(pidString); } catch (NumberFormatException e) { throw new BootupException(ErrorMessage.COULD_NOT_GET_PID.getMessage(pidString), e); } } private void trackGraknPid(long graknPid) { attemptToWritePidFile(graknPid, this.pidFile); deletePidFileOnExit(); } private void deletePidFileOnExit() { this.pidFile.toFile().deleteOnExit(); } private void attemptToWritePidFile(long pid, Path pidFilePath) { if (pidFilePath.toFile().exists()) { LOG.warn(ErrorMessage.PID_ALREADY_EXISTS.getMessage(pidFilePath.toString())); } String pidString = Long.toString(pid); try { Files.write(pidFilePath, pidString.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new BootupException(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/bootup/Grakn.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.bootup; import ai.grakn.GraknSystemProperty; import ai.grakn.engine.Server; import ai.grakn.engine.ServerFactory; import ai.grakn.util.ErrorMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; /** * The main class of the 'grakn' command. This class is not a class responsible * for booting up the real command, but rather the command itself. * * Please keep the class name "Grakn" as it is what will be displayed to the user. */ public class Grakn { private static final Logger LOG = LoggerFactory.getLogger(Grakn.class); /** * * Invocation from class '{@link GraknBootup}' * * @param args */ public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(t.getName()), e)); try { String graknPidFileProperty = Optional.ofNullable(GraknSystemProperty.GRAKN_PID_FILE.value()) .orElseThrow(() -> new RuntimeException(ErrorMessage.GRAKN_PIDFILE_SYSTEM_PROPERTY_UNDEFINED.getMessage())); Path pidfile = Paths.get(graknPidFileProperty); EnginePidManager enginePidManager = new EnginePidManager(pidfile); enginePidManager.trackGraknPid(); // Start Engine Server server = ServerFactory.createServer(); server.start(); } catch (RuntimeException | IOException e) { LOG.error(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage()), e); System.err.println(ErrorMessage.UNCAUGHT_EXCEPTION.getMessage(e.getMessage())); } } }
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/bootup/GraknBootup.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.bootup; import ai.grakn.GraknSystemProperty; import ai.grakn.engine.bootup.config.ConfigProcessor; import ai.grakn.util.ErrorMessage; import ai.grakn.util.GraknVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Scanner; /** * The {@link GraknBootup} class is responsible for starting, stopping and cleaning the keyspaces of Grakn * * @author Ganeshwara Herawan Hananda * @author Michele Orsi */ public class GraknBootup { private static final Logger LOG = LoggerFactory.getLogger(GraknBootup.class); private static final String ENGINE = "engine"; private static final String STORAGE = "storage"; private static final Class GRAKN_CLASS = Grakn.class; private final StorageBootup storageBootup; private final EngineBootup engineBootup; /** * Main function of the {@link GraknBootup}. It is meant to be invoked by the 'grakn' bash script. * You should have 'grakn.dir' and 'grakn.conf' Java properties set. * * @param args arguments such as 'server start', 'server stop', 'clean', and so on */ public static void main(String[] args) { try { Path graknHome = Paths.get(GraknSystemProperty.CURRENT_DIRECTORY.value()); Path graknProperties = Paths.get(GraknSystemProperty.CONFIGURATION_FILE.value()); assertEnvironment(graknHome, graknProperties); printGraknLogo(); BootupProcessExecutor bootupProcessExecutor = new BootupProcessExecutor(); GraknBootup graknBootup = new GraknBootup(new StorageBootup(bootupProcessExecutor, graknHome, graknProperties), new EngineBootup(bootupProcessExecutor, graknHome, graknProperties, GRAKN_CLASS)); graknBootup.run(args); System.exit(0); } catch (RuntimeException ex) { LOG.error(ErrorMessage.UNABLE_TO_START_GRAKN.getMessage(), ex); System.out.println(ErrorMessage.UNABLE_TO_START_GRAKN.getMessage()); System.err.println(ex.getMessage()); System.exit(1); } } private GraknBootup(StorageBootup storageBootup, EngineBootup engineBootup) { this.storageBootup = storageBootup; this.engineBootup = engineBootup; } /** * Basic environment checks. Grakn should only be ran if users are running Java 8, * home folder can be detected, and the configuration file 'grakn.properties' exists. * @param graknHome path to $GRAKN_HOME * @param graknProperties path to the 'grakn.properties' file */ private static void assertEnvironment(Path graknHome, Path graknProperties) { String javaVersion = System.getProperty("java.specification.version"); if (!javaVersion.equals("1.8")) { throw new RuntimeException(ErrorMessage.UNSUPPORTED_JAVA_VERSION.getMessage(javaVersion)); } if (!graknHome.resolve("grakn").toFile().exists()) { throw new RuntimeException(ErrorMessage.UNABLE_TO_GET_GRAKN_HOME_FOLDER.getMessage()); } if (!graknProperties.toFile().exists()) { throw new RuntimeException(ErrorMessage.UNABLE_TO_GET_GRAKN_CONFIG_FOLDER.getMessage()); } } private static void printGraknLogo() { Path ascii = Paths.get(".", "services", "grakn", "grakn-ascii.txt"); if(ascii.toFile().exists()) { try { System.out.println(new String(Files.readAllBytes(ascii), StandardCharsets.UTF_8)); } catch (IOException e) { // DO NOTHING } } } /** * Accepts various Grakn commands (eg., 'grakn server start') * @param args arrays of arguments, eg., { 'server', 'start' } */ public void run(String[] args) { String context = args.length > 0 ? args[0] : ""; String action = args.length > 1 ? args[1] : ""; String option = args.length > 2 ? args[2] : ""; switch (context) { case "server": server(action, option); break; case "version": version(); break; default: help(); } } private void server(String action, String option) { switch (action) { case "start": serverStart(option); break; case "stop": serverStop(option); break; case "status": serverStatus(option); break; case "clean": clean(); break; default: serverHelp(); } } private void serverStop(String arg) { switch (arg) { case ENGINE: engineBootup.stop(); break; case STORAGE: storageBootup.stop(); break; default: engineBootup.stop(); storageBootup.stop(); } } private void serverStart(String arg) { switch (arg) { case ENGINE: engineBootup.startIfNotRunning(); break; case STORAGE: storageBootup.startIfNotRunning(); break; default: ConfigProcessor.updateProcessConfigs(); storageBootup.startIfNotRunning(); engineBootup.startIfNotRunning(); } } private void serverHelp() { System.out.println("Usage: grakn server COMMAND\n" + "\n" + "COMMAND:\n" + "start ["+ENGINE+"|"+STORAGE+"] Start Grakn (or optionally, only one of the component)\n" + "stop ["+ENGINE+"|"+STORAGE+"] Stop Grakn (or optionally, only one of the component)\n" + "status Check if Grakn is running\n" + "clean DANGEROUS: wipe data completely\n" + "\n" + "Tips:\n" + "- Start Grakn with 'grakn server start'\n" + "- Start or stop only one component with, e.g. 'grakn server start storage' or 'grakn server stop storage', respectively\n"); } private void serverStatus(String verboseFlag) { storageBootup.status(); engineBootup.status(); if(verboseFlag.equals("--verbose")) { System.out.println("======== Failure Diagnostics ========"); storageBootup.statusVerbose(); engineBootup.statusVerbose(); } } private void version() { System.out.println(GraknVersion.VERSION); } private void help() { System.out.println("Usage: grakn COMMAND\n" + "\n" + "COMMAND:\n" + "server Manage Grakn components\n" + "version Print Grakn version\n" + "help Print this message\n" + "\n" + "Tips:\n" + "- Start Grakn with 'grakn server start' (by default, the dashboard will be accessible at http://localhost:4567)\n" + "- You can then perform queries by opening a console with 'graql console'"); } private void clean() { boolean storage = storageBootup.isRunning(); boolean grakn = engineBootup.isRunning(); if(storage || grakn) { System.out.println("Grakn is still running! Please do a shutdown with 'grakn server stop' before performing a cleanup."); return; } System.out.print("Are you sure you want to delete all stored data and logs? [y/N] "); System.out.flush(); String response = new Scanner(System.in, StandardCharsets.UTF_8.name()).next(); if (!response.equals("y") && !response.equals("Y")) { System.out.println("Response '" + response + "' did not equal 'y' or 'Y'. Canceling clean operation."); return; } storageBootup.clean(); engineBootup.clean(); } }
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/bootup/GraknCassandra.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.bootup; import org.apache.cassandra.service.CassandraDaemon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.PrintWriter; import java.lang.management.ManagementFactory; /** * CassandraDaemon Wrapper that persists Cassandra PID to file once the service is up and running */ public class GraknCassandra { private static final Logger LOG = LoggerFactory.getLogger(GraknCassandra.class); public static void main(String[] args) { try { CassandraDaemon instance = new CassandraDaemon(); instance.activate(); persistPID(); }catch (Exception e){ LOG.error("Cassandra Exception:", e); System.err.println(e.getMessage()); } } private static void persistPID() { String pidString = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; try { String pidFile = System.getProperty("cassandra-pidfile"); if (pidFile == null) { LOG.warn("Directory for Cassandra PID not provided, the PID will not be persisted."); return; } PrintWriter writer = new PrintWriter(pidFile, "UTF-8"); writer.print(pidString); writer.close(); } catch (IOException e) { LOG.error("Error persisting storage PID:" + e.getMessage()); } } }
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/bootup/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.engine.bootup; import ai.grakn.graql.shell.GraqlConsole; import ai.grakn.graql.shell.GraqlShellOptions; import ai.grakn.migration.csv.CSVMigrator; import ai.grakn.migration.export.Main; import ai.grakn.migration.json.JsonMigrator; import ai.grakn.migration.sql.SQLMigrator; import ai.grakn.migration.xml.XmlMigrator; import ai.grakn.util.ErrorMessage; import ai.grakn.util.GraknVersion; import ai.grakn.util.SimpleURI; import com.google.common.base.StandardSystemProperty; import org.apache.commons.cli.ParseException; import ai.grakn.client.Grakn; import java.io.IOException; import java.util.Arrays; /** * The main class of the 'graql' command. This class is not a class responsible * for booting up the real command, but rather the command itself. * <p> * Please keep the class name "Graql" as it is what will be displayed to the user. */ public class Graql { private static final String HISTORY_FILENAME = StandardSystemProperty.USER_HOME.value() + "/.graql-history"; public static final SimpleURI DEFAULT_URI = new SimpleURI("localhost:48555"); /** * Invocation from bash script 'graql' * * @param args */ public static void main(String[] args) throws IOException, InterruptedException, ParseException { String[] argsWithoutContext = Arrays.copyOfRange(args, 1, args.length); GraqlShellOptions shellOptions = GraqlShellOptions.create(argsWithoutContext); SimpleURI location = shellOptions.getUri(); SimpleURI uri = location != null ? location : DEFAULT_URI; Grakn client = new Grakn(uri); // Start Graql Console injecting args, shellOptions and a Grakn client that will be used to communicate with the Server new Graql().run(args, shellOptions, client); } public void run(String[] args, GraqlShellOptions shellOptions, Grakn client) throws IOException, InterruptedException { String context = args.length > 0 ? args[0] : ""; switch (context) { case "console": GraqlConsole.start(shellOptions, HISTORY_FILENAME, client, System.out, System.err); break; case "migrate": migrate(valuesFrom(args, 1)); break; case "version": version(); break; default: help(); } } private void migrate(String[] args) { String option = args.length > 0 ? args[0] : ""; switch (option) { case "csv": CSVMigrator.main(valuesFrom(args, 1)); break; case "json": JsonMigrator.main(valuesFrom(args, 1)); break; case "owl": System.err.println(ErrorMessage.OWL_NOT_SUPPORTED.getMessage()); break; case "export": Main.main(valuesFrom(args, 1)); break; case "sql": SQLMigrator.main(valuesFrom(args, 1)); break; case "xml": XmlMigrator.main(valuesFrom(args, 1)); break; default: help(); } } private String[] valuesFrom(String[] args, int index) { return Arrays.copyOfRange(args, index, args.length); } private void help() { System.out.println("Usage: graql COMMAND\n" + "\n" + "COMMAND:\n" + "console Start a REPL console for running Graql queries. Defaults to connecting to http://localhost\n" + "migrate Run migration from a file\n" + "version Print Grakn version\n" + "help Print this message"); } private void version() { System.out.println(GraknVersion.VERSION); } }
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/bootup/StorageBootup.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.bootup; import ai.grakn.GraknConfigKey; import ai.grakn.GraknSystemProperty; import ai.grakn.engine.GraknConfig; import org.apache.cassandra.tools.NodeTool; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.stream.Stream; import static ai.grakn.engine.bootup.BootupProcessExecutor.WAIT_INTERVAL_SECOND; /** * A class responsible for managing the bootup-related process for the Storage component, including * starting and stopping, performing status checks, and cleaning the data. * <p> * The PID file for the Storage component is managed internally by Cassandra and not by this class. This means that * you will not find any code which creates or deletes the PID file for the Storage component. * * @author Ganeshwara Herawan Hananda * @author Michele Orsi */ public class StorageBootup { private static final String DISPLAY_NAME = "Storage"; private static final String STORAGE_PROCESS_NAME = "CassandraDaemon"; private static final long STORAGE_STARTUP_TIMEOUT_SECOND = 60; private static final Path STORAGE_PIDFILE = Paths.get(System.getProperty("java.io.tmpdir"), "grakn-storage.pid"); private static final Path STORAGE_DATA = Paths.get("db", "cassandra"); private static final String JAVA_OPTS = GraknSystemProperty.STORAGE_JAVAOPTS.value(); private BootupProcessExecutor bootupProcessExecutor; private final Path graknHome; private final GraknConfig graknProperties; public StorageBootup(BootupProcessExecutor bootupProcessExecutor, Path graknHome, Path graknPropertiesPath) { this.graknHome = graknHome; this.graknProperties = GraknConfig.read(graknPropertiesPath.toFile()); this.bootupProcessExecutor = bootupProcessExecutor; } /** * Attempt to start Storage if it is not already running */ public void startIfNotRunning() { boolean isStorageRunning = bootupProcessExecutor.isProcessRunning(STORAGE_PIDFILE); if (isStorageRunning) { System.out.println(DISPLAY_NAME + " is already running"); } else { FileUtils.deleteQuietly(STORAGE_PIDFILE.toFile()); // delete dangling STORAGE_PIDFILE, if any start(); } } public void stop() { bootupProcessExecutor.stopProcessIfRunning(STORAGE_PIDFILE, DISPLAY_NAME); } public void status() { bootupProcessExecutor.processStatus(STORAGE_PIDFILE, DISPLAY_NAME); } public void statusVerbose() { System.out.println(DISPLAY_NAME + " pid = '" + bootupProcessExecutor.getPidFromFile(STORAGE_PIDFILE).orElse("") + "' (from " + STORAGE_PIDFILE + "), '" + bootupProcessExecutor.getPidFromPsOf(STORAGE_PROCESS_NAME) + "' (from ps -ef)"); } public void clean() { System.out.print("Cleaning " + DISPLAY_NAME + "..."); System.out.flush(); try (Stream<Path> files = Files.walk(STORAGE_DATA)) { files.map(Path::toFile) .sorted(Comparator.comparing(File::isDirectory)) .forEach(File::delete); Files.createDirectories(graknHome.resolve(STORAGE_DATA).resolve("data")); Files.createDirectories(graknHome.resolve(STORAGE_DATA).resolve("commitlog")); Files.createDirectories(graknHome.resolve(STORAGE_DATA).resolve("saved_caches")); System.out.println("SUCCESS"); } catch (IOException e) { System.out.println("FAILED!"); System.out.println("Unable to clean " + DISPLAY_NAME); } } public boolean isRunning() { return bootupProcessExecutor.isProcessRunning(STORAGE_PIDFILE); } /** * Attempt to start Storage and perform periodic polling until it is ready. The readiness check is performed with nodetool. * <p> * A {@link BootupException} will be thrown if Storage does not start after a timeout specified * in the 'WAIT_INTERVAL_SECOND' field. * * @throws BootupException */ public void start() { System.out.print("Starting " + DISPLAY_NAME + "..."); System.out.flush(); Future<BootupProcessResult> result = bootupProcessExecutor.executeAsync(storageCommand(), graknHome.toFile()); LocalDateTime timeout = LocalDateTime.now().plusSeconds(STORAGE_STARTUP_TIMEOUT_SECOND); while (LocalDateTime.now().isBefore(timeout) && !result.isDone()) { System.out.print("."); System.out.flush(); if (storageStatus().equals("running")) { System.out.println("SUCCESS"); return; } try { Thread.sleep(WAIT_INTERVAL_SECOND * 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } System.out.println("FAILED!"); System.err.println("Unable to start " + DISPLAY_NAME + "."); try { String errorMessage = "Process exited with code '" + result.get().exitCode() + "': '" + result.get().stderr() + "'"; System.err.println(errorMessage); throw new BootupException(errorMessage); } catch (InterruptedException | ExecutionException e) { throw new BootupException(e); } } private String storageStatus() { return bootupProcessExecutor.executeAndWait(nodetoolCommand(), graknHome.toFile()).stdout().trim(); } private List<String> storageCommand() { Path logback = graknHome.resolve("services").resolve("cassandra").resolve("logback.xml"); ArrayList<String> storageCommand = new ArrayList<>(); storageCommand.add("java"); storageCommand.add("-cp"); storageCommand.add(getStorageClassPath()); storageCommand.add("-Dlogback.configurationFile=" + logback); storageCommand.add("-Dcassandra.logdir=" + getStorageLogPathFromGraknProperties()); storageCommand.add("-Dcassandra-pidfile=" + STORAGE_PIDFILE.toString()); storageCommand.add("-Dcassandra.superuser_setup_delay_ms=0"); //default port over for JMX connections, needed for nodetool status storageCommand.add("-Dcassandra.jmx.local.port=7199"); // stop the jvm on OutOfMemoryError as it can result in some data corruption storageCommand.add("-XX:+CrashOnOutOfMemoryError"); if (JAVA_OPTS != null && JAVA_OPTS.length() > 0) { storageCommand.addAll(Arrays.asList(JAVA_OPTS.split(" "))); } storageCommand.add(GraknCassandra.class.getCanonicalName()); return storageCommand; } private String getStorageClassPath() { return graknHome.resolve("services").resolve("lib").toString() + File.separator + "*" + File.pathSeparator + graknHome.resolve("services").resolve("cassandra"); } private List<String> nodetoolCommand() { Path logback = graknHome.resolve("services").resolve("cassandra").resolve("logback.xml"); String classpath = graknHome.resolve("services").resolve("lib").toString() + File.separator + "*"; return Arrays.asList( "java", "-cp", classpath, "-Dlogback.configurationFile=" + logback, NodeTool.class.getCanonicalName(), "statusthrift" ); } private Path getStorageLogPathFromGraknProperties() { Path logPath = Paths.get(graknProperties.getProperty(GraknConfigKey.LOG_DIR)); return logPath.isAbsolute() ? logPath : graknHome.resolve(logPath); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup/config/ConfigProcessor.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.bootup.config; import ai.grakn.engine.GraknConfig; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; /** * Helper class for updating storage config file. * * @author Kasper Piskorski */ public class ConfigProcessor { public static String getConfigStringFromFile(Path configPath){ try { byte[] bytes = Files.readAllBytes(configPath); return new String(bytes, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } public static void saveConfigStringToFile(String configString, Path configPath){ try { Files.write(configPath, configString.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } } public static void updateStorageConfig(){ GraknConfig graknConfig = Configs.graknConfig(); String updatedStorageConfigString = Configs.storageConfig() .updateFromConfig(graknConfig) .toConfigString(); saveConfigStringToFile(updatedStorageConfigString, Configs.storageConfigPath()); } public static void updateProcessConfigs() { updateStorageConfig(); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup/config/Configs.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.bootup.config; import ai.grakn.GraknSystemProperty; import ai.grakn.engine.GraknConfig; import java.nio.file.Path; import java.nio.file.Paths; /** * Factory class for configs. * * @author Kasper Piskorski */ public class Configs { private static final String STORAGE_CONFIG_PATH = "services/cassandra/"; private static final String STORAGE_CONFIG_NAME = "cassandra.yaml"; public static GraknConfig graknConfig(){ return GraknConfig.read(graknConfigPath().toFile()); } public static StorageConfig storageConfig(){ return StorageConfig.from(storageConfigPath()); } public static Path graknConfigPath(){ return Paths.get(GraknSystemProperty.CONFIGURATION_FILE.value()); } /** paths relative to dist dir **/ public static Path storageConfigPath(){ return Paths.get(STORAGE_CONFIG_PATH, STORAGE_CONFIG_NAME); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup/config/ProcessConfig.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.bootup.config; import ai.grakn.engine.GraknConfig; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.util.Map; /** * * @param <V> config parameter value type * * @author Kasper Piskorski */ public abstract class ProcessConfig<V> { private final ImmutableMap<String, V> params; ProcessConfig(Map<String, V> params) { this.params = ImmutableMap.copyOf(params); } public ImmutableMap<String, V> params() { return params; } Map<String, V> updateParamsFromMap(Map<String, V> newParams){ Map<String, V> updatedParams = Maps.newHashMap(params()); updatedParams.putAll(newParams); return updatedParams; } Map<String, V> updateParamsFromConfig(String CONFIG_PARAM_PREFIX, GraknConfig config) { //overwrite params with params from grakn config Map<String, V> updatedParams = Maps.newHashMap(params()); config.properties() .stringPropertyNames() .stream() .filter(prop -> prop.contains(CONFIG_PARAM_PREFIX)) .forEach(prop -> { String param = prop.replaceAll(CONFIG_PARAM_PREFIX, ""); if (updatedParams.containsKey(param)) { Map.Entry<String, V> entry = propToEntry(param, prop); updatedParams.put(entry.getKey(), entry.getValue()); } }); return updatedParams; } abstract Map.Entry<String, V> propToEntry(String param, String value); public abstract String toConfigString(); public abstract ProcessConfig updateGenericParams(GraknConfig config); public abstract ProcessConfig updateFromConfig(GraknConfig config); }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup/config/QueueConfig.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.bootup.config; import ai.grakn.GraknConfigKey; import ai.grakn.engine.GraknConfig; import com.google.common.collect.ImmutableMap; import java.nio.file.Path; import java.nio.file.Paths; import java.util.AbstractMap; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; /** * Container class for storing and manipulating queue configuration. * NB: * - Redis allows for multiple value params hence we need a map of lists. * - Redis data dir must already exist when starting redis * * @author Kasper Piskorski */ public class QueueConfig extends ProcessConfig<List<Object>>{ private static final String CONFIG_PARAM_PREFIX = "queue.internal."; private static final String LOG_FILE = "grakn-queue.log"; private static final String DATA_SUBDIR = "redis/"; private static final String DB_DIR_CONFIG_KEY = "dir"; private static final String LOG_DIR_CONFIG_KEY = "logfile"; private static final String RECORD_SEPARATOR = "\n"; private static final String KEY_VALUE_SEPARATOR = " "; private QueueConfig(Map<String, List<Object>> params) { super(params); } public static QueueConfig of(Map<String, List<Object>> params) { return new QueueConfig(params); } public static QueueConfig from(Path configPath){ return of(parseFileToMap(configPath));} private static Map<String, List<Object>> parseFileToMap(Path configPath){ Map<String, List<Object>> map = new HashMap<>(); try { PropertiesConfiguration props = new PropertiesConfiguration(configPath.toFile()); props.getKeys().forEachRemaining(key -> map.put(key, props.getList(key))); } catch (ConfigurationException e) { e.printStackTrace(); } return map; } @Override Map.Entry<String, List<Object>> propToEntry(String param, String value) { return new AbstractMap.SimpleImmutableEntry<>(param, Collections.singletonList(value)); } @Override public String toConfigString() { return params().entrySet().stream() .flatMap(e -> e.getValue().stream().map(value -> new AbstractMap.SimpleImmutableEntry<>(e.getKey(), value))) .map(e -> e.getKey() + KEY_VALUE_SEPARATOR + e.getValue()) .collect(Collectors.joining(RECORD_SEPARATOR)); } private Path getAbsoluteLogPath(GraknConfig config){ //NB redis gets confused with relative log paths Path projectPath = GraknConfig.PROJECT_PATH; String logPathString = config.getProperty(GraknConfigKey.LOG_DIR) + LOG_FILE; Path logPath = Paths.get(logPathString); return logPath.isAbsolute() ? logPath : Paths.get(projectPath.toString(), logPathString); } private QueueConfig updateDirs(GraknConfig config) { String dbDir = config.getProperty(GraknConfigKey.DATA_DIR); ImmutableMap<String, List<Object>> dirParams = ImmutableMap.of( DB_DIR_CONFIG_KEY, Collections.singletonList("\"" + dbDir + DATA_SUBDIR + "\""), LOG_DIR_CONFIG_KEY, Collections.singletonList("\"" + getAbsoluteLogPath(config) + "\"") ); return new QueueConfig(this.updateParamsFromMap(dirParams)); } @Override public QueueConfig updateGenericParams(GraknConfig config) { return new QueueConfig(this.updateParamsFromConfig(CONFIG_PARAM_PREFIX, config)); } @Override public QueueConfig updateFromConfig(GraknConfig config) { return this .updateGenericParams(config) .updateDirs(config); } }
0
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup
java-sources/ai/grakn/grakn-engine/1.4.3/ai/grakn/engine/bootup/config/StorageConfig.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.bootup.config; import ai.grakn.GraknConfigKey; import ai.grakn.engine.GraknConfig; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.AbstractMap; import java.util.Collections; import java.util.Map; /** * Container class for storing and manipulating storage configuration. * * @author Kasper Piskorski */ public class StorageConfig extends ProcessConfig<Object> { private static final String EMPTY_VALUE = ""; private static final String CONFIG_PARAM_PREFIX = "storage.internal."; private static final String SAVED_CACHES_DIR_CONFIG_VALUE = "cassandra/saved_caches"; private static final String COMMITLOG_DIR_CONFIG_VALUE = "cassandra/commitlog"; private static final String DATA_FILE_DIR_CONFIG_VALUE = "cassandra/data"; private static final String CDC_RAW_DIR_CONFIG_VALUE = "cassandra/cdc_raw"; private static final String HINTS_DIR_CONFIG_VALUE = "cassandra/hints"; private static final String DATA_FILE_DIR_CONFIG_KEY = "data_file_directories"; private static final String CDC_RAW_DIR_CONFIG_KEY = "cdc_raw_directory"; private static final String HINTS_DIR_CONFIG_KEY = "hints_directory"; private static final String SAVED_CACHES_DIR_CONFIG_KEY = "saved_caches_directory"; private static final String COMMITLOG_DIR_CONFIG_KEY = "commitlog_directory"; private StorageConfig(Map<String, Object> yamlParams){ super(yamlParams); } public static StorageConfig of(String yaml) { return new StorageConfig(StorageConfig.parseStringToMap(yaml)); } public static StorageConfig from(Path configPath){ String configString = ConfigProcessor.getConfigStringFromFile(configPath); return of(configString); } private static Map<String, Object> parseStringToMap(String yaml){ ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)); try { TypeReference<Map<String, Object>> reference = new TypeReference<Map<String, Object>>(){}; Map<String, Object> yamlParams = mapper.readValue(yaml, reference); return Maps.transformValues(yamlParams, value -> value == null ? EMPTY_VALUE : value); } catch (IOException e) { throw new RuntimeException(e); } } @Override Map.Entry<String, Object> propToEntry(String key, String value) { return new AbstractMap.SimpleImmutableEntry<>(key, value); } @Override public String toConfigString() { ObjectMapper mapper = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)); try { ByteArrayOutputStream outputstream = new ByteArrayOutputStream(); mapper.writeValue(outputstream, params()); return outputstream.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new RuntimeException(e); } } private StorageConfig updateDirs(GraknConfig config) { String dbDir = config.getProperty(GraknConfigKey.DATA_DIR); ImmutableMap<String, Object> dirParams = ImmutableMap.of( DATA_FILE_DIR_CONFIG_KEY, Collections.singletonList(dbDir + DATA_FILE_DIR_CONFIG_VALUE), SAVED_CACHES_DIR_CONFIG_KEY, dbDir + SAVED_CACHES_DIR_CONFIG_VALUE, COMMITLOG_DIR_CONFIG_KEY, dbDir + COMMITLOG_DIR_CONFIG_VALUE, CDC_RAW_DIR_CONFIG_KEY, dbDir + CDC_RAW_DIR_CONFIG_VALUE, HINTS_DIR_CONFIG_KEY, dbDir + HINTS_DIR_CONFIG_VALUE ); return new StorageConfig(this.updateParamsFromMap(dirParams)); } @Override Map<String, Object> updateParamsFromConfig(String CONFIG_PARAM_PREFIX, GraknConfig config) { //overwrite params with params from grakn config Map<String, Object> updatedParams = Maps.newHashMap(params()); config.properties() .stringPropertyNames() .stream() .filter(prop -> prop.contains(CONFIG_PARAM_PREFIX)) .forEach(prop -> { String param = prop.replaceAll(CONFIG_PARAM_PREFIX, ""); if (updatedParams.containsKey(param)) { updatedParams.put(param, config.properties().getProperty(prop)); } }); return updatedParams; } @Override public StorageConfig updateGenericParams(GraknConfig config) { return new StorageConfig(this.updateParamsFromConfig(CONFIG_PARAM_PREFIX, config)); } @Override public StorageConfig updateFromConfig(GraknConfig config){ return this .updateGenericParams(config) .updateDirs(config); } }
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/controller/ConceptController.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; import ai.grakn.GraknTx; import ai.grakn.Keyspace; import ai.grakn.concept.Attribute; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import ai.grakn.concept.Type; import ai.grakn.engine.Jacksonisable; import ai.grakn.engine.controller.response.Concept; import ai.grakn.engine.controller.response.ConceptBuilder; import ai.grakn.engine.controller.response.EmbeddedAttribute; import ai.grakn.engine.controller.response.Link; import ai.grakn.engine.controller.response.ListResource; import ai.grakn.engine.controller.response.RolePlayer; import ai.grakn.engine.controller.response.Things; import ai.grakn.engine.controller.util.Requests; import ai.grakn.engine.factory.EngineGraknTxFactory; import ai.grakn.util.REST.WebPath; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import spark.Request; import spark.Response; import spark.Service; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static ai.grakn.GraknTxType.READ; import static ai.grakn.engine.controller.util.Requests.mandatoryPathParameter; import static ai.grakn.engine.controller.util.Requests.queryParameter; import static ai.grakn.util.REST.Request.ID_PARAMETER; import static ai.grakn.util.REST.Request.KEYSPACE_PARAM; import static ai.grakn.util.REST.Request.LABEL_PARAMETER; import static ai.grakn.util.REST.Request.LIMIT_PARAMETER; import static ai.grakn.util.REST.Request.OFFSET_PARAMETER; import static ai.grakn.util.REST.Response.ContentType.APPLICATION_ALL; import static ai.grakn.util.REST.Response.ContentType.APPLICATION_JSON; import static com.codahale.metrics.MetricRegistry.name; import static org.apache.http.HttpStatus.SC_NOT_FOUND; import static org.apache.http.HttpStatus.SC_OK; /** * Endpoints used to query for {@link ai.grakn.concept.Concept}s * * @author Grakn Warriors */ public class ConceptController implements HttpController { private static final ObjectMapper objectMapper = new ObjectMapper(); private EngineGraknTxFactory factory; private Timer conceptIdGetTimer; private Timer labelGetTimer; private Timer instancesGetTimer; public ConceptController(EngineGraknTxFactory factory, MetricRegistry metricRegistry){ this.factory = factory; this.conceptIdGetTimer = metricRegistry.timer(name(ConceptController.class, "concept-by-identifier")); this.labelGetTimer = metricRegistry.timer(name(ConceptController.class, "concept-by-label")); this.instancesGetTimer = metricRegistry.timer(name(ConceptController.class, "instances-of-type")); } @Override public void start(Service spark) { spark.get(WebPath.CONCEPT_ID, this::getConceptById); spark.get(WebPath.TYPE_LABEL, this::getSchemaByLabel); spark.get(WebPath.RULE_LABEL, this::getSchemaByLabel); spark.get(WebPath.ROLE_LABEL, this::getSchemaByLabel); spark.get(WebPath.KEYSPACE_TYPE, this::getTypes); spark.get(WebPath.KEYSPACE_RULE, this::getRules); spark.get(WebPath.KEYSPACE_ROLE, this::getRoles); spark.get(WebPath.CONCEPT_ATTRIBUTES, this::getAttributes); spark.get(WebPath.CONCEPT_KEYS, this::getKeys); spark.get(WebPath.CONCEPT_RELATIONSHIPS, this::getRelationships); spark.get(WebPath.TYPE_INSTANCES, this::getTypeInstances); spark.get(WebPath.TYPE_PLAYS, this::getTypePlays); spark.get(WebPath.TYPE_ATTRIBUTES, this::getTypeAttributes); spark.get(WebPath.TYPE_KEYS, this::getTypeKeys); spark.get(WebPath.TYPE_SUBS, this::getSchemaConceptSubs); spark.get(WebPath.ROLE_SUBS, this::getSchemaConceptSubs); spark.get(WebPath.RULE_SUBS, this::getSchemaConceptSubs); } private String getTypeAttributes(Request request, Response response) throws JsonProcessingException { Function<ai.grakn.concept.Type, Stream<Jacksonisable>> collector = type -> type.attributes().map(ConceptBuilder::build); return getConceptCollection(request, response, "attributes", buildTypeGetter(request), collector); } private String getTypeKeys(Request request, Response response) throws JsonProcessingException { Function<ai.grakn.concept.Type, Stream<Jacksonisable>> collector = type -> type.keys().map(ConceptBuilder::build); return getConceptCollection(request, response, "keys", buildTypeGetter(request), collector); } private String getTypePlays(Request request, Response response) throws JsonProcessingException { Function<ai.grakn.concept.Type, Stream<Jacksonisable>> collector = type -> type.playing().map(ConceptBuilder::build); return getConceptCollection(request, response, "plays", buildTypeGetter(request), collector); } private String getRelationships(Request request, Response response) throws JsonProcessingException { //TODO: Figure out how to incorporate offset and limit Function<ai.grakn.concept.Thing, Stream<Jacksonisable>> collector = thing -> thing.roles().flatMap(role -> { Link roleWrapper = Link.create(role); return thing.relationships(role).map(relationship -> { Link relationshipWrapper = Link.create(relationship); return RolePlayer.create(roleWrapper, relationshipWrapper); }); }); return this.getConceptCollection(request, response, "relationships", buildThingGetter(request), collector); } private String getKeys(Request request, Response response) throws JsonProcessingException { return getAttributes(request, response, thing -> thing.keys()); } private String getAttributes(Request request, Response response) throws JsonProcessingException { return getAttributes(request, response, thing -> thing.attributes()); } private String getAttributes(Request request, Response response, Function<ai.grakn.concept.Thing, Stream<Attribute<?>>> attributeFetcher) throws JsonProcessingException { int offset = getOffset(request); int limit = getLimit(request); Function<ai.grakn.concept.Thing, Stream<Jacksonisable>> collector = thing -> attributeFetcher.apply(thing).skip(offset).limit(limit).map(EmbeddedAttribute::create); return this.getConceptCollection(request, response, "attributes", buildThingGetter(request), collector); } private <X extends ai.grakn.concept.Concept> String getConceptCollection( Request request, Response response, String key, Function<GraknTx, X> getter, Function<X, Stream<Jacksonisable>> collector ) throws JsonProcessingException { response.type(APPLICATION_JSON); Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM)); try (GraknTx tx = factory.tx(keyspace, READ); Timer.Context context = labelGetTimer.time()) { X concept = getter.apply(tx); //If the concept was not found return; if(concept == null){ response.status(SC_NOT_FOUND); return "[]"; } List<Jacksonisable> list = collector.apply(concept).collect(Collectors.toList()); Link link = Link.create(request.pathInfo()); ListResource<Jacksonisable> listResource = ListResource.create(link, key, list); return objectMapper.writeValueAsString(listResource); } } private String getSchemaConceptSubs(Request request, Response response) throws JsonProcessingException { Function<ai.grakn.concept.SchemaConcept, Stream<Jacksonisable>> collector = schema -> schema.subs().map(ConceptBuilder::build); return getConceptCollection(request, response, "subs", buildSchemaConceptGetter(request), collector); } private String getTypeInstances(Request request, Response response) throws JsonProcessingException { response.type(APPLICATION_JSON); Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM)); Label label = Label.of(mandatoryPathParameter(request, LABEL_PARAMETER)); int offset = getOffset(request); int limit = getLimit(request); try (GraknTx tx = factory.tx(keyspace, READ); Timer.Context context = instancesGetTimer.time()) { Type type = tx.getType(label); if(type == null){ response.status(SC_NOT_FOUND); return ""; } //Get the wrapper Things things = ConceptBuilder.buildThings(type, offset, limit); response.status(SC_OK); return objectMapper.writeValueAsString(things); } } private int getOffset(Request request){ return getIntegerQueryParameter(request, OFFSET_PARAMETER, 0); } private int getLimit(Request request){ return getIntegerQueryParameter(request, LIMIT_PARAMETER, 100); } private int getIntegerQueryParameter(Request request, String parameter, int defaultValue){ String value = queryParameter(request, parameter); return value != null ? Integer.parseInt(value) : defaultValue; } private String getSchemaByLabel(Request request, Response response) throws JsonProcessingException { Requests.validateRequest(request, APPLICATION_ALL, APPLICATION_JSON); Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM)); Label label = Label.of(mandatoryPathParameter(request, LABEL_PARAMETER)); return getConcept(response, keyspace, (tx) -> tx.getSchemaConcept(label)); } private String getConceptById(Request request, Response response) throws JsonProcessingException { Requests.validateRequest(request, APPLICATION_ALL, APPLICATION_JSON); Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM)); ConceptId conceptId = ConceptId.of(mandatoryPathParameter(request, ID_PARAMETER)); return getConcept(response, keyspace, (tx) -> tx.getConcept(conceptId)); } private String getConcept(Response response, Keyspace keyspace, Function<GraknTx, ai.grakn.concept.Concept> getter) throws JsonProcessingException { response.type(APPLICATION_JSON); try (GraknTx tx = factory.tx(keyspace, READ); Timer.Context context = conceptIdGetTimer.time()) { ai.grakn.concept.Concept concept = getter.apply(tx); if(concept != null){ response.status(SC_OK); return objectMapper.writeValueAsString(ConceptBuilder.build(concept)); } else { response.status(SC_NOT_FOUND); return ""; } } } private String getTypes(Request request, Response response) throws JsonProcessingException { return getConcepts(request, response, "types", (tx) -> tx.admin().getMetaConcept().subs()); } private String getRules(Request request, Response response) throws JsonProcessingException { return getConcepts(request, response, "rules", (tx) -> tx.admin().getMetaRule().subs()); } private String getRoles(Request request, Response response) throws JsonProcessingException { return getConcepts(request, response, "roles", (tx) -> tx.admin().getMetaRole().subs()); } private String getConcepts( Request request, Response response, String key, Function<GraknTx, Stream<? extends ai.grakn.concept.Concept>> getter ) throws JsonProcessingException { response.type(APPLICATION_JSON); Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM)); try (GraknTx tx = factory.tx(keyspace, READ); Timer.Context context = labelGetTimer.time()) { List<Concept> concepts = getter.apply(tx).map(ConceptBuilder::<Concept>build).collect(Collectors.toList()); ListResource list = ListResource.create(Requests.selfLink(request), key, concepts); response.status(SC_OK); return objectMapper.writeValueAsString(list); } } /** * Helper method used to build a function which will get a {@link ai.grakn.concept.SchemaConcept} by {@link Label} * * @param request The request which contains the {@link Label} * @return a function which can retrieve a {@link ai.grakn.concept.SchemaConcept} by {@link Label} */ private static Function<GraknTx, ai.grakn.concept.SchemaConcept> buildSchemaConceptGetter(Request request){ Label label = Label.of(mandatoryPathParameter(request, LABEL_PARAMETER)); return tx -> tx.getSchemaConcept(label); } /** * Helper method used to build a function which will get a {@link ai.grakn.concept.Type} by {@link Label} * * @param request The request which contains the {@link Label} * @return a function which can retrieve a {@link ai.grakn.concept.Type} by {@link Label} */ private static Function<GraknTx, ai.grakn.concept.Type> buildTypeGetter(Request request){ Label label = Label.of(mandatoryPathParameter(request, LABEL_PARAMETER)); return tx -> tx.getType(label); } /** * Helper method used to build a function which will get a {@link ai.grakn.concept.Thing} by {@link ConceptId} * * @param request The request which contains the {@link ConceptId} * @return a function which can retrieve a {@link ai.grakn.concept.Thing} by {@link ConceptId} */ private static Function<GraknTx, ai.grakn.concept.Thing> buildThingGetter(Request request){ ConceptId conceptId = ConceptId.of(mandatoryPathParameter(request, ID_PARAMETER)); return tx -> { ai.grakn.concept.Concept concept = tx.getConcept(conceptId); if(concept == null || !concept.isThing()) return null; return concept.asThing(); }; } }
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/controller/GraqlController.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; import ai.grakn.GraknTx; import ai.grakn.GraknTxType; import ai.grakn.Keyspace; import ai.grakn.engine.attribute.deduplicator.AttributeDeduplicatorDaemon; import ai.grakn.engine.controller.response.ExplanationBuilder; import ai.grakn.engine.controller.util.Requests; import ai.grakn.engine.factory.EngineGraknTxFactory; import ai.grakn.exception.GraknTxOperationException; import ai.grakn.exception.GraqlQueryException; import ai.grakn.exception.GraqlSyntaxException; import ai.grakn.exception.InvalidKBException; import ai.grakn.exception.TemporaryWriteException; import ai.grakn.graql.GetQuery; import ai.grakn.graql.Query; import ai.grakn.graql.QueryBuilder; import ai.grakn.graql.QueryParser; import ai.grakn.graql.answer.ConceptMap; import ai.grakn.graql.internal.printer.Printer; import ai.grakn.graql.internal.query.answer.ConceptMapImpl; import ai.grakn.kb.internal.EmbeddedGraknTx; import ai.grakn.util.REST; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rholder.retry.Attempt; import com.github.rholder.retry.RetryException; import com.github.rholder.retry.RetryListener; import com.github.rholder.retry.Retryer; import com.github.rholder.retry.RetryerBuilder; import com.github.rholder.retry.StopStrategies; import com.github.rholder.retry.WaitStrategies; import mjson.Json; import org.apache.commons.lang.StringUtils; import org.apache.http.entity.ContentType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Request; import spark.Response; import spark.Service; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import java.util.List; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import static ai.grakn.engine.controller.util.Requests.mandatoryBody; import static ai.grakn.engine.controller.util.Requests.mandatoryPathParameter; import static ai.grakn.engine.controller.util.Requests.mandatoryQueryParameter; import static ai.grakn.engine.controller.util.Requests.queryParameter; import static ai.grakn.util.REST.Request.Graql.ALLOW_MULTIPLE_QUERIES; import static ai.grakn.util.REST.Request.Graql.DEFINE_ALL_VARS; import static ai.grakn.util.REST.Request.Graql.EXECUTE_WITH_INFERENCE; import static ai.grakn.util.REST.Request.Graql.LOADING_DATA; import static ai.grakn.util.REST.Request.Graql.QUERY; import static ai.grakn.util.REST.Request.Graql.TX_TYPE; import static ai.grakn.util.REST.Request.KEYSPACE_PARAM; import static ai.grakn.util.REST.Response.ContentType.APPLICATION_JSON; import static ai.grakn.util.REST.Response.ContentType.APPLICATION_TEXT; import static com.codahale.metrics.MetricRegistry.name; import static java.lang.Boolean.parseBoolean; import static org.apache.http.HttpStatus.SC_OK; /** * Endpoints used to query the graph using Graql and build a HAL, Graql or Json response. * * @author Marco Scoppetta */ public class GraqlController implements HttpController { private static final ObjectMapper mapper = new ObjectMapper(); private static final Logger LOG = LoggerFactory.getLogger(GraqlController.class); private static final RetryLogger retryLogger = new RetryLogger(); private static final int MAX_RETRY = 10; private final Printer printer; private final EngineGraknTxFactory factory; private AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon; private final Timer executeGraql; private final Timer executeExplanation; public GraqlController( EngineGraknTxFactory factory, AttributeDeduplicatorDaemon AttributeDeduplicatorDaemon, Printer printer, MetricRegistry metricRegistry ) { this.factory = factory; this.AttributeDeduplicatorDaemon = AttributeDeduplicatorDaemon; this.printer = printer; this.executeGraql = metricRegistry.timer(name(GraqlController.class, "execute-graql")); this.executeExplanation = metricRegistry.timer(name(GraqlController.class, "execute-explanation")); } @Override public void start(Service spark) { spark.post(REST.WebPath.KEYSPACE_GRAQL, this::executeGraql); spark.get(REST.WebPath.KEYSPACE_EXPLAIN, this::explainGraql); spark.exception(GraqlQueryException.class, (e, req, res) -> handleError(400, e, res)); spark.exception(GraqlSyntaxException.class, (e, req, res) -> handleError(400, e, res)); // Handle invalid type castings and invalid insertions spark.exception(GraknTxOperationException.class, (e, req, res) -> handleError(422, e, res)); spark.exception(InvalidKBException.class, (e, req, res) -> handleError(422, e, res)); } @GET @Path("/kb/{keyspace}/explain") private String explainGraql(Request request, Response response) throws RetryException, ExecutionException { Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM)); String queryString = mandatoryQueryParameter(request, QUERY); response.status(SC_OK); return executeFunctionWithRetrying(() -> { try (GraknTx tx = factory.tx(keyspace, GraknTxType.WRITE); Timer.Context context = executeExplanation.time()) { ConceptMap answer = tx.graql().infer(true).parser().<GetQuery>parseQuery(queryString).execute().stream().findFirst().orElse(new ConceptMapImpl()); return mapper.writeValueAsString(ExplanationBuilder.buildExplanation(answer)); } }); } @POST @Path("/kb/{keyspace}/graql") private String executeGraql(Request request, Response response) throws RetryException, ExecutionException { Keyspace keyspace = Keyspace.of(mandatoryPathParameter(request, KEYSPACE_PARAM)); String queryString = mandatoryBody(request); //Run the query with reasoning on or off Boolean infer = parseBoolean(queryParameter(request, EXECUTE_WITH_INFERENCE)); //Allow multiple queries to be executed boolean multiQuery = parseBoolean(queryParameter(request, ALLOW_MULTIPLE_QUERIES)); //Define all anonymous variables in the query Boolean defineAllVars = parseBoolean(queryParameter(request, DEFINE_ALL_VARS)); //Used to check if serialisation of results is needed. When loading we skip this for the sake of speed boolean skipSerialisation = parseBoolean(queryParameter(request, LOADING_DATA)); //Check the transaction type to use String txStr = queryParameter(request, TX_TYPE); GraknTxType txType = txStr != null ? GraknTxType.valueOf(txStr.toUpperCase(Locale.getDefault())) : GraknTxType.WRITE; //This is used to determine the response format //TODO: Maybe we should really try to stick with one representation? This would require dashboard console interpreting the json representation final String acceptType; if (APPLICATION_TEXT.equals(Requests.getAcceptType(request))) { acceptType = APPLICATION_TEXT; } else { acceptType = APPLICATION_JSON; } response.type(APPLICATION_JSON); //Execute the query and get the results LOG.debug("Executing graql query: {}", StringUtils.abbreviate(queryString, 100)); LOG.trace("Full query: {}", queryString); return executeFunctionWithRetrying(() -> { try (EmbeddedGraknTx<?> tx = factory.tx(keyspace, txType); Timer.Context context = executeGraql.time()) { QueryBuilder builder = tx.graql(); if (infer != null) builder.infer(infer); QueryParser parser = builder.parser(); if (defineAllVars != null) parser.defineAllVars(defineAllVars); response.status(SC_OK); return executeQuery(tx, queryString, acceptType, multiQuery, skipSerialisation, parser); } finally { LOG.debug("Executed graql query"); } }); } private String executeFunctionWithRetrying(Callable<String> callable) throws RetryException, ExecutionException { try { Retryer<String> retryer = RetryerBuilder.<String>newBuilder() .retryIfExceptionOfType(TemporaryWriteException.class) .withRetryListener(retryLogger) .withWaitStrategy(WaitStrategies.exponentialWait(100, 5, TimeUnit.MINUTES)) .withStopStrategy(StopStrategies.stopAfterAttempt(MAX_RETRY)) .build(); return retryer.call(callable); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw e; } } } private static class RetryLogger implements RetryListener { @Override public <V> void onRetry(Attempt<V> attempt) { if (attempt.hasException()) { LOG.warn("Retrying transaction after {" + attempt.getAttemptNumber() + "} attempts due to exception {" + attempt.getExceptionCause().getMessage() + "}"); } } } /** * Handle any {@link Exception} that are thrown by the server. Configures and returns * the correct JSON response with the given status. * * @param exception exception thrown by the server * @param response response to the client */ private static void handleError(int status, Exception exception, Response response) { LOG.error("REST error", exception); response.status(status); response.body(Json.object("exception", exception.getMessage()).toString()); response.type(ContentType.APPLICATION_JSON.getMimeType()); } /** * Execute a query and return a response in the format specified by the request. * * @param tx open transaction to current graph * @param queryString read query to be executed * @param acceptType response format that the client will accept * @param multi execute multiple statements * @param parser */ private String executeQuery(EmbeddedGraknTx<?> tx, String queryString, String acceptType, boolean multi, boolean skipSerialisation, QueryParser parser) throws JsonProcessingException { // By default use Jackson printer Printer<?> printer = this.printer; if (APPLICATION_TEXT.equals(acceptType)) printer = Printer.stringPrinter(false); String formatted; boolean commitQuery = true; if (multi) { Stream<Query<?>> query = parser.parseList(queryString); List<?> collectedResults = query.map(this::executeAndMonitor).collect(Collectors.toList()); if (skipSerialisation) { formatted = mapper.writeValueAsString(new Object[collectedResults.size()]); } else { formatted = printer.toString(collectedResults); } } else { Query<?> query = parser.parseQuery(queryString); if (skipSerialisation) { formatted = ""; } else { // If acceptType is 'application/text' add new line after every result if (APPLICATION_TEXT.equals(acceptType)) { formatted = printer.toStream(query.stream()).collect(Collectors.joining("\n")); } else { // If acceptType is 'application/json' map results to JSON representation formatted = printer.toString(executeAndMonitor(query)); } } commitQuery = !query.isReadOnly(); } if (commitQuery) { tx.commitAndGetLogs().ifPresent(commitLog -> commitLog.attributes().forEach((value, conceptIds) -> conceptIds.forEach(id -> AttributeDeduplicatorDaemon.markForDeduplication(commitLog.keyspace(), value, id)) ) ); } return formatted; } private Object executeAndMonitor(Query<?> query) { return query.execute(); } }
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/controller/HttpController.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; import spark.Service; /** * Interface implemented by all HTTPControllers * * @author marcoscoppetta */ public interface HttpController { void start(Service spark); }
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/controller/SystemController.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; import ai.grakn.GraknConfigKey; import ai.grakn.engine.GraknConfig; import ai.grakn.engine.KeyspaceStore; import ai.grakn.engine.ServerStatus; import ai.grakn.engine.controller.response.Keyspace; import ai.grakn.engine.controller.response.Keyspaces; import ai.grakn.engine.controller.response.Root; import ai.grakn.engine.controller.util.Requests; import ai.grakn.exception.GraknServerException; import ai.grakn.util.GraknVersion; import ai.grakn.util.REST; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.json.MetricsModule; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.dropwizard.DropwizardExports; import io.prometheus.client.exporter.common.TextFormat; import org.apache.commons.io.Charsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Request; import spark.Response; import spark.Service; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.nio.file.Files; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static ai.grakn.util.REST.Request.FORMAT; import static ai.grakn.util.REST.Request.KEYSPACE_PARAM; import static ai.grakn.util.REST.Response.ContentType.APPLICATION_JSON; import static org.apache.http.HttpHeaders.CACHE_CONTROL; /** * * This controller allows to get information about existing {@link ai.grakn.Keyspace}s * and check status of Grakn Server, collects Metrics and return Dashboard index page. * * @author Filipe Peliz Pinto Teixeira */ public class SystemController implements HttpController { private static final String PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4"; private static final String PROMETHEUS = "prometheus"; private static final String JSON = "json"; private static final ObjectMapper objectMapper = new ObjectMapper(); private final Logger LOG = LoggerFactory.getLogger(SystemController.class); private final ServerStatus serverStatus; private final MetricRegistry metricRegistry; private final ObjectMapper mapper; private final CollectorRegistry prometheusRegistry; private final KeyspaceStore keyspaceStore; private final GraknConfig config; public SystemController(GraknConfig config, KeyspaceStore keyspaceStore, ServerStatus serverStatus, MetricRegistry metricRegistry) { this.keyspaceStore = keyspaceStore; this.config = config; this.serverStatus = serverStatus; this.metricRegistry = metricRegistry; DropwizardExports prometheusMetricWrapper = new DropwizardExports(metricRegistry); this.prometheusRegistry = new CollectorRegistry(); prometheusRegistry.register(prometheusMetricWrapper); final TimeUnit rateUnit = TimeUnit.SECONDS; final TimeUnit durationUnit = TimeUnit.SECONDS; final boolean showSamples = false; MetricFilter filter = MetricFilter.ALL; this.mapper = new ObjectMapper().registerModule( new MetricsModule(rateUnit, durationUnit, showSamples, filter)); } @Override public void start(Service spark) { spark.get(REST.WebPath.ROOT, this::getRoot); spark.get(REST.WebPath.KB, (req, res) -> getKeyspaces(res)); spark.get(REST.WebPath.KB_KEYSPACE, this::getKeyspace); spark.delete(REST.WebPath.KB_KEYSPACE, this::deleteKeyspace); spark.get(REST.WebPath.METRICS, this::getMetrics); spark.get(REST.WebPath.STATUS, (req, res) -> getStatus()); spark.get(REST.WebPath.VERSION, (req, res) -> getVersion()); } @GET @Path(REST.WebPath.ROOT) private String getRoot(Request request, Response response) throws JsonProcessingException { // Handle root here for JSON, otherwise redirect to HTML page if (Requests.getAcceptType(request).equals(APPLICATION_JSON)) { return getJsonRoot(response); } else { return getIndexPage(); } } private String getJsonRoot(Response response) throws JsonProcessingException { response.type(APPLICATION_JSON); Root root = Root.create(); return objectMapper.writeValueAsString(root); } private String getIndexPage() { try { return new String(Files.readAllBytes(dashboardHtml()), Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } private java.nio.file.Path dashboardHtml() { return config.getPath(GraknConfigKey.STATIC_FILES_PATH).resolve("dashboard.html"); } @GET @Path(REST.WebPath.VERSION) private String getVersion() { return GraknVersion.VERSION; } @GET @Path(REST.WebPath.KB) private String getKeyspaces(Response response) throws JsonProcessingException { response.type(APPLICATION_JSON); Set<Keyspace> keyspaces = keyspaceStore.keyspaces().stream(). map(Keyspace::of). collect(Collectors.toSet()); return objectMapper.writeValueAsString(Keyspaces.of(keyspaces)); } @GET @Path("/kb/{keyspace}") private String getKeyspace(Request request, Response response) throws JsonProcessingException { response.type(APPLICATION_JSON); ai.grakn.Keyspace keyspace = ai.grakn.Keyspace.of(Requests.mandatoryPathParameter(request, KEYSPACE_PARAM)); if (keyspaceStore.containsKeyspace(keyspace)) { response.status(HttpServletResponse.SC_OK); return objectMapper.writeValueAsString(Keyspace.of(keyspace)); } else { response.status(HttpServletResponse.SC_NOT_FOUND); return ""; } } @DELETE @Path("/kb/{keyspace}") private boolean deleteKeyspace(Request request, Response response) { ai.grakn.Keyspace keyspace = ai.grakn.Keyspace.of(Requests.mandatoryPathParameter(request, KEYSPACE_PARAM)); boolean deletionComplete = keyspaceStore.deleteKeyspace(keyspace); if (deletionComplete) { LOG.info("Keyspace {} deleted", keyspace); response.status(HttpServletResponse.SC_NO_CONTENT); return true; } else { throw GraknServerException.couldNotDelete(keyspace); } } @GET @Path("/status") private String getStatus() { return serverStatus.isReady() ? "READY" : "INITIALIZING"; } @GET @Path("/metrics") private String getMetrics(Request request, Response response) throws IOException { response.header(CACHE_CONTROL, "must-revalidate,no-cache,no-store"); response.status(HttpServletResponse.SC_OK); Optional<String> format = Optional.ofNullable(request.queryParams(FORMAT)); String dFormat = format.orElse(JSON); switch (dFormat) { case PROMETHEUS: // Prometheus format for the metrics response.type(PROMETHEUS_CONTENT_TYPE); final Writer writer1 = new StringWriter(); TextFormat.write004(writer1, this.prometheusRegistry.metricFamilySamples()); return writer1.toString(); case JSON: // Json/Dropwizard format response.type(APPLICATION_JSON); final ObjectWriter writer = mapper.writer(); try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { writer.writeValue(output, this.metricRegistry); return new String(output.toByteArray(), "UTF-8"); } default: throw GraknServerException.requestInvalidParameter(FORMAT, dFormat); } } }
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/controller/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 Grakn server REST endpoints. */ package ai.grakn.engine.controller;
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/Answer.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.answer.ConceptMap; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.auto.value.AutoValue; import java.util.Map; import java.util.stream.Collectors; /** * <p> * Response wrapper for {@link ConceptMap} * </p> * * @author Filipe Peliz Pinto Teixeira */ @AutoValue public abstract class Answer { @JsonValue public abstract Map<String, Concept> conceptMap(); @JsonCreator public static Answer create(Map<String, Concept> conceptMap){ return new AutoValue_Answer(conceptMap); } public static Answer create(ConceptMap map){ Map<String, Concept> conceptMap = map.map().entrySet().stream().collect(Collectors.toMap( entry -> entry.getKey().getValue(), entry -> ConceptBuilder.build(entry.getValue()) )); return create(conceptMap); } }
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/Attribute.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; /** * <p> * Wrapper class for {@link ai.grakn.concept.Attribute} * </p> * * @author Filipe Peliz Pinto Teixeira */ @AutoValue public abstract class Attribute extends Thing { @JsonProperty("data-type") public abstract String dataType(); @JsonProperty public abstract String value(); @JsonCreator public static Attribute 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("data-type") String dataType, @JsonProperty("value") String value){ return new AutoValue_Attribute(Schema.BaseType.ATTRIBUTE.name(), id, selfLink, type, attributes, keys, relationships, inferred, explanation, dataType, value); } }
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/AttributeType.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.AttributeType} * </p> * * @author Filipe Peliz Pinto Teixeira */ @AutoValue public abstract class AttributeType extends Type{ @Nullable @JsonProperty("data-type") public abstract String dataType(); @Nullable @JsonProperty public abstract String regex(); @JsonCreator public static AttributeType 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, @Nullable @JsonProperty("data-type") String dataType, @Nullable @JsonProperty("regex") String regex){ return new AutoValue_AttributeType(Schema.BaseType.ATTRIBUTE_TYPE.name(),id, selfLink, label, implicit, sup, subs, isAbstract, plays, attributes, keys, instances, dataType, regex); } }
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/AutoValue_Answer.java
package ai.grakn.engine.controller.response; import com.fasterxml.jackson.annotation.JsonValue; import java.util.Map; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Answer extends Answer { private final Map<String, Concept> conceptMap; AutoValue_Answer( Map<String, Concept> conceptMap) { if (conceptMap == null) { throw new NullPointerException("Null conceptMap"); } this.conceptMap = conceptMap; } @JsonValue @Override public Map<String, Concept> conceptMap() { return conceptMap; } @Override public String toString() { return "Answer{" + "conceptMap=" + conceptMap + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Answer) { Answer that = (Answer) o; return (this.conceptMap.equals(that.conceptMap())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.conceptMap.hashCode(); return h; } }
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/AutoValue_Attribute.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Attribute extends Attribute { private final String baseType; private final ConceptId id; private final Link selfLink; private final EmbeddedSchemaConcept type; private final Link attributes; private final Link keys; private final Link relationships; private final boolean inferred; private final String explanation; private final String dataType; private final String value; AutoValue_Attribute( String baseType, ConceptId id, Link selfLink, EmbeddedSchemaConcept type, Link attributes, Link keys, Link relationships, boolean inferred, @Nullable String explanation, String dataType, String value) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (type == null) { throw new NullPointerException("Null type"); } this.type = type; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; if (keys == null) { throw new NullPointerException("Null keys"); } this.keys = keys; if (relationships == null) { throw new NullPointerException("Null relationships"); } this.relationships = relationships; this.inferred = inferred; this.explanation = explanation; if (dataType == null) { throw new NullPointerException("Null dataType"); } this.dataType = dataType; if (value == null) { throw new NullPointerException("Null value"); } this.value = value; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public EmbeddedSchemaConcept type() { return type; } @JsonProperty @Override public Link attributes() { return attributes; } @JsonProperty @Override public Link keys() { return keys; } @JsonProperty @Override public Link relationships() { return relationships; } @JsonProperty @Override public boolean inferred() { return inferred; } @Nullable @JsonProperty(value = "explanation-query") @Override public String explanation() { return explanation; } @JsonProperty(value = "data-type") @Override public String dataType() { return dataType; } @JsonProperty @Override public String value() { return value; } @Override public String toString() { return "Attribute{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "type=" + type + ", " + "attributes=" + attributes + ", " + "keys=" + keys + ", " + "relationships=" + relationships + ", " + "inferred=" + inferred + ", " + "explanation=" + explanation + ", " + "dataType=" + dataType + ", " + "value=" + value + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Attribute) { Attribute that = (Attribute) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.type.equals(that.type())) && (this.attributes.equals(that.attributes())) && (this.keys.equals(that.keys())) && (this.relationships.equals(that.relationships())) && (this.inferred == that.inferred()) && ((this.explanation == null) ? (that.explanation() == null) : this.explanation.equals(that.explanation())) && (this.dataType.equals(that.dataType())) && (this.value.equals(that.value())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.type.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); h *= 1000003; h ^= this.keys.hashCode(); h *= 1000003; h ^= this.relationships.hashCode(); h *= 1000003; h ^= this.inferred ? 1231 : 1237; h *= 1000003; h ^= (explanation == null) ? 0 : this.explanation.hashCode(); h *= 1000003; h ^= this.dataType.hashCode(); h *= 1000003; h ^= this.value.hashCode(); return h; } }
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/AutoValue_AttributeType.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_AttributeType extends AttributeType { private final String baseType; private final ConceptId id; private final Link selfLink; private final Label label; private final Boolean implicit; private final EmbeddedSchemaConcept sup; private final Link subs; private final Boolean isAbstract; private final Link plays; private final Link attributes; private final Link keys; private final Link instances; private final String dataType; private final String regex; AutoValue_AttributeType( String baseType, ConceptId id, Link selfLink, Label label, Boolean implicit, @Nullable EmbeddedSchemaConcept sup, Link subs, Boolean isAbstract, Link plays, Link attributes, Link keys, Link instances, @Nullable String dataType, @Nullable String regex) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (label == null) { throw new NullPointerException("Null label"); } this.label = label; if (implicit == null) { throw new NullPointerException("Null implicit"); } this.implicit = implicit; this.sup = sup; if (subs == null) { throw new NullPointerException("Null subs"); } this.subs = subs; if (isAbstract == null) { throw new NullPointerException("Null isAbstract"); } this.isAbstract = isAbstract; if (plays == null) { throw new NullPointerException("Null plays"); } this.plays = plays; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; if (keys == null) { throw new NullPointerException("Null keys"); } this.keys = keys; if (instances == null) { throw new NullPointerException("Null instances"); } this.instances = instances; this.dataType = dataType; this.regex = regex; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public Label label() { return label; } @JsonProperty @Override public Boolean implicit() { return implicit; } @Nullable @JsonProperty(value = "super") @Override public EmbeddedSchemaConcept sup() { return sup; } @JsonProperty @Override public Link subs() { return subs; } @JsonProperty(value = "abstract") @Override public Boolean isAbstract() { return isAbstract; } @JsonProperty @Override public Link plays() { return plays; } @JsonProperty @Override public Link attributes() { return attributes; } @JsonProperty @Override public Link keys() { return keys; } @JsonProperty @Override public Link instances() { return instances; } @Nullable @JsonProperty(value = "data-type") @Override public String dataType() { return dataType; } @Nullable @JsonProperty @Override public String regex() { return regex; } @Override public String toString() { return "AttributeType{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "label=" + label + ", " + "implicit=" + implicit + ", " + "sup=" + sup + ", " + "subs=" + subs + ", " + "isAbstract=" + isAbstract + ", " + "plays=" + plays + ", " + "attributes=" + attributes + ", " + "keys=" + keys + ", " + "instances=" + instances + ", " + "dataType=" + dataType + ", " + "regex=" + regex + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof AttributeType) { AttributeType that = (AttributeType) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.label.equals(that.label())) && (this.implicit.equals(that.implicit())) && ((this.sup == null) ? (that.sup() == null) : this.sup.equals(that.sup())) && (this.subs.equals(that.subs())) && (this.isAbstract.equals(that.isAbstract())) && (this.plays.equals(that.plays())) && (this.attributes.equals(that.attributes())) && (this.keys.equals(that.keys())) && (this.instances.equals(that.instances())) && ((this.dataType == null) ? (that.dataType() == null) : this.dataType.equals(that.dataType())) && ((this.regex == null) ? (that.regex() == null) : this.regex.equals(that.regex())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.label.hashCode(); h *= 1000003; h ^= this.implicit.hashCode(); h *= 1000003; h ^= (sup == null) ? 0 : this.sup.hashCode(); h *= 1000003; h ^= this.subs.hashCode(); h *= 1000003; h ^= this.isAbstract.hashCode(); h *= 1000003; h ^= this.plays.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); h *= 1000003; h ^= this.keys.hashCode(); h *= 1000003; h ^= this.instances.hashCode(); h *= 1000003; h ^= (dataType == null) ? 0 : this.dataType.hashCode(); h *= 1000003; h ^= (regex == null) ? 0 : this.regex.hashCode(); return h; } }
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/AutoValue_EmbeddedAttribute.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_EmbeddedAttribute extends EmbeddedAttribute { private final ConceptId id; private final Link selfLink; private final EmbeddedSchemaConcept type; private final String value; private final String dataType; AutoValue_EmbeddedAttribute( ConceptId id, Link selfLink, EmbeddedSchemaConcept type, String value, String dataType) { if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (type == null) { throw new NullPointerException("Null type"); } this.type = type; if (value == null) { throw new NullPointerException("Null value"); } this.value = value; if (dataType == null) { throw new NullPointerException("Null dataType"); } this.dataType = dataType; } @JsonProperty @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public EmbeddedSchemaConcept type() { return type; } @JsonProperty @Override public String value() { return value; } @JsonProperty(value = "data-type") @Override public String dataType() { return dataType; } @Override public String toString() { return "EmbeddedAttribute{" + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "type=" + type + ", " + "value=" + value + ", " + "dataType=" + dataType + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof EmbeddedAttribute) { EmbeddedAttribute that = (EmbeddedAttribute) o; return (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.type.equals(that.type())) && (this.value.equals(that.value())) && (this.dataType.equals(that.dataType())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.type.hashCode(); h *= 1000003; h ^= this.value.hashCode(); h *= 1000003; h ^= this.dataType.hashCode(); return h; } }
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/AutoValue_EmbeddedSchemaConcept.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.Label; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_EmbeddedSchemaConcept extends EmbeddedSchemaConcept { private final Link selfLink; private final Label label; AutoValue_EmbeddedSchemaConcept( Link selfLink, Label label) { if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (label == null) { throw new NullPointerException("Null label"); } this.label = label; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public Label label() { return label; } @Override public String toString() { return "EmbeddedSchemaConcept{" + "selfLink=" + selfLink + ", " + "label=" + label + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof EmbeddedSchemaConcept) { EmbeddedSchemaConcept that = (EmbeddedSchemaConcept) o; return (this.selfLink.equals(that.selfLink())) && (this.label.equals(that.label())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.label.hashCode(); return h; } }
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/AutoValue_Entity.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Entity extends Entity { private final String baseType; private final ConceptId id; private final Link selfLink; private final EmbeddedSchemaConcept type; private final Link attributes; private final Link keys; private final Link relationships; private final boolean inferred; private final String explanation; AutoValue_Entity( String baseType, ConceptId id, Link selfLink, EmbeddedSchemaConcept type, Link attributes, Link keys, Link relationships, boolean inferred, @Nullable String explanation) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (type == null) { throw new NullPointerException("Null type"); } this.type = type; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; if (keys == null) { throw new NullPointerException("Null keys"); } this.keys = keys; if (relationships == null) { throw new NullPointerException("Null relationships"); } this.relationships = relationships; this.inferred = inferred; this.explanation = explanation; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public EmbeddedSchemaConcept type() { return type; } @JsonProperty @Override public Link attributes() { return attributes; } @JsonProperty @Override public Link keys() { return keys; } @JsonProperty @Override public Link relationships() { return relationships; } @JsonProperty @Override public boolean inferred() { return inferred; } @Nullable @JsonProperty(value = "explanation-query") @Override public String explanation() { return explanation; } @Override public String toString() { return "Entity{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "type=" + type + ", " + "attributes=" + attributes + ", " + "keys=" + keys + ", " + "relationships=" + relationships + ", " + "inferred=" + inferred + ", " + "explanation=" + explanation + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Entity) { Entity that = (Entity) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.type.equals(that.type())) && (this.attributes.equals(that.attributes())) && (this.keys.equals(that.keys())) && (this.relationships.equals(that.relationships())) && (this.inferred == that.inferred()) && ((this.explanation == null) ? (that.explanation() == null) : this.explanation.equals(that.explanation())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.type.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); h *= 1000003; h ^= this.keys.hashCode(); h *= 1000003; h ^= this.relationships.hashCode(); h *= 1000003; h ^= this.inferred ? 1231 : 1237; h *= 1000003; h ^= (explanation == null) ? 0 : this.explanation.hashCode(); return h; } }
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/AutoValue_EntityType.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_EntityType extends EntityType { private final String baseType; private final ConceptId id; private final Link selfLink; private final Label label; private final Boolean implicit; private final EmbeddedSchemaConcept sup; private final Link subs; private final Boolean isAbstract; private final Link plays; private final Link attributes; private final Link keys; private final Link instances; AutoValue_EntityType( String baseType, ConceptId id, Link selfLink, Label label, Boolean implicit, @Nullable EmbeddedSchemaConcept sup, Link subs, Boolean isAbstract, Link plays, Link attributes, Link keys, Link instances) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (label == null) { throw new NullPointerException("Null label"); } this.label = label; if (implicit == null) { throw new NullPointerException("Null implicit"); } this.implicit = implicit; this.sup = sup; if (subs == null) { throw new NullPointerException("Null subs"); } this.subs = subs; if (isAbstract == null) { throw new NullPointerException("Null isAbstract"); } this.isAbstract = isAbstract; if (plays == null) { throw new NullPointerException("Null plays"); } this.plays = plays; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; if (keys == null) { throw new NullPointerException("Null keys"); } this.keys = keys; if (instances == null) { throw new NullPointerException("Null instances"); } this.instances = instances; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public Label label() { return label; } @JsonProperty @Override public Boolean implicit() { return implicit; } @Nullable @JsonProperty(value = "super") @Override public EmbeddedSchemaConcept sup() { return sup; } @JsonProperty @Override public Link subs() { return subs; } @JsonProperty(value = "abstract") @Override public Boolean isAbstract() { return isAbstract; } @JsonProperty @Override public Link plays() { return plays; } @JsonProperty @Override public Link attributes() { return attributes; } @JsonProperty @Override public Link keys() { return keys; } @JsonProperty @Override public Link instances() { return instances; } @Override public String toString() { return "EntityType{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "label=" + label + ", " + "implicit=" + implicit + ", " + "sup=" + sup + ", " + "subs=" + subs + ", " + "isAbstract=" + isAbstract + ", " + "plays=" + plays + ", " + "attributes=" + attributes + ", " + "keys=" + keys + ", " + "instances=" + instances + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof EntityType) { EntityType that = (EntityType) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.label.equals(that.label())) && (this.implicit.equals(that.implicit())) && ((this.sup == null) ? (that.sup() == null) : this.sup.equals(that.sup())) && (this.subs.equals(that.subs())) && (this.isAbstract.equals(that.isAbstract())) && (this.plays.equals(that.plays())) && (this.attributes.equals(that.attributes())) && (this.keys.equals(that.keys())) && (this.instances.equals(that.instances())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.label.hashCode(); h *= 1000003; h ^= this.implicit.hashCode(); h *= 1000003; h ^= (sup == null) ? 0 : this.sup.hashCode(); h *= 1000003; h ^= this.subs.hashCode(); h *= 1000003; h ^= this.isAbstract.hashCode(); h *= 1000003; h ^= this.plays.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); h *= 1000003; h ^= this.keys.hashCode(); h *= 1000003; h ^= this.instances.hashCode(); return h; } }
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/AutoValue_Keyspace.java
package ai.grakn.engine.controller.response; import ai.grakn.API; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Keyspace extends Keyspace { private final ai.grakn.Keyspace value; AutoValue_Keyspace( ai.grakn.Keyspace value) { if (value == null) { throw new NullPointerException("Null value"); } this.value = value; } @API @CheckReturnValue @Override public ai.grakn.Keyspace value() { return value; } @Override public String toString() { return "Keyspace{" + "value=" + value + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Keyspace) { Keyspace that = (Keyspace) o; return (this.value.equals(that.value())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.value.hashCode(); return h; } }
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/AutoValue_Keyspaces.java
package ai.grakn.engine.controller.response; import ai.grakn.API; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Set; import javax.annotation.CheckReturnValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Keyspaces extends Keyspaces { private final Set<Keyspace> keyspaces; AutoValue_Keyspaces( Set<Keyspace> keyspaces) { if (keyspaces == null) { throw new NullPointerException("Null keyspaces"); } this.keyspaces = keyspaces; } @API @CheckReturnValue @JsonProperty @Override public Set<Keyspace> keyspaces() { return keyspaces; } @Override public String toString() { return "Keyspaces{" + "keyspaces=" + keyspaces + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Keyspaces) { Keyspaces that = (Keyspaces) o; return (this.keyspaces.equals(that.keyspaces())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.keyspaces.hashCode(); return h; } }
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/AutoValue_Link.java
package ai.grakn.engine.controller.response; import com.fasterxml.jackson.annotation.JsonValue; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Link extends Link { private final String id; AutoValue_Link( String id) { if (id == null) { throw new NullPointerException("Null id"); } this.id = id; } @JsonValue @Override public String id() { return id; } @Override public String toString() { return "Link{" + "id=" + id + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Link) { Link that = (Link) o; return (this.id.equals(that.id())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.id.hashCode(); return h; } }
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/AutoValue_ListResource.java
package ai.grakn.engine.controller.response; import java.util.List; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_ListResource<T> extends ListResource<T> { private final Link selfLink; private final String key; private final List<T> items; AutoValue_ListResource( Link selfLink, String key, List<T> items) { if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (key == null) { throw new NullPointerException("Null key"); } this.key = key; if (items == null) { throw new NullPointerException("Null items"); } this.items = items; } @Override public Link selfLink() { return selfLink; } @Override public String key() { return key; } @Override public List<T> items() { return items; } @Override public String toString() { return "ListResource{" + "selfLink=" + selfLink + ", " + "key=" + key + ", " + "items=" + items + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ListResource) { ListResource<?> that = (ListResource<?>) o; return (this.selfLink.equals(that.selfLink())) && (this.key.equals(that.key())) && (this.items.equals(that.items())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.key.hashCode(); h *= 1000003; h ^= this.items.hashCode(); return h; } }
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/AutoValue_MetaConcept.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_MetaConcept extends MetaConcept { private final String baseType; private final ConceptId id; private final Link selfLink; private final Label label; private final Boolean implicit; private final EmbeddedSchemaConcept sup; private final Link subs; private final Boolean isAbstract; private final Link plays; private final Link attributes; private final Link keys; private final Link instances; AutoValue_MetaConcept( String baseType, ConceptId id, Link selfLink, Label label, Boolean implicit, @Nullable EmbeddedSchemaConcept sup, Link subs, Boolean isAbstract, Link plays, Link attributes, Link keys, Link instances) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (label == null) { throw new NullPointerException("Null label"); } this.label = label; if (implicit == null) { throw new NullPointerException("Null implicit"); } this.implicit = implicit; this.sup = sup; if (subs == null) { throw new NullPointerException("Null subs"); } this.subs = subs; if (isAbstract == null) { throw new NullPointerException("Null isAbstract"); } this.isAbstract = isAbstract; if (plays == null) { throw new NullPointerException("Null plays"); } this.plays = plays; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; if (keys == null) { throw new NullPointerException("Null keys"); } this.keys = keys; if (instances == null) { throw new NullPointerException("Null instances"); } this.instances = instances; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public Label label() { return label; } @JsonProperty @Override public Boolean implicit() { return implicit; } @Nullable @JsonProperty(value = "super") @Override public EmbeddedSchemaConcept sup() { return sup; } @JsonProperty @Override public Link subs() { return subs; } @JsonProperty(value = "abstract") @Override public Boolean isAbstract() { return isAbstract; } @JsonProperty @Override public Link plays() { return plays; } @JsonProperty @Override public Link attributes() { return attributes; } @JsonProperty @Override public Link keys() { return keys; } @JsonProperty @Override public Link instances() { return instances; } @Override public String toString() { return "MetaConcept{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "label=" + label + ", " + "implicit=" + implicit + ", " + "sup=" + sup + ", " + "subs=" + subs + ", " + "isAbstract=" + isAbstract + ", " + "plays=" + plays + ", " + "attributes=" + attributes + ", " + "keys=" + keys + ", " + "instances=" + instances + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof MetaConcept) { MetaConcept that = (MetaConcept) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.label.equals(that.label())) && (this.implicit.equals(that.implicit())) && ((this.sup == null) ? (that.sup() == null) : this.sup.equals(that.sup())) && (this.subs.equals(that.subs())) && (this.isAbstract.equals(that.isAbstract())) && (this.plays.equals(that.plays())) && (this.attributes.equals(that.attributes())) && (this.keys.equals(that.keys())) && (this.instances.equals(that.instances())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.label.hashCode(); h *= 1000003; h ^= this.implicit.hashCode(); h *= 1000003; h ^= (sup == null) ? 0 : this.sup.hashCode(); h *= 1000003; h ^= this.subs.hashCode(); h *= 1000003; h ^= this.isAbstract.hashCode(); h *= 1000003; h ^= this.plays.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); h *= 1000003; h ^= this.keys.hashCode(); h *= 1000003; h ^= this.instances.hashCode(); return h; } }
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/AutoValue_Relationship.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Set; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Relationship extends Relationship { private final String baseType; private final ConceptId id; private final Link selfLink; private final EmbeddedSchemaConcept type; private final Link attributes; private final Link keys; private final Link relationships; private final boolean inferred; private final String explanation; private final Set<RolePlayer> roleplayers; AutoValue_Relationship( String baseType, ConceptId id, Link selfLink, EmbeddedSchemaConcept type, Link attributes, Link keys, Link relationships, boolean inferred, @Nullable String explanation, Set<RolePlayer> roleplayers) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (type == null) { throw new NullPointerException("Null type"); } this.type = type; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; if (keys == null) { throw new NullPointerException("Null keys"); } this.keys = keys; if (relationships == null) { throw new NullPointerException("Null relationships"); } this.relationships = relationships; this.inferred = inferred; this.explanation = explanation; if (roleplayers == null) { throw new NullPointerException("Null roleplayers"); } this.roleplayers = roleplayers; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public EmbeddedSchemaConcept type() { return type; } @JsonProperty @Override public Link attributes() { return attributes; } @JsonProperty @Override public Link keys() { return keys; } @JsonProperty @Override public Link relationships() { return relationships; } @JsonProperty @Override public boolean inferred() { return inferred; } @Nullable @JsonProperty(value = "explanation-query") @Override public String explanation() { return explanation; } @JsonProperty @Override public Set<RolePlayer> roleplayers() { return roleplayers; } @Override public String toString() { return "Relationship{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "type=" + type + ", " + "attributes=" + attributes + ", " + "keys=" + keys + ", " + "relationships=" + relationships + ", " + "inferred=" + inferred + ", " + "explanation=" + explanation + ", " + "roleplayers=" + roleplayers + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Relationship) { Relationship that = (Relationship) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.type.equals(that.type())) && (this.attributes.equals(that.attributes())) && (this.keys.equals(that.keys())) && (this.relationships.equals(that.relationships())) && (this.inferred == that.inferred()) && ((this.explanation == null) ? (that.explanation() == null) : this.explanation.equals(that.explanation())) && (this.roleplayers.equals(that.roleplayers())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.type.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); h *= 1000003; h ^= this.keys.hashCode(); h *= 1000003; h ^= this.relationships.hashCode(); h *= 1000003; h ^= this.inferred ? 1231 : 1237; h *= 1000003; h ^= (explanation == null) ? 0 : this.explanation.hashCode(); h *= 1000003; h ^= this.roleplayers.hashCode(); return h; } }
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/AutoValue_RelationshipType.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Set; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_RelationshipType extends RelationshipType { private final String baseType; private final ConceptId id; private final Link selfLink; private final Label label; private final Boolean implicit; private final EmbeddedSchemaConcept sup; private final Link subs; private final Boolean isAbstract; private final Link plays; private final Link attributes; private final Link keys; private final Link instances; private final Set<Link> relates; AutoValue_RelationshipType( String baseType, ConceptId id, Link selfLink, Label label, Boolean implicit, @Nullable EmbeddedSchemaConcept sup, Link subs, Boolean isAbstract, Link plays, Link attributes, Link keys, Link instances, Set<Link> relates) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (label == null) { throw new NullPointerException("Null label"); } this.label = label; if (implicit == null) { throw new NullPointerException("Null implicit"); } this.implicit = implicit; this.sup = sup; if (subs == null) { throw new NullPointerException("Null subs"); } this.subs = subs; if (isAbstract == null) { throw new NullPointerException("Null isAbstract"); } this.isAbstract = isAbstract; if (plays == null) { throw new NullPointerException("Null plays"); } this.plays = plays; if (attributes == null) { throw new NullPointerException("Null attributes"); } this.attributes = attributes; if (keys == null) { throw new NullPointerException("Null keys"); } this.keys = keys; if (instances == null) { throw new NullPointerException("Null instances"); } this.instances = instances; if (relates == null) { throw new NullPointerException("Null relates"); } this.relates = relates; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public Label label() { return label; } @JsonProperty @Override public Boolean implicit() { return implicit; } @Nullable @JsonProperty(value = "super") @Override public EmbeddedSchemaConcept sup() { return sup; } @JsonProperty @Override public Link subs() { return subs; } @JsonProperty(value = "abstract") @Override public Boolean isAbstract() { return isAbstract; } @JsonProperty @Override public Link plays() { return plays; } @JsonProperty @Override public Link attributes() { return attributes; } @JsonProperty @Override public Link keys() { return keys; } @JsonProperty @Override public Link instances() { return instances; } @JsonProperty @Override public Set<Link> relates() { return relates; } @Override public String toString() { return "RelationshipType{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "label=" + label + ", " + "implicit=" + implicit + ", " + "sup=" + sup + ", " + "subs=" + subs + ", " + "isAbstract=" + isAbstract + ", " + "plays=" + plays + ", " + "attributes=" + attributes + ", " + "keys=" + keys + ", " + "instances=" + instances + ", " + "relates=" + relates + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RelationshipType) { RelationshipType that = (RelationshipType) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.label.equals(that.label())) && (this.implicit.equals(that.implicit())) && ((this.sup == null) ? (that.sup() == null) : this.sup.equals(that.sup())) && (this.subs.equals(that.subs())) && (this.isAbstract.equals(that.isAbstract())) && (this.plays.equals(that.plays())) && (this.attributes.equals(that.attributes())) && (this.keys.equals(that.keys())) && (this.instances.equals(that.instances())) && (this.relates.equals(that.relates())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.label.hashCode(); h *= 1000003; h ^= this.implicit.hashCode(); h *= 1000003; h ^= (sup == null) ? 0 : this.sup.hashCode(); h *= 1000003; h ^= this.subs.hashCode(); h *= 1000003; h ^= this.isAbstract.hashCode(); h *= 1000003; h ^= this.plays.hashCode(); h *= 1000003; h ^= this.attributes.hashCode(); h *= 1000003; h ^= this.keys.hashCode(); h *= 1000003; h ^= this.instances.hashCode(); h *= 1000003; h ^= this.relates.hashCode(); return h; } }
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/AutoValue_Role.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Set; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Role extends Role { private final String baseType; private final ConceptId id; private final Link selfLink; private final Label label; private final Boolean implicit; private final EmbeddedSchemaConcept sup; private final Link subs; private final Set<Link> relationships; private final Set<Link> roleplayers; AutoValue_Role( String baseType, ConceptId id, Link selfLink, Label label, Boolean implicit, @Nullable EmbeddedSchemaConcept sup, Link subs, Set<Link> relationships, Set<Link> roleplayers) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (label == null) { throw new NullPointerException("Null label"); } this.label = label; if (implicit == null) { throw new NullPointerException("Null implicit"); } this.implicit = implicit; this.sup = sup; if (subs == null) { throw new NullPointerException("Null subs"); } this.subs = subs; if (relationships == null) { throw new NullPointerException("Null relationships"); } this.relationships = relationships; if (roleplayers == null) { throw new NullPointerException("Null roleplayers"); } this.roleplayers = roleplayers; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public Label label() { return label; } @JsonProperty @Override public Boolean implicit() { return implicit; } @Nullable @JsonProperty(value = "super") @Override public EmbeddedSchemaConcept sup() { return sup; } @JsonProperty @Override public Link subs() { return subs; } @JsonProperty @Override public Set<Link> relationships() { return relationships; } @JsonProperty @Override public Set<Link> roleplayers() { return roleplayers; } @Override public String toString() { return "Role{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "label=" + label + ", " + "implicit=" + implicit + ", " + "sup=" + sup + ", " + "subs=" + subs + ", " + "relationships=" + relationships + ", " + "roleplayers=" + roleplayers + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Role) { Role that = (Role) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.label.equals(that.label())) && (this.implicit.equals(that.implicit())) && ((this.sup == null) ? (that.sup() == null) : this.sup.equals(that.sup())) && (this.subs.equals(that.subs())) && (this.relationships.equals(that.relationships())) && (this.roleplayers.equals(that.roleplayers())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.label.hashCode(); h *= 1000003; h ^= this.implicit.hashCode(); h *= 1000003; h ^= (sup == null) ? 0 : this.sup.hashCode(); h *= 1000003; h ^= this.subs.hashCode(); h *= 1000003; h ^= this.relationships.hashCode(); h *= 1000003; h ^= this.roleplayers.hashCode(); return h; } }
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/AutoValue_RolePlayer.java
package ai.grakn.engine.controller.response; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_RolePlayer extends RolePlayer { private final Link role; private final Link thing; AutoValue_RolePlayer( Link role, Link thing) { if (role == null) { throw new NullPointerException("Null role"); } this.role = role; if (thing == null) { throw new NullPointerException("Null thing"); } this.thing = thing; } @JsonProperty @Override public Link role() { return role; } @JsonProperty @Override public Link thing() { return thing; } @Override public String toString() { return "RolePlayer{" + "role=" + role + ", " + "thing=" + thing + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof RolePlayer) { RolePlayer that = (RolePlayer) o; return (this.role.equals(that.role())) && (this.thing.equals(that.thing())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.role.hashCode(); h *= 1000003; h ^= this.thing.hashCode(); return h; } }
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/AutoValue_Root.java
package ai.grakn.engine.controller.response; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Root extends Root { private final Link selfLink; private final Link kb; AutoValue_Root( Link selfLink, Link kb) { if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (kb == null) { throw new NullPointerException("Null kb"); } this.kb = kb; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty(value = "keyspaces") @Override public Link kb() { return kb; } @Override public String toString() { return "Root{" + "selfLink=" + selfLink + ", " + "kb=" + kb + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Root) { Root that = (Root) o; return (this.selfLink.equals(that.selfLink())) && (this.kb.equals(that.kb())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.kb.hashCode(); return h; } }
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/AutoValue_Rule.java
package ai.grakn.engine.controller.response; import ai.grakn.concept.ConceptId; import ai.grakn.concept.Label; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Rule extends Rule { private final String baseType; private final ConceptId id; private final Link selfLink; private final Label label; private final Boolean implicit; private final EmbeddedSchemaConcept sup; private final Link subs; private final String when; private final String then; AutoValue_Rule( String baseType, ConceptId id, Link selfLink, Label label, Boolean implicit, @Nullable EmbeddedSchemaConcept sup, Link subs, @Nullable String when, @Nullable String then) { if (baseType == null) { throw new NullPointerException("Null baseType"); } this.baseType = baseType; if (id == null) { throw new NullPointerException("Null id"); } this.id = id; if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (label == null) { throw new NullPointerException("Null label"); } this.label = label; if (implicit == null) { throw new NullPointerException("Null implicit"); } this.implicit = implicit; this.sup = sup; if (subs == null) { throw new NullPointerException("Null subs"); } this.subs = subs; this.when = when; this.then = then; } @JsonProperty(value = "base-type") @Override public String baseType() { return baseType; } @JsonProperty(value = "id") @Override public ConceptId id() { return id; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public Label label() { return label; } @JsonProperty @Override public Boolean implicit() { return implicit; } @Nullable @JsonProperty(value = "super") @Override public EmbeddedSchemaConcept sup() { return sup; } @JsonProperty @Override public Link subs() { return subs; } @Nullable @JsonProperty @Override public String when() { return when; } @Nullable @JsonProperty @Override public String then() { return then; } @Override public String toString() { return "Rule{" + "baseType=" + baseType + ", " + "id=" + id + ", " + "selfLink=" + selfLink + ", " + "label=" + label + ", " + "implicit=" + implicit + ", " + "sup=" + sup + ", " + "subs=" + subs + ", " + "when=" + when + ", " + "then=" + then + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Rule) { Rule that = (Rule) o; return (this.baseType.equals(that.baseType())) && (this.id.equals(that.id())) && (this.selfLink.equals(that.selfLink())) && (this.label.equals(that.label())) && (this.implicit.equals(that.implicit())) && ((this.sup == null) ? (that.sup() == null) : this.sup.equals(that.sup())) && (this.subs.equals(that.subs())) && ((this.when == null) ? (that.when() == null) : this.when.equals(that.when())) && ((this.then == null) ? (that.then() == null) : this.then.equals(that.then())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.baseType.hashCode(); h *= 1000003; h ^= this.id.hashCode(); h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.label.hashCode(); h *= 1000003; h ^= this.implicit.hashCode(); h *= 1000003; h ^= (sup == null) ? 0 : this.sup.hashCode(); h *= 1000003; h ^= this.subs.hashCode(); h *= 1000003; h ^= (when == null) ? 0 : this.when.hashCode(); h *= 1000003; h ^= (then == null) ? 0 : this.then.hashCode(); return h; } }
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/AutoValue_Things.java
package ai.grakn.engine.controller.response; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import javax.annotation.Generated; import javax.annotation.Nullable; @Generated("com.google.auto.value.processor.AutoValueProcessor") final class AutoValue_Things extends Things { private final Link selfLink; private final List<Thing> instances; private final Link next; private final Link previous; AutoValue_Things( Link selfLink, List<Thing> instances, @Nullable Link next, @Nullable Link previous) { if (selfLink == null) { throw new NullPointerException("Null selfLink"); } this.selfLink = selfLink; if (instances == null) { throw new NullPointerException("Null instances"); } this.instances = instances; this.next = next; this.previous = previous; } @JsonProperty(value = "@id") @Override public Link selfLink() { return selfLink; } @JsonProperty @Override public List<Thing> instances() { return instances; } @JsonProperty @Nullable @Override public Link next() { return next; } @JsonProperty @Nullable @Override public Link previous() { return previous; } @Override public String toString() { return "Things{" + "selfLink=" + selfLink + ", " + "instances=" + instances + ", " + "next=" + next + ", " + "previous=" + previous + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof Things) { Things that = (Things) o; return (this.selfLink.equals(that.selfLink())) && (this.instances.equals(that.instances())) && ((this.next == null) ? (that.next() == null) : this.next.equals(that.next())) && ((this.previous == null) ? (that.previous() == null) : this.previous.equals(that.previous())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.selfLink.hashCode(); h *= 1000003; h ^= this.instances.hashCode(); h *= 1000003; h ^= (next == null) ? 0 : this.next.hashCode(); h *= 1000003; h ^= (previous == null) ? 0 : this.previous.hashCode(); return h; } }
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/Concept.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.engine.Jacksonisable; import com.fasterxml.jackson.annotation.JsonProperty; /** * <p> * Wrapper class for {@link ai.grakn.concept.Concept} * </p> * * @author Filipe Peliz Pinto Teixeira */ public abstract class Concept implements Jacksonisable{ @JsonProperty("base-type") public abstract String baseType(); @JsonProperty("id") public abstract ConceptId id(); @JsonProperty("@id") public abstract Link selfLink(); }
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/ConceptBuilder.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.exception.GraknBackendException; import ai.grakn.graql.Graql; import ai.grakn.graql.internal.reasoner.utils.conversion.ConceptConverter; import ai.grakn.util.Schema; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * <p> * Factory used to build the wrapper {@link Concept}s from real {@link ai.grakn.concept.Concept}s * </p> * * @author Filipe Peliz Pinto Teixeira */ public class ConceptBuilder { /** * Takes a {@link ai.grakn.concept.Concept} and returns the equivalent response object * * @param concept The {@link ai.grakn.concept.Concept} to be converted into a response object * @return the response object wrapper {@link Concept} */ public static <X extends Concept> X build(ai.grakn.concept.Concept concept){ Concept response; if(concept.isSchemaConcept()){ response = buildSchemaConcept(concept.asSchemaConcept()); } else if (concept.isThing()) { response = buildThing(concept.asThing()); } else { throw GraknBackendException.convertingUnknownConcept(concept); } return (X) response; } /** * Gets all the instances of a specific {@link ai.grakn.concept.Type} and wraps them in a {@link Things} * response object * * @param type The {@link ai.grakn.concept.Type} to extract the {@link ai.grakn.concept.Thing}s from * @return The wrapper of the {@link ai.grakn.concept.Thing}s */ public static Things buildThings(ai.grakn.concept.Type type, int offset, int limit){ Link selfLink = Link.createInstanceLink(type, offset, limit); Link previous = null; if (offset != 0) { int previousIndex = offset - limit; if (previousIndex < 0) previousIndex = 0; previous = Link.createInstanceLink(type, previousIndex, limit); } //TODO: This does not actually scale. The DB is still read in this instance List<Thing> things = type.instances().skip(offset).limit(limit + 1L). map(ConceptBuilder::buildThing).collect(Collectors.toList()); // We get one extra instance and then remove it so we can sneakily check if there is a next page boolean hasNextPage = things.size() == limit + 1; Link next = hasNextPage ? Link.createInstanceLink(type, offset + limit, limit) : null; if (things.size() == limit + 1) things.remove(things.size() - 1); return Things.create(selfLink, things, next, previous); } //TODO: This will scale poorly with super nodes. Need to introduce some sort of paging maybe? private static Thing buildThing(ai.grakn.concept.Thing thing) { Link selfLink = Link.create(thing); EmbeddedSchemaConcept type = EmbeddedSchemaConcept.create(thing.type()); Link attributes = Link.createAttributesLink(thing); Link keys = Link.createKeysLink(thing); Link relationships = Link.createRelationshipsLink(thing); String explanation = null; if(thing.isInferred()) explanation = Graql.match(ConceptConverter.toPattern(thing)).get().toString(); if(thing.isAttribute()){ return buildAttribute(thing.asAttribute(), selfLink, type, attributes, keys, relationships, explanation); } else if (thing.isRelationship()){ return buildRelationship(thing.asRelationship(), selfLink, type, attributes, keys, relationships, explanation); } else if (thing.isEntity()){ return buildEntity(thing.asEntity(), selfLink, type, attributes, keys, relationships, explanation); } else { throw GraknBackendException.convertingUnknownConcept(thing); } } private static SchemaConcept buildSchemaConcept(ai.grakn.concept.SchemaConcept schemaConcept){ Link selfLink = Link.create(schemaConcept); EmbeddedSchemaConcept sup = null; if(schemaConcept.sup() != null) sup = EmbeddedSchemaConcept.create(schemaConcept.sup()); Link subs = Link.createSubsLink(schemaConcept); if(schemaConcept.isRole()){ return buildRole(schemaConcept.asRole(), selfLink, sup, subs); } else if(schemaConcept.isRule()){ return buildRule(schemaConcept.asRule(), selfLink, sup, subs); } else { return buildType(schemaConcept.asType(), selfLink, sup, subs); } } private static Entity buildEntity(ai.grakn.concept.Entity entity, Link selfLink, EmbeddedSchemaConcept type, Link attributes, Link keys, Link relationships, String explanation){ return Entity.create(entity.id(), selfLink, type, attributes, keys, relationships, entity.isInferred(), explanation); } private static Attribute buildAttribute(ai.grakn.concept.Attribute attribute, Link selfLink, EmbeddedSchemaConcept type, Link attributes, Link keys, Link relationships, String explanation){ return Attribute.create(attribute.id(), selfLink, type, attributes, keys, relationships, attribute.isInferred(), explanation, attribute.type().dataType().getName(), attribute.value().toString()); } private static Relationship buildRelationship(ai.grakn.concept.Relationship relationship, Link selfLink, EmbeddedSchemaConcept type, Link attributes, Link keys, Link relationships, String explanation){ //Get all the role players and roles part of this relationship Set<RolePlayer> roleplayers = new HashSet<>(); relationship.rolePlayersMap().forEach((role, things) -> { Link roleLink = Link.create(role); things.forEach(thing -> roleplayers.add(RolePlayer.create(roleLink, Link.create(thing)))); }); return Relationship.create(relationship.id(), selfLink, type, attributes, keys, relationships, relationship.isInferred(), explanation, roleplayers); } private static Type buildType(ai.grakn.concept.Type type, Link selfLink, EmbeddedSchemaConcept sup, Link subs){ Link plays = Link.createPlaysLink(type); Link attributes = Link.createAttributesLink(type); Link keys = Link.createKeysLink(type); Link instances = Link.createInstancesLink(type); if(Schema.MetaSchema.THING.getLabel().equals(type.label())) { return MetaConcept.create(type.id(), selfLink, type.label(), sup, subs, plays, attributes, keys, instances); } else if(type.isAttributeType()){ return buildAttributeType(type.asAttributeType(), selfLink, sup, subs, plays, attributes, keys, instances); } else if (type.isEntityType()){ return buildEntityType(type.asEntityType(), selfLink, sup, subs, plays, attributes, keys, instances); } else if (type.isRelationshipType()){ return buildRelationshipType(type.asRelationshipType(), selfLink, sup, subs, plays, attributes, keys, instances); } else { throw GraknBackendException.convertingUnknownConcept(type); } } private static Role buildRole(ai.grakn.concept.Role role, Link selfLink, EmbeddedSchemaConcept sup, Link subs){ Set<Link> relationships = role.relationships().map(Link::create).collect(Collectors.toSet()); Set<Link> roleplayers = role.players().map(Link::create).collect(Collectors.toSet()); return Role.create(role.id(), selfLink, role.label(), role.isImplicit(), sup, subs, relationships, roleplayers); } private static Rule buildRule(ai.grakn.concept.Rule rule, Link selfLink, EmbeddedSchemaConcept sup, Link subs){ String when = null; if(rule.when() != null) when = rule.when().toString(); String then = null; if(rule.then() != null) then = rule.then().toString(); return Rule.create(rule.id(), selfLink, rule.label(), rule.isImplicit(), sup, subs, when, then); } private static AttributeType buildAttributeType(ai.grakn.concept.AttributeType attributeType, Link selfLink, EmbeddedSchemaConcept sup, Link subs, Link plays, Link attributes, Link keys, Link instances){ String dataType = null; if(attributeType.dataType() != null) dataType = attributeType.dataType().getName(); return AttributeType.create(attributeType.id(), selfLink, attributeType.label(), attributeType.isImplicit(), sup, subs, attributeType.isAbstract(), plays, attributes, keys, instances, dataType, attributeType.regex()); } private static EntityType buildEntityType(ai.grakn.concept.EntityType entityType, Link selfLink, EmbeddedSchemaConcept sup, Link subs, Link plays, Link attributes, Link keys, Link instances){ return EntityType.create(entityType.id(), selfLink, entityType.label(), entityType.isImplicit(), sup, subs, entityType.isAbstract(), plays, attributes, keys, instances); } private static RelationshipType buildRelationshipType(ai.grakn.concept.RelationshipType relationshipType, Link selfLink, EmbeddedSchemaConcept sup, Link subs, Link plays, Link attributes, Link keys, Link instances){ Set<Link> relates = relationshipType.roles(). map(Link::create). collect(Collectors.toSet()); return RelationshipType.create(relationshipType.id(), selfLink, relationshipType.label(), relationshipType.isImplicit(), sup, subs, relationshipType.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/EmbeddedAttribute.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.engine.Jacksonisable; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; /** * <p> * Wrapper class for a light representation of {@link ai.grakn.concept.Attribute}s which are embedded in the * {@link Thing} representations * </p> * * @author Filipe Peliz Pinto Teixeira */ @AutoValue public abstract class EmbeddedAttribute implements Jacksonisable { @JsonProperty public abstract ConceptId id(); @JsonProperty("@id") public abstract Link selfLink(); @JsonProperty public abstract EmbeddedSchemaConcept type(); @JsonProperty public abstract String value(); @JsonProperty("data-type") public abstract String dataType(); @JsonCreator public static EmbeddedAttribute create( @JsonProperty("id") ConceptId id, @JsonProperty("@id") Link selfLink, @JsonProperty("type") EmbeddedSchemaConcept type, @JsonProperty("value") String value, @JsonProperty("data-type") String dataType ){ return new AutoValue_EmbeddedAttribute(id, selfLink, type, value, dataType); } public static EmbeddedAttribute create(ai.grakn.concept.Attribute attribute){ return create(attribute.id(), Link.create(attribute), EmbeddedSchemaConcept.create(attribute.type()), attribute.value().toString(), attribute.dataType().getName()); } }
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/EmbeddedSchemaConcept.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.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; /** * <p> * Wrapper class for a light representation of {@link ai.grakn.concept.Type} which is embedded in the * {@link Thing} representation * </p> * * @author Filipe Peliz Pinto Teixeira */ @AutoValue public abstract class EmbeddedSchemaConcept { @JsonProperty("@id") public abstract Link selfLink(); @JsonProperty public abstract Label label(); @JsonCreator public static EmbeddedSchemaConcept create(@JsonProperty("@id") Link selfLink, @JsonProperty("label") Label label){ return new AutoValue_EmbeddedSchemaConcept(selfLink, label); } public static EmbeddedSchemaConcept create(ai.grakn.concept.SchemaConcept schemaConcept){ return create(Link.create(schemaConcept), schemaConcept.label()); } }
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/Entity.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; /** * <p> * Wrapper class for {@link ai.grakn.concept.Entity} * </p> * * @author Filipe Peliz Pinto Teixeira */ @AutoValue public abstract class Entity extends Thing { @JsonCreator public static Entity 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 ){ return new AutoValue_Entity(Schema.BaseType.ENTITY.name(), id, selfLink, type, attributes, keys, relationships, inferred, explanation); } }