예제 #1
1
  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);
    }

    // used until/unless gui is created
    consoleHandler = new FancyConsoleHandler();
    // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);

    // todo: why is this here?
    Runtime.getRuntime().addShutdownHook(new ServerShutdownThread());

    // 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));
  }
예제 #2
0
 private static PrintStream wrap(PrintStream stream) {
   OutputStream o = AnsiConsole.wrapOutputStream(stream);
   if (o instanceof PrintStream) {
     return (PrintStream) o;
   } else {
     return new PrintStream(o);
   }
 }
예제 #3
0
  /**
   * Called only in standalone mode
   *
   * @param args
   */
  private void startMetricsServer(String[] args) {
    AnsiConsole.systemInstall();
    String version =
        ((MetricsServer.class.getPackage().getImplementationVersion() != null)
            ? MetricsServer.class.getPackage().getImplementationVersion()
            : "'undefined'");
    System.out.println(
        ansi()
            .fg(RED)
            .render("@|bold Starting BigLoupe Metrics server version |@")
            .fg(GREEN)
            .a(version)
            .fg(WHITE));
    logger.info("Starting BigLoupe Metrics server version " + version);

    try {
      commandLineParser(args);
      applyCommonOption();

      Server server = startWebServer(version);

      keepAliveLatch = new CountDownLatch(1);
      // keep this thread alive (non daemon thread) until we shutdown
      Runtime.getRuntime()
          .addShutdownHook(
              new Thread() {
                @Override
                public void run() {
                  keepAliveLatch.countDown();
                }
              });

      keepAliveThread =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    keepAliveLatch.await();
                  } catch (InterruptedException e) {
                    // bail out
                  }
                }
              },
              "BigLoupe metrics-server[keepAlive/" + version + "]");
      keepAliveThread.setDaemon(false);
      keepAliveThread.start();

      Runtime.getRuntime().addShutdownHook(new Thread(new MetricsServerCleaner(server)));
    } catch (ParseException e) {
      System.out.println(e.getMessage());
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("java -jar bigloupe-chart.jar [options]", options);
      System.exit(-1);
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }
예제 #4
0
 private static boolean detectAnsiSupport() {
   OutputStream out = AnsiConsole.wrapOutputStream(new ByteArrayOutputStream());
   try {
     out.close();
   } catch (Exception e) {
     // ignore;
   }
   return out instanceof WindowsAnsiOutputStream;
 }
예제 #5
0
 public OutputEventRenderer addStandardOutputAndError() {
   boolean stdOutIsTerminal = terminalDetector.isSatisfiedBy(FileDescriptor.out);
   boolean stdErrIsTerminal = terminalDetector.isSatisfiedBy(FileDescriptor.err);
   if (stdOutIsTerminal) {
     PrintStream outStr = org.fusesource.jansi.AnsiConsole.out();
     Console console = new AnsiConsole(outStr, outStr, colourMap);
     addConsole(console, true, stdErrIsTerminal);
   } else if (stdErrIsTerminal) {
     // Only stderr is connected to a terminal
     PrintStream errStr = org.fusesource.jansi.AnsiConsole.err();
     Console console = new AnsiConsole(errStr, errStr, colourMap);
     addConsole(console, false, true);
   }
   if (!stdOutIsTerminal) {
     addStandardOutput(System.out);
   }
   if (!stdErrIsTerminal) {
     addStandardError(System.err);
   }
   return this;
 }
예제 #6
0
 public void run() {
   try {
     System.out.println(
         ansi().fg(RED).bold().a("Stopping BigLoupe Metrics server").boldOff().fg(WHITE));
     // metricsServer.stopListener() called by PreDestro annotation
     if (server != null) server.stop();
   } catch (Exception e) {
     System.out.println(ansi().fg(RED).a("Can't stop properly Jetty Web Server"));
   } finally {
     AnsiConsole.systemUninstall();
   }
 }
