Beispiel #1
0
  private void splitJourneyLocation(
      ConcurrentMap<String, IRI> variableTypes,
      List<LDObject> journeyLocation,
      List<LDObject> journeyDatas,
      BindingSet bindings) {
    LDObject locationsData = new LDObject();
    LDObject journeyData = new LDObject();

    bindings
        .getBindingNames()
        .stream()
        .forEach(
            bindingName -> {
              org.openrdf.model.Value value = bindings.getBinding(bindingName).getValue();
              QueryResultsParser.updateVariableTypes(variableTypes, bindingName, value);

              if (Arrays.asList("id", "creationDate", "name", "status").contains(bindingName)) {
                journeyData.addKeyValue(new KeyValue(bindingName, value.stringValue()));
              } else {
                locationsData.addKeyValue(new KeyValue(bindingName, value.stringValue()));
              }

              if ("locationId".equalsIgnoreCase(bindingName)) {
                journeyData.addKeyValue(new KeyValue(bindingName, value.stringValue()));
              }
            });

    journeyLocation.add(locationsData);
    journeyDatas.add(journeyData);
  }
 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());
   }
 }
Beispiel #3
0
    public boolean matches(final Vertex vertex, final Value value) {
      String kind = (String) vertex.getProperty(KIND);
      String val = (String) vertex.getProperty(VALUE);
      if (value instanceof URI) {
        return kind.equals(URI) && val.equals(value.stringValue());
      } else if (value instanceof Literal) {
        if (kind.equals(LITERAL)) {
          if (!val.equals(((Literal) value).getLabel())) {
            return false;
          }

          String type = (String) vertex.getProperty(TYPE);
          String lang = (String) vertex.getProperty(LANG);

          URI vType = ((Literal) value).getDatatype();
          String vLang = ((Literal) value).getLanguage();

          return null == type && null == vType && null == lang && null == vLang
              || null != type && null != vType && type.equals(vType.stringValue())
              || null != lang && null != vLang && lang.equals(vLang);

        } else {
          return false;
        }
      } else if (value instanceof BNode) {
        return kind.equals(BNODE) && ((BNode) value).getID().equals(val);
      } else {
        throw new IllegalStateException("value of unexpected kind: " + value);
      }
    }
  private RDFRectangle toRectangle(StatementPattern pattern, BindingSet bindings) {
    Value sVal = pattern.getSubjectVar().getValue();
    Value pVal = pattern.getPredicateVar().getValue();
    Value oVal = pattern.getObjectVar().getValue();

    RDFURIRange subjectRange;
    List<String> list = new ArrayList<String>();
    if (sVal == null) {
      if (bindings.hasBinding(pattern.getSubjectVar().getName()))
        list.add(bindings.getValue(pattern.getSubjectVar().getName()).stringValue());
    } else list.add(sVal.stringValue());

    if (!list.isEmpty()) subjectRange = new RDFURIRange(list);
    else subjectRange = new RDFURIRange();

    ExplicitSetRange<URI> predicateRange;
    Set<URI> set = new HashSet<URI>();
    if (pVal == null) {
      if (bindings.hasBinding(pattern.getPredicateVar().getName()))
        set.add((URI) bindings.getValue(pattern.getPredicateVar().getName()));
    } else set.add((URI) pVal);

    if (!set.isEmpty()) predicateRange = new ExplicitSetRange<URI>(set);
    else predicateRange = new ExplicitSetRange<>();

    RDFValueRange objectRange = new RDFValueRange();
    if (oVal == null) {
      if (bindings.hasBinding(pattern.getObjectVar().getName()))
        objectRange = fillObjectRange(bindings.getValue(pattern.getObjectVar().getName()));
    } else objectRange = fillObjectRange(oVal);

    return new RDFRectangle(subjectRange, predicateRange, objectRange);
  }
Beispiel #5
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;
    }
