public ModifySuperclassDialog(
      NCIEditTab tab, String name, RDFSClass aClass, boolean defining, boolean definingEditable) {
    super((JFrame) tab.getTopLevelAncestor(), "Modify Named Superclass", true);
    this.tab = tab;
    this.owlModel = tab.getOWLModel();
    this.defining = defining;
    this.defining_prev = defining;

    this.aClass = aClass;

    this.name = name;
    this.definingEditable = definingEditable;

    selectedCls = null;
    if (aClass != null) {
      selectedCls = (Cls) aClass;
    }

    String title = "Modify Named Superclass";
    cancelBtnPressed = false;
    JPanel panel = createPanel();

    int r =
        ProtegeUI.getModalDialogFactory()
            .showDialog(tab, panel, title, ModalDialogFactory.MODE_OK_CANCEL);

    if (r == ModalDialogFactory.OPTION_OK) {
      if (selectedCls == null) {
        try {
          MsgDialog.ok(this, "Incomplete data entry.");
          cancelBtnPressed = true;
          return;
        } catch (Exception ex) {
          Log.getLogger().log(Level.WARNING, "Exception caught", ex);
          ;
        }
      } else {
        if (name == null) {
          modified = true;
        } else {
          String selectedClsName = tab.getOWLWrapper().getInternalName(selectedCls);
          if (selectedClsName.compareTo(name) != 0) {
            modified = true;
          }
        }

        defining = definingCheckBox.isSelected();

        if (!defining_prev && definingCheckBox.isSelected()) modified = true;
        if (defining_prev && !definingCheckBox.isSelected()) modified = true;
        if (!modified) {
          cancelBtnPressed = true;
        }

        isDefinition = defining;
      }
    } else {
      cancelBtnPressed = true;
    }
  }
    // if there are multiple unmatched siblings of the same class, look for the ones that have similar names
    public static boolean run (ResultTable currentResults, PromptDiff promptDiff) {
    	Log.getLogger().info ("*********** start MultipleUnmatchedSiblingsWithSimilarNames ************");
        _changesMade = false;
        if (currentResults == null) return false;
		_results = currentResults;
        startAlgorithm ();
        return _changesMade;
    }
 public OWLNamedClass getOwner() {
   OWLNamedClass owner = null;
   try {
     owner = (OWLNamedClass) new GetOwnerForAnonymousClassJob(getOWLModel(), this).execute();
   } catch (Throwable t) {
     Log.getLogger().log(Level.SEVERE, "Could not get owner for anonymous class: " + this, t);
   }
   return owner;
 }
 private RDFResource getMetadataOnt() {
   RDFResource result = null;
   try {
     URI metaURI = new URI(ProtegeNames.PROTEGE_OWL_ONTOLOGY);
     result = owlModel.getOWLOntologyByURI(metaURI);
   } catch (URISyntaxException e) {
     Log.getLogger().log(Level.SEVERE, "Exception caught", e);
   }
   return result;
 }
 public OWLAnonymousClass getExpressionRoot() {
   OWLAnonymousClass root = this;
   try {
     root =
         (OWLAnonymousClass)
             new GetExpressionRootForAnonymousClassJob(getOWLModel(), this).execute();
   } catch (Throwable t) {
     Log.getLogger()
         .log(Level.SEVERE, "Could not compute expression root for anonymous class " + this, t);
   }
   return root;
 }
 public void testGetProject() {
   if (!Server_Test.isServerRunning()) {
     return;
   }
   Project p =
       RemoteProjectManager.getInstance()
           .getProject(Server_Test.HOST, USER, PASSWORD, PROJECT_NAME, true);
   assertNotNull(p);
   OWLModel kb = (OWLModel) p.getKnowledgeBase();
   Cls cls = kb.getOWLNamedClass(kb.getNamespaceManager().getDefaultNamespace() + "Pizza");
   Log.getLogger().info("found " + cls + " with frame id = " + cls.getFrameID());
   assertNotNull(cls);
   p.dispose();
 }
  public String getBrowserText() {
    // TT This should not be null...
    if (getDirectType() == null) {
      if (Log.getLogger().getLevel() == Level.WARNING) {
        Log.getLogger().log(Level.WARNING, "Called method on deleted frame " + this);
      }
      return "deleted frame id: " + getFrameID().getName();
    }

    String str = getDirectType().getBrowserText() + " (";
    for (Iterator it = getValues().iterator(); it.hasNext(); ) {
      Object value = it.next();
      if (value instanceof Instance) {
        str += ((Instance) value).getBrowserText();
      } else {
        str += value;
      }
      if (it.hasNext()) {
        str += ", ";
      }
    }
    return str + ")";
  }
public class DatabaseRepositoryCreatorWizardPlugin implements RepositoryCreatorWizardPlugin {
  static final transient Logger log = Log.getLogger(DatabaseRepositoryCreatorWizardPlugin.class);

  public String getName() {
    return "Database Repository";
  }

  public String getDescription() {
    return "Create a repository representing ontologies found in a database";
  }

  public boolean isSuitable(OWLModel model) {
    return true;
  }

