Exemplo n.º 1
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;
  }
  /**
   * Builds a String result for Elastic Search from an RDFNode
   *
   * @param node An RDFNode representing the value of a property for a given resource
   * @return If the RDFNode has a Literal value, among Boolean, Byte, Double, Float, Integer Long,
   *     Short, this value is returned, converted to String
   *     <p>If the RDFNode has a String Literal value, this value will be returned, surrounded by
   *     double quotes
   *     <p>If the RDFNode has a Resource value (URI) and toDescribeURIs is set to true, the value
   *     of @getLabelForUri for the resource is returned, surrounded by double quotes. Otherwise,
   *     the URI will be returned
   */
  private String getStringForResult(RDFNode node, boolean getNodeLabel) {
    String result = "";
    boolean quote = false;

    if (node.isLiteral()) {
      Object literalValue = node.asLiteral().getValue();
      try {
        Class<?> literalJavaClass = node.asLiteral().getDatatype().getJavaClass();

        if (literalJavaClass.equals(Boolean.class)
            || Number.class.isAssignableFrom(literalJavaClass)) {

          result += literalValue;
        } else {
          result = EEASettings.parseForJson(node.asLiteral().getLexicalForm());
          quote = true;
        }
      } catch (java.lang.NullPointerException npe) {
        result = EEASettings.parseForJson(node.asLiteral().getLexicalForm());
        quote = true;
      }

    } else if (node.isResource()) {
      result = node.asResource().getURI();
      if (getNodeLabel) {
        result = getLabelForUri(result);
      }
      quote = true;
    }
    if (quote) {
      result = "\"" + result + "\"";
    }
    return result;
  }
Exemplo n.º 3
0
 /**
  * Answer the string described by the value of the unique optional <code>classProperty</code>
  * property of <code>root</code>, or null if there's no such property. The value may be a URI, in
  * which case it must be a <b>java:</b> URI with content the class name; or it may be a literal,
  * in which case its lexical form is its class name; otherwise, BOOM.
  */
 public static String getOptionalClassName(Resource root, Property classProperty) {
   RDFNode classNode = getUnique(root, classProperty);
   return classNode == null
       ? null
       : classNode.isLiteral()
           ? classNode.asNode().getLiteralLexicalForm()
           : classNode.isResource() ? mustBeJava(classNode.asNode().getURI()) : null;
 }
Exemplo n.º 4
0
  /**
   * Equals rdf.
   *
   * @param object the object
   * @return true, if successful
   */
  public boolean equalsRDF(RDFNode object) {
    // URI resources & properties
    if (object.isResource() && ((Resource) object).isURIResource()) {
      if (rdfNode.isResource() && ((Resource) rdfNode).isURIResource()) {
        if (((Resource) rdfNode).getURI().equals(((Resource) object).getURI())) return true;
        else return false;
      }
    }
    // bnode
    if (object.isAnon() && rdfNode.isAnon()) {
      if (((Resource) rdfNode).getId().equals(((Resource) object).getId())) return true;
      else return false;
    }
    // literal
    if (object.isLiteral() && rdfNode.isLiteral()) {
      if (((Literal) object).equals((rdfNode))
          || (((Literal) object).sameValueAs((Literal) rdfNode))) return true;
    }

    return false;
  }
 protected static void addRangeTypes(Model result, Model schema) {
   Model toAdd = ModelFactory.createDefaultModel();
   for (StmtIterator it = schema.listStatements(ANY, RDFS.range, ANY); it.hasNext(); ) {
     Statement s = it.nextStatement();
     RDFNode type = s.getObject();
     Property property = s.getSubject().as(Property.class);
     for (StmtIterator x = result.listStatements(ANY, property, ANY); x.hasNext(); ) {
       RDFNode ob = x.nextStatement().getObject();
       if (ob.isResource()) toAdd.add((Resource) ob, RDF.type, type);
     }
   }
   result.add(toAdd);
 }
