Search in sources :

Example 31 with RDFTerm

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

the class UserResource method changeLiteral.

/**
     * Replaces/inserts literal value for predicate assumes there is only one
     * triple for the given predicate new value is added before deleting old one
     * in case user is modifying their own data in which case they need triples
     * in place for rights etc.
     *
     * @param userNode node in systemGraph corresponding to the user to change
     * @param predicate property of the triple to change
     * @param newValue new value for given predicate
     */
private void changeLiteral(GraphNode userNode, IRI predicate, String newValue) {
    Iterator<Triple> oldTriples = systemGraph.filter((BlankNodeOrIRI) userNode.getNode(), predicate, null);
    ArrayList<Triple> oldBuffer = new ArrayList<Triple>();
    RDFTerm oldObject = null;
    Lock readLock = systemGraph.getLock().readLock();
    readLock.lock();
    try {
        while (oldTriples.hasNext()) {
            Triple triple = oldTriples.next();
            oldObject = triple.getObject();
            oldBuffer.add(triple);
        }
    } finally {
        readLock.unlock();
    }
    // filter appears to see plain literals and xsd:strings as differerent
    // so not
    // userNode.addPropertyValue(predicate, newValue);
    Literal newObject = new PlainLiteralImpl(newValue);
    userNode.addProperty(predicate, newObject);
    if (newObject.equals(oldObject)) {
        return;
    }
    systemGraph.removeAll(oldBuffer);
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) PlainLiteralImpl(org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl) Literal(org.apache.clerezza.commons.rdf.Literal) ArrayList(java.util.ArrayList) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) Lock(java.util.concurrent.locks.Lock)

Example 32 with RDFTerm

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

the class UserResource method remove.

/**
     * Deletes a named user
     *
     * @param userName
     */
private void remove(String userName) {
    RDFTerm userResource = getNamedUser(userName).getNode();
    Iterator<Triple> userTriples = systemGraph.filter((BlankNodeOrIRI) userResource, null, null);
    ArrayList<Triple> buffer = new ArrayList<Triple>();
    Lock readLock = systemGraph.getLock().readLock();
    readLock.lock();
    try {
        while (userTriples.hasNext()) {
            Triple triple = userTriples.next();
            buffer.add(triple);
        }
    } finally {
        readLock.unlock();
    }
    // ImmutableGraph context = getNamedUser(userName).getNodeContext();
    Lock writeLock = systemGraph.getLock().writeLock();
    writeLock.lock();
    try {
        systemGraph.removeAll(buffer);
    } finally {
        writeLock.unlock();
    }
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) ArrayList(java.util.ArrayList) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) Lock(java.util.concurrent.locks.Lock)

Example 33 with RDFTerm

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

the class EnhancementStructureHelper method validateTopicAnnotation.

/**
     * Checks if a fise:TopicAnnotation is valid as defined by 
     * <a herf="https://issues.apache.org/jira/browse/STANBOL-617">STANBOL-617</a>. 
     * NOTE that this also validates all fise:Enhancement related requirements by 
     * calling {@link #validateEnhancement(Graph, IRI, Map)}
     * @param enhancements the enhancements graph
     * @param topicAnnotation the topic annotation to validate
     * @param expectedValues expected values (properties for the values are used as keys)
     */