  public RepositoryCreatorWizardPanel createRepositoryCreatorWizardPanel(
      WizardPage wizardPage, OWLModel owlModel) {
    return new DatabaseWizardPanel(wizardPage, owlModel);
  }
}
 public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
   SWRLImp imp = getImp(rowIndex);
   if (columnIndex == COL_EXPRESSION) {
     String text = (String) aValue;
     try {
       imp.setExpression(text);
       if (!isSuitable(imp)) {
         ProtegeUI.getModalDialogFactory()
             .showMessageDialog(
                 owlModel,
                 "The replacing rule no longer fits the selection\n"
                     + "criteria of this rules list, and will therefore no\n"
                     + "longer be visible here.  But no reason to panic: It\n"
                     + "should still show up on the SWRL tab.");
       }
     } catch (Exception ex) {
       Log.getLogger().warning("Exception caught defining rule " + ex);
     }
   } else if (columnIndex == COL_NAME) {
     String newName = (String) aValue;
     if (owlModel.isValidResourceName(newName, imp)) {
       RDFResource resource = owlModel.getRDFResource(newName);
       if (resource != null) {
         if (!imp.equals(resource)) {
           ProtegeUI.getModalDialogFactory()
               .showErrorMessageDialog(
                   owlModel, "The name " + newName + " is already used in this ontology.");
         }
       } else {
         imp = (SWRLImp) imp.rename(newName);
         setImp(rowIndex, imp);
       }
     } else
       ProtegeUI.getModalDialogFactory()
           .showErrorMessageDialog(owlModel, newName + " is not a valid rule name.");
   } else if (columnIndex == COL_ENABLED) {
     Boolean enabled = (Boolean) aValue;
     if (enabled.booleanValue()) imp.enable();
     else imp.disable();
   } // if
 } // setValueAt
