/** Wait for the server to die. */
  private void waitForDeath() throws CommandException {
    if (!programOpts.isTerse()) {
      // use stdout because logger always appends a newline
      System.out.print(Strings.get("StopInstance.waitForDeath") + " ");
    }
    long startWait = System.currentTimeMillis();
    boolean alive = true;
    int count = 0;

    while (!timedOut(startWait)) {
      if (!isRunning()) {
        alive = false;
        break;
      }
      try {
        Thread.sleep(100);
        if (!programOpts.isTerse() && count++ % 10 == 0) System.out.print(".");
      } catch (InterruptedException ex) {
        // don't care
      }
    }

    if (!programOpts.isTerse()) System.out.println();

    if (alive) {
      throw new CommandException(
          Strings.get("StopInstance.instanceNotDead", (CLIConstants.DEATH_TIMEOUT_MS / 1000)));
    }
  }
Beispiel #2
0
  /*
   * return 0 is success, otherwise failure
   */
  public final int runAdminCommandOnRemoteNode(
      Node thisNode, StringBuilder output, List<String> args, List<String> stdinLines)
      throws SSHCommandExecutionException, IllegalArgumentException, UnsupportedOperationException {

    String humanreadable = null;
    try {
      this.node = thisNode;
      dcomInfo = new DcomInfo(node);
      List<String> fullcommand = new ArrayList<String>();
      WindowsRemoteAsadmin asadmin = dcomInfo.getAsadmin();

      if (stdinLines != null && !stdinLines.isEmpty()) setupAuthTokenFile(fullcommand, stdinLines);

      fullcommand.addAll(args);
      humanreadable = dcomInfo.getNadminPath() + " " + commandListToString(fullcommand);

      // This is where the rubber meets the road...
      String out = asadmin.run(fullcommand);
      output.append(out);
      logger.info(Strings.get("remote.command.summary", humanreadable, out));
      return determineStatus(args);
    } catch (WindowsException ex) {
      throw new SSHCommandExecutionException(
          Strings.get("remote.command.error", ex.getMessage(), humanreadable), ex);
    } finally {
      teardownAuthTokenFile();
    }
  }
 void put(final URI uri, ArtifactData data) throws Exception {
   reporter.trace("put %s %s", uri, data);
   File tmp = createTempFile(repoDir, "mtp", ".whatever");
   tmp.deleteOnExit();
   try {
     copy(uri.toURL(), tmp);
     byte[] sha = SHA1.digest(tmp).digest();
     reporter.trace("SHA %s %s", uri, Hex.toHexString(sha));
     ArtifactData existing = get(sha);
     if (existing != null) {
       reporter.trace("existing");
       xcopy(existing, data);
       return;
     }
     File meta = new File(repoDir, Hex.toHexString(sha) + ".json");
     File file = new File(repoDir, Hex.toHexString(sha));
     rename(tmp, file);
     reporter.trace("file %s", file);
     data.file = file.getAbsolutePath();
     data.sha = sha;
     data.busy = false;
     CommandData cmddata = parseCommandData(data);
     if (cmddata.bsn != null) {
       data.name = cmddata.bsn + "-" + cmddata.version;
     } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri);
     codec.enc().to(meta).put(data);
     reporter.trace("TD = " + data);
   } finally {
     tmp.delete();
     reporter.trace("puted %s %s", uri, data);
   }
 }
Beispiel #4
0
  /**
   * Constructor.
   *
   * @param os output stream
   * @param sopts serializer options
   * @throws QueryIOException query I/O exception
   */
  protected OutputSerializer(final OutputStream os, final SerializerOptions sopts)
      throws QueryIOException {

    this.sopts = sopts;
    indent = sopts.yes(INDENT);

    // project-specific options
    indents = sopts.get(INDENTS);
    tab = sopts.yes(TABULATOR) ? '\t' : ' ';

    encoding = Strings.normEncoding(sopts.get(ENCODING), true);
    PrintOutput po;
    if (encoding == Strings.UTF8) {
      po = PrintOutput.get(os);
    } else {
      try {
        po = new EncoderOutput(os, Charset.forName(encoding));
      } catch (final Exception ex) {
        throw SERENCODING_X.getIO(encoding);
      }
    }
    final int limit = sopts.get(LIMIT);
    if (limit != -1) po.setLimit(limit);

    final byte[] nl = token(sopts.get(NEWLINE).newline());
    if (nl.length != 1 || nl[0] != '\n') po = new NewlineOutput(po, nl);
    out = po;
  }
Beispiel #5
0
 private void printScriptFrames(StringBuilder sb, Realm realm, Throwable e, int level) {
   final String indent = Strings.repeat('\t', level);
   final int maxDepth = options.stacktraceDepth;
   int depth = 0;
   StackTraceElement[] stackTrace = StackTraces.scriptStackTrace(e);
   for (; depth < Math.min(stackTrace.length, maxDepth); ++depth) {
     StackTraceElement element = stackTrace[depth];
     String methodName = element.getMethodName();
     String fileName = element.getFileName();
     int lineNumber = element.getLineNumber();
     sb.append(indent)
         .append("at ")
         .append(methodName)
         .append(" (")
         .append(fileName)
         .append(':')
         .append(lineNumber)
         .append(")\n");
   }
   if (depth < stackTrace.length) {
     int skipped = stackTrace.length - depth;
     sb.append("\t.. ").append(skipped).append(" frames omitted\n");
   }
   if (e.getSuppressed().length > 0 && level == 1) {
     Throwable suppressed = e.getSuppressed()[0];
     String message;
     if (suppressed instanceof ScriptException) {
       message = ((ScriptException) suppressed).getMessage(realm.defaultContext());
     } else {
       message = Objects.toString(suppressed.getMessage(), suppressed.getClass().getSimpleName());
     }
     sb.append(indent).append(formatMessage("suppressed_exception", message)).append('\n');
     printScriptFrames(sb, realm, suppressed, level + 1);
   }
 }
