Esempio n. 1
0
  public static Offering addServiceFeatures(Resource service, Offering offering) {
    ArrayList<QualitativeFeature> qualFeatures = offering.getQualitativeFeatures();
    ArrayList<QuantitativeFeature> quantFeatures = offering.getQuantitativeFeatures();

    /*//adding the offering provider
    if(service.hasProperty(hasProvider)){
    	Resource provider = service.getPropertyResourceValue(hasProvider);
    	if(provider.hasProperty(page))
    		offering.setURL(provider.getProperty(page).getString());
    }*/

    // get qualitativeFeatures
    StmtIterator iter = service.listProperties(qualitativeProductOrServiceProperty);
    // System.out.println(iter.toList().size());
    while (iter.hasNext()) {
      Resource feature = iter.next().getObject().asResource();
      qualFeatures.addAll(convertQualitativeFeatures(feature));
    }
    // get quantitative
    StmtIterator iter2 = service.listProperties(quantitativeProductOrServiceProperty);
    // System.out.println(iter.toList().size());
    while (iter2.hasNext()) {
      Resource feature = iter2.next().getObject().asResource();
      quantFeatures.addAll(convertQuantitativeFeatures(feature));
    }

    return offering;
  }
Esempio n. 2
0
  @Test
  public void testUpdate() throws Exception {
    Resource rhmRes = model.getResource(FakeRDFModel.rhm);
    Property name = model.getProperty(foaf + "name");

    Statement nameSt = rhmRes.listProperties(name).nextStatement();
    String originalName = nameSt.getLiteral().getString();

    // assume update is always first remove and then add
    model.remove(nameSt);
    model.add(rhmRes, name, "TESTNAME");

    assert changes.size() == 2;
    assert rhmRes.listProperties(name).toList().size() == 1;
    assert rhmRes.listProperties(name).nextStatement().getLiteral().getString().equals("TESTNAME");

    changes.undo();

    assert changes.size() == 2;
    assert rhmRes.listProperties(name).toList().size() == 1;
    assert rhmRes
        .listProperties(name)
        .nextStatement()
        .getLiteral()
        .getString()
        .equals(originalName);

    changes.redo();

    assert changes.size() == 2;
    assert rhmRes.listProperties(name).toList().size() == 1;
    assert rhmRes.listProperties(name).nextStatement().getLiteral().getString().equals("TESTNAME");
  }
  public List<ReMSerialisation> getReMSerialisations() throws OREException {
    try {
      List<ReMSerialisation> serialisations = new ArrayList<ReMSerialisation>();
      StmtIterator itr = res.listProperties(ORE.isDescribedBy);
      while (itr.hasNext()) {
        Statement statement = itr.nextStatement();
        Resource resource = (Resource) statement.getObject();
        StmtIterator itr2 = resource.listProperties(DC.format);
        StmtIterator itr3 = resource.listProperties(OREX.isAuthoritativeFor);
        String mime = "application/octet-stream";
        if (itr2.hasNext()) {
          Statement stmt = itr2.nextStatement();
          mime = ((Literal) stmt.getObject()).getLexicalForm();
        }
        boolean authoritative = false;
        if (itr3.hasNext()) {
          authoritative = true;
        }
        ReMSerialisation serialisation = new ReMSerialisation(mime, new URI(resource.getURI()));
        serialisation.setAuthoritative(authoritative);

        serialisations.add(serialisation);
      }
      return serialisations;
    } catch (URISyntaxException e) {
      throw new OREException(e);
    }
  }
Esempio n. 4
0
  public static Offering convertOffering(Resource resource, Float price) {
    Offering offering = new Offering();

    offering.setId(resource.getLocalName());
    if (resource.hasProperty(label)) {
      offering.setName(resource.getProperty(label).getString());
    } else {
      offering.setName(resource.getLocalName());
    }

    if (resource.hasProperty(comment)) {
      offering.setDescription(resource.getProperty(comment).getString());
    }

    // get included services
    StmtIterator iter = resource.listProperties(includes);
    // System.out.println(iter.toList().size());
    while (iter.hasNext()) {
      Resource service = iter.next().getResource();
      offering = addFeatures(service, offering);
    }

    // get offering price
    offering = getOfferingPrice(price, offering);

    return offering;
  }
