Example #1
0
  @Override
  public Value value(final QueryContext qc) throws QueryException {
    final FItem getKey = checkArity(exprs[1], 1, qc);
    final long k = Math.min(toLong(exprs[2], qc), Integer.MAX_VALUE);
    if (k < 1) return Empty.SEQ;

    final Iter iter = exprs[0].iter(qc);
    final MinHeap<Item, Item> heap =
        new MinHeap<>(
            new Comparator<Item>() {
              @Override
              public int compare(final Item it1, final Item it2) {
                try {
                  return OpV.LT.eval(it1, it2, sc.collation, sc, info) ? -1 : 1;
                } catch (final QueryException qe) {
                  throw new QueryRTException(qe);
                }
              }
            });

    try {
      for (Item it; (it = iter.next()) != null; ) {
        heap.insert(checkNoEmpty(getKey.invokeItem(qc, info, it)), it);
        if (heap.size() > k) heap.removeMin();
      }
    } catch (final QueryRTException ex) {
      throw ex.getCause();
    }

    final ValueBuilder vb = new ValueBuilder();
    while (!heap.isEmpty()) vb.addFront(heap.removeMin());
    return vb.value();
  }
Example #2
0
 @Override
 public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
   final Iter ir = iter(qc);
   final Item it = ir.next();
   if (it == null || ir.size() == 1) return it;
   final Item n = ir.next();
   if (n != null) {
     final ValueBuilder vb = new ValueBuilder().add(it).add(n);
     if (ir.next() != null) vb.add(Str.get(DOTS));
     throw SEQFOUND_X.get(info, vb.value());
   }
   return it;
 }
Example #3
0
  @Override
  public Value value(final QueryContext qc) throws QueryException {
    final FItem f = checkArity(exprs[1], 1, qc);
    final Iter iter = exprs[0].iter(qc);
    Item it = iter.next();
    if (it == null) return Empty.SEQ;
    final Value v1 = f.invokeValue(qc, info, it);
    it = iter.next();
    if (it == null) return v1;

    final ValueBuilder vb = new ValueBuilder().add(v1);
    do {
      vb.add(f.invokeValue(qc, info, it));
    } while ((it = iter.next()) != null);
    return vb.value();
  }
Example #4
0
 @Override
 public final Item ebv(final QueryContext qc, final InputInfo ii) throws QueryException {
   final Item it;
   if (seqType().zeroOrOne()) {
     it = item(qc, info);
   } else {
     final Iter ir = iter(qc);
     it = ir.next();
     if (it != null && !(it instanceof ANode)) {
       final Item n = ir.next();
       if (n != null) {
         final ValueBuilder vb = new ValueBuilder().add(it).add(n);
         if (ir.next() != null) vb.add(Str.get(DOTS));
         throw EBV_X.get(info, vb.value());
       }
     }
   }
   return it == null ? Bln.FALSE : it;
 }
Example #5
0
  @Override
  public Iter iter(final QueryContext qc) throws QueryException {
    final Iter ir = exprs[0].iter(qc);
    final long len = ir.size();
    if (len == 0) throw ONEORMORE.get(info);
    if (len > 0) return ir;
    return new Iter() {
      private boolean first = true;

      @Override
      public Item next() throws QueryException {
        final Item it = ir.next();
        if (first) {
          if (it == null) throw ONEORMORE.get(info);
          first = false;
        }
        return it;
      }
    };
  }
Example #6
0
  /**
   * Returns a minimum or maximum item.
   *
   * @param cmp comparator
   * @param qc query context
   * @return resulting item
   * @throws QueryException query exception
   */
  Item minmax(final OpV cmp, final QueryContext qc) throws QueryException {
    final Collation coll = toCollation(1, qc);

    final Iter iter = exprs[0].atomIter(qc, info);
    Item curr = iter.next();
    if (curr == null) return null;

    // check if first item is comparable
    cmp.eval(curr, curr, coll, sc, info);

    // strings
    if (curr instanceof AStr) {
      for (Item it; (it = iter.next()) != null; ) {
        if (!(it instanceof AStr)) throw EXPTYPE_X_X_X.get(info, curr.type, it.type, it);
        final Type rt = curr.type, ri = it.type;
        if (cmp.eval(curr, it, coll, sc, info)) curr = it;
        if (rt != ri && curr.type == URI) curr = STR.cast(curr, qc, sc, info);
      }
      return curr;
    }
    // dates, durations, booleans, binary values
    if (curr instanceof ADate || curr instanceof Dur || curr instanceof Bin || curr.type == BLN) {
      for (Item it; (it = iter.next()) != null; ) {
        if (curr.type != it.type) throw EXPTYPE_X_X_X.get(info, curr.type, it.type, it);
        if (cmp.eval(curr, it, coll, sc, info)) curr = it;
      }
      return curr;
    }
    // numbers
    if (curr.type.isUntyped()) curr = DBL.cast(curr, qc, sc, info);
    for (Item it; (it = iter.next()) != null; ) {
      final Type type = numType(curr, it);
      if (cmp.eval(curr, it, coll, sc, info) || Double.isNaN(it.dbl(info))) curr = it;
      if (type != null) curr = (Item) type.cast(curr, qc, sc, info);
    }
    return curr;
  }
Example #7
0
  /**
   * Evaluates the specified function and creates a response.
   *
   * @throws Exception exception (including unexpected ones)
   */
  void create() throws Exception {
    // bind variables
    final StaticFunc sf = function.function;
    final Expr[] args = new Expr[sf.args.length];
    function.bind(http, args, error);

    // wrap function with a function call
    final MainModule mm = new MainModule(sf, args);

    // assign main module and http context and register process
    query.mainModule(mm);
    query.http(http);
    query.context.register(query);

    String redirect = null, forward = null;
    RestXqRespBuilder resp = null;
    try {
      // compile and evaluate query
      query.compile();
      final Iter iter = query.iter();
      Item item = iter.next();

      // handle response element
      if (item != null && item instanceof ANode) {
        final ANode node = (ANode) item;
        // send redirect to browser
        if (REST_REDIRECT.eq(node)) {
          final ANode ch = node.children().next();
          if (ch == null || ch.type != NodeType.TXT) throw function.error(NO_VALUE, node.name());
          redirect = string(ch.string()).trim();
          return;
        }
        // server-side forwarding
        if (REST_FORWARD.eq(node)) {
          final ANode ch = node.children().next();
          if (ch == null || ch.type != NodeType.TXT) throw function.error(NO_VALUE, node.name());
          forward = string(ch.string()).trim();
          return;
        }
        if (REST_RESPONSE.eq(node)) {
          resp = new RestXqRespBuilder();
          resp.build(node, function, iter, http);
          return;
        }
      }

      // HEAD method must return a single response element
      if (function.methods.size() == 1 && function.methods.contains(HTTPMethod.HEAD.name()))
        throw function.error(HEAD_METHOD);

      // serialize result
      final SerializerOptions sp = function.output;
      http.sopts(sp);
      http.initResponse();
      final Serializer ser = Serializer.get(http.res.getOutputStream(), sp);
      for (; item != null; item = iter.next()) ser.serialize(item);
      ser.close();

    } finally {
      query.close();
      query.context.unregister(query);

      if (redirect != null) {
        http.res.sendRedirect(redirect);
      } else if (forward != null) {
        http.req.getRequestDispatcher(forward).forward(http.req, http.res);
      } else if (resp != null) {
        if (resp.status != 0) http.status(resp.status, resp.message, resp.error);
        http.res.getOutputStream().write(resp.cache.toArray());
      }
    }
  }