Search in sources :

Example 1 with Thing

use of com.inova8.intelligentgraph.model.Thing in project com.inova8.intelligentgraph by peterjohnlawrence.

the class IntelligentEvaluator method handleScript.

/**
 * Handle script.
 *
 * @param thing the thing
 * @param scriptString the script string
 * @param predicate the predicate
 * @param customQueryOptions the custom query options
 * @param contexts the contexts
 * @return the resource
 * @throws HandledException the handled exception
 */
protected static Resource handleScript(Thing thing, SimpleLiteral scriptString, IRI predicate, CustomQueryOptions customQueryOptions, org.eclipse.rdf4j.model.Resource... contexts) throws HandledException {
    if (predicate.equals(SCRIPT.SCRIPTCODE)) {
        return Resource.create(thing.getSource(), scriptString, thing.getEvaluationContext());
    } else {
        String scriptCode = scriptString.getLabel();
        scriptCode = scriptCode.trim();
        if (scriptCode.startsWith("<")) {
            String scriptIRI = scriptCode.substring(0, scriptCode.length() - 1).substring(1);
            // convertQName(scriptIRI);
            org.eclipse.rdf4j.model.Resource scriptResource = thing.getSource().getRepositoryContext().convertQName(scriptIRI, thing.getSource().getPrefixes());
            Statement scriptStatement;
            SimpleLiteral scriptCodeliteral = null;
            try {
                CloseableIteration<? extends Statement, QueryEvaluationException> scriptStatements = thing.getSource().getTripleSource().getStatements(scriptResource, SCRIPT.SCRIPTCODE, null);
                while (scriptStatements.hasNext()) {
                    scriptStatement = scriptStatements.next();
                    scriptCodeliteral = (SimpleLiteral) scriptStatement.getObject();
                }
            } catch (QueryEvaluationException qe) {
                thing.getEvaluationContext().getTracer().traceRedirectingFailed(thing, predicate, scriptCode);
                throw new ScriptFailedException(String.format("Reference script <%s> not found for  %s of  subject %s", scriptIRI, predicate, thing), qe);
            }
            if (scriptCodeliteral != null) {
                thing.getEvaluationContext().getTracer().traceRedirecting(thing, predicate, scriptCode);
                return handleScript(thing, scriptCodeliteral, predicate, customQueryOptions, contexts);
            } else {
                thing.getEvaluationContext().getTracer().traceRedirectingFailed(thing, predicate, scriptCode);
                throw new ScriptFailedException(String.format("Reference script null <%s> for %s of subject %s", scriptIRI, predicate, thing));
            }
        } else {
            thing.getEvaluationContext().getTracer().incrementLevel();
            IRI cacheContextIRI = thing.generateCacheContext(predicate);
            thing.getEvaluationContext().getTracer().traceEvaluating(thing, predicate, scriptString);
            Object scriptResult = null;
            try {
                // Test to see if the same 'call' is on the stack
                // If so report that circular reference encountered
                // If not push on stack
                String stackKey = generateStackKey(thing, predicate);
                if (!thing.searchStack(stackKey)) {
                    CompiledScript compiledScriptCode = thing.getSource().compiledScriptFactory(scriptString);
                    SimpleBindings scriptBindings = new SimpleBindings();
                    Object _result = null;
                    scriptBindings.put("_result", _result);
                    scriptBindings.put("_this", thing);
                    scriptBindings.put("_customQueryOptions", customQueryOptions);
                    Resource result;
                    try {
                        thing.pushStack(stackKey);
                        scriptResult = compiledScriptCode.eval(scriptBindings);
                        if (scriptResult == null) {
                            // Could be Python which will not return a result by default
                            scriptResult = scriptBindings.get("_result");
                        }
                        result = returnResult(thing, scriptResult, cacheContextIRI);
                    } finally {
                        // Since script complete, pop from stack
                        thing.popStack();
                    }
                    thing.getEvaluationContext().getTracer().decrementLevel();
                    if (result != null)
                        thing.getEvaluationContext().getTracer().traceEvaluated(thing, predicate, result);
                    else {
                        throw new NullValueReturnedException(String.format("Evaluated null for %s of %s, using script %s", predicate, thing.getSuperValue(), scriptString));
                    }
                    thing.getEvaluationContext().getTracer().decrementLevel();
                    return result;
                } else {
                    thing.getEvaluationContext().getTracer().traceCircularReference(thing, predicate, thing.getStack(), stackKey);
                    logger.error("Circular reference encountered when evaluating <{}> of <{}>.\r\n{}", predicate.stringValue(), ((IRI) thing.getSuperValue()).stringValue(), thing.getStack().subList(thing.getStack().size() - thing.getStack().search(stackKey), thing.getStack().size()).toString());
                    throw new CircularReferenceException(String.format("Circular reference encountered when evaluating <%s> of <%s>.\r\n%s", predicate.stringValue(), ((IRI) thing.getSuperValue()).stringValue(), thing.getStack().subList(thing.getStack().size() - thing.getStack().search(stackKey), thing.getStack().size())));
                }
            } catch (ScriptException e) {
                thing.getEvaluationContext().getTracer().decrementLevel();
                logger.error(String.format("Script failed with <br/><code ><span style=\"white-space: pre-wrap\">%s</span></code >", StringEscapeUtils.escapeHtml4(e.getMessage())));
                thing.getEvaluationContext().getTracer().traceScriptError(e);
                throw new ScriptFailedException(e);
            }
        }
    }
}
Also used : CompiledScript(javax.script.CompiledScript) IRI(org.eclipse.rdf4j.model.IRI) Statement(org.eclipse.rdf4j.model.Statement) Resource(com.inova8.intelligentgraph.model.Resource) CircularReferenceException(com.inova8.intelligentgraph.exceptions.CircularReferenceException) ScriptException(javax.script.ScriptException) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) SimpleBindings(javax.script.SimpleBindings) ScriptFailedException(com.inova8.intelligentgraph.exceptions.ScriptFailedException) NullValueReturnedException(com.inova8.intelligentgraph.exceptions.NullValueReturnedException) SimpleLiteral(org.eclipse.rdf4j.model.impl.SimpleLiteral)