Esempio n. 5
0
 @Override
 public void processInput(Resource input, Resource output) {
   final Model model = ModelFactory.createDefaultModel();
   final List<Statement> tipURIs = input.listProperties(Vocab.has).toList();
   final SublistIterator<Statement> tipsIterator =
       new SublistIterator<Statement>(tipURIs, QUERY_CHUNK_SIZE);
   while (tipsIterator.hasNext()) {
     final List<String> ancestorQueryBlocks = new ArrayList<String>();
     final List<String> parentQueryBlocks = new ArrayList<String>();
     final List<Statement> tips = tipsIterator.next();
     for (Statement statement : tips) {
       final String tipURI =
           statement.getResource().getProperty(DC.subject).getResource().getURI();
       ancestorQueryBlocks.add(String.format(ancestorQueryBody, tipURI));
       parentQueryBlocks.add(String.format(parentQueryBody, tipURI));
     }
     final String ancestorQuery =
         String.format(ancestorQueryHead, StringUtils.join(ancestorQueryBlocks, " UNION "));
     final String parentQuery =
         String.format(parentQueryHead, StringUtils.join(parentQueryBlocks, ", "));
     QueryEngineHTTP ancestorQE = new QueryEngineHTTP(endpoint, ancestorQuery);
     QueryEngineHTTP parentQE = new QueryEngineHTTP(endpoint, parentQuery);
     ancestorQE.execConstruct(model);
     ancestorQE.close();
     parentQE.execConstruct(model);
     parentQE.close();
   }
   this.processNode(Vocab.TaxonomyRoot, model, output.getModel(), null, output);
   output.getModel().setNsPrefix("cdao", "http://www.evolutionaryontology.org/cdao/1.0/cdao.owl#");
 }
Esempio n. 6
0
  private static boolean hasPermission(
      String userPrefix, String username, String uri, Property[] permissions) {
    Set<Property> permissionSet = new HashSet<Property>();
    Resource resource = configModel.createResource(uri);
    Resource user;

    if (username == null) user = PERM.Public;
    else user = configModel.createResource(userPrefix + username);

    for (Property permission : permissions) {
      if (configModel.contains(user, permission, resource)) return true;
      permissionSet.add(permission);
    }

    StmtIterator stmts = user.listProperties();
    while (stmts.hasNext()) {
      Statement stmt = stmts.next();
      if (!permissionSet.contains(stmt.getPredicate())) continue;
      RDFNode resourceMatch = stmt.getObject();
      if (!(resourceMatch.isResource()
          && configModel.contains((Resource) resourceMatch, RDF.type, PERM.ResourceMatch)))
        continue;

      RDFNode matchRegex = ((Resource) resourceMatch).getProperty(PERM.matchExpression).getObject();
      if (matchRegex == null || !matchRegex.isLiteral()) continue;

      try {
        if (uri.matches(((Literal) matchRegex).getString())) return true;
      } catch (PatternSyntaxException e) {
      }
    }

    if (username != null) return hasPermission(userPrefix, null, uri, permissions);
    else return false;
  }
Esempio n. 7
0
  /**
   * Returns reflection of the given resource <code>r</code> into given domain <code>mDomain</code>.
   *
   * @param uri uri of the resource to be reflected
   * @param mDB is model, which contains statements about resource <code>uri</code>
   * @param mDomain domain model describing classes
   * @return <
   *     <UL>
   *       <LI><code>uri</code> if resource with this <code>uri</code> , i.e. this resource occurs
   *           as a subject of a any statement in <code>mDomain</code>.
   *       <LI>URI of <code>C</code>, if resource with this <code>uri</code> does NOT belong do
   *           <code>mDomain</code> and instance of resource (class) C, belonging do <code>mDomain
   *           </code>.
   *       <LI><code>null</code> -- otherwise.
   *     </UL>
   */
  public static Resource getReflection(Resource r, OntModel mDB, OntModel mDomain) {
    // TODO The idea of reflexion becomes illogical when the individual as
    // an instance of more then one type (class).

    if (mDomain.containsResource(r))
      // Associate resource with mDomain
      return (Resource) r.inModel(mDomain);

    // Check whether ontr is instance (individual) of some class...
    // Associate it for the test with mDB model
    r = (Resource) r.inModel(mDB);
    for (StmtIterator it = r.listProperties(RDF.type); it.hasNext(); ) {
      Resource clazz = it.nextStatement().getResource();
      // ...and this class belongs to domain ontology
      if (mDomain.containsResource(clazz)) {
        // Since clazz is object of rdf:type predicate, than it is
        // rdfs:Resource.
        // Associate it with mDomain.
        return (Resource) clazz.inModel(mDomain);
      }
    }

    // The value is undefined
    return null;
  }
  // add collection elements
  private void processDomainVmElements(Resource vm, OntModel om, OrcaNode parent) {

    // HACK - if we added real interfaces to inner nodes, we don't need link to parent
    boolean innerNodeConnected = false;

    for (StmtIterator vmEl = vm.listProperties(NdlCommons.collectionElementProperty);
        vmEl.hasNext(); ) {
      Resource tmpR = vmEl.next().getResource();
      OrcaNode on = new OrcaNode(getTrueName(tmpR), parent, true);
      nodes.put(getTrueName(tmpR), on);
      pg.addNodeLater(on);
      OrcaLink ol = new OrcaLink("Unnamed");

      // link to parent (a visual HACK)
      links.put(ol.getName(), ol);

      pg.addEdgeLater(on, parent, null, ol);
      // add various properties
      setCommonNodeProperties(on, tmpR);

      // process interfaces. if there is an interface that leads to
      // a link, this is an intra-domain case, so we can delete the parent later
      for (Resource intR : NdlCommons.getResourceInterfaces(tmpR)) {
        // interfaceToNode.put(getTrueName(intR), on);
        addNodeToInterface(getTrueName(intR), on);
        // HACK: for now check that this interface connects to something
        // and is not just hanging there with IP address
        List<Resource> hasI = NdlCommons.getWhoHasInterface(intR, om);
        if (hasI.size() > 1) innerNodeConnected = true;
      }
    }

    // Hack - remove parent if nodes are linked between themselves
    if (innerNodeConnected) pg.removeNode(parent);
  }
