コード例 #1
0
ファイル: StringParser.java プロジェクト: phspaelti/basex
 /**
  * Converts the specified commands into a string list.
  *
  * @param comp input completions
  * @return string list
  */
 private static StringList list(final Enum<?>[] comp) {
   final StringList list = new StringList();
   if (comp != null) {
     for (final Enum<?> c : comp) list.add(c.name().toLowerCase(Locale.ENGLISH));
   }
   return list;
 }
コード例 #2
0
ファイル: WebDAVLockService.java プロジェクト: nikhi/basex
  /**
   * Executes a query.
   *
   * @param query query to be executed
   * @return list of serialized result items
   * @throws IOException error during query execution
   */
  private StringList execute(final WebDAVQuery query) throws IOException {
    final ClassLoader cl = getClass().getClassLoader();
    final InputStream s = cl.getResourceAsStream(FILE);
    if (s == null) throw new IOException("WebDAV module not found");
    final byte[] module = new IOStream(s).read();

    final QueryProcessor qp = new QueryProcessor(query.toString(), http.context());
    try {
      for (final Entry<String, Object> entry : query.entries()) {
        qp.bind(entry.getKey(), entry.getValue());
      }
      qp.ctx.parseLibrary(string(module), FILE, qp.sc);

      final Result r = qp.execute();
      final int n = (int) r.size();
      final StringList items = new StringList(n);
      for (int i = 0; i < n; i++) {
        final ArrayOutput ao = new ArrayOutput();
        r.serialize(Serializer.get(ao), 0);
        items.add(ao.toString());
      }
      return items;
    } catch (final QueryException ex) {
      throw new BaseXException(ex);
    } catch (final Exception ex) {
      Util.debug(ex);
      throw new BaseXException(ex);
    } finally {
      qp.close();
    }
  }
コード例 #3
0
ファイル: ExploreArea.java プロジェクト: dimitarp/basex-all
 /**
  * Returns the combo box selections and the keys of the specified set.
  *
  * @param key keys
  * @return key array
  */
 private String[] entries(final byte[][] key) {
   final StringList sl = new StringList();
   sl.add(Util.info(INFOENTRIES, key.length));
   for (final byte[] k : key) sl.add(Token.string(k));
   sl.sort(true, true, 1);
   return sl.toArray();
 }
コード例 #4
0
ファイル: Databases.java プロジェクト: dirkk/basex
  /**
   * Returns the sorted names of all available databases and, optionally, backups. Filters for
   * {@code name} if not {@code null} with glob support.
   *
   * @param db return databases?
   * @param backup return backups?
   * @param name name filter (may be {@code null})
   * @return database and backups list
   */
  private StringList list(final boolean db, final boolean backup, final String name) {
    final Pattern pt;
    if (name != null) {
      final String nm =
          REGEX.matcher(name).matches()
              ? IOFile.regex(name)
              : name.replaceAll("([" + REGEXCHARS + "])", "\\\\$1");
      pt = Pattern.compile(nm, Prop.CASE ? 0 : Pattern.CASE_INSENSITIVE);
    } else {
      pt = null;
    }

    final IOFile[] children = soptions.dbpath().children();
    final StringList list = new StringList(children.length);
    final HashSet<String> map = new HashSet<>(children.length);
    for (final IOFile f : children) {
      final String fn = f.name();
      String add = null;
      if (backup && fn.endsWith(IO.ZIPSUFFIX)) {
        final String nn = ZIPPATTERN.split(fn)[0];
        if (!nn.equals(fn)) add = nn;
      } else if (db && f.isDir() && fn.indexOf('.') == -1) {
        add = fn;
      }
      // add entry if it matches the pattern, and has not already been added
      if (add != null && (pt == null || pt.matcher(add).matches()) && map.add(add)) {
        list.add(add);
      }
    }
    return list.sort(false);
  }