Example 2 with Thing

use of com.inova8.intelligentgraph.model.Thing in project com.inova8.intelligentgraph by peterjohnlawrence.

the class Tracer method traceFacts.

/**
 * Trace facts.
 *
 * @param thing the thing
 * @param pathQLValue the path QL value
 * @param prefixes the prefixes
 * @param contexts the contexts
 */
public void traceFacts(Thing thing, String pathQLValue, Prefixes prefixes, org.eclipse.rdf4j.model.Resource... contexts) {
    if (!tracing)
        return;
    addTrace(String.format("Getting facts  '%s' of %s", toHTML(pathQLValue), addIRI(thing.getSuperValue())));
    CustomQueryOptions customQueryOptions = CustomQueryOption.getCustomQueryOptions(contexts, prefixes);
    if (!customQueryOptions.isEmpty())
        addTrace(String.format("...using options: [%s]", toHTML(customQueryOptions.toString())));
    ArrayList<org.eclipse.rdf4j.model.Resource> coreContexts = CustomQueryOption.getCoreContexts(contexts);
    if (!coreContexts.isEmpty())
        addTrace(String.format("...within contexts: %s", coreContexts.toString()));
}
Also used : CustomQueryOptions(com.inova8.intelligentgraph.context.CustomQueryOptions) Resource(com.inova8.intelligentgraph.model.Resource)

Example 3 with Thing

use of com.inova8.intelligentgraph.model.Thing in project com.inova8.intelligentgraph by peterjohnlawrence.

the class FactDebug method evaluate.

/**
 * Evaluate.
 *
 * @param tripleSource the triple source
 * @param args the args
 * @return the value
 * @throws ValueExprEvaluationException the value expr evaluation exception
 */