Esempio n. 9
0
  public Configuration(Model configurationModel) {
    model = configurationModel;
    StmtIterator it = model.listStatements(null, RDF.type, CONF.Configuration);
    if (!it.hasNext()) {
      throw new IllegalArgumentException("No conf:Configuration found in configuration model");
    }
    config = it.nextStatement().getSubject();

    datasets = new ArrayList();
    it = model.listStatements(config, CONF.dataset, (RDFNode) null);
    while (it.hasNext()) {
      datasets.add(new Dataset(it.nextStatement().getResource()));
    }
    labelProperties = new ArrayList();
    it = model.listStatements(config, CONF.labelProperty, (RDFNode) null);
    while (it.hasNext()) {
      labelProperties.add(it.nextStatement().getObject().as(Property.class));
    }
    if (labelProperties.isEmpty()) {
      labelProperties.add(RDFS.label);
      labelProperties.add(DC.title);
      labelProperties.add(model.createProperty("http://xmlns.com/foaf/0.1/name"));
    }
    commentProperties = new ArrayList();
    it = model.listStatements(config, CONF.commentProperty, (RDFNode) null);
    while (it.hasNext()) {
      commentProperties.add(it.nextStatement().getObject().as(Property.class));
    }
    if (commentProperties.isEmpty()) {
      commentProperties.add(RDFS.comment);
      commentProperties.add(DC.description);
    }
    imageProperties = new ArrayList();
    it = model.listStatements(config, CONF.imageProperty, (RDFNode) null);
    while (it.hasNext()) {
      imageProperties.add(it.nextStatement().getObject().as(Property.class));
    }
    if (imageProperties.isEmpty()) {
      imageProperties.add(model.createProperty("http://xmlns.com/foaf/0.1/depiction"));
    }

    prefixes = new PrefixMappingImpl();
    if (config.hasProperty(CONF.usePrefixesFrom)) {
      it = config.listProperties(CONF.usePrefixesFrom);
      while (it.hasNext()) {
        Statement stmt = it.nextStatement();
        prefixes.setNsPrefixes(FileManager.get().loadModel(stmt.getResource().getURI()));
      }
    } else {
      prefixes.setNsPrefixes(model);
    }
    if (prefixes.getNsURIPrefix(CONF.NS) != null) {
      prefixes.removeNsPrefix(prefixes.getNsURIPrefix(CONF.NS));
    }
  }
  public boolean doGet(
      MappedResource resource,
      Property property,
      boolean isInverse,
      HttpServletRequest request,
      HttpServletResponse response,
      Configuration config)
      throws IOException {
    Model descriptions = getAnonymousPropertyValues(resource, property, isInverse);
    if (descriptions.size() == 0) {
      return false;
    }

    Resource r = descriptions.getResource(resource.getWebURI());
    List resourceDescriptions = new ArrayList();
    StmtIterator it =
        isInverse ? descriptions.listStatements(null, property, r) : r.listProperties(property);
    while (it.hasNext()) {
      Statement stmt = it.nextStatement();
      RDFNode value = isInverse ? stmt.getSubject() : stmt.getObject();
      if (!value.isAnon()) {
        continue;
      }
      resourceDescriptions.add(
          new ResourceDescription((Resource) value.as(Resource.class), descriptions, config));
    }

    Model description = getResourceDescription(resource);
    ResourceDescription resourceDescription =
        new ResourceDescription(resource, description, config);

    String title =
        resourceDescription.getLabel()
            + (isInverse ? " ? " : " ? ")
            + config.getPrefixes().getNsURIPrefix(property.getNameSpace())
            + ":"
            + property.getLocalName();
    VelocityHelper template = new VelocityHelper(getServletContext(), response);
    Context context = template.getVelocityContext();
    context.put("project_name", config.getProjectName());
    context.put("project_link", config.getProjectLink());
    context.put("title", title);
    context.put("server_base", config.getWebApplicationBaseURI());
    context.put("sparql_endpoint", resource.getDataset().getDataSource().getEndpointURL());
    context.put("back_uri", resource.getWebURI());
    context.put("back_label", resourceDescription.getLabel());
    context.put(
        "rdf_link",
        isInverse ? resource.getInversePathDataURL(property) : resource.getPathDataURL(property));
    context.put("resources", resourceDescriptions);
    template.renderXHTML("pathpage.vm");
    return true;
  }
 public Collection<URI> getSupportedFacets(URI needUri) throws NoSuchNeedException {
   List<URI> ret = new LinkedList<URI>();
   Need need = DataAccessUtils.loadNeed(needRepository, needUri);
   Model content = rdfStorageService.loadContent(need);
   if (content == null) return ret;
   Resource baseRes = content.getResource(content.getNsPrefixURI(""));
   StmtIterator stmtIterator = baseRes.listProperties(WON.HAS_FACET);
   while (stmtIterator.hasNext()) {
     RDFNode object = stmtIterator.nextStatement().getObject();
     if (object.isURIResource()) {
       ret.add(URI.create(object.toString()));
     }
   }
   return ret;
 }