コード例 #5
0
ファイル: Find.java プロジェクト: phspaelti/basex
  /**
   * Creates an XQuery representation for the specified table query.
   *
   * @param filter filter terms
   * @param cols filter columns
   * @param elem element flag
   * @param name name of root element
   * @param root root flag
   * @return query
   */
  public static String findTable(
      final StringList filter,
      final TokenList cols,
      final BoolList elem,
      final byte[] name,
      final boolean root) {

    final TokenBuilder tb = new TokenBuilder();
    final int is = filter.size();
    for (int i = 0; i < is; ++i) {
      final String[] spl = split(filter.get(i));
      for (final String s : spl) {
        final byte[] term = trim(replace(token(s), '"', ' '));
        if (term.length == 0) continue;
        tb.add('[');

        final boolean elm = elem.get(i);
        tb.add(elm ? ".//" : "@");
        tb.add("*:");
        tb.add(cols.get(i));

        if (term[0] == '<' || term[0] == '>') {
          tb.add(term[0]);
          tb.addLong(calcNum(substring(term, 1)));
        } else {
          tb.add(" contains text \"");
          tb.add(term);
          tb.add('"');
        }
        tb.add(']');
      }
    }
    return tb.isEmpty() ? "/" : (root ? "/" : "") + Axis.DESCORSELF + "::*:" + string(name) + tb;
  }
コード例 #6
0
 /**
  * Tests if the combo box entries have changed.
  *
  * @param sl strings to be compared
  * @return result of check
  */
 private boolean comboChanged(final StringList sl) {
   if (sl.size() != box.getItemCount()) return true;
   final int is = sl.size();
   for (int i = 0; i < is; ++i) {
     if (!sl.get(i).equals(box.getItemAt(i))) return true;
   }
   return false;
 }
コード例 #7
0
ファイル: List.java プロジェクト: JohnLeM/basex
 /**
  * Returns a list of all databases.
  *
  * @param ctx database context
  * @return list of databases
  */
 public static StringList list(final Context ctx) {
   final StringList db = new StringList();
   for (final IOFile f : ctx.mprop.dbpath().children()) {
     final String name = f.name();
     if (f.isDir() && !name.startsWith(".")) db.add(name);
   }
   return db.sort(false);
 }
コード例 #8
0
ファイル: Databases.java プロジェクト: dirkk/basex
 /**
  * Returns the names of all backups.
  *
  * @return backups
  */
 public StringList backups() {
   final StringList backups = new StringList();
   for (final IOFile f : soptions.dbpath().children()) {
     final String n = f.name();
     if (n.endsWith(IO.ZIPSUFFIX)) backups.add(n.substring(0, n.lastIndexOf('.')));
   }
   return backups;
 }
コード例 #9
0
  /**
   * Creates and shows the combo box.
   *
   * @param sl strings to be added
   */
  private void createCombo(final StringList sl) {
    if (sl == null || sl.size() == 0) {
      pop.setVisible(false);
      return;
    }
    if (comboChanged(sl)) {
      box.setModel(new DefaultComboBoxModel(sl.toArray()));
      box.setSelectedIndex(-1);
      pop = new ComboPopup(box);
    }

    final int w = getFontMetrics(getFont()).stringWidth(pre);
    pop.show(this, Math.min(getWidth(), w), getHeight());
  }
コード例 #10
0
ファイル: Databases.java プロジェクト: dirkk/basex
 /**
  * Returns the name of a specific backup, or all backups found for a specific database, in a
  * descending order.
  *
  * @param db database
  * @return names of specified backups
  */
 public StringList backups(final String db) {
   final StringList backups = new StringList();
   final IOFile file = soptions.dbpath(db + IO.ZIPSUFFIX);
   if (file.exists()) {
     backups.add(db);
   } else {
     final String regex =
         db.replaceAll("([" + REGEXCHARS + "])", "\\\\$1") + DateTime.PATTERN + IO.ZIPSUFFIX;
     for (final IOFile f : soptions.dbpath().children()) {
       final String n = f.name();
       if (n.matches(regex)) backups.add(n.substring(0, n.lastIndexOf('.')));
     }
   }
   return backups.sort(Prop.CASE, false);
 }
