Search in sources :

Example 6 with TupleQueryResult

use of org.eclipse.rdf4j.query.TupleQueryResult in project rdf4j by eclipse.

the class RepositoryFederatedService method select.

/**
 * Evaluate the provided sparqlQueryString at the initialized {@link Repository} of this
 * {@link FederatedService}. Insert bindings into SELECT query and evaluate
 */
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> select(Service service, Set<String> projectionVars, BindingSet bindings, String baseUri) throws QueryEvaluationException {
    try {
        String sparqlQueryString = service.getSelectQueryString(projectionVars);
        TupleQuery query = getConnection().prepareTupleQuery(QueryLanguage.SPARQL, sparqlQueryString, baseUri);
        Iterator<Binding> bIter = bindings.iterator();
        while (bIter.hasNext()) {
            Binding b = bIter.next();
            if (service.getServiceVars().contains(b.getName()))
                query.setBinding(b.getName(), b.getValue());
        }
        TupleQueryResult res = query.evaluate();
        // insert original bindings again
        InsertBindingSetCursor result = new InsertBindingSetCursor(res, bindings);
        if (service.isSilent())
            return new SilentIteration(result);
        else
            return result;
    } catch (MalformedQueryException e) {
        throw new QueryEvaluationException(e);
    } catch (RepositoryException e) {
        throw new QueryEvaluationException("Repository for endpoint " + rep.toString() + " could not be initialized.", e);
    }
}
Also used : Binding(org.eclipse.rdf4j.query.Binding) InsertBindingSetCursor(org.eclipse.rdf4j.repository.sparql.query.InsertBindingSetCursor) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) MalformedQueryException(org.eclipse.rdf4j.query.MalformedQueryException) TupleQuery(org.eclipse.rdf4j.query.TupleQuery) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) TupleQueryResult(org.eclipse.rdf4j.query.TupleQueryResult)

Example 7 with TupleQueryResult

use of org.eclipse.rdf4j.query.TupleQueryResult in project rdf4j by eclipse.

the class RepositoryFederatedService method evaluateInternal.

/**
 * Evaluate the SPARQL query that can be constructed from the SERVICE node at the initialized
 * {@link Repository} of this {@link FederatedService}. Use specified bindings as constraints to the
 * query. Try to evaluate using BINDINGS clause, if this yields an exception fall back to the naive
 * implementation. This method deals with SILENT SERVICEs.
 */
protected CloseableIteration<BindingSet, QueryEvaluationException> evaluateInternal(Service service, CloseableIteration<BindingSet, QueryEvaluationException> bindings, String baseUri) throws QueryEvaluationException {
    // materialize all bindings (to allow for fallback in case of errors)
    // note that this may be blocking depending on the underlying iterator
    List<BindingSet> allBindings = new LinkedList<BindingSet>();
    while (bindings.hasNext()) {
        allBindings.add(bindings.next());
    }
    if (allBindings.size() == 0) {
        return new EmptyIteration<BindingSet, QueryEvaluationException>();
    }
    // projection vars
    Set<String> projectionVars = new HashSet<String>(service.getServiceVars());
    projectionVars.removeAll(allBindings.get(0).getBindingNames());
    // below we need to take care for SILENT services
    CloseableIteration<BindingSet, QueryEvaluationException> result = null;
    try {
        // fallback to simple evaluation (just a single binding)
        if (allBindings.size() == 1) {
            result = select(service, projectionVars, allBindings.get(0), baseUri);
            result = service.isSilent() ? new SilentIteration(result) : result;
            return result;
        }
        // To be able to insert the input bindings again later on, we need some
        // means to identify the row of each binding. hence, we use an
        // additional
        // projection variable, which is also passed in the BINDINGS clause
        // with the value of the actual row. The value corresponds to the index
        // of the binding in the index list
        projectionVars.add("__rowIdx");
        String queryString = service.getSelectQueryString(projectionVars);
        List<String> relevantBindingNames = getRelevantBindingNames(allBindings, service.getServiceVars());
        if (relevantBindingNames.size() != 0) {
            // append the VALUES clause to the query
            queryString += buildVALUESClause(allBindings, relevantBindingNames);
        }
        TupleQuery query = getConnection().prepareTupleQuery(QueryLanguage.SPARQL, queryString, baseUri);
        TupleQueryResult res = null;
        // TODO how to retrieve max query value
        query.setMaxQueryTime(60);
        // from actual setting?
        res = query.evaluate();
        if (relevantBindingNames.size() == 0)
            // cross
            result = new SPARQLCrossProductIteration(res, allBindings);
        else
            // product
            // common
            result = new ServiceJoinConversionIteration(res, allBindings);
        // join
        result = service.isSilent() ? new SilentIteration(result) : result;
        return result;
    } catch (RepositoryException e) {
        Iterations.closeCloseable(result);
        if (service.isSilent())
            return new CollectionIteration<BindingSet, QueryEvaluationException>(allBindings);
        throw new QueryEvaluationException("Repository for endpoint " + rep.toString() + " could not be initialized.", e);
    } catch (MalformedQueryException e) {
        // this exception must not be silenced, bug in our code
        throw new QueryEvaluationException(e);
    } catch (QueryEvaluationException e) {
        Iterations.closeCloseable(result);
        if (service.isSilent())
            return new CollectionIteration<BindingSet, QueryEvaluationException>(allBindings);
        throw e;
    } catch (RuntimeException e) {
        Iterations.closeCloseable(result);
        // QueryEval) if silent
        if (service.isSilent())
            return new CollectionIteration<BindingSet, QueryEvaluationException>(allBindings);
        throw e;
    }
}
Also used : EmptyBindingSet(org.eclipse.rdf4j.query.impl.EmptyBindingSet) BindingSet(org.eclipse.rdf4j.query.BindingSet) EmptyIteration(org.eclipse.rdf4j.common.iteration.EmptyIteration) TupleQuery(org.eclipse.rdf4j.query.TupleQuery) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) LinkedList(java.util.LinkedList) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) MalformedQueryException(org.eclipse.rdf4j.query.MalformedQueryException) TupleQueryResult(org.eclipse.rdf4j.query.TupleQueryResult) HashSet(java.util.HashSet)