Exemple #10
0
  public Vector<String> validateData(Vector<String> v) {

    // keep a vector or error messages, may be more than one
    Vector<String> w = new Vector<String>();

    try {

      String cls_name = (String) v.elementAt(0);
      String action = (String) v.elementAt(1);
      String attribute = (String) v.elementAt(2);
      String attributename = (String) v.elementAt(3);
      String attributevalue_1 = (String) v.elementAt(4);
      String attributevalue_2 = (String) v.elementAt(5);

      OWLNamedClass hostClass = wrapper.getOWLNamedClass(cls_name);

      Vector superclasses = new Vector();
      if (hostClass == null) {
        String error_msg = " -- concept " + cls_name + " does not exist.";
        w.add(error_msg);

      } else if (wrapper.isRetired(hostClass)) {
        w.add(" -- concept " + cls_name + " is retired, cannot edit");
      }

      if (action.compareToIgnoreCase("new") != 0
          && action.compareToIgnoreCase("edit") != 0
          && action.compareToIgnoreCase("delete") != 0) {
        String error_msg = " -- action " + action + " is not supported.";
        w.add(error_msg);
      }

      if (attribute.compareToIgnoreCase("parent") != 0
          && attribute.compareToIgnoreCase("role") != 0
          && attribute.compareToIgnoreCase("property") != 0
          && attribute.compareToIgnoreCase("association") != 0) {
        String error_msg = " -- attribute " + attribute + " is not supported.";
        w.add(error_msg);
      }

      if (action.compareToIgnoreCase("new") == 0) {
        if (hostClass != null) {
          if (attribute.compareToIgnoreCase("role") == 0) {
            if (!supportedRoles.contains(attributename)) {
              String error_msg = " -- role " + attributename + " is not identifiable.";
              w.add(error_msg);
            } else {
              int pos = attributevalue_1.indexOf("|");
              if (pos == -1) {
                String error_msg = " -- missing modifier or filler.";
                w.add(error_msg);
              } else {
                String filler = attributevalue_1.substring(pos + 1, attributevalue_1.length());

                OWLNamedClass targetClass = (OWLNamedClass) owlModel.getRDFSNamedClass(filler);
                if (targetClass == null) {
                  String error_msg = " -- concept " + filler + " does not exist.";
                  w.add(error_msg);
                } else {
                  if (wrapper.hasRole(hostClass, attributename, filler)) {
                    String error_msg = " -- role already exists.";
                    w.add(error_msg);
                  }
                }
              }
            }
          } else if (attribute.compareToIgnoreCase("parent") == 0) {

            OWLNamedClass superClass = (OWLNamedClass) owlModel.getRDFSNamedClass(attributename);
            if (superClass == null) {
              String error_msg = " -- superconcept does not exist.";
              w.add(error_msg);

            } else {

              if (wrapper.isPremerged(superClass)
                  || wrapper.isPreretired(superClass)
                  || wrapper.isRetired(superClass)) {
                String error_msg = "superconcept cannot be premerged, preretired, or retired.";
                w.add(error_msg);
              }
            }

          } else if (attribute.compareToIgnoreCase("property") == 0) {
            if (!supportedProperties.contains(attributename)) {
              String error_msg = " -- property " + attributename + " is not identifiable.";
              w.add(error_msg);
            } else {
              if (wrapper.hasProperty(hostClass, attributename, attributevalue_1)) {
                String error_msg = " -- property already exists.";
                w.add(error_msg);
              }
            }
            if (this.tab.getFilter().checkBatchProperty(attributename, attributevalue_1)
                && this.tab
                    .getFilter()
                    .checkBatchPropertyNotFullSynPT(attributename, attributevalue_1)) {

            } else {
              w.add(tab.getFilter().getErrorMessage());
            }
          } else if (attribute.compareToIgnoreCase("association") == 0) {
            if (!supportedAssociations.contains(attributename)) {
              String error_msg = " -- association " + attributename + " is not identifiable.";
              w.add(error_msg);
            } else {
              OWLNamedClass targetClass =
                  (OWLNamedClass) owlModel.getRDFSNamedClass(attributevalue_1);
              if (targetClass == null) {
                String error_msg = " -- concept " + attributevalue_1 + " does not exist.";
                w.add(error_msg);
              } else {
                if (wrapper.hasAssociation(hostClass, attributename, attributevalue_1)) {
                  String error_msg = " -- association already exists.";
                  w.add(error_msg);
                }
              }
            }
          }
        }
      } else if (action.compareToIgnoreCase("edit") == 0
          || action.compareToIgnoreCase("delete") == 0) {
        if (hostClass != null) {
          if (attribute.compareToIgnoreCase("parent") == 0) {
            if (action.compareToIgnoreCase("delete") == 0) {
              OWLNamedClass superClass = (OWLNamedClass) owlModel.getRDFSNamedClass(attributename);
              if (superClass == null) {
                String error_msg = " -- superconcept " + attributename + " does not exist.";
                w.add(error_msg);
              } else if (wrapper.getDirectSuperclassNames(hostClass).size() == 1) {
                String error_msg = " -- can't delete last superconcept " + attributename;
                w.add(error_msg);
              }

            } else {
              String error_msg =
                  " -- edit parent action is not supported. Use delete and add actions instead.";
              w.add(error_msg);
            }
          } else if (attribute.compareTo("role") == 0) {
            if (!supportedRoles.contains(attributename)) {
              String error_msg = " -- role " + attributename + " is not identifiable.";
              w.add(error_msg);
            } else {
              int pos = attributevalue_1.indexOf("|");
              if (pos == -1) {
                String error_msg = " -- missing modifier or filler.";
                w.add(error_msg);
              } else {
                String filler = attributevalue_1.substring(pos + 1, attributevalue_1.length());

                OWLNamedClass targetClass = (OWLNamedClass) owlModel.getRDFSNamedClass(filler);
                if (targetClass == null) {
                  String error_msg = " -- concept " + filler + " does not exist.";
                  w.add(error_msg);
                } else {
                  if (!wrapper.hasRole(hostClass, attributename, filler)) {
                    String error_msg = " -- role does not exist.";
                    w.add(error_msg);
                  }

                  if (action.compareTo("edit") == 0) {
                    pos = attributevalue_2.indexOf("|");
                    if (pos == -1) {
                      String error_msg = " -- missing modifier or filler.";
                      w.add(error_msg);
                    } else {
                      filler = attributevalue_2.substring(pos + 1, attributevalue_2.length());

                      targetClass = (OWLNamedClass) owlModel.getRDFSNamedClass(filler);
                      if (targetClass == null) {
                        String error_msg = " -- concept " + filler + " does not exist.";
                        w.add(error_msg);
                      }
                    }
                  }
                }
              }
            }
          } else if (attribute.compareToIgnoreCase("property") == 0) {
            if (!supportedProperties.contains(attributename)) {
              String error_msg = " -- property " + attributename + " is not identifiable.";
              w.add(error_msg);
            } else {
              Boolean editable = wrapper.isReadOnlyProperty(attributename);
              if (editable.equals(Boolean.TRUE)) {
                String error_msg = " -- property " + attributename + ", it is read-only.";
                w.add(error_msg);
              }

              if (!wrapper.hasProperty(hostClass, attributename, attributevalue_1)) {

                String error_msg =
                    " -- property "
                        + "("
                        + attributename
                        + ", "
                        + attributevalue_1
                        + ") does not exist.";
                w.add(error_msg);
              }

              if (action.compareToIgnoreCase("edit") == 0) {
                if (wrapper.hasProperty(hostClass, attributename, attributevalue_2)) {
                  String error_msg =
                      " -- property "
                          + "("
                          + attributename
                          + ", "
                          + attributevalue_2
                          + ") already exists.";
                  w.add(error_msg);
                } else if (attributevalue_2.equalsIgnoreCase("NA")) {
                  String error_msg =
                      " -- property " + "(" + attributename + ") new value is not specified.";
                  w.add(error_msg);
                } else if (this.tab.getFilter().checkBatchProperty(attributename, attributevalue_2)
                    && this.tab
                        .getFilter()
                        .checkBatchPropertyNotFullSynPT(attributename, attributevalue_2)) {

                } else {
                  w.add(tab.getFilter().getErrorMessage());
                }
              } else {
                if (this.tab.getFilter().checkBatchProperty(attributename, attributevalue_1)) {

                } else {
                  w.add(tab.getFilter().getErrorMessage());
                }
              }
            }
          } else if (attribute.compareTo("association") == 0) {
            if (!supportedAssociations.contains(attributename)) {
              String error_msg = " -- association " + attributename + " is not identifiable.";
              w.add(error_msg);
            }

            if (action.compareToIgnoreCase("delete") == 0) {
              OWLNamedClass targetClass =
                  (OWLNamedClass) owlModel.getRDFSNamedClass(attributevalue_1);
              if (targetClass == null) {
                String error_msg = " -- concept " + attributevalue_1 + " does not exist.";
                w.add(error_msg);
              } else {
                if (!wrapper.hasAssociation(hostClass, attributename, attributevalue_1)) {
                  String error_msg = " -- association does not exist.";
                  w.add(error_msg);
                }
              }
            } else {
              String error_msg =
                  " -- edit association action is not supported. Use delete and add actions instead.";
              w.add(error_msg);
            }
          }
        }
      }

    } catch (Exception e) {
      Log.getLogger().log(Level.WARNING, "Exception caught", e);
    }

    return w;
  }