Beispiel #6
0
 /**
  * Insert Triple/Statement into graph
  *
  * @param s subject uriref
  * @param p predicate uriref
  * @param o value object (URIref or Literal)
  * @param contexts varArgs context objects (use default graph if null)
  */
 public void add(Resource s, URI p, Value o, Resource... contexts) {
   if (log.isDebugEnabled())
     log.debug(
         "[SesameDataSet:add] Add triple ("
             + s.stringValue()
             + ", "
             + p.stringValue()
             + ", "
             + o.stringValue()
             + ").");
   try {
     RepositoryConnection con = currentRepository.getConnection();
     try {
       ValueFactory myFactory = con.getValueFactory();
       Statement st = myFactory.createStatement((Resource) s, p, (Value) o);
       con.add(st, contexts);
       con.commit();
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
       con.close();
     }
   } catch (Exception e) {
     // handle exception
   }
 }
  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();
  }
  public static void main(String[] args) {

    // create a graph with type inferencing
    SimpleSesameGraph g = new SimpleSesameGraph(true);

    //        //load the film schema and the example data
    //        g.addFile("../roadstead_ontologies/film-ontology.owl", SimpleSesameGraph.RDFXML);

    // try loading the geopolitical ontology
    g.addURI("http://aims.fao.org/aos/geopolitical.owl");

    //        List<HashMap<Object, Value>> solutions = g.runSPARQL("SELECT ?who WHERE  { " +
    //                "?who <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
    // <http://roadstead.org/film#Person> ." +
    //                "}");

    /*
    Here we are looking for the names of all the things with a name
     */
    List<HashMap<Object, Value>> solutions =
        g.runSPARQL(
            "SELECT ?name WHERE  { "
                + "?what <http://aims.fao.org/aos/geopolitical.owl#territory> ?name ."
                + "?what <http://aims.fao.org/aos/geopolitical.owl#nameListEN> ?name ."
                + "}");
    for (HashMap<Object, Value> object : solutions) {
      for (Value value : object.values()) {
        System.out.println("country: " + value.stringValue());
      }
    }
  }
  /**
   * Extract content value from a term type resource.
   *
   * @return
   * @throws InvalidR2RMLStructureException
   */
  private static Value extractValueFromTermMap(
      SesameDataSet r2rmlMappingGraph, Resource termType, Enum term)
      throws InvalidR2RMLStructureException {

    URI p = getTermURI(r2rmlMappingGraph, term);

    List<Statement> statements = r2rmlMappingGraph.tuplePattern(termType, p, null);
    if (statements.isEmpty()) {
      return null;
    }
    if (statements.size() > 1) {
      throw new InvalidR2RMLStructureException(
          "[RMLMappingFactory:extractValueFromTermMap] "
              + termType
              + " has too many "
              + term
              + " predicate defined.");
    }
    Value result = statements.get(0).getObject();
    log.debug(
        "[RMLMappingFactory:extractValueFromTermMap] Extracted "
            + term
            + " : "
            + result.stringValue());
    return result;
  }
Beispiel #10
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);
  }
  /**
   * Sorts in the order nulls>BNodes>URIs>Literals
   *
   * <p>This is due to the fact that nulls are only applicable to contexts, and according to the
   * OpenRDF documentation, the type of the null cannot be sufficiently distinguished from any other
   * Value to make an intelligent comparison to other Values
   *
   * <p>http://www.openrdf.org/doc/sesame2/api/org/openrdf/OpenRDFUtil.html#verifyContextNotNull(org.
   * openrdf.model.Resource...)
   *
   * <p>BNodes are sorted according to the lexical compare of their identifiers, which provides a
   * way to sort statements with the same BNodes in the same positions, near each other
   *
   * <p>BNode sorting is not specified across sessions
   */
  @Override
  public int compare(final Value first, final Value second) {
    if (first == null) {
      if (second == null) {
        return ValueComparator.EQUALS;
      } else {
        return ValueComparator.BEFORE;
      }
    } else if (second == null) {
      // always sort null Values before others, so if the second is null, but the first
      // wasn't, sort the first after the second
      return ValueComparator.AFTER;
    }

    if (first == second || first.equals(second)) {
      return ValueComparator.EQUALS;
    }

    if (first instanceof BNode) {
      if (second instanceof BNode) {
        // if both are BNodes, sort based on the lexical value of the internal ID
        // Although this sorting is not guaranteed to be consistent across sessions,
        // it provides a consistent sorting of statements in every case
        // so that statements with the same BNode are sorted near each other
        return ((BNode) first).getID().compareTo(((BNode) second).getID());
      } else {
        return ValueComparator.BEFORE;
      }
    } else if (second instanceof BNode) {
      // sort BNodes before other things, and first was not a BNode
      return ValueComparator.AFTER;
    } else if (first instanceof URI) {
      if (second instanceof URI) {
        return ((URI) first).stringValue().compareTo(((URI) second).stringValue());
      } else {
        return ValueComparator.BEFORE;
      }
    } else if (second instanceof URI) {
      // sort URIs before Literals
      return ValueComparator.AFTER;
    }
    // they must both be Literal's, so sort based on the lexical value of the Literal
    else {
      return first.stringValue().compareTo(second.stringValue());
    }
  }
 private String getrawDatasetId(Value rawDatasetUrl) {
   String dataset = rawDatasetUrl.stringValue();
   int datasetOffset = dataset.lastIndexOf("dataset");
   if (datasetOffset >= 0) {
     return dataset.substring(datasetOffset + 8);
   }
   return dataset.substring(dataset.lastIndexOf("/") + 1);
 }
