Example #1
0
 @Override
 public final void plan(final Serializer ser) throws IOException {
   ser.openElement(this);
   ser.attribute(AXIS, Token.token(axis.name));
   ser.attribute(TEST, Token.token(test.toString()));
   super.plan(ser);
   ser.closeElement();
 }
Example #2
0
  /**
   * Test concurrent reader and writer (GH-458).
   *
   * <p><b>Test case:</b>
   *
   * <ol>
   *   <li/>start a long running reader;
   *   <li/>try to start a writer: it should time out;
   *   <li/>stop the reader;
   *   <li/>start the writer again: it should succeed.
   * </ol>
   *
   * @throws Exception error during request execution
   */
  @Test
  @Ignore("There is no way to stop a query on the server!")
  public void testReaderWriter() throws Exception {
    final String readerQuery = "?query=(1%20to%20100000000000000)%5b.=1%5d";
    final String writerQuery = "/test.xml";
    final byte[] content = Token.token("<a/>");

    final Get readerAction = new Get(readerQuery);
    final Put writerAction = new Put(writerQuery, content);

    final ExecutorService exec = Executors.newFixedThreadPool(2);

    // start reader
    exec.submit(readerAction);
    Performance.sleep(TIMEOUT); // delay in order to be sure that the reader has started
    // start writer
    Future<HTTPResponse> writer = exec.submit(writerAction);

    try {
      final HTTPResponse result = writer.get(TIMEOUT, TimeUnit.MILLISECONDS);

      if (result.status.isSuccess()) fail("Database modified while a reader is running");
      throw new Exception(result.toString());
    } catch (final TimeoutException e) {
      // writer is blocked by the reader: stop it
      writerAction.stop = true;
    }

    // stop reader
    readerAction.stop = true;

    // start the writer again
    writer = exec.submit(writerAction);
    assertEquals(HTTPCode.CREATED, writer.get().status);
  }