Esempio n. 12
0
  private static ArrayList<QualitativeFeature> convertQualitativeFeatures(Resource r) {
    ArrayList<QualitativeFeature> features = new ArrayList<QualitativeFeature>();

    // a feature can have multiple types
    StmtIterator iter = r.listProperties(type);
    // iterate through types
    while (iter.hasNext()) {
      Resource rType = iter.next().getResource();
      String type = rType.getLocalName();
      if (QUAL_FEATURE.get(type) != null) {
        features.add(convertQualitativeFeature(r, type));
      }
    }

    return features;
  }
 public Individual fillExistingDataPropertyStatementsForIndividual(
     Individual entity /*, boolean allowAnyNameSpace*/) {
   if (entity.getURI() == null) {
     return entity;
   } else {
     OntModel ontModel = getOntModelSelector().getABoxModel();
     ontModel.enterCriticalSection(Lock.READ);
     try {
       Resource ind = ontModel.getResource(entity.getURI());
       List<DataPropertyStatement> edList = new ArrayList<DataPropertyStatement>();
       StmtIterator stmtIt = ind.listProperties();
       while (stmtIt.hasNext()) {
         Statement st = (Statement) stmtIt.next();
         boolean addToList = /*allowAnyNameSpace ? st.getObject().canAs(Literal.class) :*/
             st.getObject().isLiteral()
                 && ((RDF.value.equals(st.getPredicate())
                         || VitroVocabulary.value.equals(st.getPredicate().getURI()))
                     || !(NONUSER_NAMESPACES.contains(st.getPredicate().getNameSpace())));
         if (addToList) {
             /* now want to expose Cornellemailnetid and potentially other properties so can at least control whether visible
             boolean isExternalId = false;
             ClosableIterator externalIdStmtIt = getOntModel().listStatements(st.getPredicate(), DATAPROPERTY_ISEXTERNALID, (Literal)null);
             try {
                 if (externalIdStmtIt.hasNext()) {
                     isExternalId = true;
                 }
             } finally {
                 externalIdStmtIt.close();
             }
             if (!isExternalId) { */
           DataPropertyStatement ed = new DataPropertyStatementImpl();
           Literal lit = (Literal) st.getObject();
           fillDataPropertyStatementWithJenaLiteral(ed, lit);
           ed.setDatapropURI(st.getPredicate().getURI());
           ed.setIndividualURI(ind.getURI());
           ed.setIndividual(entity);
           edList.add(ed);
           /* } */
         }
       }
       entity.setDataPropertyStatements(edList);
       return entity;
     } finally {
       ontModel.leaveCriticalSection();
     }
   }
 }
Esempio n. 14
0
  public static Offering addFeatures(Resource service, Offering offering) {
    ArrayList<Resource> services = new ArrayList<Resource>();

    services.add(service);

    // get the parent features
    StmtIterator iter = service.listProperties(hasServiceModel);
    while (iter.hasNext()) {
      // get the Service Parent
      services.add(iter.next().getResource());
    }

    for (Resource r : services) {
      offering = addServiceFeatures(r, offering);
    }

    return offering;
  }