@Override
public Value evaluate(TripleSource tripleSource, Value... args) throws ValueExprEvaluationException {
    // logger.debug("Trace Evaluate for <{}>, {} with args <{}>",tripleSource, tripleSource.getValueFactory(),Arrays.toString(args));
    if (args.length < 3) {
        String message = "At least subject, predicate, and script arguments required";
        logger.error(message);
        return tripleSource.getValueFactory().createLiteral(message);
    } else {
        IRI subject;
        IRI predicate;
        SimpleLiteral scriptLiteral;
        try {
            subject = (IRI) args[0];
            predicate = (IRI) args[1];
            scriptLiteral = (SimpleLiteral) args[2];
        } catch (Exception e) {
            String message = "Subject and predicate must be valid IRI, and script must be a literal";
            logger.error(message);
            return tripleSource.getValueFactory().createLiteral(message.toString());
        }
        try {
            Value[] argumentArray = Arrays.copyOfRange(args, 3, args.length);
            IntelligentGraphRepository source = sources.getSource(tripleSource, argumentArray);
            CustomQueryOptions customQueryOptions = source.getCustomQueryOptions(argumentArray);
            EvaluationContext evaluationContext = new EvaluationContext(customQueryOptions);
            evaluationContext.setTracing(true);
            Thing subjectThing = Thing.create(source, subject, evaluationContext);
            IntelligentEvaluator.processFactObjectValue(subjectThing, predicate, scriptLiteral, customQueryOptions);
            // TODO 	subjectThing.getFact(predicate,	scriptLiteral,customQueryOptions);
            logger.debug("Trace\r\n" + evaluationContext.getTrace());
            return tripleSource.getValueFactory().createLiteral(evaluationContext.getTrace());
        } catch (Exception e) {
            return tripleSource.getValueFactory().createLiteral(e.getMessage());
        }
    }
}
Also used : IRI(org.eclipse.rdf4j.model.IRI) IntelligentGraphRepository(com.inova8.intelligentgraph.intelligentGraphRepository.IntelligentGraphRepository) CustomQueryOptions(com.inova8.intelligentgraph.context.CustomQueryOptions) Value(org.eclipse.rdf4j.model.Value) SimpleLiteral(org.eclipse.rdf4j.model.impl.SimpleLiteral) EvaluationContext(com.inova8.intelligentgraph.evaluator.EvaluationContext) ValueExprEvaluationException(org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException) Thing(com.inova8.intelligentgraph.model.Thing)

Example 4 with Thing

use of com.inova8.intelligentgraph.model.Thing in project com.inova8.intelligentgraph by peterjohnlawrence.

the class FactProvenance method evaluate.

/**
 * Evaluate.
 *
 * @param tripleSource the triple source
 * @param args the args
 * @return the value
 * @throws ValueExprEvaluationException the value expr evaluation exception
 */
@Override
public Value evaluate(TripleSource tripleSource, Value... args) throws ValueExprEvaluationException {
    logger.debug("Trace Evaluate for <{}>, {} with args <{}>", tripleSource, tripleSource.getValueFactory(), args);
    if (args.length < 2) {
        String message = "At least subject, and predicate arguments required";
        logger.error(message);
        return tripleSource.getValueFactory().createLiteral(message);
    } else {
        IRI subject;
        IRI predicate;
        try {
            subject = (IRI) args[0];
            predicate = (IRI) args[1];
        } catch (Exception e) {
            String message = "Subject and predicate must be valid IRI";
            logger.error(message);
            return tripleSource.getValueFactory().createLiteral(message);
        }
        try {
            Value[] argumentArray = Arrays.copyOfRange(args, 2, args.length);
            IntelligentGraphRepository source = sources.getSource(tripleSource, argumentArray);
            CustomQueryOptions customQueryOptions = source.getCustomQueryOptions(argumentArray);
            EvaluationContext evaluationContext = new EvaluationContext(customQueryOptions);
            evaluationContext.setTracing(true);
            Thing subjectThing = Thing.create(source, subject, evaluationContext);
            // olgap.Value fact =
            // PredicateElement(source,predicate));
            subjectThing.getFact("<" + predicate.stringValue() + ">");
            logger.debug("Trace\r\n" + evaluationContext.getTrace());
            return tripleSource.getValueFactory().createLiteral(evaluationContext.getTrace());
        } catch (Exception e) {
            return tripleSource.getValueFactory().createLiteral(e.getMessage());
        }
    }
}
Also used : IRI(org.eclipse.rdf4j.model.IRI) IntelligentGraphRepository(com.inova8.intelligentgraph.intelligentGraphRepository.IntelligentGraphRepository) CustomQueryOptions(com.inova8.intelligentgraph.context.CustomQueryOptions) Value(org.eclipse.rdf4j.model.Value) EvaluationContext(com.inova8.intelligentgraph.evaluator.EvaluationContext) ValueExprEvaluationException(org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException) Thing(com.inova8.intelligentgraph.model.Thing)

