public static Triple createTriple(Statement statement) throws OREException {
    try {
      URI subject = new URI(statement.getSubject().getURI());
      Property property = statement.getPredicate();

      Predicate pred = new Predicate();
      pred.setURI(new URI(property.getURI()));

      TripleJena triple = new TripleJena();
      triple.initialise(new URI(statement.getSubject().getURI()));

      RDFNode node = statement.getObject();
      if (node instanceof Resource) {
        String uris = ((Resource) node).getURI();

        // if the object is not a blank node, we include it
        if (uris != null) {
          URI object = new URI(uris);
          triple.relate(pred, object);
        }
      } else {
        String object = ((Literal) statement.getObject()).getLexicalForm();
        triple.relate(pred, object);
      }

      return triple;
    } catch (URISyntaxException e) {
      throw new OREException(e);
    }
  }
 public void testCreatePropertyStrangeURITwoArgs() {
   final String local = "_345";
   final Property p = model.createProperty(RDF.getURI(), local);
   Assert.assertEquals(RDF.getURI(), p.getNameSpace());
   Assert.assertEquals(local, p.getLocalName());
   Assert.assertEquals(RDF.getURI() + local, p.getURI());
 }
 public void testCreatePropertyStrangeURI() {
   final String uri = RDF.getURI() + "_345";
   final Property p = model.createProperty(uri);
   Assert.assertEquals(RDF.getURI(), p.getNameSpace());
   Assert.assertEquals("_345", p.getLocalName());
   Assert.assertEquals(uri, p.getURI());
 }
  /**
   * 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 #5
0
 private String getPathURL(String urlPrefix, Property property) {
   if (serverConfig.getPrefixes().qnameFor(property.getURI()) == null) {
     return null;
   }
   return serverConfig.getWebApplicationBaseURI()
       + urlPrefix
       + serverConfig.getPrefixes().qnameFor(property.getURI())
       + "/"
       + relativeWebURI;
 }
  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;
  }
  @Test
  public void testTermbindsIncludesMetaproperties() throws URISyntaxException {
    Integer totalResults = null;
    Resource thisMetaPage = createMetadata(false, totalResults);

    for (Property p : expectedTermboundProperties) {
      Model model = thisMetaPage.getModel();
      if (!model.contains(null, API.property, p)) {
        fail("term bindings should include " + model.shortForm(p.getURI()));
      }
    }
  }
Example #8
0
 /**
  * Self configuration Properties(target) - Properties(source) Find properties in target which are
  * not in source
  *
  * @param source
  * @param target
  * @return Map of (key, value) pairs of self configured parameters
  * @author sherif
  */
 public Map<String, String> selfConfig(Model source, Model target) {
   Map<String, String> parameters = new HashMap<String, String>();
   Set<Property> properties = getPropertyDifference(source, target);
   int propertyNr = 1;
   for (Property p : properties) {
     parameters.put(INPUT_PROPERTY + propertyNr, p.toString());
     parameters.put(OUTPUT_PROPERTY + propertyNr, p.toString());
     propertyNr++;
   }
   //		logger.info("Self configuration: " + parameters);
   if (parameters.size() == 0) {
     return null;
   }
   return parameters;
 }
    // Get predicate local anchor
    public static String getPredicateLocalName(EditConfigurationVTwo editConfig) {
      String predicateLocalName = null;
      if (editConfig != null) {
        String predicateUri = editConfig.getPredicateUri();
        if (predicateUri != null) {
          try {
            Property prop = ResourceFactory.createProperty(predicateUri);
            predicateLocalName = prop.getLocalName();

          } catch (com.hp.hpl.jena.shared.InvalidPropertyURIException e) {
            log.debug("could not convert predicateUri into a valid URI", e);
          }
        }
      }
      return predicateLocalName;
    }
  protected boolean populateKeyValue(Text key, Triple value) {

    Resource subject;
    Property predicate = null;
    RDFNode object;

    inErr = false;

    skipWhiteSpace();
    if (in.eof()) {
      return false;
    }

    subject = readResource();
    if (inErr) return false;

    skipWhiteSpace();
    try {
      predicate = model.createProperty(readResource().getURI());
    } catch (Exception e1) {
      e1.printStackTrace();
      errorHandler.fatalError(e1);
    }
    if (inErr) return false;

    skipWhiteSpace();
    object = readNode();
    if (inErr) return false;

    skipWhiteSpace();
    if (badEOF()) return false;

    if (!expect(".")) return false;

    try {
      key.set(getCurrentFileName());
      value.setTriple(subject.asNode(), predicate.asNode(), object.asNode());
      recordCounter++;
      // System.out.println("Triple value:"+value);
      return true;
    } catch (Exception e2) {
      e2.printStackTrace();
      errorHandler.fatalError(e2);
    }

    return false;
  }
  @Override
  public void compute(Quad quad) {
    logger.debug("Computing : {} ", quad.asTriple().toString());

    Node subject = quad.getSubject();
    Node object = quad.getObject();

    if (quad.getObject().equals(FOAF.Document.asNode())) {
      docs.putIfAbsent(subject.toString(), new DigitalSignature());
    }

    if (quad.getPredicate().equals(ASSURANCE.asNode())) {
      DigitalSignature ds;
      if (endorsements.containsKey(object.getURI())) {
        ds = endorsements.get(object.getURI());
      } else {
        ds = new DigitalSignature();
        ds.endorcement = object.getURI();
      }

      ds.assurance = subject.getURI();

      docs.put(subject.toString(), ds);
      endorsements.put(object.getURI(), ds);
    }

    if (quad.getPredicate().equals(ENDORSER.asNode())) {
      DigitalSignature ds;
      if (endorsements.containsKey(object.getURI())) {
        ds = endorsements.get(object.getURI());
      } else {
        ds = new DigitalSignature();
        ds.endorcement = subject.getURI();
      }

      ds.endorcer = object.getURI();
    }

    if (quad.getObject().equals(ENDORSEMENT.asNode())) {
      DigitalSignature ds = new DigitalSignature();
      ds.endorcement = subject.getURI();

      endorsements.putIfAbsent(subject.getURI(), ds);
    }
  }