Esempio n. 15
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;
  }
Esempio n. 16
0
  /**
   * Gets NXRelations statement corresponding to the Jena statement.
   *
   * <p>Reified statements may be retrieved from the Jena graph and set as properties on NXRelations
   * statements.
   *
   * @param graph the jena graph
   * @param jenaStatement jena statement
   * @return NXRelations statement
   */
  private Statement getNXRelationsStatement(
      Model graph, com.hp.hpl.jena.rdf.model.Statement jenaStatement) {
    Node subject = getNXRelationsNode(jenaStatement.getSubject().asNode());
    Node predicate = getNXRelationsNode(jenaStatement.getPredicate().asNode());
    Node object = getNXRelationsNode(jenaStatement.getObject().asNode());
    Statement statement = new StatementImpl(subject, predicate, object);

    // take care of properties
    if (graph.isReified(jenaStatement)) {
      com.hp.hpl.jena.rdf.model.Resource reifiedStmt = graph.getAnyReifiedStatement(jenaStatement);
      StmtIterator it = reifiedStmt.listProperties();
      while (it.hasNext()) {
        com.hp.hpl.jena.rdf.model.Statement stmt = it.nextStatement();
        Node nuxNode = getNXRelationsNode(stmt.getPredicate().asNode());
        // ugly cast as a Resource
        Node value = getNXRelationsNode(stmt.getObject().asNode());
        statement.addProperty((Resource) nuxNode, value);
      }
    }

    return statement;
  }
