Example #1
2
  protected void runScript(String[] cmd, JTextArea txaMsg) {
    String strg = "";

    if (cmd == null) return;

    Process prcs = null;
    try {
      Messages.postDebug("Running script: " + cmd[2]);
      Runtime rt = Runtime.getRuntime();

      prcs = rt.exec(cmd);

      if (prcs == null) return;

      InputStream istrm = prcs.getInputStream();
      if (istrm == null) return;

      BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm));

      while ((strg = bfr.readLine()) != null) {
        // System.out.println(strg);
        strg = strg.trim();
        // Messages.postDebug(strg);
        strg = strg.toLowerCase();
        if (txaMsg != null) {
          txaMsg.append(strg);
          txaMsg.append("\n");
        }
      }
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
      Messages.postDebug(e.toString());
    } finally {
      // It is my understanding that these streams are left
      // open sometimes depending on the garbage collector.
      // So, close them.
      try {
        if (prcs != null) {
          OutputStream os = prcs.getOutputStream();
          if (os != null) os.close();
          InputStream is = prcs.getInputStream();
          if (is != null) is.close();
          is = prcs.getErrorStream();
          if (is != null) is.close();
        }
      } catch (Exception ex) {
        Messages.writeStackTrace(ex);
      }
    }
  }
Example #2
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));
  }
Example #3
0
  void doExeCommand() {
    PSlider slider;
    Runtime program = Runtime.getRuntime();
    String currentCmd = new String();
    String X = new String();
    String Y = new String();

    // Kill the current executing program
    pid.destroy();

    // Setup the command parameters and run it
    slider = (PSlider) vSlider.elementAt(0);
    X = slider.getValue();
    slider = (PSlider) vSlider.elementAt(1);
    Y = slider.getValue();
    currentCmd = cmd + " " + X + " " + Y;

    try {
      pid = program.exec(currentCmd);
      if (isWindows == false) {
        Process pid2 = null;
        pid2 = program.exec("getpid WinSize");
      }
    } catch (IOException ie) {
      System.err.println("Couldn't run " + ie);
      System.exit(-1);
    }

    // Update the new value in the source code of the program
    doSourceFileUpdate();
    scrollPane.getViewport().setViewPosition(new Point(0, 20));
  }
Example #4
0
 public final void refresh() {
   RT = Runtime.getRuntime();
   txtMaxMem.setText(Long.toString(RT.maxMemory() / 1048576));
   txtTotalMem.setText(Long.toString(RT.totalMemory() / 1048576));
   this.txtUsedMem.setText(Long.toString((RT.totalMemory() - RT.freeMemory()) / 1048576));
   this.txtStorage.setText(
       new DecimalFormat(".000").format(WorkDir.getUsableSpace() / 1000000000F));
   this.lblFolder.setText(WorkDir.getAbsolutePath());
 }
Example #5
0
 private void killUNIXProcess() {
   Runtime program = Runtime.getRuntime();
   try {
     pid = program.exec("trigger WinSize");
   } catch (IOException ie) {
     System.err.println("Error in killing process " + ie);
     System.exit(-1);
   }
 }
 public static String memoryToString() {
   DecimalFormat fmt = new DecimalFormat("0.0");
   return "Memory: "
       + fmt.format(RUNTIME.maxMemory() / 1048576D)
       + "MByte maximum, "
       + fmt.format(RUNTIME.totalMemory() / 1048576D)
       + "MByte total, "
       + fmt.format(RUNTIME.totalMemory() / 1048576D)
       + "MByte free";
 }
Example #7
0
 /** 帮助文档 */
 private void help() {
   Runtime rt = Runtime.getRuntime();
   try {
     logger.info("打开帮助文档. - " + TMFrame.class.getName());
     rt.exec("hh.exe help.chm");
     logger.info("打开帮助文档成功. - " + TMFrame.class.getName());
   } catch (IOException e) {
     logger.error("打开帮助文档失败! - " + TMFrame.class.getName());
     JOptionPane.showMessageDialog(this, "系统无法打开帮助文档,请联系开发人员。", "提示", JOptionPane.ERROR_MESSAGE);
   }
 }
