/**
   * Method that calculates if two elements of an ontology are exact.
   *
   * @param requestParameter - A request parameter.
   * @param serviceParameter - A service parameter.
   * @param typoOfParameter - It informs if the parameters are inputs or outputs.
   * @return true/false - return true if they are the same and false if they are different.
   */
  @SuppressWarnings("unchecked")
  private boolean isExactMatching(
      URI requestParameter, URI serviceParameter, char typeOfParameter) {
    Iterator iterClass = null;
    NodeIterator iter = null;
    OntClass ontClass = null;

    loadOntology(
        requestParameter.getScheme() + ":" + requestParameter.getSchemeSpecificPart() + "#");

    if (typeOfParameter == FunctionalMatcher.INPUT) {
      resource = model.getResource(ontology + requestParameter.getFragment());
      iter = model.listObjectsOfProperty(resource, OWL.equivalentClass);
      while (iter.hasNext()) {
        if (serviceParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }

      ontClass = model.getOntClass(requestParameter.toString());
      iterClass = ontClass.listSubClasses(true);
      while (iterClass.hasNext()) {
        if (serviceParameter.toString().equals(iterClass.next().toString())) {
          return true;
        }
      }
    } else if (typeOfParameter == FunctionalMatcher.OUTPUT) {
      resource = model.getResource(ontology + requestParameter.getFragment());
      iter = model.listObjectsOfProperty(resource, OWL.equivalentClass);
      while (iter.hasNext()) {
        if (serviceParameter.toString().equals(iter.next().toString())) {
          return true;
        }
      }

      ontClass = model.getOntClass(serviceParameter.toString());
      iterClass = ontClass.listSubClasses(true);
      while (iterClass.hasNext()) {
        if (requestParameter.toString().equals(iterClass.next().toString())) {
          return true;
        }
      }
    }
    if (requestParameter.toString().equals(serviceParameter.toString())) {
      return true;
    }
    return false;
  }
 protected void checkNumericContent(final Container cont2, final int num) {
   final NodeIterator nit = cont2.iterator();
   for (int i = 0; i < num; i += 1) {
     Assert.assertEquals(i, ((Literal) nit.nextNode()).getInt());
   }
   Assert.assertFalse(nit.hasNext());
 }
  @Override
  protected void doRun(Event event) throws Exception {

    // check the global COORDINATION_MESSAGE (must be ABORT)
    if (event instanceof CloseFromOtherNeedEvent) {
      WonMessage wonMessage = ((CloseFromOtherNeedEvent) event).getWonMessage();
      NodeIterator ni =
          RdfUtils.visitFlattenedToNodeIterator(
              wonMessage.getMessageContent(),
              new RdfUtils.ModelVisitor<NodeIterator>() {
                @Override
                public NodeIterator visit(final Model model) {
                  return model.listObjectsOfProperty(
                      model.createProperty(WON_TX.COORDINATION_MESSAGE.getURI()));
                }
              });
      if (ni.hasNext()) {
        String coordinationMessageUri = ni.toList().get(0).asResource().getURI().toString();
        if (coordinationMessageUri.equals(WON_TX.COORDINATION_MESSAGE_ABORT.getURI().toString()))
          logger.debug("Sent COORDINATION_MESSAGE: {}", coordinationMessageUri);
        else
          logger.error(
              "Content of the COORDINATION_MESSAGE must be: {}. Currently it is: {}",
              WON_TX.COORDINATION_MESSAGE_ABORT.getURI(),
              coordinationMessageUri);
      }
    }
    List<URI> toDeactivate = getEventListenerContext().getBotContext().listNeedUris();
    for (URI uri : toDeactivate) {
      getEventListenerContext().getOwnerService().deactivate(uri, createWonMessage(uri));
      getEventListenerContext().getEventBus().publish(new NeedDeactivatedEvent(uri));
    }
  }
 protected void seeWhatsThere(final Container cont2, final boolean[] found) {
   final NodeIterator nit = cont2.iterator();
   while (nit.hasNext()) {
     final int v = ((Literal) nit.nextNode()).getInt();
     Assert.assertFalse(found[v]);
     found[v] = true;
   }
 }
 protected void retainOnlySpecified(final Container cont2, final int num, final boolean[] retain) {
   final NodeIterator nit = cont2.iterator();
   for (int i = 0; i < num; i++) {
     nit.nextNode();
     if (retain[i] == false) {
       nit.remove();
     }
   }
   Assert.assertFalse(nit.hasNext());
 }
Beispiel #6
0
 public RDFNode lookup(Resource identity, String sourceValue) {
   if (!_model.contains(identity, Vertere.lookup)) {
     return null;
   }
   Resource lookupResource = _model.getProperty(identity, Vertere.lookup).getResource();
   NodeIterator listObjectsOfProperty =
       _model.listObjectsOfProperty(lookupResource, Vertere.lookup_entry);
   while (listObjectsOfProperty.hasNext()) {
     RDFNode entry = listObjectsOfProperty.next();
     Resource asResource = entry.asResource();
     String key = _model.getProperty(asResource, Vertere.lookup_key).getString();
     if (sourceValue.equals(key)) {
       return _model.getProperty(asResource, Vertere.lookup_value).getObject();
     }
   }
   return null;
 }
Beispiel #7
0
  public Search(
      final java.awt.Frame parent,
      boolean modal,
      final OntClass ontClass,
      final OntProperty ontTarget,
      final JTextField txtField) {
    super(parent, modal);
    initComponents();
    this.parent = (SaveImage) parent;
    this.ontClass = ontClass;
    individuals = new ArrayList<>();
    all_individuals = new ArrayList<>();
    for (NodeIterator i =
            ontClass.listPropertyValues(
                Ontology.getOntModel().getProperty(Ontology.getNameSpace() + "lbl_netbeans"));
        i.hasNext(); ) {
      title_class.setText(i.next().toString());
    }
    this.txtField = txtField;
    model = new InstancesTable();
    tbl_individuals.setModel(model);
    for (ExtendedIterator<? extends OntResource> i = ontClass.listInstances(); i.hasNext(); ) {
      Individual inst = (Individual) i.next();
      if (inst.getNameSpace() != null) {
        individuals.add(inst);
        all_individuals.add(inst);
      }
    }

    tbl_individuals.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              JTable target = (JTable) e.getSource();
              int row = target.getSelectedRow();
              temp = ((SaveImage) parent).getContentFields().get(ontTarget.toString());
              temp.setIndividual(individuals.get(row));
              temp.getField().setText(individuals.get(row).getLocalName());
            }
          }
        });
  }