예제 #7
0
  public Server(boolean shouldDebug)
      throws IOException, InterruptedException, PluginException, DiamondException, LangException {
    // Predefine console data
    AnsiConsole.systemInstall();
    Lang.setLang("en_US"); // TODO: Add ability to change language

    // Start server
    debug = shouldDebug;
    Diamond.setServer(this);
    lang.info("server.start");
    if (debug) lang.info("server.debugOn");
    else lang.info("server.debugOff");

    // Make sure Mojang Auth Server is online
    lang.info("mojang.checkAuth");
    if (MojangAuthServer.isOnline())
      lang.info("mojang.authOnline", MojangAuthServer.getImplementationVersion());
    else lang.warn("mojang.authOffline");

    // Check Files and Properties
    FileList.setDebug(shouldDebug);
    new FileCheckup();
    new PropertiesCheckup();

    // Load Server Settings
    ServerSettings.load();

    // Initialize everything
    Block.registerBlocks();
    Command.registerNatives();

    // Finish startup
    new MainTicker().start();
    new UDPPacketHandler(new DatagramSocket(ServerSettings.getPEPort())).start();
    new TCPPacketHandler(new ServerSocket(ServerSettings.getPCPort())).start();
    this.broadcaster = new TCPBroadcaster(InetAddress.getByName("127.0.0.1"), 4445);
    this.broadcaster.start();
    new Console().start();

    // Load plugins after everything is initialized
    PluginLoader.loadPlugins();
    MainTicker ticker = new MainTicker();
    ticker.start();

    running = true;
    lang.info("server.started");
  }
예제 #8
0
  public MainLogger(String logFile, Boolean logDebug) {
    AnsiConsole.systemInstall();

    if (logger != null) {
      throw new RuntimeException("MainLogger has been already created");
    }
    logger = this;
    this.logFile = new File(logFile);
    if (!this.logFile.exists()) {
      try {
        this.logFile.createNewFile();
      } catch (IOException e) {
        this.logException(e);
      }
    }
    this.logDebug = logDebug;
    this.start();
  }
예제 #9
0
  @Override
  public void run() {
    ClientSession session = clientOptions.toClientSession();
    boolean hasQuery = !Strings.isNullOrEmpty(clientOptions.execute);
    boolean isFromFile = !Strings.isNullOrEmpty(clientOptions.file);

    if (!hasQuery || !isFromFile) {
      AnsiConsole.systemInstall();
    }

    initializeLogging(session.isDebug());

    String query = clientOptions.execute;
    if (hasQuery) {
      query += ";";
    }

    if (isFromFile) {
      if (hasQuery) {
        throw new RuntimeException("both --execute and --file specified");
      }
      try {
        query = Files.toString(new File(clientOptions.file), UTF_8);
        hasQuery = true;
      } catch (IOException e) {
        throw new RuntimeException(
            format("Error reading from file %s: %s", clientOptions.file, e.getMessage()));
      }
    }

    try (QueryRunner queryRunner =
        QueryRunner.create(session, Optional.ofNullable(clientOptions.socksProxy))) {
      if (hasQuery) {
        executeCommand(queryRunner, query, clientOptions.outputFormat);
      } else {
        runConsole(queryRunner, session);
      }
    }
  }
예제 #10
0
public class Context implements Closeable {
  private final Map<String, String> parameters = new HashMap<String, String>();
  private final Map<String, Object> cache = new HashMap<String, Object>();

  private PrintStream console = AnsiConsole.out();

  private boolean withLog;
  private boolean noPrompt;
  private boolean withColor = true;

  public void put(final CompileParameter parameter, final String value) {
    if (parameter instanceof Prompt) {
      noPrompt = true;
    } else if (parameter instanceof LogOutput) {
      withLog = true;
    } else if (parameter instanceof DisableColors) {
      withColor = false;
      console = System.out;
    }
    parameters.put(parameter.getAlias(), value);
  }

  public void put(final String parameter, final String value) {
    parameters.put(parameter.toLowerCase(), value);
  }

  public boolean contains(final CompileParameter parameter) {
    return parameters.containsKey(parameter.getAlias());
  }

  public boolean contains(final String parameter) {
    return parameters.containsKey(parameter);
  }

  public String get(final CompileParameter parameter) {
    return parameters.get(parameter.getAlias());
  }

  public String get(final String parameter) {
    return parameters.get(parameter.toLowerCase());
  }

