Search in sources :

Example 11 with ImmutableGraph

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

the class TestStorage method storageOnScopeCreation.

@Test
public void storageOnScopeCreation() throws Exception {
    assertEquals(1, ontologyProvider.getStore().listGraphs().size());
    // This one has an import that we want to hijack locally, so we use the ParentPathInputSource.
    OntologyInputSource<?> ois = new ParentPathInputSource(new File(getClass().getResource("/ontologies/minorcharacters.owl").toURI()));
    Scope sc = onManager.createOntologyScope(scopeId, ois);
    Set<Triple> triples = new HashSet<Triple>();
    for (IRI iri : ontologyProvider.getStore().listGraphs()) {
        log.info("{}", iri.toString());
        IRI entity = new IRI(Constants.PEANUTS_MINOR_BASE + "#" + Constants.truffles);
        ImmutableGraph ctx = new GraphNode(entity, ontologyProvider.getStore().getGraph(iri)).getNodeContext();
        Iterator<Triple> it = ctx.iterator();
        while (it.hasNext()) triples.add(it.next());
    }
    assertFalse(ontologyProvider.getStore().listGraphs().isEmpty());
    assertEquals(3, triples.size());
}
Also used : Triple(org.apache.clerezza.commons.rdf.Triple) IRI(org.apache.clerezza.commons.rdf.IRI) Scope(org.apache.stanbol.ontologymanager.servicesapi.scope.Scope) ParentPathInputSource(org.apache.stanbol.ontologymanager.sources.owlapi.ParentPathInputSource) GraphNode(org.apache.clerezza.rdf.utils.GraphNode) File(java.io.File) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 12 with ImmutableGraph

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

the class PermissionDefinitionsTest method setUp.

@Before
public void setUp() {
    final ImmutableGraph graph = Parser.getInstance().parse(getClass().getResourceAsStream("systemgraph.nt"), "text/rdf+n3");
    this.permissionDefinitions = new PermissionDefinitions(new SimpleGraph(graph.iterator()));
    this.allPermissions = new PermissionInfo[] { new PermissionInfo("(java.io.FilePermission \"file:///home/foo/-\" \"read,write,delete\")"), new PermissionInfo("(java.io.FilePermission \"file:///home/foo/*\" \"read,write\")"), new PermissionInfo("(java.io.FilePermission \"file:///home/*\" \"read,write\")") };
    this.nullPermission = null;
}
Also used : PermissionInfo(org.osgi.service.permissionadmin.PermissionInfo) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) PermissionDefinitions(org.apache.stanbol.commons.security.PermissionDefinitions) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph)

Example 13 with ImmutableGraph

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

the class EnhancementPropertyTest method testExecutionPropertySupportOfExecutionPlanHelper.

/**
     * This tests if the {@link ExecutionPlanHelper} correctly adds Enhancement
     * Properties to generated Execution plans. <p>
     * NOTE: If this fails also tests testing chain level properties are expected
     * to fail. This only present to validate that the ExecutionPlan is correctly
     * generated by the {@link ExecutionPlanHelper}
     * @throws ChainException
     */