コード例 #11
0
ファイル: DialogNew.java プロジェクト: dirkk/basex
  @Override
  public void action(final Object comp) {
    final boolean valid = general.action(comp, true);
    ft.action(ftxindex.isSelected());

    // ...must be located before remaining checks
    if (comp == general.browse || comp == general.input) dbname.setText(general.dbname);

    final String nm = dbname.getText().trim();
    ok = valid && !nm.isEmpty();

    String inf = valid ? ok ? null : ENTER_DB_NAME : RES_NOT_FOUND;
    Msg icon = Msg.ERROR;
    if (ok) {
      ok = Databases.validName(nm);
      if (ok) gui.gopts.set(GUIOptions.DBNAME, nm);

      if (!ok) {
        // name of database is invalid
        inf = Util.info(INVALID_X, NAME);
      } else if (general.input.getText().trim().isEmpty()) {
        // database will be empty
        inf = EMPTY_DB;
        icon = Msg.WARN;
      } else if (db.contains(nm)) {
        // old database will be overwritten
        inf = OVERWRITE_DB;
        icon = Msg.WARN;
      }
    }

    general.info.setText(inf, icon);
    enableOK(buttons, B_OK, ok);
  }
コード例 #12
0
ファイル: BaseXClientTest.java プロジェクト: phspaelti/basex
  /**
   * Runs a request with the specified arguments and server arguments.
   *
   * @param args command-line arguments
   * @param sargs server arguments
   * @return result
   * @throws IOException I/O exception
   */
  private static String run(final String[] args, final String[] sargs) throws IOException {
    final BaseXServer server = createServer(sargs);
    final ArrayOutput ao = new ArrayOutput();
    System.setOut(new PrintStream(ao));
    System.setErr(NULL);

    final StringList sl = new StringList();
    sl.add("-p9999").add("-U" + Text.S_ADMIN).add("-P" + Text.S_ADMIN).add(args);
    try {
      new BaseXClient(sl.finish());
      return ao.toString();
    } finally {
      System.setErr(ERR);
      stopServer(server);
    }
  }
コード例 #13
0
ファイル: Command.java プロジェクト: plutext/basex
 /**
  * Adds the names of the database that has been addressed by the argument index. No databases will
  * be added if the argument uses glob syntax.
  *
  * @param db databases
  * @param a argument index
  * @return {@code false} if database cannot be determined due to glob syntax
  */
 protected final boolean databases(final StringList db, final int a) {
   // return true if the addressed database argument does not exists
   if (args.length <= a || args[a] == null) return true;
   final boolean noglob = !args[a].matches(".*[\\?\\*,].*");
   if (noglob) db.add(args[a]);
   return noglob;
 }
コード例 #14
0
ファイル: Util.java プロジェクト: ngrstad/basex
  /**
   * Starts the specified class in a separate process.
   *
   * @param clz class to start
   * @param args command-line arguments
   * @return reference to a {@link Process} instance representing the started process
   */
  public static Process start(final Class<?> clz, final String... args) {
    final String[] largs = {
      "java",
      "-Xmx" + Runtime.getRuntime().maxMemory(),
      "-cp",
      System.getProperty("java.class.path"),
      clz.getName(),
      "-D",
    };
    final StringList sl = new StringList().add(largs).add(args);

    try {
      return new ProcessBuilder(sl.toArray()).start();
    } catch (final IOException ex) {
      notexpected(ex);
      return null;
    }
  }
コード例 #15
0
 /**
  * Converts the path to a string array, containing the single segments.
  *
  * @param path path, or {@code null}
  * @return path depth
  */
 public static String[] toSegments(final String path) {
   final StringList sl = new StringList();
   if (path != null) {
     final TokenBuilder tb = new TokenBuilder();
     for (int s = 0; s < path.length(); s++) {
       final char ch = path.charAt(s);
       if (ch == '/') {
         if (tb.isEmpty()) continue;
         sl.add(tb.toString());
         tb.reset();
       } else {
         tb.add(ch);
       }
     }
     if (!tb.isEmpty()) sl.add(tb.toString());
   }
   return sl.toArray();
 }
