Пример #1
0
  @Override
  protected void doExecute(ApplicationService applicationService)
      throws ApplicationServiceException {

    Set<Application> applications = applicationService.getApplications();
    console.printf("%s%10s%n", "State", "Name");
    for (Application curApp : applications) {
      ApplicationStatus appStatus = applicationService.getApplicationStatus(curApp);
      // only show applications that have features (gets rid of repo
      // aggregator 'apps')
      if (!curApp.getFeatures().isEmpty()) {
        console.print("[");
        switch (appStatus.getState()) {
          case ACTIVE:
            console.print(Ansi.ansi().fg(Ansi.Color.GREEN).toString());
            break;
          case FAILED:
            console.print(Ansi.ansi().fg(Ansi.Color.RED).toString());
            break;
          case INACTIVE:
            // don't set a color
            break;
          case UNKNOWN:
            console.print(Ansi.ansi().fg(Ansi.Color.YELLOW).toString());
            break;
          default:
            break;
        }
        console.print(StringUtils.rightPad(appStatus.getState().toString(), STATUS_COLUMN_LENGTH));
        console.print(Ansi.ansi().reset().toString());
        console.println("] " + curApp.getName());
      }
    }
    return;
  }
Пример #2
0
 /**
  * prompts the user with the given question.
  *
  * @param session the command session.
  * @param messageKey the message key.
  * @param messageArgs the message arguments.
  * @return true if user hits 'y' OR 'yes' else returns false
  * @throws IOException Indicates a failure while accessing the session's stdout.
  */
 public static boolean promptUser(
     final CommandSession session, final String messageKey, final Object... messageArgs)
     throws IOException {
   if ((Boolean) session.get(Constants.INTERACTIVE_MODE)) {
     session.getConsole().print(Ansi.ansi().eraseLine(Erase.ALL));
     final String confirmationQuestion = ShellUtils.getFormattedMessage(messageKey, messageArgs);
     session.getConsole().print(confirmationQuestion + " ");
     session.getConsole().flush();
     char responseChar = '\0';
     final StringBuilder responseBuffer = new StringBuilder();
     while (true) {
       responseChar = (char) session.getKeyboard().read();
       if (responseChar == '\u007F') { // backspace
         if (responseBuffer.length() > 0) {
           responseBuffer.deleteCharAt(responseBuffer.length() - 1);
           session.getConsole().print(Ansi.ansi().cursorLeft(1).eraseLine());
         }
       } else if (responseChar == WIN_RETURN_CHAR || responseChar == LINUX_RETURN_CHAR) {
         session.getConsole().println();
         break;
       } else {
         session.getConsole().print(responseChar);
         responseBuffer.append(responseChar);
       }
       session.getConsole().flush();
     }
     final String responseStr = responseBuffer.toString().trim();
     return "y".equalsIgnoreCase(responseStr) || "yes".equalsIgnoreCase(responseStr);
   }
   // Shell is running in nonInteractive mode. we skip the question.
   return true;
 }
Пример #3
0
 String withColor(Color color, boolean bright, Attribute attribute, String text) {
   if (withColor) {
     Ansi ansi = bright ? Ansi.ansi().fgBright(color) : Ansi.ansi().fg(color);
     if (attribute != null) {
       ansi = ansi.a(attribute);
     }
     return ansi.a(text).reset().toString();
   }
   return text;
 }
Пример #4
0
  /**
   * Outputs normal info to the console with a green color.
   *
   * @param msg - Info message
   */
  public synchronized void info(String msg) {
    this.logger.info(
        Ansi.ansi().fg(Ansi.Color.GREEN)
            + ConsoleLogger.template
            + "["
            + this.name
            + "] - "
            + msg
            + Ansi.ansi().fg(Ansi.Color.WHITE));

    broadcastToListeners("info", msg);
  }
Пример #5
0
  /**
   * Outputs warnings to the console with a yellow color.
   *
   * @param msg - Warning message
   */
  public synchronized void warning(String msg) {
    this.logger.warning(
        Ansi.ansi().fg(Ansi.Color.YELLOW)
            + ConsoleLogger.template
            + "["
            + this.name
            + "] - "
            + msg
            + Ansi.ansi().fg(Ansi.Color.WHITE));

    broadcastToListeners("warning", msg);
  }
Пример #6
0
  /**
   * Outputs severe messages to the console with a red color.
   *
   * @param msg - Severe message
   */
  public synchronized void severe(String msg) {
    this.logger.severe(
        Ansi.ansi().fg(Ansi.Color.RED)
            + ConsoleLogger.template
            + "["
            + this.name
            + "] - "
            + msg
            + Ansi.ansi().fg(Ansi.Color.WHITE));

    broadcastToListeners("severe", msg);
  }
Пример #7
0
  /**
   * This will only output if the debug is set to true. Outputs with a cyan color.
   *
   * @param msg - Debug message
   */
  public synchronized void debug(String msg) {
    if (debug == true)
      this.logger.info(
          Ansi.ansi().fg(Ansi.Color.CYAN)
              + ConsoleLogger.template
              + "DEBUG ["
              + this.name
              + "] - "
              + msg
              + Ansi.ansi().fg(Ansi.Color.WHITE));

    broadcastToListeners("debug", msg);
  }