Beispiel #13
0
  private void addToUrlList(Value iri) {
    try {
      URI uri = new URI(iri.stringValue());

      if (uri.getScheme().startsWith("http")) {
        httpURIs.add(pruneFragment(uri));
      }
    } catch (URISyntaxException e) {
      invalidResources.add(iri.toString());
    }
  }
Beispiel #14
0
    public Vertex findVertex(final Value value) {
      CloseableSequence<Vertex> i = values.get(VALUE, value.stringValue());
      try {
        while (i.hasNext()) {
          Vertex v = i.next();

          if (matches(v, value)) {
            return v;
          }
        }

        return null;
      } finally {
        i.close();
      }
    }
    public Vertex findVertex(final Value value) {
      Iterator<Vertex> i = store.graph.getVertices(VALUE, value.stringValue()).iterator();
      // TODO: restore the close()
      // try {
      while (i.hasNext()) {
        Vertex v = i.next();

        if (matches(v, value)) {
          return v;
        }
      }

      return null;
      // } finally {
      //    i.close();
      // }
    }
  /**
   * Extract content values from a term type resource.
   *
   * @return
   * @throws InvalidR2RMLStructureException
   */
  private static Set<Value> extractValuesFromResource(
      SesameDataSet r2rmlMappingGraph, Resource termType, Enum term)
      throws InvalidR2RMLStructureException {
    URI p = getTermURI(r2rmlMappingGraph, term);

    List<Statement> statements = r2rmlMappingGraph.tuplePattern(termType, p, null);
    if (statements.isEmpty()) {
      return null;
    }
    Set<Value> values = new HashSet<Value>();
    for (Statement statement : statements) {
      Value value = statement.getObject();
      log.debug(
          "[RMLMappingFactory:extractURIsFromTermMap] Extracted "
              + term
              + " : "
              + value.stringValue());
      values.add(value);
    }
    return values;
  }
  public static TestSuite suite(String manifestFileURL, Factory factory, boolean approvedOnly)
      throws Exception {
    logger.info("Building test suite for {}", manifestFileURL);

    TestSuite suite = new TestSuite(factory.getClass().getName());

    // Read manifest and create declared test cases
    Repository manifestRep = new SailRepository(new MemoryStore());
    manifestRep.initialize();
    RepositoryConnection con = manifestRep.getConnection();

    ManifestTest.addTurtle(con, new URL(manifestFileURL), manifestFileURL);

    suite.setName(getManifestName(manifestRep, con, manifestFileURL));

    // Extract test case information from the manifest file. Note that we
    // only
    // select those test cases that are mentioned in the list.
    StringBuilder query = new StringBuilder(512);
    query.append(
        " SELECT DISTINCT testURI, testName, resultFile, action, queryFile, defaultGraph, ordered ");
    query.append(" FROM {} rdf:first {testURI} ");
    if (approvedOnly) {
      query.append("                          dawgt:approval {dawgt:Approved}; ");
    }
    query.append("                             mf:name {testName}; ");
    query.append("                             mf:result {resultFile}; ");
    query.append("                             [ mf:checkOrder {ordered} ]; ");
    query.append("                             [ mf:requires {Requirement} ];");
    query.append("                             mf:action {action} qt:query {queryFile}; ");
    query.append("                                               [qt:data {defaultGraph}]; ");
    query.append("                                               [sd:entailmentRegime {Regime} ]");

    // skip tests involving CSV result files, these are not query tests
    query.append(" WHERE NOT resultFile LIKE \"*.csv\" ");
    // skip tests involving JSON, sesame currently does not have a
    // SPARQL/JSON
    // parser.
    query.append(" AND NOT resultFile LIKE \"*.srj\" ");
    // skip tests involving entailment regimes
    query.append(" AND NOT BOUND(Regime) ");
    // skip test involving basic federation, these are tested separately.
    query.append(" AND (NOT BOUND(Requirement) OR (Requirement != mf:BasicFederation)) ");
    query.append(" USING NAMESPACE ");
    query.append("  mf = <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>, ");
    query.append("  dawgt = <http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#>, ");
    query.append("  qt = <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>, ");
    query.append("  sd = <http://www.w3.org/ns/sparql-service-description#>, ");
    query.append("  ent = <http://www.w3.org/ns/entailment/> ");
    TupleQuery testCaseQuery = con.prepareTupleQuery(QueryLanguage.SERQL, query.toString());

    query.setLength(0);
    query.append(" SELECT graph ");
    query.append(" FROM {action} qt:graphData {graph} ");
    query.append(" USING NAMESPACE ");
    query.append(" qt = <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>");
    TupleQuery namedGraphsQuery = con.prepareTupleQuery(QueryLanguage.SERQL, query.toString());

    query.setLength(0);
    query.append("SELECT 1 ");
    query.append(" FROM {testURI} mf:resultCardinality {mf:LaxCardinality}");
    query.append(
        " USING NAMESPACE mf = <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>");
    TupleQuery laxCardinalityQuery = con.prepareTupleQuery(QueryLanguage.SERQL, query.toString());

    logger.debug("evaluating query..");
    TupleQueryResult testCases = testCaseQuery.evaluate();
    while (testCases.hasNext()) {
      BindingSet bindingSet = testCases.next();

      URI testURI = (URI) bindingSet.getValue("testURI");
      String testName = bindingSet.getValue("testName").toString();
      String resultFile = bindingSet.getValue("resultFile").toString();
      String queryFile = bindingSet.getValue("queryFile").toString();
      URI defaultGraphURI = (URI) bindingSet.getValue("defaultGraph");
      Value action = bindingSet.getValue("action");
      Value ordered = bindingSet.getValue("ordered");

      logger.debug("found test case : {}", testName);

      // Query named graphs
      namedGraphsQuery.setBinding("action", action);
      TupleQueryResult namedGraphs = namedGraphsQuery.evaluate();

      DatasetImpl dataset = null;

      if (defaultGraphURI != null || namedGraphs.hasNext()) {
        dataset = new DatasetImpl();

        if (defaultGraphURI != null) {
          dataset.addDefaultGraph(defaultGraphURI);
        }

        while (namedGraphs.hasNext()) {
          BindingSet graphBindings = namedGraphs.next();
          URI namedGraphURI = (URI) graphBindings.getValue("graph");
          logger.debug(" adding named graph : {}", namedGraphURI);
          dataset.addNamedGraph(namedGraphURI);
        }
      }

      // Check for lax-cardinality conditions
      boolean laxCardinality = false;
      laxCardinalityQuery.setBinding("testURI", testURI);
      TupleQueryResult laxCardinalityResult = laxCardinalityQuery.evaluate();
      try {
        laxCardinality = laxCardinalityResult.hasNext();
      } finally {
        laxCardinalityResult.close();
      }

      // if this is enabled, Sesame passes all tests, showing that the
      // only
      // difference is the semantics of arbitrary-length
      // paths
      /*
       * if (!laxCardinality) { // property-path tests always with lax
       * cardinality because Sesame filters out duplicates by design if
       * (testURI.stringValue().contains("property-path")) {
       * laxCardinality = true; } }
       */

      // check if we should test for query result ordering
      boolean checkOrder = false;
      if (ordered != null) {
        checkOrder = Boolean.parseBoolean(ordered.stringValue());
      }

      SPARQLQueryTest test =
          factory.createSPARQLQueryTest(
              testURI.toString(),
              testName,
              queryFile,
              resultFile,
              dataset,
              laxCardinality,
              checkOrder);
      if (test != null) {
        suite.addTest(test);
      }
    }

    testCases.close();
    con.close();

    manifestRep.shutDown();
    logger.info("Created test suite with " + suite.countTestCases() + " test cases.");
    return suite;
  }
Beispiel #18
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 String getString(Value v) {
   if (v != null) {
     return v.stringValue();
   }
   return null;
 }
  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();
  }