コード例 #16
0
ファイル: EditorView.java プロジェクト: rostam/basex
 /**
  * Refreshes the list of recent query files and updates the query path.
  *
  * @param file new file
  */
 void refreshHistory(final IOFile file) {
   final StringList sl = new StringList();
   String path = null;
   if (file != null) {
     path = file.path();
     gui.gprop.set(GUIProp.WORKPATH, file.dirPath());
     sl.add(path);
     tabs.setToolTipTextAt(tabs.getSelectedIndex(), path);
   }
   final String[] qu = gui.gprop.strings(GUIProp.EDITOR);
   for (int q = 0; q < qu.length && q < 19; q++) {
     final String f = qu[q];
     if (!f.equalsIgnoreCase(path) && IO.get(f).exists()) sl.add(f);
   }
   // store sorted history
   gui.gprop.set(GUIProp.EDITOR, sl.toArray());
   hist.setEnabled(!sl.isEmpty());
 }
コード例 #17
0
ファイル: GUICommands.java プロジェクト: JosuaKrause/basex
    @Override
    public void execute(final GUI gui) {
      final Nodes n = gui.context.marked;
      final DialogInsert insert = new DialogInsert(gui);
      if (!insert.ok()) return;

      final StringList sl = insert.result;
      final NodeType type = ANode.type(insert.kind);
      String item = Token.string(type.string()) + " { " + quote(sl.get(0)) + " }";

      if (type == NodeType.ATT || type == NodeType.PI) {
        item += " { " + quote(sl.get(1)) + " }";
      } else if (type == NodeType.ELM) {
        item += " { () }";
      }

      gui.context.copied = null;
      gui.execute(new XQuery("insert node " + item + " into " + openPre(n, 0)));
    }
コード例 #18
0
ファイル: ProjectFiles.java プロジェクト: vincentml/basex
  /**
   * Refreshes the view after a file has been saved.
   *
   * @param root root directory
   * @param ctx database context
   * @throws InterruptedException interruption
   */
  void parse(final IOFile root, final Context ctx) throws InterruptedException {
    final long id = ++parseId;
    final HashSet<String> parsed = new HashSet<>();
    final TreeMap<String, InputInfo> errs = new TreeMap<>();

    // collect files to be parsed
    final ProjectCache pc = cache(root);
    final StringList mods = new StringList(), lmods = new StringList();
    for (final String path : pc) {
      final IOFile file = new IOFile(path);
      if (file.hasSuffix(IO.XQSUFFIXES)) (file.hasSuffix(IO.XQMSUFFIX) ? lmods : mods).add(path);
    }
    mods.add(lmods);

    // parse modules
    for (final String path : mods) {
      if (id != parseId) throw new InterruptedException();
      if (parsed.contains(path)) continue;

      final IOFile file = new IOFile(path);
      try (final TextInput ti = new TextInput(file)) {
        // parse query
        try (final QueryContext qc = new QueryContext(ctx)) {
          final String input = ti.cache().toString();
          final boolean lib = QueryProcessor.isLibrary(input);
          qc.parse(input, lib, path, null);
          // parsing was successful: remember path
          parsed.add(path);
          for (final byte[] mod : qc.modParsed) parsed.add(Token.string(mod));
        } catch (final QueryException ex) {
          // parsing failed: remember path
          final InputInfo ii = ex.info();
          errs.put(path, ii);
          parsed.add(ii.path());
        }
      } catch (final IOException ex) {
        // file may not be accessible
        Util.debug(ex);
      }
    }
    errors = errs;
  }
コード例 #19
0
ファイル: RestXqFunction.java プロジェクト: jolau/basex-api
 /**
  * Checks if the produced content type matches.
  *
  * @param http http context
  * @return result of check
  */
 private boolean produces(final HTTPContext http) {
   // return true if no type is given
   if (produces.isEmpty()) return true;
   // check if any combination matches
   for (final String pr : http.produces()) {
     for (final String p : produces) {
       if (MimeTypes.matches(p, pr)) return true;
     }
   }
   return false;
 }