Пример #8
0
  private static void renderErrorLocation(String query, ErrorLocation location, PrintStream out) {
    List<String> lines = ImmutableList.copyOf(Splitter.on('\n').split(query).iterator());

    String errorLine = lines.get(location.getLineNumber() - 1);
    String good = errorLine.substring(0, location.getColumnNumber() - 1);
    String bad = errorLine.substring(location.getColumnNumber() - 1);

    if ((location.getLineNumber() == lines.size()) && bad.trim().isEmpty()) {
      bad = " <EOF>";
    }

    if (REAL_TERMINAL) {
      Ansi ansi = Ansi.ansi();

      ansi.fg(Ansi.Color.CYAN);
      for (int i = 1; i < location.getLineNumber(); i++) {
        ansi.a(lines.get(i - 1)).newline();
      }
      ansi.a(good);

      ansi.fg(Ansi.Color.RED);
      ansi.a(bad).newline();
      for (int i = location.getLineNumber(); i < lines.size(); i++) {
        ansi.a(lines.get(i)).newline();
      }

      ansi.reset();
      out.print(ansi);
    } else {
      String prefix = format("LINE %s: ", location.getLineNumber());
      String padding = Strings.repeat(" ", prefix.length() + (location.getColumnNumber() - 1));
      out.println(prefix + errorLine);
      out.println(padding + "^");
    }
  }
Пример #9
0
  /** Print all rules along with their descriptions to STDOUT. */
  public static void printRules() {
    Rules[] rules = Rules.values();

    AnsiConsole.out.println(
        Ansi.ansi().render(String.format("@|bold %d rules available|@%n", rules.length)));
    for (Rules rule : rules) {
      AnsiConsole.out.println(
          Ansi.ansi()
              .render(
                  String.format(
                      "@|bold %s|@%n"
                          + "@|underline Description:|@ %s%n"
                          + "@|underline Style Guide:|@ %s%n",
                      rule.getName(), rule.getDescription(), rule.getLink())));
    }
  }
Пример #10
0
  public synchronized void renameInstance(String oldName, String newName) throws Exception {
    if (instances.get(newName) != null) {
      throw new IllegalArgumentException("Instance " + newName + " already exists");
    }
    Instance instance = instances.get(oldName);
    if (instance == null) {
      throw new IllegalArgumentException("Instance " + oldName + " not found");
    }
    if (instance.isRoot()) {
      throw new IllegalArgumentException("You can't rename the root instance");
    }
    if (instance.getPid() != 0) {
      throw new IllegalStateException("Instance not stopped");
    }

    println(
        Ansi.ansi()
            .a("Renaming instance ")
            .a(Ansi.Attribute.INTENSITY_BOLD)
            .a(oldName)
            .a(Ansi.Attribute.RESET)
            .a(" to ")
            .a(Ansi.Attribute.INTENSITY_BOLD)
            .a(newName)
            .a(Ansi.Attribute.RESET)
            .toString());
    // remove the old instance
    instances.remove(oldName);
    // update instance
    instance.setName(newName);
    // rename directory
    String oldLocationPath = instance.getLocation();
    File oldLocation = new File(oldLocationPath);
    String basedir = oldLocation.getParent();
    File newLocation = new File(basedir, newName);
    oldLocation.renameTo(newLocation);
    // update the instance location
    instance.setLocation(newLocation.getPath());
    // create the properties map including the instance name and instance location
    HashMap<String, String> props = new HashMap<String, String>();
    props.put(oldName, newName);
    props.put(oldLocationPath, newLocation.getPath());
    // replace all references to the "old" name by the new one in etc/system.properties
    // NB: it's replacement to avoid to override the user's changes
    filterResource(newLocation, "etc/system.properties", props);
    // replace all references to the "old" name by the new one in bin/karaf
    filterResource(newLocation, "bin/karaf", props);
    filterResource(newLocation, "bin/start", props);
    filterResource(newLocation, "bin/stop", props);
    filterResource(newLocation, "bin/karaf.bat", props);
    filterResource(newLocation, "bin/start.bat", props);
    filterResource(newLocation, "bin/stop.bat", props);
    // add the renamed instances
    instances.put(newName, instance);
    // save instance definition in the instances.properties
    saveState();
  }
Пример #11
0
 /**
  * Append text with the given ANSI codes.
  *
  * @param text the text to append
  * @param codes the ANSI codes
  * @return this string
  */
 AnsiString append(String text, Code... codes) {
   if (codes.length == 0 || !isAnsiSupported()) {
     this.value.append(text);
     return this;
   }
   Ansi ansi = Ansi.ansi();
   for (Code code : codes) {
     ansi = applyCode(ansi, code);
   }
   this.value.append(ansi.a(text).reset().toString());
   return this;
 }
Пример #12
0
 private void mkdir(File karafBase, String path) {
   File file = new File(karafBase, path);
   if (!file.exists()) {
     println(
         Ansi.ansi()
             .a("Creating dir:  ")
             .a(Ansi.Attribute.INTENSITY_BOLD)
             .a(file.getPath())
             .a(Ansi.Attribute.RESET)
             .toString());
     file.mkdirs();
   }
 }
Пример #13
0
public class Logger {

  private final String ansi_green = Ansi.ansi().fg(Ansi.Color.GREEN).boldOff().toString();
  private final String ansi_yellow = Ansi.ansi().fg(Ansi.Color.YELLOW).boldOff().toString();
  private final String ansi_red = Ansi.ansi().fg(Ansi.Color.RED).boldOff().toString();

