Search in sources :

Example 26 with Literal

use of org.apache.clerezza.commons.rdf.Literal in project stanbol by apache.

the class EnhancementRDFUtils method writeEntityAnnotation.

/**
     * @param literalFactory
     *            the LiteralFactory to use
     * @param graph
     *            the Graph to use
     * @param contentItemId
     *            the contentItemId the enhancement is extracted from
     * @param relatedEnhancements
     *            enhancements this textAnnotation is related to
     * @param suggestion
     *            the entity suggestion
     * @param nameField the field used to extract the name
     * @param lang the preferred language to include or <code>null</code> if none
     */
public static IRI writeEntityAnnotation(EnhancementEngine engine, LiteralFactory literalFactory, Graph graph, IRI contentItemId, Collection<BlankNodeOrIRI> relatedEnhancements, Suggestion suggestion, String nameField, String lang) {
    Representation rep = suggestion.getEntity().getRepresentation();
    // 1. extract the "best label"
    //Start with the matched one
    Text label = suggestion.getMatchedLabel();
    //if the matched label is not in the requested language
    boolean langMatch = (lang == null && label.getLanguage() == null) || (label.getLanguage() != null && label.getLanguage().startsWith(lang));
    //search if a better label is available for this Entity
    if (!langMatch) {
        Iterator<Text> labels = rep.getText(nameField);
        while (labels.hasNext() && !langMatch) {
            Text actLabel = labels.next();
            langMatch = (lang == null && actLabel.getLanguage() == null) || (actLabel.getLanguage() != null && actLabel.getLanguage().startsWith(lang));
            if (langMatch) {
                //if the language matches ->
                //override the matched label
                label = actLabel;
            }
        }
    }
    //else the matched label will be the best to use
    Literal literal;
    if (label.getLanguage() == null) {
        literal = new PlainLiteralImpl(label.getText());
    } else {
        literal = new PlainLiteralImpl(label.getText(), new Language(label.getLanguage()));
    }
    // Now create the entityAnnotation
    IRI entityAnnotation = EnhancementEngineHelper.createEntityEnhancement(graph, engine, contentItemId);
    // first relate this entity annotation to the text annotation(s)
    for (BlankNodeOrIRI enhancement : relatedEnhancements) {
        graph.add(new TripleImpl(entityAnnotation, DC_RELATION, enhancement));
    }
    IRI entityUri = new IRI(rep.getId());
    // add the link to the referred entity
    graph.add(new TripleImpl(entityAnnotation, ENHANCER_ENTITY_REFERENCE, entityUri));
    // add the label parsed above
    graph.add(new TripleImpl(entityAnnotation, ENHANCER_ENTITY_LABEL, literal));
    if (suggestion.getScore() != null) {
        graph.add(new TripleImpl(entityAnnotation, ENHANCER_CONFIDENCE, literalFactory.createTypedLiteral(suggestion.getScore())));
    }
    Iterator<Reference> types = rep.getReferences(RDF_TYPE.getUnicodeString());
    while (types.hasNext()) {
        graph.add(new TripleImpl(entityAnnotation, ENHANCER_ENTITY_TYPE, new IRI(types.next().getReference())));
    }
    //add the name of the ReferencedSite that manages the Entity
    if (suggestion.getEntity().getSite() != null) {
        graph.add(new TripleImpl(entityAnnotation, new IRI(RdfResourceEnum.site.getUri()), new PlainLiteralImpl(suggestion.getEntity().getSite())));
    }
    return entityAnnotation;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) Language(org.apache.clerezza.commons.rdf.Language) PlainLiteralImpl(org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl) Reference(org.apache.stanbol.entityhub.servicesapi.model.Reference) Literal(org.apache.clerezza.commons.rdf.Literal) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) Text(org.apache.stanbol.entityhub.servicesapi.model.Text) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)

Example 27 with Literal