コード例 #20
0
ファイル: RestXqFunction.java プロジェクト: jolau/basex-api
 /**
  * Checks if the consumed content type matches.
  *
  * @param http http context
  * @return result of check
  */
 private boolean consumes(final HTTPContext http) {
   // return true if no type is given
   if (consumes.isEmpty()) return true;
   // return true if no content type is specified by the user
   final String ct = http.contentType();
   if (ct == null) return true;
   // check if any combination matches
   for (final String c : consumes) {
     if (MimeTypes.matches(c, ct)) return true;
   }
   return false;
 }
コード例 #21
0
  @Override
  public void close() {
    super.close();

    final String in1 = input1.getText();
    final String in2 = string(input2.getText());
    switch (kind) {
      case Data.ATTR:
      case Data.PI:
        result.add(in1);
        result.add(in2);
        break;
      case Data.ELEM:
        result.add(in1);
        break;
      case Data.TEXT:
      case Data.COMM:
        result.add(in2);
        break;
    }
  }
コード例 #22
0
  @Override
  protected void parseArguments(final String[] args) throws IOException {
    final Args arg = new Args(args, this, SERVERINFO, Util.info(CONSOLE, SERVERMODE));

    commands = new StringList();
    boolean daemon = false;
    while (arg.more()) {
      if (arg.dash()) {
        switch (arg.next()) {
          case 'c': // send database commands
            commands.add(arg.string());
            break;
          case 'd': // activate debug mode
            context.mprop.set(MainProp.DEBUG, true);
            break;
          case 'D': // hidden flag: daemon mode
            daemon = true;
            break;
          case 'e': // parse event port
            context.mprop.set(MainProp.EVENTPORT, arg.number());
            break;
          case 'i': // activate interactive mode
            console = true;
            break;
          case 'p': // parse server port
            context.mprop.set(MainProp.SERVERPORT, arg.number());
            break;
          case 'S': // set service flag
            service = !daemon;
            break;
          case 'z': // suppress logging
            quiet = true;
            break;
          default:
            arg.usage();
        }
      } else {
        if (arg.string().equalsIgnoreCase("stop")) {
          stopped = true;
        } else {
          arg.usage();
        }
      }
    }
  }
コード例 #23
0
ファイル: DialogExport.java プロジェクト: fpapai/basex
  /**
   * Default constructor.
   *
   * @param main reference to the main window
   */
  public DialogExport(final GUI main) {
    super(main, EXPORT);

    // create checkboxes
    final BaseXBack p = new BaseXBack(new TableLayout(4, 1, 0, 0));
    p.add(new BaseXLabel(OUTPUT_DIR + COL, true, true).border(0, 0, 6, 0));

    // output label
    BaseXBack pp = new BaseXBack(new TableLayout(1, 2, 8, 0));

    path = new BaseXTextField(main.gopts.get(GUIOptions.INPUTPATH), this);
    pp.add(path.history(GUIOptions.INPUTS, this));

    final BaseXButton browse = new BaseXButton(BROWSE_D, this);
    browse.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            choose();
          }
        });
    pp.add(browse);
    p.add(pp);

    // provide components for method and encoding
    final MainOptions opts = gui.context.options;
    final SerializerOptions sopts = opts.get(MainOptions.EXPORTER);

    // method (ignore last entry)
    final StringList sl = new StringList();
    for (final SerialMethod sm : SerialMethod.values()) sl.add(sm.name());
    sl.remove(sl.size() - 1);
    method = new BaseXCombo(this, sl.finish());
    final SerialMethod sm = sopts.get(SerializerOptions.METHOD);
    method.setSelectedItem((sm == null ? SerialMethod.BASEX : sm).name());

    mparams = new BaseXTextField(this);
    mparams.setColumns(24);

    final BaseXBack mth = new BaseXBack(new TableLayout(1, 2, 8, 0));
    mth.add(method);
    mth.add(mparams);

    encoding = new BaseXCombo(this, ENCODINGS);
    String enc = sopts.get(SerializerOptions.ENCODING);
    boolean f = false;
    for (final String s : ENCODINGS) f |= s.equals(enc);
    if (!f) {
      enc = enc.toUpperCase(Locale.ENGLISH);
      for (final String s : ENCODINGS) f |= s.equals(enc);
    }
    encoding.setSelectedItem(f ? enc : sopts.get(SerializerOptions.ENCODING));

    params = new BaseXTextField(sopts.toString(), this);
    params.setToolTipText(tooltip(SerializerMode.DEFAULT.get()));

    pp = new BaseXBack(new TableLayout(3, 2, 16, 6)).border(8, 0, 8, 0);
    pp.add(new BaseXLabel(METHOD + COL, true, true));
    pp.add(mth);
    pp.add(new BaseXLabel(ENCODING + COL, true, true));
    pp.add(encoding);
    pp.add(new BaseXLabel(PARAMETERS + COL, true, true));
    pp.add(params);
    p.add(pp);
    info = new BaseXLabel(" ").border(8, 0, 0, 0);
    p.add(info);

    // indentation
    set(p, BorderLayout.CENTER);

    // buttons
    pp = new BaseXBack(new BorderLayout());
    buttons = okCancel();
    pp.add(buttons, BorderLayout.EAST);
    set(pp, BorderLayout.SOUTH);

    action(method);
    finish(null);
  }
