Search in sources :

Example 1 with RdfValueFactory

use of org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory in project stanbol by apache.

the class ClerezzaYard method getRepresentation.

/**
 * Internally used to create Representations for URIs
 * @param uri the uri
 * @param check if <code>false</code> than there is no check if the URI
 *     refers to a RDFTerm in the graph that is of type {@link #REPRESENTATION}
 * @return the Representation
 */
protected final Representation getRepresentation(IRI uri, boolean check) {
    final Lock readLock = readLockGraph();
    try {
        if (!check || isRepresentation(uri)) {
            Graph nodeGraph = createRepresentationGraph(uri, graph);
            // Remove the triple internally used to represent an empty Representation
            // ... this will only remove the triple if the Representation is empty
            // but a check would take longer than the this call
            nodeGraph.remove(new TripleImpl(uri, MANAGED_REPRESENTATION, TRUE_LITERAL));
            return ((RdfValueFactory) getValueFactory()).createRdfRepresentation(uri, nodeGraph);
        } else {
            // not found
            return null;
        }
    } finally {
        if (readLock != null) {
            readLock.unlock();
        }
    }
}
Also used : ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) Graph(org.apache.clerezza.commons.rdf.Graph) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory) Lock(java.util.concurrent.locks.Lock)

Example 2 with RdfValueFactory

use of org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory in project stanbol by apache.

the class RdfResultListTest method testRdfResultSorting.

/**
 * Providing a sorted Iteration over query results stored in an RDF
 * graph is not something trivial. Therefore this test
 */
@Test
public void testRdfResultSorting() {
    SortedMap<Double, RdfRepresentation> sorted = new TreeMap<Double, RdfRepresentation>();
    Graph resultGraph = new IndexedGraph();
    RdfValueFactory vf = new RdfValueFactory(resultGraph);
    IRI resultListNode = new IRI(RdfResourceEnum.QueryResultSet.getUri());
    IRI resultProperty = new IRI(RdfResourceEnum.queryResult.getUri());
    for (int i = 0; i < 100; i++) {
        Double rank;
        do {
            // avoid duplicate keys
            rank = Math.random();
        } while (sorted.containsKey(rank));
        RdfRepresentation r = vf.createRepresentation("urn:sortTest:rep." + i);
        // link the representation with the query result set
        resultGraph.add(new TripleImpl(resultListNode, resultProperty, r.getNode()));
        r.set(RdfResourceEnum.resultScore.getUri(), rank);
        sorted.put(rank, r);
    }
    RdfQueryResultList resultList = new RdfQueryResultList(new FieldQueryImpl(), resultGraph);
    if (log.isDebugEnabled()) {
        log.debug("---DEBUG Sorting ---");
        for (Iterator<Representation> it = resultList.iterator(); it.hasNext(); ) {
            Representation r = it.next();
            log.debug("{}: {}", r.getFirst(RdfResourceEnum.resultScore.getUri()), r.getId());
        }
    }
    log.debug("---ASSERT Sorting ---");
    for (Iterator<Representation> it = resultList.iterator(); it.hasNext(); ) {
        Representation r = it.next();
        Double lastkey = sorted.lastKey();
        Representation last = sorted.get(lastkey);
        Assert.assertEquals("score: " + r.getFirst(RdfResourceEnum.resultScore.getUri()) + " of Representation " + r.getId() + " is not as expected " + last.getFirst(RdfResourceEnum.resultScore.getUri()) + " of Representation " + last.getId() + "!", r, last);
        sorted.remove(lastkey);
    }
    Assert.assertTrue(sorted.isEmpty());
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) RdfRepresentation(org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) TreeMap(java.util.TreeMap) FieldQueryImpl(org.apache.stanbol.entityhub.core.query.FieldQueryImpl) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Graph(org.apache.clerezza.commons.rdf.Graph) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) RdfRepresentation(org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory) Test(org.junit.Test)

Example 3 with RdfValueFactory

use of org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory in project stanbol by apache.

the class ReferencedSiteRootResource method executeLDPathQuery.

/**
 * Execute a Query that uses LDPath to process results.
 * @param query the query
 * @param mediaType the mediaType for the response
 * @param headers the http headers of the request
 * @return the response
 */
