Exemple #1
0
    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;
    }
 @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);
 }
Exemple #3
0
    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();
      }
    }
Exemple #4
0
  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);
  }
  /**
   * 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 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 Value copy(Value value) {
   if (value instanceof IRI) {
     return createIRI(value.stringValue());
   } else if (value instanceof Literal) {
     Literal lit = (Literal) value;
     if (Literals.isLanguageLiteral(lit)) {
       return createLiteral(value.stringValue(), lit.getLanguage().orElse(null));
     } else {
       return createLiteral(value.stringValue(), lit.getDatatype());
     }
   } else {
     return createBNode(value.stringValue());
   }
 }
  private RDFValueRange fillObjectRange(Value oVal) {
    if (oVal instanceof URI) {
      URI uri = (URI) oVal;
      PrefixRange pr = new PrefixRange();
      pr.getPrefixList().add(uri.stringValue());

      return new RDFValueRange(
          new RDFURIRange(pr.getPrefixList()),
          new RDFLiteralRange(Collections.<URI, RangeLength<?>>emptyMap()));
    } else if (oVal instanceof Literal) {
      Literal l = (Literal) oVal;
      Range literalRange = null;

      if (l.getDatatype().equals(XMLSchema.INT))
        literalRange =
            new RDFLiteralRange(XMLSchema.INT, new IntervalRange(l.intValue(), l.intValue()));
      else if (l.getDatatype().equals(XMLSchema.LONG))
        literalRange =
            new RDFLiteralRange(
                XMLSchema.LONG, new IntervalRange((int) l.longValue(), (int) l.longValue()));
      else if (l.getDatatype().equals(XMLSchema.STRING)) {
        PrefixRange pr = new PrefixRange();
        pr.getPrefixList().add(l.stringValue());
        literalRange = new RDFLiteralRange(XMLSchema.STRING, pr);
      } else if (l.getDatatype().equals(XMLSchema.DATETIME)) {
        Calendar cal = l.calendarValue().toGregorianCalendar();
        CalendarRange cr = new CalendarRange(cal.getTime(), cal.getTime());
        literalRange = new RDFLiteralRange(XMLSchema.DATETIME, cr);
      }

      if (literalRange != null)
        return new RDFValueRange(
            new RDFURIRange(Collections.<String>emptyList()), (RDFLiteralRange) literalRange);
    }

    return new RDFValueRange();
  }
Exemple #9
0
  @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);
  }
 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);
 }
  /** 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;
  }
Exemple #12
0
 /**
  * Implementation using the org.json API.
  *
  * @param graph A Sesame Graph.
  * @return An RDF/JSON string if successful, otherwise null.
  */
 public static String graphToRdfJson(Graph graph) {
   JSONObject result = new JSONObject();
   try {
     Set<Resource> subjects = new HashSet<Resource>();
     for (Statement s1 : graph) {
       subjects.add(s1.getSubject());
     }
     for (Resource subject : subjects) {
       JSONObject predicateObj = new JSONObject();
       Set<URI> predicates = new HashSet<URI>();
       Iterator<Statement> s2 = graph.match(subject, null, null);
       while (s2.hasNext()) {
         predicates.add(s2.next().getPredicate());
       }
       for (URI predicate : predicates) {
         JSONArray valueArray = new JSONArray();
         Iterator<Statement> stmnts = graph.match(subject, predicate, null);
         Set<Value> objects = new HashSet<Value>();
         while (stmnts.hasNext()) {
           objects.add(stmnts.next().getObject());
         }
         for (Value object : objects) {
           Iterator<Statement> stmnts2 = graph.match(subject, predicate, object);
           JSONArray contexts = new JSONArray();
           int i = 0;
           boolean nonDefaultContext = false;
           while (stmnts2.hasNext()) {
             Resource context = stmnts2.next().getContext();
             contexts.put(i, null == context ? null : context.toString());
             if (null != context) {
               nonDefaultContext = true;
             }
             i++;
           }
           JSONObject valueObj = new JSONObject();
           valueObj.put("value", object.stringValue());
           if (object instanceof Literal) {
             valueObj.put("type", "literal");
             Literal l = (Literal) object;
             if (l.getLanguage() != null) {
               valueObj.put("lang", l.getLanguage());
             } else if (l.getDatatype() != null) {
               valueObj.put("datatype", l.getDatatype().stringValue());
             }
           } else if (object instanceof BNode) {
             valueObj.put("type", "bnode");
           } else if (object instanceof URI) {
             valueObj.put("type", "uri");
           }
           if (nonDefaultContext) {
             valueObj.put("graphs", contexts);
           }
           valueArray.put(valueObj);
         }
         predicateObj.put(predicate.stringValue(), valueArray);
       }
       result.put(subject.stringValue(), predicateObj);
     }
     return result.toString(2);
   } catch (JSONException e) {
     log.error(e.getMessage(), e);
   }
   return null;
 }
 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);
 }