Esempio n. 17
0
  /**
   * Answer the shortest path from the <code>start</code> resource to the <code>end</code> RDF node,
   * such that every step on the path is accepted by the given filter. A path is a {@link List} of
   * RDF {@link Statement}s. The subject of the first statement in the list is <code>start</code>,
   * and the object of the last statement in the list is <code>end</code>.
   *
   * <p>The <code>onPath</code> argument is a {@link Filter}, which accepts a statement and returns
   * true if the statement should be considered to be on the path. To search for an unconstrained
   * path, pass {@link Filter#any} as an argument. To search for a path whose predicates match a
   * fixed restricted set of property names, pass an instance of {@link PredicatesFilter}.
   *
   * <p>If there is more than one path of minimal length from <code>start</code> to <code>end</code>
   * , this method returns an arbitrary one. The algorithm is blind breadth-first search, with loop
   * detection.
   *
   * @param m The model in which we are seeking a path
   * @param start The starting resource
   * @param end The end, or goal, node
   * @param onPath A filter which determines whether a given statement can be considered part of the
   *     path
   * @return A path, consisting of a list of statements whose first subject is <code>start</code>,
   *     and whose last object is <code>end</code>, or null if no such path exists.
   */
  public static Path findShortestPath(
      Model m, Resource start, RDFNode end, Filter<Statement> onPath) {
    List<Path> bfs = new LinkedList<Path>();
    Set<Resource> seen = new HashSet<Resource>();

    // initialise the paths
    for (Iterator<Statement> i = m.listStatements(start, null, (RDFNode) null).filterKeep(onPath);
        i.hasNext(); ) {
      bfs.add(new Path().append(i.next()));
    }

    // search
    Path solution = null;
    while (solution == null && !bfs.isEmpty()) {
      Path candidate = bfs.remove(0);

      if (candidate.hasTerminus(end)) {
        solution = candidate;
      } else {
        Resource terminus = candidate.getTerminalResource();
        if (terminus != null) {
          seen.add(terminus);

          // breadth-first expansion
          for (Iterator<Statement> i = terminus.listProperties().filterKeep(onPath);
              i.hasNext(); ) {
            Statement link = i.next();

            // no looping allowed, so we skip this link if it takes us to a node we've seen
            if (!seen.contains(link.getObject())) {
              bfs.add(candidate.append(link));
            }
          }
        }
      }
    }

    return solution;
  }
  public Organization getOrganization(String organizationUri) {
    long startTime = System.currentTimeMillis();
    Organization org = new Organization();
    // ResIterator iter =
    // ontModel.listSubjectsWithProperty(ontModel.getProperty(ORGID),organizationId);

    Resource r = ontModel.getResource(organizationUri);
    if (r != null) {
      // Resource r = iter.nextResource();

      org.setUri(organizationUri);

      StmtIterator typeStmtIter = r.listProperties(ontModel.getProperty(TYPE));
      Resource organizationalCollaboration = ontModel.getResource(ORGANIZATIONALCOLLABORATION);
      while (typeStmtIter.hasNext()) {
        Statement typeStmt = typeStmtIter.next();
        if (typeStmt != null) {
          String organizationClass = typeStmt.getResource().getURI();
          if (organizationClass.equalsIgnoreCase(organizationalCollaboration.getURI()))
            org.setOrganizationalCollaboration(true);
        }
      }

      Statement id = r.getProperty(ontModel.getProperty(ORGID));
      if (id != null) org.setId(id.getString());

      Statement title = r.getProperty(ontModel.getProperty(TITLE));
      if (title != null) org.setTitle(title.getString());

      Statement preflabel = r.getProperty(ontModel.getProperty(PREFLABEL));
      if (preflabel != null) org.setPrefLabel(preflabel.getString());

      Statement purpose = r.getProperty(ontModel.getProperty(PURPOSE));
      if (purpose != null) org.setPurpose(purpose.getString());

      Statement description = r.getProperty(ontModel.getProperty(DESCRIPTION));
      if (description != null) org.setDescription(description.getString());

      Statement classification = r.getProperty(ontModel.getProperty(CLASSIFICATION));
      if (classification != null) {
        Resource classificationObj = classification.getObject().asResource();
        Statement preflabelClassification =
            classificationObj.getProperty(ontModel.getProperty(PREFLABEL));
        org.setClassification(preflabelClassification.getString());
      }

      // depiction
      Statement depiction = r.getProperty(ontModel.getProperty(DEPICTION));
      if (depiction != null) {
        Statement depicts = depiction.getProperty(ontModel.getProperty(DEPICTS));
        if (depicts != null) {
          Resource imgRes = depicts.getResource();
          if (imgRes != null) org.setDepicts(depicts.getResource().getURI());
        }
      }

      // memberOrganizations
      StmtIterator memberOrgIter = r.listProperties(ontModel.getProperty(HASMEMBERORGANIZATION));
      ArrayList<String> hasMemberOrganization = new ArrayList<String>();
      while (memberOrgIter.hasNext()) {
        Statement stmtMembOrg = memberOrgIter.next();
        Resource memberOrgRes = stmtMembOrg.getResource();
        if (memberOrgRes != null) {
          //			    	Statement memberOrgStmt = memberOrgRes.getProperty(ontModel.getProperty(ORGID));
          //			    	if (memberOrgStmt!=null)
          //			    	    hasMemberOrganization.add(memberOrgStmt.getString());
          hasMemberOrganization.add(memberOrgRes.getURI());
        }
      }
      org.setHasMemberOrganization(hasMemberOrganization);

      // hasProject
      StmtIterator projectOrgIter = r.listProperties(ontModel.getProperty(HASPROJECT));
      ArrayList<String> hasProject = new ArrayList<String>();
      while (projectOrgIter.hasNext()) {
        Statement stmtProjOrg = projectOrgIter.next();
        Resource projRes = stmtProjOrg.getResource();
        if (projRes != null) {
          hasProject.add(projRes.getURI());
        }
      }
      org.setHasProject(hasProject);

      // hasProduct
      StmtIterator productOrgIter = r.listProperties(ontModel.getProperty(HASPRODUCT));
      ArrayList<String> hasProduct = new ArrayList<String>();
      while (productOrgIter.hasNext()) {
        Statement stmtProdOrg = productOrgIter.next();
        Resource prodRes = stmtProdOrg.getResource();
        if (prodRes != null) {
          hasProduct.add(prodRes.getURI());
        }
      }
      org.setHasProduct(hasProduct);

      // hasMember
      StmtIterator hasMemberIter = r.listProperties(ontModel.getProperty(HASMEMBER));
      ArrayList<String> hasMember = new ArrayList<String>();
      while (hasMemberIter.hasNext()) {
        Statement stmtHasMember = hasMemberIter.next();
        Resource personRes = stmtHasMember.getResource();
        if (personRes != null) {
          //			    	Statement personIdStmt = personRes.getProperty(ontModel.getProperty(PERSONID));
          //			    	if (personIdStmt!=null)
          //			    	    hasMember.add(personIdStmt.getString());
          hasMember.add(personRes.getURI());
        }
      }
      org.setHasMember(hasMember);

      // organizationPosition
      StmtIterator orgPositionIter = r.listProperties(ontModel.getProperty(ORGPOSITION));
      ArrayList<String> position = new ArrayList<String>();
      while (orgPositionIter.hasNext()) {
        Statement stmtOrgPosition = orgPositionIter.next();
        Resource positionRes = stmtOrgPosition.getResource();
        if (positionRes != null) {
          position.add(positionRes.getURI());
        }
      }
      org.setPosition(position);

      // organizationRole
      StmtIterator orgRoleIter = r.listProperties(ontModel.getProperty(ORGROLE));
      ArrayList<String> role = new ArrayList<String>();
      while (orgRoleIter.hasNext()) {
        Statement stmtOrgRole = orgRoleIter.next();
        Resource roleRes = stmtOrgRole.getResource();
        if (roleRes != null) {
          role.add(roleRes.getURI());
        }
      }
      org.setRole(role);

      // membership
      StmtIterator membershipIter = r.listProperties(ontModel.getProperty(MEMBERSHIP));
      ArrayList<String> membership = new ArrayList<String>();
      while (membershipIter.hasNext()) {
        Statement stmtMembership = membershipIter.next();
        Resource membershipRes = stmtMembership.getResource();
        if (membershipRes != null) {
          membership.add(membershipRes.getURI());
        }
      }
      org.setMembership(membership);

      long stopTime = System.currentTimeMillis();
      long elapsedTime = stopTime - startTime;
      LOGGER.debug("- Load the organization, elapsed time (ms)..: {}", elapsedTime);
    }
    return org;
  }
