/**
  * Renders an IRI as a full IRI rather than as an IRI that represents an entity in the signature
  * of the imports closure of the active ontology.
  *
  * @param page The page that the IRI should be rendered into.
  * @param iri The IRI to be rendered.
  * @return A list of paragraphs that represent the rendering of the annotation value.
  */
 private List<Paragraph> renderExternalIRI(Page page, IRI iri) {
   Paragraph paragraph;
   if (isLinkableAddress(iri)) {
     paragraph = page.addParagraph(iri.toString(), new HTTPLink(iri.toURI()));
   } else {
     paragraph = page.addParagraph(iri.toString());
   }
   return Arrays.asList(paragraph);
 }
示例#2
0
  public KuabaRepository getSourceRepository(IRI iri) {
    IRI repoIRI = IRI.create(iri.getStart().replaceAll("#", ""));
    KuabaRepository repo = repoMap.get(repoIRI);
    try {
      if (repo == null) repo = this.load(repoIRI.toString());
    } catch (Exception e) {
      System.err.println("Error when trying to get the source repository of " + iri.toString());
      System.err.println("Source repository not found.");
    }

    return repo;
  }
 public IRI getDocumentIRI(IRI lookupIRI) {
   if (lookupIRI.toString().startsWith(MY_NAMESPACE)) {
     String importOnto = lookupIRI.toString().substring(MY_NAMESPACE.length());
     String mapped =
         "file://"
             + context.getOwlSourceFile().getAbsoluteFile().getParent()
             + "/"
             + importOnto
             + ".owl";
     context.log("Loading " + lookupIRI + " from filesystem: " + mapped);
     return IRI.create(mapped);
   }
   return null;
 }
 protected void handleSelectAnnotation() {
   OWLAnnotationProperty prop = new UIHelper(getOWLEditorKit()).pickAnnotationProperty();
   if (prop != null) {
     labelAnnotation = prop.getIRI();
     annotationIriLabel.setText(labelAnnotation.toString());
   }
 }
  private void write(IRI iri) {

    if (iri.equals(getOntology().getOntologyID().getOntologyIRI())) {
      writeAsURI(iri.toString());
    } else {
      String name = pm.getPrefixIRI(iri);
      if (name == null) {
        // No QName!
        writeAsURI(iri.toString());
      } else {
        if (name.indexOf(':') != -1) {
          write(name);
        } else {
          write(":");
          write(name);
        }
      }
    }
  }
示例#6
0
  @Test
  public void testNonCycle3() throws Exception {
    ParserWrapper parser = new ParserWrapper();
    IRI iri = IRI.create(getResource("verification/self_references.obo").getAbsoluteFile());
    OWLGraphWrapper graph = parser.parseToOWLGraph(iri.toString());

    OntologyCheck check = new CycleCheck();

    Collection<CheckWarning> warnings = check.check(graph, graph.getAllOWLObjects());
    assertTrue(warnings.isEmpty());
  }
 /**
  * @param namespace The OntoNet namespace that will prefix the space ID in Web references. This
  *     implementation only allows non-null and non-empty IRIs, with no query or fragment. Hash
  *     URIs are not allowed, slash URIs are preferred. If neither, a slash will be concatenated
  *     and a warning will be logged.
  */
 @Override
 public void setDefaultNamespace(IRI namespace) {
   if (namespace == null)
     throw new IllegalArgumentException("Stanbol ontology namespace cannot be null.");
   if (namespace.toURI().getQuery() != null)
     throw new IllegalArgumentException(
         "URI Query is not allowed in Stanbol ontology namespaces.");
   if (namespace.toURI().getFragment() != null)
     throw new IllegalArgumentException(
         "URI Fragment is not allowed in Stanbol ontology namespaces.");
   if (namespace.toString().endsWith("#"))
     throw new IllegalArgumentException(
         "Stanbol ontology namespaces must not end with a hash ('#') character.");
   if (!namespace.toString().endsWith("/")) {
     log.warn(
         "Namespace {} does not end with a slash ('/') character. It be added automatically.",
         namespace);
     namespace = IRI.create(namespace + "/");
   }
   this.namespace = namespace;
 }
