Example #1
0
 @Override
 public List<Node> getSubjects(Node predicate, Node object) {
   Model graph = null;
   GraphConnection graphConnection = null;
   try {
     graphConnection = openGraph();
     graph = graphConnection.getGraph();
     graph.enterCriticalSection(Lock.READ);
     SimpleSelector selector = getJenaSelector(graph, new StatementImpl(null, predicate, object));
     ResIterator it =
         graph.listSubjectsWithProperty(selector.getPredicate(), selector.getObject());
     List<Node> res = new ArrayList<Node>();
     while (it.hasNext()) {
       res.add(getNXRelationsNode(it.nextResource().asNode()));
     }
     return res;
   } finally {
     if (graph != null) {
       graph.leaveCriticalSection();
     }
     if (graphConnection != null) {
       graphConnection.close();
     }
   }
 }
 static Set<Resource> subjects(Model model, Property p, RDFNode r) {
   Set<Resource> subjects = new HashSet<>();
   ResIterator it = model.listSubjectsWithProperty(p, r);
   while (it.hasNext()) subjects.add(it.next().asResource());
   it.close();
   return subjects;
 }
Example #3
0
 private String getConfigsUriFromPrefix(String pre) {
   ResIterator subjects = config.listSubjectsWithProperty(EYE.prefix, config.createLiteral(pre));
   if (subjects.hasNext()) {
     StmtIterator uris = config.listStatements(subjects.nextResource(), EYE.nsURI, (RDFNode) null);
     if (uris.hasNext()) return uris.nextStatement().getObject().asNode().getLiteralLexicalForm();
   }
   return null; // Return null otherwise
 }
  public static void main(String[] args) {
    Store store = HBaseRdfFactory.connectStore("Store/hbaserdf-simple.ttl");
    store.getTableFormatter().format();

    Model model = HBaseRdfFactory.connectDefaultModel(store);

    model.add(
        model.createResource("http://example.org/person#John"),
        VCARD.FN,
        model.asRDFNode(Node.createLiteral("John Smith")));
    model.add(
        model.createResource("http://example.org/person#John"),
        VCARD.EMAIL,
        model.asRDFNode(Node.createLiteral("*****@*****.**")));
    model.add(
        model.createResource("http://example.org/person#Jim"),
        VCARD.FN,
        model.asRDFNode(Node.createLiteral("Jim Mason")));
    model.add(
        model.createResource("http://example.org/person#Jim"),
        VCARD.EMAIL,
        model.asRDFNode(Node.createLiteral("*****@*****.**")));
    model.add(
        model.createResource("http://example.org/person#Bob"),
        VCARD.FN,
        model.asRDFNode(Node.createLiteral("Bob Brown")));
    model.add(
        model.createResource("http://example.org/person#Bob"),
        VCARD.EMAIL,
        model.asRDFNode(Node.createLiteral("*****@*****.**")));

    StmtIterator iter = model.listStatements();
    while (iter.hasNext()) {
      System.out.println(iter.next().toString());
    }

    iter = model.getResource("http://example.org/person#John").listProperties();
    while (iter.hasNext()) {
      System.out.println(iter.next().toString());
    }

    ResIterator resIter = model.listSubjects();
    while (resIter.hasNext()) {
      System.out.println(resIter.next().toString());
    }

    String query =
        " PREFIX vcard: <http://www.w3.org/2001/vcard-rdf/3.0#> "
            + " SELECT ?x "
            + " WHERE "
            + " { "
            + " 		<http://example.org/person#John> vcard:FN ?x "
            + " } ";

    QueryExecution qe = QueryExecutionFactory.create(query, model);
    ResultSet rs = qe.execSelect();
    ResultSetFormatter.out(rs);
  }
  /**
   * Index all the resources in a Jena Model to ES
   *
   * @param model the model to index
   * @param bulkRequest a BulkRequestBuilder
   * @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}.
   */
  private void addModelToES(Model model, BulkRequestBuilder bulkRequest, boolean getPropLabel) {
    long startTime = System.currentTimeMillis();
    long bulkLength = 0;
    HashSet<Property> properties = new HashSet<Property>();

    StmtIterator it = model.listStatements();
    while (it.hasNext()) {
      Statement st = it.nextStatement();
      Property prop = st.getPredicate();
      String property = prop.toString();

      if (rdfPropList.isEmpty()
          || (isWhitePropList && rdfPropList.contains(property))
          || (!isWhitePropList && !rdfPropList.contains(property))
          || (normalizeProp.containsKey(property))) {
        properties.add(prop);
      }
    }

    ResIterator resIt = model.listSubjects();

    while (resIt.hasNext()) {
      Resource rs = resIt.nextResource();
      Map<String, ArrayList<String>> jsonMap = getJsonMap(rs, properties, model, getPropLabel);

      bulkRequest.add(
          client.prepareIndex(indexName, typeName, rs.toString()).setSource(mapToString(jsonMap)));
      bulkLength++;

      // We want to execute the bulk for every  DEFAULT_BULK_SIZE requests
      if (bulkLength % EEASettings.DEFAULT_BULK_SIZE == 0) {
        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        // After executing, flush the BulkRequestBuilder.
        bulkRequest = client.prepareBulk();

        if (bulkResponse.hasFailures()) {
          processBulkResponseFailure(bulkResponse);
        }
      }
    }

    // Execute remaining requests
    if (bulkRequest.numberOfActions() > 0) {
      BulkResponse response = bulkRequest.execute().actionGet();
      // Handle failure by iterating through each bulk response item
      if (response.hasFailures()) {
        processBulkResponseFailure(response);
      }
    }

    // Show time taken to index the documents
    logger.info(
        "Indexed {} documents on {}/{} in {} seconds",
        bulkLength,
        indexName,
        typeName,
        (System.currentTimeMillis() - startTime) / 1000.0);
  }
