Search in sources :

Example 26 with YardException

use of org.apache.stanbol.entityhub.servicesapi.yard.YardException in project stanbol by apache.

the class ClerezzaYard method find.

@Override
public final QueryResultList<Representation> find(FieldQuery parsedQuery) throws YardException, IllegalArgumentException {
    if (parsedQuery == null) {
        throw new IllegalArgumentException("The parsed query MUST NOT be NULL!");
    }
    final SparqlFieldQuery query = SparqlFieldQueryFactory.getSparqlFieldQuery(parsedQuery);
    int limit = QueryUtils.getLimit(query, getConfig().getDefaultQueryResultNumber(), getConfig().getMaxQueryResultNumber());
    Query sparqlQuery;
    //NOTE:
    // - use the endpoint type standard, because we do not know what type of
    //   SPARQL implementation is configured for Clerezza via OSGI
    String sparqlQueryString = SparqlQueryUtils.createSparqlConstructQuery(query, limit, EndpointTypeEnum.Standard);
    try {
        sparqlQuery = QueryParser.getInstance().parse(sparqlQueryString);
    } catch (ParseException e) {
        log.error("ParseException for SPARQL Query in findRepresentation");
        log.error("FieldQuery: " + query);
        log.error("SPARQL Query: " + sparqlQueryString);
        throw new YardException("Unable to parse SPARQL query generated for the parse FieldQuery", e);
    }
    Object resultObject = tcManager.executeSparqlQuery(sparqlQuery, graph);
    final Graph resultGraph;
    if (resultObject instanceof Graph) {
        resultGraph = (Graph) resultObject;
    } else if (resultObject instanceof ImmutableGraph) {
        resultGraph = new IndexedGraph();
        resultGraph.addAll((ImmutableGraph) resultObject);
    } else {
        log.error("Unable to create " + Graph.class + " instance for query reults of type " + resultObject.getClass() + " (this indicates that the used SPARQL Query was not of type CONSTRUCT)");
        log.error("FieldQuery: " + query);
        log.error("SPARQL Query: " + sparqlQueryString);
        throw new YardException("Unable to process results of Query");
    }
    return new RdfQueryResultList(query, resultGraph);
}
Also used : YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) Query(org.apache.clerezza.rdf.core.sparql.query.Query) SparqlFieldQuery(org.apache.stanbol.entityhub.query.clerezza.SparqlFieldQuery) FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) SelectQuery(org.apache.clerezza.rdf.core.sparql.query.SelectQuery) RdfQueryResultList(org.apache.stanbol.entityhub.query.clerezza.RdfQueryResultList) SparqlFieldQuery(org.apache.stanbol.entityhub.query.clerezza.SparqlFieldQuery) ParseException(org.apache.clerezza.rdf.core.sparql.ParseException) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph)

Example 27 with YardException

use of org.apache.stanbol.entityhub.servicesapi.yard.YardException in project stanbol by apache.

the class SesameYard method getRepresentation.

@Override
public Representation getRepresentation(String id) throws YardException {
    if (id == null) {
        throw new IllegalArgumentException("The parsed representation id MUST NOT be NULL!");
    }
    if (id.isEmpty()) {
        throw new IllegalArgumentException("The parsed representation id MUST NOT be EMTPY!");
    }
    RepositoryConnection con = null;
    try {
        con = repository.getConnection();
        con.begin();
        Representation rep = getRepresentation(con, sesameFactory.createURI(id), true);
        con.commit();
        return rep;
    } catch (RepositoryException e) {
        throw new YardException("Unable to get Representation " + id, e);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (RepositoryException ignore) {
            }
        }
    }
}
Also used : RepositoryConnection(org.openrdf.repository.RepositoryConnection) YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) RdfRepresentation(org.apache.stanbol.entityhub.model.sesame.RdfRepresentation) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) RepositoryException(org.openrdf.repository.RepositoryException)

Example 28 with YardException

use of org.apache.stanbol.entityhub.servicesapi.yard.YardException in project stanbol by apache.

the class SesameYard method find.

