Java Code Examples for org.apache.jena.graph.Node#isLiteral()

The following examples show how to use org.apache.jena.graph.Node#isLiteral() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ParserProfileTurtleStarExtImpl.java    From RDFstarTools with Apache License 2.0 6 votes vote down vote up
@Override
protected void checkTriple(Node subject, Node predicate, Node object, long line, long col) {
	if ( subject == null
	     || (!subject.isURI() && 
	         !subject.isBlank() &&
	         !(subject instanceof Node_Triple)) ) {
    	getErrorHandler().error("Subject is not a URI, blank node, or triple", line, col);
        throw new RiotException("Bad subject: " + subject);
    }
    if ( predicate == null || (!predicate.isURI()) ) {
    	getErrorHandler().error("Predicate not a URI", line, col);
        throw new RiotException("Bad predicate: " + predicate);
    }
    if ( object == null
         || (!object.isURI() &&
             !object.isBlank() &&
             !object.isLiteral() &&
             !(object instanceof Node_Triple)) ) {
    	getErrorHandler().error("Object is not a URI, blank node, literal, or triple", line, col);
        throw new RiotException("Bad object: " + object);
    }
}
 
Example 2
Source File: TrimValidator.java    From rdflint with MIT License 6 votes vote down vote up
@Override
public List<LintProblem> validateTriple(Node subject, Node predicate, Node object,
    int beginLine, int beginCol, int endLine, int endCol) {
  List<LintProblem> rtn = new LinkedList<>();

  if (object.isLiteral()) {
    String s = object.getLiteralValue().toString();
    if (!s.equals(s.trim())) {
      rtn.add(new LintProblem(ErrorLevel.WARN,
          this,
          new LintProblemLocation(beginLine, beginCol, endLine, endCol,
              new Triple(subject, predicate, object)),
          "needTrimLiteral", s));
    }
  }
  return rtn;
}
 
Example 3
Source File: IsValidForDatatypeFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeValue exec(Node literalNode, Node datatypeNode, FunctionEnv env) {
	
	if(literalNode == null || !literalNode.isLiteral()) {
		throw new ExprEvalException();
	}
	String lex = literalNode.getLiteralLexicalForm();
	
	if(!datatypeNode.isURI()) {
		throw new ExprEvalException();
	}
	RDFDatatype datatype = TypeMapper.getInstance().getTypeByName(datatypeNode.getURI());
	
	if(datatype == null) {
		return NodeValue.TRUE;
	}
	else {
		boolean valid = datatype.isValid(lex);
		return NodeValue.makeBoolean(valid);
	}
}
 
Example 4
Source File: CheckRegexSyntaxFunction.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
protected NodeValue exec(Node regexNode, FunctionEnv env) {
	if(regexNode == null || !regexNode.isLiteral()) {
		return NodeValue.makeString("Invalid argument to spif:checkRegexSyntax: " + regexNode);
	}
	else {
		String str = regexNode.getLiteralLexicalForm();
		try {
			Pattern.compile(str);
		}
		catch(Exception ex) {
			return NodeValue.makeString(ex.getMessage());
		}
		throw new ExprEvalException(); // OK
	}
}
 
Example 5
Source File: TermFactory.java    From shacl with Apache License 2.0 6 votes vote down vote up
public JSTerm term(String str) {
       Node n;
       try {
       	n = NodeFactoryExtra.parseNode(str, pm);
       }
       catch(Exception ex) {
       	throw new IllegalArgumentException("Cannot parse node \"" + str + "\"", ex);
       }
       if(n.isURI()) {
       	return new JSNamedNode(n);
       }
       else if(n.isLiteral()) {
       	return new JSLiteral(n);
       }
       else if(n.isBlank()) {
       	return new JSBlankNode(n);
       }
       else {
       	throw new IllegalArgumentException("Unexpected node type for " + n);
       }
}
 
Example 6
Source File: TriplesToRuleSystem.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * converts a {@link Node} into an {l@ink Expr}
 * @param n
 * @return
 */