  private final String ansi_underline =
      Ansi.ansi().a(Ansi.Attribute.UNDERLINE).boldOff().toString();
  private final String ansi_reset = Ansi.ansi().a(Ansi.Attribute.RESET).boldOff().toString();

  public void notice(String s, Class<?> c) {
    System.out.println(ansi_green + "[GTAShops (" + c.getSimpleName() + ")] " + s + ansi_reset);
  }

  public void debug(String s, Class<?> c) {
    System.out.println(
        ansi_yellow
            + "(DE) "
            + ansi_reset
            + "[GTAShops ("
            + c.getSimpleName()
            + ")] "
            + s
            + ansi_reset);
  }

  public void log(String s, Class<?> c) {
    System.out.println("[GTAShops (" + c.getSimpleName() + ")] " + s);
  }

  public void warning(String s, Class<?> c) {
    System.out.println(ansi_yellow + "[GTAShops (" + c.getSimpleName() + ")] " + s + ansi_reset);
  }

  public void error(String s, Class<?> c) {
    System.out.println(ansi_red + "[GTAShops(" + c.getSimpleName() + ")] " + s + ansi_reset);
  }
}
Пример #14
0
 private void copyFilteredResourceToDir(
     File target, String resource, HashMap<String, String> props) throws Exception {
   File outFile = new File(target, resource);
   if (!outFile.exists()) {
     println(
         Ansi.ansi()
             .a("Creating file: ")
             .a(Ansi.Attribute.INTENSITY_BOLD)
             .a(outFile.getPath())
             .a(Ansi.Attribute.RESET)
             .toString());
     InputStream is =
         getClass().getClassLoader().getResourceAsStream("org/apache/karaf/admin/" + resource);
     copyAndFilterResource(is, new FileOutputStream(outFile), props);
   }
 }
Пример #15
0
  @Override
  protected Object doExecute() throws Exception {
    History history = (History) session.get(".jline.history");

    for (History.Entry element : history) {
      System.out.println(
          Ansi.ansi()
              .a("  ")
              .a(Ansi.Attribute.INTENSITY_BOLD)
              .render("%3d", element.index())
              .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
              .a("  ")
              .a(element.value())
              .toString());
    }
    return null;
  }
Пример #16
0
 private String colorize(String string) {
   if (string.indexOf(ChatColor.COLOR_CHAR) < 0) {
     return string; // no colors in the message
   } else if (!jLine || !reader.getTerminal().isAnsiSupported()) {
     return ChatColor.stripColor(string); // color not supported
   } else {
     // colorize or strip all colors
     for (ChatColor color : colors) {
       if (replacements.containsKey(color)) {
         string = string.replaceAll("(?i)" + color.toString(), replacements.get(color));
       } else {
         string = string.replaceAll("(?i)" + color.toString(), "");
       }
     }
     return string + Ansi.ansi().reset().toString();
   }
 }
Пример #17
0
 public String ask(final String question) {
   if (withColor) {
     write(
         console,
         false,
         Ansi.ansi()
             .fgBright(Ansi.Color.WHITE)
             .bold()
             .a(question + " ")
             .boldOff()
             .reset()
             .toString());
   } else {
     write(console, false, question + " ");
   }
   return System.console().readLine();
 }
Пример #18
0
 public char[] askSecret(final String question) {
   if (withColor) {
     write(
         console,
         false,
         Ansi.ansi()
             .fgBright(Ansi.Color.CYAN)
             .bold()
             .a(question + " ")
             .boldOff()
             .reset()
             .toString());
   } else {
     write(console, false, question + " ");
   }
   return System.console().readPassword();
 }
Пример #19
0
 private void printValue(String name, int pad, String value) {
   if (value == null) {
     value = "<not set>";
   } else if (value.equals("")) {
     value = "<empty>";
   }
   System.out.println(
       Ansi.ansi()
           .a("  ")
           .a(Ansi.Attribute.INTENSITY_BOLD)
           .a(name)
           .a(spaces(pad - name.length()))
           .a(Ansi.Attribute.RESET)
           .a("   ")
           .a(value)
           .toString());
 }
Пример #20
0
 public static void main(String args[]) throws Exception {
   Main main = new Main();
   try {
     main.run(args);
   } catch (CommandNotFoundException cnfe) {
     String str =
         Ansi.ansi()
             .fg(Ansi.Color.RED)
             .a("Command not found: ")
             .a(Ansi.Attribute.INTENSITY_BOLD)
             .a(cnfe.getCommand())
             .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
             .fg(Ansi.Color.DEFAULT)
             .toString();
     System.err.println(str);
     System.exit(Errno.UNKNOWN.getErrno());
   } catch (CommandException ce) {
     System.err.println(ce.getNiceHelp());
     System.exit(Errno.UNKNOWN.getErrno());
   } catch (Throwable t) {
     exitIfThrowableMatches(t, AuthorizationException.class, Errno.EACCES, "Authorization error");
     exitIfThrowableMatches(
         t, ContainerNotFoundException.class, Errno.ENOENT, "Container not found");
     // FileNotFoundException must precede IOException due to inheritance
     exitIfThrowableMatches(t, FileNotFoundException.class, Errno.ENOENT, "File not found");
     // UnknownHostException must precede IOException due to inheritance
     exitIfThrowableMatches(t, UnknownHostException.class, Errno.ENXIO, "Unknown host");
     exitIfThrowableMatches(t, IOException.class, Errno.EIO, "IO error");
     exitIfThrowableMatches(
         t, InsufficientResourcesException.class, Errno.EDQUOT, "Insufficient resources");
     exitIfThrowableMatches(t, KeyNotFoundException.class, Errno.ENOENT, "Blob not found");
     exitIfThrowableMatches(
         t, ResourceAlreadyExistsException.class, Errno.EEXIST, "Resource already exists");
     // ContainerNotFoundException and KeyNotFoundException must precede ResourceNotFoundException
     // due to inheritance
     exitIfThrowableMatches(
         t, ResourceNotFoundException.class, Errno.ENOENT, "Resource not found");
     exitIfThrowableMatches(t, TimeoutException.class, Errno.ETIMEDOUT, "Timeout");
     t.printStackTrace();
     System.exit(Errno.UNKNOWN.getErrno());
   }
   // We must explicitly exit on success since we do not close
   // BlobStoreContext and ComputeServiceContext.
   System.exit(0);
 }