@Override
public final QueryResultList<Representation> find(FieldQuery parsedQuery) throws YardException, IllegalArgumentException {
    if (parsedQuery == null) {
        throw new IllegalArgumentException("The parsed query MUST NOT be NULL!");
    }
    final SparqlFieldQuery query = SparqlFieldQueryFactory.getSparqlFieldQuery(parsedQuery);
    RepositoryConnection con = null;
    TupleQueryResult results = null;
    try {
        con = repository.getConnection();
        con.begin();
        //execute the query
        int limit = QueryUtils.getLimit(query, getConfig().getDefaultQueryResultNumber(), getConfig().getMaxQueryResultNumber());
        results = executeSparqlFieldQuery(con, query, limit, true);
        //parse the results and generate the Representations
        //create an own valueFactors so that all the data of the query results
        //are added to the same Sesame Model
        Model model = new TreeModel();
        RdfValueFactory valueFactory = new RdfValueFactory(model, sesameFactory);
        List<Representation> representations = limit > 0 ? new ArrayList<Representation>(limit) : new ArrayList<Representation>();
        Map<String, URI> bindings = new HashMap<String, URI>(query.getFieldVariableMappings().size());
        for (Entry<String, String> mapping : query.getFieldVariableMappings().entrySet()) {
            bindings.put(mapping.getValue(), sesameFactory.createURI(mapping.getKey()));
        }
        while (results.hasNext()) {
            BindingSet result = results.next();
            Value value = result.getValue(query.getRootVariableName());
            if (value instanceof URI) {
                URI subject = (URI) value;
                //link the result with the query result
                model.add(queryRoot, queryResult, subject);
                //now copy over the other selected data
                for (String binding : result.getBindingNames()) {
                    URI property = bindings.get(binding);
                    if (property != null) {
                        model.add(subject, property, result.getValue(binding));
                    }
                //else no mapping for the query.getRootVariableName()
                }
                //create a representation and add it to the results
                representations.add(valueFactory.createRdfRepresentation(subject));
            }
        //ignore non URI results
        }
        con.commit();
        return new SesameQueryResultList(model, query, representations);
    } catch (RepositoryException e) {
        throw new YardException("Unable to execute findReferences query", e);
    } catch (QueryEvaluationException e) {
        throw new YardException("Unable to execute findReferences query", e);
    } finally {
        if (results != null) {
            //close the result if present
            try {
                results.close();
            } catch (QueryEvaluationException ignore) {
            /* ignore */
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (RepositoryException ignore) {
            /* ignore */
            }
        }
    }
}
Also used : RepositoryConnection(org.openrdf.repository.RepositoryConnection) BindingSet(org.openrdf.query.BindingSet) HashMap(java.util.HashMap) RdfRepresentation(org.apache.stanbol.entityhub.model.sesame.RdfRepresentation) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) RepositoryException(org.openrdf.repository.RepositoryException) URI(org.openrdf.model.URI) TreeModel(org.openrdf.model.impl.TreeModel) YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) QueryEvaluationException(org.openrdf.query.QueryEvaluationException) SparqlFieldQuery(org.apache.stanbol.entityhub.query.sparql.SparqlFieldQuery) Model(org.openrdf.model.Model) TreeModel(org.openrdf.model.impl.TreeModel) Value(org.openrdf.model.Value) TupleQueryResult(org.openrdf.query.TupleQueryResult) RdfValueFactory(org.apache.stanbol.entityhub.model.sesame.RdfValueFactory)

Example 29 with YardException

use of org.apache.stanbol.entityhub.servicesapi.yard.YardException in project stanbol by apache.

the class ReferencedSiteImpl method findEntities.

