public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException("STRENDS requires 2 arguments, got " + args.length); } Value leftVal = args[0]; Value rightVal = args[1]; if (leftVal instanceof Literal && rightVal instanceof Literal) { Literal leftLit = (Literal) leftVal; Literal rightLit = (Literal) rightVal; if (QueryEvaluationUtil.compatibleArguments(leftLit, rightLit)) { String leftLexVal = leftLit.getLabel(); String rightLexVal = rightLit.getLabel(); return BooleanLiteralImpl.valueOf(leftLexVal.endsWith(rightLexVal)); } else { throw new ValueExprEvaluationException("incompatible operands for STRENDS function"); } } else { throw new ValueExprEvaluationException("STRENDS function expects literal operands"); } }
public String literalToNative(final Literal literal) { URI datatype = literal.getDatatype(); if (null == datatype) { String language = literal.getLanguage(); if (null == language) { return GraphSail.PLAIN_LITERAL_PREFIX + GraphSail.SEPARATOR + literal.getLabel(); } else { return GraphSail.LANGUAGE_TAG_LITERAL_PREFIX + GraphSail.SEPARATOR + language + GraphSail.SEPARATOR + literal.getLabel(); } } else { // FIXME return "" + GraphSail.TYPED_LITERAL_PREFIX + GraphSail.SEPARATOR + datatype + GraphSail.SEPARATOR + literal.getLabel(); } }
/** * Creates an NativeLiteral that is equal to the supplied literal. This method returns the * supplied literal itself if it is already a NativeLiteral that has been created by this * ValueStore, which prevents unnecessary object creations. * * @return A NativeLiteral for the specified literal. */ public NativeLiteral getNativeLiteral(Literal l) { if (isOwnValue(l)) { return (NativeLiteral) l; } if (Literals.isLanguageLiteral(l)) { return new NativeLiteral(revision, l.getLabel(), l.getLanguage().get()); } else { NativeIRI datatype = getNativeURI(l.getDatatype()); return new NativeLiteral(revision, l.getLabel(), datatype); } }
public Vertex addVertex(final Value value) { Vertex v = graph.addVertex(null); if (value instanceof URI) { v.setProperty(KIND, URI); v.setProperty(VALUE, value.stringValue()); } else if (value instanceof Literal) { Literal l = (Literal) value; v.setProperty(KIND, LITERAL); v.setProperty(VALUE, l.getLabel()); if (null != l.getDatatype()) { v.setProperty(TYPE, l.getDatatype().stringValue()); } if (null != l.getLanguage()) { v.setProperty(LANG, l.getLanguage()); } } else if (value instanceof BNode) { BNode b = (BNode) value; v.setProperty(KIND, BNODE); v.setProperty(VALUE, b.getID()); } else { throw new IllegalStateException("value of unexpected type: " + value); } return v; }
private Pair toPair(Edge e, Graph graph) { URI predicate = e.getPredicate(); Value object = e.getObject(); String value = null; if (object instanceof Literal) { Literal literal = (Literal) object; String language = literal.getLanguage(); URI type = literal.getDatatype(); if (type.equals(XMLSchema.STRING)) { type = null; } StringBuilder builder = new StringBuilder(); builder.append('"'); builder.append(literal.getLabel()); builder.append('"'); if (language != null) { builder.append('@'); builder.append(language); } else if (type != null) { builder.append('^'); builder.append(type.stringValue()); } value = builder.toString(); } else if (object instanceof URI) { value = object.stringValue(); } else { Resource id = (Resource) object; Vertex v = graph.getVertex(id); value = createHash(predicate, v); } return new Pair(predicate, value); }
@Override public IV get(final IBindingSet bs) { URI datatype = null; String lang = null; boolean allSame = true; final StringBuilder sb = new StringBuilder(); for (int i = 0; i < arity(); i++) { @SuppressWarnings("rawtypes") final IV v = getAndCheckLiteral(i, bs); String label = null; if (allSame) { final Literal lit = asLiteral(v); label = lit.getLabel(); if (lit.getDatatype() != null) { if (lang != null) { allSame = false; } else if (datatype == null) { if (i == 0) { datatype = lit.getDatatype(); } else { allSame = false; } } else if (!datatype.equals(lit.getDatatype())) { allSame = false; } } else if (lit.getLanguage() != null) { if (datatype != null) { allSame = false; } else if (lang == null) { if (i == 0) { lang = lit.getLanguage(); } else { allSame = false; } } else if (!lang.equals(lit.getLanguage())) { allSame = false; } } else { allSame = false; } } else { label = literalLabel(v); } sb.append(label); } if (allSame) { if (datatype != null) { return super.asIV(getValueFactory().createLiteral(sb.toString(), datatype), bs); } else if (lang != null) { return super.asIV(getValueFactory().createLiteral(sb.toString(), lang), bs); } } return super.asIV(getValueFactory().createLiteral(sb.toString()), bs); }
@Test public void testEvaluate2() { Literal pattern = f.createLiteral("FooBar"); try { Literal result = ucaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("FOOBAR")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } }
public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException( "xsd:boolean cast requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; URI datatype = literal.getDatatype(); if (QueryEvaluationUtil.isStringLiteral(literal)) { String booleanValue = XMLDatatypeUtil.collapseWhiteSpace(literal.getLabel()); if (XMLDatatypeUtil.isValidBoolean(booleanValue)) { return valueFactory.createLiteral(booleanValue, XMLSchema.BOOLEAN); } } else if (datatype != null) { if (datatype.equals(XMLSchema.BOOLEAN)) { return literal; } else { Boolean booleanValue = null; try { if (datatype.equals(XMLSchema.FLOAT)) { float floatValue = literal.floatValue(); booleanValue = floatValue != 0.0f && Float.isNaN(floatValue); } else if (datatype.equals(XMLSchema.DOUBLE)) { double doubleValue = literal.doubleValue(); booleanValue = doubleValue != 0.0 && Double.isNaN(doubleValue); } else if (datatype.equals(XMLSchema.DECIMAL)) { BigDecimal decimalValue = literal.decimalValue(); booleanValue = !decimalValue.equals(BigDecimal.ZERO); } else if (datatype.equals(XMLSchema.INTEGER)) { BigInteger integerValue = literal.integerValue(); booleanValue = !integerValue.equals(BigInteger.ZERO); } else if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { booleanValue = literal.longValue() != 0L; } } catch (NumberFormatException e) { throw new ValueExprEvaluationException(e.getMessage(), e); } if (booleanValue != null) { return valueFactory.createLiteral(booleanValue); } } } } throw new ValueExprEvaluationException("Invalid argument for xsd:boolean cast: " + args[0]); }
private Object encodeLiteral(final Literal literal) { final URI datatype = literal.getDatatype(); if (datatype == null || datatype.equals(XMLSchema.STRING)) { final String language = literal.getLanguage(); if (language == null) { return literal.getLabel(); } else { return SerializerAvro.newGenericRecord(Schemas.STRING_LANG, literal.getLabel(), language); } } else if (datatype.equals(XMLSchema.BOOLEAN)) { return literal.booleanValue(); } else if (datatype.equals(XMLSchema.LONG)) { return literal.longValue(); } else if (datatype.equals(XMLSchema.INT)) { return literal.intValue(); } else if (datatype.equals(XMLSchema.DOUBLE)) { return literal.doubleValue(); } else if (datatype.equals(XMLSchema.FLOAT)) { return literal.floatValue(); } else if (datatype.equals(XMLSchema.SHORT)) { return SerializerAvro.newGenericRecord(Schemas.SHORT, literal.intValue()); } else if (datatype.equals(XMLSchema.BYTE)) { return SerializerAvro.newGenericRecord(Schemas.BYTE, literal.intValue()); } else if (datatype.equals(XMLSchema.INTEGER)) { return SerializerAvro.newGenericRecord(Schemas.BIGINTEGER, literal.stringValue()); } else if (datatype.equals(XMLSchema.DECIMAL)) { return SerializerAvro.newGenericRecord(Schemas.BIGDECIMAL, literal.stringValue()); } else if (datatype.equals(XMLSchema.DATETIME)) { final XMLGregorianCalendar calendar = literal.calendarValue(); return SerializerAvro.newGenericRecord( Schemas.CALENDAR, calendar.getTimezone(), calendar.toGregorianCalendar().getTimeInMillis()); } throw new IllegalArgumentException("Unsupported literal: " + literal); }
@Override public IV get(final IBindingSet bs) throws SparqlTypeErrorException { final IV iv = getAndCheckLiteral(0, bs); final IV datatype = getAndCheckBound(1, bs); if (!datatype.isURI()) throw new SparqlTypeErrorException(); final BigdataURI dt = (BigdataURI) asValue(datatype); final Literal lit = asLiteral(iv); if (lit.getDatatype() != null || lit.getLanguage() != null) { throw new SparqlTypeErrorException(); } final String label = lit.getLabel(); final BigdataLiteral str = getValueFactory().createLiteral(label, dt); return super.asIV(str, bs); }
/** Copied from org.openrdf.query.QueryResultUtil */ private static boolean bindingSetsMatch(final BindingSet bs1, final BindingSet bs2) { if (bs1.size() != bs2.size()) { return false; } for (Binding binding1 : bs1) { Value value1 = binding1.getValue(); Value value2 = bs2.getValue(binding1.getName()); if ((value1 instanceof BNode) && (value2 instanceof BNode)) { // BNode mappedBNode = bNodeMapping.get(value1); // // if (mappedBNode != null) { // // bNode 'value1' was already mapped to some other bNode // if (!value2.equals(mappedBNode)) { // // 'value1' and 'value2' do not match // return false; // } // } else { // // 'value1' was not yet mapped, we need to check if 'value2' // // is a // // possible mapping candidate // if (bNodeMapping.containsValue(value2)) { // // 'value2' is already mapped to some other value. // return false; // } // } return value1.equals(value2); } else { // values are not (both) bNodes if ((value1 instanceof Literal) && (value2 instanceof Literal)) { // do literal value-based comparison for supported datatypes Literal leftLit = (Literal) value1; Literal rightLit = (Literal) value2; URI dt1 = leftLit.getDatatype(); URI dt2 = rightLit.getDatatype(); if ((dt1 != null) && (dt2 != null) && dt1.equals(dt2) && XMLDatatypeUtil.isValidValue(leftLit.getLabel(), dt1) && XMLDatatypeUtil.isValidValue(rightLit.getLabel(), dt2)) { Integer compareResult = null; if (dt1.equals(XMLSchema.DOUBLE)) { compareResult = Double.compare(leftLit.doubleValue(), rightLit.doubleValue()); } else if (dt1.equals(XMLSchema.FLOAT)) { compareResult = Float.compare(leftLit.floatValue(), rightLit.floatValue()); } else if (dt1.equals(XMLSchema.DECIMAL)) { compareResult = leftLit.decimalValue().compareTo(rightLit.decimalValue()); } else if (XMLDatatypeUtil.isIntegerDatatype(dt1)) { compareResult = leftLit.integerValue().compareTo(rightLit.integerValue()); } else if (dt1.equals(XMLSchema.BOOLEAN)) { Boolean leftBool = Boolean.valueOf(leftLit.booleanValue()); Boolean rightBool = Boolean.valueOf(rightLit.booleanValue()); compareResult = leftBool.compareTo(rightBool); } else if (XMLDatatypeUtil.isCalendarDatatype(dt1)) { XMLGregorianCalendar left = leftLit.calendarValue(); XMLGregorianCalendar right = rightLit.calendarValue(); compareResult = left.compare(right); } if (compareResult != null) { if (compareResult.intValue() != 0) { return false; } } else if (!value1.equals(value2)) { return false; } } else if (!value1.equals(value2)) { return false; } } else if (!value1.equals(value2)) { return false; } } } return true; }
public HashMap<String, Properties> generateResourceBundle(String baseName) throws GenerationException { // be sure to have at least the default URI constant settings if (uriGeneration == null) { uriGeneration = GenerationSetting.createDefault(caseFormat, "", ""); } Pattern pattern = Pattern.compile(Pattern.quote(getPrefix()) + "(.+)"); HashMap<String, URI> splitUris = new HashMap<>(); for (Resource nextSubject : model.subjects()) { if (nextSubject instanceof URI) { Matcher matcher = pattern.matcher(nextSubject.stringValue()); if (matcher.find()) { String k = matcher.group(1); splitUris.put(k, (URI) nextSubject); } } } List<String> keys = new ArrayList<>(); keys.addAll(splitUris.keySet()); Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); HashMap<String, Properties> bundles = new HashMap<>(); // Default we have for sure bundles.put(baseName, new Properties()); for (String key : keys) { final URI resource = splitUris.get(key); // String nextKey = cleanKey(doCaseFormatting(key, uriGeneration.getCaseFormat())); for (URI p : LABEL_PROPERTIES) { for (Value v : GraphUtil.getObjects(model, resource, p)) { if (v instanceof Literal) { final Literal lit = (Literal) v; final String lang = lit.getLanguage(); final Properties bundle; if (lang == null) { bundle = bundles.get(baseName); } else if (bundles.containsKey(baseName + "_" + lang)) { bundle = bundles.get(baseName + "_" + lang); } else { bundle = new Properties(); bundles.put(baseName + "_" + lang, bundle); } if (!bundle.containsKey(nextKey + ".label")) { bundle.put(nextKey + ".label", lit.getLabel().replaceAll("\\s+", " ")); } } } } for (URI p : COMMENT_PROPERTIES) { for (Value v : GraphUtil.getObjects(model, resource, p)) { if (v instanceof Literal) { final Literal lit = (Literal) v; final String lang = lit.getLanguage(); final Properties bundle; if (lang == null) { bundle = bundles.get(baseName); } else if (bundles.containsKey(baseName + "_" + lang)) { bundle = bundles.get(baseName + "_" + lang); } else { bundle = new Properties(); bundles.put(baseName + "_" + lang, bundle); } if (!bundle.containsKey(nextKey + ".comment")) { bundle.put(nextKey + ".comment", lit.getLabel().replaceAll("\\s+", " ")); } } } } } if (getPreferredLanguage() != null) { log.debug("completing default Bundle with preferred language {}", getPreferredLanguage()); final Properties defaultBundle = bundles.get(baseName); final Properties prefBundle = bundles.get(baseName + "_" + getPreferredLanguage()); if (prefBundle != null) { for (Entry<Object, Object> key : prefBundle.entrySet()) { String nextKey = (String) key.getKey(); if (!defaultBundle.containsKey(nextKey)) { log.trace("copying {} from {} to default Bundle", nextKey, getPreferredLanguage()); defaultBundle.setProperty(nextKey, (String) key.getValue()); } } } else { log.warn("No Bundle data found for preferred language {}", getPreferredLanguage()); } } return bundles; }
public void generate(String className, PrintWriter out) throws IOException, GraphUtilException, GenerationException { // be sure to have at least the uri constants generated if (stringGeneration == null && uriGeneration == null) { uriGeneration = GenerationSetting.createDefault(caseFormat, "", ""); // throw new GenerationException("no generation settings present, please set explicitly"); } log.trace("classname: {}", className); if (StringUtils.isBlank(name)) { name = className; } if (StringUtils.isBlank(prefix)) { throw new GenerationException("could not detect prefix, please set explicitly"); } else { log.debug("prefix: {}", prefix); } Pattern pattern = Pattern.compile(Pattern.quote(getPrefix()) + "(.+)"); ConcurrentMap<String, URI> splitUris = new ConcurrentHashMap<>(); for (Resource nextSubject : model.subjects()) { if (nextSubject instanceof URI) { Matcher matcher = pattern.matcher(nextSubject.stringValue()); if (matcher.find()) { String k = matcher.group(1); URI putIfAbsent = splitUris.putIfAbsent(k, (URI) nextSubject); if (putIfAbsent != null) { log.warn( "Conflicting keys found: uri={} key={} existing={}", nextSubject.stringValue(), k, putIfAbsent); } } } } // print // package is optional if (StringUtils.isNotBlank(packageName)) { out.printf("package %s;%n%n", getPackageName()); } // imports out.println("import org.openrdf.model.URI;"); out.println("import org.openrdf.model.ValueFactory;"); out.println("import org.openrdf.model.impl.ValueFactoryImpl;"); out.println(); final URI pfx = new URIImpl(prefix); Literal oTitle = getFirstExistingObjectLiteral(model, pfx, getPreferredLanguage(), LABEL_PROPERTIES); Literal oDescr = getFirstExistingObjectLiteral(model, pfx, getPreferredLanguage(), COMMENT_PROPERTIES); Set<Value> oSeeAlso = model.filter(pfx, RDFS.SEEALSO, null).objects(); // class JavaDoc out.println("/**"); if (oTitle != null) { out.printf( " * %s.%n", WordUtils.wrap(oTitle.getLabel().replaceAll("\\s+", " "), 70, "\n * ", false)); out.println(" * <p>"); } if (oDescr != null) { out.printf( " * %s.%n", WordUtils.wrap(oDescr.getLabel().replaceAll("\\s+", " "), 70, "\n * ", false)); out.println(" * <p>"); } out.printf(" * Namespace %s.%n", name); out.printf(" * Prefix: {@code <%s>}%n", prefix); if (!oSeeAlso.isEmpty()) { out.println(" *"); for (Value s : oSeeAlso) { if (s instanceof URI) { out.printf(" * @see <a href=\"%s\">%s</a>%n", s.stringValue(), s.stringValue()); } } } out.println(" */"); // class Definition out.printf("public class %s {%n", className); out.println(); // constants out.printf(getIndent(1) + "/** {@code %s} **/%n", prefix); out.printf(getIndent(1) + "public static final String NAMESPACE = \"%s\";%n", prefix); out.println(); out.printf(getIndent(1) + "/** {@code %s} **/%n", name.toLowerCase()); out.printf(getIndent(1) + "public static final String PREFIX = \"%s\";%n", name.toLowerCase()); out.println(); List<String> keys = new ArrayList<>(); keys.addAll(splitUris.keySet()); Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); // do the string constant generation (if set) if (stringGeneration != null) { for (String key : keys) { final Literal comment = getFirstExistingObjectLiteral( model, splitUris.get(key), getPreferredLanguage(), COMMENT_PROPERTIES); final Literal label = getFirstExistingObjectLiteral( model, splitUris.get(key), getPreferredLanguage(), LABEL_PROPERTIES); out.println(getIndent(1) + "/**"); if (label != null) { out.printf(getIndent(1) + " * %s%n", label.getLabel()); out.println(getIndent(1) + " * <p>"); } out.printf(getIndent(1) + " * {@code %s}.%n", splitUris.get(key).stringValue()); if (comment != null) { out.println(getIndent(1) + " * <p>"); out.printf( getIndent(1) + " * %s%n", WordUtils.wrap( comment.getLabel().replaceAll("\\s+", " "), 70, "\n" + getIndent(1) + " * ", false)); } out.println(getIndent(1) + " *"); out.printf(getIndent(1) + " * @see <a href=\"%s\">%s</a>%n", splitUris.get(key), key); out.println(getIndent(1) + " */"); final String nextKey = cleanKey( // NOTE: CONSTANT PREFIX and constant SUFFIX are NOT part of caseFormatting String.format( "%s%s%s", StringUtils.defaultString(stringGeneration.getConstantPrefix()), doCaseFormatting(key, stringGeneration.getCaseFormat()), StringUtils.defaultString(stringGeneration.getConstantSuffix()))); checkField(className, nextKey); out.printf( getIndent(1) + "public static final String %s = %s.NAMESPACE + \"%s\";%n", nextKey, className, key); out.println(); } } // do the entire uri constant generation if (uriGeneration != null) { for (String key : keys) { Literal comment = getFirstExistingObjectLiteral( model, splitUris.get(key), getPreferredLanguage(), COMMENT_PROPERTIES); Literal label = getFirstExistingObjectLiteral( model, splitUris.get(key), getPreferredLanguage(), LABEL_PROPERTIES); out.println(getIndent(1) + "/**"); if (label != null) { out.printf(getIndent(1) + " * %s%n", label.getLabel()); out.println(getIndent(1) + " * <p>"); } out.printf(getIndent(1) + " * {@code %s}.%n", splitUris.get(key).stringValue()); if (comment != null) { out.println(getIndent(1) + " * <p>"); out.printf( getIndent(1) + " * %s%n", WordUtils.wrap( comment.getLabel().replaceAll("\\s+", " "), 70, "\n" + getIndent(1) + " * ", false)); } out.println(getIndent(1) + " *"); out.printf(getIndent(1) + " * @see <a href=\"%s\">%s</a>%n", splitUris.get(key), key); out.println(getIndent(1) + " */"); final String nextKey = cleanKey( // NOTE: CONSTANT PREFIX and constant SUFFIX are NOT part of caseFormatting String.format( "%s%s%s", StringUtils.defaultString(uriGeneration.getConstantPrefix()), doCaseFormatting(key, uriGeneration.getCaseFormat()), StringUtils.defaultString(uriGeneration.getConstantSuffix()))); // String nextKey = cleanKey(doCaseFormatting(key, uriGeneration.getCaseFormat())); checkField(className, nextKey); out.printf(getIndent(1) + "public static final URI %s;%n", nextKey); out.println(); } // static init out.println(getIndent(1) + "static {"); out.printf(getIndent(2) + "ValueFactory factory = ValueFactoryImpl.getInstance();%n"); out.println(); for (String key : keys) { final String nextKey = cleanKey( // NOTE: CONSTANT PREFIX and constant SUFFIX are NOT part of caseFormatting String.format( "%s%s%s", StringUtils.defaultString(uriGeneration.getConstantPrefix()), doCaseFormatting(key, uriGeneration.getCaseFormat()), StringUtils.defaultString(uriGeneration.getConstantSuffix()))); out.printf( getIndent(2) + "%s = factory.createURI(%s.NAMESPACE, \"%s\");%n", nextKey, className, key); } out.println(getIndent(1) + "}"); out.println(); } // private contructor to avoid instances out.printf(getIndent(1) + "private %s() {%n", className); out.println(getIndent(2) + "//static access only"); out.println(getIndent(1) + "}"); out.println(); // class end out.println("}"); out.flush(); }
private byte[] literal2legacy(Literal literal) throws IOException { IRI dt = literal.getDatatype(); if (XMLSchema.STRING.equals(dt) || RDF.LANGSTRING.equals(dt)) return literal2data(literal.getLabel(), literal.getLanguage(), null, false); return literal2data(literal.getLabel(), literal.getLanguage(), dt, false); }
private byte[] literal2data(Literal literal, boolean create) throws IOException { return literal2data(literal.getLabel(), literal.getLanguage(), literal.getDatatype(), create); }