use of org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException in project stanbol by apache.
the class AbstractOntologyCollectorImpl method addOntology.
@Override
public synchronized OWLOntologyID addOntology(OntologyInputSource<?> ontologySource) throws UnmodifiableOntologyCollectorException {
// Check for error conditions.
if (locked)
throw new UnmodifiableOntologyCollectorException(this);
if (ontologySource == null)
throw new IllegalArgumentException("Ontology source cannot be null.");
log.debug("Adding ontology to collector {}", getID());
OWLOntologyID key = null;
if (ontologySource.hasRootOntology()) {
long before = System.currentTimeMillis();
Object o = ontologySource.getRootOntology();
// Check the origin anyhow, as it may be useful for setting aliases with physical locations etc.
if (ontologySource.hasOrigin())
key = ontologyProvider.loadInStore(o, false, ontologySource.getOrigin());
else
key = ontologyProvider.loadInStore(o, false);
if (key != null) {
managedOntologies.add(key);
// Note that imported ontologies are not considered as managed! TODO should we change this?
log.info("Add ontology completed in {} ms.", (System.currentTimeMillis() - before));
// Fire the event
fireOntologyAdded(key);
}
} else if (ontologySource.hasOrigin()) {
// Just the origin : see if it is satisfiable
log.debug("Checking origin satisfiability...");
Origin<?> origin = ontologySource.getOrigin();
Object ref = origin.getReference();
log.debug("Origin wraps a {}", ref.getClass().getCanonicalName());
if (ref instanceof org.semanticweb.owlapi.model.IRI)
try {
log.debug("Deferring addition to physical IRI {} (if available).", ref);
key = addOntology(new RootOntologySource((org.semanticweb.owlapi.model.IRI) ref));
} catch (OWLOntologyCreationException e) {
throw new RuntimeException(e);
}
else if (ref instanceof IRI) {
log.debug("Deferring addition to stored Clerezza graph {} (if available).", ref);
key = addOntology(new GraphSource((IRI) ref));
} else if (ref instanceof OWLOntologyID) {
OWLOntologyID idref = (OWLOntologyID) ref;
log.debug("Deferring addition to stored ontology with public key {} (if available).", ref);
if (!ontologyProvider.hasOntology(idref))
throw new MissingOntologyException(this, idref);
key = idref;
if (managedOntologies.add(idref))
fireOntologyAdded(idref);
} else
throw new IllegalArgumentException("Invalid origin " + origin);
} else
throw new IllegalArgumentException("Ontology source must provide either an ontology object, or a way to reference one (i.e. an origin).");
log.info("Public key : {}", key);
return key;
}
use of org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException in project stanbol by apache.
the class RefactorEnhancementEngine method initEngine.
/**
* Method for adding ontologies to the scope core ontology.
* <ol>
* <li>Get all the ontologies from the property.</li>
* <li>Create a base scope.</li>
* <li>Retrieve the ontology space from the scope.</li>
* <li>Add the ontologies to the scope via ontology space.</li>
* </ol>
*/
private void initEngine(RefactorEnhancementEngineConf engineConfiguration) {
// IRI dulcifierScopeIRI = org.semanticweb.owlapi.model.IRI.create((String) context.getProperties().get(SCOPE));
String scopeId = engineConfiguration.getScope();
// Create or get the scope with the configured ID
try {
scope = onManager.createOntologyScope(scopeId);
// No need to deactivate a newly created scope.
} catch (DuplicateIDException e) {
scope = onManager.getScope(scopeId);
onManager.setScopeActive(scopeId, false);
}
// All resolvable ontologies stated in the configuration are loaded into the core space.
OntologySpace ontologySpace = scope.getCoreSpace();
ontologySpace.tearDown();
String[] coreScopeOntologySet = engineConfiguration.getScopeCoreOntologies();
List<String> success = new ArrayList<String>(), failed = new ArrayList<String>();
try {
log.info("Will now load requested ontology into the core space of scope '{}'.", scopeId);
OWLOntologyManager sharedManager = OWLManager.createOWLOntologyManager();
org.semanticweb.owlapi.model.IRI physicalIRI = null;
for (int o = 0; o < coreScopeOntologySet.length; o++) {
String url = coreScopeOntologySet[o];
try {
physicalIRI = org.semanticweb.owlapi.model.IRI.create(url);
} catch (Exception e) {
failed.add(url);
}
try {
// TODO replace with a Clerezza equivalent
ontologySpace.addOntology(new RootOntologySource(physicalIRI, sharedManager));
success.add(url);
} catch (OWLOntologyCreationException e) {
log.error("Failed to load ontology from physical location " + physicalIRI + " Continuing with next...", e);
failed.add(url);
}
}
} catch (UnmodifiableOntologyCollectorException ex) {
log.error("Ontology space {} was found locked for modification. Cannot populate.", ontologySpace);
}
for (String s : success) log.info(" >> {} : SUCCESS", s);
for (String s : failed) log.info(" >> {} : FAILED", s);
ontologySpace.setUp();
// if (!onManager.containsScope(scopeId)) onManager.registerScope(scope);
onManager.setScopeActive(scopeId, true);
/*
* The first thing to do is to create a recipe in the rule store that can be used by the engine to
* refactor the enhancement graphs.
*/
String recipeId = engineConfiguration.getRecipeId();
Recipe recipe = null;
try {
recipe = ruleStore.createRecipe(new IRI(recipeId), null);
} catch (AlreadyExistingRecipeException e1) {
log.error("A recipe with ID {} already exists in the store.", recipeId);
}
if (recipe != null) {
log.debug("Initialised blank recipe with ID {}", recipeId);
/*
* The set of rule to put in the recipe can be provided by the user. A default set of rules is
* provided in /META-INF/default/seo_rules.sem. Use the property engine.refactor in the felix
* console to pass to the engine your set of rules.
*/
String recipeLocation = engineConfiguration.getRecipeLocation();
InputStream recipeStream = null;
String recipeString = null;
if (recipeLocation != null && !recipeLocation.isEmpty()) {
Dereferencer dereferencer = new DereferencerImpl();
try {
recipeStream = dereferencer.resolve(recipeLocation);
log.debug("Loaded recipe from external source {}", recipeLocation);
} catch (FileNotFoundException e) {
log.error("Recipe Stream is null.", e);
}
} else {
// TODO remove this part (or manage it better in the @Activate method).
String loc = "/META-INF/default/seo_rules.sem";
recipeStream = getClass().getResourceAsStream(loc);
log.debug("Loaded default recipe in {}.", loc);
}
if (recipeStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(recipeStream));
recipeString = "";
String line = null;
try {
while ((line = reader.readLine()) != null) recipeString += line;
} catch (IOException e) {
log.error("Failed to load Refactor Engine recipe from stream. Aborting read. ", e);
recipeString = null;
}
}
log.debug("Recipe content follows :\n{}", recipeString);
if (recipeString != null) {
ruleStore.addRulesToRecipe(recipe, recipeString, null);
log.debug("Added rules to recipe {}", recipeId);
}
}
}
use of org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException in project stanbol by apache.
the class RefactorEnhancementEngine method computeEnhancements.
@Override
public void computeEnhancements(ContentItem ci) throws EngineException {
// Prepare the OntoNet environment. First we create the OntoNet session in which run the whole
final Session session;
try {
session = sessionManager.createSession();
} catch (SessionLimitException e1) {
throw new EngineException("OntoNet session quota reached. The Refactor Engine requires its own new session to execute.");
}
if (session == null)
throw new EngineException("Failed to create OntoNet session. The Refactor Engine requires its own new session to execute.");
log.debug("Refactor enhancement job will run in session '{}'.", session.getID());
// Retrieve and filter the metadata graph for entities recognized by the engines.
final Graph metadataGraph = ci.getMetadata(), signaturesGraph = new IndexedGraph();
// FIXME the Stanbol Enhancer vocabulary should be retrieved from somewhere in the enhancer API.
final IRI ENHANCER_ENTITY_REFERENCE = new IRI("http://fise.iks-project.eu/ontology/entity-reference");
Iterator<Triple> tripleIt = metadataGraph.filter(null, ENHANCER_ENTITY_REFERENCE, null);
while (tripleIt.hasNext()) {
// Get the entity URI
RDFTerm obj = tripleIt.next().getObject();
if (!(obj instanceof IRI)) {
log.warn("Invalid IRI for entity reference {}. Skipping.", obj);
continue;
}
final String entityReference = ((IRI) obj).getUnicodeString();
log.debug("Trying to resolve entity {}", entityReference);
// Populate the entity signatures graph, by querying either the Entity Hub or the dereferencer.
if (engineConfiguration.isEntityHubUsed()) {
Graph result = populateWithEntity(entityReference, signaturesGraph);
if (result != signaturesGraph && result != null) {
log.warn("Entity Hub query added triples to a new graph instead of populating the supplied one!" + " New signatures will be discarded.");
}
} else
try {
OntologyInputSource<Graph> source = new GraphContentSourceWithPhysicalIRI(dereferencer.resolve(entityReference), org.semanticweb.owlapi.model.IRI.create(entityReference));
signaturesGraph.addAll(source.getRootOntology());
} catch (FileNotFoundException e) {
log.error("Failed to dereference entity " + entityReference + ". Skipping.", e);
continue;
}
}
try {
/*
* The dedicated session for this job will store the following: (1) all the (merged) signatures
* for all detected entities; (2) the original content metadata graph returned earlier in the
* chain.
*
* There is no chance that (2) could be null, as it was previously controlled by the JobManager
* through the canEnhance() method and the computeEnhancement is always called iff the former
* returns true.
*/
session.addOntology(new GraphSource(signaturesGraph));
session.addOntology(new GraphSource(metadataGraph));
} catch (UnmodifiableOntologyCollectorException e1) {
throw new EngineException("Cannot add enhancement graph to OntoNet session for refactoring", e1);
}
try {
/*
* Export the entire session (incl. entities and enhancement graph) as a single merged ontology.
*
* TODO the refactorer should have methods to accommodate an OntologyCollector directly instead.
*/
OWLOntology ontology = session.export(OWLOntology.class, true);
log.debug("Refactoring recipe IRI is : " + engineConfiguration.getRecipeId());
/*
* We pass the ontology and the recipe IRI to the Refactor that returns the refactored graph
* expressed by using the given vocabulary.
*
* To perform the refactoring of the ontology to a given vocabulary we use the Stanbol Refactor.
*/
Recipe recipe = ruleStore.getRecipe(new IRI(engineConfiguration.getRecipeId()));
log.debug("Recipe {} contains {} rules.", recipe, recipe.getRuleList().size());
log.debug("The ontology to be refactor is {}", ontology);
Graph tc = refactorer.graphRefactoring(OWLAPIToClerezzaConverter.owlOntologyToClerezzaGraph(ontology), recipe);
/*
* The newly generated ontology is converted to Clarezza format and then added os substitued to
* the old mGraph.
*/
if (engineConfiguration.isInGraphAppendMode()) {
log.debug("Metadata of the content will replace old ones.", this);
} else {
metadataGraph.clear();
log.debug("Content metadata will be appended to the existing ones.", this);
}
metadataGraph.addAll(tc);
} catch (RefactoringException e) {
String msg = "Refactor engine execution failed on content item " + ci + ".";
log.error(msg, e);
throw new EngineException(msg, e);
} catch (NoSuchRecipeException e) {
String msg = "Refactor engine could not find recipe " + engineConfiguration.getRecipeId() + " to refactor content item " + ci + ".";
log.error(msg, e);
throw new EngineException(msg, e);
} catch (Exception e) {
throw new EngineException("Refactor Engine has failed.", e);
} finally {
/*
* The session needs to be destroyed anyhow.
*
* Clear contents before destroying (FIXME only do this until this is implemented in the
* destroySession() method).
*/
for (OWLOntologyID id : session.listManagedOntologies()) {
try {
String key = ontologyProvider.getKey(id.getOntologyIRI());
ontologyProvider.getStore().deleteGraph(new IRI(key));
} catch (Exception ex) {
log.error("Failed to delete triple collection " + id, ex);
continue;
}
}
sessionManager.destroySession(session.getID());
}
}
use of org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException in project stanbol by apache.
the class ScopeResource method managedOntologyUnload.
/**
* Unloads an ontology from an ontology scope.
*
* @param scopeId
* @param ontologyid
* @param uriInfo
* @param headers
*/
@DELETE
@Path("/{ontologyId:.+}")
public Response managedOntologyUnload(@PathParam("scopeid") String scopeid, @PathParam("ontologyId") String ontologyId, @PathParam("scopeid") String scopeId, @Context UriInfo uriInfo, @Context HttpHeaders headers) {
ResponseBuilder rb;
scope = onm.getScope(scopeid);
if (ontologyId != null && !ontologyId.trim().isEmpty()) {
OWLOntologyID id = OntologyUtils.decode(ontologyId);
OntologySpace cs = scope.getCustomSpace();
if (// ontology not managed
!cs.hasOntology(id))
// ontology not managed
rb = Response.notModified();
else
try {
onm.setScopeActive(scopeId, false);
cs.removeOntology(id);
rb = Response.ok();
} catch (IrremovableOntologyException e) {
throw new WebApplicationException(e, FORBIDDEN);
} catch (UnmodifiableOntologyCollectorException e) {
throw new WebApplicationException(e, FORBIDDEN);
} catch (OntologyCollectorModificationException e) {
throw new WebApplicationException(e, INTERNAL_SERVER_ERROR);
} finally {
onm.setScopeActive(scopeId, true);
}
} else
// null/blank ontology ID
rb = Response.status(BAD_REQUEST);
// addCORSOrigin(servletContext, rb, headers);
return rb.build();
}
use of org.apache.stanbol.ontologymanager.servicesapi.collector.UnmodifiableOntologyCollectorException in project stanbol by apache.
the class ScopeResource method manageOntology.
/**
* Tells the session that it should manage the ontology obtained by dereferencing the supplied IRI.<br>
* <br>
* Note that the PUT method cannot be used, as it is not possible to predict what ID the ontology will
* have until it is parsed.
*
* @param content
* the ontology physical IRI
* @return {@link Status#OK} if the addition was successful, {@link Status#NOT_FOUND} if there is no such
* session at all, {@link Status#FORBIDDEN} if the session is locked or cannot modified for some
* other reason, {@link Status#INTERNAL_SERVER_ERROR} if some other error occurs.
*/
@POST
@Consumes(value = MediaType.TEXT_PLAIN)
public Response manageOntology(String iri, @PathParam("scopeid") String scopeid, @Context HttpHeaders headers) {
ResponseBuilder rb;
scope = onm.getScope(scopeid);
if (scope == null)
rb = Response.status(NOT_FOUND);
else
try {
OWLOntologyID key = scope.getCustomSpace().addOntology(new RootOntologySource(IRI.create(iri)));
URI created = getCreatedResource(OntologyUtils.encode(key));
rb = Response.created(created);
} catch (UnmodifiableOntologyCollectorException e) {
throw new WebApplicationException(e, FORBIDDEN);
} catch (OWLOntologyCreationException e) {
throw new WebApplicationException(e, INTERNAL_SERVER_ERROR);
}
// addCORSOrigin(servletContext, rb, headers);
return rb.build();
}
Aggregations