Esempio n. 19
0
 protected static Statement getUniqueStatement(Resource root, Property property) {
   List<Statement> statements = root.listProperties(property).toList();
   if (statements.size() == 0) return null;
   if (statements.size() == 1) return statements.get(0);
   throw new NotUniqueException(root, property);
 }
Esempio n. 20
0
 private void testResource(final Model model, final Resource r, final int numProps) {
   final Literal tvLiteral = model.createLiteral("test 12 string 2");
   final Resource tvResource = model.createResource();
   final String lang = "fr";
   //
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvBoolean)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvBoolean));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvByte)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvByte));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvShort)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvShort));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvInt)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvInt));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvLong)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvLong));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvChar)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvChar));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvFloat)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvFloat));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvDouble)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvDouble));
   Assert.assertTrue(
       r.addProperty(RDF.value, AbstractModelTestBase.tvString)
           .hasProperty(RDF.value, AbstractModelTestBase.tvString));
   Assert.assertTrue(
       r.addProperty(RDF.value, AbstractModelTestBase.tvString, lang)
           .hasProperty(RDF.value, AbstractModelTestBase.tvString, lang));
   Assert.assertTrue(
       r.addLiteral(RDF.value, AbstractModelTestBase.tvObject)
           .hasLiteral(RDF.value, AbstractModelTestBase.tvObject));
   Assert.assertTrue(r.addProperty(RDF.value, tvLiteral).hasProperty(RDF.value, tvLiteral));
   Assert.assertTrue(r.addProperty(RDF.value, tvResource).hasProperty(RDF.value, tvResource));
   Assert.assertTrue(r.getRequiredProperty(RDF.value).getSubject().equals(r));
   //
   final Property p = model.createProperty("foo/", "bar");
   try {
     r.getRequiredProperty(p);
     Assert.fail("should detect missing property");
   } catch (final PropertyNotFoundException e) {
     JenaTestBase.pass();
   }
   //
   Assert.assertEquals(13, GraphTestBase.iteratorToSet(r.listProperties(RDF.value)).size());
   Assert.assertEquals(
       setOf(r),
       GraphTestBase.iteratorToSet(
           r.listProperties(RDF.value).mapWith(Statement.Util.getSubject)));
   //
   Assert.assertEquals(0, GraphTestBase.iteratorToSet(r.listProperties(p)).size());
   Assert.assertEquals(
       new HashSet<Resource>(),
       GraphTestBase.iteratorToSet(r.listProperties(p).mapWith(Statement.Util.getSubject)));
   //
   Assert.assertEquals(13 + numProps, GraphTestBase.iteratorToSet(r.listProperties()).size());
   Assert.assertEquals(
       setOf(r),
       GraphTestBase.iteratorToSet(r.listProperties().mapWith(Statement.Util.getSubject)));
   //
   r.removeProperties();
   Assert.assertEquals(0, model.query(new SimpleSelector(r, null, (RDFNode) null)).size());
 }
Esempio n. 21
0
 protected static RDFNode getUnique(Resource root, Property property) {
   List<RDFNode> nodes = root.listProperties(property).mapWith(getObject).toList();
   if (nodes.size() == 0) return null;
   if (nodes.size() == 1) return nodes.get(0);
   throw new NotUniqueException(root, property);
 }
  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;
  }