use of org.apache.clerezza.commons.rdf.Literal in project stanbol by apache.

the class TestEntityLinkingEnhancementEngine method validateAllEntityAnnotations.

private static int validateAllEntityAnnotations(NamedEntityTaggingEngine entityLinkingEngine, ContentItem ci) {
    Map<IRI, RDFTerm> expectedValues = new HashMap<IRI, RDFTerm>();
    expectedValues.put(ENHANCER_EXTRACTED_FROM, ci.getUri());
    expectedValues.put(DC_CREATOR, LiteralFactory.getInstance().createTypedLiteral(entityLinkingEngine.getClass().getName()));
    Iterator<Triple> entityAnnotationIterator = ci.getMetadata().filter(null, RDF_TYPE, ENHANCER_ENTITYANNOTATION);
    //adding null as expected for confidence makes it a required property
    expectedValues.put(Properties.ENHANCER_CONFIDENCE, null);
    int entityAnnotationCount = 0;
    while (entityAnnotationIterator.hasNext()) {
        IRI entityAnnotation = (IRI) entityAnnotationIterator.next().getSubject();
        // test if selected Text is added
        validateEntityAnnotation(ci.getMetadata(), entityAnnotation, expectedValues);
        //fise:confidence now checked by EnhancementStructureHelper (STANBOL-630)
        //            Iterator<Triple> confidenceIterator = ci.getMetadata().filter(entityAnnotation, ENHANCER_CONFIDENCE, null);
        //            assertTrue("Expected fise:confidence value is missing (entityAnnotation "
        //                    +entityAnnotation+")",confidenceIterator.hasNext());
        //            Double confidence = LiteralFactory.getInstance().createObject(Double.class,
        //                (TypedLiteral)confidenceIterator.next().getObject());
        //            assertTrue("fise:confidence MUST BE <= 1 (value= '"+confidence
        //                    + "',entityAnnotation " +entityAnnotation+")",
        //                    1.0 >= confidence.doubleValue());
        //            assertTrue("fise:confidence MUST BE >= 0 (value= '"+confidence
        //                    +"',entityAnnotation "+entityAnnotation+")",
        //                    0.0 <= confidence.doubleValue());
        //Test the entityhub:site property (STANBOL-625)
        IRI ENTITYHUB_SITE = new IRI(RdfResourceEnum.site.getUri());
        Iterator<Triple> entitySiteIterator = ci.getMetadata().filter(entityAnnotation, ENTITYHUB_SITE, null);
        assertTrue("Expected entityhub:site value is missing (entityAnnotation " + entityAnnotation + ")", entitySiteIterator.hasNext());
        RDFTerm siteResource = entitySiteIterator.next().getObject();
        assertTrue("entityhub:site values MUST BE Literals", siteResource instanceof Literal);
        assertEquals("'dbpedia' is expected as entityhub:site value", "dbpedia", ((Literal) siteResource).getLexicalForm());
        assertFalse("entityhub:site MUST HAVE only a single value", entitySiteIterator.hasNext());
        entityAnnotationCount++;
    }
    return entityAnnotationCount;
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) IRI(org.apache.clerezza.commons.rdf.IRI) HashMap(java.util.HashMap) Literal(org.apache.clerezza.commons.rdf.Literal) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm)

Example 28 with Literal

use of org.apache.clerezza.commons.rdf.Literal in project stanbol by apache.

the class UserResource method rolesCheckboxes.

/**
     * Provides HTML corresponding to a user's roles
     *
     * all roles are listed with checkboxes, the roles this user has are checked
     *
     * (isn't very pretty but is just a one-off)
     *
     * @param userName the user in question
     * @return HTML checkboxes as HTTP response
     */