Example 8 with TupleQueryResult

use of org.eclipse.rdf4j.query.TupleQueryResult in project rdf4j by eclipse.

the class HTTPRepository method isWritable.

@Override
public boolean isWritable() throws RepositoryException {
    if (!isInitialized()) {
        throw new IllegalStateException("HTTPRepository not initialized.");
    }
    boolean isWritable = false;
    try (RDF4JProtocolSession client = createHTTPClient()) {
        final String repositoryURL = client.getRepositoryURL();
        final TupleQueryResult repositoryList = client.getRepositoryList();
        try {
            while (repositoryList.hasNext()) {
                final BindingSet bindingSet = repositoryList.next();
                final Value uri = bindingSet.getValue("uri");
                if (uri != null && uri.stringValue().equals(repositoryURL)) {
                    isWritable = Literals.getBooleanValue(bindingSet.getValue("writable"), false);
                    break;
                }
            }
        } finally {
            repositoryList.close();
        }
    } catch (QueryEvaluationException e) {
        throw new RepositoryException(e);
    } catch (IOException e) {
        throw new RepositoryException(e);
    }
    return isWritable;
}
Also used : BindingSet(org.eclipse.rdf4j.query.BindingSet) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) Value(org.eclipse.rdf4j.model.Value) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) RDF4JProtocolSession(org.eclipse.rdf4j.http.client.RDF4JProtocolSession) IOException(java.io.IOException) TupleQueryResult(org.eclipse.rdf4j.query.TupleQueryResult)

Example 9 with TupleQueryResult

use of org.eclipse.rdf4j.query.TupleQueryResult in project rdf4j by eclipse.

the class HTTPRepositoryConnection method getNamespaces.

public RepositoryResult<Namespace> getNamespaces() throws RepositoryException {
    try {
        List<Namespace> namespaceList = new ArrayList<Namespace>();
        TupleQueryResult namespaces = client.getNamespaces();
        try {
            while (namespaces.hasNext()) {
                BindingSet bindingSet = namespaces.next();
                Value prefix = bindingSet.getValue("prefix");
                Value namespace = bindingSet.getValue("namespace");
                if (prefix instanceof Literal && namespace instanceof Literal) {
                    String prefixStr = ((Literal) prefix).getLabel();
                    String namespaceStr = ((Literal) namespace).getLabel();
                    namespaceList.add(new SimpleNamespace(prefixStr, namespaceStr));
                }
            }
        } finally {
            namespaces.close();
        }
        return createRepositoryResult(namespaceList);
    } catch (QueryEvaluationException e) {
        throw new RepositoryException(e);
    } catch (IOException e) {
        throw new RepositoryException(e);
    }
}
Also used : BindingSet(org.eclipse.rdf4j.query.BindingSet) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) Literal(org.eclipse.rdf4j.model.Literal) ArrayList(java.util.ArrayList) Value(org.eclipse.rdf4j.model.Value) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) IOException(java.io.IOException) TupleQueryResult(org.eclipse.rdf4j.query.TupleQueryResult) Namespace(org.eclipse.rdf4j.model.Namespace) SimpleNamespace(org.eclipse.rdf4j.model.impl.SimpleNamespace) SimpleNamespace(org.eclipse.rdf4j.model.impl.SimpleNamespace)