Esempio n. 23
0
  @Override
  public Protocol fromJena(Model source, Resource res) throws IllegalArgumentException {
    Protocol protocol = new Protocol();
    try {
      protocol.setResourceURL(new URL(res.getURI()));
    } catch (MalformedURLException e) {
      throw new IllegalArgumentException(String.format(msg_InvalidURI, "protocol", res.getURI()));
    }
    try {
      protocol.setSearchable(res.getProperty(TOXBANK.ISSUMMARYSEARCHABLE).getBoolean());
    } catch (Exception x) {
      protocol.setSearchable(false);
    }
    try {
      protocol.setVersion(res.getProperty(TOXBANK.HASVERSIONINFO).getInt());
    } catch (Exception x) {
      protocol.setVersion(0);
    }
    try {
      protocol.setPublished(res.getProperty(TOXBANK.ISPUBLISHED).getBoolean());
    } catch (Exception x) {
      protocol.setPublished(null);
    }
    try {
      protocol.setTimeModified(res.getProperty(DCTerms.modified).getLong());
    } catch (Exception x) {
      protocol.setTimeModified(null);
    }
    try {
      protocol.setSubmissionDate(res.getProperty(DCTerms.dateSubmitted).getLong());
    } catch (Exception x) {
      protocol.setSubmissionDate(null);
    }
    if (res.getProperty(DCTerms.title) != null)
      protocol.setTitle(res.getProperty(DCTerms.title).getString());
    if (res.getProperty(TOXBANK.HASSTATUS) != null)
      try {
        protocol.setStatus(Protocol.STATUS.valueOf(res.getProperty(TOXBANK.HASSTATUS).getString()));
      } catch (Exception x) {
        protocol.setStatus(STATUS.RESEARCH);
      }
    if (res.getProperty(DCTerms.identifier) != null)
      protocol.setIdentifier(res.getProperty(DCTerms.identifier).getString());
    if (res.getProperty(TOXBANK.HASABSTRACT) != null)
      protocol.setAbstract(res.getProperty(TOXBANK.HASABSTRACT).getString());
    StmtIterator keywords = res.listProperties(TOXBANK.HASKEYWORD);
    while (keywords.hasNext()) {
      protocol.addKeyword(keywords.next().getString());
    }

    String uri = null;
    StmtIterator authors = res.listProperties(TOXBANK.HASAUTHOR);
    while (authors.hasNext()) {
      Resource authorRes = authors.next().getResource();
      User author = userIO.fromJena(source, authorRes);
      protocol.addAuthor(author);
    }
    authors.close();

    StmtIterator projects = res.listProperties(TOXBANK.HASPROJECT);
    while (projects.hasNext()) {
      Resource projectRes = projects.next().getResource();
      Project project = projectIO.fromJena(source, projectRes);
      protocol.addProject(project);
    }
    projects.close();

    if (res.getProperty(TOXBANK.HASORGANISATION) != null) {
      Organisation org =
          organisationIO.fromJena(source, res.getProperty(TOXBANK.HASORGANISATION).getResource());
      protocol.setOrganisation(org);
    }

    if (res.getProperty(TOXBANK.HASOWNER) != null)
      try {
        uri = res.getProperty(TOXBANK.HASOWNER).getResource().getURI();
        User author = new User();

        author.setResourceURL(new URL(uri));
        protocol.setOwner(author);
      } catch (MalformedURLException e) {
        throw new IllegalArgumentException(String.format(msg_InvalidURI, "a protocol owner", uri));
      }

    if (res.getProperty(TOXBANK.HASDOCUMENT) != null)
      try {
        uri = res.getProperty(TOXBANK.HASDOCUMENT).getResource().getURI();
        Document document = new Document(new URL(uri));

        protocol.setDocument(document);
      } catch (MalformedURLException e) {
        throw new IllegalArgumentException(String.format(msg_InvalidURI, "a document", uri));
      }

    if (res.getProperty(TOXBANK.HASTEMPLATE) != null)
      try {
        uri = res.getProperty(TOXBANK.HASTEMPLATE).getResource().getURI();
        Template dataTemplate = new Template(new URL(uri));

        protocol.setDataTemplate(dataTemplate);
      } catch (MalformedURLException e) {
        throw new IllegalArgumentException(String.format(msg_InvalidURI, "data template", uri));
      }
    if (res.getProperty(DCTerms.license) != null)
      try {
        protocol.setLicense(new URL(res.getProperty(DCTerms.license).getObject().toString()));
      } catch (MalformedURLException e) {
        throw new IllegalArgumentException(
            String.format(
                msg_InvalidURI, "a license", res.getProperty(DCTerms.license).getObject()));
      }
    return protocol;
  }
 /** @see com.hp.hpl.jena.rdf.model.Resource#listProperties(com.hp.hpl.jena.rdf.model.Property) */
 public StmtIterator listProperties(Property p) {
   synchronized (model) {
     return new CachingStmtIterator(model, wrapped.listProperties(p));
   }
 }