protected Expr	toExpr(Node n) {
	if (n.isVariable()) {
		return new VariableExpr(n.getName());
	} else if (n.isURI()) {
		try {
			return new ConstantExpr(new URI(n.getURI()));
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	} else if (n.isLiteral()) {
		Literal l = (Literal) n;
		return new ConstantExpr(l.getValue());
	} else {
		throw new RuntimeException("Unsuported node type in query : "+n);
	}
}
 
Example 7
Source File: localname.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private QueryIterator execAllNodes(Var subjVar, Node nodeLocalname,  Binding input, ExecutionContext execCxt)
{
    if ( ! nodeLocalname.isVariable() )
    {
        if ( ! nodeLocalname.isLiteral() )
            // Not a variable, not a literal=> can't match
            return QueryIterNullIterator.create(execCxt) ;
    
        if( ! NodeUtils.isSimpleString(nodeLocalname) )
            return QueryIterNullIterator.create(execCxt) ;
    }
    
    //Set bindings = new HashSet() ;    // Use a Set if you want unique results. 
    List<Binding> bindings = new ArrayList<Binding>() ;   // Use a list if you want counting results. 
    Graph graph = execCxt.getActiveGraph() ;
    
    ExtendedIterator<Triple>iter = graph.find(Node.ANY, Node.ANY, Node.ANY) ;
    for ( ; iter.hasNext() ; )
    {
        Triple t = iter.next() ;
        slot(bindings, input, t.getSubject(),   subjVar, nodeLocalname) ;
        slot(bindings, input, t.getPredicate(), subjVar, nodeLocalname) ;
        slot(bindings, input, t.getObject(),    subjVar, nodeLocalname) ;
    }
    return new QueryIterPlainWrapper(bindings.iterator(), execCxt) ;
}
 
Example 8
Source File: IsValidLangTagFunction.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
protected NodeValue exec(Node arg, FunctionEnv env) {
	if(arg == null || !arg.isLiteral()) {
		throw new ExprEvalException("Argument must be a (string) literal");
	}
	return NodeValue.makeBoolean(LangTag.check(arg.getLiteralLexicalForm()));
}
 
Example 9
Source File: OWLClassPropertyMetadataPlugin.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public void init(ClassPropertyMetadata cpm, Node classNode, Graph graph) {
	ExtendedIterator<Triple> it = graph.find(classNode, RDFS.subClassOf.asNode(), Node.ANY);
	while(it.hasNext()) {
		Node superClass = it.next().getObject();
		if(superClass.isBlank() && graph.contains(superClass, OWL.onProperty.asNode(), cpm.getPredicate())) {
			if(cpm.getLocalRange() == null) {
				Node localRange = JenaNodeUtil.getObject(superClass, OWL.allValuesFrom.asNode(), graph);
				if(localRange != null) {
					cpm.setLocalRange(localRange);
					it.close();
					break;
				}
			}
			if(cpm.getMaxCount() == null) {
				Node maxCountNode = JenaNodeUtil.getObject(superClass, OWL.maxCardinality.asNode(), graph);
				if(maxCountNode == null) {
					maxCountNode = JenaNodeUtil.getObject(superClass, OWL.cardinality.asNode(), graph);
				}
				if(maxCountNode != null && maxCountNode.isLiteral()) {
					Object value = maxCountNode.getLiteralValue();
					if(value instanceof Number) {
						cpm.setMaxCount(((Number) value).intValue());
					}
				}
			}
		}
	}
}
 
Example 10
Source File: JSFactory.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static JSTerm asJSTerm(Node node) {
	if(node.isURI()) {
		return new JSNamedNode(node);
	}
	else if(node.isBlank()) {
		return new JSBlankNode(node);
	}
	else if(node.isLiteral()) {
		return new JSLiteral(node);
	}
	else {
		throw new IllegalArgumentException("Unsupported node type " + node);
	}
}
 
Example 11
Source File: Node2String.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
public static short getType(Node n)
{
if (n.isURI())
   {
   return TypeMap.IRI_ID;
   }
if (n.isBlank())
   {
   return TypeMap.BLANK_NODE_ID;
   }

if (n.isLiteral())
   {

   if (n.getLiteral().getDatatype() != null)
      {
      return TypeMap.getDatatypeType(n.getLiteralDatatypeURI());
      }
   else
      {
      String lang = n.getLiteralLanguage();
      if (lang != null && lang.length() > 0)
         {
         return TypeMap.getLanguageType(lang);
         }
      else
         {
         return TypeMap.SIMPLE_LITERAL_ID;
         }
      }
   }

throw new RdfStoreException("Unknown RDFterm");
}
 
Example 12
Source File: uppercase.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Override
public Node calc(Node node)
{
    if ( ! node.isLiteral() ) 
        return null ;
    String str = node.getLiteralLexicalForm().toUpperCase() ;
    return NodeFactory.createLiteral(str) ;
}
 
Example 13
Source File: DataTypeValidator.java    From rdflint with MIT License 4 votes vote down vote up
@Override
public List<LintProblem> validateTriple(Node subject, Node predicate, Node object,
    int beginLine, int beginCol, int endLine, int endCol) {
  List<LintProblem> rtn = new LinkedList<>();

  if (object.isLiteral()) {
    String value = object.getLiteralValue().toString();

    // check data type by guessedType
    DataType guessedType = dataTypeMap.get(predicate.getURI());
    DataType dataType = DataTypeUtils.guessDataType(value);
    if (!DataTypeUtils.isDataType(dataType, guessedType)) {
      rtn.add(new LintProblem(ErrorLevel.INFO, this,
          new LintProblemLocation(beginLine, beginCol, endLine, endCol,
              new Triple(subject, predicate, object)),
          "notmatchedGuessedDataType", guessedType, dataType));
    }

    // check data type by language
    String litLang = object.getLiteralLanguage();
    if (!DataTypeUtils.isLang(value, litLang)) {
      rtn.add(new LintProblem(ErrorLevel.INFO, this,
          new LintProblemLocation(beginLine, beginCol, endLine, endCol,
              new Triple(subject, predicate, object)),
          "notmatchedLanguageType", litLang, value));
    }

    // check computed outlier
    double[] ngValues = dataNgValues.get(predicate.getURI());
    if (ngValues != null && ngValues.length > 0) {
      try {
        double val = Double.parseDouble(value);
        boolean match = false;
        for (double v : ngValues) {
          if (v == val) {
            match = true;
          }
        }
        if (match) {
          rtn.add(new LintProblem(ErrorLevel.INFO, this,
              new LintProblemLocation(beginLine, beginCol, endLine, endCol,
                  new Triple(subject, predicate, object)),
              "predictedOutlier", val));
        }
      } catch (NumberFormatException ex) {
        // Invalid Number Format
      }
    }
  }
  return rtn;
}
 
Example 14
Source File: LogUtils.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public static Node compress(Node n) {
    if (n.isLiteral()) {
        n = NodeFactory.createLiteral(compress(n.getLiteralLexicalForm()), n.getLiteralLanguage(), n.getLiteralDatatype());
    }
    return n;
}
 
Example 15
Source File: ClassPropertyMetadata.java    From shacl with Apache License 2.0 4 votes vote down vote up
private void initFromShape(Node shape, Node systemPredicate, Graph graph) {
	ExtendedIterator<Triple> it = graph.find(shape, systemPredicate, Node.ANY);
	while(it.hasNext()) {
		Node propertyShape = it.next().getObject();
		if(!propertyShape.isLiteral()) {
			if(hasMatchingPath(propertyShape, graph)) {
				if(!graph.contains(propertyShape, SH.deactivated.asNode(), JenaDatatypes.TRUE.asNode())) {
					if(description == null) {
						description = JenaNodeUtil.getObject(propertyShape, SH.description.asNode(), graph);
					}
					if(editWidget == null) {
						editWidget = JenaNodeUtil.getObject(propertyShape, TOSH.editWidget.asNode(), graph);
					}
					if(localRange == null) {
						if(inverse) {
							// Maybe: support inverse ranges
						}
						else {
							localRange = SHACLUtil.walkPropertyShapesHelper(propertyShape, graph);
						}
					}
					if(maxCount == null) {
						Node maxCountNode = JenaNodeUtil.getObject(propertyShape, SH.maxCount.asNode(), graph);
						if(maxCountNode != null && maxCountNode.isLiteral()) {
							Object value = maxCountNode.getLiteralValue();
							if(value instanceof Number) {
								maxCount = ((Number) value).intValue();
							}
						}
					}
					if(name == null) {
						name = JenaNodeUtil.getObject(propertyShape, SH.name.asNode(), graph);
					}
					if(order == null) {
						order = JenaNodeUtil.getObject(propertyShape, SH.order.asNode(), graph);
					}
					if(viewWidget == null) {
						viewWidget = JenaNodeUtil.getObject(propertyShape, TOSH.viewWidget.asNode(), graph);
					}
				}
			}
		}
	}
}
 
Example 16
Source File: Node2String.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
public static String getString(Node n)
{
if (n.isURI())
   {
   return n.toString(false);
   }
else if (n.isBlank())
   {
   return Constants.PREFIX_BLANK_NODE + n.toString();
   }
else if (n.isLiteral())
   {
   String object;
   if (n.getLiteral().getDatatype() != null)
      {
      // mdb types handling //uri = n.getLiteralDatatypeURI();
      // object = n.getLiteral().toString(false);
      object = n.getLiteralLexicalForm();
      // object = n.getLiteralValue().toString();
      }
   else
      {
      String lang = n.getLiteralLanguage();
      if (lang != null && lang.length() > 0)
         {
         // mdb types
         // object = n.getLiteralValue() + Constants.LITERAL_LANGUAGE
         // + lang;
         object = n.getLiteralValue().toString();
         }
      else
         {
         // mdb datatype change
         // object = "\"" + n.getLiteralValue() + "\"";
         object = n.getLiteralValue().toString();
         }
      }
   return object;
   }
else
   {
   return "\"" + n.toString(false) + "\"";
   }
}