Example #6
0
 @Override
 protected List<Resource> getModelTargetConnections() {
   final Resource property = getResource();
   final List<Resource> list = new ArrayList<Resource>();
   final ResIterator iterator =
       property.getModel().listSubjectsWithProperty(Schema.destination, property);
   while (iterator.hasNext()) {
     list.add(iterator.nextResource());
   }
   return list;
 }
Example #7
0
  @Override
  public List<Entity> getEntities(String text) {
    List<Entity> list = new ArrayList<>();
    try {
      String foxJSONOutput = doTASK(text);

      JSONParser parser = new JSONParser();
      JSONArray jsonArray = (JSONArray) parser.parse(foxJSONOutput);
      String output =
          URLDecoder.decode((String) ((JSONObject) jsonArray.get(0)).get("output"), "UTF-8");

      String baseURI = "http://dbpedia.org";
      Model model = ModelFactory.createDefaultModel();
      RDFReader r = model.getReader("N3");
      r.read(model, new StringReader(output), baseURI);

      ResIterator iter = model.listSubjects();
      while (iter.hasNext()) {
        Resource next = iter.next();
        StmtIterator statementIter = next.listProperties();
        Entity ent = new Entity();
        while (statementIter.hasNext()) {
          Statement statement = statementIter.next();
          String predicateURI = statement.getPredicate().getURI();
          if (predicateURI.equals("http://www.w3.org/2000/10/annotation-ns#body")) {
            ent.label = statement.getObject().asLiteral().getString();
          } else if (predicateURI.equals("http://ns.aksw.org/scms/means")) {
            String uri = statement.getObject().asResource().getURI();
            String encode = uri.replaceAll(",", "%2C");
            ent.URI = encode;
          } else if (predicateURI.equals("http://ns.aksw.org/scms/beginIndex")) {
            ent.start = statement.getObject().asLiteral().getInt();
          } else if (predicateURI.equals("http://ns.aksw.org/scms/endIndex")) {
            ent.end = statement.getObject().asLiteral().getInt();
          }
        }
        list.add(ent);
      }

    } catch (IOException | ParseException e) {
      log.error("Could not call FOX for NER/NED", e);
    }
    return list;
  }
  public static void main(String[] args) {
    Model adapterModel =
        OntologyModelUtil.loadModel("ontologies/docker.ttl", IMessageBus.SERIALIZATION_TURTLE);

    Property propCommand =
        adapterModel.getProperty(adapterModel.getNsPrefixURI("docker"), "command");

    Model m = OntologyModelUtil.loadModel("test.ttl", IMessageBus.SERIALIZATION_TURTLE);

    ResIterator rs = m.listResourcesWithProperty(propCommand);
    while (rs.hasNext()) {
      Resource r = rs.next();
      Statement c = r.getProperty(propCommand);

      Resource listHead = c.getObject().asResource();
      LinkedList<String> output = new LinkedList<String>();
      extractList(output, listHead);

      for (String elem : output) {
        System.out.println("elem: " + elem);
      }
    }
  }
  public ArrayList<String> getOrganizations() {
    long startTime = System.currentTimeMillis();

    ArrayList<String> organizations = new ArrayList<String>();

    Resource organization = ontModel.getResource(ORGANIZATION_CLASS);

    ResIterator iter = ontModel.listSubjectsWithProperty(RDF.type, organization);

    if (iter.hasNext()) {
      LOGGER.info("Organizations were found in the database");
      LOGGER.debug("The database contains these organizations:");
      while (iter.hasNext()) {
        Resource organizationResource = iter.nextResource();
        String organizationUri = organizationResource.getURI();
        LOGGER.debug(organizationUri);
        //		        String organizationId =
        // organizationResource.getProperty(ontModel.getProperty(ORGID)).getString();
        //		        System.out.println("  " + organizationId);
        organizations.add(organizationUri);
        // System.out.println("   -" +
        // iter.nextResource().getProperty(ontModel.getProperty("http://www.smartdeveloperhub.org/vocabulary/organization#id")).getString());
        // System.out.println("   -" +
        // iter.nextResource().getProperty(ontModel.getProperty("http://www.w3.org/ns/org#classification")).getResource().getURI());
      }
    } else {
      LOGGER.info("No organizations were found in the database");
    }

    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    // System.out.println("Load organizations, elapsed time (ms):"+elapsedTime);
    LOGGER.debug("- Load organizations, elapsed time (ms)..: {}", elapsedTime);

    return organizations;
  }
 private void processPermanentURIRequest(VitroRequest vreq, ModelMaker maker) {
   String modelName = vreq.getParameter("modelName");
   String oldModel = vreq.getParameter("oldModel");
   String newModel = vreq.getParameter("newModel");
   String oldNamespace = vreq.getParameter("oldNamespace");
   String newNamespace = vreq.getParameter("newNamespace");
   String dNamespace = vreq.getParameter("defaultNamespace");
   newNamespace = (newNamespace == null || newNamespace.isEmpty()) ? oldNamespace : newNamespace;
   newNamespace = (dNamespace != null) ? dNamespace : newNamespace;
   if (modelName != null) {
     Model m = maker.getModel(modelName);
     List<String> namespaceList = new ArrayList<>();
     ResIterator resItr = m.listResourcesWithProperty((Property) null);
     if (resItr != null) {
       while (resItr.hasNext()) {
         String namespace = resItr.nextResource().getNameSpace();
         if (!namespaceList.contains(namespace)) {
           namespaceList.add(namespace);
         }
       }
     } else {
       namespaceList.add("no resources present");
     }
     String defaultNamespace = vreq.getUnfilteredWebappDaoFactory().getDefaultNamespace();
     vreq.setAttribute("modelName", modelName);
     vreq.setAttribute("defaultNamespace", defaultNamespace);
     vreq.setAttribute("namespaceList", namespaceList);
     vreq.setAttribute("title", "Permanent URI");
     vreq.setAttribute("bodyJsp", PERMANENT_URI);
   } else if (oldModel != null) {
     JenaIngestUtils utils = new JenaIngestUtils();
     utils.doPermanentURI(oldModel, newModel, oldNamespace, newNamespace, maker, vreq);
     vreq.setAttribute("title", "Ingest Menu");
     vreq.setAttribute("bodyJsp", INGEST_MENU_JSP);
   }
 }
  public Collection<PropertyInstance> getAllPropInstByVClasses(List<VClass> vclasses) {

    List<PropertyInstance> propInsts = new ArrayList<PropertyInstance>();

    if (vclasses == null || vclasses.isEmpty()) {
      return propInsts;
    }

    Collections.sort(
        vclasses, new VClassHierarchyRanker(this.getWebappDaoFactory().getVClassDao()));

    OntModel ontModel = getOntModelSelector().getTBoxModel();

    try {

      ontModel.enterCriticalSection(Lock.READ);

      // map object property URI to an array of two resources:
      // the first is the "allValuesFrom" resource and the second is
      // "someValuesFrom"
      Map<String, Resource[]> applicableProperties = new HashMap<String, Resource[]>();

      try {
        for (VClass vclass : vclasses) {
          if (vclass.isAnonymous()) {
            continue;
          }
          String VClassURI = vclass.getURI();

          OntClass ontClass = getOntClass(ontModel, VClassURI);
          if (ontClass != null) {
            List<OntClass> relatedClasses = new ArrayList<OntClass>();
            relatedClasses.addAll(ontClass.listEquivalentClasses().toList());
            relatedClasses.addAll(ontClass.listSuperClasses().toList());
            for (OntClass relatedClass : relatedClasses) {
              // find properties in restrictions
              if (relatedClass.isRestriction()) {
                // TODO: check if restriction is something like
                // maxCardinality 0 or allValuesFrom owl:Nothing,
                // in which case the property is NOT applicable!
                Restriction rest = (Restriction) relatedClass.as(Restriction.class);
                OntProperty onProperty = rest.getOnProperty();
                if (onProperty != null && onProperty.canAs(ObjectProperty.class)) {
                  Resource[] ranges = new Resource[2];
                  if (rest.isAllValuesFromRestriction()) {
                    ranges[0] = (rest.asAllValuesFromRestriction()).getAllValuesFrom();
                  } else if (rest.isSomeValuesFromRestriction()) {
                    ranges[1] = (rest.asSomeValuesFromRestriction()).getSomeValuesFrom();
                  }
                  updatePropertyRangeMap(applicableProperties, onProperty.getURI(), ranges);
                }
              }
            }

            // find properties with class in domain
            ResIterator pit = ontModel.listSubjectsWithProperty(RDFS.domain, ontClass);
            while (pit.hasNext()) {
              Resource prop = pit.nextResource();
              if (prop.getNameSpace() != null
                  && !NONUSER_NAMESPACES.contains(prop.getNameSpace())) {
                StmtIterator rangeSit = prop.listProperties(RDFS.range);
                Resource rangeRes = null;
                while (rangeSit.hasNext()) {
                  Statement s = rangeSit.nextStatement();
                  if (s.getObject().isURIResource()) {
                    rangeRes = (Resource) s.getObject();
                  }
                }
                Resource[] ranges = new Resource[2];
                ranges[0] = rangeRes;
                updatePropertyRangeMap(applicableProperties, prop.getURI(), ranges);
              }
            }
          }
        }
      } catch (Exception e) {
        log.error(
            "Unable to get applicable properties "
                + "by examining property restrictions and domains",
            e);
      }

      // make the PropertyInstance objects
      for (String propertyURI : applicableProperties.keySet()) {
        ObjectProperty op = ontModel.getObjectProperty(propertyURI);
        if (op == null) {
          continue;
        }
        String domainURIStr = getURIStr(op.getDomain());
        Resource[] foundRanges = applicableProperties.get(propertyURI);
        Resource rangeRes =
            (foundRanges[0] != null)
                ? foundRanges[0]
                : (op.getRange() == null && foundRanges[1] != null)
                    ? foundRanges[1]
                    : op.getRange();
        PropertyInstance pi = new PropertyInstance();
        if (rangeRes != null) {
          String rangeClassURI;
          if (rangeRes.isAnon()) {
            rangeClassURI = PSEUDO_BNODE_NS + rangeRes.getId().toString();
          } else {
            rangeClassURI = (String) rangeRes.getURI();
          }
          pi.setRangeClassURI(rangeClassURI);
          try {
            pi.setRangeClassName(
                getWebappDaoFactory().getVClassDao().getVClassByURI(rangeClassURI).getName());
            // pi.setRangeClassName(getLabel(getOntModel().getOntResource(rangeClassURI)));
          } catch (NullPointerException e) {
            /* probably a union or intersection - need to handle this somehow */
          }
        } else {
          pi.setRangeClassURI(OWL.Thing.getURI()); // TODO see above
        }
        pi.setDomainClassURI(domainURIStr);
        try {
          pi.setDomainClassName(
              getWebappDaoFactory().getVClassDao().getVClassByURI(domainURIStr).getName());
          // pi.setDomainClassName(getLabel(getOntModel().getOntResource(op.getDomain().getURI())));
        } catch (NullPointerException e) {
          /* probably a union or intersection - need to handle this somehow */
        }
        pi.setSubjectSide(true);
        pi.setPropertyURI(op.getURI());
        pi.setPropertyName(getLabelOrId(op)); // TODO
        pi.setRangePublic(getLabelOrId(op));
        pi.setDomainPublic(getLabelOrId(op));
        propInsts.add(pi);
      }
    } finally {
      ontModel.leaveCriticalSection();
    }

    Collections.sort(propInsts, new PropInstSorter());
    return propInsts;
  }