  public void cache(final String name, final Object value) {
    cache.put(name, value);
  }

  public <T> T notify(final String action, final T target) {
    log("Notify: " + action + " for " + target);
    return target;
  }

  @SuppressWarnings("unchecked")
  public <T> T load(final String name) {
    return (T) cache.get(name);
  }

  private static synchronized void write(
      final PrintStream console, final boolean newLine, final String... values) {
    if (values.length == 0) {
      console.println();
    } else {
      if (newLine) {
        for (final String v : values) {
          console.println(v);
        }
      } else {
        for (final String v : values) {
          console.print(v);
        }
      }
    }
    console.flush();
  }

  public void show(final String... values) {
    write(console, true, values);
  }

  public static String inColor(final Ansi.Color color, final String message) {
    return Ansi.ansi().fg(color).a(message).reset().toString();
  }

  public void log(final String value) {
    if (withLog) {
      write(console, true, withColor ? inColor(Color.YELLOW, value) : value);
    }
  }

  public void log(final char[] value, final int len) {
    if (withLog) {
      final String msg = new String(value, 0, len);
      write(console, false, withColor ? inColor(Color.YELLOW, msg) : msg);
    }
  }

  public void error(final String value) {
    write(console, true, withColor ? inColor(Color.RED, value) : value);
  }

  public void error(final Exception ex) {
    error(ex.getMessage());
    if (withLog) {
      final StringWriter sw = new StringWriter();
      ex.printStackTrace(new PrintWriter(sw));
      error(sw.toString());
    }
  }

  public boolean canInteract() {
    return System.console() != null && !noPrompt;
  }

  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();
  }

  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();
  }

  @Override
  public void close() {
    for (Object it : cache.values()) {
      if (it instanceof Closeable) {
        try {
          ((Closeable) it).close();
        } catch (IOException e) {
          error(e);
        }
      }
    }
  }
}
  public static void main(String[] args) throws Exception {
    System.out.println(args.length + " parameter(s).");
    if (args.length > 0) {
      if (args[0].equals("-cal")) {
        calibration = true;
        ansiConsole = false;
      }
    }

    LelandPrototype lp = new LelandPrototype();

    if (!calibration) {
      props = new Properties();
      try {
        props.load(new FileInputStream("props.properties"));
      } catch (IOException ioe) {
        displayAppErr(ioe);
        //  ioe.printStackTrace();
      }

      try {
        windowWidth =
            Integer.parseInt(
                LelandPrototype.getAppProperties()
                    .getProperty("smooth.width", "10")); // For smoothing
        alfa =
            Double.parseDouble(
                LelandPrototype.getAppProperties().getProperty("low.pass.filter.alfa", "0.5"));
      } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
      }

      try {
        cleaningDelay =
            Long.parseLong(props.getProperty("cleaning.delay", "86400")); // Default: one day
      } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
      }

      try {
        nbSeenInARow = Integer.parseInt(props.getProperty("seen.in.a.row", "40"));
      } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
      }

      try {
        rangeSensorHeight = Double.parseDouble(props.getProperty("range.sensor.height", "10"));
      } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
      }

      try {
        fileLogger = new BufferedWriter(new FileWriter(LOG_FILE));
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      if (ansiConsole) AnsiConsole.systemInstall();

      final ReadWriteFONA fona;

      if ("true".equals(props.getProperty("with.fona", "false"))) {
        System.setProperty("baud.rate", props.getProperty("baud.rate"));
        System.setProperty("serial.port", props.getProperty("serial.port"));

        fona = new ReadWriteFONA(lp);
        fona.openSerialInput();
        fona.startListening();
        while (!fonaReady) {
          System.out.println("Waiting for the FONA device to come up...");
          try {
            Thread.sleep(1000L);
          } catch (InterruptedException ie) {
          }
        }
        fona.requestBatteryState();
        fona.requestNetworkStatus();
        displayAppMess(">>> FONA Ready, moving on");
        smsProvider = fona;
      } else {
        System.out.println("Will simulate the phone calls.");
      }
      delay(1);

      wsUri = props.getProperty("ws.uri", "");
      phoneNumber_1 = props.getProperty("phone.number.1", "14153505547");
      phoneNumber_2 = props.getProperty("phone.number.2", "14153505547");
      phoneNumber_3 = props.getProperty("phone.number.3", "14153505547");
      boatName = props.getProperty("boat.name", "Never Again XXIII");

      try {
        rm = new RelayManager();
        rm.set("00", RelayManager.RelayState.ON);
      } catch (Exception ex) {
        System.err.println("You're not on the PI, hey?");
        ex.printStackTrace();
      }

      if (wsUri.trim().startsWith("ws://")) {
        log(">>> Connecting to the WebSocket server [" + wsUri + "]");
        initWebSocketConnection(wsUri);
      } else {
        log(">>> No WebSocket server");
        delay(1);
      }
    }

    final SevenADCChannelsManager sacm = (calibration ? null : new SevenADCChannelsManager(lp));
    final SurfaceDistanceManager sdm = new SurfaceDistanceManager(lp);
    sdm.startListening();

    final Thread me = Thread.currentThread();

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                // Cleanup
                System.out.println();
                if (sacm != null) sacm.quit();
                if (smsProvider != null) smsProvider.closeChannel();
                synchronized (me) {
                  me.notify();
                }
                gpio.shutdown();
                if (channelLogger != null) {
                  try {
                    for (BufferedWriter bw : channelLogger) {
                      bw.close();
                    }
                  } catch (Exception ex) {
                    ex.printStackTrace();
                  }
                }
                System.out.println("Program stopped by user's request.");
              }
            });

    if (!calibration) {
      if ("true".equals(props.getProperty("log.channels", "false"))) {
        channelLogger = new BufferedWriter[SevenADCChannelsManager.getChannel().length];
        for (int i = 0; i < SevenADCChannelsManager.getChannel().length; i++) {
          channelLogger[i] =
              new BufferedWriter(
                  new FileWriter(CHANNEL_PREFIX + CHANNEL_NF.format(i) + CHANNEL_SUFFIX));
        }
      }

      // CLS
      if (ansiConsole) AnsiConsole.out.println(EscapeSeq.ANSI_CLS);
    }
    synchronized (me) {
      System.out.println("Main thread waiting...");
      me.wait();
    }
    System.out.println("Done.");
  }