Example #12
0
  @Test
  public void shouldSortTriplesForDisplay() {
    final Model model = createDefaultModel();

    model.setNsPrefix("prefix", "namespace");
    final Property propertyA = model.createProperty("namespace", "a");
    final Property propertyB = model.createProperty("namespace", "b");
    final Property propertyC = model.createProperty("c");
    final Literal literalA = model.createLiteral("a");
    final Literal literalB = model.createLiteral("b");
    final Resource resourceB = model.createResource("b");
    model.add(resourceB, propertyA, literalA);

    final Resource a = model.createResource("a");
    model.add(a, propertyC, literalA);

    model.add(a, propertyB, literalA);

    model.add(a, propertyA, literalA);
    model.add(a, propertyA, literalB);

    final Iterator<Quad> iterator = DatasetFactory.create(model).asDatasetGraph().find();

    final List<Quad> sortedTriples = testObj.getSortedTriples(model, iterator);

    sortedTriples.get(0).matches(ANY, a.asNode(), propertyA.asNode(), literalA.asNode());
    sortedTriples.get(1).matches(ANY, a.asNode(), propertyA.asNode(), literalB.asNode());
    sortedTriples.get(2).matches(ANY, a.asNode(), propertyB.asNode(), literalA.asNode());
    sortedTriples.get(3).matches(ANY, a.asNode(), propertyC.asNode(), literalA.asNode());
    sortedTriples.get(4).matches(ANY, resourceB.asNode(), propertyC.asNode(), literalA.asNode());
  }
Example #13
0
 private static void printModel(OntModel model, Property prop) {
   StmtIterator stit = model.listStatements();
   Statement st = null;
   while (stit.hasNext()) {
     st = stit.next();
     if (prop == null || prop.equals(st.getPredicate())) {
       System.out.println("S: " + st.getSubject());
       System.out.println("P: " + st.getPredicate());
       System.out.println("O: " + st.getObject());
     }
   }
 }
Example #14
0
 private void unifyRDFSVersion(String ns) {
   for (Iterator it = Jena.cloneIt(model.listStatements()); it.hasNext(); ) {
     Statement s = (Statement) it.next();
     Resource newSubject = s.getSubject();
     Property newPredicate = s.getPredicate();
     RDFNode newObject = s.getObject();
     boolean changed = false;
     if (ns.equals(newSubject.getNameSpace())) {
       changed = true;
       newSubject = model.getResource(RDFS.getURI() + newSubject.getLocalName());
     }
     if (ns.equals(newPredicate.getNameSpace())) {
       changed = true;
       newPredicate = model.getProperty(RDFS.getURI() + newPredicate.getLocalName());
     }
     if (newObject.canAs(Resource.class)) {
       Resource oldResource = (Resource) newObject.as(Resource.class);
       if (ns.equals(oldResource.getNameSpace())) {
         changed = true;
         newObject = model.getResource(RDFS.getURI() + oldResource.getLocalName());
       }
     }
     if (changed) {
       model.add(newSubject, newPredicate, newObject);
       if (log.isLoggable(Level.FINE)) {
         log.fine(
             "Replaced deprecated triple "
                 + s
                 + " with "
                 + newSubject
                 + ", "
                 + newPredicate
                 + ", "
                 + newObject);
       }
       it.remove();
     }
   }
 }