示例#8
0
  @Test
  public void testCycle1() throws Exception {
    ParserWrapper parser = new ParserWrapper();
    IRI iri = IRI.create(getResource("verification/cycle.obo").getAbsoluteFile());
    OWLGraphWrapper graph = parser.parseToOWLGraph(iri.toString());

    OntologyCheck check = new CycleCheck();

    Collection<CheckWarning> warnings = check.check(graph, graph.getAllOWLObjects());
    assertEquals(1, warnings.size());
    CheckWarning warning = warnings.iterator().next();
    List<IRI> iris = warning.getIris();
    assertEquals(3, iris.size());
  }
  /** This method gets an OWL ontology used as an input for the supplied rule. */
  private OWLOntology getInputOntologyForRule(IRI iri) throws OWLOntologyCreationException {
    if (iri.getScheme().equals(PREFIX)) {
      iri = getOntologyIRIForRuleName(iri.toString().substring(PREFIX.length()));
    }

    final OWLOntologyManager m = controller.getOWLOntologyManager();
    OWLOntology o;
    if (m.contains(iri)) {
      o = m.getOntology(iri);
    } else {
      o = m.loadOntology(iri);
    }
    return o;
  }
  /**
   * Renders an IRI as a full IRI rather than as an IRI that represents an entity in the signature
   * of the imports closure of the active ontology.
   *
   * @param page The page that the IRI should be rendered into.
   * @param iri The IRI to be rendered.
   * @return A list of paragraphs that represent the rendering of the annotation value.
   */
  private List<Paragraph> renderExternalIRI(Page page, IRI iri) {
    List<Paragraph> paragraphs = new ArrayList<>();
    String iriString = iri.toString();
    if (isLinkableAddress(iri)) {
      if (isImageAddress(iri) && isDisplayThumbnails()) {
        try {
          IconBox iconBox = getImageBox(iri);
          page.add(iconBox);

        } catch (MalformedURLException e) {
          paragraphs.add(page.addParagraph(iriString, new HTTPLink(iri.toURI())));
        }
      } else {
        paragraphs.add(page.addParagraph(iriString, new HTTPLink(iri.toURI())));
      }
    } else {
      paragraphs.add(page.addParagraph(iriString));
    }
    return paragraphs;
  }