public static void validateTopicAnnotation(Graph enhancements, IRI topicAnnotation, Map<IRI, RDFTerm> expectedValues) {
    //validate the rdf:type
    Iterator<Triple> rdfTypeIterator = enhancements.filter(topicAnnotation, RDF_TYPE, ENHANCER_TOPICANNOTATION);
    assertTrue("Parsed Enhancement " + topicAnnotation + " is missing the fise:TopicAnnotation type ", rdfTypeIterator.hasNext());
    //TopicAnnotations need to be linked to TextAnnotations describing the
    //section of the text that has a specific Topic.
    //If the topic is for the whole text the TextAnnotation will have no
    //selected-text value
    Iterator<Triple> relationToTextAnnotationIterator = enhancements.filter(topicAnnotation, DC_RELATION, null);
    // check if the relation to the text annotation is set
    assertTrue(relationToTextAnnotationIterator.hasNext());
    while (relationToTextAnnotationIterator.hasNext()) {
        // test if the referred annotations are text annotations
        IRI referredTextAnnotation = (IRI) relationToTextAnnotationIterator.next().getObject();
        assertTrue(enhancements.filter(referredTextAnnotation, RDF_TYPE, ENHANCER_TEXTANNOTATION).hasNext());
    }
    // test if an entity (the topic) is referred (NOTE: in contrast to
    // fise:EntityAnnotations this property is NOT required - cardinality [0..*]
    Iterator<Triple> entityReferenceIterator = enhancements.filter(topicAnnotation, ENHANCER_ENTITY_REFERENCE, null);
    RDFTerm expectedReferencedEntity = expectedValues.get(ENHANCER_ENTITY_REFERENCE);
    while (entityReferenceIterator.hasNext()) {
        //check possible multiple references
        RDFTerm entityReferenceResource = entityReferenceIterator.next().getObject();
        // test if the reference is an URI
        assertTrue("fise:entity-reference value MUST BE of URIs", entityReferenceResource instanceof IRI);
        if (expectedReferencedEntity != null && expectedReferencedEntity.equals(entityReferenceResource)) {
            //found
            expectedReferencedEntity = null;
        }
    }
    assertNull("EntityAnnotation " + topicAnnotation + "fise:entity-reference has not the expected value " + expectedReferencedEntity + "!", expectedReferencedEntity);
    //test if the entity label is set (required)
    Iterator<Triple> entityLabelIterator = enhancements.filter(topicAnnotation, ENHANCER_ENTITY_LABEL, null);
    assertTrue(entityLabelIterator.hasNext());
    RDFTerm expectedEntityLabel = expectedValues.get(ENHANCER_ENTITY_LABEL);
    while (entityLabelIterator.hasNext()) {
        RDFTerm entityLabelResource = entityLabelIterator.next().getObject();
        assertTrue("fise:entity-label values MUST BE PlainLiterals (EntityAnnotation: " + topicAnnotation + ")!", entityLabelResource instanceof Literal);
        if (expectedEntityLabel != null && expectedEntityLabel.equals(entityLabelResource)) {
            expectedEntityLabel = null;
        }
    }
    assertNull("The expected EntityLabel " + expectedEntityLabel + " was not found", expectedEntityLabel);
    // test fise:entity-type(s). NOTE: this is not required - cardinality [0..*]
    Iterator<Triple> entityTypeIterator = enhancements.filter(topicAnnotation, Properties.ENHANCER_ENTITY_TYPE, null);
    RDFTerm expectedEntityType = expectedValues.get(Properties.ENHANCER_ENTITY_TYPE);
    if (entityTypeIterator.hasNext()) {
        RDFTerm entityTypeResource = entityTypeIterator.next().getObject();
        assertTrue("fise:entity-type values MUST BE URIs", entityTypeResource instanceof IRI);
        if (expectedEntityType != null && expectedEntityType.equals(entityTypeResource)) {
            //found
            expectedEntityType = null;
        }
    }
    assertNull("The expected fise:entity-type value " + expectedEntityType + " was not found!", expectedEntityType);
    //test all properties required by fise:Enhancement
    validateEnhancement(enhancements, topicAnnotation, expectedValues);
}
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) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm)

Example 34 with RDFTerm

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

the class EnhancementStructureHelper method validateEnhancement.

/**
     * Validates all fise:Enhancement related properties and values. NOTE that
     * this method is called by {@link #validateEntityAnnotation(Graph, IRI, Map)}
     * and {@link #validateTextAnnotation(Graph, IRI, String)}.
     * @param enhancements the enhancements graph
     * @param enhancement the fise:Enhancement to validate
     * @param expectedValues expected values (properties for the values are used as keys)
     */