Пример #21
0
 private void copyResourceToDir(File target, String resource, boolean text) throws Exception {
   File outFile = new File(target, resource);
   if (!outFile.exists()) {
     println(
         Ansi.ansi()
             .a("Creating file: ")
             .a(Ansi.Attribute.INTENSITY_BOLD)
             .a(outFile.getPath())
             .a(Ansi.Attribute.RESET)
             .toString());
     InputStream is =
         getClass().getClassLoader().getResourceAsStream("org/apache/karaf/admin/" + resource);
     try {
       if (text) {
         // Read it line at a time so that we can use the platform line ending when we write it
         // out.
         PrintStream out = new PrintStream(new FileOutputStream(outFile));
         try {
           Scanner scanner = new Scanner(is);
           while (scanner.hasNextLine()) {
             String line = scanner.nextLine();
             out.println(line);
           }
         } finally {
           safeClose(out);
         }
       } else {
         // Binary so just write it out the way it came in.
         FileOutputStream out = new FileOutputStream(new File(target, resource));
         try {
           int c = 0;
           while ((c = is.read()) >= 0) {
             out.write(c);
           }
         } finally {
           safeClose(out);
         }
       }
     } finally {
       safeClose(is);
     }
   }
 }
Пример #22
0
  public synchronized Instance cloneInstance(
      String name, String cloneName, InstanceSettings settings) throws Exception {
    if (instances.get(cloneName) != null) {
      throw new IllegalArgumentException("Instance " + cloneName + " already exists");
    }
    Instance instance = instances.get(name);
    if (instance == null) {
      throw new IllegalArgumentException("Instance " + name + " not found");
    }
    if (instance.isRoot()) {
      throw new IllegalArgumentException("You can't clone the root instance");
    }
    if (instance.getPid() != 0) {
      throw new IllegalStateException("Instance not stopped");
    }

    println(
        Ansi.ansi()
            .a("Cloning instance ")
            .a(Ansi.Attribute.INTENSITY_BOLD)
            .a(name)
            .a(Ansi.Attribute.RESET)
            .a(" into ")
            .a(Ansi.Attribute.INTENSITY_BOLD)
            .a(cloneName)
            .toString());
    // define the clone instance location
    String cloneLocationPath = settings.getLocation() != null ? settings.getLocation() : name;
    File cloneLocation = new File(cloneLocationPath);
    if (!cloneLocation.isAbsolute()) {
      cloneLocation = new File(storageLocation, cloneLocationPath);
    }
    // copy instance directory
    String locationPath = instance.getLocation();
    File location = new File(locationPath);
    copy(location, cloneLocation);
    // create the properties map including the instance name, location, ssh and rmi port numbers
    HashMap<String, String> props = new HashMap<String, String>();
    props.put(name, cloneName);
    props.put(locationPath, cloneLocationPath);
    if (settings.getSshPort() > 0)
      props.put(
          new Integer(instance.getSshPort()).toString(),
          new Integer(settings.getSshPort()).toString());
    if (settings.getRmiRegistryPort() > 0)
      props.put(
          new Integer(instance.getRmiRegistryPort()).toString(),
          new Integer(settings.getRmiRegistryPort()).toString());
    if (settings.getRmiServerPort() > 0)
      props.put(
          new Integer(instance.getRmiServerPort()).toString(),
          new Integer(settings.getRmiServerPort()).toString());
    // filtering clone files
    filterResource(cloneLocation, "etc/customer.properties", props);
    filterResource(cloneLocation, "etc/org.apache.karaf.management.cfg", props);
    filterResource(cloneLocation, "etc/org.apache.karaf.shell.cfg", props);
    filterResource(cloneLocation, "etc/org.ops4j.pax.logging.cfg", props);
    filterResource(cloneLocation, "etc/system.properties", props);
    filterResource(cloneLocation, "bin/karaf", props);
    filterResource(cloneLocation, "bin/start", props);
    filterResource(cloneLocation, "bin/stop", props);
    filterResource(cloneLocation, "bin/karaf.bat", props);
    filterResource(cloneLocation, "bin/start.bat", props);
    filterResource(cloneLocation, "bin/stop.bat", props);
    // create and add the clone instance in the registry
    String javaOpts = settings.getJavaOpts();
    if (javaOpts == null || javaOpts.length() == 0) {
      javaOpts = "-server -Xmx512M -Dcom.sun.management.jmxremote";
    }
    Instance cloneInstance =
        new InstanceImpl(this, name, cloneLocation.toString(), settings.getJavaOpts());
    instances.put(name, instance);
    saveState();
    return cloneInstance;
  }