/**
 * This is a basic cache that takes the behavior of its delegate. But it ignores the impact of
 * transactions on the cache and assumes that its delegate does the same.
 *
 * <p>It will only return valid results in the case that the transaction isolation level is NONE or
 * where the caller covers the in transaction case.
 *
 * @author tredmond
 */
public class CompleteableCache<S, V, R> implements Cache<S, V, R> {
  enum CompletionStatus {
    NORMAL,
    GETTING_COMPLETE_CACHE,
    CACHE_COMPLETE;
  };

  private Logger logger = Log.getLogger(CompleteableCache.class);

  private CompletionStatus status = CompletionStatus.NORMAL;
  private Set<V> invalidReads = new HashSet<V>();
  private Cache<S, V, R> delegate;

  public CompleteableCache(Cache<S, V, R> delegate) {
    this.delegate = delegate;
  }

  public CacheResult<R> readCache(S session, V var) {
    CacheResult<R> result = delegate.readCache(session, var);
    if (result.getResult() == null
        && status == CompletionStatus.CACHE_COMPLETE
        && !invalidReads.contains(var)
        && !result.isValid()) {
      if (logger.isLoggable(Level.FINEST)) {
        logger.finest("Cache " + getCacheId() + " is complete - null is valid.");
      }
      return new CacheResult<R>(null, true);
    }
    return result;
  }

  public void updateCache(S session, V var) {
    if (status != CompletionStatus.NORMAL) {
      invalidReads.add(var);
    }
    delegate.updateCache(session, var);
  }

  public void updateCache(S session, V var, R value) {
    if (status != CompletionStatus.NORMAL) {
      invalidReads.remove(var);
    }
    delegate.updateCache(session, var, value);
  }

  public void modifyCache(S session, V var) {
    if (status != CompletionStatus.NORMAL) {
      invalidReads.add(var);
    }
    delegate.modifyCache(session, var);
  }

  public void modifyCache(S session, V var, R value) {
    if (status != CompletionStatus.NORMAL) {
      invalidReads.remove(var);
    }
    delegate.modifyCache(session, var, value);
  }

  public void invalidate(S session) {
    delegate.invalidate(session);
  }

  public boolean isInvalid() {
    return delegate.isInvalid();
  }

  public void startCompleteCache() {
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Cache " + getCacheId() + " starting to complete the cache");
    }
    status = CompletionStatus.GETTING_COMPLETE_CACHE;
    invalidReads = new HashSet<V>();
    delegate.startCompleteCache();
  }

  public void finishCompleteCache() {
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Cache " + getCacheId() + " cache completed");
    }
    if (status == CompletionStatus.GETTING_COMPLETE_CACHE) {
      status = CompletionStatus.CACHE_COMPLETE;
    }
    delegate.finishCompleteCache();
  }

  public void abortCompleteCache() {
    if (logger.isLoggable(Level.FINEST)) {
      logger.finest("Cache " + getCacheId() + " caching aborted");
    }
    status = CompletionStatus.NORMAL;
    invalidReads.clear();
    delegate.abortCompleteCache();
  }

  public boolean isCacheComplete() {
    return status == CompletionStatus.CACHE_COMPLETE;
  }

  public void beginTransaction(S session) {
    delegate.beginTransaction(session);
  }

  public void commitTransaction(S session) {
    delegate.commitTransaction(session);
  }

  public void rollbackTransaction(S session) {
    delegate.rollbackTransaction(session);
  }

  public int getTransactionNesting(S session) {
    return delegate.getTransactionNesting(session);
  }

  public void flush() {
    localFlush();
    delegate.flush();
  }

  private void localFlush() {
    status = CompletionStatus.NORMAL;
    invalidReads.clear();
  }

  public int getCacheId() {
    return delegate.getCacheId();
  }
}
/**
 * The base class of various JUnit tests in this package.
 *
 * @author Holger Knublauch <*****@*****.**>
 */
public abstract class AbstractJenaTestCase extends AbstractOWLTestCase {
  private static final transient Logger log = Log.getLogger(AbstractJenaTestCase.class);

  protected OntModel ontModel;