Example 5 with Thing

use of com.inova8.intelligentgraph.model.Thing in project com.inova8.intelligentgraph by peterjohnlawrence.

the class FactValue method evaluate.

/**
 * Evaluate.
 *
 * @param tripleSource the triple source
 * @param args the args
 * @return the value
 * @throws ValueExprEvaluationException the value expr evaluation exception
 */
@Override
public Value evaluate(TripleSource tripleSource, Value... args) throws ValueExprEvaluationException {
    logger.debug("Evaluate for {} with args <{}>", tripleSource.getValueFactory(), args);
    if (args.length < 2) {
        String message = "At least subject, and predicate arguments required";
        logger.error(message);
        return tripleSource.getValueFactory().createLiteral(message);
    } else {
        IRI subject;
        IRI predicate;
        try {
            subject = (IRI) args[0];
            predicate = (IRI) args[1];
        } catch (Exception e) {
            String message = "Subject and predicate must be valid IRI";
            logger.error(message);
            return tripleSource.getValueFactory().createLiteral(message.toString());
        }
        try {
            Value[] argumentArray = Arrays.copyOfRange(args, 2, args.length);
            IntelligentGraphRepository source = sources.getSource(tripleSource, argumentArray);
            CustomQueryOptions customQueryOptions = source.getCustomQueryOptions(argumentArray);
            EvaluationContext evaluationContext = new EvaluationContext(customQueryOptions);
            Thing subjectThing = Thing.create(source, subject, evaluationContext);
            // new PredicateElement(source,predicate));
            com.inova8.intelligentgraph.model.Resource fact = subjectThing.getFact("<" + predicate.stringValue() + ">");
            if (fact != null && fact.getValue() != null) {
                Value result = fact.getValue();
                logger.debug("FactValue = {}", result);
                return result;
            } else {
                return tripleSource.getValueFactory().createLiteral("");
            }
        } catch (Exception e) {
            return tripleSource.getValueFactory().createLiteral(e.getMessage());
        }
    }
}
Also used : IRI(org.eclipse.rdf4j.model.IRI) IntelligentGraphRepository(com.inova8.intelligentgraph.intelligentGraphRepository.IntelligentGraphRepository) CustomQueryOptions(com.inova8.intelligentgraph.context.CustomQueryOptions) Value(org.eclipse.rdf4j.model.Value) EvaluationContext(com.inova8.intelligentgraph.evaluator.EvaluationContext) ValueExprEvaluationException(org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException) Thing(com.inova8.intelligentgraph.model.Thing)

Aggregations

Thing (com.inova8.intelligentgraph.model.Thing)211 Order (org.junit.jupiter.api.Order)189 Test (org.junit.jupiter.api.Test)189 TestMethodOrder (org.junit.jupiter.api.TestMethodOrder)189 Resource (com.inova8.intelligentgraph.model.Resource)112 Graph (com.inova8.intelligentgraph.intelligentGraphRepository.Graph)45 IntelligentGraphRepository (com.inova8.intelligentgraph.intelligentGraphRepository.IntelligentGraphRepository)36 ResourceResults (com.inova8.intelligentgraph.results.ResourceResults)33 PathResults (com.inova8.intelligentgraph.results.PathResults)29 CustomQueryOptions (com.inova8.intelligentgraph.context.CustomQueryOptions)20 IRI (org.eclipse.rdf4j.model.IRI)13 Value (org.eclipse.rdf4j.model.Value)13 Path (com.inova8.intelligentgraph.path.Path)11 PathPatternException (com.inova8.pathql.processor.PathPatternException)11 RecognitionException (org.antlr.v4.runtime.RecognitionException)11 Trace (com.inova8.intelligentgraph.evaluator.Trace)10 QueryEvaluationException (org.eclipse.rdf4j.query.QueryEvaluationException)9 RepositoryConnection (org.eclipse.rdf4j.repository.RepositoryConnection)9 EvaluationContext (com.inova8.intelligentgraph.evaluator.EvaluationContext)8 SimpleLiteral (org.eclipse.rdf4j.model.impl.SimpleLiteral)8