Пример #23
0
  private void runAsciiMode() throws IOException {
    Ansi.setEnabled(_useColors);
    while (true) {
      String prompt = Ansi.ansi().bold().a(_userAdminShell.getPrompt()).boldOff().toString();
      Object result;
      try {
        String str = _console.readLine(prompt);
        try {
          if (str == null) {
            throw new CommandExitException();
          }
          result = _userAdminShell.executeCommand(str);
        } catch (IllegalArgumentException e) {
          result = e.toString();
        } catch (SerializationException e) {
          result = "There is a bug here, please report to [email protected]";
          _logger.error("This must be a bug, please report to [email protected].", e);
        } catch (CommandSyntaxException e) {
          result = e;
        } catch (CommandExitException e) {
          break;
        } catch (CommandPanicException e) {
          result =
              "Command '"
                  + str
                  + "' triggered a bug ("
                  + e.getTargetException()
                  + "); the service log file contains additional information. Please "
                  + "contact [email protected].";
        } catch (CommandException e) {
          result = e.getMessage();
        } catch (NoRouteToCellException e) {
          result = "Cell name does not exist or cell is not started: " + e.getMessage();
          _logger.warn(
              "The cell the command was sent to is no " + "longer there: {}", e.getMessage());
        } catch (RuntimeException e) {
          result =
              String.format(
                  "Command '%s' triggered a bug (%s); please"
                      + " locate this message in the log file of the admin service and"
                      + " send an email to [email protected] with this line and the"
                      + " following stack-trace",
                  str, e);
          _logger.error((String) result, e);
        }
      } catch (InterruptedIOException e) {
        _console.getCursorBuffer().clear();
        _console.println();
        result = null;
      } catch (InterruptedException e) {
        _console.println("^C");
        _console.flush();
        _console.getCursorBuffer().clear();
        result = null;
      } catch (IOException e) {
        throw e;
      } catch (Exception e) {
        result = e.getMessage();
        if (result == null) {
          result = e.getClass().getSimpleName() + ": (null)";
        }
      }

      if (result != null) {
        if (result instanceof CommandSyntaxException) {
          CommandSyntaxException e = (CommandSyntaxException) result;
          Ansi sb = Ansi.ansi();
          sb.fg(RED).a("Syntax error: ").a(e.getMessage()).newline();
          String help = e.getHelpText();
          if (help != null) {
            sb.fg(CYAN);
            sb.a("Help : ").newline();
            sb.a(help);
          }
          _console.println(sb.reset().toString());
        } else {
          String s;
          s = Strings.toMultilineString(result);
          if (!s.isEmpty()) {
            _console.println(s);
            _console.flush();
          }
        }
      }
      _console.flush();
    }
  }
Пример #24
0
 String bold(String text) {
   if (withColor) {
     return Ansi.ansi().bold().a(text).boldOff().toString();
   }
   return text;
 }
Пример #25
0
  @Override
  protected Object doExecute() throws Exception {

    String formatString =
        "%1$-33s %2$-26s %3$-" + TITLE_MAX_LENGTH + "s %4$-" + EXCERPT_MAX_LENGTH + "s%n";

    CatalogFacade catalogProvider = getCatalog();

    Filter filter = null;
    if (cqlFilter != null) {
      filter = CQL.toFilter(cqlFilter);
    } else {
      if (searchPhrase == null) {
        searchPhrase = "*";
      }
      if (caseSensitive) {
        filter =
            getFilterBuilder()
                .attribute(Metacard.ANY_TEXT)
                .is()
                .like()
                .caseSensitiveText(searchPhrase);
      } else {
        filter = getFilterBuilder().attribute(Metacard.ANY_TEXT).is().like().text(searchPhrase);
      }
    }

    QueryImpl query = new QueryImpl(filter);

    query.setRequestsTotalResultsCount(true);

    if (numberOfItems > -1) {
      query.setPageSize(numberOfItems);
    }

    long start = System.currentTimeMillis();

    SourceResponse response = catalogProvider.query(new QueryRequestImpl(query));

    long end = System.currentTimeMillis();

    int size = 0;
    if (response.getResults() != null) {
      size = response.getResults().size();
    }

    console.println();
    console.printf(
        " %d result(s) out of %s%d%s in %3.3f seconds",
        (size),
        Ansi.ansi().fg(Ansi.Color.CYAN).toString(),
        response.getHits(),
        Ansi.ansi().reset().toString(),
        (end - start) / MILLISECONDS_PER_SECOND);
    console.printf(formatString, "", "", "", "");
    printHeaderMessage(String.format(formatString, ID, DATE, TITLE, EXCERPT));

    for (Result result : response.getResults()) {
      Metacard metacard = result.getMetacard();

      String title = (metacard.getTitle() != null ? metacard.getTitle() : "N/A");
      String excerpt = "N/A";
      String modifiedDate = "";

      if (searchPhrase != null) {
        if (metacard.getMetadata() != null) {
          XPathHelper helper = new XPathHelper(metacard.getMetadata());
          String indexedText = helper.getDocument().getDocumentElement().getTextContent();
          indexedText = indexedText.replaceAll("\\r\\n|\\r|\\n", " ");

          String normalizedSearchPhrase = searchPhrase.replaceAll("\\*", "");

          int index = -1;

          if (caseSensitive) {
            index = indexedText.indexOf(normalizedSearchPhrase);
          } else {
            index = indexedText.toLowerCase().indexOf(normalizedSearchPhrase.toLowerCase());
          }

          if (index != -1) {
            int contextLength = (EXCERPT_MAX_LENGTH - normalizedSearchPhrase.length() - 8) / 2;
            excerpt = "..." + indexedText.substring(Math.max(index - contextLength, 0), index);
            excerpt = excerpt + Ansi.ansi().fg(Ansi.Color.GREEN).toString();
            excerpt =
                excerpt + indexedText.substring(index, index + normalizedSearchPhrase.length());
            excerpt = excerpt + Ansi.ansi().reset().toString();
            excerpt =
                excerpt
                    + indexedText.substring(
                        index + normalizedSearchPhrase.length(),
                        Math.min(
                            indexedText.length(),
                            index + normalizedSearchPhrase.length() + contextLength))
                    + "...";
          }
        }
      }

      if (metacard.getModifiedDate() != null) {
        modifiedDate =
            new DateTime(metacard.getModifiedDate().getTime()).toString(DATETIME_FORMATTER);
      }

      console.printf(
          formatString,
          metacard.getId(),
          modifiedDate,
          title.substring(0, Math.min(title.length(), TITLE_MAX_LENGTH)),
          excerpt);
    }

    return null;
  }
