예제 #1
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);
  }
예제 #2
0
  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");
    }
  }
예제 #3
0
  public void tupleQuery()
      throws QueryEvaluationException, RepositoryException, MalformedQueryException {

    // /query repo
    // con.setNamespace("onto",
    // "<http://it.unibz.krdb/obda/ontologies/test/translation/onto2.owl#>");
    // System.out.println(con.getNamespaces().next().toString());
    String queryString =
        "PREFIX : \n<http://it.unibz.krdb/obda/ontologies/test/translation/onto2.owl#>\n "
            + "SELECT ?x ?y WHERE { ?x a :Person. ?x :age ?y } ";
    // String queryString =
    // "SELECT ?x ?y WHERE { ?x a onto:Person. ?x onto:age ?y } ";
    TupleQuery tupleQuery = (con).prepareTupleQuery(QueryLanguage.SPARQL, queryString);
    TupleQueryResult result = tupleQuery.evaluate();

    System.out.println(result.getBindingNames());

    while (result.hasNext()) {
      BindingSet bindingSet = result.next();
      Value valueOfX = bindingSet.getValue("x");
      Literal valueOfY = (Literal) bindingSet.getValue("y");
      System.out.println(valueOfX.stringValue() + ", " + valueOfY.floatValue());
    }
    result.close();
  }
예제 #4
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();
      }
    }
예제 #5
0
  /**
   * 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);
    }
  }
예제 #6
0
  @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());
    }
  }
예제 #7
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 Literal getOptionalObjectLiteral(
      Model model, Resource subject, URI predicate, String lang) {
    Set<Value> objects = GraphUtil.getObjects(model, subject, predicate);

    Literal result = null;

    for (Value nextValue : objects) {
      if (nextValue instanceof Literal) {
        final Literal literal = (Literal) nextValue;
        if (result == null || (lang != null && lang.equals(literal.getLanguage()))) {
          result = literal;
        }
      }
    }
    return result;
  }
예제 #9
0
 @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);
 }
예제 #10
0
  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]);
  }
예제 #11
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;
    }
예제 #12
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);
  }
예제 #13
0
  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();
  }
예제 #14
0
 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);
 }
예제 #15
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);
 }
예제 #16
0
 public static String literal(Literal l) {
   return literal(l.stringValue());
 }
예제 #17
0
  /** 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;
  }
예제 #18
0
  public void testIsLiteral() throws Exception {

    final BigdataSail sail = getSail();
    sail.initialize();
    final BigdataSailRepository repo = new BigdataSailRepository(sail);
    final BigdataSailRepositoryConnection cxn =
        (BigdataSailRepositoryConnection) repo.getConnection();
    cxn.setAutoCommit(false);

    try {

      final ValueFactory vf = sail.getValueFactory();

      URI A = vf.createURI("_:A");
      URI B = vf.createURI("_:B");
      URI X = vf.createURI("_:X");
      URI AGE = vf.createURI("_:AGE");
      Literal _25 = vf.createLiteral(25);
      Literal _45 = vf.createLiteral(45);

      cxn.add(A, RDF.TYPE, X);
      cxn.add(B, RDF.TYPE, X);
      cxn.add(A, AGE, _25);
      cxn.add(B, AGE, _45);

      /*
       * Note: The either flush() or commit() is required to flush the
       * statement buffers to the database before executing any operations
       * that go around the sail.
       */
      cxn.flush(); // commit();

      if (log.isInfoEnabled()) {
        log.info("\n" + sail.getDatabase().dumpStore());
      }

      {
        String query =
            "select ?s ?age "
                + "WHERE { "
                + "  ?s <"
                + RDF.TYPE
                + "> <"
                + X
                + "> . "
                + "  ?s <"
                + AGE
                + "> ?age . "
                + "  FILTER( isLiteral(?age) ) . "
                + "}";

        final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);

        if (log.isInfoEnabled()) {
          final TupleQueryResult result = tupleQuery.evaluate();
          log.info("results:");
          if (!result.hasNext()) {
            log.info("no results.");
          }
          while (result.hasNext()) {
            log.info(result.next());
          }
        }

        final TupleQueryResult result = tupleQuery.evaluate();

        Collection<BindingSet> solution = new LinkedList<BindingSet>();
        solution.add(
            createBindingSet(new Binding[] {new BindingImpl("s", A), new BindingImpl("age", _25)}));
        solution.add(
            createBindingSet(new Binding[] {new BindingImpl("s", B), new BindingImpl("age", _45)}));

        compare(result, solution);
      }

      {
        String query =
            "select ?s ?age "
                + "WHERE { "
                + "  ?s <"
                + RDF.TYPE
                + "> <"
                + X
                + "> . "
                + "  ?s <"
                + AGE
                + "> ?age . "
                + "  FILTER( isLiteral("
                + _25.toString()
                + ") ) . "
                + "}";

        final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);

        if (log.isInfoEnabled()) {
          final TupleQueryResult result = tupleQuery.evaluate();
          log.info("results:");
          if (!result.hasNext()) {
            log.info("no results.");
          }
          while (result.hasNext()) {
            log.info(result.next());
          }
        }

        final TupleQueryResult result = tupleQuery.evaluate();

        Collection<BindingSet> solution = new LinkedList<BindingSet>();
        solution.add(
            createBindingSet(new Binding[] {new BindingImpl("s", A), new BindingImpl("age", _25)}));
        solution.add(
            createBindingSet(new Binding[] {new BindingImpl("s", B), new BindingImpl("age", _45)}));

        compare(result, solution);
      }

    } finally {
      cxn.close();
      sail.__tearDownUnitTest();
    }
  }
예제 #19
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;
 }
예제 #20
0
 private byte[] literal2data(Literal literal, boolean create) throws IOException {
   return literal2data(literal.getLabel(), literal.getLanguage(), literal.getDatatype(), create);
 }
예제 #21
0
  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;
  }
예제 #22
0
  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();
  }