コード例 #24
0
ファイル: AProp.java プロジェクト: cristian-chiric/basex
  /**
   * Reads the configuration file and initializes the project properties. The file is located in the
   * project home directory.
   *
   * @param prop property file extension
   */
  protected synchronized void read(final String prop) {
    file = new IOFile(HOME + IO.BASEXSUFFIX + prop);

    final StringList read = new StringList();
    final TokenBuilder err = new TokenBuilder();
    if (!file.exists()) {
      err.addExt("Saving properties in \"%\"..." + NL, file);
    } else {
      BufferedReader br = null;
      try {
        br = new BufferedReader(new FileReader(file.file()));
        for (String line; (line = br.readLine()) != null; ) {
          line = line.trim();
          if (line.isEmpty() || line.charAt(0) == '#') continue;
          final int d = line.indexOf('=');
          if (d < 0) {
            err.addExt("%: \"%\" ignored. " + NL, file, line);
            continue;
          }

          final String val = line.substring(d + 1).trim();
          String key = line.substring(0, d).trim();

          // extract numeric value in key
          int num = 0;
          final int ss = key.length();
          for (int s = 0; s < ss; ++s) {
            if (Character.isDigit(key.charAt(s))) {
              num = Integer.parseInt(key.substring(s));
              key = key.substring(0, s);
              break;
            }
          }
          read.add(key);

          final Object entry = props.get(key);
          if (entry == null) {
            err.addExt("%: \"%\" not found. " + NL, file, key);
          } else if (entry instanceof String) {
            props.put(key, val);
          } else if (entry instanceof Integer) {
            props.put(key, Integer.parseInt(val));
          } else if (entry instanceof Boolean) {
            props.put(key, Boolean.parseBoolean(val));
          } else if (entry instanceof String[]) {
            if (num == 0) {
              props.put(key, new String[Integer.parseInt(val)]);
            } else {
              ((String[]) entry)[num - 1] = val;
            }
          } else if (entry instanceof int[]) {
            ((int[]) entry)[num] = Integer.parseInt(val);
          }
        }
      } catch (final Exception ex) {
        err.addExt("% could not be parsed." + NL, file);
        Util.debug(ex);
      } finally {
        if (br != null)
          try {
            br.close();
          } catch (final IOException ex) {
          }
      }
    }

    // check if all mandatory files have been read
    try {
      if (err.isEmpty()) {
        boolean ok = true;
        for (final Field f : getClass().getFields()) {
          final Object obj = f.get(null);
          if (!(obj instanceof Object[])) continue;
          final String key = ((Object[]) obj)[0].toString();
          ok &= read.contains(key);
        }
        if (!ok) err.addExt("Saving properties in \"%\"..." + NL, file);
      }
    } catch (final IllegalAccessException ex) {
      Util.notexpected(ex);
    }

    if (!err.isEmpty()) {
      Util.err(err.toString());
      write();
    }
  }