Example 10 with TupleQueryResult

use of org.eclipse.rdf4j.query.TupleQueryResult in project rdf4j by eclipse.

the class RemoteRepositoryManager method getAllRepositoryInfos.

@Override
public Collection<RepositoryInfo> getAllRepositoryInfos(boolean skipSystemRepo) throws RepositoryException {
    List<RepositoryInfo> result = new ArrayList<RepositoryInfo>();
    try (RDF4JProtocolSession httpClient = getSesameClient().createRDF4JProtocolSession(serverURL)) {
        httpClient.setUsernameAndPassword(username, password);
        TupleQueryResult responseFromServer = httpClient.getRepositoryList();
        while (responseFromServer.hasNext()) {
            BindingSet bindingSet = responseFromServer.next();
            RepositoryInfo repInfo = new RepositoryInfo();
            String id = Literals.getLabel(bindingSet.getValue("id"), null);
            if (skipSystemRepo && id.equals(SystemRepository.ID)) {
                continue;
            }
            Value uri = bindingSet.getValue("uri");
            String description = Literals.getLabel(bindingSet.getValue("title"), null);
            boolean readable = Literals.getBooleanValue(bindingSet.getValue("readable"), false);
            boolean writable = Literals.getBooleanValue(bindingSet.getValue("writable"), false);
            if (uri instanceof IRI) {
                try {
                    repInfo.setLocation(new URL(uri.toString()));
                } catch (MalformedURLException e) {
                    logger.warn("Server reported malformed repository URL: {}", uri);
                }
            }
            repInfo.setId(id);
            repInfo.setDescription(description);
            repInfo.setReadable(readable);
            repInfo.setWritable(writable);
            result.add(repInfo);
        }
    } catch (IOException ioe) {
        logger.warn("Unable to retrieve list of repositories", ioe);
        throw new RepositoryException(ioe);
    } catch (QueryEvaluationException qee) {
        logger.warn("Unable to retrieve list of repositories", qee);
        throw new RepositoryException(qee);
    } catch (UnauthorizedException ue) {
        logger.warn("Not authorized to retrieve list of repositories", ue);
        throw new RepositoryException(ue);
    } catch (RepositoryException re) {
        logger.warn("Unable to retrieve list of repositories", re);
        throw re;
    }
    return result;
}
Also used : BindingSet(org.eclipse.rdf4j.query.BindingSet) IRI(org.eclipse.rdf4j.model.IRI) MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) RepositoryException(org.eclipse.rdf4j.repository.RepositoryException) IOException(java.io.IOException) URL(java.net.URL) QueryEvaluationException(org.eclipse.rdf4j.query.QueryEvaluationException) Value(org.eclipse.rdf4j.model.Value) UnauthorizedException(org.eclipse.rdf4j.http.protocol.UnauthorizedException) RDF4JProtocolSession(org.eclipse.rdf4j.http.client.RDF4JProtocolSession) TupleQueryResult(org.eclipse.rdf4j.query.TupleQueryResult)

Aggregations

TupleQueryResult (org.eclipse.rdf4j.query.TupleQueryResult)15 RepositoryException (org.eclipse.rdf4j.repository.RepositoryException)10 QueryEvaluationException (org.eclipse.rdf4j.query.QueryEvaluationException)9 IOException (java.io.IOException)7 TupleQuery (org.eclipse.rdf4j.query.TupleQuery)7 BindingSet (org.eclipse.rdf4j.query.BindingSet)6 MalformedQueryException (org.eclipse.rdf4j.query.MalformedQueryException)5 Value (org.eclipse.rdf4j.model.Value)4 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 AtomSetException (fr.lirmm.graphik.graal.api.core.AtomSetException)2 ExceptionConvertingIteration (org.eclipse.rdf4j.common.iteration.ExceptionConvertingIteration)2 RDF4JProtocolSession (org.eclipse.rdf4j.http.client.RDF4JProtocolSession)2 Resource (org.eclipse.rdf4j.model.Resource)2 UnsupportedQueryLanguageException (org.eclipse.rdf4j.query.UnsupportedQueryLanguageException)2 UpdateExecutionException (org.eclipse.rdf4j.query.UpdateExecutionException)2 IteratingTupleQueryResult (org.eclipse.rdf4j.query.impl.IteratingTupleQueryResult)2 ListBindingSet (org.eclipse.rdf4j.query.impl.ListBindingSet)2 UnknownTransactionStateException (org.eclipse.rdf4j.repository.UnknownTransactionStateException)2 SPARQLTupleQuery (org.eclipse.rdf4j.repository.sparql.query.SPARQLTupleQuery)2