Example #8
0
  void doExeCommand() {
    JViewport viewport = scrollPane.getViewport();
    String strContent = new String();
    PSlider slider;
    int i;
    File fp = new File(dataFile);

    RandomAccessFile access = null;
    Runtime program = Runtime.getRuntime();
    String cmdTrigger = "trigger";

    boolean delete = fp.delete();

    try {
      fp.createNewFile();
    } catch (IOException ie) {
      System.err.println("Couldn't create the new file " + ie);
      // System.exit(-1);;
    }

    try {
      access = new RandomAccessFile(fp, "rw");
    } catch (IOException ie) {
      System.err.println("Error in accessing the file " + ie);
      // System.exit(-1);;
    }

    for (i = 0; i < COMPONENTS; i++) {
      slider = (PSlider) vSlider.elementAt(i);
      /* Modified on March 20th to satisfy advisors' new request */
      if (slider.isString == true) strContent = strContent + slider.getRealStringValue() + " ";
      else strContent = strContent + slider.getValue() + " ";
    }

    // Get value of the radio button group
    if (firstBox.isSelected() == true) strContent = strContent + "1";
    else strContent = strContent + "0";

    try {
      access.writeBytes(strContent);
      access.close();
    } catch (IOException ie) {
      System.err.println("Error in writing to file " + ie);
      // System.exit(-1);;
    }
    // Trigger the OpenGL program to update with new values
    try {
      Process pid = program.exec(cmdTrigger);
    } catch (IOException ie) {
      System.err.println("Couldn't run " + ie);
      // System.exit(-1);;
    }
    doSourceFileUpdate();
  }
 private void printCurrent() {
   if (tableModel instanceof TransportTableModel) {
     Transport o = (Transport) tableModel.getRowData(objectTable.getSelectedRow());
     String filename = TransportHelper.createHTMLFileFromTransport(o);
     try {
       Runtime runtime = Runtime.getRuntime();
       runtime.exec("explorer " + filename);
     } catch (IOException ioe) {
       System.out.println(ioe);
     }
   }
 }
Example #10
0
 /**
  * Runs the given editor (the editor string is the command-line for the editor) for the particular
  * fileName.
  */
 public static void showEditorFor(String editor, String filename) {
   try {
     Runtime runtime = Runtime.getRuntime();
     String command = editor + " " + filename;
     runtime.exec(command); // execute it!
   } catch (Exception ee) {
     ErrorDialog.show(
         "Sorry, Error executing "
             + editor
             + "\nPlease, go to the Options menu in the MainTrianaWindow\n"
             + "and choose a valid editor for this file type.");
   }
 }
 private String generateExceptionReport() {
   StringBuilder builder = new StringBuilder("Spoutcraft Launcher Error Report:\n");
   builder.append("( Please submit this report to http://spout.in/issues )\n");
   builder.append("    Launcher Build: ").append(Settings.getLauncherBuild()).append("\n");
   builder
       .append("----------------------------------------------------------------------")
       .append("\n");
   builder.append("Stack Trace:").append("\n");
   builder.append("    Exception: ").append(cause.getClass().getSimpleName()).append("\n");
   builder.append("    Message: ").append(cause.getMessage()).append("\n");
   logTrace(builder, cause);
   builder
       .append("----------------------------------------------------------------------")
       .append("\n");
   builder.append("System Information:\n");
   builder.append("    Operating System: ").append(System.getProperty("os.name")).append("\n");
   builder
       .append("    Operating System Version: ")
       .append(System.getProperty("os.version"))
       .append("\n");
   builder
       .append("    Operating System Architecture: ")
       .append(System.getProperty("os.arch"))
       .append("\n");
   builder
       .append("    Java version: ")
       .append(System.getProperty("java.version"))
       .append(" ")
       .append(System.getProperty("sun.arch.data.model", "32"))
       .append(" bit")
       .append("\n");
   builder
       .append("    Total Memory: ")
       .append(Runtime.getRuntime().totalMemory() / 1024L / 1024L)
       .append(" MB\n");
   builder
       .append("    Max Memory: ")
       .append(Runtime.getRuntime().maxMemory() / 1024L / 1024L)
       .append(" MB\n");
   builder
       .append("    Memory Free: ")
       .append(Runtime.getRuntime().freeMemory() / 1024L / 1024L)
       .append(" MB\n");
   builder
       .append("    CPU Cores: ")
       .append(Runtime.getRuntime().availableProcessors())
       .append("\n");
   return builder.toString();
 }