private Response executeLDPathQuery(Site site, FieldQuery query, String ldpathProgramString, MediaType mediaType, HttpHeaders headers) {
    QueryResultList<Representation> result;
    ValueFactory vf = new RdfValueFactory(new IndexedGraph());
    SiteBackend backend = new SiteBackend(site, vf);
    EntityhubLDPath ldPath = new EntityhubLDPath(backend, vf);
    // copy the selected fields, because we might need to delete some during
    // the preparation phase
    Set<String> selectedFields = new HashSet<String>(query.getSelectedFields());
    // first prepare (only execute the query if the parameters are valid)
    Program<Object> program;
    try {
        program = prepareQueryLDPathProgram(ldpathProgramString, selectedFields, backend, ldPath);
    } catch (LDPathParseException e) {
        log.warn("Unable to parse LDPath program used as select for Query:");
        log.warn("FieldQuery: \n {}", query);
        log.warn("LDPath: \n {}", ((LDPathSelect) query).getLDPathSelect());
        log.warn("Exception:", e);
        return Response.status(Status.BAD_REQUEST).entity(("Unable to parse LDPath program (Messages: " + getLDPathParseExceptionMessage(e) + ")!\n")).header(HttpHeaders.ACCEPT, mediaType).build();
    } catch (IllegalStateException e) {
        log.warn("parsed LDPath program is not compatible with parsed Query!", e);
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).header(HttpHeaders.ACCEPT, mediaType).build();
    }
    // 2. execute the query
    Iterator<Representation> resultIt;
    try {
        // we need to adapt from Entity to Representation
        resultIt = new AdaptingIterator<Entity, Representation>(site.findEntities(query).iterator(), new AdaptingIterator.Adapter<Entity, Representation>() {

            @Override
            public Representation adapt(Entity value, Class<Representation> type) {
                return value.getRepresentation();
            }
        }, Representation.class);
    } catch (SiteException e) {
        String message = String.format("Unable to Query Site '%s' (message: %s)", site.getId(), e.getMessage());
        log.error(message, e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).header(HttpHeaders.ACCEPT, mediaType).build();
    }
    // process the results
    Collection<Representation> transformedResults = transformQueryResults(resultIt, program, selectedFields, ldPath, backend, vf);
    result = new QueryResultListImpl<Representation>(query, transformedResults, Representation.class);
    ResponseBuilder rb = Response.ok(result);
    rb.header(HttpHeaders.CONTENT_TYPE, mediaType + "; charset=utf-8");
    // addCORSOrigin(servletContext, rb, headers);
    return rb.build();
}
Also used : Entity(org.apache.stanbol.entityhub.servicesapi.model.Entity) SiteBackend(org.apache.stanbol.entityhub.ldpath.backend.SiteBackend) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) RdfRepresentation(org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation) ValueFactory(org.apache.stanbol.entityhub.servicesapi.model.ValueFactory) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory) LDPathSelect(org.apache.stanbol.entityhub.ldpath.query.LDPathSelect) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) LDPathParseException(org.apache.marmotta.ldpath.exception.LDPathParseException) SiteException(org.apache.stanbol.entityhub.servicesapi.site.SiteException) ManagedSiteException(org.apache.stanbol.entityhub.servicesapi.site.ManagedSiteException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) EntityhubLDPath(org.apache.stanbol.entityhub.ldpath.EntityhubLDPath) HashSet(java.util.HashSet)

Example 4 with RdfValueFactory

use of org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory in project stanbol by apache.

the class ReferencedSiteRootResource method license2Representation.

private Representation license2Representation(String id, License license) {
    RdfValueFactory valueFactory = RdfValueFactory.getInstance();
    RdfRepresentation rep = valueFactory.createRepresentation(id);
    if (license.getName() != null) {
        rep.add("http://purl.org/dc/terms/license", license.getName());
        rep.add("http://www.w3.org/2000/01/rdf-schema#label", license.getName());
        rep.add("http://purl.org/dc/terms/title", license.getName());
    }
    if (license.getText() != null) {
        rep.add("http://www.w3.org/2000/01/rdf-schema#description", license.getText());
    }
    rep.add("http://creativecommons.org/ns#licenseUrl", license.getUrl() == null ? id : license.getUrl());
    return rep;
}
Also used : RdfRepresentation(org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory)

Example 5 with RdfValueFactory

use of org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory in project stanbol by apache.

the class ReferencedSiteRootResource method site2Representation.

/*
     * Referenced Site Metadata
     */
/**
 * Transforms a site to a Representation that can be serialised
 * @param context
 * @return
 */
