Search in sources :

Example 1 with Resource

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

the class IntelligentGraphRepository method removeGraph.

/**
 * Removes the graph.
 *
 * @param graphName the graph name
 * @return the iri
 */
public IRI removeGraph(String graphName) {
    // RepositoryConnection connection = this.getRepository().getConnection();//.getContextAwareConnection();
    IRI graphNameIri = null;
    try (RepositoryConnection connection = this.getRepository().getConnection()) {
        graphNameIri = PathParser.parseIriRef(getRepositoryContext(), graphName).getIri();
        @SuppressWarnings("deprecation") Boolean contextExists = connection.getContextIDs().asList().contains(graphNameIri);
        if (contextExists) {
            Resource[] contexts = { graphNameIri };
            // connection.begin(IsolationLevels.SERIALIZABLE);
            // connection.clear(graphNameIri);
            // connection.clear();
            connection.remove((IRI) null, (IRI) null, null, contexts);
            // connection.remove(graphNameIri, (IRI) null, null,contexts);//graphNameIri);
            // connection.remove((Resource) null, (IRI) null, null);//graphNameIri);
            // connection.commit();
            logger.debug("Removed graph {} ", graphNameIri.stringValue());
        } else {
            logger.error("Failed to remove graph {} ", graphNameIri.stringValue());
            return null;
        // throw new ServerException(FAILEDTOREMOVEGRAPH_EXCEPTION,  String.format("Failed to remove graph %s. Does not exist", graphName));
        }
    } catch (Exception qe) {
        throw new ServerException(FAILEDTOREMOVEGRAPH_EXCEPTION, String.format("Failed to remove graph %s", graphName, qe.getMessage()), qe);
    }
    return graphNameIri;
}
Also used : RepositoryConnection(org.eclipse.rdf4j.repository.RepositoryConnection) IRI(org.eclipse.rdf4j.model.IRI) ServerException(com.inova8.intelligentgraph.exceptions.ServerException) Resource(org.eclipse.rdf4j.model.Resource) NullValueReturnedException(com.inova8.intelligentgraph.exceptions.NullValueReturnedException) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) ScriptException(javax.script.ScriptException) ServerException(com.inova8.intelligentgraph.exceptions.ServerException) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) PathPatternException(com.inova8.pathql.processor.PathPatternException) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 2 with Resource

use of com.inova8.intelligentgraph.model.Resource 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 3 with Resource

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

the class Thing method getFact.

/**
 * Gets the fact.
 *
 * @param predicatePattern the predicate pattern
 * @param bindValues the bind values
 * @return the fact
 */
public Resource getFact(String predicatePattern, Value... bindValues) {
    logger.debug("getFact{}\n", predicatePattern);
    // this.getEvaluationContext().getTracer().traceFact(this, predicatePattern);
    ResourceResults factValues = getFacts(predicatePattern, bindValues);
    if (factValues == null) {
        this.getEvaluationContext().getTracer().traceFactReturnNull(this, predicatePattern);
        throw new NullValueReturnedException(String.format("No values found for pattern %s with subject %s", predicatePattern, this));
    } else if (factValues.hasNext()) {
        Resource nextFact = factValues.next();
        this.getEvaluationContext().getTracer().traceFactReturnValue(this, predicatePattern, nextFact);
        return nextFact;
    } else {
        this.getEvaluationContext().getTracer().traceFactEmpty(this, predicatePattern);
        factValues.close();
        throw new NullValueReturnedException(String.format("No values found for pattern %s with subject %s", predicatePattern, this));
    }
}
Also used : NullValueReturnedException(com.inova8.intelligentgraph.exceptions.NullValueReturnedException) ResourceResults(com.inova8.intelligentgraph.results.ResourceResults)

Example 4 with Resource

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

the class Thing method traceFact.

/**
 * Trace fact.
 *
 * @param predicatePattern the predicate pattern
 * @param customQueryOptions the custom query options
 * @return the trace
 */