public static void validateEnhancement(Graph enhancements, IRI enhancement, Map<IRI, RDFTerm> expectedValues) {
    //validate the rdf:type
    Iterator<Triple> rdfTypeIterator = enhancements.filter(enhancement, RDF_TYPE, ENHANCER_ENHANCEMENT);
    assertTrue("Parsed Enhancement " + enhancement + " is missing the fise:Enhancement type ", rdfTypeIterator.hasNext());
    //validate the creator
    Iterator<Triple> creatorIterator = enhancements.filter(enhancement, Properties.DC_CREATOR, null);
    assertTrue("Enhancements MUST HAVE a creator", creatorIterator.hasNext());
    RDFTerm creatorResource = creatorIterator.next().getObject();
    assertTrue("Creator MUST BE an TypedLiteral (found '" + creatorResource.getClass().getSimpleName() + "')!", creatorResource instanceof Literal || creatorResource instanceof IRI);
    if (creatorResource instanceof Literal) {
        assertEquals("The dc:creator value MUST be of dataType xsd:string", XSD.string, ((Literal) creatorResource).getDataType());
    }
    RDFTerm expectedCreator = expectedValues.get(Properties.DC_CREATOR);
    if (expectedCreator != null) {
        assertEquals("Creator is not the expected value!", expectedCreator, creatorResource);
    }
    assertFalse("only a single creater MUST BE present for an Enhancement", creatorIterator.hasNext());
    //validate the optional contributor
    RDFTerm expectedContributor = expectedValues.get(DCTERMS.contributor);
    Iterator<Triple> contributorIterator = enhancements.filter(enhancement, DCTERMS.contributor, null);
    while (contributorIterator.hasNext()) {
        RDFTerm contributorResource = contributorIterator.next().getObject();
        assertTrue("Creator MUST BE an TypedLiteral or an IRI (found '" + contributorResource.getClass().getSimpleName() + "')!", contributorResource instanceof Literal || contributorResource instanceof IRI);
        if (contributorResource instanceof Literal) {
            assertEquals("The dc:contributor value MUST be of dataType xsd:string", XSD.string, ((Literal) contributorResource).getDataType());
        }
        if (expectedContributor != null && expectedContributor.equals(expectedContributor)) {
            //found
            expectedContributor = null;
        }
    }
    assertNull("The expected contributor '" + expectedContributor + "'was not present in the Enhancement", expectedContributor);
    //validate creation date
    Iterator<Triple> createdIterator = enhancements.filter(enhancement, Properties.DC_CREATED, null);
    assertTrue("The creation date MUST BE present for an Enhancement", createdIterator.hasNext());
    RDFTerm createdResource = createdIterator.next().getObject();
    assertTrue("Creation date MUST be a typed Literal", createdResource instanceof Literal);
    assertTrue("Creation date MUST have the dataTyoe xsd:dateTime", XSD.dateTime.equals(((Literal) createdResource).getDataType()));
    Date creationDate = LiteralFactory.getInstance().createObject(Date.class, (Literal) createdResource);
    assertNotNull("Unable to convert " + createdResource + " to a Java Date object", creationDate);
    Date now = new Date();
    assertTrue("CreationDate MUST NOT be in the Future", now.after(creationDate) || now.equals(creationDate));
    assertFalse("Only a single createnDate MUST BE present", createdIterator.hasNext());
    //validate optional modification date if present
    Iterator<Triple> modDateIterator = enhancements.filter(enhancement, DCTERMS.modified, null);
    while (modDateIterator.hasNext()) {
        RDFTerm modDateResurce = modDateIterator.next().getObject();
        assertTrue("Creation date MUST be a typed Literal", modDateResurce instanceof Literal);
        assertTrue("Creation date MUST have the dataTyoe xsd:dateTime", XSD.dateTime.equals(((Literal) modDateResurce).getDataType()));
        Date modDate = LiteralFactory.getInstance().createObject(Date.class, (Literal) modDateResurce);
        assertNotNull("Unable to convert " + modDateResurce + " to a Java Date object", modDate);
        assertTrue("CreationDate MUST NOT be in the Future", new Date().after(modDate));
    }
    //validate the fise:extracted-from
    Iterator<Triple> extractedIterator = enhancements.filter(enhancement, Properties.ENHANCER_EXTRACTED_FROM, null);
    assertTrue("The fise:extracted-from property MUST BE present for an Enhancement", extractedIterator.hasNext());
    RDFTerm extractedResource = extractedIterator.next().getObject();
    assertTrue("Creator MUST BE an IRI (found '" + extractedResource.getClass().getSimpleName() + "')!", extractedResource instanceof IRI);
    RDFTerm expectedExtractedFrom = expectedValues.get(Properties.ENHANCER_EXTRACTED_FROM);
    if (expectedExtractedFrom != null) {
        assertEquals("fise:extracted-from has not the expected value!", expectedExtractedFrom, extractedResource);
    }
    assertFalse("only a single creater MUST BE present for an Enhancement", extractedIterator.hasNext());
    //validate that all dc:requires and dc:relation link to resources of type fise:Enhancement
    Iterator<Triple> relatedIterator = enhancements.filter(enhancement, Properties.DC_RELATION, null);
    while (relatedIterator.hasNext()) {
        RDFTerm relatedResource = relatedIterator.next().getObject();
        assertTrue("dc:relation values MUST BE URIs", relatedResource instanceof IRI);
        Iterator<Triple> relatedTypes = enhancements.filter((IRI) relatedResource, RDF_TYPE, TechnicalClasses.ENHANCER_ENHANCEMENT);
        assertTrue("dc:relation Resources MUST BE of rdf:type fise:Enhancement", relatedTypes.hasNext());
    }
    Iterator<Triple> requiresIterator = enhancements.filter(enhancement, Properties.DC_REQUIRES, null);
    while (requiresIterator.hasNext()) {
        RDFTerm requiredResource = requiresIterator.next().getObject();
        assertTrue("dc:requires values MUST BE URIs", requiredResource instanceof IRI);
        Iterator<Triple> relatedTypes = enhancements.filter((IRI) requiredResource, RDF_TYPE, TechnicalClasses.ENHANCER_ENHANCEMENT);
        assertTrue("dc:requires Resources MUST BE of rdf:type fise:Enhancement", relatedTypes.hasNext());
    }
    //validate that fise:confidence has [0..1] values and are of type xsd:float
    Iterator<Triple> confidenceIterator = enhancements.filter(enhancement, Properties.ENHANCER_CONFIDENCE, null);
    boolean confidenceRequired = expectedValues.containsKey(Properties.ENHANCER_CONFIDENCE);
    if (confidenceIterator.hasNext()) {
        //confidence is optional
        RDFTerm confidenceResource = confidenceIterator.next().getObject();
        assertTrue("fise:confidence value MUST BE a TypedLiteral", confidenceResource instanceof Literal);
        assertTrue("fise:confidence MUST BE xsd:double", XSD.double_.equals(((Literal) confidenceResource).getDataType()));
        Double confidence = LiteralFactory.getInstance().createObject(Double.class, (Literal) confidenceResource);
        assertNotNull("Unable to convert TypedLiteral '" + confidenceResource + "' to a Java Double value", confidence);
        assertFalse("fise:confidence MUST HAVE [0..1] values", confidenceIterator.hasNext());
        //STANBOL-630: confidence [0..1]
        assertTrue("fise:confidence MUST BE <= 1 (value= '" + confidence + "',enhancement " + enhancement + ")", 1.0 >= confidence.doubleValue());
        assertTrue("fise:confidence MUST BE >= 0 (value= '" + confidence + "',enhancement " + enhancement + ")", 0.0 <= confidence.doubleValue());
        RDFTerm expectedConfidence = expectedValues.get(Properties.ENHANCER_CONFIDENCE);
        if (expectedConfidence != null) {
            assertEquals("The fise:confidence for enhancement " + enhancement + " does not have the expected value", expectedConfidence, confidenceResource);
        }
    } else {
        assertFalse("The required fise:confidence value is missing for enhancement " + enhancement, confidenceRequired);
    }
    //validate that the (optional) dc:type is an URI and that there are not multiple values
    Iterator<Triple> dcTypeIterator = enhancements.filter(enhancement, Properties.DC_TYPE, null);
    RDFTerm expectedDcType = expectedValues.get(Properties.DC_TYPE);
    if (dcTypeIterator.hasNext()) {
        //dc:type is optional
        RDFTerm dcTypeResource = dcTypeIterator.next().getObject();
        assertTrue("dc:type values MUST BE URIs", dcTypeResource instanceof IRI);
        if (expectedDcType != null) {
            assertEquals("The dc:type value is not the expected " + expectedDcType + "!", expectedDcType, dcTypeResource);
        }
        assertFalse("Only a single dc:type value is allowed!", dcTypeIterator.hasNext());
    }
    //validate the fise:confidence-value introduced by STANBOL-631
    Iterator<Triple> confidenceLevelIterator = enhancements.filter(enhancement, Properties.ENHANCER_CONFIDENCE_LEVEL, null);
    RDFTerm expectedConfidenceValue = expectedValues.get(Properties.ENHANCER_CONFIDENCE_LEVEL);
    if (confidenceLevelIterator.hasNext()) {
        RDFTerm confidenceLevelResource = confidenceLevelIterator.next().getObject();
        assertTrue("fise:confidence-level values MUST BE URIs but found " + confidenceLevelResource, confidenceLevelResource instanceof IRI);
        assertNotNull("The fise:confidence-level value MUST BE one of the four " + "values defined in the ontology! (found: " + confidenceLevelResource + " | enhancement " + enhancement + ")", CONFIDENCE_LEVEL_ENUM.getConfidenceLevel((IRI) confidenceLevelResource));
        assertFalse("The fise:confidence-level property is functional and MUST " + "HAVE only a single value (enhancement " + enhancement + ")!", confidenceLevelIterator.hasNext());
    } else {
        assertNull("fise:confidence-level " + expectedConfidenceValue + "expected for Enhancement " + enhancement + "but no 'fise:confidence-level' value present!", expectedConfidenceValue);
    }
}
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) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) Date(java.util.Date)