Example #3
0
  /**
   * Chooses files that match the specified pattern.
   *
   * @param file file filter
   * @param content content filter
   * @param root root directory
   * @return sorted file paths
   * @throws InterruptedException interruption
   */
  String[] filter(final String file, final String content, final IOFile root)
      throws InterruptedException {

    final long id = ++filterId;
    final TreeSet<String> results = new TreeSet<>();
    final int[] search = new TokenParser(Token.lc(Token.token(content))).toArray();

    // glob pattern
    final ProjectCache pc = cache(root);
    if (file.contains("*") || file.contains("?")) {
      final Pattern pt = Pattern.compile(IOFile.regex(file));
      for (final String path : pc) {
        final int offset = offset(path, true);
        if (pt.matcher(path.substring(offset)).matches() && filterContent(path, search)) {
          results.add(path);
          if (results.size() >= MAXHITS) break;
        }
        if (id != filterId) throw new InterruptedException();
      }
    } else {
      // starts-with, contains, camel case
      final String pttrn = file.toLowerCase(Locale.ENGLISH).replace('\\', '/');
      final HashSet<String> exclude = new HashSet<>();
      final boolean pathSearch = pttrn.indexOf('/') != -1;
      for (int i = 0; i < (pathSearch ? 2 : 3); i++) {
        filter(pttrn, search, i, results, exclude, pathSearch, pc, id);
      }
    }
    return results.toArray(new String[results.size()]);
  }
 @Override
 public void startNonterminal(String name, int begin) {
   try {
     builder.openElem(Token.token(name), atts, nsp);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
 private void characters(int begin, int end) {
   if (begin < end) {
     try {
       builder.text(Token.token(input.subSequence(begin, end).toString()));
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
 }
Example #6
0
 @Override
 public void plan(final Serializer ser) throws IOException {
   try {
     ser.emptyElement(ITM, VAL, atom(null), TYP, Token.token(name()));
   } catch (final QueryException ex) {
     // only function items throw exceptions in atomization, and they should
     // override plan(Serializer) sensibly
     Util.notexpected(ex);
   }
 }
Example #7
0
  @Override
  public void actionPerformed(final ActionEvent e) {
    if (e != null) {
      final Object source = e.getSource();

      // find modified component
      int cp = 0;
      final int cs = panel.getComponentCount();
      for (int c = 0; c < cs; ++c) if (panel.getComponent(c) == source) cp = c;

      if ((cp & 1) == 0) {
        // combo box with tags/attributes
        final BaseXCombo combo = (BaseXCombo) source;
        panel.remove(cp + 1);

        final Data data = gui.context.data();
        final boolean selected = combo.getSelectedIndex() != 0;
        if (selected) {
          final String item = combo.getSelectedItem().toString();
          final boolean att = item.startsWith("@");
          final Names names = att ? data.atnindex : data.tagindex;
          final byte[] key = Token.token(att ? item.substring(1) : item);
          final StatsKey stat = names.stat(names.id(key));
          switch (stat.kind) {
            case INT:
              addSlider(stat.min, stat.max, cp + 1, true);
              break;
            case DBL:
              addSlider(stat.min, stat.max, cp + 1, false);
              break;
            case CAT:
              addCombo(entries(stat.cats.keys()), cp + 1);
              break;
            case TEXT:
              addInput(cp + 1);
              break;
            case NONE:
              panel.add(new BaseXLabel(""), cp + 1);
              break;
          }
        } else {
          panel.add(new BaseXLabel(""), cp + 1);
        }
        while (cp + 2 < panel.getComponentCount()) {
          panel.remove(cp + 2);
          panel.remove(cp + 2);
        }
        if (selected) addKeys(data);
        panel.revalidate();
        panel.repaint();
      }
    }
    query(false);
  }
Example #8
0
 /**
  * Returns the color for the specified string or {@code null}.
  *
  * @param string string string
  * @return color
  */
 static String color(final byte[] string) {
   for (final Object[] color : COLORS) {
     final int cl = color.length;
     for (int c = 1; c < cl; c++) {
       final Object o = color[c];
       final byte[] col =
           o instanceof byte[]
               ? (byte[]) o
               : Token.token(o instanceof Class ? Util.className((Class<?>) o) : o.toString());
       if (Token.eq(col, string)) return color[0].toString();
     }
   }
   return null;
 }
Example #9
0
 /**
  * Adds the time to the specified token builder.
  *
  * @param tb token builder
  */
 final void time(final TokenBuilder tb) {
   if (sec.remainder(DAYSECONDS).signum() == 0) return;
   tb.add('T');
   final long h = hou();
   if (h != 0) {
     tb.addLong(Math.abs(h));
     tb.add('H');
   }
   final long m = min();
   if (m != 0) {
     tb.addLong(Math.abs(m));
     tb.add('M');
   }
   final BigDecimal sc = sec();
   if (sc.signum() == 0) return;
   tb.add(Token.chopNumber(Token.token(sc.abs().toPlainString()))).add('S');
 }
Example #10
0
  /**
   * Adds a category combobox.
   *
   * @param data data reference
   */
  private void addKeys(final Data data) {
    final TokenList tl = new TokenList();
    final int cs = panel.getComponentCount();

    for (int c = 0; c < cs; c += 2) {
      final BaseXCombo combo = (BaseXCombo) panel.getComponent(c);
      if (combo.getSelectedIndex() == 0) continue;
      final String elem = combo.getSelectedItem().toString();
      if (!elem.startsWith("@")) tl.add(Token.token(elem));
    }

    final TokenList tmp = data.pthindex.desc(tl, true, false);
    final String[] keys = entries(tmp.toArray());
    final BaseXCombo cm = new BaseXCombo(gui, keys);
    cm.addActionListener(this);
    cm.addKeyListener(main);
    if (tmp.size() == 0) cm.setEnabled(false);
    panel.add(cm);
    panel.add(new BaseXLabel(""));
  }
Example #11
0
  /**
   * Default constructor.
   *
   * @param main reference to the main window
   * @param txt message text
   * @param ic message type
   */
  DialogMessage(final GUI main, final String txt, final Msg ic) {
    super(main, ic == Msg.ERROR ? Text.ERROR : Text.INFORMATION);

    panel.setLayout(new BorderLayout(12, 0));

    final BaseXLabel b = new BaseXLabel();
    b.setIcon(ic.large);
    set(b, BorderLayout.WEST);

    final BaseXEditor text = new BaseXEditor(false, this);
    text.setFont(b.getFont());
    text.setText(Token.token(txt));
    text.setFocusable(true);
    set(text, BorderLayout.CENTER);

    final BaseXBack buttons;
    if (ic == Msg.QUESTION || ic == Msg.YESNOCANCEL) {
      yes = new BaseXButton(Text.B_YES, this);
      no = new BaseXButton(Text.B_NO, this);
      if (ic == Msg.QUESTION) {
        buttons = newButtons(yes, no);
      } else {
        /* Cancel button. */
        final BaseXButton cancel = new BaseXButton(Text.B_CANCEL, this);
        buttons = newButtons(yes, no, cancel);
      }
    } else {
      yes = new BaseXButton(Text.B_OK, this);
      buttons = newButtons(yes);
    }
    set(buttons, BorderLayout.SOUTH);

    SwingUtilities.invokeLater(
        new Thread() {
          @Override
          public void run() {
            yes.requestFocusInWindow();
          }
        });
    finish(null);
  }
Example #12
0
  /**
   * Test concurrent writers (GH-458).
   *
   * <p><b>Test case:</b>
   *
   * <ol>
   *   <li/>start several writers one after another;
   *   <li/>all writers should succeed.
   * </ol>
   *
   * @throws Exception error during request execution
   */
  @Test
  public void testMultipleWriters() throws Exception {
    final int count = 10;
    final String template =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<command xmlns=\"http://basex.org/rest\"><text><![CDATA["
            + "ADD TO %1$d <node id=\"%1$d\"/>"
            + "]]></text></command>";

    @SuppressWarnings("unchecked")
    final Future<HTTPResponse>[] tasks = new Future[count];
    final ExecutorService exec = Executors.newFixedThreadPool(count);

    // start all writers (not at the same time, but still in parallel)
    for (int i = 0; i < count; i++) {
      final String command = String.format(template, i);
      tasks[i] = exec.submit(new Post("", Token.token(command)));
    }

    // check if all have finished successfully
    for (final Future<HTTPResponse> task : tasks) {
      assertEquals(HTTPCode.OK, task.get(TIMEOUT, TimeUnit.MILLISECONDS).status);
    }
  }
Example #13
0
 @Override
 public byte[] string(final InputInfo ii) {
   final TokenBuilder tb = new TokenBuilder();
   final boolean ymd = yea != Long.MAX_VALUE;
   if (ymd) {
     if (yea <= 0) tb.add('-');
     prefix(tb, Math.abs(yea()), 4);
     tb.add('-');
     prefix(tb, mon(), 2);
     tb.add('-');
     prefix(tb, day(), 2);
   }
   if (hou >= 0) {
     if (ymd) tb.add('T');
     prefix(tb, hou(), 2);
     tb.add(':');
     prefix(tb, min(), 2);
     tb.add(':');
     if (sec.intValue() < 10) tb.add('0');
     tb.addExt(Token.chopNumber(Token.token(sec().abs().toPlainString())));
   }
   zone(tb);
   return tb.finish();
 }
Example #14
0
 @Override
 public void plan(final Serializer ser) throws IOException {
   ser.openElement(this, TYP, Token.token(type.toString()));
   expr.plan(ser);
   ser.closeElement();
 }
Example #15
0
 @Override
 public void plan(final Serializer ser) throws IOException {
   ser.openElement(this, OP, Token.token(calc.name));
   for (final Expr e : expr) e.plan(ser);
   ser.closeElement();
 }
Example #16
0
File: Dtm.java Project: johoe/basex
 /**
  * Constructor.
  *
  * @param tm milliseconds since January 1, 1970, 00:00:00 GMT
  * @param ii input info
  * @throws QueryException query exception
  */
 public Dtm(final long tm, final InputInfo ii) throws QueryException {
   this(Token.token(DATE.format(new java.util.Date(tm))), ii);
 }
Example #17
0
File: Dtm.java Project: johoe/basex
 /**
  * Constructor.
  *
  * @param tm time in milliseconds
  * @param ii input info
  * @throws QueryException query exception
  */
 Dtm(final Int tm, final InputInfo ii) throws QueryException {
   this(Token.token(DATE.format(new java.util.Date(tm.itr(ii)))), ii);
 }
Example #18
0
 /**
  * Sends a string to the server.
  *
  * @param s string to be sent
  * @throws IOException I/O exception
  */
 protected void send(final String s) throws IOException {
   sout.write(Token.token(s));
   sout.write(0);
 }
Example #19
0
 /**
  * Prints a string to the output stream.
  *
  * @param string string to be written
  * @throws IOException I/O exception
  */
 public void print(final String string) throws IOException {
   print(Token.token(string));
 }
Example #20
0
/**
 * Functions on archives.
 *
 * @author BaseX Team 2005-12, BSD License
 * @author Christian Gruen
 */
public class FNArchive extends StandardFunc {
  /** Archive namespace. */
  private static final Atts NS = new Atts(ARCHIVE, ARCHIVEURI);
  /** Element: Entry. */
  private static final QNm Q_ENTRY = new QNm("archive:entry", ARCHIVEURI);
  /** Element: options. */
  private static final QNm Q_OPTIONS = new QNm("archive:options", ARCHIVEURI);
  /** Option: algorithm. */
  private static final QNm Q_FORMAT = new QNm("archive:format", ARCHIVEURI);
  /** Option: algorithm. */
  private static final QNm Q_ALGORITHM = new QNm("archive:algorithm", ARCHIVEURI);
  /** Root node test. */
  private static final ExtTest TEST = new ExtTest(NodeType.ELM, Q_ENTRY);

  /** Level. */
  private static final QNm Q_LEVEL = new QNm("compression-level");
  /** Encoding. */
  private static final QNm Q_ENCODING = new QNm("encoding");
  /** Last modified. */
  private static final QNm Q_LAST_MOD = new QNm("last-modified");
  /** Compressed size. */
  private static final QNm Q_COMP_SIZE = new QNm("compressed-size");
  /** Uncompressed size. */
  private static final QNm Q_SIZE = new QNm("size");
  /** Value. */
  private static final QNm Q_VALUE = new QNm("value");

  /** Option: format. */
  private static final byte[] FORMAT = Token.token("format");
  /** Option: algorithm. */
  private static final byte[] ALGORITHM = Token.token("algorithm");
  /** Option: algorithm: deflate. */
  private static final byte[] DEFLATE = Token.token("deflate");
  /** Option: algorithm: stored. */
  private static final byte[] STORED = Token.token("stored");
  /** Option: algorithm: unknown. */
  private static final byte[] UNKNOWN = Token.token("unknown");

  /**
   * Constructor.
   *
   * @param ii input info
   * @param f function definition
   * @param e arguments
   */
  public FNArchive(final InputInfo ii, final Function f, final Expr... e) {
    super(ii, f, e);
  }

  @Override
  public Iter iter(final QueryContext ctx) throws QueryException {
    switch (sig) {
      case _ARCHIVE_ENTRIES:
        return entries(ctx);
      case _ARCHIVE_EXTRACT_TEXT:
        return extractText(ctx);
      case _ARCHIVE_EXTRACT_BINARY:
        return extractBinary(ctx);
      default:
        return super.iter(ctx);
    }
  }

  @Override
  public Item item(final QueryContext ctx, final InputInfo ii) throws QueryException {
    checkCreate(ctx);
    switch (sig) {
      case _ARCHIVE_CREATE:
        return create(ctx);
      case _ARCHIVE_UPDATE:
        return update(ctx);
      case _ARCHIVE_DELETE:
        return delete(ctx);
      case _ARCHIVE_OPTIONS:
        return options(ctx);
      default:
        return super.item(ctx, ii);
    }
  }

  /**
   * Creates a new archive.
   *
   * @param ctx query context
   * @return archive
   * @throws QueryException query exception
   */
  private B64 create(final QueryContext ctx) throws QueryException {
    final Iter entr = ctx.iter(expr[0]);
    final Iter cont = ctx.iter(expr[1]);
    final Item opt = expr.length > 2 ? expr[2].item(ctx, info) : null;
    final TokenMap map = new FuncParams(Q_OPTIONS, info).parse(opt);

    final byte[] f = map.get(FORMAT);
    final String format = f != null ? string(lc(f)) : "zip";
    final ArchiveOut out = ArchiveOut.get(format, info);
    // check algorithm
    final byte[] alg = map.get(ALGORITHM);
    int level = ZipEntry.DEFLATED;
    if (alg != null) {
      if (format.equals("zip") && !eq(alg, STORED, DEFLATE)
          || format.equals("gzip") && !eq(alg, DEFLATE)) {
        ARCH_SUPP.thrw(info, ALGORITHM, alg);
      }
      if (eq(alg, STORED)) level = ZipEntry.STORED;
      else if (eq(alg, DEFLATE)) level = ZipEntry.DEFLATED;
    }
    out.level(level);

    try {
      int e = 0;
      int c = 0;
      Item en, cn;
      while (true) {
        en = entr.next();
        cn = cont.next();
        if (en == null || cn == null) break;
        if (out instanceof GZIPOut && c > 0)
          ARCH_ONE.thrw(info, format.toUpperCase(Locale.ENGLISH));
        add(checkElmStr(en), cn, out, level);
        e++;
        c++;
      }
      // count remaining entries
      if (cn != null) do c++; while (cont.next() != null);
      if (en != null) do e++; while (entr.next() != null);
      if (e != c) throw ARCH_DIFF.thrw(info, e, c);
    } catch (final IOException ex) {
      Util.debug(ex);
      throw ARCH_FAIL.thrw(info, ex);
    } finally {
      out.close();
    }
    return new B64(out.toArray());
  }

  /**
   * Returns the options of an archive.
   *
   * @param ctx query context
   * @return entries
   * @throws QueryException query exception
   */
  private FElem options(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);
    String format = null;
    int level = -1;

    final ArchiveIn arch = ArchiveIn.get(archive.input(info), info);
    try {
      format = arch.format();
      while (arch.more()) {
        final ZipEntry ze = arch.entry();
        if (ze.isDirectory()) continue;
        level = ze.getMethod();
        break;
      }
    } catch (final IOException ex) {
      Util.debug(ex);
      ARCH_FAIL.thrw(info, ex);
    } finally {
      arch.close();
    }

    // create result element
    final FElem e = new FElem(Q_OPTIONS, NS);
    if (format != null) e.add(new FElem(Q_FORMAT).add(Q_VALUE, format));
    if (level >= 0) {
      final byte[] lvl = level == 8 ? DEFLATE : level == 0 ? STORED : UNKNOWN;
      e.add(new FElem(Q_ALGORITHM).add(Q_VALUE, lvl));
    }
    return e;
  }

  /**
   * Returns the entries of an archive.
   *
   * @param ctx query context
   * @return entries
   * @throws QueryException query exception
   */
  private Iter entries(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);

    final ValueBuilder vb = new ValueBuilder();
    final ArchiveIn in = ArchiveIn.get(archive.input(info), info);
    try {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        if (ze.isDirectory()) continue;
        final FElem e = new FElem(Q_ENTRY, NS);
        long s = ze.getSize();
        if (s != -1) e.add(Q_SIZE, token(s));
        s = ze.getTime();
        if (s != -1) e.add(Q_LAST_MOD, new Dtm(s, info).string(info));
        s = ze.getCompressedSize();
        if (s != -1) e.add(Q_COMP_SIZE, token(s));
        e.add(ze.getName());
        vb.add(e);
      }
      return vb;
    } catch (final IOException ex) {
      Util.debug(ex);
      throw ARCH_FAIL.thrw(info, ex);
    } finally {
      in.close();
    }
  }

  /**
   * Extracts text entries.
   *
   * @param ctx query context
   * @return text entry
   * @throws QueryException query exception
   */
  private ValueBuilder extractText(final QueryContext ctx) throws QueryException {
    final String enc = encoding(2, ARCH_ENCODING, ctx);
    final ValueBuilder vb = new ValueBuilder();
    for (final byte[] b : extract(ctx)) vb.add(Str.get(encode(b, enc)));
    return vb;
  }

  /**
   * Extracts binary entries.
   *
   * @param ctx query context
   * @return binary entry
   * @throws QueryException query exception
   */
  private ValueBuilder extractBinary(final QueryContext ctx) throws QueryException {
    final ValueBuilder vb = new ValueBuilder();
    for (final byte[] b : extract(ctx)) vb.add(new B64(b));
    return vb;
  }

  /**
   * Updates an archive.
   *
   * @param ctx query context
   * @return updated archive
   * @throws QueryException query exception
   */
  private B64 update(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);
    // entries to be updated
    final TokenObjMap<Item[]> hm = new TokenObjMap<Item[]>();

    final Iter entr = ctx.iter(expr[1]);
    final Iter cont = ctx.iter(expr[2]);
    int e = 0;
    int c = 0;
    Item en, cn;
    while (true) {
      en = entr.next();
      cn = cont.next();
      if (en == null || cn == null) break;
      hm.add(checkElmStr(en).string(info), new Item[] {en, cn});
      e++;
      c++;
    }
    // count remaining entries
    if (cn != null) do c++; while (cont.next() != null);
    if (en != null) do e++; while (entr.next() != null);
    if (e != c) ARCH_DIFF.thrw(info, e, c);

    final ArchiveIn in = ArchiveIn.get(archive.input(info), info);
    final ArchiveOut out = ArchiveOut.get(in.format(), info);
    try {
      if (in instanceof GZIPIn) ARCH_MODIFY.thrw(info, in.format().toUpperCase(Locale.ENGLISH));
      // delete entries to be updated
      while (in.more()) if (!hm.contains(token(in.entry().getName()))) out.write(in);
      // add new and updated entries
      for (final byte[] h : hm) {
        if (h == null) continue;
        final Item[] it = hm.get(h);
        add(it[0], it[1], out, ZipEntry.DEFLATED);
      }
    } catch (final IOException ex) {
      Util.debug(ex);
      ARCH_FAIL.thrw(info, ex);
    } finally {
      in.close();
      out.close();
    }
    return new B64(out.toArray());
  }

  /**
   * Deletes files from an archive.
   *
   * @param ctx query context
   * @return updated archive
   * @throws QueryException query exception
   */
  private B64 delete(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);
    // entries to be deleted
    final TokenObjMap<Item[]> hm = new TokenObjMap<Item[]>();
    final Iter names = ctx.iter(expr[1]);
    for (Item en; (en = names.next()) != null; ) {
      hm.add(checkElmStr(en).string(info), null);
    }

    final ArchiveIn in = ArchiveIn.get(archive.input(info), info);
    final ArchiveOut out = ArchiveOut.get(in.format(), info);
    try {
      if (in instanceof GZIPIn) ARCH_MODIFY.thrw(info, in.format().toUpperCase(Locale.ENGLISH));
      while (in.more()) if (!hm.contains(token(in.entry().getName()))) out.write(in);
    } catch (final IOException ex) {
      Util.debug(ex);
      ARCH_FAIL.thrw(info, ex);
    } finally {
      in.close();
      out.close();
    }
    return new B64(out.toArray());
  }

  /**
   * Extracts entries from the archive.
   *
   * @param ctx query context
   * @return text entries
   * @throws QueryException query exception
   */
  private TokenList extract(final QueryContext ctx) throws QueryException {
    final B64 archive = (B64) checkType(checkItem(expr[0], ctx), AtomType.B64);
    TokenSet hs = null;
    if (expr.length > 1) {
      // filter result to specified entries
      hs = new TokenSet();
      final Iter names = ctx.iter(expr[1]);
      for (Item en; (en = names.next()) != null; ) {
        hs.add(checkElmStr(en).string(info));
      }
    }

    final TokenList tl = new TokenList();
    final ArchiveIn in = ArchiveIn.get(archive.input(info), info);
    try {
      while (in.more()) {
        final ZipEntry ze = in.entry();
        if (ze.isDirectory()) continue;
        if (hs == null || hs.delete(token(ze.getName())) != 0) tl.add(in.read());
      }
    } catch (final IOException ex) {
      Util.debug(ex);
      ARCH_FAIL.thrw(info, ex);
    } finally {
      in.close();
    }
    return tl;
  }

  /**
   * Adds the specified entry to the output stream.
   *
   * @param entry entry descriptor
   * @param con contents
   * @param out output archive
   * @param level default compression level
   * @throws QueryException query exception
   * @throws IOException I/O exception
   */
  private void add(final Item entry, final Item con, final ArchiveOut out, final int level)
      throws QueryException, IOException {

    // create new zip entry
    final String name = string(entry.string(info));
    if (name.isEmpty()) ARCH_EMPTY.thrw(info);
    final ZipEntry ze = new ZipEntry(name);
    String en = null;

    // compression level
    byte[] lvl = null;
    if (entry instanceof ANode) {
      final ANode el = (ANode) entry;
      lvl = el.attribute(Q_LEVEL);

      // last modified
      final byte[] mod = el.attribute(Q_LAST_MOD);
      if (mod != null) {
        try {
          ze.setTime(new Int(new Dtm(mod, info)).itr());
        } catch (final QueryException qe) {
          ARCH_DATETIME.thrw(info, mod);
        }
      }

      // encoding
      final byte[] enc = el.attribute(Q_ENCODING);
      if (enc != null) {
        en = string(enc);
        if (!Charset.isSupported(en)) ARCH_ENCODING.thrw(info, enc);
      }
    }

    // data to be compressed
    byte[] val = checkStrBin(con);
    if (con instanceof AStr && en != null && en != Token.UTF8) val = encode(val, en);

    try {
      out.level(lvl == null ? level : toInt(lvl));
    } catch (final IllegalArgumentException ex) {
      ARCH_LEVEL.thrw(info, lvl);
    }
    out.write(ze, val);
  }

  /**
   * Encodes the specified string to another encoding.
   *
   * @param val value to be encoded
   * @param en encoding
   * @return encoded string
   * @throws QueryException query exception
   */
  private byte[] encode(final byte[] val, final String en) throws QueryException {
    try {
      return FNConvert.toString(new ArrayInput(val), en);
    } catch (final IOException ex) {
      throw ARCH_ENCODE.thrw(info, ex);
    }
  }

  /**
   * Checks if the specified item is a string or element.
   *
   * @param it item to be checked
   * @return item
   * @throws QueryException query exception
   */
  private Item checkElmStr(final Item it) throws QueryException {
    if (it instanceof AStr || TEST.eq(it)) return it;
    throw ELMSTRTYPE.thrw(info, Q_ENTRY.string(), it.type);
  }
}
 public ANode call(Str str) throws IOException {
   String input = str.toJava();
   SingleParser singleParser =
       new SingleParser(new IOContent(""), MainOptions.get()) {
         @Override
         protected void parse() throws IOException {}
       };
   MemBuilder memBuilder = new MemBuilder(input, singleParser);
   memBuilder.init();
   BaseXTreeBuilder treeBuilder = new BaseXTreeBuilder(memBuilder);
   Parse_XQDocComments parser = new Parse_XQDocComments();
   parser.initialize(input, treeBuilder);
   try {
     execute(parser);
   } catch (ParseException pe) {
     memBuilder = new MemBuilder(input, singleParser);
     memBuilder.init();
     Atts atts = new Atts();
     atts.add(Token.token("b"), Token.token(pe.getBegin() + 1));
     atts.add(Token.token("e"), Token.token(pe.getEnd() + 1));
     if (pe.getOffending() < 0) {
       atts.add(Token.token("s"), Token.token(pe.getState()));
     } else {
       atts.add(Token.token("o"), Token.token(pe.getOffending()));
       atts.add(Token.token("x"), Token.token(pe.getExpected()));
     }
     memBuilder.openElem(Token.token("ERROR"), atts, new Atts());
     memBuilder.text(Token.token(parser.getErrorMessage(pe)));
     memBuilder.closeElem();
   }
   return new DBNode(memBuilder.data());
 }
Example #22
0
 /**
  * Prefixes the specified number of zero digits before a number.
  *
  * @param tb token builder
  * @param number number to be printed
  * @param zero maximum number of zero digits
  */
 static void prefix(final TokenBuilder tb, final long number, final int zero) {
   final byte[] t = Token.token(number);
   for (int i = t.length; i < zero; i++) tb.add('0');
   tb.add(t);
 }
Example #23
0
 /**
  * Constructor, specifying the string to be read.
  *
  * @param input input bytes
  */
 public ArrayInput(final String input) {
   this(Token.token(input));
 }
Example #24
0
 /**
  * Test alternate encoding.
  *
  * @param enc encoding to be tested
  * @param input input string
  * @throws IOException I/O exception
  */
 private static void encoding(final String enc, final String input) throws IOException {
   final byte[] utf8 = Token.token(input);
   final IO io = new IOContent(input.getBytes(enc));
   final byte[] cache = new TextInput(io).encoding(enc).content();
   assertSame(cache, utf8);
 }