Exemplo n.º 1
0
  /**
   * Creates an XQuery representation for the specified query.
   *
   * @param query query
   * @param ctx database context
   * @param root start from root node
   * @return query
   */
  public static String find(final String query, final Context ctx, final boolean root) {
    // treat input as XQuery
    if (query.startsWith("/")) return query;

    final boolean r = root || ctx.root();
    if (query.isEmpty()) return r ? "/" : ".";

    // parse user input
    final String qu = query.replaceAll(" \\+", " ");
    final String[] terms = split(qu);

    String pre = "";
    String preds = "";
    final String tag = "*";
    for (String term : terms) {
      if (term.startsWith("@=")) {
        preds += "[@* = \"" + term.substring(2) + "\"]";
      } else if (term.startsWith("=")) {
        preds += "[text() = \"" + term.substring(1) + "\"]";
      } else if (term.startsWith("~")) {
        preds += "[text() contains text \"" + term.substring(1) + "\" using fuzzy]";
      } else if (term.startsWith("@")) {
        if (term.length() == 1) continue;
        preds += "[@* contains text \"" + term.substring(1) + "\"]";
        term = term.substring(1);
        // add valid name tests
        if (XMLToken.isName(token(term))) {
          pre += (r ? "" : ".") + "//@" + term + " | ";
        }
      } else {
        preds += "[text() contains text \"" + term + "\"]";
        // add valid name tests
        if (XMLToken.isName(token(term))) {
          pre += (r ? "/" : "") + Axis.DESC + "::*:" + term + " | ";
        }
      }
    }
    if (pre.isEmpty() && preds.isEmpty()) return root ? "/" : ".";

    // create final string
    final TokenBuilder tb = new TokenBuilder();
    tb.add(pre + (r ? "/" : "") + Axis.DESCORSELF + "::" + tag + preds);
    return tb.toString();
  }