@Test
public void testExecutionPropertySupportOfExecutionPlanHelper() throws ChainException {
    //the value we are setting
    Collection<String> derefernceLanguages = Arrays.asList("en", "de");
    Integer maxSuggestions = Integer.valueOf(5);
    IRI maxSuggestionsProperty = new IRI(NamespaceEnum.ehp + PROPERTY_MAX_SUGGESTIONS);
    IRI dereferenceLanguagesProperty = new IRI(NamespaceEnum.ehp + PROPERTY_DEREFERENCE_LANGUAGES);
    //set up the map with the enhancement properties we want to set for the
    //Enhancement Chain
    Map<String, Map<String, Object>> enhancementProperties = new HashMap<String, Map<String, Object>>();
    Map<String, Object> chainProperties = new HashMap<String, Object>();
    chainProperties.put(PROPERTY_MAX_SUGGESTIONS, maxSuggestions);
    enhancementProperties.put(null, chainProperties);
    Map<String, Object> linkingProperties = new HashMap<String, Object>();
    linkingProperties.put(PROPERTY_DEREFERENCE_LANGUAGES, derefernceLanguages);
    enhancementProperties.put(linking.getName(), linkingProperties);
    //create the ExecutionPlan
    ImmutableGraph ep = ExecutionPlanHelper.calculateExecutionPlan("test", engines, Collections.<String>emptySet(), Collections.<String>emptySet(), enhancementProperties);
    //now assert that the enhancement properties where correctly written
    //first the property we set on the chain level
    BlankNodeOrIRI epNode = ExecutionPlanHelper.getExecutionPlan(ep, "test");
    assertNotNull(epNode);
    Iterator<Triple> maxSuggestionValues = ep.filter(epNode, maxSuggestionsProperty, null);
    assertTrue(maxSuggestionValues.hasNext());
    RDFTerm maxSuggestionValue = maxSuggestionValues.next().getObject();
    assertFalse(maxSuggestionValues.hasNext());
    assertTrue(maxSuggestionValue instanceof Literal);
    assertEquals(maxSuggestions.toString(), ((Literal) maxSuggestionValue).getLexicalForm());
    assertEquals(maxSuggestions, LiteralFactory.getInstance().createObject(Integer.class, (Literal) maxSuggestionValue));
    //second the property we set for the linking engine
    boolean found = false;
    for (BlankNodeOrIRI ee : ExecutionPlanHelper.getExecutionNodes(ep, epNode)) {
        String engineName = ExecutionPlanHelper.getEngine(ep, ee);
        if (linking.getName().equals(engineName)) {
            found = true;
            Iterator<Triple> derefLangValues = ep.filter(ee, dereferenceLanguagesProperty, null);
            assertTrue(derefLangValues.hasNext());
            int numValues = 0;
            while (derefLangValues.hasNext()) {
                RDFTerm r = derefLangValues.next().getObject();
                assertTrue(r instanceof Literal);
                assertTrue(derefernceLanguages.contains(((Literal) r).getLexicalForm()));
                numValues++;
            }
            assertEquals(derefernceLanguages.size(), numValues);
        }
    }
    assertTrue("ExecutionNode for the Linking Engine was not present!", found);
//NOTE: this does not validate that there are no other (not expected)
//      enhancement properties in the executionPlan
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) HashMap(java.util.HashMap) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) RDFTerm(org.apache.clerezza.commons.rdf.RDFTerm) Triple(org.apache.clerezza.commons.rdf.Triple) Literal(org.apache.clerezza.commons.rdf.Literal) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) Test(org.junit.Test)

Example 14 with ImmutableGraph

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

the class OpenCalaisEngine method readModel.

/**
     * Parses an InputStream of RDF data and produces an Graph from them
     *
     * @param in The InputStream of RDF data
     * @param format the format of the RDF data
     *
     * @return the resulting Graph or null if the RDF serialization format is not supported by the parser
     */
public Graph readModel(InputStream in, String format) {
    Parser parser = Parser.getInstance();
    if (parser.getSupportedFormats().contains(format)) {
        ImmutableGraph graph = parser.parse(in, format);
        Graph model = new SimpleGraph(graph);
        return model;
    } else {
        log.warn("Unsupported RDF format: {}\nSupported RDF formats: {}", format, parser.getSupportedFormats());
    }
    return null;
}
Also used : ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Graph(org.apache.clerezza.commons.rdf.Graph) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) QueryParser(org.apache.clerezza.rdf.core.sparql.QueryParser) Parser(org.apache.clerezza.rdf.core.serializedform.Parser)

Example 15 with ImmutableGraph

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

the class RootResource method getGraph.