示例#11
0
  public KuabaRepository copy(KuabaRepository kr, String url, File destination) {
    IRI iri;
    if (url == null) iri = IRI.generateDocumentIRI();
    else iri = IRI.create(url);

    try {
      OWLOntology model = (OWLOntology) kr.getModel();
      OWLOntology inst = manager.createOntology(iri);

      OntologyMigrator migrator = new OntologyMigrator(manager, model, inst);
      migrator.performMigration();

      EntityFindAndReplaceURIRenamer renamer =
          new EntityFindAndReplaceURIRenamer(
              manager,
              inst.getSignature(false),
              Collections.singleton(inst),
              model.getOntologyID().getOntologyIRI().toString(),
              iri.toString());

      if (renamer.hasErrors()) System.err.println("ERRO durante a cópia - rename");

      manager.applyChanges(renamer.getChanges());

      KuabaRepository repo = new OwlApiKuabaRepository(inst, manager.getOWLDataFactory());
      repoMap.put(inst.getOntologyID().getOntologyIRI(), repo);
      fileMap.put(repo, destination);

      return repo;

    } catch (OWLOntologyCreationException ex) {
      System.err.println("ERRO em copy");
      Logger.getLogger(OwlApiFileGateway.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
  }
示例#12
0
 /**
  * Resolves an IRI with the current base.
  *
  * @param uri the IRI being resolved
  * @return the resolved IRI
  */
 @Nonnull
 public String resolveIRI(@Nonnull String uri) {
   checkNotNull(uri, "uri cannot be null");
   if (uri.isEmpty()) {
     // MH - Fix for resolving a "This document" reference against base
     // IRIs.
     String namespace = getBaseIRI().getNamespace();
     if (namespace.charAt(namespace.length() - 1) == '#') {
       return namespace.substring(0, namespace.length() - 1);
     }
     String base = getBaseIRI().toString();
     int hashIndex = base.indexOf('#');
     if (hashIndex != -1) {
       return base.substring(0, hashIndex);
     } else {
       return base;
     }
   } else {
     try {
       String resolved = resolvedIRIs.get(uri);
       if (resolved != null) {
         return resolved;
       } else {
         IRI theIRI = resolveFromDelegate(getBaseIRI(), uri);
         String u = theIRI.toString();
         uriCache.put(u, theIRI);
         resolvedIRIs.put(uri, u);
         return u;
       }
     } catch (IllegalArgumentException e) {
       throw new RDFParserException(
           e,
           String.format(WRONGRESOLVE, uri, getBaseIRI(), e.getMessage()),
           getDocumentLocator());
     }
   }
 }
 private boolean isImageAddress(IRI iri) {
   String iriString = iri.toString();
   return iriString.endsWith(".png") || iriString.endsWith(".jpg") || iriString.endsWith(".jpeg");
 }
示例#14
0
 /**
  * Returns a string representation that can be used as the ID of this entity. This is the toString
  * representation of the IRI
  *
  * @return A string representing the toString of the IRI of this entity.
  */
 public String toStringID() {
   return iri.toString();
 }
  /**
   * This method has no conversion calls, to it can be invoked by subclasses that wish to modify it
   * afterwards.
   *
   * @param merge
   * @return
   */
  protected MGraph exportToMGraph(boolean merge, IRI prefix) {
    // if (merge) throw new UnsupportedOperationException(
    // "Merge not implemented yet for Clerezza triple collections.");

    long before = System.currentTimeMillis();

    // No need to store, give it a name, or anything.
    MGraph root = new SimpleMGraph();
    UriRef iri = new UriRef(prefix + _id);
    // Add the import declarations for directly managed ontologies.
    if (root != null) {
      // Set the ontology ID
      root.add(new TripleImpl(iri, RDF.type, OWL.Ontology));

      if (merge) {
        log.warn(
            "Merging of Clerezza triple collections is only implemented one level down. Import statements will be preserved for further levels.");
        Iterator<Triple> it;
        Set<Resource> importTargets = new HashSet<Resource>();
        for (OWLOntologyID ontologyId : managedOntologies) {
          Graph g = getOntology(ontologyId, Graph.class, false);
          root.addAll(g);

          it = g.filter(null, OWL.imports, null);
          while (it.hasNext()) {
            IRI tgt;
            Resource r = it.next().getObject();
            try {
              if (r instanceof UriRef) tgt = IRI.create(((UriRef) r).getUnicodeString());
              else if (r instanceof Literal) tgt = IRI.create(((Literal) r).getLexicalForm());
              else tgt = IRI.create(r.toString());
              tgt = URIUtils.sanitize(tgt);
              importTargets.add(new UriRef(tgt.toString()));
            } catch (Exception ex) {
              log.error("FAILED to obtain import target from resource {}", r);
              continue;
            }
          }

          it = g.filter(null, RDF.type, OWL.Ontology);
          while (it.hasNext()) {
            NonLiteral ontology = it.next().getSubject();
            log.debug("Removing all triples related to {} from {}", ontology, iri);
            Iterator<Triple> it2 = g.filter(ontology, null, null);
            while (it2.hasNext()) root.remove(it2.next());
          }

          /*
           * Reinstate import statements, though. If imported ontologies were not merged earlier, we
           * are not doing it now anyway.
           */
          for (Resource target : importTargets) root.add(new TripleImpl(iri, OWL.imports, target));
        }

      } else {

        String base = prefix + getID();
        for (int i = 0; i < backwardPathLength; i++)
          base = URIUtils.upOne(URI.create(base)).toString();
        base += "/";

        // The key set of managedOntologies contains the ontology IRIs, not their storage keys.
        for (OWLOntologyID ontologyId : managedOntologies) {
          IRI physIRI =
              // ontologyId.getVersionIRI() == null ? URIUtils.sanitize(IRI
              // .create(base + ontologyId.getOntologyIRI())) : URIUtils.sanitize(IRI
              // .create(base + ontologyId.getVersionIRI()));
              IRI.create(base + OntologyUtils.encode(ontologyId));
          root.add(new TripleImpl(iri, OWL.imports, new UriRef(physIRI.toString())));
        }
      }

      log.debug(
          "Clerezza export of {} completed in {} ms.",
          getID(),
          System.currentTimeMillis() - before);
    }

    return root;
  }
示例#16
0
 private void writeAttribute(String attributeName, IRI value) throws IOException {
   writer.writeAttribute(attributeName, value.toString());
 }
示例#17
0
 public void writeDatatypeAttribute(IRI datatypeIRI) throws IOException {
   writer.writeAttribute(Namespaces.RDF + "datatype", datatypeIRI.toString());
 }
示例#18
0
 public void writeStartElement(IRI elementName) throws IOException {
   // Sort out with namespace
   writer.writeStartElement(elementName.toString());
 }
示例#19
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;
          }
      }
    }
  private JPanel createEntityLabelPanel() {
    final Class<? extends LabelDescriptor> labelDescrCls =
        EntityCreationPreferences.getLabelDescriptorClass();

    JPanel panel = new JPanel();
    panel.setBorder(new TitledBorder("Entity Label (for use with Auto-generated ID)"));
    panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;
    c.gridheight = 1;
    c.fill = GridBagConstraints.NONE;
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    c.insets = new Insets(0, 12, 0, 0);
    /*sameAsRendererLabelButton = new JRadioButton("Same as label renderer (currently "
    + new SimpleIRIShortFormProvider().getShortForm(getFirstRendererLabel()) + ")");*/
    sameAsRendererLabelButton = new JRadioButton("Same as label renderer");
    sameAsRendererLabelButton.setSelected(labelDescrCls.equals(MatchRendererLabelDescriptor.class));
    panel.add(sameAsRendererLabelButton, c);

    c.gridy = 1;
    customLabelButton = new JRadioButton("Custom label");
    customLabelButton.setSelected(labelDescrCls.equals(CustomLabelDescriptor.class));
    panel.add(customLabelButton, c);

    ButtonGroup group = new ButtonGroup();
    group.add(sameAsRendererLabelButton);
    group.add(customLabelButton);

    c.gridy = 2;
    c.gridwidth = 1;
    c.insets = new Insets(5, 30, 0, 5);
    iriLabel = new JLabel("IRI");
    panel.add(iriLabel, c);

    c.gridx = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(5, 0, 0, 0);
    c.weightx = 1.0;
    annotationIriLabel = new JTextField();
    labelAnnotation = EntityCreationPreferences.getNameLabelIRI();
    if (labelAnnotation == null) {
      labelAnnotation = OWLRDFVocabulary.RDFS_LABEL.getIRI();
    }
    annotationIriLabel.setText(labelAnnotation.toString());
    annotationIriLabel.setEditable(false);
    panel.add(annotationIriLabel, c);

    c.gridx = 2;
    c.fill = GridBagConstraints.NONE;
    c.insets = new Insets(5, 5, 0, 12);
    c.weightx = 0;
    annotationSelectButton =
        new JButton(
            new AbstractAction("...") {
              private static final long serialVersionUID = 7759812643136092837L;

              public void actionPerformed(ActionEvent event) {
                handleSelectAnnotation();
              }
            });
    panel.add(annotationSelectButton, c);

    c.gridx = 0;
    c.gridy = 3;
    c.insets = new Insets(5, 30, 12, 5);
    langLabel = new JLabel("Lang");
    panel.add(langLabel, c);

    c.gridx = 1;
    c.insets = new Insets(5, 0, 12, 0);
    c.weighty = 1.0;
    annotationLangSelector = new UIHelper(getOWLEditorKit()).getLanguageSelector();
    annotationLangSelector.setSelectedItem(EntityCreationPreferences.getNameLabelLang());
    panel.add(annotationLangSelector, c);

    return panel;
  }