Beispiel #6
0
 private void teardownAuthTokenFile() {
   if (authTokenFile != null)
     try {
       authTokenFile.delete();
     } catch (WindowsException ex) {
       logger.warning(Strings.get("cant.delete", dcomInfo.getHost(), authTokenFilePath));
     }
 }
 private String getHQLCondition(boolean order) throws XavaException {
   StringBuffer sb = new StringBuffer("from ");
   sb.append(getMetaModel().getName());
   sb.append(" as o");
   if (!Is.emptyString(this.condition)) {
     sb.append(" where ");
     String condition = transformAggregateProperties(getCondition());
     condition = Strings.change(condition, getArgumentsToHQL());
     sb.append(Strings.change(condition, getTokensToChangeDollarsAndNL()));
   }
   if (order && !Is.emptyString(this.order)) {
     sb.append(" order by ");
     sb.append(
         Strings.change(
             transformAggregateProperties(this.order), getTokensToChangeDollarsAndNL()));
   }
   return sb.toString();
 }
  /** Print message and return exit code when we detect that the DAS is not running. */
  protected int instanceNotRunning() throws CommandException {
    if (kill) return kill();

    // by definition this is not an error
    // https://glassfish.dev.java.net/issues/show_bug.cgi?id=8387

    logger.warning(Strings.get("StopInstance.instanceNotRunning"));
    return 0;
  }
 /**
  * Turn the shas into a readable form
  *
  * @param dependencies
  * @return
  * @throws Exception
  */
 public List<?> toString(List<byte[]> dependencies) throws Exception {
   List<String> out = new ArrayList<String>();
   for (byte[] dependency : dependencies) {
     ArtifactData data = get(dependency);
     if (data == null) out.add(Hex.toHexString(dependency));
     else {
       out.add(Strings.display(data.name, Hex.toHexString(dependency)));
     }
   }
   return out;
 }
  private int kill() throws CommandException {
    File prevPid = null;
    String pids = null;

    try {
      prevPid = new File(getServerDirs().getPidFile().getPath() + ".prev");

      if (!prevPid.canRead())
        throw new CommandException(Strings.get("StopInstance.nopidprev", prevPid));

      pids = FileUtils.readSmallFile(prevPid).trim();
      String s = ProcessUtils.kill(Integer.parseInt(pids));

      if (s != null) logger.finer(s);
    } catch (CommandException ce) {
      throw ce;
    } catch (Exception ex) {
      throw new CommandException(
          Strings.get("StopInstance.pidprevreaderror", prevPid, ex.getMessage()));
    }
    return 0;
  }
Beispiel #11
0
  private void handleException(ParserExceptionWithSource exception) {
    ParserException e = exception.getCause();
    String sourceCode = exception.getSourceCode();
    int lineOffset = exception.getSource().getLine();

    String sourceInfo = String.format("%s:%d:%d", e.getFile(), e.getLine(), e.getColumn());
    int start = skipLines(sourceCode, e.getLine() - lineOffset);
    int end = nextLineTerminator(sourceCode, start);
    String offendingLine = sourceCode.substring(start, end);
    String marker = Strings.repeat('.', Math.max(e.getColumn() - 1, 0)) + '^';

    console.printf("%s %s: %s%n", sourceInfo, e.getType(), e.getFormattedMessage());
    console.printf("%s %s%n", sourceInfo, offendingLine);
    console.printf("%s %s%n", sourceInfo, marker);
    printStackTrace(e);
  }
 public String getEJBQLCondition() throws XavaException {
   StringBuffer sb = new StringBuffer("SELECT OBJECT(o) FROM ");
   sb.append(getMetaModel().getName());
   sb.append(" o");
   if (!Is.emptyString(this.condition)) {
     sb.append(" WHERE ");
     String attributesCondition =
         getMetaModel().getMapping().changePropertiesByCMPAttributes(this.condition);
     sb.append(Strings.change(attributesCondition, getArgumentsJBoss11ToEJBQL()));
   }
   if (!Is.emptyString(this.order)) {
     sb.append(" ORDER BY ");
     sb.append(getMetaModel().getMapping().changePropertiesByCMPAttributes(this.order));
   }
   return sb.toString();
 }
Beispiel #13
0
  /**
   * 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();
    }
  }
 /** Print message and return exit code when we detect that there is no such instance */
 private int noSuchInstance() {
   // by definition this is not an error
   // https://glassfish.dev.java.net/issues/show_bug.cgi?id=8387
   logger.warning(Strings.get("Instance.noSuchInstance"));
   return 0;
 }
 public String getColumnName(int c) {
   return labelAsHeader
       ? getMetaProperty(c).getLabel(locale)
       : Strings.change(getMetaProperty(c).getQualifiedName(), ".", "_");
 }
Beispiel #16
0
 public Char get(int index) {
   return Char.valueOf(Strings.characterAt(base, start, end, index + start));
 }
 public String getArguments() {
   arguments = Strings.change(arguments, "String", "java.lang.String");
   arguments = Strings.change(arguments, "java.lang.java.lang.String", "java.lang.String");
   return arguments;
 }