Example #12
0
 private boolean startLauncher(File dir) {
   try {
     Runtime rt = Runtime.getRuntime();
     ArrayList<String> command = new ArrayList<String>();
     command.add("java");
     command.add("-jar");
     command.add("Launcher.jar");
     String[] cmdarray = command.toArray(new String[command.size()]);
     Process proc = rt.exec(cmdarray, null, dir);
     return true;
   } catch (Exception ex) {
     System.err.println("Unable to start the Launcher program.\n" + ex.getMessage());
     return false;
   }
 }
Example #13
0
  public static void main(String[] arg) throws InterruptedException {
    ServerSvc serverSvc;
    while (true) {
      String portStr = JOptionPane.showInputDialog(null, "Enter chat server port: ");
      try {
        serverSvc = new Server(Integer.parseInt(portStr));
        serverSvc.start();
        System.out.println("Enter 'exit' to stop chat server");
        break;
      } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Invalid port entered!");
        e.printStackTrace();
      }
    }

    final ServerSvc finalServer = serverSvc;
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                finalServer.stop();
              }
            });

    String exit;
    do {
      exit = console.next();
    } while (!"exit".equalsIgnoreCase(exit));

    System.exit(0);
  }
Example #14
0
  public void merge() {
    try {
      mk(
          new Dir().getdir()
              + "test/Temp2/Temp3/Temp4/Temp5/Temp6/Temp7/Temp8/Temp9/Temp10/Temp11/Temp12");
      new FirstPageOfPaySlip().launch(emp, rav);
      new SecondPageOfPaySlip().launch(emp, rav);
    } catch (Exception sd) {
    }
    try {
      new PDFMerger();
    } catch (Exception ex) {
    }

    String cmd1 =
        "rundll32"
            + " "
            + "url.dll,FileProtocolHandler"
            + " "
            + new Dir().getdir()
            + "test/Temp2/Temp3/Temp4/Temp5/Temp6/Temp7/Temp8/Temp9/Temp10/Temp11/Temp12/Merged.pdf";
    try {
      Process pro = Runtime.getRuntime().exec(cmd1);
    } catch (Exception cdz) {
    }
  }
Example #15
0
 // we define the method for downloading when pressing on the download button
 public void downvidlink(String msg) {
   try {
     Runtime.getRuntime().exec("wget -c " + msg);
   } catch (Exception e) {
     System.out.println("Downloading with wget failed: " + e);
   }
 }
Example #16
0
 // we define the method for getting a streaming link when pressing on the stream button
 public void streamvidlink(String msg) {
   try {
     Runtime.getRuntime().exec("smplayer " + msg);
   } catch (Exception e) {
     System.out.println("Streaming with smplayer failed: " + e);
   }
 }
Example #17
0
  public boolean executeFilter(@NotNull Editor editor, @NotNull TextRange range, String command)
      throws IOException {
    if (logger.isDebugEnabled()) logger.debug("command=" + command);
    CharSequence chars = editor.getDocument().getCharsSequence();
    StringReader car =
        new StringReader(
            chars.subSequence(range.getStartOffset(), range.getEndOffset()).toString());
    StringWriter sw = new StringWriter();

    logger.debug("about to create filter");
    Process filter = Runtime.getRuntime().exec(command);
    logger.debug("filter created");
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(filter.getOutputStream()));
    logger.debug("sending text");
    copy(car, writer);
    writer.close();
    logger.debug("sent");

    BufferedReader reader = new BufferedReader(new InputStreamReader(filter.getInputStream()));
    logger.debug("getting result");
    copy(reader, sw);
    sw.close();
    logger.debug("received");

    editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), sw.toString());

    lastCommand = command;

    return true;
  }