Beispiel #8
0
 @Override
 public List<Node> getObjects(Node subject, Node predicate) {
   Model graph = null;
   GraphConnection graphConnection = null;
   try {
     graphConnection = openGraph();
     graph = graphConnection.getGraph();
     graph.enterCriticalSection(Lock.READ);
     SimpleSelector selector = getJenaSelector(graph, new StatementImpl(subject, predicate, null));
     NodeIterator it = graph.listObjectsOfProperty(selector.getSubject(), selector.getPredicate());
     List<Node> res = new ArrayList<Node>();
     while (it.hasNext()) {
       res.add(getNXRelationsNode(it.nextNode().asNode()));
     }
     return res;
   } finally {
     if (graph != null) {
       graph.leaveCriticalSection();
     }
     if (graphConnection != null) {
       graphConnection.close();
     }
   }
 }
Beispiel #9
0
  private void ImportRelationsComposition() throws Exception {
    List<ObjectProperty> properties = this.jena.listObjectProperties().toList();

    for (ObjectProperty property : properties) {

      OntClass domain = property.listDomain().next().asClass();
      if (domain.isUnionClass()) domain = domain.asUnionClass().listOperands().toList().get(0);

      OntClass range = property.listRange().next().asClass();
      if (range.isUnionClass()) range = range.asUnionClass().listOperands().toList().get(0);

      Relation r = null;

      if (property.isSymmetricProperty())
        r =
            this.mobi.createSymmetricRelation(
                this.getNameObjectProperty(
                    property.getLocalName(),
                    domain.getLocalName().length(),
                    range.getLocalName().length()));
      else if (property.getInverse() == null)
        r =
            this.mobi.createUnidirecionalCompositionRelationship(
                this.getNameObjectProperty(
                    property.getLocalName(),
                    domain.getLocalName().length(),
                    range.getLocalName().length()));
      else if (property.getInverse() != null)
        r =
            this.mobi.createBidirecionalCompositionRelationship(
                this.getNameObjectProperty(
                    property.getLocalName(),
                    domain.getLocalName().length(),
                    range.getLocalName().length()),
                this.getNameObjectProperty(
                    property.getInverse().getLocalName(),
                    range.getLocalName().length(),
                    domain.getLocalName().length()));

      Class mobiDomain = new Class(domain.getLocalName());
      // this.mobi.getClass(domain.getLocalName());
      Class mobiRange = new Class(range.getLocalName());
      // this.mobi.getClass(range.getLocalName());

      if (mobiDomain != null && mobiRange != null) {
        r.setClassA(mobiDomain);
        r.setClassB(mobiRange);

        List<? extends OntResource> individuals = domain.listInstances().toList();

        for (OntResource resourceIndividual : individuals) {
          Individual individualDomain = resourceIndividual.asIndividual();

          NodeIterator propertyValues =
              this.jena.getIndividual(individualDomain.getURI()).listPropertyValues(property);

          while (propertyValues.hasNext()) {
            RDFNode node = propertyValues.next();
            Individual individualValue = node.as(Individual.class);

            this.mobi.addConcept(mobiDomain);
            this.mobi.addConcept(mobiRange);

            Instance instanceDomain = new Instance(individualDomain.getLocalName());
            Instance instanceRange = new Instance(individualValue.getLocalName());

            try {
              this.mobi.isOneOf(instanceDomain, mobiDomain);
              this.mobi.isOneOf(instanceRange, mobiRange);
            } catch (ExceptionURI e) {
            }

            r.addInstanceRelation(instanceDomain, instanceRange);
          }
        }

        r.processCardinality();

        if (r.getInstanceRelationMapA().size() > 0) this.mobi.addConcept(r);
      }
    }
  }
  @Test
  public void testConversion() throws Exception {
    status.put(DepositField.sourcePath.name(), "src/test/resources/paths/valid-bag");
    status.put(DepositField.fileName.name(), "Test File");
    status.put(
        DepositField.extras.name(), "{\"accessionNumber\" : \"123456\", \"mediaId\" : \"789\"}");

    when(stages.getStagedURI(any(URI.class)))
        .thenAnswer(
            new Answer<URI>() {
              public URI answer(InvocationOnMock invocation) throws URISyntaxException {
                Object[] args = invocation.getArguments();
                URI uri = (URI) args[0];
                String path = uri.toString();
                int index = path.lastIndexOf("/paths");
                path = path.substring(index + 6);

                return new URI("tag:" + path);
              }
            });

    job.run();

    Model model = job.getReadOnlyModel();
    Bag depositBag = model.getBag(job.getDepositPID().getURI());

    assertEquals(depositBag.size(), 1);

    Bag bagFolder = model.getBag((Resource) depositBag.iterator().next());
    assertEquals(
        "Bag folder label was not set",
        "Test File",
        bagFolder.getProperty(dprop(model, label)).getString());
    assertEquals(
        "Content model was not set",
        CONTAINER.toString(),
        bagFolder.getPropertyResourceValue(fprop(model, hasModel)).getURI());

    Resource folder = (Resource) bagFolder.iterator().next();

    assertEquals(
        "Folder label was not set", folder.getProperty(dprop(model, label)).getString(), "test");
    assertEquals(
        "Content model was not set",
        CONTAINER.toString(),
        folder.getPropertyResourceValue(fprop(model, hasModel)).getURI());

    Bag childrenBag = model.getBag(folder.getURI());

    assertEquals(childrenBag.size(), 2);

    // Put children into a map since we can't guarantee order from jena
    Map<String, Resource> children = new HashMap<>(2);
    NodeIterator childIt = childrenBag.iterator();
    while (childIt.hasNext()) {
      Resource file = (Resource) childIt.next();
      children.put(file.getProperty(dprop(model, label)).getString(), file);
    }

    ArgumentCaptor<String> filePathCaptor = ArgumentCaptor.forClass(String.class);
    verify(depositStatusFactory, times(2)).addManifest(anyString(), filePathCaptor.capture());
    List<String> capturedFilePaths =
        Arrays.asList("tag:/valid-bag/bagit.txt", "tag:/valid-bag/manifest-md5.txt");
    assertEquals(capturedFilePaths, filePathCaptor.getAllValues());

    Resource file = children.get("lorem.txt");
    assertEquals(
        "Content model was not set",
        SIMPLE.toString(),
        file.getPropertyResourceValue(fprop(model, hasModel)).getURI());
    assertEquals(
        "Checksum was not set",
        "fa5c89f3c88b81bfd5e821b0316569af",
        file.getProperty(dprop(model, md5sum)).getString());
    assertEquals(
        "File location not set",
        "tag:/valid-bag/data/test/lorem.txt",
        file.getProperty(dprop(model, stagingLocation)).getString());

    Resource file2 = children.get("ipsum.txt");
    assertEquals(
        "Content model was not set",
        SIMPLE.toString(),
        file2.getPropertyResourceValue(fprop(model, hasModel)).getURI());
    assertEquals(
        "Checksum was not set",
        "e78f5438b48b39bcbdea61b73679449d",
        file2.getProperty(dprop(model, md5sum)).getString());
    assertEquals(
        "File location not set",
        "tag:/valid-bag/data/test/ipsum.txt",
        file2.getProperty(dprop(model, stagingLocation)).getString());

    File modsFile =
        new File(job.getDescriptionDir(), new PID(bagFolder.getURI()).getUUID() + ".xml");
    assertTrue(modsFile.exists());

    Set<String> cleanupSet = new HashSet<>();
    StmtIterator it = depositBag.listProperties(dprop(model, cleanupLocation));
    while (it.hasNext()) {
      Statement stmt = it.nextStatement();
      cleanupSet.add(stmt.getString());
    }

    assertEquals("Incorrect number of objects identified for cleanup", 3, cleanupSet.size());
    assertTrue("Cleanup of bag not set", cleanupSet.contains("tag:/valid-bag/"));
    assertTrue("Cleanup of manifest not set", cleanupSet.contains("tag:/valid-bag/bagit.txt"));
    assertTrue(
        "Cleanup of manifest not set", cleanupSet.contains("tag:/valid-bag/manifest-md5.txt"));
  }