  protected Model owlFullModel;

  protected int getNamedClassesCount() {
    return list(ontModel.listNamedClasses()).size();
  }

  public void loadRemoteOntology(String localFileName) throws OntologyLoadException {
    loadTestOntology(getRemoteOntologyURI(localFileName));
  }

  protected void loadRemoteOntologyWithProtegeMetadataOntology() throws Exception {
    loadRemoteOntology("import-protege.owl");
  }

  @SuppressWarnings("unchecked")
  public void loadTestOntology(URI uri) throws OntologyLoadException {
    Collection errors = new ArrayList();
    OwlProjectFromUriCreator creator = new OwlProjectFromUriCreator();
    creator.setOntologyUri(uri.toString());
    creator.create(errors);
    owlModel = creator.getOwlModel();
    owlModel.setExpandShortNameInMethods(true);
    project = owlModel.getProject();
    owlThing = owlModel.getOWLThingClass();
  }

  protected boolean ontResourceExists(Iterator it, String uri) {
    while (it.hasNext()) {
      OntResource ontResource = (OntResource) it.next();
      String otherURI = ontResource.getURI();
      if (otherURI.equals(uri)) {
        return true;
      }
    }
    return false;
  }

  @SuppressWarnings("unchecked")
  public JenaOWLModel reload(JenaOWLModel owlModel) throws Exception {
    Collection errors = new ArrayList();
    OntModel ontModel = owlModel.getOntModel();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Jena.dumpRDF(ontModel, stream);
    String str = stream.toString();
    StringReader reader = new StringReader(str);
    if (log.isLoggable(Level.FINE)) {
      log.fine("Saved ontology to string");
      log.fine(str);
      log.fine("reloading...");
    }
    OwlProjectFromReaderCreator creator = new OwlProjectFromReaderCreator();
    creator.setReader(reader);
    creator.create(errors);
    return creator.getOwlModel();
  }

  public JenaOWLModel reloadWithJenaLoader(JenaOWLModel owlModel) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Jena.dumpRDF(owlModel.getOntModel(), stream);
    String str = stream.toString();
    return ProtegeOWL.createJenaOWLModelFromReader(new StringReader(str));
  }
}
public class AllValuesFromRestrictionUpdater extends QuantifierRestrictionUpdater {
  private static final transient Logger log = Log.getLogger(AllValuesFromRestrictionUpdater.class);

  private Cls metaCls;

  private Facet valueTypeFacet;

  public AllValuesFromRestrictionUpdater(OWLModel owlModel) {
    super(owlModel);
    metaCls = owlModel.getSystemFrames().getOwlAllValuesFromClass();
    valueTypeFacet = owlModel.getSystemFrames().getValueTypeFacet();
  }

  private void addAllRestriction(Cls cls, RDFProperty property, Cls allCls) {
    OWLAllValuesFrom restriction = owlModel.createOWLAllValuesFrom(property, (RDFSClass) allCls);
    cls.addDirectSuperclass(restriction);
    if (log.isLoggable(Level.FINE)) {
      log.fine(
          "+ OWLAllValuesFrom "
              + restriction.getBrowserText()
              + " to "
              + cls.getName()
              + "."
              + property.getName());
    }
  }

  @Override
  protected void clearFiller(OWLQuantifierRestriction restriction) {
    owlModel.setTemplateSlotAllowedClses(
        restriction, restriction.getOnProperty(), Collections.EMPTY_LIST);
    // restriction.setTemplateSlotAllowedClses(restriction.getOnProperty(), Collections.EMPTY_LIST);
  }

  // Implements RestrictionUpdater
  public void copyFacetValuesIntoNamedClass(RDFSNamedClass cls, OWLRestriction restriction) {
    Slot slot = restriction.getOnProperty();
    updateValueTypeFacet(cls, slot);
  }

  private void removeValueTypeOverride(RDFSNamedClass cls, Slot slot) {
    if (slot != null && ((Cls) cls).hasDirectlyOverriddenTemplateFacet(slot, valueTypeFacet)) {
      ((Cls) cls).setTemplateSlotAllowedClses(slot, Collections.EMPTY_LIST);
      ((Cls) cls).setTemplateFacetValues(slot, valueTypeFacet, Collections.EMPTY_LIST);
      if (log.isLoggable(Level.FINE)) {
        log.fine("- Removed :VALUE-TYPE override from " + cls.getName() + "." + slot.getName());
      }
    }
  }

  private void setAllowedClses(RDFSNamedClass cls, Slot slot, Collection newAllowedClses) {
    if (log.isLoggable(Level.FINE)) {
      log.fine("+ Setting allowed clses of " + cls.getName() + "." + slot.getName());
    }
    for (Iterator it = newAllowedClses.iterator(); it.hasNext(); ) {
      Cls ac = (Cls) it.next();
      if (log.isLoggable(Level.FINE)) {
        log.fine("  - " + ac.getBrowserText());
      }
    }
    ((Cls) cls).setTemplateSlotAllowedClses(slot, newAllowedClses);
  }