Exemplo n.º 6
0
  /**
   * Create a JCR value from an RDF node with the given JCR type
   *
   * @param valueFactory
   * @param data
   * @param type
   * @return
   * @throws RepositoryException
   */
  public Value createValue(final ValueFactory valueFactory, final RDFNode data, final int type)
      throws RepositoryException {
    assert (valueFactory != null);

    if (data.isURIResource() && (type == REFERENCE || type == WEAKREFERENCE)) {
      // reference to another node (by path)
      final Node nodeFromGraphSubject =
          session.getNode(graphSubjects.getPathFromSubject(data.asResource()));
      return valueFactory.createValue(nodeFromGraphSubject, type == WEAKREFERENCE);
    } else if (data.isURIResource() || type == URI) {
      // some random opaque URI
      return valueFactory.createValue(data.toString(), PropertyType.URI);
    } else if (data.isResource()) {
      // a non-URI resource (e.g. a blank node)
      return valueFactory.createValue(data.toString(), UNDEFINED);
    } else if (data.isLiteral() && type == UNDEFINED) {
      // the JCR schema doesn't know what this should be; so introspect
      // the RDF and try to figure it out
      final Literal literal = data.asLiteral();
      final RDFDatatype dataType = literal.getDatatype();
      final Object rdfValue = literal.getValue();

      if (rdfValue instanceof Boolean) {
        return valueFactory.createValue((Boolean) rdfValue);
      } else if (rdfValue instanceof Byte
          || (dataType != null && dataType.getJavaClass() == Byte.class)) {
        return valueFactory.createValue(literal.getByte());
      } else if (rdfValue instanceof Double) {
        return valueFactory.createValue((Double) rdfValue);
      } else if (rdfValue instanceof Float) {
        return valueFactory.createValue((Float) rdfValue);
      } else if (rdfValue instanceof Long
          || (dataType != null && dataType.getJavaClass() == Long.class)) {
        return valueFactory.createValue(literal.getLong());
      } else if (rdfValue instanceof Short
          || (dataType != null && dataType.getJavaClass() == Short.class)) {
        return valueFactory.createValue(literal.getShort());
      } else if (rdfValue instanceof Integer) {
        return valueFactory.createValue((Integer) rdfValue);
      } else if (rdfValue instanceof XSDDateTime) {
        return valueFactory.createValue(((XSDDateTime) rdfValue).asCalendar());
      } else {
        return valueFactory.createValue(literal.getString(), STRING);
      }

    } else {
      LOGGER.debug("Using default JCR value creation for RDF literal: {}", data);
      return valueFactory.createValue(data.asLiteral().getString(), type);
    }
  }
 protected Set<ValueFactory> getValueFactory(RDFNode valueNode, OntModel displayOntModel) {
   // maybe use jenabean or owl2java for this?
   if (valueNode.isResource()) {
     Resource res = (Resource) valueNode.as(Resource.class);
     Statement stmt = res.getProperty(DisplayVocabulary.JAVA_CLASS_NAME);
     if (stmt == null || !stmt.getObject().isLiteral()) {
       log.debug("Cannot build value factory: java class was " + stmt.getObject());
       return Collections.emptySet();
     }
     String javaClassName = ((Literal) stmt.getObject().as(Literal.class)).getLexicalForm();
     if (javaClassName == null || javaClassName.length() == 0) {
       log.debug("Cannot build value factory: no java class was set.");
       return Collections.emptySet();
     }
     Class<?> clazz;
     Object newObj;
     try {
       clazz = Class.forName(javaClassName);
     } catch (ClassNotFoundException e) {
       log.debug("Cannot build value factory: no class found for " + javaClassName);
       return Collections.emptySet();
     }
     try {
       newObj = clazz.newInstance();
     } catch (Exception e) {
       log.debug(
           "Cannot build value factory: exception while creating object of java class "
               + javaClassName
               + " "
               + e.getMessage());
       return Collections.emptySet();
     }
     if (newObj instanceof ValueFactory) {
       ValueFactory valueFactory = (ValueFactory) newObj;
       return Collections.singleton(valueFactory);
     } else {
       log.debug(
           "Cannot build value factory: "
               + javaClassName
               + " does not implement "
               + ValueFactory.class.getName());
       return Collections.emptySet();
     }
   } else {
     log.debug("Cannot build value factory for " + valueNode);
     return Collections.emptySet();
   }
 }
Exemplo n.º 8
0
 @Override
 public Iterable<Vertex> getVertices() {
   final Set<Vertex> vertices = new HashSet<Vertex>();
   final StmtIterator statements = model.listStatements();
   while (statements.hasNext()) {
     final Statement statement = statements.next();
     final Resource resource = statement.getSubject();
     if (resource.isResource()) {
       vertices.add(new JenaVertex(model, resource));
     }
     final RDFNode object = statement.getObject();
     if (object.isResource()) {
       vertices.add(new JenaVertex(model, object));
     }
   }
   return vertices;
 }
  @SuppressWarnings("unchecked")
  public Set<S> getNegativeExamples(EvaluatedAxiom<T> axiom) {

    ResultSet rs = executeSelectQuery(negExamplesQueryTemplate.toString());

    Set<OWLObject> negExamples = new TreeSet<OWLObject>();

    while (rs.hasNext()) {
      RDFNode node = rs.next().get("s");
      if (node.isResource()) {
        negExamples.add(df.getOWLNamedIndividual(IRI.create(node.asResource().getURI())));
      } else if (node.isLiteral()) {
        negExamples.add(convertLiteral(node.asLiteral()));
      }
    }
    return (Set<S>) negExamples;
    //		throw new UnsupportedOperationException("Getting negative examples is not possible.");
  }