Example 35 with RDFTerm

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

the class ExecutionMetadataHelper method getExecutionNode.

/**
     * Getter for the ep:ExecutionNode for a given em:Execution.
     * @param graph the graph containing the execution metadata
     * @param execution the em:Execution node
     * @return the ep:ExecutionNode node
     */
public static BlankNodeOrIRI getExecutionNode(Graph graph, BlankNodeOrIRI execution) {
    Iterator<Triple> it = graph.filter(execution, EXECUTION_NODE, null);
    if (it.hasNext()) {
        Triple t = it.next();
        RDFTerm o = t.getObject();
        if (o instanceof BlankNodeOrIRI) {
            return (BlankNodeOrIRI) o;
        } else {
            throw new IllegalStateException("Value of property " + EXECUTION_NODE + "MUST BE of type BlankNodeOrIRI (triple: '" + t + "')!");
        }
    } else {
        //maybe an em:ChainExecution
        return null;
    }
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm)

Aggregations

RDFTerm (org.apache.clerezza.commons.rdf.RDFTerm)126 IRI (org.apache.clerezza.commons.rdf.IRI)84 Triple (org.apache.clerezza.commons.rdf.Triple)70 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)48 Literal (org.apache.clerezza.commons.rdf.Literal)35 Test (org.junit.Test)35 HashSet (java.util.HashSet)30 HashMap (java.util.HashMap)28 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)26 Graph (org.apache.clerezza.commons.rdf.Graph)24 ContentItem (org.apache.stanbol.enhancer.servicesapi.ContentItem)18 ArrayList (java.util.ArrayList)17 PlainLiteralImpl (org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl)16 EngineException (org.apache.stanbol.enhancer.servicesapi.EngineException)13 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)13 SimpleGraph (org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph)12 Collection (java.util.Collection)10 IndexedGraph (org.apache.stanbol.commons.indexedgraph.IndexedGraph)10 Lock (java.util.concurrent.locks.Lock)9 IOException (java.io.IOException)5