  private void setAllowedValues(RDFSNamedClass cls, Slot slot, Collection newAllowedValues) {
    if (log.isLoggable(Level.FINE)) {
      log.fine("+ Setting allowed values of " + cls.getName() + "." + slot.getName());
    }
    for (Iterator it = newAllowedValues.iterator(); it.hasNext(); ) {
      Object ac = it.next();
      if (log.isLoggable(Level.FINE)) {
        log.fine("  - " + ac);
      }
    }
    ((Cls) cls).setTemplateSlotAllowedValues(slot, newAllowedValues);
  }

  protected void updateAllRestrictions(Cls cls, RDFProperty property) {
    if (cls.hasDirectlyOverriddenTemplateFacet(property, valueTypeFacet)) {
      ValueType valueType = cls.getTemplateSlotValueType(property);
      if (valueType == ValueType.INSTANCE) {
        Collection clses = cls.getTemplateSlotAllowedClses(property);
        if (clses.size() == 0) {
          removeRestrictions(cls, property, metaCls);
          addAllRestriction(cls, property, owlModel.createOWLEnumeratedClass());
        } else {
          ensureNoSurvivingClsesAreDeleted(cls, property, clses, metaCls);
          if (clses.size() == 1) {
            Cls allCls = (Cls) clses.iterator().next();
            removeRestrictions(cls, property, metaCls);
            addAllRestriction(cls, property, allCls);
          } else {
            OWLUnionClass unionCls = owlModel.createOWLUnionClass(clses);
            removeRestrictions(cls, property, metaCls);
            addAllRestriction(cls, property, unionCls);
          }
        }
      } else if (valueType != ValueType.SYMBOL && valueType != ValueType.CLS) {
        removeRestrictions(cls, property, metaCls);
        RDFSDatatype datatype =
            owlModel.getRDFSDatatypeByURI(
                XMLSchemaDatatypes.getDefaultXSDDatatype(valueType).getURI());
        OWLAllValuesFrom restriction = owlModel.createOWLAllValuesFrom(property, datatype);
        cls.addDirectSuperclass(restriction);
        if (log.isLoggable(Level.FINE)) {
          log.fine(
              "+ OWLAllValuesFrom "
                  + restriction.getBrowserText()
                  + " to "
                  + cls.getName()
                  + "."
                  + property.getName());
        }
      }
    } else {
      removeRestrictions(cls, property, metaCls);
    }
  }

  // Implements RestrictionUpdater
  public void updateRestrictions(OWLNamedClass cls, RDFProperty property, Facet facet) {
    updateAllRestrictions(cls, property);
  }

  /**
   * Called when the superclasses have changed for a given Cls. This makes sure that the :VALUE-TYPE
   * facet is overridden to contain all the "all" values from the current restrictions and union
   * superclasses.
   *
   * @param cls the Cls where the restrictions have changed
   * @param slot the Slot that the restrictions restrict
   */
  void updateValueTypeFacet(RDFSNamedClass cls, Slot slot) {
    if (slot != null) {
      Collection<OWLAllValuesFrom> rs = getDirectRestrictions(cls, slot, OWLAllValuesFrom.class);
      if (rs.size() == 1) {
        OWLQuantifierRestriction restriction = rs.iterator().next();
        updateValueTypeFacet(cls, slot, restriction);
      } else {
        // Cannot do any overrides when more than one exist (this would be intersection)
        removeValueTypeOverride(cls, slot);
      }
    }
  }

  private void updateValueTypeFacet(
      RDFSNamedClass cls, Slot slot, OWLQuantifierRestriction restriction) {
    ValueType oldValueType = ((Cls) cls).getTemplateSlotValueType(slot);
    ValueType newValueType = oldValueType;
    Collection oldAllowedClses = ((Cls) cls).getTemplateSlotAllowedClses(slot);
    Collection newAllowedClses = oldAllowedClses;
    Collection oldAllowedValues = ((Cls) cls).getTemplateSlotAllowedValues(slot);
    Collection newAllowedValues = oldAllowedValues;
    RDFResource filler = restriction.getFiller();
    if (filler instanceof RDFSClass) {
      RDFSClass quantifierClass = (RDFSClass) filler;
      if (RDFSNames.Cls.LITERAL.equals(quantifierClass.getName())) {
        newValueType = ValueType.ANY;
      } else {
        newValueType = ValueType.INSTANCE;
        newAllowedClses = getQuantifierClsClses(quantifierClass);
      }
    } else {
      if (filler instanceof OWLDataRange) {
        newAllowedValues = ((OWLDataRange) filler).getOneOf().getValues();
        newValueType = ValueType.SYMBOL;
      } else {
        RDFSDatatype datatype = (RDFSDatatype) filler;
        if (datatype.equals(owlModel.getRDFXMLLiteralType())) {
          newValueType = ValueType.STRING;
        } else {
          String uri = XMLSchemaDatatypes.getXSDDatatype(datatype).getURI();
          newValueType = XMLSchemaDatatypes.getValueType(uri);
        }
      }
    }

    if (oldValueType == newValueType) {
      if (newValueType == ValueType.INSTANCE && !oldAllowedClses.equals(newAllowedClses)) {
        setAllowedClses(cls, slot, newAllowedClses);
      } else if (newValueType == ValueType.SYMBOL && !oldAllowedValues.equals(newAllowedValues)) {
        setAllowedValues(cls, slot, newAllowedValues);
      }
    } else {
      if (log.isLoggable(Level.FINE)) {
        log.fine(
            "+ Setting :VALUE-TYPE of "
                + cls.getName()
                + "."
                + slot.getName()
                + " to "
                + newValueType);
      }
      ((Cls) cls).setTemplateSlotValueType(slot, newValueType);
      if (newValueType == ValueType.INSTANCE) {
        setAllowedClses(cls, slot, newAllowedClses);
      } else if (newValueType == ValueType.SYMBOL) {
        setAllowedValues(cls, slot, newAllowedValues);
      }
    }
  }
}
Exemple #14
0
/**
 * A class that can convert pure RDF statements from a Model into corresponding OWL statements.
 *
 * @author Holger Knublauch <*****@*****.**>
 */