private Graph getGraph(String ontologyId, boolean merged, URI requestUri) {
    long before = System.currentTimeMillis();
    OWLOntologyID key = OntologyUtils.decode(ontologyId);
    log.debug("Will try to retrieve ontology {} from provider.", key);
    /*
         * Export directly to Graph since the OWLOntologyWriter uses (de-)serializing converters for the
         * other formats.
         * 
         * Use oTemp for the "real" graph and o for the graph that will be exported. This is due to the fact
         * that in o we want to change import statements, but we do not want these changes to be stored
         * permanently.
         */
    Graph o = null, oTemp = null;
    try {
        oTemp = ontologyProvider.getStoredOntology(key, Graph.class, merged);
    } catch (Exception ex) {
        log.warn("Retrieval of ontology with ID " + key + " failed.", ex);
    }
    if (oTemp == null) {
        log.debug("Ontology {} missing from provider. Trying libraries...", key);
        // TODO remove once registry supports OWLOntologyID as public key.
        IRI iri = URIUtils.sanitize(IRI.create(ontologyId));
        // See if we can touch a library. TODO: replace with event model on the ontology provider.
        int minSize = -1;
        IRI smallest = null;
        for (Library lib : registryManager.getLibraries(iri)) {
            int size = lib.getChildren().length;
            if (minSize < 1 || size < minSize) {
                smallest = lib.getIRI();
                minSize = size;
            }
        }
        if (smallest != null) {
            log.debug("Selected library for ontology {} is {} .", iri, smallest);
            try {
                oTemp = registryManager.getLibrary(smallest).getOntology(iri, Graph.class);
            } catch (RegistryContentException e) {
                log.warn("The content of library " + smallest + " could not be accessed.", e);
            }
        }
    }
    // resource-intensive IndexedGraph, since both o and oTemp will be GC'ed after serialization.
    if (oTemp != null) {
        o = new SimpleGraph(oTemp);
    }
    if (o == null) {
        log.debug("Ontology {} not found in any ontology provider or library.", ontologyId);
        return null;
    }
    log.debug("Retrieved ontology {} .", ontologyId);
    // Rewrite imports
    String uri = uriInfo.getRequestUri().toString();
    URI base = URI.create(uri.substring(0, uri.lastIndexOf(ontologyId) - 1));
    // Rewrite import statements
    /*
         * TODO manage import rewrites better once the container ID is fully configurable (i.e. instead of
         * going upOne() add "session" or "ontology" if needed).
         */
    Iterator<Triple> imports = o.filter(null, OWL.imports, null);
    Set<Triple> oldImports = new HashSet<Triple>();
    while (imports.hasNext()) {
        oldImports.add(imports.next());
    }
    for (Triple t : oldImports) {
        // construct new statement
        String s = ((org.apache.clerezza.commons.rdf.IRI) t.getObject()).getUnicodeString();
        if (s.contains("::")) {
            s = s.substring(s.indexOf("::") + 2, s.length());
        }
        org.apache.clerezza.commons.rdf.IRI target = new org.apache.clerezza.commons.rdf.IRI(base + "/" + s);
        o.add(new TripleImpl(t.getSubject(), OWL.imports, target));
        // remove old statement
        o.remove(t);
    }
    // Versioning.
    OWLOntologyID id = OWLUtils.extractOntologyID(o);
    if (id != null && !id.isAnonymous() && id.getVersionIRI() == null) {
        org.apache.clerezza.commons.rdf.IRI viri = new org.apache.clerezza.commons.rdf.IRI(requestUri.toString());
        log.debug("Setting version IRI for export : {}", viri);
        o.add(new TripleImpl(new org.apache.clerezza.commons.rdf.IRI(id.getOntologyIRI().toString()), new org.apache.clerezza.commons.rdf.IRI(OWL2Constants.OWL_VERSION_IRI), viri));
    }
    log.debug("Exported as Clerezza ImmutableGraph in {} ms. Handing over to writer.", System.currentTimeMillis() - before);
    return o;
}
Also used : IRI(org.semanticweb.owlapi.model.IRI) URI(java.net.URI) UnsupportedFormatException(org.apache.clerezza.rdf.core.serializedform.UnsupportedFormatException) WebApplicationException(javax.ws.rs.WebApplicationException) ConcurrentModificationException(java.util.ConcurrentModificationException) IOException(java.io.IOException) OntologyLoadingException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyLoadingException) OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) OntologyHandleException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OntologyHandleException) RegistryContentException(org.apache.stanbol.ontologymanager.registry.api.RegistryContentException) OrphanOntologyKeyException(org.apache.stanbol.ontologymanager.servicesapi.ontology.OrphanOntologyKeyException) Triple(org.apache.clerezza.commons.rdf.Triple) ImmutableGraph(org.apache.clerezza.commons.rdf.ImmutableGraph) Graph(org.apache.clerezza.commons.rdf.Graph) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) OWLOntologyID(org.semanticweb.owlapi.model.OWLOntologyID) RegistryContentException(org.apache.stanbol.ontologymanager.registry.api.RegistryContentException) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Library(org.apache.stanbol.ontologymanager.registry.api.model.Library) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) HashSet(java.util.HashSet)

Aggregations

ImmutableGraph (org.apache.clerezza.commons.rdf.ImmutableGraph)25 Graph (org.apache.clerezza.commons.rdf.Graph)9 IRI (org.semanticweb.owlapi.model.IRI)8 GET (javax.ws.rs.GET)7 Produces (javax.ws.rs.Produces)7 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)7 SimpleGraph (org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph)7 HashSet (java.util.HashSet)6 Path (javax.ws.rs.Path)5 BlankNodeOrIRI (org.apache.clerezza.commons.rdf.BlankNodeOrIRI)5 Triple (org.apache.clerezza.commons.rdf.Triple)5 IRI (org.apache.clerezza.commons.rdf.IRI)4 IndexedGraph (org.apache.stanbol.commons.indexedgraph.IndexedGraph)4 Test (org.junit.Test)4 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)4 InputStream (java.io.InputStream)3 RDFTerm (org.apache.clerezza.commons.rdf.RDFTerm)3 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)3 Parser (org.apache.clerezza.rdf.core.serializedform.Parser)3 OntologySpace (org.apache.stanbol.ontologymanager.servicesapi.scope.OntologySpace)3