public Trace traceFact(String predicatePattern, CustomQueryOptions customQueryOptions) {
    SimpleDataset dataset = IntelligentGraphRepository.getDataset(customQueryOptions);
    dataset.addDefaultGraph(this.graphName);
    org.eclipse.rdf4j.model.Resource[] contextArray = dataset.getDefaultGraphs().toArray(new org.eclipse.rdf4j.model.Resource[0]);
    ResourceStatementResults results = null;
    IRI predicate = IntelligentGraphRepository.preparePredicate(PATHQL.traceFacts, predicatePattern);
    CloseableIteration<Statement, RepositoryException> statementIterator = this.getSource().getRepository().getConnection().getStatements(this.getIRI(), predicate, null, contextArray);
    results = new ResourceStatementResults(statementIterator, this, null, customQueryOptions);
    for (Resource result : results) {
        String resultString = result.stringValue();
        results.close();
        return new Trace(resultString);
    }
    results.close();
    return new Trace("results");
}
Also used : IRI(org.eclipse.rdf4j.model.IRI) Statement(org.eclipse.rdf4j.model.Statement) ResourceStatementResults(com.inova8.intelligentgraph.results.ResourceStatementResults) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) SimpleDataset(org.eclipse.rdf4j.query.impl.SimpleDataset) Trace(com.inova8.intelligentgraph.evaluator.Trace)

Example 5 with Resource

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

the class Thing method getFact.

/**
 * Gets the fact.
 *
 * @param predicatePattern the predicate pattern
 * @param customQueryOptions the custom query options
 * @return the fact
 */
public Resource getFact(String predicatePattern, CustomQueryOptions customQueryOptions) {
    logger.debug("getFact{}\n", predicatePattern);
    ResourceResults factValues = getFacts(predicatePattern, customQueryOptions);
    if (factValues == null) {
        // return new NullResource();
        throw new NullValueReturnedException(String.format("No values found for pattern %s with subject %s and customQueryOptions %s", predicatePattern, this, customQueryOptions));
    } else if (factValues.hasNext()) {
        return factValues.next();
    } else {
        factValues.close();
        // return new NullResource();
        throw new NullValueReturnedException(String.format("No values found for pattern %s with subject %s and customQueryOptions %s", predicatePattern, this, customQueryOptions));
    }
}
Also used : NullValueReturnedException(com.inova8.intelligentgraph.exceptions.NullValueReturnedException) ResourceResults(com.inova8.intelligentgraph.results.ResourceResults)

Aggregations

Resource (com.inova8.intelligentgraph.model.Resource)140 Order (org.junit.jupiter.api.Order)135 Test (org.junit.jupiter.api.Test)135 TestMethodOrder (org.junit.jupiter.api.TestMethodOrder)135 Thing (com.inova8.intelligentgraph.model.Thing)113 ResourceResults (com.inova8.intelligentgraph.results.ResourceResults)26 IntelligentGraphRepository (com.inova8.intelligentgraph.intelligentGraphRepository.IntelligentGraphRepository)20 Graph (com.inova8.intelligentgraph.intelligentGraphRepository.Graph)19 QueryEvaluationException (org.eclipse.rdf4j.query.QueryEvaluationException)11 CustomQueryOptions (com.inova8.intelligentgraph.context.CustomQueryOptions)9 PathPatternException (com.inova8.pathql.processor.PathPatternException)8 RecognitionException (org.antlr.v4.runtime.RecognitionException)8 ArrayList (java.util.ArrayList)7 IRI (org.eclipse.rdf4j.model.IRI)7 RepositoryException (org.eclipse.rdf4j.repository.RepositoryException)7 Repository (org.eclipse.rdf4j.repository.Repository)6 RepositoryConnection (org.eclipse.rdf4j.repository.RepositoryConnection)6 NullValueReturnedException (com.inova8.intelligentgraph.exceptions.NullValueReturnedException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 BindingSet (org.eclipse.rdf4j.query.BindingSet)5