public class RDF2OWL {
  private static final transient Logger log = Log.getLogger(RDF2OWL.class);

  private Model model;

  public RDF2OWL(Model model) {
    this.model = model;
  }

  /** Converts all rdfs:Classes into owl:Classes */
  private void convertRDFSClasses() {
    for (StmtIterator it = model.listStatements(null, RDF.type, RDFS.Class); it.hasNext(); ) {
      Statement s = it.nextStatement();
      Resource clazz = s.getSubject();
      s.getModel().add(clazz, RDF.type, OWL.Class);
      it.remove();
      if (log.isLoggable(Level.FINE)) {
        log.fine("Converted rdfs:Class " + clazz + " into owl:Class");
      }
    }
  }

  /** Converts the properties to either owl:DatatypeProperties or owl:ObjectProperties. */
  private void convertProperties() {
    for (StmtIterator it = model.listStatements(null, RDF.type, RDF.Property); it.hasNext(); ) {
      Statement s = it.nextStatement();
      Resource property = s.getSubject();
      Resource type = getPropertyType(property);
      s.getModel().add(property, RDF.type, type);
      it.remove();
      if (log.isLoggable(Level.FINE)) {
        log.fine("Converted rdf:Property " + property + " into " + type);
      }
    }
  }

  /** Converts all object occurances of rdfs:Resource with owl:Thing */
  private void convertRDFSResource() {
    for (StmtIterator it = model.listStatements(null, null, RDFS.Resource); it.hasNext(); ) {
      Statement s = it.nextStatement();
      s.getModel().add(s.getSubject(), s.getPredicate(), OWL.Thing);
      if (log.isLoggable(Level.FINE)) {
        log.fine("Replaced triple " + s + " with (x, x, owl:Thing)");
      }
      it.remove();
    }
  }

  /**
   * Attempts to find the most plausible RDF type for a given property.
   *
   * @param property the property to get the type of
   * @return either owl:DatatypeProperty or owl:ObjectProperty
   */
  private Resource getPropertyType(Resource property) {
    StmtIterator it = model.listStatements(property, RDFS.range, (RDFNode) null);
    if (it.hasNext()) {
      while (it.hasNext()) {
        Statement s = it.nextStatement();
        RDFNode n = s.getObject();
        if (n.canAs(Resource.class)
            && model.contains((Resource) n.as(Resource.class), RDF.type, OWL.Class)) {
          return OWL.ObjectProperty;
        }
      }
    }
    return OWL.DatatypeProperty;
  }

  public void run() {
    unifyRDFSVersion();
    convertRDFSResource();
    // convertRDFSClasses();
    // convertProperties();
  }

  /** Converts any statements containing old RDFS vocabulary to the official ones. */
  private void unifyRDFSVersion() {
    String[] oldRDFSNSs = {
      // "http://www.w3.org/2000/01/rdf-schema#",
      "http://www.w3.org/TR/1999/PR-rdf-schema-19990303#" // Any others???
    };
    for (int i = 0; i < oldRDFSNSs.length; i++) {
      String oldRDFSNS = oldRDFSNSs[i];
      unifyRDFSVersion(oldRDFSNS);
    }
  }

  private void unifyRDFSVersion(String ns) {
    for (Iterator it = Jena.cloneIt(model.listStatements()); it.hasNext(); ) {
      Statement s = (Statement) it.next();
      Resource newSubject = s.getSubject();
      Property newPredicate = s.getPredicate();
      RDFNode newObject = s.getObject();
      boolean changed = false;
      if (ns.equals(newSubject.getNameSpace())) {
        changed = true;
        newSubject = model.getResource(RDFS.getURI() + newSubject.getLocalName());
      }
      if (ns.equals(newPredicate.getNameSpace())) {
        changed = true;
        newPredicate = model.getProperty(RDFS.getURI() + newPredicate.getLocalName());
      }
      if (newObject.canAs(Resource.class)) {
        Resource oldResource = (Resource) newObject.as(Resource.class);
        if (ns.equals(oldResource.getNameSpace())) {
          changed = true;
          newObject = model.getResource(RDFS.getURI() + oldResource.getLocalName());
        }
      }
      if (changed) {
        model.add(newSubject, newPredicate, newObject);
        if (log.isLoggable(Level.FINE)) {
          log.fine(
              "Replaced deprecated triple "
                  + s
                  + " with "
                  + newSubject
                  + ", "
                  + newPredicate
                  + ", "
                  + newObject);
        }
        it.remove();
      }
    }
  }
}
/** @author Holger Knublauch <*****@*****.**> */
public class OWLDatabaseWizardPage extends DatabaseWizardPage {
  private static final long serialVersionUID = 251501005887139194L;
  private static transient Logger log = Log.getLogger(OWLDatabaseWizardPage.class);