Example #15
0
  /**
   * Get the JCR property name for an RDF predicate
   *
   * @param namespaceRegistry
   * @param predicate
   * @param namespaceMapping
   * @return
   * @throws RepositoryException
   */
  public String getPropertyNameFromPredicate(
      final NamespaceRegistry namespaceRegistry,
      final com.hp.hpl.jena.rdf.model.Property predicate,
      final Map<String, String> namespaceMapping)
      throws RepositoryException {

    final String prefix;

    final String namespace = getJcrNamespaceForRDFNamespace(predicate.getNameSpace());

    assert (namespaceRegistry != null);

    if (namespaceRegistry.isRegisteredUri(namespace)) {
      LOGGER.debug("Discovered namespace: {} in namespace registry.", namespace);
      prefix = namespaceRegistry.getPrefix(namespace);
    } else {
      LOGGER.debug("Didn't discover namespace: {} in namespace registry.", namespace);
      final ImmutableBiMap<String, String> nsMap = ImmutableBiMap.copyOf(namespaceMapping);
      if (nsMap.containsValue(namespace)) {
        LOGGER.debug("Discovered namespace: {} in namespace map: {}.", namespace, nsMap);
        prefix = nsMap.inverse().get(namespace);
        namespaceRegistry.registerNamespace(prefix, namespace);
      } else {
        prefix = namespaceRegistry.registerNamespace(namespace);
      }
    }

    final String localName = predicate.getLocalName();

    final String propertyName = prefix + ":" + localName;

    LOGGER.debug(
        "Took RDF predicate {} and translated it to JCR property {}", predicate, propertyName);

    return propertyName;
  }
 /* (non-Javadoc)
  * @see org.sadiframework.client.Registry#findServicesByAttachedProperty(com.hp.hpl.jena.rdf.model.Property)
  */
 @Override
 public Collection<? extends Service> findServicesByAttachedProperty(Property property)
     throws SADIException {
   Set<String> propertyURIs = new HashSet<String>();
   if (property.isURIResource()) propertyURIs.add(property.getURI());
   if (property.canAs(OntProperty.class)) {
     for (Iterator<? extends Property> i = property.as(OntProperty.class).listSubProperties();
         i.hasNext(); ) {
       Property p = i.next();
       if (p.isURIResource()) propertyURIs.add(p.getURI());
     }
   }
   return findServicesByAttachedProperty(propertyURIs);
   // TODO
   //		return findServices(RegistrySearchCriteria.findService().addAttachedProperty(property));
 }
Example #17
0
 @Override
 public void visitComponentProperty(Property property, Resource resource, ComponentType... types) {
   if (resource == null) return;
   if (property == null) {
     out.printResourceStart(resource);
     super.visitComponentProperty(property, resource, types);
     out.printResourceEnd();
   } else if (resource.isAnon()) {
     // boolean isRefObjectMap = property.equals(RR.objectMap) &&
     //		mapping.referencingObjectMaps().has(resource);
     // d2.1
     boolean isRefObjectMap = property.equals(RR.objectMap);
     out.printPropertyStart(property, COMPACT_PROPERTIES.contains(property) && !isRefObjectMap);
     super.visitComponentProperty(property, resource, types);
     out.printPropertyEnd();
   } else {
     out.printProperty(property, resource);
   }
 }