Beispiel #11
0
  public void doctorModel(Model report, Model m, Model config) {
    this.input = m;
    this.repair = report;
    this.output = this.input;
    this.config = config;

    ResIterator it = repair.listSubjectsWithProperty(EYE.repairType, EYE.replaceNamespace);
    while (it.hasNext()) {
      /*
       * We are able to make one or more of the following assumptions;
       * (1)	o The Prefix is probably desired                                       \\
       * (3)	o The URI is likely misspelt                                          ===>  Work these with the precedence specified
       * (2)	o The URI is right, but the user mistakenly used a 'reserved' prefix   //
       */
      Resource curr = it.nextResource();
      String prefix =
          repair
              .listObjectsOfProperty(curr, EYE.onPrefix)
              .nextNode()
              .asNode()
              .getLiteralLexicalForm();
      String currUri = output.getNsPrefixURI(prefix);
      String configsUri = getConfigsUriFromPrefix(prefix);
      String configsPre = null;
      if (currUri != null) configsPre = getConfigsPrefixFromUri(currUri);
      if (configsUri != null) // Change the URI to a preferred one
      changeNsUri(currUri, configsUri);
      else if (configsPre != null) // Use that URI, but set the prefix according to config
      changeNsPrefix(prefix, configsPre);
      else // Use the 'expected' URI
      output.setNsPrefix(
            prefix,
            repair
                .listObjectsOfProperty(curr, EYE.expected)
                .nextNode()
                .asNode()
                .getLiteralLexicalForm());
    }

    it = repair.listSubjectsWithProperty(EYE.repairType, EYE.removeDuplicatePrefixes);
    while (it.hasNext()) {
      Resource curr = it.nextResource();
      NodeIterator it2 = repair.listObjectsOfProperty(curr, EYE.onPrefix);
      String uri =
          repair
              .listObjectsOfProperty(curr, EYE.multiplePrefixesForNamespace)
              .nextNode()
              .asNode()
              .getLiteralLexicalForm();
      if (it2.hasNext()) {
        boolean oneKept = false;
        while (it2.hasNext()) {
          RDFNode curra = it2.nextNode();
          if (m.getNsPrefixURI(curra.asNode().getLiteralLexicalForm()) != null)
            if (m.getNsPrefixURI(curra.asNode().getLiteralLexicalForm())
                .equals(uri)) // The prefix is still used in the model
            {
              if (oneKept) m.removeNsPrefix(curra.asNode().getLiteralLexicalForm());
              else oneKept = true;
            }
        }
      }
    }
  }
  /**
   * Get JSON map for a given resource by applying the river settings
   *
   * @param rs resource being processed
   * @param properties properties to be indexed
   * @param model model returned by the indexing query
   * @param getPropLabel if set to true all URI property values will be indexed as their label. The
   *     label is taken as the value of one of the properties set in {@link #uriDescriptionList}.
   * @return map of properties to be indexed for res
   */
  private Map<String, ArrayList<String>> getJsonMap(
      Resource rs, Set<Property> properties, Model model, boolean getPropLabel) {
    Map<String, ArrayList<String>> jsonMap = new HashMap<String, ArrayList<String>>();
    ArrayList<String> results = new ArrayList<String>();

    if (addUriForResource) {
      results.add("\"" + rs.toString() + "\"");
      jsonMap.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#about", results);
    }

    Set<String> rdfLanguages = new HashSet<String>();

    for (Property prop : properties) {
      NodeIterator niter = model.listObjectsOfProperty(rs, prop);
      String property = prop.toString();
      results = new ArrayList<String>();

      String lang;
      String currValue;

      while (niter.hasNext()) {
        RDFNode node = niter.next();
        currValue = getStringForResult(node, getPropLabel);
        if (addLanguage) {
          if (node.isLiteral()) {
            lang = node.asLiteral().getLanguage();
            if (!lang.isEmpty()) {
              rdfLanguages.add("\"" + lang + "\"");
            }
          }
        }

        String shortValue = currValue;

        int currLen = currValue.length();
        // Unquote string
        if (currLen > 1) shortValue = currValue.substring(1, currLen - 1);

        // If either whiteMap does contains shortValue
        // or blackMap contains the value
        // skip adding it to the index
        boolean whiteMapCond =
            whiteMap.containsKey(property) && !whiteMap.get(property).contains(shortValue);
        boolean blackMapCond =
            blackMap.containsKey(property) && blackMap.get(property).contains(shortValue);

        if (whiteMapCond || blackMapCond) {
          continue;
        }

        if (normalizeObj.containsKey(shortValue)) {
          results.add("\"" + normalizeObj.get(shortValue) + "\"");
        } else {
          results.add(currValue);
        }
      }

      // Do not index empty properties
      if (results.isEmpty()) continue;

      if (normalizeProp.containsKey(property)) {
        property = normalizeProp.get(property);
        if (jsonMap.containsKey(property)) {
          jsonMap.get(property).addAll(results);
        } else {
          jsonMap.put(property, results);
        }
      } else {
        jsonMap.put(property, results);
      }
    }

    if (addLanguage) {
      if (rdfLanguages.isEmpty() && !language.isEmpty()) rdfLanguages.add(language);
      if (!rdfLanguages.isEmpty()) jsonMap.put("language", new ArrayList<String>(rdfLanguages));
    }

    for (Map.Entry<String, String> it : normalizeMissing.entrySet()) {
      if (!jsonMap.containsKey(it.getKey())) {
        ArrayList<String> res = new ArrayList<String>();
        res.add("\"" + it.getValue() + "\"");
        jsonMap.put(it.getKey(), res);
      }
    }

    return jsonMap;
  }