示例#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
  /**
   * 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);
    }
  }
示例#3
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");
  }
示例#4
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();
  }
示例#5
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);
      }
    }
  }
  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.");
  }
示例#7
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());
  }