@GET
@Path("users/{username}/rolesCheckboxes")
@Produces(MediaType.TEXT_HTML)
public Response rolesCheckboxes(@PathParam("username") String userName) {
    // return new RdfViewable("rolesCheckboxes", getRoleType(), this.getClass());
    StringBuffer html = new StringBuffer();
    Iterator<Triple> allRoleTriples = systemGraph.filter(null, RDF.type, PERMISSION.Role);
    ArrayList<String> allRoleNames = new ArrayList<String>();
    Lock readLock = systemGraph.getLock().readLock();
    readLock.lock();
    try {
        // pulls out all role names
        while (allRoleTriples.hasNext()) {
            Triple triple = allRoleTriples.next();
            GraphNode roleNode = new GraphNode(triple.getSubject(), systemGraph);
            Iterator<Literal> titlesIterator = roleNode.getLiterals(DC.title);
            while (titlesIterator.hasNext()) {
                allRoleNames.add(titlesIterator.next().getLexicalForm());
            }
        }
    } finally {
        readLock.unlock();
    }
    Graph rolesGraph = getUserRolesGraph(userName);
    ArrayList<String> userRoleNames = new ArrayList<String>();
    Iterator<Triple> userRoleTriples = rolesGraph.filter(null, RDF.type, PERMISSION.Role);
    while (userRoleTriples.hasNext()) {
        Triple triple = userRoleTriples.next();
        GraphNode roleNode = new GraphNode(triple.getSubject(), rolesGraph);
        Iterator<Literal> titlesIterator = roleNode.getLiterals(DC.title);
        while (titlesIterator.hasNext()) {
            userRoleNames.add(titlesIterator.next().getLexicalForm());
        }
    }
    for (int i = 0; i < allRoleNames.size(); i++) {
        String role = allRoleNames.get(i);
        if (role.equals("BasePermissionsRole")) {
            // filter out
            continue;
        }
        if (userRoleNames.contains(role)) {
            html.append("<input class=\"role\" type=\"checkbox\" id=\"").append(role).append("\" name=\"").append(role).append("\" value=\"").append(role).append("\" checked=\"checked\" />");
        } else {
            html.append("<input class=\"role\" type=\"checkbox\" id=\"").append(role).append("\" name=\"").append(role).append("\" value=\"").append(role).append("\" />");
        }
        html.append("<label for=\"").append(role).append("\">").append(role).append("</label>");
        html.append("<br />");
    }
    return Response.ok(html.toString()).build();
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Graph(org.apache.clerezza.commons.rdf.Graph) Literal(org.apache.clerezza.commons.rdf.Literal) ArrayList(java.util.ArrayList) GraphNode(org.apache.clerezza.rdf.utils.GraphNode) Lock(java.util.concurrent.locks.Lock) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 29 with Literal

use of org.apache.clerezza.commons.rdf.Literal in project stanbol by apache.

the class UserResource method changeUser.

/**
     * Modify user given a graph describing the change.
     *
     * @param inputGraph change graph
     * @return HTTP response
     */
@POST
@Consumes(SupportedFormat.TURTLE)
@Path("change-user")
public Response changeUser(ImmutableGraph inputGraph) {
    Lock readLock = systemGraph.getLock().readLock();
    readLock.lock();
    Iterator<Triple> changes = inputGraph.filter(null, null, Ontology.Change);
    Triple oldTriple = null;
    Triple newTriple = null;
    if (changes.hasNext()) {
        Triple changeTriple = changes.next();
        BlankNodeOrIRI changeNode = changeTriple.getSubject();
        Literal userName = (Literal) inputGraph.filter(changeNode, PLATFORM.userName, null).next().getObject();
        Iterator<Triple> userTriples = systemGraph.filter(null, PLATFORM.userName, userName);
        //     if (userTriples.hasNext()) {
        BlankNodeOrIRI userNode = userTriples.next().getSubject();
        IRI predicateIRI = (IRI) inputGraph.filter(changeNode, Ontology.predicate, null).next().getObject();
        // handle old value (if it exists)
        Iterator<Triple> iterator = inputGraph.filter(changeNode, Ontology.oldValue, null);
        RDFTerm oldValue = null;
        if (iterator.hasNext()) {
            oldValue = iterator.next().getObject();
            // Triple oldTriple = systemGraph.filter(null, predicateIRI,
            // oldValue).next();
            Iterator<Triple> oldTriples = systemGraph.filter(userNode, predicateIRI, oldValue);
            if (oldTriples.hasNext()) {
                oldTriple = oldTriples.next();
            }
        }
        RDFTerm newValue = inputGraph.filter(changeNode, Ontology.newValue, null).next().getObject();
        newTriple = new TripleImpl(userNode, predicateIRI, newValue);
    // }
    }
    readLock.unlock();
    Lock writeLock = systemGraph.getLock().writeLock();
    writeLock.lock();
    if (oldTriple != null) {
        systemGraph.remove(oldTriple);
    }
    systemGraph.add(newTriple);
    writeLock.unlock();
    // seems the most appropriate response
    return Response.noContent().build();
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) Literal(org.apache.clerezza.commons.rdf.Literal) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) Lock(java.util.concurrent.locks.Lock) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 30 with Literal