예제 #12
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());
  }
예제 #13
0
  private void initReaderAndStreams() throws IOException {
    boolean noInitMode = isNoInitMode();
    if ((_redirectedStream == null) && noInitMode) {
      return;
    }

    if ((inputPipe == null) && (_redirectedStream == null)) {
      inputPipe = new ConsoleInputSession(System.in);
    }
    if (outputStream == null) {
      outputStream = System.out;
    }

    Terminal terminal;
    if (Boolean.getBoolean("forge.compatibility.IDE")) {
      terminal = new IdeTerminal();
    } else if (OSUtils.isWindows()) {
      final OutputStream ansiOut = AnsiConsole.wrapOutputStream(System.out);

      TerminalFactory.configure(TerminalFactory.Type.WINDOWS);
      terminal = TerminalFactory.get();

      final OutputStreamWriter writer =
          new OutputStreamWriter(
              ansiOut,
              System.getProperty(
                  "jline.WindowsTerminal.output.encoding", System.getProperty("file.encoding")));

      outputStream =
          new OutputStream() {
            @Override
            public void write(final int b) throws IOException {
              writer.write(b);
              writer.flush();
            }
          };
    } else {
      terminal = TerminalFactory.get();
    }

    this.screenBuffer = new JLineScreenBuffer(terminal, outputStream);
    this.reader =
        new ConsoleReader(
            _redirectedStream == null ? inputPipe.getExternalInputStream() : _redirectedStream,
            this,
            null,
            terminal);
    this.reader.setHistoryEnabled(true);
    this.reader.setBellEnabled(false);

    for (TriggeredAction action : triggeredActions) {
      this.reader.addTriggeredAction(action.getTrigger(), action.getListener());
    }

    if (noInitMode) {
      if (_historyOverride != null) {

        _setHistory(_historyOverride);
      }

      if (_deferredCompleters != null) {
        for (Completer completer : _deferredCompleters) {
          _initCompleters(completer);
        }
      }
    }
  }