コード例 #25
0
ファイル: RestXqFunction.java プロジェクト: jolau/basex-api
  /**
   * Binds the annotated variables.
   *
   * @param http http context
   * @param arg argument array
   * @throws QueryException query exception
   * @throws IOException I/O exception
   */
  void bind(final HTTPContext http, final Expr[] arg) throws QueryException, IOException {
    // bind variables from segments
    for (int s = 0; s < path.size; s++) {
      final Matcher m = TEMPLATE.matcher(path.segment[s]);
      if (!m.find()) continue;
      final QNm qnm = new QNm(token(m.group(1)), context);
      bind(qnm, arg, new Atm(http.segment(s)));
    }

    // cache request body
    final String ct = http.contentType();
    IOContent body = null;

    if (requestBody != null) {
      body = cache(http, null);
      try {
        // bind request body in the correct format
        body.name(http.method + IO.XMLSUFFIX);
        bind(requestBody, arg, Parser.item(body, context.context.prop, ct));
      } catch (final IOException ex) {
        error(INPUT_CONV, ex);
      }
    }

    // bind query parameters
    final Map<String, String[]> params = http.params();
    for (final RestXqParam rxp : queryParams) bind(rxp, arg, params.get(rxp.key));

    // bind form parameters
    if (!formParams.isEmpty()) {
      if (MimeTypes.APP_FORM.equals(ct)) {
        // convert parameters encoded in a form
        body = cache(http, body);
        addParams(body.toString(), params);
      }
      for (final RestXqParam rxp : formParams) bind(rxp, arg, params.get(rxp.key));
    }

    // bind header parameters
    for (final RestXqParam rxp : headerParams) {
      final StringList sl = new StringList();
      final Enumeration<?> en = http.req.getHeaders(rxp.key);
      while (en.hasMoreElements()) {
        for (final String s : en.nextElement().toString().split(", *")) sl.add(s);
      }
      bind(rxp, arg, sl.toArray());
    }

    // bind cookie parameters
    final Cookie[] ck = http.req.getCookies();
    for (final RestXqParam rxp : cookieParams) {
      String v = null;
      if (ck != null) {
        for (final Cookie c : ck) {
          if (rxp.key.equals(c.getName())) v = c.getValue();
        }
      }
      if (v == null) bind(rxp, arg);
      else bind(rxp, arg, v);
    }
  }
コード例 #26
0
ファイル: RestXqFunction.java プロジェクト: jolau/basex-api
  /**
   * Adds items to the specified list.
   *
   * @param value value
   * @param name name
   * @param list list to add values to
   * @throws QueryException HTTP exception
   */
  private void strings(final Value value, final QNm name, final StringList list)
      throws QueryException {

    final long vs = value.size();
    for (int v = 0; v < vs; v++) list.add(toString(value.itemAt(v), name));
  }
コード例 #27
0
ファイル: WebDAVLockService.java プロジェクト: nikhi/basex
 /**
  * Gets lock with given token.
  *
  * @param token lock token
  * @return lock
  * @throws IOException I/O exception
  */
 public String lock(final String token) throws IOException {
   final StringList locks = execute(new WebDAVQuery("w:lock($token)").bind("token", token));
   return locks.isEmpty() ? null : locks.get(0);
 }
コード例 #28
0
ファイル: WebDAVLockService.java プロジェクト: nikhi/basex
 /**
  * Gets active locks for the given resource.
  *
  * @param db database
  * @param path path
  * @return locks
  * @throws IOException I/O exception
  */
 public String lock(final String db, final String path) throws IOException {
   final WebDAVQuery query = new WebDAVQuery("w:locks-on($path)").bind("path", db + SEP + path);
   final StringList sl = execute(query);
   return sl.isEmpty() ? null : sl.get(0);
 }
コード例 #29
0
ファイル: NameUpdate.java プロジェクト: runeengh/basex
 /**
  * Adds all databases to be updated to the specified list.
  *
  * @param db databases
  */
 public void databases(final StringList db) {
   db.add(name);
 }