private Representation site2Representation(Site site, String id) {
    RdfValueFactory valueFactory = RdfValueFactory.getInstance();
    RdfRepresentation rep = valueFactory.createRepresentation(id);
    String namespace = NamespaceEnum.entityhub.getNamespace();
    rep.add(namespace + "localMode", site.supportsLocalMode());
    rep.add(namespace + "supportsSearch", site.supportsSearch());
    SiteConfiguration config = site.getConfiguration();
    rep.add("http://www.w3.org/2000/01/rdf-schema#label", config.getName());
    rep.add("http://www.w3.org/1999/02/22-rdf-syntax-ns#type", valueFactory.createReference(namespace + "ReferencedSite"));
    if (config.getDescription() != null) {
        rep.add("http://www.w3.org/2000/01/rdf-schema#description", config.getDescription());
    }
    if (config.getAttribution() != null) {
        rep.add("http://creativecommons.org/ns#attributionName", config.getAttribution());
    }
    if (config.getAttributionUrl() != null) {
        rep.add("http://creativecommons.org/ns#attributionURL", config.getAttributionUrl());
    }
    // add the licenses
    if (config.getLicenses() != null) {
        int count = 0;
        for (License license : config.getLicenses()) {
            String licenseUrl;
            if (license.getUrl() != null) {
                licenseUrl = license.getUrl();
            } else {
                licenseUrl = id + (!id.endsWith("/") ? "/" : "") + LICENSE_PATH + '/' + LICENSE_NAME + (count > 0 ? count : "");
                count++;
            }
            // if defined add the name to dc:license
            if (license.getName() != null) {
                rep.add("http://purl.org/dc/terms/license", licenseUrl);
            }
            // link to the license via cc:license
            rep.add("http://creativecommons.org/ns#license", licenseUrl);
        }
    }
    if (config.getEntityPrefixes() != null) {
        for (String prefix : config.getEntityPrefixes()) {
            rep.add(namespace + "entityPrefix", prefix);
        }
    } else {
        // all entities are allowed/processed
        rep.add(namespace + "entityPrefix", "*");
    }
    if (config instanceof ReferencedSiteConfiguration) {
        ReferencedSiteConfiguration refConfig = (ReferencedSiteConfiguration) config;
        if (refConfig.getCacheStrategy() != null) {
            rep.add(namespace + "cacheStrategy", valueFactory.createReference(namespace + "cacheStrategy-" + refConfig.getCacheStrategy().name()));
        }
        // add the accessUri and queryUri
        if (refConfig.getAccessUri() != null) {
            rep.add(namespace + "accessUri", valueFactory.createReference(refConfig.getAccessUri()));
        }
        if (refConfig.getQueryUri() != null) {
            rep.add(namespace + "queryUri", valueFactory.createReference(refConfig.getQueryUri()));
        }
    }
    return rep;
}
Also used : ReferencedSiteConfiguration(org.apache.stanbol.entityhub.servicesapi.site.ReferencedSiteConfiguration) RdfRepresentation(org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation) License(org.apache.stanbol.entityhub.servicesapi.site.License) SiteConfiguration(org.apache.stanbol.entityhub.servicesapi.site.SiteConfiguration) ReferencedSiteConfiguration(org.apache.stanbol.entityhub.servicesapi.site.ReferencedSiteConfiguration) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory)

Aggregations

RdfValueFactory (org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory)13 IndexedGraph (org.apache.stanbol.commons.indexedgraph.IndexedGraph)9 Representation (org.apache.stanbol.entityhub.servicesapi.model.Representation)8 Graph (org.apache.clerezza.commons.rdf.Graph)7 HashSet (java.util.HashSet)6 IRI (org.apache.clerezza.commons.rdf.IRI)6 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)5 RdfRepresentation (org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation)5 EntityhubLDPath (org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)4 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)3 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)3 LiteralFactory (org.apache.clerezza.rdf.core.LiteralFactory)3 LDPathParseException (org.apache.marmotta.ldpath.exception.LDPathParseException)3 LDPathSelect (org.apache.stanbol.entityhub.ldpath.query.LDPathSelect)3 ValueFactory (org.apache.stanbol.entityhub.servicesapi.model.ValueFactory)3 Test (org.junit.Test)3 HashMap (java.util.HashMap)2 Lock (java.util.concurrent.locks.Lock)2 Triple (org.apache.clerezza.commons.rdf.Triple)2 EntityhubException (org.apache.stanbol.entityhub.servicesapi.EntityhubException)2