Example #18
0
 public String getElement(Property key) {
   return getElements(key.getURI())[0];
 }
  /**
   * 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;
  }
  @Override
  public void runMetric() {

    // class annotation cover
    // List<Property> classAnnotationList = new ArrayList<Property>();
    classMetricMap = new HashMap<Property, CoverageTriple>();

    totalClassCount = ontology.getClassesList().size();

    for (Node classNode : ontology.getClassesList()) {
      OntClass currentClass = (OntClass) classNode.getResource().as(OntClass.class);
      StmtIterator i = currentClass.listProperties();

      Map<Property, Boolean> countedMap = new HashMap<Property, Boolean>();
      while (i.hasNext()) {
        Statement s = (Statement) i.next();
        Property p = s.getPredicate();

        if (p.canAs(AnnotationProperty.class) && countedMap.get(p) == null) {
          // this is an annotation property
          if (classMetricMap.get(p) == null) {
            // this property doesn't exit
            CoverageTriple t = new CoverageTriple();
            t.count = 1;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
            classMetricMap.put(p, t);
          } else {
            CoverageTriple count = classMetricMap.get(p);
            count.count++;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          }
        }
      }
    }

    totalPropertyCount = ontology.getPropertiesList().size();
    // property annotation cover
    propertyMetricMap = new HashMap<Property, CoverageTriple>();

    for (Node propertyNode : ontology.getPropertiesList()) {
      OntProperty currentProperty = (OntProperty) propertyNode.getResource().as(OntProperty.class);
      StmtIterator i = currentProperty.listProperties();

      Map<Property, Boolean> countedMap = new HashMap<Property, Boolean>();
      while (i.hasNext()) {
        Statement s = (Statement) i.next();
        Property p = s.getPredicate();

        if (p.canAs(AnnotationProperty.class)) {
          // this is an annotation property
          if (propertyMetricMap.get(p) == null && countedMap.get(p) == null) {
            // this property doesn't exit
            CoverageTriple t = new CoverageTriple();
            t.count = 1;
            propertyMetricMap.put(p, t);
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          } else {
            CoverageTriple count = propertyMetricMap.get(p);
            count.count++;
            countedMap.put(p, new Boolean(true)); // avoid counting duplicate annotations
          }
        }
      }
    }

    // compute the percent coverage
    for (Entry<Property, CoverageTriple> entry : classMetricMap.entrySet()) {
      entry.getValue().coverage = (double) entry.getValue().count / (double) totalClassCount;
      if (entry.getValue().count > totalClassCount) {
        // test?
        System.out.println("--");
      }
    }

    for (Entry<Property, CoverageTriple> entry : propertyMetricMap.entrySet()) {
      entry.getValue().coverage = (double) entry.getValue().count / (double) totalPropertyCount;
      if (entry.getValue().count > totalPropertyCount) {
        // test?
        System.out.println("--");
      }
    }
  }
Example #21
0
  /**
   * @param uri : the URI to be dereferenced
   * @param predicates : targeted predicates to be added to enrich the model
   * @return This method retrieves list of values for targeted predicates for a URI-typed object for
   *     each URI-typed object, through content negotiation an open connection is done retrieving
   *     its predicates/values. An iteration is made over targeted predicates. For each predicate
   *     list of statements with the targeted predicate is retrieved and extracting its value in
   *     order to be added to hashmap<predicate,Value>
   */
  @SuppressWarnings("unchecked")
  private static HashMap<Property, List<RDFNode>> getURIInfo(RDFNode p) {
    String uri = p.asResource().getURI();
    // to store each predicate and its value
    HashMap<Property, List<RDFNode>> resourceFocusedInfo = new HashMap<Property, List<RDFNode>>();

    if (demo) { // Deserialize the results if exists (For Demo purpose)
      if (useCache) {
        try {
          HashMap<String, List<String>> ser = new HashMap<String, List<String>>();
          File file = new File("resourceFocusedInfo.ser");
          if (file.exists()) {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            ser = (HashMap<String, List<String>>) in.readObject();
            in.close();
            // convert every object back from string
            for (String prop : ser.keySet()) {
              List<String> l = ser.get(prop);
              List<RDFNode> nodes = new ArrayList<RDFNode>();
              for (String n : l) {
                nodes.add(ResourceFactory.createResource(n));
              }
              resourceFocusedInfo.put(ResourceFactory.createProperty(prop), nodes);
            }
            return resourceFocusedInfo;
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    // define local model to have the data of the URI and extract focused info through built sparql
    // query
    List<RDFNode> values = new ArrayList<RDFNode>();
    try {
      URLConnection conn = new URL(uri).openConnection();
      conn.setRequestProperty("Accept", "application/rdf+xml");
      conn.setRequestProperty("Accept-Language", "en");
      Model model = ModelFactory.createDefaultModel();
      InputStream in = conn.getInputStream();
      model.read(in, null);
      for (Property inputProperty : inputProperties) {
        for (Statement st :
            model.listStatements(model.getResource(uri), inputProperty, (RDFNode) null).toList()) {
          RDFNode value = st.getObject();
          if (value.isLiteral()) {
            if (value.asLiteral().getLanguage().toLowerCase().equals("en")
                || value.asLiteral().getLanguage().toLowerCase().equals("")) {
              values.add(value);
            }
          } else {
            values.add(value);
          }
        }
        resourceFocusedInfo.put(inputProperty, values);
        values = new ArrayList<RDFNode>(); // create new list for new predicate
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (demo) { // serialize the output (for Demo purpose)
      try {
        HashMap<String, List<String>> ser = new HashMap<String, List<String>>();
        FileOutputStream fileOut = new FileOutputStream("resourceFocusedInfo.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        // convert to Serializabe Strings
        for (Property prop : resourceFocusedInfo.keySet()) {
          List<String> l = new ArrayList<String>();
          for (RDFNode n : resourceFocusedInfo.get(prop)) {
            l.add(n.toString());
          }
          ser.put(prop.toString(), l);
        }
        out.writeObject(ser);
        out.close();
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }
    return resourceFocusedInfo;
  }
Example #22
0
 public void testCreatePropertyTwoArgs() {
   final Property p = model.createProperty("abc/", "def");
   Assert.assertEquals("abc/", p.getNameSpace());
   Assert.assertEquals("def", p.getLocalName());
   Assert.assertEquals("abc/def", p.getURI());
 }
  private void tryRestriction(
      OntClass theClass,
      VClassDao vcDao,
      ObjectPropertyDao opDao,
      IndividualDao iDao,
      ArrayList results,
      String vClassURI) {
    if (theClass.isRestriction()) {
      Restriction rest = (Restriction) theClass.as(Restriction.class);
      try {
        results.add("XX");
        Property onProperty = rest.getOnProperty();
        ObjectProperty op = opDao.getObjectPropertyByURI(onProperty.getURI());
        results.add(op.getLocalNameWithPrefix());
        if (rest.isAllValuesFromRestriction()) {
          results.add("all values from");
          AllValuesFromRestriction avfrest =
              (AllValuesFromRestriction) rest.as(AllValuesFromRestriction.class);
          Resource allValuesFrom = avfrest.getAllValuesFrom();
          results.add(printAsClass(vcDao, allValuesFrom));
        } else if (rest.isSomeValuesFromRestriction()) {
          results.add("some values from");
          SomeValuesFromRestriction svfrest =
              (SomeValuesFromRestriction) rest.as(SomeValuesFromRestriction.class);
          Resource someValuesFrom = svfrest.getSomeValuesFrom();
          results.add(printAsClass(vcDao, someValuesFrom));
        } else if (rest.isHasValueRestriction()) {
          results.add("has value");
          HasValueRestriction hvrest = (HasValueRestriction) rest.as(HasValueRestriction.class);
          RDFNode hasValue = hvrest.getHasValue();
          if (hasValue.isResource()) {
            Resource hasValueRes = (Resource) hasValue.as(Resource.class);
            try {
              if (hasValueRes.getURI() != null) {
                Individual ind = iDao.getIndividualByURI(hasValueRes.getURI());
                if (ind.getName() != null) {
                  results.add(ind.getName());
                }
              }
            } catch (Exception e) {
              results.add("???");
            }
          }

        } else if (rest.isMinCardinalityRestriction()) {
          MinCardinalityRestriction crest =
              (MinCardinalityRestriction) rest.as(MinCardinalityRestriction.class);
          results.add("at least " + crest.getMinCardinality());
          results.add(LAMBDA);
        } else if (rest.isMaxCardinalityRestriction()) {
          MaxCardinalityRestriction crest =
              (MaxCardinalityRestriction) rest.as(MaxCardinalityRestriction.class);
          results.add("at most " + crest.getMaxCardinality());
          results.add(LAMBDA);
        } else if (rest.isCardinalityRestriction()) {
          CardinalityRestriction crest =
              (CardinalityRestriction) rest.as(CardinalityRestriction.class);
          results.add("exactly " + crest.getCardinality());
          results.add(LAMBDA);
        }

        results.add(
            "<form action=\"addRestriction\" method=\"post\">"
                + "<input type=\"hidden\" name=\"_action\" value=\"delete\"/>"
                + "<input type=\"submit\" value=\"Delete\"/>"
                + "<input type=\"hidden\" name=\"_epoKey\" value=\""
                + epo.getKey()
                + "\"/>"
                + "<input type=\"hidden\" name=\"classUri\" value=\""
                + vClassURI
                + "\"/>"
                + "<input type=\"hidden\" name=\"restrictionId\" value=\""
                + ((rest.getId() != null) ? rest.getId() : rest.getURI())
                + "\"/>"
                + "</form>");

      } catch (Exception e) {
        e.printStackTrace(); // results.add("unknown property");
      }
    }
  }
  public void deleteObjectPropertyStatement(
      String subjectURI, String propertyURI, String objectURI, OntModel ontModel) {
    ontModel.enterCriticalSection(Lock.WRITE);
    try {
      Resource subjRes = ontModel.getResource(subjectURI);
      Property pred = ontModel.getProperty(propertyURI);
      OntProperty invPred = null;
      if (pred.canAs(OntProperty.class)) {
        invPred = ((OntProperty) pred.as(OntProperty.class)).getInverse();
      }
      Resource objRes = ontModel.getResource(objectURI);
      if ((subjRes != null) && (pred != null) && (objRes != null)) {
        getOntModel()
            .getBaseModel()
            .notifyEvent(
                new IndividualUpdateEvent(getWebappDaoFactory().getUserURI(), true, subjectURI));
        try {
          ontModel.remove(subjRes, pred, objRes);

          updatePropertyDateTimeValue(
              subjRes, MODTIME, Calendar.getInstance().getTime(), getOntModel());
        } finally {
          getOntModel()
              .getBaseModel()
              .notifyEvent(
                  new IndividualUpdateEvent(getWebappDaoFactory().getUserURI(), false, subjectURI));
        }
        try {
          getOntModel()
              .getBaseModel()
              .notifyEvent(
                  new IndividualDeletionEvent(getWebappDaoFactory().getUserURI(), true, objectURI));
          List<Statement> depResStmts =
              DependentResourceDeleteJena.getDependentResourceDeleteList(
                  ResourceFactory.createStatement(subjRes, pred, objRes), ontModel);
          getOntModel().remove(depResStmts);
        } finally {
          getOntModel()
              .getBaseModel()
              .notifyEvent(
                  new IndividualDeletionEvent(
                      getWebappDaoFactory().getUserURI(), false, objectURI));
        }
        if (invPred != null) {
          getOntModel()
              .getBaseModel()
              .notifyEvent(
                  new IndividualUpdateEvent(getWebappDaoFactory().getUserURI(), true, objectURI));
          try {
            ontModel.remove(objRes, invPred, subjRes);
            updatePropertyDateTimeValue(
                objRes, MODTIME, Calendar.getInstance().getTime(), getOntModel());
          } finally {
            getOntModel()
                .getBaseModel()
                .notifyEvent(
                    new IndividualUpdateEvent(
                        getWebappDaoFactory().getUserURI(), false, subjectURI));
          }
        }
      }
    } finally {
      ontModel.leaveCriticalSection();
    }
  }
  public Model getRdfModel() {

    Model allrisModel = ModelFactory.createDefaultModel();
    allrisModel.setNsPrefix("dcterms", "http://purl.org/dc/terms/");
    allrisModel.setNsPrefix("allris", this.urlBase);
    Property subject = allrisModel.createProperty("http://purl.org/dc/terms/subject");

    Property aktenzeichen = allrisModel.createProperty(this.urlBase + "aktenzeichen");
    aktenzeichen.addProperty(RDFS.label, allrisModel.createLiteral("Aktenzeichen", "de"));
    aktenzeichen.addProperty(
        RDFS.comment, allrisModel.createLiteral("Das Aktenzeichen einer Drucksache.", "de"));

    Property druckClass = allrisModel.createProperty(this.urlBase + "Drucksache");

    Property betreff = allrisModel.createProperty(this.urlBase + "betreff");
    betreff.addProperty(RDFS.label, allrisModel.createLiteral("Betreff", "de"));
    betreff.addProperty(
        RDFS.comment, allrisModel.createLiteral("Der Betreff der Drucksache.", "de"));

    Property status = allrisModel.createProperty(this.urlBase + "status");
    status.addProperty(RDFS.label, allrisModel.createLiteral("Status", "de"));
    status.addProperty(
        RDFS.comment,
        allrisModel.createLiteral("Status der Drucksache, öffentlich, abgeschlossen, etc.", "de"));

    Property druckArt = allrisModel.createProperty(this.urlBase + "artDerDrucksache");
    druckArt.addProperty(RDFS.label, allrisModel.createLiteral("Art der Drucksache", "de"));
    druckArt.addProperty(
        RDFS.comment,
        allrisModel.createLiteral(
            "Die Art der Drucksache kann eine mündliche oder schriftliche Anfrage sein, ein Antrag, eine Resolution oder ähnliches.",
            "de"));

    Property initiator = allrisModel.createProperty(this.urlBase + "initiator");
    initiator.addProperty(RDFS.label, allrisModel.createLiteral("Initiator der Drucksache", "de"));
    initiator.addProperty(
        RDFS.comment,
        allrisModel.createLiteral(
            "Der Initiator der Drucksache ist meist eine Fraktion, manchmal auch eine Abteilung oder ähnliches.",
            "de"));

    Property text = allrisModel.createProperty(this.urlBase + "text");
    text.addProperty(RDFS.label, allrisModel.createLiteral("Text der Drucksache", "de"));
    text.addProperty(RDFS.comment, allrisModel.createLiteral("Der Volltext der Drucksache.", "de"));

    Property verfasser = allrisModel.createProperty(this.urlBase + "verfasser");
    verfasser.addProperty(
        RDFS.label, allrisModel.createLiteral("VerfasserIn der Drucksache", "de"));
    verfasser.addProperty(
        RDFS.comment, allrisModel.createLiteral("VerfasserIn der Drucksache.", "de"));

    Property beschluss = allrisModel.createProperty(this.urlBase + "beschluss");
    beschluss.addProperty(RDFS.label, allrisModel.createLiteral("Beschluss zur Drucksache", "de"));
    beschluss.addProperty(
        RDFS.comment,
        allrisModel.createLiteral(
            "Link zum zugehörigen Beschluss. Autogeneriert: Falls die Drucksache keinen Beschluss hat, ist die Seite trotzdem verlinkt.",
            "de"));

    for (Drucksache d : this.drucksachen) {

      Resource drucksacheResource =
          allrisModel.createResource(this.urlBase + "drucksache/" + d.getVolfdnr());
      drucksacheResource.addProperty(subject, allrisModel.createProperty(d.getUri()));
      if (d.getBetreff() != null) {
        drucksacheResource.addProperty(RDFS.label, allrisModel.createLiteral(d.getBetreff(), "de"));
        drucksacheResource.addProperty(betreff, allrisModel.createLiteral(d.getBetreff(), "de"));
      }
      drucksacheResource.addProperty(RDF.type, druckClass);

      if (d.getStatus() != null)
        drucksacheResource.addProperty(status, allrisModel.createLiteral(d.getStatus(), "de"));
      if (d.getArt() != null)
        drucksacheResource.addProperty(druckArt, allrisModel.createLiteral(d.getArt(), "de"));
      if (d.getInitiator() != null) {
        drucksacheResource.addProperty(
            initiator, allrisModel.createLiteral(d.getInitiator(), "de"));
        String initiatorUri = this.getInitiatorUri(d);
        if (initiatorUri != null) {
          drucksacheResource.addProperty(initiator, allrisModel.createProperty(initiatorUri));
        }
      }
      if (d.getText() != null) {
        drucksacheResource.addProperty(text, allrisModel.createLiteral(d.getText(), "de"));
      }
      if (d.getVerfasser() != null && !d.getVerfasser().isEmpty()) {
        drucksacheResource.addProperty(
            verfasser, allrisModel.createLiteral(d.getVerfasser(), "de"));
        String verfasserUri = this.getVerfasserUri(d.getVerfasser());
        if (verfasserUri != null) {
          drucksacheResource.addProperty(verfasser, allrisModel.createProperty(verfasserUri));
        }
      }
      if (d.getBeschlussLink() != null) {
        drucksacheResource.addProperty(beschluss, allrisModel.createProperty(d.getBeschlussLink()));
      }
    }

    Property name = allrisModel.createProperty(this.urlBase + "name");
    name.addProperty(RDFS.label, allrisModel.createLiteral("Name der Fraktion oder Person", "de"));
    name.addProperty(
        RDFS.comment, allrisModel.createLiteral("Der Name der Fraktio, Gruppe oder Person.", "de"));

    Property fraktionClass = allrisModel.createProperty(this.urlBase + "Fraktion");

    Property adresse = allrisModel.createProperty(this.urlBase + "adresse");
    adresse.addProperty(RDFS.label, allrisModel.createLiteral("Adresse", "de"));
    adresse.addProperty(
        RDFS.comment,
        allrisModel.createLiteral(
            "Die Adresse bezeichnet einen physikalischen Ort, an dem das Subjekt zu erreichen ist.",
            "de"));

    Property sprechzeiten = allrisModel.createProperty(this.urlBase + "sprechzeiten");
    sprechzeiten.addProperty(RDFS.label, allrisModel.createLiteral("Sprechzeiten", "de"));
    sprechzeiten.addProperty(
        RDFS.comment,
        allrisModel.createLiteral("Die Sprechzeiten der Fraktion oder eines Politikers.", "de"));

    Property email = allrisModel.createProperty(this.urlBase + "email");
    email.addProperty(RDFS.label, allrisModel.createLiteral("Email-Adresse", "de"));
    email.addProperty(
        RDFS.comment,
        allrisModel.createLiteral("Die Email einer Fraktion oder eines Politikers.", "de"));

    Property homepage = allrisModel.createProperty(this.urlBase + "homepage");
    homepage.addProperty(RDFS.label, allrisModel.createLiteral("Homepage", "de"));
    homepage.addProperty(
        RDFS.comment,
        allrisModel.createLiteral("Die Homepage einer Fraktion oder eines Politikers.", "de"));

    Property politikerClass = allrisModel.createProperty(this.urlBase + "Politiker");

    Property politikerArt = allrisModel.createProperty(this.urlBase + "fraktionsFunktion");
    politikerArt.addProperty(RDFS.label, allrisModel.createLiteral("Funktion in Fraktion", "de"));
    politikerArt.addProperty(
        RDFS.comment,
        allrisModel.createLiteral("Die Funktion eines Politikers in einer Fraktion.", "de"));

    for (Fraktion f : fraktionen) {
      Resource fraktionResource =
          allrisModel.createResource(this.urlBase + "fraktion/F" + f.getId());
      fraktionResource.addProperty(subject, allrisModel.createProperty(f.getUri()));
      if (f.getName() != null) {
        fraktionResource.addProperty(RDFS.label, allrisModel.createLiteral(f.getName(), "de"));
        fraktionResource.addProperty(name, allrisModel.createLiteral(f.getName(), "de"));
      }
      fraktionResource.addProperty(RDF.type, fraktionClass);

      if (f.getAdresse() != null)
        fraktionResource.addProperty(adresse, allrisModel.createLiteral(f.getAdresse(), "de"));
      if (f.getSprechzeiten() != null)
        fraktionResource.addProperty(
            sprechzeiten, allrisModel.createLiteral(f.getSprechzeiten(), "de"));
      if (f.getEmail() != null)
        fraktionResource.addProperty(email, allrisModel.createLiteral(f.getEmail(), "de"));
      if (f.getHomepage() != null)
        fraktionResource.addProperty(homepage, allrisModel.createLiteral(f.getHomepage(), "de"));

      List<Politiker> fraktionsMitglieder = f.getMitglieder();
      if (!fraktionsMitglieder.isEmpty()) {
        for (Politiker p : fraktionsMitglieder) {

          Resource politikerResource =
              allrisModel.createResource(this.getVerfasserUri(p.getName()));
          politikerResource.addProperty(subject, allrisModel.createProperty(p.getUri()));
          if (p.getName() != null) {
            politikerResource.addProperty(RDFS.label, allrisModel.createLiteral(p.getName(), "de"));
            politikerResource.addProperty(name, allrisModel.createLiteral(p.getName(), "de"));
          }
          politikerResource.addProperty(RDF.type, politikerClass);

          if (p.getArt() != null)
            politikerResource.addProperty(
                politikerArt, allrisModel.createLiteral(p.getArt(), "de"));
        }
      }
    }

    return allrisModel;
  }
  public static void main(String[] args) {

    List<String> obj = new ArrayList<String>();

    Scanner input = new Scanner(System.in);

    System.out.print("Enter URI: ");

    String userIn = input.nextLine();

    // create an empty Model
    Model model = ModelFactory.createDefaultModel();

    // read the RDF/XML file
    model.read(userIn);

    // write it to standard out
    // model.write(System.out);

    // list the statements in the Model
    StmtIterator iter = model.listStatements();

    System.out.println();

    // print out the predicate, subject and object of each statement
    while (iter.hasNext()) {
      Statement stmt = iter.nextStatement(); // get next statement
      Resource subject = stmt.getSubject(); // get the subject
      Property predicate = stmt.getPredicate(); // get the predicate
      RDFNode object = stmt.getObject(); // get the object

      System.out.print(subject.toString());
      System.out.print(" -> " + predicate.toString() + " -> ");
      if (object instanceof Resource) {
        System.out.print(object.toString() + "\n");
      } else {
        // object is a literal
        System.out.print(" \"" + object.toString() + "\"\n");
      }
    }

    /* for(int i = 0; i < (obj.size()); i++){

    	String sparqlQueryString1=
    								"SELECT ?s ?o "+
    								"WHERE {"+
    								"?s ?p ?o ."+
    								"?o <bif:contains> \""+obj.get(i)+"\" ."+
    								"}"+
    								"limit 10";

    		      Query query = QueryFactory.create(sparqlQueryString1);
    		      QueryExecution qexec = QueryExecutionFactory.sparqlService("http://pubmed.bio2rdf.org/sparql", query);

    		      ResultSet results = qexec.execSelect();
    		      System.out.println("Query: "+obj.get(i));
    		      ResultSetFormatter.out(System.out, results, query);

    		     qexec.close() ;
    } */

  }
  // renames percentage properties and classes
  // activeProperties -> if true, then rename properties
  // activeClasses -> if true, then rename classes
  public OntModel renameResource(
      boolean activeProperties,
      boolean activeClasses,
      float percentage,
      boolean activeRandomString,
      boolean activeTranslateString,
      boolean activeSynonym,
      int activeStringOperation) {
    List<Statement> statements = null; // the list of all statements
    HashMap<String, String> propertiesIdentifiers =
        null; // the HashMap of the properties identifiers
    HashMap<String, String> classesIdentifiers = null; // the HashMap of the classes identifiers

    OntModel newModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); // create new Model
    // get properties and classes identifiers
    if (activeProperties)
      propertiesIdentifiers =
          getPropertiesIdentifiers(
              percentage,
              activeRandomString,
              activeTranslateString,
              activeSynonym,
              activeStringOperation);
    if (activeClasses)
      classesIdentifiers =
          getClassesIdentifiers(
              percentage,
              activeRandomString,
              activeTranslateString,
              activeSynonym,
              activeStringOperation);

    // iterate and modify the identifiers
    for (Statement stm : modifiedModel.listStatements().toList()) {

      Resource subject = stm.getSubject(); // the subject
      Property predicate = stm.getPredicate(); // the predicate
      RDFNode object = stm.getObject(); // the object

      boolean isPred, isSubj, isObj;
      isPred = isSubj = isObj = false;

      String subjuri = subject.getURI();
      String subjectLocalName = getLocalName(subjuri);
      Resource subj = null;
      // if it is the subject of the statement
      if (subjectLocalName != null) {
        String subjectNameSpace = getNameSpace(subjuri);
        if (activeProperties) {
          if (propertiesIdentifiers.containsKey(subjectLocalName)) {
            // if the namespace of the subject is the same as the namespace of the property
            // identifier
            if (subjectNameSpace.equals(modifiedOntologyNS)) { // that we want to remove
              isSubj = true;
              subj =
                  newModel.createResource(
                      subjectNameSpace + propertiesIdentifiers.get(subjectLocalName));
            }
          }
        }

        if (activeClasses) {
          if (classesIdentifiers.containsKey(subjectLocalName)) {
            // if the namespace of the subject is the same as the namespace of the property
            // identifier
            // that we want to remove
            if (subjectNameSpace.equals(modifiedOntologyNS)) {
              isSubj = true;
              subj =
                  newModel.createResource(
                      subjectNameSpace + classesIdentifiers.get(subjectLocalName));
            }
          }
        }
      }

      // if it is the predicate of the statement
      String preduri = predicate.getURI();
      String predicateLocalName = getLocalName(preduri);
      String predicateNameSpace = getNameSpace(preduri);
      Property pred = null;
      if (activeProperties) {
        if (propertiesIdentifiers.containsKey(predicateLocalName)) {
          // if the namespace of the predicate is the same as the namespace of the property
          // identifier
          // that we want to remove
          if (predicateNameSpace.equals(modifiedOntologyNS)) {
            isPred = true;
            pred =
                newModel.createProperty(
                    predicateNameSpace, propertiesIdentifiers.get(predicateLocalName));
          }
        }
      }

      if (activeClasses) {
        if (classesIdentifiers.containsKey(predicateLocalName)) {
          // if the namespace of the predicate is the same as the namespace of the property
          // identifier
          // that we want to remove
          if (predicateNameSpace.equals(modifiedOntologyNS)) {
            isPred = true;
            pred =
                newModel.createProperty(
                    predicateNameSpace, classesIdentifiers.get(predicateLocalName));
          }
        }
      }

      Resource obj = null;
      // if it is the object of the statement
      if (object.canAs(Resource.class))
        if (object.isURIResource()) {
          String uri = object.asResource().getURI();
          String objectLocalName = getLocalName(uri);
          String objectNameSpace = getNameSpace(uri);
          if (activeProperties) {
            if (propertiesIdentifiers.containsKey(objectLocalName)) {
              // if the namespace of the object is the same as the namespace of the property
              // identifier
              // that we want to remove
              if (objectNameSpace.equals(modifiedOntologyNS)) {
                isObj = true;
                obj =
                    newModel.createResource(
                        objectNameSpace + propertiesIdentifiers.get(objectLocalName));
              }
            }
          }

          if (activeClasses) {
            if (classesIdentifiers.containsKey(objectLocalName)) {
              // if the namespace of the object is the same as the namespace of the property
              // identifier that we want to remove
              if (objectNameSpace.equals(modifiedOntologyNS)) {
                isObj = true;
                obj =
                    newModel.createResource(
                        objectNameSpace + classesIdentifiers.get(objectLocalName));
              }
            }
          }
        }

      if (isSubj) {
        if (isPred) {
          if (isObj) newModel.add(subj, pred, obj);
          else newModel.add(subj, pred, object);
        } else {
          if (isObj) newModel.add(subj, predicate, obj);
          else newModel.add(subj, predicate, object);
        }
      } else {
        if (isPred) {
          if (isObj) newModel.add(subject, pred, obj);
          else newModel.add(subject, pred, object);
        } else {
          if (isObj) newModel.add(subject, predicate, obj);
          else newModel.add(subject, predicate, object);
        }
      }
    }
    if (activeClasses) {
      buildClassHierarchy();
      // we update the class hierarchy according to the new modifications
      classHierarchy.updateClassHierarchy(alignment);
      // classHierarchy.printClassHierarchy();
    }
    return newModel;
  }