コード例 #30
0
ファイル: BaseX.java プロジェクト: james-jw/basex
  /**
   * Constructor.
   *
   * @param args command-line arguments
   * @throws IOException I/O exception
   */
  public BaseX(final String... args) throws IOException {
    super(args);

    // create session to show optional login request
    session();

    console = true;
    try {
      // loop through all commands
      final StringBuilder bind = new StringBuilder();
      SerializerOptions sopts = null;
      boolean v = false, qi = false, qp = false;
      final int os = ops.size();
      for (int o = 0; o < os; o++) {
        final int c = ops.get(o);
        String val = vals.get(o);

        if (c == 'b') {
          // set/add variable binding
          if (bind.length() != 0) bind.append(',');
          // commas are escaped by a second comma
          val = bind.append(val.replaceAll(",", ",,")).toString();
          execute(new Set(MainOptions.BINDINGS, val), false);
        } else if (c == 'c') {
          // evaluate commands
          final IO io = IO.get(val);
          String base = ".";
          if (io.exists() && !io.isDir()) {
            val = io.string();
            base = io.path();
          }
          execute(new Set(MainOptions.QUERYPATH, base), false);
          execute(val);
          execute(new Set(MainOptions.QUERYPATH, ""), false);
          console = false;
        } else if (c == 'D') {
          // hidden option: show/hide dot query graph
          execute(new Set(MainOptions.DOTPLAN, null), false);
        } else if (c == 'i') {
          // open database or create main memory representation
          execute(new Set(MainOptions.MAINMEM, true), false);
          execute(new Check(val), verbose);
          execute(new Set(MainOptions.MAINMEM, false), false);
        } else if (c == 'I') {
          // set/add variable binding
          if (bind.length() != 0) bind.append(',');
          // commas are escaped by a second comma
          val = bind.append("=").append(val.replaceAll(",", ",,")).toString();
          execute(new Set(MainOptions.BINDINGS, val), false);
        } else if (c == 'o') {
          // change output stream
          if (out != System.out) out.close();
          out = new PrintOutput(val);
          session().setOutputStream(out);
        } else if (c == 'q') {
          // evaluate query
          execute(new XQuery(val), verbose);
          console = false;
        } else if (c == 'Q') {
          // evaluate file contents or string as query
          final IO io = IO.get(val);
          String base = ".";
          if (io.exists() && !io.isDir()) {
            val = io.string();
            base = io.path();
          }
          execute(new Set(MainOptions.QUERYPATH, base), false);
          execute(new XQuery(val), verbose);
          execute(new Set(MainOptions.QUERYPATH, ""), false);
          console = false;
        } else if (c == 'r') {
          // parse number of runs
          execute(new Set(MainOptions.RUNS, Strings.toInt(val)), false);
        } else if (c == 'R') {
          // toggle query evaluation
          execute(new Set(MainOptions.RUNQUERY, null), false);
        } else if (c == 's') {
          // set/add serialization parameter
          if (sopts == null) sopts = new SerializerOptions();
          final String[] kv = val.split("=", 2);
          sopts.assign(kv[0], kv.length > 1 ? kv[1] : "");
          execute(new Set(MainOptions.SERIALIZER, sopts), false);
        } else if (c == 't') {
          // evaluate query
          execute(new Test(val), verbose);
          console = false;
        } else if (c == 'u') {
          // (de)activate write-back for updates
          execute(new Set(MainOptions.WRITEBACK, null), false);
        } else if (c == 'v') {
          // show/hide verbose mode
          v ^= true;
        } else if (c == 'V') {
          // show/hide query info
          qi ^= true;
          execute(new Set(MainOptions.QUERYINFO, null), false);
        } else if (c == 'w') {
          // toggle chopping of whitespaces
          execute(new Set(MainOptions.CHOP, null), false);
        } else if (c == 'x') {
          // show/hide xml query plan
          execute(new Set(MainOptions.XMLPLAN, null), false);
          qp ^= true;
        } else if (c == 'X') {
          // show query plan before/after query compilation
          execute(new Set(MainOptions.COMPPLAN, null), false);
        } else if (c == 'z') {
          // toggle result serialization
          execute(new Set(MainOptions.SERIALIZE, null), false);
        }
        verbose = qi || qp || v;
      }
      if (console) console();
    } finally {
      quit();
    }
  }