Exemplo n.º 10
0
 @Override
 public void nextTuple() {
   try {
     if (numOfReports < maxReports) {
       currTime = System.nanoTime();
       LOG.info(
           "startTime: "
               + startTime
               + " currTime: "
               + currTime
               + " interval: "
               + ((currTime - startTime) * 1e-6));
       if (((currTime - startTime) * 1e-6) >= interval) {
         if (query == null) query = QueryFactory.create(queryString);
         Store store = StoreFactory.getJenaHBaseStore(configFile, iri, isReified);
         int solnCount = 0;
         ResultSet rs = store.executeSelectQuery(query);
         List<Var> listVars = query.getProject().getVars();
         while (rs.hasNext()) {
           solnCount++;
           QuerySolution qs = rs.next();
           Object[] results = new String[listVars.size() + 1];
           if (solnCount == 1) results[0] = "new";
           else results[0] = "cont";
           for (int i = 1; i <= listVars.size(); i++) {
             Var var = listVars.get(i - 1);
             RDFNode value = qs.get(var.toString());
             if (value.isResource() || value.isAnon()) results[i] = value.asResource().toString();
             else if (value.isLiteral()) results[i] = value.asLiteral().toString();
           }
           collector.emit(new Values(results));
         }
         numOfReports += 1;
         startTime = currTime;
       }
       Thread.sleep(30000);
     }
   } catch (Exception e) {
     throw new TopologyException("Exception in query spout:: ", e);
   }
 }
Exemplo n.º 11
0
  /**
   * Checks if a given RDFNode represents a template call. It either needs to be an instance of an
   * instance of sh:Template, or be a typeless blank node that has an incoming edge via a property
   * such as sh:property, that has a declared sh:defaultType.
   *
   * @param node the node to check
   * @return true if node is a template call
   */
  public static boolean isTemplateCall(RDFNode node) {
    if (node != null && node.isResource()) {
      Resource resource = (Resource) node;

      // Return true if this has sh:Template as its metaclass
      for (Resource type : JenaUtil.getTypes(resource)) {
        if (JenaUtil.hasIndirectType(type, SH.Template)) {
          return true;
        }
      }

      // If this is a typeless blank node, check for defaultType of incoming references
      if (resource.isAnon() && !resource.hasProperty(RDF.type)) {
        Resource dt = SHACLUtil.getDefaultTemplateType(resource);
        if (dt != null
            && !SH.NativeConstraint.equals(dt)
            && !SH.NativeScope.equals(dt)
            && !SH.NativeRule.equals(dt)) {
          return true;
        }
      }
    }
    return false;
  }
Exemplo n.º 12
0
 /**
  * Gets the string.
  *
  * @param rdfNode the rdf node
  * @return the string
  */
 public static String getString(RDFNode rdfNode) {
   if (rdfNode.isURIResource())
     // return ((Resource)rdfNode).getURI();
     return ((Resource) rdfNode).getLocalName();
   else if (rdfNode.isResource()) return "  ";
   // ((Resource) rdfNode).getId().toString(); //
   else if (rdfNode.isLiteral()) {
     String label = ((Literal) rdfNode).toString();
     // if(label.length() > 10){ // TODO come back to this
     // label = "";
     // String[] split = label.split(" ");
     // for(int i=0;i<split.length;i++){
     // label = label + split[i] + " ";
     // if(label.length()>25) continue;
     // if(label.length() % 8 == 0) label = label +"\n";
     // }
     // }
     if (label.length() > 10) {
       label = label.substring(0, 9);
     }
     return label;
   }
   return null;
 }
Exemplo n.º 13
0
 /** Answer the resource at the end of the path, if defined, or null */
 public Resource getTerminalResource() {
   RDFNode n = getTerminal();
   return (n != null && n.isResource()) ? (Resource) n : null;
 }
  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");
      }
    }
  }
Exemplo n.º 15
0
 /**
  * Gets the uRI.
  *
  * @return the uRI
  */
 public String getURI() {
   if (rdfNode.isResource()) return ((Resource) rdfNode).getURI();
   return null;
 }
Exemplo n.º 16
0
 /* (non-Javadoc)
  * @see com.hp.hpl.jena.rdf.model.RDFNode#isResource()
  */
 @Override
 public boolean isResource() {
   return rdfNode.isResource();
 }