Пример #26
0
 public static String inColor(final Ansi.Color color, final String message) {
   return Ansi.ansi().fg(color).a(message).reset().toString();
 }
Пример #27
0
 /**
  * Gets the given message formatted to be displayed in the specified color.
  *
  * @param message The text message
  * @param color The color the message should be displayed in
  * @return A formatted message text
  */
 public static String getColorMessage(final String message, final Color color) {
   final String formattedMessage = Ansi.ansi().fg(color).a(message).toString();
   return formattedMessage + FIRST_ESC_CHAR + SECOND_ESC_CHAR + '0' + COMMAND_CHAR;
 }
Пример #28
0
  public boolean prepareDelegate(
      Object subject, CommandSession session, List<Object> params, CommandArguments args)
      throws Exception {
    args.subject = subject;
    // Introspect
    for (Class type = subject.getClass(); type != null; type = type.getSuperclass()) {
      for (Field field : type.getDeclaredFields()) {
        Option option = field.getAnnotation(Option.class);
        if (option != null) {
          args.options.put(option, field);
        }
        Argument argument = field.getAnnotation(Argument.class);
        if (argument != null) {
          if (Argument.DEFAULT.equals(argument.name())) {
            final Argument delegate = argument;
            final String name = field.getName();
            argument =
                new Argument() {
                  public String name() {
                    return name;
                  }

                  public String description() {
                    return delegate.description();
                  }

                  public boolean required() {
                    return delegate.required();
                  }

                  public int index() {
                    return delegate.index();
                  }

                  public boolean multiValued() {
                    return delegate.multiValued();
                  }

                  public String valueToShowInHelp() {
                    return delegate.valueToShowInHelp();
                  }

                  public Class<? extends Annotation> annotationType() {
                    return delegate.annotationType();
                  }
                };
          }
          args.arguments.put(argument, field);
          int index = argument.index();
          while (args.orderedArguments.size() <= index) {
            args.orderedArguments.add(null);
          }
          if (args.orderedArguments.get(index) != null) {
            throw new IllegalArgumentException("Duplicate argument index: " + index);
          }
          args.orderedArguments.set(index, argument);
        }
      }
    }
    // Check indexes are correct
    for (int i = 0; i < args.orderedArguments.size(); i++) {
      if (args.orderedArguments.get(i) == null) {
        throw new IllegalArgumentException("Missing argument for index: " + i);
      }
    }
    // Populate
    Map<Option, Object> optionValues =
        new TreeMap<Option, Object>(CommandArguments.OPTION_COMPARATOR);
    Map<Argument, Object> argumentValues = new HashMap<Argument, Object>();
    boolean processOptions = true;
    int argIndex = 0;
    for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
      Object param = it.next();
      // Check for help
      if (HELP.name().equals(param) || Arrays.asList(HELP.aliases()).contains(param)) {
        printUsageDelegate(session, subject, args.options, args.arguments, System.out);
        return false;
      }
      if (processOptions && param instanceof String && ((String) param).startsWith("-")) {
        boolean isKeyValuePair = ((String) param).indexOf('=') != -1;
        String name;
        Object value = null;
        if (isKeyValuePair) {
          name = ((String) param).substring(0, ((String) param).indexOf('='));
          value = ((String) param).substring(((String) param).indexOf('=') + 1);
        } else {
          name = (String) param;
        }
        Option option = null;
        for (Option opt : args.options.keySet()) {
          if (name.equals(opt.name()) || Arrays.asList(opt.aliases()).contains(name)) {
            option = opt;
            break;
          }
        }
        if (option == null) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(" undefined option ")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(param)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Undefined option: " + param);
        }
        Field field = args.options.get(option);
        if (value == null
            && (field.getType() == boolean.class || field.getType() == Boolean.class)) {
          value = Boolean.TRUE;
        }
        if (value == null && it.hasNext()) {
          value = it.next();
        }
        if (value == null) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(" missing value for option ")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(param)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Missing value for option: " + param);
        }
        if (option.multiValued()) {
          List<Object> l = (List<Object>) optionValues.get(option);
          if (l == null) {
            l = new ArrayList<Object>();
            optionValues.put(option, l);
          }
          l.add(value);
        } else {
          optionValues.put(option, value);
        }
      } else {
        processOptions = false;
        if (argIndex >= args.orderedArguments.size()) {
          throw new CommandException(
              Ansi.ansi()
                  .fg(Ansi.Color.RED)
                  .a("Error executing command ")
                  .a(scope)
                  .a(":")
                  .a(Ansi.Attribute.INTENSITY_BOLD)
                  .a(name)
                  .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                  .a(": too many arguments specified")
                  .fg(Ansi.Color.DEFAULT)
                  .toString(),
              "Too many arguments specified");
        }
        Argument argument = args.orderedArguments.get(argIndex);
        if (!argument.multiValued()) {
          argIndex++;
        }
        if (argument.multiValued()) {
          List<Object> l = (List<Object>) argumentValues.get(argument);
          if (l == null) {
            l = new ArrayList<Object>();
            argumentValues.put(argument, l);
          }
          l.add(param);
        } else {
          argumentValues.put(argument, param);
        }
      }
    }
    // Check required arguments / options
    for (Option option : args.options.keySet()) {
      if (option.required() && optionValues.get(option) == null) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": option ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(option.name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" is required")
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Option " + option.name() + " is required");
      }
    }
    for (Argument argument : args.arguments.keySet()) {
      if (argument.required() && argumentValues.get(argument) == null) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": argument ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(argument.name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" is required")
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Argument " + argument.name() + " is required");
      }
    }
    // Convert and inject values
    for (Map.Entry<Option, Object> entry : optionValues.entrySet()) {
      Field field = args.options.get(entry.getKey());
      Object value;
      try {
        value = convert(subject, entry.getValue(), field.getGenericType());
      } catch (Exception e) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": unable to convert option ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(entry.getKey().name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" with value '")
                .a(entry.getValue())
                .a("' to type ")
                .a(new GenericType(field.getGenericType()).toString())
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Unable to convert option "
                + entry.getKey().name()
                + " with value '"
                + entry.getValue()
                + "' to type "
                + new GenericType(field.getGenericType()).toString(),
            e);
      }
      field.setAccessible(true);
      field.set(subject, value);
    }
    for (Map.Entry<Argument, Object> entry : argumentValues.entrySet()) {
      Field field = args.arguments.get(entry.getKey());
      Object value;
      try {
        value = convert(subject, entry.getValue(), field.getGenericType());
      } catch (Exception e) {
        throw new CommandException(
            Ansi.ansi()
                .fg(Ansi.Color.RED)
                .a("Error executing command ")
                .a(scope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(name)
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(": unable to convert argument ")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(entry.getKey().name())
                .a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                .a(" with value '")
                .a(entry.getValue())
                .a("' to type ")
                .a(new GenericType(field.getGenericType()).toString())
                .fg(Ansi.Color.DEFAULT)
                .toString(),
            "Unable to convert argument "
                + entry.getKey().name()
                + " with value '"
                + entry.getValue()
                + "' to type "
                + new GenericType(field.getGenericType()).toString(),
            e);
      }
      field.setAccessible(true);
      field.set(subject, value);
    }
    return true;
  }