Example #12
0
  @Test
  @Ignore
  // fixme: this test is slow!
  public void manifestRoundtrip()
      throws JAXBException, InvalidModelException, IOException, XMLStreamException,
          MissingRspecElementException, DeprecatedRspecVersionException,
          InvalidRspecValueException {

    final String filename = "/geni/manifest/manifest_paper2015.xml";
    final InputStream inputRspec = ManifestConverterTest.class.getResourceAsStream(filename);
    System.out.println("Converting this input from '" + filename + "':");
    System.out.println("===============================");
    System.out.println(AbstractConverter.toString(filename));
    System.out.println("===============================");

    final Model model = ManifestConverter.getModel(inputRspec);
    final ResIterator topology = model.listResourcesWithProperty(RDF.type, Omn_lifecycle.Manifest);
    System.out.println("Generated this graph:");
    System.out.println("===============================");
    System.out.println(Parser.toString(model));
    System.out.println("===============================");
    Assert.assertTrue("should have a topology", topology.hasNext());

    final InfModel infModel = new Parser(model).getInfModel();
    final String outputRspec = ManifestConverter.getRSpec(infModel, "testbed.example.org");
    System.out.println("Generated this rspec:");
    System.out.println("===============================");
    System.out.println(outputRspec);
    System.out.println("===============================");

    System.out.println("===============================");
    String inputRSpec = AbstractConverter.toString(filename);
    System.out.println(inputRSpec);

    System.out.println("Diffs:");
    int[] diffsNodes = RSpecValidation.getDiffsNodes(inputRSpec);

    Assert.assertTrue("type", outputRspec.contains("type=\"manifest\""));
    Assert.assertTrue("client id", outputRspec.contains("client_id=\"myMotor\""));

    Document xmlDoc = RSpecValidation.loadXMLFromString(outputRspec);

    // check that output has one rspec element
    NodeList rspec =
        xmlDoc.getElementsByTagNameNS("http://www.geni.net/resources/rspec/3", "rspec");
    Assert.assertTrue(rspec.getLength() == 1);

    NodeList nodes = xmlDoc.getElementsByTagNameNS("http://www.geni.net/resources/rspec/3", "node");
    Assert.assertTrue(nodes.getLength() == 1);

    NodeList sliverType =
        xmlDoc.getElementsByTagNameNS("http://www.geni.net/resources/rspec/3", "sliver_type");
    Assert.assertTrue(sliverType.getLength() == 1);

    String sliverName = sliverType.item(0).getAttributes().getNamedItem("name").getNodeValue();
    Assert.assertTrue(
        sliverName.equals("http://open-multinet.info/ontology/resources/motor#Motor"));

    // TODO: This test does not consistently return 0, only sometimes. Need
    // to debug.
    // Assert.assertTrue("No differences between input and output files",
    // diffsNodes[0] == 0);

  }
  @Test
  public void manifestRoundtrip()
      throws JAXBException, InvalidModelException, IOException, XMLStreamException,
          MissingRspecElementException, DeprecatedRspecVersionException {
    final String filename = "/geni/gimiv3/4nodes.manifest";
    final InputStream inputRspec = FourNodesTest.class.getResourceAsStream(filename);
    System.out.println("Converting this input from '" + filename + "':");
    System.out.println("===============================");
    System.out.println(AbstractConverter.toString(filename));
    System.out.println("===============================");

    final Model model = ManifestConverter.getModel(inputRspec);
    final ResIterator topology = model.listResourcesWithProperty(RDF.type, Omn_lifecycle.Manifest);
    System.out.println("Generated this graph:");
    System.out.println("===============================");
    System.out.println(Parser.toString(model));
    System.out.println("===============================");
    Assert.assertTrue("should have a topology", topology.hasNext());

    final InfModel infModel = new Parser(model).getInfModel();
    final String outputRspec = ManifestConverter.getRSpec(infModel, "instageni.gpolab.bbn.com");
    System.out.println("Generated this rspec:");
    System.out.println("===============================");
    System.out.println(outputRspec);
    System.out.println("===============================");

    Assert.assertTrue("type", outputRspec.contains("type=\"manifest\""));
    Assert.assertTrue(
        "sliver_id",
        outputRspec.contains(
            "sliver_id=\"urn:publicid:IDN+exogeni.net:rcivmsite+sliver+bd6b53fd-9185-4cd5-99cb-f9b8736010b2:0\""));
    Assert.assertTrue("exclusive", outputRspec.contains("exclusive=\"false\""));

    // TODO fix this for manifest converter
    // Assert.assertTrue("component_name",
    // outputRspec.contains("component_name=\"orca-vm-cloud\""));
    Assert.assertTrue(
        "component_manager_id",
        outputRspec.contains(
            "component_manager_id=\"urn:publicid:IDN+exogeni.net:rcivmsite+authority+am\""));
    Assert.assertTrue(
        "component_id",
        outputRspec.contains(
            "component_id=\"urn:publicid:IDN+exogeni.net:rcivmsite+node+orca-vm-cloud\""));
    Assert.assertTrue("client_id", outputRspec.contains("client_id=\"0\""));
    Assert.assertTrue("latitude", outputRspec.contains("latitude=\"35.939518\""));
    Assert.assertTrue("longitude", outputRspec.contains("longitude=\"-79.017426\""));
    Assert.assertTrue("country", outputRspec.contains("country=\"Unspecified\""));
    Assert.assertTrue("sliver_type", outputRspec.contains("sliver_type"));

    // TODO fix this for manifest converter
    // Assert.assertTrue("sliver_type name",
    // outputRspec.contains("name=\"xo.small\""));
    Assert.assertTrue("disk image", outputRspec.contains("disk_image"));
    Assert.assertTrue(
        "disk image version",
        outputRspec.contains("version=\"807c4570e46413cba1faf3a25fdfff8361489c69\""));
    Assert.assertTrue(
        "disk image name",
        outputRspec.contains("name=\"http://pkg.mytestbed.net/geni/deb7-64-p2p.xml\""));
    Assert.assertTrue("login", outputRspec.contains("login"));
    Assert.assertTrue("login username", outputRspec.contains("username=\"root\""));
    Assert.assertTrue("login hostname", outputRspec.contains("hostname=\"152.54.14.17\""));
    Assert.assertTrue("login authentication", outputRspec.contains("authentication=\"ssh-keys\""));
    Assert.assertTrue(
        "services_post_boot_script", outputRspec.contains("services_post_boot_script"));
    Assert.assertTrue("services_post_boot_script type", outputRspec.contains("type=\"velocity\""));
    Assert.assertTrue("services_post_boot_script text", outputRspec.contains("#!/bin/bash"));
    Assert.assertTrue("ip address", outputRspec.contains("address=\"192.168.1.1\""));
    Assert.assertTrue("ip netmask", outputRspec.contains("netmask=\"255.255.255.0\""));
    Assert.assertTrue("ip type", outputRspec.contains("type=\"ipv4\""));
    Assert.assertTrue("geni_sliver_info", outputRspec.contains("geni_sliver_info"));
    Assert.assertTrue(
        "geni_sliver_info resource_id",
        outputRspec.contains("resource_id=\"rci-w7:bdd5b251-4a63-4bd4-b77c-cad57974602d\""));
    //		Assert.assertTrue("geni_sliver_info state",
    //				outputRspec.contains("state=\"ready\""));
    Assert.assertTrue(
        "geni_sliver_info start_time",
        outputRspec.contains("start_time=\"2013-12-03T00:57:47.000Z\""));
    Assert.assertTrue(
        "geni_sliver_info expiration_time",
        outputRspec.contains("expiration_time=\"2013-12-10T00:55:03.000Z\""));
    Assert.assertTrue(
        "geni_sliver_info creation_time",
        outputRspec.contains("creation_time=\"2013-12-03T00:57:47.000Z\""));
    Assert.assertTrue(
        "geni_sliver_info creator_urn",
        outputRspec.contains(
            "creator_urn=\"[email protected], urn:publicid:IDN+ch.geni.net+user+johren\""));

    Assert.assertTrue("link", outputRspec.contains("link"));
    Assert.assertTrue(
        "link sliver_id",
        outputRspec.contains(
            "sliver_id=\"urn:publicid:IDN+exogeni.net:rcivmsite+sliver+bd6b53fd-9185-4cd5-99cb-f9b8736010b2:link0\""));
    Assert.assertTrue("link client_id", outputRspec.contains("client_id=\"link0\""));
    Assert.assertTrue("link vlantag", outputRspec.contains("vlantag=\"2200\""));
    Assert.assertTrue("interface_ref", outputRspec.contains("interface_ref"));
    Assert.assertTrue("interface_ref client_id", outputRspec.contains("client_id=\"3:if0\""));

    Assert.assertTrue("geni_slice_info", outputRspec.contains("geni_slice_info"));
    Assert.assertTrue(
        "geni_slice_info uuid",
        outputRspec.contains("uuid=\"5fcc5c81-c686-4e02-89bb-8dd7162697d3\""));
    Assert.assertTrue(
        "geni_slice_info urn",
        outputRspec.contains("urn=\"urn:publicid:IDN+ch.geni.net:GIMITesting+slice+joOEDLTut\""));

    System.out.println("===============================");
    String inputRSpec = AbstractConverter.toString(filename);
    System.out.println(inputRSpec);
    System.out.println("Diffs:");
    int[] diffsNodes = RSpecValidation.getDiffsNodes(inputRSpec);

    // TODO: This test does not consistently return 0, only sometimes. Need
    // to debug.
    // Assert.assertTrue("No differences between input and output files",
    // diffsNodes[0] == 0);

  }
Example #14
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;
            }
        }
      }
    }
  }