  private OWLDatabasePlugin plugin;

  private JTextField ontologyName;

  public OWLDatabaseWizardPage(Wizard wizard, OWLDatabasePlugin plugin) {
    super(wizard, plugin);
    this.plugin = plugin;
  }

  protected Class<? extends DatabaseFrameDb> getDatabaseFrameDbClass() {
    return DefaultDatabaseFrameDb.class;
  }

  @Override
  protected void layoutComponents(Box panel) {
    if (!getFromExistingSources()) {
      ontologyName = ComponentFactory.createTextField(FactoryUtils.generateOntologyURIBase());
      ontologyName.addFocusListener(
          new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent event) {
              updateSetPageComplete();
            }
          });
      panel.add(new LabeledComponent("Ontology Name", ontologyName));
    }
    super.layoutComponents(panel);
  }

  @Override
  protected boolean isComplete() {
    if (getFromExistingSources()) {
      return super.isComplete();
    }
    return super.isComplete() && isValidURL();
  }

  private boolean isValidURL() {
    try {
      new URL(ontologyName.getText());
      return true;
    } catch (MalformedURLException e) {
      setErrorText("Need valid URL for ontology name: " + e);
      return false;
    }
  }

  @Override
  public void onFinish() {
    if (!getFromExistingSources()) {
      plugin.setOntologyName(ontologyName.getText());
    }
    if (!okToCreateDatabase()) { // ToDo Jennifer or Tania will know the better way...
      throw new ProtegeIOException("Database already exists! and the user denied overwrite");
    }
    super.onFinish();
  }

  protected boolean okToCreateDatabase() {
    Connection connection = null;
    try {
      try {
        Class.forName(getFieldText(DRIVER_PROPERTY));
        connection =
            DriverManager.getConnection(
                getFieldText(URL_PROPERTY),
                getFieldText(USERNAME_PROPERTY),
                getFieldText(PASSWORD_PROPERTY));
      } catch (ClassNotFoundException cnfe) {
        throw new ProtegeIOException(cnfe);
      } catch (SQLException sqle) {
        throw new ProtegeIOException(sqle);
      }
      return okToCreateDatabase(connection);
    } finally {
      try {
        if (connection != null) {
          connection.close();
        }
      } catch (SQLException sqle) {
        log.log(
            Level.WARNING,
            "Exception caught trying to close connections during database existence check.",
            sqle);
      }
    }
  }

  private boolean okToCreateDatabase(Connection connection) {
    if (!databaseExists(connection)) {
      return true;
    }
    String existingOntologyName;
    try {
      existingOntologyName =
          DatabaseFactoryUtils.getOntologyFromTable(
              getDatabaseFrameDbClass(),
              getFieldText(DRIVER_PROPERTY),
              getFieldText(URL_PROPERTY),
              getFieldText(USERNAME_PROPERTY),
              getFieldText(PASSWORD_PROPERTY),
              getFieldText(TABLENAME_PROPERTY));
    } catch (SQLException sqle) {
      existingOntologyName = null;
    }
    String message;
    if (getFromExistingSources() && !isFileToDatabase() && existingOntologyName != null) {
      return true;
    } else if (getFromExistingSources() && !isFileToDatabase()) {
      message =
          "Database already exists but is in the wrong format for an OWL Database Project.\nOverwrite with blank owl project?";
    } else if (existingOntologyName != null) {
      message =
          "Database table already exists and holds an ontology named\n"
              + existingOntologyName
              + ".\nOverwrite?";
    } else {
      message = "Database table already exists.  Overwrite?";
    }
    int ok =
        ModalDialog.showMessageDialog(
            this, message, "Overwrite Table?", ModalDialog.MODE_OK_CANCEL);
    return ok == ModalDialog.OPTION_OK;
  }

  private boolean databaseExists(Connection connection) {
    Statement statement;
    try {
      statement = connection.createStatement();
    } catch (SQLException sqle) {
      throw new ProtegeIOException(sqle);
    }
    try {
      statement.execute("select count(*) from " + getFieldText(TABLENAME_PROPERTY));
      return true;
    } catch (SQLException sqle) {
      if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, "This exception should indicate that the table doesn't exist", sqle);
      }
      return false;
    } finally {
      try {
        if (statement != null) {
          statement.close();
        }
      } catch (SQLException sqle) {
        log.log(
            Level.WARNING,
            "Unexpected exception caught trying to check the  existence of a database table",
            sqle);
      }
    }
  }

  public boolean getFromExistingSources() {
    return false;
  }

  public boolean isFileToDatabase() {
    return false;
  }
}