コード例 #1
0
ファイル: OwlApiFileGateway.java プロジェクト: brunodiniz/KSE
  @Override
  public KuabaRepository load(String url) throws RepositoryLoadException {

    IRI iri;
    File f = new File(url);
    if (!url.contains(":/")) {
      iri = IRI.create(f);
    } else iri = IRI.create(url);

    try {
      OWLOntology inst = manager.loadOntologyFromOntologyDocument(iri);

      if (inst == null) throw new RepositoryLoadException(url, "Invalid Location.");
      if (inst.getOntologyID().getOntologyIRI() == null) {
        // An anonymous Ontology was loaded, and they are not supported by the Kuaba Subsystem
        manager.removeOntology(inst);
        throw new RepositoryLoadException(url, "It is probably an incompatible or malformed file.");
      }

      KuabaRepository repo = new OwlApiKuabaRepository(inst, manager.getOWLDataFactory());
      repoMap.put(inst.getOntologyID().getOntologyIRI(), repo);
      fileMap.put(repo, f);
      return repo;
    } catch (OWLOntologyAlreadyExistsException ex) {
      OWLOntologyID id = ex.getOntologyID();
      //            System.err.println("Ontologia "+id.getOntologyIRI().toString()+" já está
      // carregada, esta será retornada.");
      return repoMap.get(id.getOntologyIRI());

    } catch (OWLOntologyCreationException ex) {
      throw new RepositoryLoadException(url, "Invalid Location.");
      //            Logger.getLogger(OwlApiFileGateway.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
コード例 #2
0
  /**
   * This method makes sure is used to setup a new/fresh OBDA model. This is done by replacing the
   * instance this.obdacontroller (the OBDA model) with a new object. On creation listeners for the
   * datasources, mappings and queries are setup so that changes in these trigger and ontology
   * change.
   *
   * <p>Additionally, this method configures all available OBDAOWLReasonerFacotry objects to have a
   * reference to the newly created OBDA model and to the global preference object. This is
   * necessary so that the factories are able to pass the OBDA model to the reasoner instances when
   * they are created.
   */
  private void setupNewOBDAModel() {
    OBDAModel activeOBDAModel = getActiveOBDAModel();

    if (activeOBDAModel != null) {
      return;
    }
    activeOBDAModel = dfac.getOBDAModel();

    activeOBDAModel.addSourcesListener(dlistener);
    activeOBDAModel.addMappingsListener(mlistener);
    queryController.addListener(qlistener);

    OWLModelManager mmgr = owlEditorKit.getOWLWorkspace().getOWLModelManager();

    Set<OWLOntology> ontologies = mmgr.getOntologies();
    for (OWLOntology ontology : ontologies) {
      // Setup the entity declarations
      for (OWLClass c : ontology.getClassesInSignature()) {
        OClass pred = ofac.createClass(c.getIRI().toString());
        activeOBDAModel.declareClass(pred);
      }
      for (OWLObjectProperty r : ontology.getObjectPropertiesInSignature()) {
        ObjectPropertyExpression pred = ofac.createObjectProperty(r.getIRI().toString());
        activeOBDAModel.declareObjectProperty(pred);
      }
      for (OWLDataProperty p : ontology.getDataPropertiesInSignature()) {
        DataPropertyExpression pred = ofac.createDataProperty(p.getIRI().toString());
        activeOBDAModel.declareDataProperty(pred);
      }
    }

    // Setup the prefixes
    PrefixOWLOntologyFormat prefixManager =
        PrefixUtilities.getPrefixOWLOntologyFormat(mmgr.getActiveOntology());
    //		addOBDACommonPrefixes(prefixManager);

    PrefixManagerWrapper prefixwrapper = new PrefixManagerWrapper(prefixManager);
    activeOBDAModel.setPrefixManager(prefixwrapper);

    OWLOntology activeOntology = mmgr.getActiveOntology();

    String defaultPrefix = prefixManager.getDefaultPrefix();
    if (defaultPrefix == null) {
      OWLOntologyID ontologyID = activeOntology.getOntologyID();
      defaultPrefix = ontologyID.getOntologyIRI().toURI().toString();
    }
    activeOBDAModel.getPrefixManager().addPrefix(PrefixManager.DEFAULT_PREFIX, defaultPrefix);

    // Add the model
    URI modelUri = activeOntology.getOntologyID().getOntologyIRI().toURI();
    obdamodels.put(modelUri, activeOBDAModel);
  }
コード例 #3
0
 public OBDAModel getActiveOBDAModel() {
   OWLOntology ontology = owlEditorKit.getOWLModelManager().getActiveOntology();
   if (ontology != null) {
     OWLOntologyID ontologyID = ontology.getOntologyID();
     IRI ontologyIRI = ontologyID.getOntologyIRI();
     URI uri = null;
     if (ontologyIRI != null) {
       uri = ontologyIRI.toURI();
     } else {
       uri = URI.create(ontologyID.toString());
     }
     return obdamodels.get(uri);
   }
   return null;
 }
コード例 #4
0
 public boolean setEditedObject(OWLAnonymousIndividual object) {
   if (object == null) {
     String id = "genid-" + UUID.randomUUID().toString();
     final OWLOntologyID ontologyID =
         editorKit.getModelManager().getActiveOntology().getOntologyID();
     if (!ontologyID.isAnonymous()) {
       id = ontologyID.getOntologyIRI().get() + "#" + id;
     }
     object = editorKit.getModelManager().getOWLDataFactory().getOWLAnonymousIndividual(id);
   }
   frameList.setRootObject(object);
   mainComponent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
   annotationValueLabel.setIcon(OWLIcons.getIcon("individual.png"));
   annotationValueLabel.setText(editorKit.getModelManager().getRendering(object));
   return true;
 }
コード例 #5
0
 protected void showNewExistsDocumentRepoMessage(OWLOntologyID ontoId, IRI repoDocumentIRI) {
   String message =
       "Cannot create an ontology, because another ontology with the same document IRI exists in the repository. \n"
           + "    The ontology ID was: Ontology IRI "
           + ontoId.getOntologyIRI()
           + "\n "
           + "                         Version  IRI "
           + ontoId.getVersionIRI()
           + "\n "
           + "    Reason: Existing Repository Document IRI: "
           + repoDocumentIRI
           + "\n \n"
           + " You should check the repository and maybe consider using Version IRI, in case you want another version of the same ontology.";
   JOptionPane.showMessageDialog(
       getWorkspace(),
       message,
       "Create Hypergraph DB Ontology - " + "Already exists in repository.",
       JOptionPane.ERROR_MESSAGE);
 }
コード例 #6
0
 protected void showNewExistsOntologyIDMessage(OWLOntologyID ontoId, IRI existingOntologyIRI) {
   String message =
       "Cannot create an ontology, because another ontology is currently loaded with the same ontology ID. \n"
           + "    The ontology ID was: Ontology IRI "
           + ontoId.getOntologyIRI()
           + "\n "
           + "                         Version  IRI "
           + ontoId.getVersionIRI()
           + "\n "
           + "    Reason: Existing Ontology IRI: "
           + existingOntologyIRI
           + "\n \n"
           + " You should check File/loaded ontology sources...";
   JOptionPane.showMessageDialog(
       getWorkspace(),
       message,
       "Create Hypergraph DB Ontology - " + "Already exists in loaded ontologies.",
       JOptionPane.ERROR_MESSAGE);
 }
コード例 #7
0
 public void showDeleteSuccessOrFailure(boolean success, OWLOntologyID oID, URI physicalURI) {
   String message =
       "The following ontology : \n"
           + "    OntologyIRI: "
           + oID.getOntologyIRI()
           + "\n"
           + "    VersionIRI : "
           + oID.getVersionIRI()
           + "\n"
           + "    PhysicalURI: "
           + physicalURI
           + "\n \n"
           + (success
               ? " was sucessfully deleted from the repository."
               : " COULD NOT BE DELETED !");
   JOptionPane.showMessageDialog(
       getWorkspace(),
       message,
       "Delete Hypergraph Database Backed Ontology - " + (success ? "Result" : " FAILED"),
       success ? JOptionPane.WARNING_MESSAGE : JOptionPane.ERROR_MESSAGE);
 }
コード例 #8
0
 /**
  * @param oId
  * @param physicalURI
  * @param loadedOntology or null, if not loaded.
  * @return
  */
 public boolean showDeleteConfirmation(
     OWLOntologyID oID, URI physicalURI, OWLOntology loadedOntology) {
   String message =
       "Do you really want to delete the following ontology: \n"
           + "    OntologyIRI: "
           + oID.getOntologyIRI()
           + "\n"
           + "    VersionIRI : "
           + oID.getVersionIRI()
           + "\n"
           + "    PhysicalURI: "
           + physicalURI
           + "\n \n"
           + "    This action cannot be undone! Make sure you have a current backup of the ontology. \n";
   int userInput =
       JOptionPane.showConfirmDialog(
           getWorkspace(),
           message,
           "Delete Hypergraph Database Backed Ontology - Confirm Deletion",
           JOptionPane.YES_NO_OPTION);
   return (userInput == JOptionPane.YES_OPTION);
 }
コード例 #9
0
  @Override
  public void removeOntology(OWLOntologyID publicKey)
      throws OntologyCollectorModificationException {
    if (publicKey == null)
      throw new IllegalArgumentException(
          "Cannot remove an ontology by providing a null public key.");
    if (publicKey.getOntologyIRI() == null)
      throw new IllegalArgumentException(
          "Cannot remove an ontology whose public key has a null ontology IRI.");
    if (locked) throw new UnmodifiableOntologyCollectorException(this);

    Set<OWLOntologyID> aliases = ontologyProvider.listAliases(publicKey);
    aliases.add(publicKey);
    boolean removed = false;
    for (OWLOntologyID alias : aliases) removed |= managedOntologies.remove(alias);
    // Don't fire if the ontology wasn't there in the first place.
    if (removed) fireOntologyRemoved(publicKey);
    else throw new MissingOntologyException(this, publicKey);
  }
コード例 #10
0
    @Override
    public void handleChange(OWLModelManagerChangeEvent event) {

      // Get the active ontology
      OWLModelManager source = event.getSource();
      OWLOntology activeOntology = source.getActiveOntology();

      // Initialize the active OBDA model
      OBDAModel activeOBDAModel = null;

      // Perform a proper handling for each type of event
      final EventType eventType = event.getType();
      switch (eventType) {
        case ABOUT_TO_CLASSIFY:
          log.debug("ABOUT TO CLASSIFY");
          loadingData = true;
          break;

        case ENTITY_RENDERER_CHANGED:
          log.debug("RENDERER CHANGED");
          break;

        case ONTOLOGY_CLASSIFIED:
          loadingData = false;
          break;

        case ACTIVE_ONTOLOGY_CHANGED:
          log.debug("ACTIVE ONTOLOGY CHANGED");
          inititializing = true; // flag on

          // Setting up a new OBDA model and retrieve the object.
          setupNewOBDAModel();
          activeOBDAModel = getActiveOBDAModel();

          OWLModelManager mmgr = owlEditorKit.getOWLWorkspace().getOWLModelManager();

          OWLOntology ontology = mmgr.getActiveOntology();
          PrefixOWLOntologyFormat prefixManager =
              PrefixUtilities.getPrefixOWLOntologyFormat(ontology);

          String defaultPrefix = prefixManager.getDefaultPrefix();
          if (defaultPrefix == null) {
            OWLOntologyID ontologyID = ontology.getOntologyID();
            defaultPrefix = ontologyID.getOntologyIRI().toURI().toString();
          }
          activeOBDAModel.getPrefixManager().addPrefix(PrefixManager.DEFAULT_PREFIX, defaultPrefix);

          ProtegeOWLReasonerInfo factory =
              owlEditorKit.getOWLModelManager().getOWLReasonerManager().getCurrentReasonerFactory();
          if (factory instanceof ProtegeOBDAOWLReformulationPlatformFactory) {
            ProtegeOBDAOWLReformulationPlatformFactory questfactory =
                (ProtegeOBDAOWLReformulationPlatformFactory) factory;
            ProtegeReformulationPlatformPreferences reasonerPreference =
                (ProtegeReformulationPlatformPreferences)
                    owlEditorKit.get(QuestPreferences.class.getName());
            questfactory.setPreferences(reasonerPreference);
            questfactory.setOBDAModel(getActiveOBDAModel());
            if (applyUserConstraints) questfactory.setImplicitDBConstraints(userConstraints);
          }
          fireActiveOBDAModelChange();

          inititializing = false; // flag off
          break;

        case ENTITY_RENDERING_CHANGED:
          break;

        case ONTOLOGY_CREATED:
          log.debug("ONTOLOGY CREATED");
          break;

        case ONTOLOGY_LOADED:
        case ONTOLOGY_RELOADED:
          log.debug("ONTOLOGY LOADED/RELOADED");
          loadingData = true; // flag on
          try {
            // Get the active OBDA model
            activeOBDAModel = getActiveOBDAModel();

            String owlDocumentIri =
                source.getOWLOntologyManager().getOntologyDocumentIRI(activeOntology).toString();
            String obdaDocumentIri =
                owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + OBDA_EXT;
            String queryDocumentIri =
                owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + QUERY_EXT;
            String dbprefsDocumentIri =
                owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + DBPREFS_EXT;

            File obdaFile = new File(URI.create(obdaDocumentIri));
            File queryFile = new File(URI.create(queryDocumentIri));
            File dbprefsFile = new File(URI.create(dbprefsDocumentIri));
            IRI ontologyIRI = activeOntology.getOntologyID().getOntologyIRI();

            activeOBDAModel
                .getPrefixManager()
                .addPrefix(PrefixManager.DEFAULT_PREFIX, ontologyIRI.toString());
            if (obdaFile.exists()) {
              try {
                // Load the OBDA model
                ModelIOManager modelIO = new ModelIOManager(activeOBDAModel);
                modelIO.load(obdaFile);
              } catch (Exception ex) {
                activeOBDAModel.reset();
                throw new Exception(
                    "Exception occurred while loading OBDA document: "
                        + obdaFile
                        + "\n\n"
                        + ex.getMessage());
              }
              try {
                // Load the saved queries
                QueryIOManager queryIO = new QueryIOManager(queryController);
                queryIO.load(queryFile);
              } catch (Exception ex) {
                queryController.reset();
                throw new Exception(
                    "Exception occurred while loading Query document: "
                        + queryFile
                        + "\n\n"
                        + ex.getMessage());
              }
              applyUserConstraints = false;
              if (dbprefsFile.exists()) {
                try {
                  // Load user-supplied constraints
                  userConstraints = new ImplicitDBConstraints(dbprefsFile);
                  applyUserConstraints = true;
                } catch (Exception ex) {
                  throw new Exception(
                      "Exception occurred while loading database preference file : "
                          + dbprefsFile
                          + "\n\n"
                          + ex.getMessage());
                }
              }
            } else {
              log.warn(
                  "OBDA model couldn't be loaded because no .obda file exists in the same location as the .owl file");
            }
            OBDAModelValidator refactorer = new OBDAModelValidator(activeOBDAModel, activeOntology);
            refactorer.run(); // adding type information to the mapping predicates.
          } catch (Exception e) {
            OBDAException ex =
                new OBDAException(
                    "An exception has occurred when loading input file.\nMessage: "
                        + e.getMessage());
            DialogUtils.showQuickErrorDialog(null, ex, "Open file error");
            log.error(e.getMessage());
          } finally {
            loadingData = false; // flag off
          }
          break;

        case ONTOLOGY_SAVED:
          log.debug("ACTIVE ONTOLOGY SAVED");
          try {
            // Get the active OBDA model
            activeOBDAModel = getActiveOBDAModel();

            String owlDocumentIri =
                source.getOWLOntologyManager().getOntologyDocumentIRI(activeOntology).toString();
            String obdaDocumentIri =
                owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + OBDA_EXT;
            String queryDocumentIri =
                owlDocumentIri.substring(0, owlDocumentIri.length() - 3) + QUERY_EXT;

            // Save the OBDA model
            File obdaFile = new File(URI.create(obdaDocumentIri));
            ModelIOManager ModelIO = new ModelIOManager(activeOBDAModel);
            ModelIO.save(obdaFile);

            // Save the queries
            File queryFile = new File(URI.create(queryDocumentIri));
            QueryIOManager queryIO = new QueryIOManager(queryController);
            queryIO.save(queryFile);

          } catch (IOException e) {
            log.error(e.getMessage());
            Exception newException =
                new Exception(
                    "Error saving the OBDA file. Closing Protege now can result in losing changes in your data sources or mappings. Please resolve the issue that prevents saving in the current location, or do \"Save as..\" to save in an alternative location. \n\nThe error message was: \n"
                        + e.getMessage());
            DialogUtils.showQuickErrorDialog(null, newException, "Error saving OBDA file");
            triggerOntologyChanged();
          }
          break;

        case ONTOLOGY_VISIBILITY_CHANGED:
          log.debug("VISIBILITY CHANGED");
          break;

        case REASONER_CHANGED:
          log.info("REASONER CHANGED");

          // Get the active OBDA model
          activeOBDAModel = getActiveOBDAModel();

          if ((!inititializing)
              && (obdamodels != null)
              && (owlEditorKit != null)
              && (getActiveOBDAModel() != null)) {
            ProtegeOWLReasonerInfo fac =
                owlEditorKit
                    .getOWLModelManager()
                    .getOWLReasonerManager()
                    .getCurrentReasonerFactory();
            if (fac instanceof ProtegeOBDAOWLReformulationPlatformFactory) {
              ProtegeOBDAOWLReformulationPlatformFactory questfactory =
                  (ProtegeOBDAOWLReformulationPlatformFactory) fac;
              ProtegeReformulationPlatformPreferences reasonerPreference =
                  (ProtegeReformulationPlatformPreferences)
                      owlEditorKit.get(QuestPreferences.class.getName());
              questfactory.setPreferences(reasonerPreference);
              questfactory.setOBDAModel(getActiveOBDAModel());
            }
            break;
          }
      }
    }
コード例 #11
0
  public void testRenderAndParse() {
    List<File> renderedFiles = new ArrayList<File>();
    String dblocation = System.getProperty("java.io.tmpdir") + File.separator + "hgdbtest";
    HGDBOntologyManager manager = HGOntologyManagerFactory.getOntologyManager(dblocation);
    HGDBOntologyRepository repo = new HGDBOntologyRepository(dblocation);
    VersionManager versionManager = manager.getVersionManager();
    HyperGraph graph = manager.getOntologyRepository().getHyperGraph();

    //
    // IMPORT AND RENDER
    //
    try {
      // repo.dropHypergraph();
      repo.deleteAllOntologies();
      // System.out.println("Running GC");
      // CANNOT RUN GC nullHANDLE problem !!! repo.runGarbageCollector();
      URL ontologyUrl = this.getClass().getResource("/sampleOntology.owl");
      IRI targetIRI = ImportOntologies.importOntology(ontologyUrl, manager);
      // IRI targetIRI = ImportOntologies.importOntology(f2, manager);
      HGDBOntology o = (HGDBOntology) manager.loadOntologyFromOntologyDocument(targetIRI);
      VersionedOntology vo = versionManager.versioned(o.getAtomHandle());
      // MANIPULATE REMOVE CHANGED
      Object[] axioms = o.getAxioms().toArray();
      // remove all axioms 10.
      for (int i = 0; i < axioms.length / 10; i++) {
        int j = i;
        for (; j < i + axioms.length / 100; j++) {
          if (j < axioms.length) {
            manager.applyChange(new RemoveAxiom(o, (OWLAxiom) axioms[j]));
          }
        }
        i = j;
        vo.commit("SameUser", " commit no " + i);
      }
      // RENDER VERSIONED ONTOLOGY, includes data

      // TODO...
      VOWLXMLRenderConfiguration c = new VOWLXMLRenderConfiguration();
      VOWLXMLVersionedOntologyRenderer r = new VOWLXMLVersionedOntologyRenderer(manager);
      File fx = new File(TESTFILE.getAbsolutePath() + " Revision-" + ".xml");
      renderedFiles.add(fx);
      Writer fwriter = new OutputStreamWriter(new FileOutputStream(fx), Charset.forName("UTF-8"));
      r.render(vo, null, fwriter, c);
      //			for (int i = 0; i < vo.getArity(); i++)
      //			{
      //				VOWLXMLRenderConfiguration c = new VOWLXMLRenderConfiguration();
      //				//c.setLastRevisionIndex(i);
      //				VOWLXMLVersionedOntologyRenderer r = new VOWLXMLVersionedOntologyRenderer(manager);
      //				File fx = new File(TESTFILE.getAbsolutePath() + " Revision-" + i + ".xml");
      //				// File fx = new
      //				// File("C:\\_CiRM\\testontos\\CountyVersioned-Rev-"+ i +
      //				// ".vowlxml");
      //				renderedFiles.add(fx);
      //				// File fx = new File("C:\\_CiRM\\testontos\\1 csr-Rev-"+ i +
      //				// ".vowlxml");
      //				Writer fwriter = new OutputStreamWriter(new FileOutputStream(fx),
      // Charset.forName("UTF-8"));
      //				// Full export
      //				r.render(vo, fwriter, c);
      //			}
      System.out.println("DELETE ALL ONTOLOGIES");
      repo.deleteAllOntologies();
      GarbageCollector gc = new GarbageCollector(repo);
      gc.runGarbageCollection(GarbageCollector.MODE_DELETED_ONTOLOGIES);
    } catch (OWLOntologyCreationException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OWLRendererException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    //
    // PARSE
    //
    File f = new File(TESTFILE.getAbsolutePath() + " Revision-" + 10 + ".xml");
    System.out.println("PARSING: " + f + " length: " + (f.length() / 1024) + " kB");
    OWLOntologyDocumentSource source = new FileDocumentSource(f);
    VOWLXMLParser parser = new VOWLXMLParser();
    OWLOntologyEx onto = new OWLTempOntologyImpl(manager, new OWLOntologyID());
    // must have onto for manager in super class
    VOWLXMLDocument versionedOntologyRoot = new VOWLXMLDocument(onto);
    //
    // Create VersionedOntology Revision 10
    try {
      parser.parse(graph, source, versionedOntologyRoot, new OWLOntologyLoaderConfiguration());
      System.out.println("PARSING FINISHED.");
    } catch (OWLOntologyChangeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnloadableImportException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (OWLParserException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (versionedOntologyRoot.getRenderConfig().heads().isEmpty()
        && versionedOntologyRoot
            .getRenderConfig()
            .roots()
            .contains(versionedOntologyRoot.getRenderConfig().firstRevision())) {
      OWLOntologyID ontologyID = versionedOntologyRoot.getRevisionData().getOntologyID();
      IRI documentIRI =
          IRI.create("hgdb://" + ontologyID.getDefaultDocumentIRI().toString().substring(7));
      HGPersistentHandle ontologyUUID =
          repo.getHyperGraph().getHandleFactory().makeHandle(versionedOntologyRoot.getOntologyID());
      try {
        System.out.println("Storing ontology data for : " + ontologyUUID);
        HGDBOntology o =
            manager
                .getOntologyRepository()
                .createOWLOntology(ontologyID, documentIRI, ontologyUUID);
        storeFromTo(versionedOntologyRoot.getRevisionData(), o);
      } catch (HGDBOntologyAlreadyExistsByDocumentIRIException e) {
        e.printStackTrace();
      } catch (HGDBOntologyAlreadyExistsByOntologyIDException e) {
        e.printStackTrace();
      } catch (HGDBOntologyAlreadyExistsByOntologyUUIDException e) {
        e.printStackTrace();
      }
      // Add version control with full matching history.
      System.out.println("Adding version control history to : " + ontologyUUID);
      //			VersionedOntology voParsed = new VersionedOntology(versionedOntologyRoot.getRevisions(),
      //					versionedOntologyRoot.getChangesets(), graph);
      //			VHGDBOntologyRepository vrepo = (VHGDBOntologyRepository)
      // manager.getOntologyRepository();
      //			System.out.println("Versioned Repository Contents: ");
      //			for (VersionedOntology vox : vrepo.getVersionControlledOntologies())
      //			{
      //				System.out.println("Versioned Ontology: " + vox.getWorkingSetData());
      //				System.out.println("Versioned Ontology Revs: " + vox.getNrOfRevisions());
      //			}
      //			//
      //			// Rendering FULL Versioned Ontology
      //			//
      //			System.out.println("Rendering full versioned ontology after parse and store: " +
      // ontologyUUID);
      //			VOWLXMLVersionedOntologyRenderer r = new VOWLXMLVersionedOntologyRenderer(manager);
      //			File fx = new File(TESTFILE.getAbsolutePath() + "FULL-afterParse.xml");
      //			Writer fwriter;
      //			try
      //			{
      //				fwriter = new OutputStreamWriter(new FileOutputStream(fx), Charset.forName("UTF-8"));
      //				r.render(voParsed, fwriter);
      //			}
      //			catch (IOException e)
      //			{
      //				e.printStackTrace();
      //			}
      //			catch (OWLRendererException e)
      //			{
      //				e.printStackTrace();
      //			}
    } else {
      System.out.println("ERROR: EXPECTING COMPLETE VERSIONED ONTOLOGY");
    }
    // }
  }
コード例 #12
0
  protected OWLOntology getOntologyAsOWLOntology(
      OWLOntologyID ontologyId, boolean merge, IRI universalPrefix) {
    // if (merge) throw new UnsupportedOperationException("Merge not implemented yet for
    // OWLOntology.");

    // Remove the check below. It might be an unmanaged dependency (TODO remove from collector and
    // reintroduce check?).
    // if (!hasOntology(ontologyIri)) return null;
    OWLOntology o;
    o = ontologyProvider.getStoredOntology(ontologyId, OWLOntology.class, merge);

    if (merge) {
      final Set<OWLOntology> set = new HashSet<OWLOntology>();
      log.debug("Merging {} with its imports, if any.", o);
      set.add(o);
      // Actually, if the provider already performed the merge, this won't happen
      for (OWLOntology impo : o.getImportsClosure()) {
        log.debug("Imported ontology {} will be merged with {}.", impo, o);
        set.add(impo);
      }
      OWLOntologySetProvider provider =
          new OWLOntologySetProvider() {
            @Override
            public Set<OWLOntology> getOntologies() {
              return set;
            }
          };
      OWLOntologyMerger merger = new OWLOntologyMerger(provider);
      try {
        o =
            merger.createMergedOntology(
                OWLManager.createOWLOntologyManager(), ontologyId.getOntologyIRI());
      } catch (OWLOntologyCreationException e) {
        log.error("Failed to merge imports for ontology " + ontologyId, e);
        // do not reassign the root ontology
      }
    } else {
      // Rewrite import statements
      List<OWLOntologyChange> changes = new ArrayList<OWLOntologyChange>();
      OWLDataFactory df = OWLManager.getOWLDataFactory();

      /*
       * TODO manage import rewrites better once the container ID is fully configurable (i.e. instead of
       * going upOne() add "session" or "ontology" if needed). But only do this if we keep considering
       * imported ontologies as *not* managed.
       */
      for (OWLImportsDeclaration oldImp : o.getImportsDeclarations()) {
        changes.add(new RemoveImport(o, oldImp));
        String s = oldImp.getIRI().toString();
        // FIXME Ugly way to check, but we'll get through with it
        if (s.contains("::")) s = s.substring(s.indexOf("::") + 2, s.length());
        boolean managed = managedOntologies.contains(oldImp.getIRI());
        // For space, always go up at least one

        String tid = getID();
        if (backwardPathLength > 0) tid = tid.split("/")[0];

        IRI target =
            IRI.create(
                (managed
                        ? universalPrefix + "/" + tid + "/"
                        : URIUtils.upOne(universalPrefix) + "/")
                    + s);
        changes.add(new AddImport(o, df.getOWLImportsDeclaration(target)));
      }
      o.getOWLOntologyManager().applyChanges(changes);
    }

    return o;
  }