Пример #29
0
  protected void printUsageDelegate(
      CommandSession session,
      Object action,
      Map<Option, Field> optionsMap,
      Map<Argument, Field> argsMap,
      PrintStream out) {
    Command command = action.getClass().getAnnotation(Command.class);
    Terminal term = session != null ? (Terminal) session.get(".jline.terminal") : null;
    List<Argument> arguments = new ArrayList<Argument>(argsMap.keySet());
    Collections.sort(
        arguments,
        new Comparator<Argument>() {
          public int compare(Argument o1, Argument o2) {
            return Integer.valueOf(o1.index()).compareTo(Integer.valueOf(o2.index()));
          }
        });

    String commandName = command != null ? command.name() : name;
    String commandScope = command != null ? command.scope() : scope;
    String commandDescription =
        command != null ? command.description() : "No description available for " + name + ".";
    String commandDetailedDescription = command != null ? command.detailedDescription() : "";

    Set<Option> options = new TreeSet<Option>(CommandArguments.OPTION_COMPARATOR);
    options.addAll(optionsMap.keySet());
    options.add(HELP);
    boolean globalScope = NameScoping.isGlobalScope(session, scope);
    out.println(
        Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("DESCRIPTION").a(Ansi.Attribute.RESET));
    out.print("        ");
    if (commandName != null) {
      if (globalScope) {
        out.println(
            Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(commandName).a(Ansi.Attribute.RESET));
      } else {
        out.println(
            Ansi.ansi()
                .a(commandScope)
                .a(":")
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(commandName)
                .a(Ansi.Attribute.RESET));
      }
      out.println();
    }
    String description = commandDescription;
    if (isBlank(description)) {
      description = "No description available for " + name + ".";
    }
    out.print("\t");
    out.println(description);
    out.println();
    out.println("\tLoaded from");
    out.println("\t" + scriptFile);
    out.println();

    StringBuffer syntax = new StringBuffer();
    if (globalScope) {
      syntax.append(commandName);
    } else {
      syntax.append(String.format("%s:%s", commandScope, commandName));
    }

    if (options.size() > 0) {
      syntax.append(" [options]");
    }
    if (arguments.size() > 0) {
      syntax.append(' ');
      for (Argument argument : arguments) {
        if (!argument.required()) {
          syntax.append(String.format("[%s] ", argument.name()));
        } else {
          syntax.append(String.format("%s ", argument.name()));
        }
      }
    }

    out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("SYNTAX").a(Ansi.Attribute.RESET));
    out.print("        ");
    out.println(syntax.toString());
    out.println();
    if (arguments.size() > 0) {
      out.println(
          Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("ARGUMENTS").a(Ansi.Attribute.RESET));
      for (Argument argument : arguments) {
        out.print("        ");
        out.println(
            Ansi.ansi()
                .a(Ansi.Attribute.INTENSITY_BOLD)
                .a(argument.name())
                .a(Ansi.Attribute.RESET));
        printFormatted(
            "                ", argument.description(), term != null ? term.getWidth() : 80, out);
        if (!argument.required()) {
          if (argument.valueToShowInHelp() != null && argument.valueToShowInHelp().length() != 0) {
            try {
              if (Argument.DEFAULT_STRING.equals(argument.valueToShowInHelp())) {
                argsMap.get(argument).setAccessible(true);
                Object o = argsMap.get(argument).get(action);
                printObjectDefaultsTo(out, o);
              } else {
                printDefaultsTo(out, argument.valueToShowInHelp());
              }
            } catch (Throwable t) {
              // Ignore
            }
          }
        }
      }
      out.println();
    }
    if (options.size() > 0) {
      out.println(
          Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("OPTIONS").a(Ansi.Attribute.RESET));
      for (Option option : options) {
        String opt = option.name();
        for (String alias : option.aliases()) {
          opt += ", " + alias;
        }
        out.print("        ");
        out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(opt).a(Ansi.Attribute.RESET));
        printFormatted(
            "                ", option.description(), term != null ? term.getWidth() : 80, out);
        if (option.valueToShowInHelp() != null && option.valueToShowInHelp().length() != 0) {
          try {
            if (Option.DEFAULT_STRING.equals(option.valueToShowInHelp())) {
              optionsMap.get(option).setAccessible(true);
              Object o = optionsMap.get(option).get(action);
              printObjectDefaultsTo(out, o);
            } else {
              printDefaultsTo(out, option.valueToShowInHelp());
            }
          } catch (Throwable t) {
            // Ignore
          }
        }
      }
      out.println();
    }
    if (commandDetailedDescription.length() > 0) {
      out.println(
          Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("DETAILS").a(Ansi.Attribute.RESET));
      String desc = loadDescription(action.getClass(), commandDetailedDescription);
      printFormattedFixed("        ", desc, term != null ? term.getWidth() : 80, out);
    }
  }