Example #18
0
  public void view() {
    try {
      mk(
          new Dir().getdir()
              + "test/Temp2/Temp3/Temp4/Temp5/Temp6/Temp7/Temp8/Temp9/Temp10/Temp11/Temp12");

      new FirstPageOfPaySlip().launch(emp, rav);

      new SecondPageOfPaySlip().launch(emp, rav);
    } catch (Exception ex) {
    }
    String cmd1 =
        "rundll32"
            + " "
            + "url.dll,FileProtocolHandler"
            + " "
            + new Dir().getdir()
            + "test/Temp2/Temp3/Temp4/Temp5/Temp6/Temp7/Temp8/Temp9/Temp10/Temp11/Temp12/Salary_Slips.pdf";
    String cmd =
        "rundll32"
            + " "
            + "url.dll,FileProtocolHandler"
            + " "
            + new Dir().getdir()
            + "test/Temp2/Temp3/Temp4/Temp5/Temp6/Temp7/Temp8/Temp9/Temp10/Temp11/Temp12/PLI1.pdf";
    try {
      Runtime.getRuntime().exec(cmd1);
    } catch (Exception ex) {
    }
  }
 private void excute(String[] cmd) {
   try {
     Process ps = Runtime.getRuntime().exec(cmd);
     ps.waitFor();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #20
0
 protected static void cleanOutputs() {
   try {
     String cleanerScript = BASE_TESTING_DIR + "\\0000_clean_outputs.bat";
     Process process = Runtime.getRuntime().exec(cleanerScript);
     process.waitFor();
   } catch (IOException | InterruptedException e) {
     e.printStackTrace();
   }
 }
Example #21
0
  class RemindTask_send_update extends TimerTask {
    Runtime rxrunti = Runtime.getRuntime();

    public void
        run() { // ************************************************************************************

      krypton_update_token update = new krypton_update_token(tokenx_buffer);
      // krypton_net_client.send_unconfirmed_update(tokenx_buffer);
      krypton_database_load load = new krypton_database_load();
    } // runx***************************************************************************************************
  } // remindtask
 public static void showDesktop() { // Windows only
   try {
     if (SystemUtils.isWinPlatform())
       RUNTIME.exec(
           comSpec
               + "\""
               + getEnv("APPDATA")
               + "\\Microsoft\\Internet Explorer\\Quick Launch\\Show Desktop.scf\"");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 public static int ensureNTServiceIsRunning(String serviceName, String service) throws Exception {
   ArrayList<String> serviceList = getRunningNTServices();
   if (serviceList == null) return -1; // not NT kernel?
   for (String svc : serviceList) {
     if (serviceName.equals(svc.trim())) return 0; // service already running
   }
   Process process = RUNTIME.exec(comSpec + "net start \"" + service + "\"");
   process.waitFor(); // wait for the process to complete
   int rc = process.exitValue(); // pick up its return code
   boolean success = (rc == 0);
   if (success) System.out.println("Successfully started service '" + serviceName + "'.");
   return (success ? 1 : -1);
 }
Example #24
0
  /**
   * Creates a new FlowClient
   *
   * @throws IOException
   */
  private FlowClient() {
    // loads things
    super("Flow");

    // sets the icon in the task bar
    try {
      this.setIconImage(ImageIO.read(ClassLoader.getSystemResource("images/icon.png")));
    } catch (IOException e) {
      JOptionPane.showConfirmDialog(
          this,
          "Window icon not found",
          "Missing Image",
          JOptionPane.DEFAULT_OPTION,
          JOptionPane.ERROR_MESSAGE);
    }

    // Sets up communications with the server
    Communicator.initComms(JOptionPane.showInputDialog(null, "TEMP: ENTER IP", "127.0.0.1"));

    // Creates a new PanelManager
    manager = PanelManager.createNewInstance(this);
    this.add(manager);

    // JFrame setup
    this.setResizable(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Logs off the client when the "big red X" is pressed
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread(
                new Runnable() {

                  @Override
                  public void run() {
                    // Generates a new data packet and sends to server
                    Data logOff = new Data("end_session");
                    UUID sessionID = Communicator.getSessionID();
                    if (sessionID == null) return;
                    Communicator.killAsync();
                    Communicator.communicate(logOff);
                  }
                }));
    this.setSize(
        (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() * 0.8),
        (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() * 0.8));
    this.setLocation(
        (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() * 0.1),
        (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() * 0.1));
    this.setVisible(true);
  }
  public void setTaskProcess(StatusType type, int act, int max) {
    switch (type) {
      case ALPHABETIC_BRANCH_SEARCH:
        alphabet.setMinimum(0);
        alphabet.setMaximum(max);
        alphabet.setValue(act);
        alphabet.setString(act + "/" + max);
        break;
      case BRANCH_SEARCH:
        branchen.setMinimum(0);
        branchen.setMaximum(max);
        branchen.setValue(act);
        branchen.setString(act + "/" + max);
        break;
      case BUILDING_SEARCH:
        buildings.setMinimum(0);
        buildings.setMaximum(max);
        buildings.setValue(act);
        buildings.setString(act + "/" + max);
        break;
      case DB_WRITE:
        database.setMinimum(0);
        database.setMaximum(max);
        database.setValue(act);
        database.setString(act + "/" + max);
        break;
    }

    // long freeMem = Runtime.getRuntime().freeMemory();
    long totalMem = Runtime.getRuntime().totalMemory() / (1024 * 1024);
    long maxMem = Runtime.getRuntime().maxMemory() / (1024 * 1024);

    this.memConsumption.setString(totalMem + " MB / " + maxMem + " MB");
    this.memConsumption.setMinimum(0);
    this.memConsumption.setMaximum((int) maxMem);
    this.memConsumption.setValue((int) totalMem);
  }
Example #26
0
  class RemindTask_restart extends TimerTask {
    Runtime rxrunti = Runtime.getRuntime();

    public void
        run() { // **************************************************************************************

      try {

        restartApplication();

      } catch (Exception e) {
        e.printStackTrace();
      }
    } // runx***************************************************************************************************
  } // remindtask
 /** Execute the system command 'cmd' and fill an ArrayList with the results. */
 public static ArrayList<String> executeSystemCommand(String cmd) {
   if (debug) System.out.println("cmd: " + cmd);
   ArrayList<String> list = new ArrayList<>();
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (debug) System.out.println(line);
       list.add(line);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return list;
 }
Example #28
0
 public static void openURL(final String url) {
   final Configuration.OperatingSystem os = Configuration.getCurrentOperatingSystem();
   try {
     if (os == Configuration.OperatingSystem.MAC) {
       final Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
       final Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class});
       openURL.invoke(null, url);
     } else if (os == Configuration.OperatingSystem.WINDOWS) {
       Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
     } else {
       final String[] browsers = {
         "firefox",
         "opera",
         "konqueror",
         "epiphany",
         "mozilla",
         "netscape",
         "google-chrome",
         "chromium-browser"
       };
       String browser = null;
       for (int count = 0; count < browsers.length && browser == null; count++) {
         if (Runtime.getRuntime().exec(new String[] {"which", browsers[count]}).waitFor() == 0) {
           browser = browsers[count];
         }
       }
       if (browser == null) {
         throw new Exception("Could not find web browser");
       } else {
         Runtime.getRuntime().exec(new String[] {browser, url});
       }
     }
   } catch (final Exception e) {
     log.warning("Unable to open " + url);
   }
 }
 public static String ping(String address) {
   String reply = "Request timed out";
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (line.trim().startsWith("Reply ")) {
         reply = line;
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return reply;
 }
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    LauncherDirectories directories = new LauncherDirectories();
    Directories.instance = directories;

    // Prefer IPv4
    System.setProperty("java.net.preferIPv4Stack", "true");

    params = setupParameters(args);

    cleanup();

    SplashScreen splash =
        new SplashScreen(
            Toolkit.getDefaultToolkit()
                .getImage(
                    SplashScreen.class.getResource(
                        "/org/spoutcraft/launcher/resources/splash.png")));
    splash.setVisible(true);
    directories.setSplashScreen(splash);

    MetalLookAndFeel.setCurrentTheme(new OceanTheme());
    setLookAndFeel();

    console = new Console(params.isConsole());
    SpoutcraftLauncher.logger = setupLogger();
    console.setRotatingFileHandler(SpoutcraftLauncher.handler);

    int launcherBuild = parseInt(getLauncherBuild(), -1);
    logger.info("------------------------------------------");
    logger.info("Love Launcher is starting....");
    logger.info("Launcher Build: " + launcherBuild);

    params.logParameters(logger);

    Runtime.getRuntime().addShutdownHook(new ShutdownThread(console));

    // Set up the launcher and load login frame
    Launcher launcher = new Launcher();

    splash.dispose();
    launcher.startup();

    logger.info("Launcher took: " + (System.currentTimeMillis() - start) + "ms to start");
  }