@Override
public QueryResultList<Entity> findEntities(FieldQuery query) throws SiteException {
    List<Entity> results;
    if (siteConfiguration.getCacheStrategy() == CacheStrategy.all) {
        try {
            // When using the Cache, directly get the representations!
            QueryResultList<Representation> representations = cache.findRepresentation((query));
            results = new ArrayList<Entity>(representations.size());
            for (Representation result : representations) {
                Entity entity = new EntityImpl(getId(), result, null);
                results.add(entity);
                initEntityMetadata(entity, siteMetadata, singletonMap(RdfResourceEnum.isChached.getUri(), (Object) Boolean.TRUE));
            }
            return new QueryResultListImpl<Entity>(query, results, Entity.class);
        } catch (YardException e) {
            if (entitySearcher == null) {
                throw new SiteException("Unable to execute query on Cache " + siteConfiguration.getCacheId(), e);
            } else {
                log.warn(String.format("Error while performing query on Cache %s! Try to use remote site %s as fallback!", siteConfiguration.getCacheId(), siteConfiguration.getQueryUri()), e);
            }
        }
    }
    QueryResultList<String> entityIds;
    if (entitySearcher == null) {
        throw new SiteException(String.format("The ReferencedSite %s does not support queries!", getId()));
    }
    try {
        entityIds = entitySearcher.findEntities(query);
    } catch (IOException e) {
        throw new SiteException(String.format("Unable to execute query on remote site %s with entitySearcher %s!", siteConfiguration.getQueryUri(), siteConfiguration.getEntitySearcherType()), e);
    }
    int numResults = entityIds.size();
    List<Entity> entities = new ArrayList<Entity>(numResults);
    int errors = 0;
    SiteException lastError = null;
    for (String id : entityIds) {
        Entity entity;
        try {
            entity = getEntity(id);
            if (entity == null) {
                log.warn("Unable to create Entity for ID that was selected by an FieldQuery (id=" + id + ")");
            }
            entities.add(entity);
            // use the position in the list as resultSocre
            entity.getRepresentation().set(RdfResourceEnum.resultScore.getUri(), Float.valueOf((float) numResults));
        } catch (SiteException e) {
            lastError = e;
            errors++;
            log.warn(String.format("Unable to get Representation for Entity " + "%s. -> %d Error%s for %d Entities in QueryResult (Reason:%s)", id, errors, errors > 1 ? "s" : "", entityIds.size(), e.getMessage()));
        }
        // decrease numResults because it is used as resultScore for
        // entities
        numResults--;
    }
    if (lastError != null) {
        if (entities.isEmpty()) {
            throw new SiteException("Unable to get anly Representations for " + "Entities selected by the parsed Query (Root-Cause is the " + "last Exception trown)", lastError);
        } else {
            log.warn(String.format("Unable to get %d/%d Represetnations for selected Entities.", errors, entityIds.size()));
            log.warn("Stack trace of the last Exception:", lastError);
        }
    }
    return new QueryResultListImpl<Entity>(query, entities, Entity.class);
}
Also used : Entity(org.apache.stanbol.entityhub.servicesapi.model.Entity) EntityImpl(org.apache.stanbol.entityhub.core.model.EntityImpl) ArrayList(java.util.ArrayList) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) IOException(java.io.IOException) YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) QueryResultListImpl(org.apache.stanbol.entityhub.core.query.QueryResultListImpl) SiteException(org.apache.stanbol.entityhub.servicesapi.site.SiteException)

Example 30 with YardException

use of org.apache.stanbol.entityhub.servicesapi.yard.YardException in project stanbol by apache.

the class CacheComponent method updateServiceRegistration.

private synchronized void updateServiceRegistration(ComponentContext cc, Yard yard, String[] additionalMappings, NamespacePrefixService nsPrefixService) {
    if (cacheRegistration != null) {
        cacheRegistration.unregister();
        cacheRegistration = null;
        cache = null;
    }
    if (cc != null && yard != null) {
        try {
            cache = new CacheImpl(yard, additionalMappings, nsPrefixService);
        } catch (YardException e) {
            log.warn("Unable to init Cache for Yard '" + yard.getId() + "'!", e);
        }
        cacheRegistration = cc.getBundleContext().registerService(Cache.class.getName(), cache, OsgiUtils.copyConfig(cc.getProperties()));
    }
}
Also used : YardException(org.apache.stanbol.entityhub.servicesapi.yard.YardException) CacheImpl(org.apache.stanbol.entityhub.core.site.CacheImpl)

Aggregations

YardException (org.apache.stanbol.entityhub.servicesapi.yard.YardException)31 Representation (org.apache.stanbol.entityhub.servicesapi.model.Representation)15 RepositoryConnection (org.openrdf.repository.RepositoryConnection)10 RepositoryException (org.openrdf.repository.RepositoryException)10 IOException (java.io.IOException)9 SolrServerException (org.apache.solr.client.solrj.SolrServerException)6 PrivilegedActionException (java.security.PrivilegedActionException)5 ArrayList (java.util.ArrayList)5 QueryResultListImpl (org.apache.stanbol.entityhub.core.query.QueryResultListImpl)5 RdfRepresentation (org.apache.stanbol.entityhub.model.sesame.RdfRepresentation)5 EntityImpl (org.apache.stanbol.entityhub.core.model.EntityImpl)4 Entity (org.apache.stanbol.entityhub.servicesapi.model.Entity)4 ManagedSiteException (org.apache.stanbol.entityhub.servicesapi.site.ManagedSiteException)4 HashSet (java.util.HashSet)3 UpdateRequest (org.apache.solr.client.solrj.request.UpdateRequest)3 SolrDocument (org.apache.solr.common.SolrDocument)3 SolrInputDocument (org.apache.solr.common.SolrInputDocument)3 SparqlFieldQuery (org.apache.stanbol.entityhub.query.sparql.SparqlFieldQuery)3 FieldMapper (org.apache.stanbol.entityhub.servicesapi.mapping.FieldMapper)3 FieldQuery (org.apache.stanbol.entityhub.servicesapi.query.FieldQuery)3