Пример #30
0
  public ConsoleManager(GlowServer server) {
    this.server = server;

    // install Ansi code handler, which makes colors work on Windows
    AnsiConsole.systemInstall();

    for (Handler h : logger.getHandlers()) {
      logger.removeHandler(h);
    }

    // add log handler which writes to console
    logger.addHandler(new FancyConsoleHandler());

    // reader must be initialized before standard streams are changed
    try {
      reader = new ConsoleReader();
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Exception initializing console reader", ex);
    }
    reader.addCompleter(new CommandCompleter());

    // set system output streams
    System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true));
    System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true));

    // set up colorization replacements
    replacements.put(
        ChatColor.BLACK,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString());
    replacements.put(
        ChatColor.DARK_BLUE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString());
    replacements.put(
        ChatColor.DARK_GREEN,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString());
    replacements.put(
        ChatColor.DARK_AQUA,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString());
    replacements.put(
        ChatColor.DARK_RED,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString());
    replacements.put(
        ChatColor.DARK_PURPLE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString());
    replacements.put(
        ChatColor.GOLD,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString());
    replacements.put(
        ChatColor.GRAY,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString());
    replacements.put(
        ChatColor.DARK_GRAY,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString());
    replacements.put(
        ChatColor.BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString());
    replacements.put(
        ChatColor.GREEN,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString());
    replacements.put(
        ChatColor.AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString());
    replacements.put(
        ChatColor.RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString());
    replacements.put(
        ChatColor.LIGHT_PURPLE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString());
    replacements.put(
        ChatColor.YELLOW,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString());
    replacements.put(
        ChatColor.WHITE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString());
    replacements.put(ChatColor.MAGIC, Ansi.ansi().a(Ansi.Attribute.BLINK_SLOW).toString());
    replacements.put(ChatColor.BOLD, Ansi.ansi().a(Ansi.Attribute.UNDERLINE_DOUBLE).toString());
    replacements.put(
        ChatColor.STRIKETHROUGH, Ansi.ansi().a(Ansi.Attribute.STRIKETHROUGH_ON).toString());
    replacements.put(ChatColor.UNDERLINE, Ansi.ansi().a(Ansi.Attribute.UNDERLINE).toString());
    replacements.put(ChatColor.ITALIC, Ansi.ansi().a(Ansi.Attribute.ITALIC).toString());
    replacements.put(ChatColor.RESET, Ansi.ansi().a(Ansi.Attribute.RESET).toString());
  }