use of org.apache.clerezza.commons.rdf.Literal in project stanbol by apache.

the class PermissionDefinitions method lookForPermissions.

/**
	 * Look for all permissions of a role and add them to a list.
	 * And if the role has another role, then execute this function recursively,
	 * until all permissions are found.
	 * 
	 * @param role	a <code>BlankNodeOrIRI</code> which is either a user or a role
	 * @param permInfoList	a list with all the added permissions of this bundle
	 */
private void lookForPermissions(BlankNodeOrIRI role, List<PermissionInfo> permInfoList) {
    Iterator<Triple> permissionTriples = systemGraph.filter(role, PERMISSION.hasPermission, null);
    while (permissionTriples.hasNext()) {
        BlankNodeOrIRI permission = (BlankNodeOrIRI) permissionTriples.next().getObject();
        Iterator<Triple> javaPermissionTriples = systemGraph.filter(permission, PERMISSION.javaPermissionEntry, null);
        while (javaPermissionTriples.hasNext()) {
            Triple t = javaPermissionTriples.next();
            Literal permEntry = (Literal) t.getObject();
            permInfoList.add(new PermissionInfo(permEntry.getLexicalForm()));
        }
    }
    Iterator<Triple> roleTriples = systemGraph.filter(role, SIOC.has_function, null);
    while (roleTriples.hasNext()) {
        BlankNodeOrIRI anotherRole = (BlankNodeOrIRI) roleTriples.next().getObject();
        this.lookForPermissions(anotherRole, permInfoList);
    }
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) PermissionInfo(org.osgi.service.permissionadmin.PermissionInfo) Literal(org.apache.clerezza.commons.rdf.Literal) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI)

Aggregations

Literal (org.apache.clerezza.commons.rdf.Literal)71 IRI (org.apache.clerezza.commons.rdf.IRI)35 RDFTerm (org.apache.clerezza.commons.rdf.RDFTerm)35 Triple (org.apache.clerezza.commons.rdf.Triple)30 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)22 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)20 ArrayList (java.util.ArrayList)16 PlainLiteralImpl (org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl)16 Language (org.apache.clerezza.commons.rdf.Language)12 Graph (org.apache.clerezza.commons.rdf.Graph)11 Test (org.junit.Test)10 HashSet (java.util.HashSet)9 Date (java.util.Date)8 Lock (java.util.concurrent.locks.Lock)6 Entity (org.apache.stanbol.enhancer.engines.entitylinking.Entity)5 HashMap (java.util.HashMap)4 SimpleGraph (org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph)4 NoConvertorException (org.apache.clerezza.rdf.core.NoConvertorException)4 Representation (org.apache.stanbol.entityhub.servicesapi.model.Representation)4 Collection (java.util.Collection)3