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);
      }
    }
  }
  /**
   * Takes as input a GnuPlot script file path and executes this script. inside the script the user
   * can plot to screen, pause and then print to a post script file.
   *
   * @param args args[0] should be the path to the GnuPlot script file relative to the Simulator
   *     directory e.g. ./inputFiles/100C_20P_centralised/Gnuplot.gnu
   *     <p>Example Script file GnuPlot.gnu:
   *     <p>set xlabel "Lateral Displacement"; set ylabel "Contra-Lateral Displacement"; set zlabel
   *     "Amplitude" set parametric set isosamples 75,75 set contour base set cntrparam level
   *     incremental -1, 0.2, 10 set clabel '%4.2f' set contour surface set contour base; set
   *     nosurface set surface; set view 20,60 set view 60,30 set hidden3d splot u,v,sin(u)*cos(v)
   *     title "Standing Waves" set size 1.0, 0.6 set terminal postscript portrait enhanced color
   *     dashed lw 1 "Helvetica" 14 set output 'tempoutput/my-plot.ps' replot set terminal x11 set
   *     size 1,1 #pause 5
   */
  public static void gnuplot(String[] args) {

    logger.info("gnuplot called on scriptfile: " + args[0]);
    // get a Runtime object
    Runtime r = Runtime.getRuntime();

    try {
      // start the process: gnuplot
      String exe = "wgnuplot " + args[0];
      // String exe = "C:/Program Files/gnuplot/bin/wgnuplot " + args[0];
      logger.info(exe);
      Process p = r.exec(exe);

      //			any error message?
      StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERR");

      // any output?
      StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUT");

      // kick them off
      errorGobbler.start();
      outputGobbler.start();

      // any error???
      int exitVal = p.waitFor();
      logger.error("ExitValue: " + exitVal);

    } catch (Exception e) {
      logger.fatal("Error Executing gnuplot: " + args[0] + " - ", e);
    }
  }
Example #3
0
  String[] getMedkit(
      String[] availableResources,
      String[] requiredResources,
      String[] missions,
      double P,
      double C) {
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(exec);
      OutputStream os = proc.getOutputStream();
      InputStream is = proc.getInputStream();
      new ErrorReader(proc.getErrorStream()).start();

      StringBuffer sb = new StringBuffer();
      append(sb, availableResources);
      append(sb, requiredResources);
      append(sb, missions);
      sb.append(P).append('\n');
      sb.append(C).append('\n');
      os.write(sb.toString().getBytes());

      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      int N = Integer.parseInt(br.readLine().trim());
      String[] ret = new String[N];
      for (int i = 0; i < N; i++) ret[i] = br.readLine().trim();
      return ret;

    } catch (Exception e) {
      System.err.println("An error occurred while executing your program");
      e.printStackTrace();
      return null;
    }
  }
Example #4
0
  public String ejecutar(String programa, String arg1) throws Exception {
    String res = null;

    // Se lanza el ejecutable
    Process p;

    if (arg1 == null) {
      log.debug("ejecutar " + programa);
      p = Runtime.getRuntime().exec(programa);
    } else {
      log.debug("ejecutar " + programa + " " + arg1);
      p = Runtime.getRuntime().exec(new String[] {programa, arg1});
    }

    // Se obtiene el stream de salida del programa
    InputStream is = p.getInputStream();

    /* Se prepara un bufferedReader para poder leer la salida más comodamente. */
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    // Se lee la primera linea
    res = br.readLine();

    return res;
  }
  public String[] runJob(String command) {
    outputCatcher = null;

    try {

      String[] cmd = null;
      Process proc = null;
      Runtime rt = Runtime.getRuntime();

      String os = getOsName();
      System.out.println("OS = " + os);
      if (os.startsWith("Windows")) {
        cmd = new String[3];
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
        cmd[2] = command;

        proc = rt.exec(cmd);
      } else if (os.startsWith("Linux")) {
        cmd = new String[1];
        cmd[0] = command;

        proc = rt.exec(command.split(" "));
      }

      System.out.println("command is:");
      for (int i = 0; i < cmd.length; i++) {
        System.out.print(cmd[i] + " ");
      }
      System.out.println();

      // any error message?
      errorCatcher = new StreamCatcher(proc.getErrorStream(), "ERROR");

      // any output?
      outputCatcher = new StreamCatcher(proc.getInputStream(), "OUTPUT");

      // kick them off
      errorCatcher.start();
      outputCatcher.start();

      // any error???
      exitVal = proc.waitFor();

      System.out.println("ExitValue: " + exitVal);

      if (exitVal != 0) System.out.println(errorCatcher.builder.toString());
    } catch (Throwable t) {
      t.printStackTrace();
    }

    // now return both the stdout and stderr streams
    // just use a String array for this -- not pretty but it works
    // stdout is at position [0], stderr is at [1]
    String[] outputs = new String[2];
    outputs[0] = outputCatcher.builder.toString();
    outputs[1] = errorCatcher.builder.toString();

    return outputs;
  }
Example #6
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));
  }
  public void openUrl(String url) {
    String os = System.getProperty("os.name");
    Runtime runtime = Runtime.getRuntime();
    try {
      // Block for Windows Platform
      if (os.startsWith("Windows")) {
        String cmd = "rundll32 url.dll,FileProtocolHandler " + url;
        Process p = runtime.exec(cmd);

        // Block for Mac OS
      } else if (os.startsWith("Mac OS")) {
        Class fileMgr = Class.forName("com.apple.eio.FileManager");
        Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class});
        openURL.invoke(null, new Object[] {url});

        // Block for UNIX Platform
      } else {
        String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
        String browser = null;
        for (int count = 0; count < browsers.length && browser == null; count++)
          if (runtime.exec(new String[] {"which", browsers[count]}).waitFor() == 0)
            browser = browsers[count];

        if (browser == null) throw new Exception("Could not find web browser");
        else runtime.exec(new String[] {browser, url});
      }
    } catch (Exception x) {
      System.err.println("Exception occurd while invoking Browser!");
      x.printStackTrace();
    }
  }
Example #8
0
  /* Heck there's no getenv, we have to roll one ourselves! */
  public static Hashtable getenv() throws Throwable {
    Process p;
    if (File.separator.equals("\\")) {
      p = Runtime.getRuntime().exec("cmd /c set");
    } else {
      p = Runtime.getRuntime().exec("printenv");
    }

    InputStream in = p.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line;
    Hashtable table = new Hashtable();

    while ((line = reader.readLine()) != null) {
      int i = line.indexOf('=');
      if (i > 0) {
        String name = line.substring(0, i);
        String value = line.substring(i + 1);
        table.put(name, value);
      }
    }

    in.close();
    p.waitFor();
    return table;
  }
    public void generateDiagram(String outputDirectory, File dotFile) {
      try {
        Runtime run = Runtime.getRuntime();
        Process pr =
            run.exec(
                "dot "
                    + dotFile.getAbsolutePath()
                    + " -Tpng -o"
                    + outputDirectory
                    + FILE_SEPARATOR
                    + "graph.png");
        pr.waitFor();
        // BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        // should the output be really printed?
        //            String line;
        //            while ( ( line = buf.readLine() ) != null )
        //            {
        //                System.out.println(line) ;
        //            }
        // FIXME how to handle exceptions in listener?
      } catch (IOException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InterruptedException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
Example #10
0
  public static void main(String args[]) {

    try {
      Runtime rt = Runtime.getRuntime();
      // Process pr = rt.exec("cmd /c dir");
      Process pr = rt.exec("python ciao.py");

      BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

      String line = null;

      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }

      int exitVal = pr.waitFor();
      if (exitVal == 0) {
        System.out.println("Exited without errors ");
      } else {
        System.out.println("Exited with error code " + exitVal);
      }

    } catch (Exception e) {
      System.out.println(e.toString());
      e.printStackTrace();
    }
  }
Example #11
0
  public static String getArchName() throws Exception {
    if (archName == null) {
      archName = "lin";

      // bits
      Process process = Runtime.getRuntime().exec("uname -m");
      process.waitFor();
      if (process.exitValue() != 0) throw new Exception("Error arch");
      BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String arch = inStream.readLine();
      if (arch.equals("i686")) archName += "32";
      else archName += "64";
      process.destroy();

      // SSE
      process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
      process.waitFor();
      if (process.exitValue() != 0) throw new Exception("Error /proc/cpuinfo");
      inStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line, cpuinfo = "";
      while ((line = inStream.readLine()) != null) cpuinfo += line;

      String bestSSE = "sse";
      String[] sses = {"sse2", "sse3", "ssse3", "sse4", "avx"};
      for (int i = 0; i < sses.length; i++) {
        if (cpuinfo.indexOf(sses[i]) >= 0) bestSSE = sses[i];
      }
      archName += bestSSE;
      process.destroy();
    }
    return archName;
  }
Example #12
0
 public void run() {
   /*
   int ch;
   RandomAccessFile fin=null;
   try{
       fin= new RandomAccessFile("/dev/simplechar","rw");
       while(true){
   	try{
   	    while((ch=fin.read())!=-1){
   		System.out.println((char) ch);
   		//Thread.sleep(50);
   	    }
   	}catch (Exception e){System.out.println(e);}
       }
   } catch(FileNotFoundException e){
       System.out.println("Ooops! didn't find device");
       }
   */
   while (true) {
     try {
       Runtime.getRuntime().exec("cat /dev/simplechar ");
       Runtime.getRuntime().exec("echo 'ddddd'>/dev/simplechar");
     } catch (Exception e) {
       System.out.println(e);
     }
   }
 }
 @Override
 public void onStart() {
   super.onStart();
   try {
     InputStream in = getAssets().open("hid-gadget-test");
     OutputStream out =
         new BufferedOutputStream(
             new FileOutputStream(getFilesDir().getAbsolutePath() + "/hid-gadget-test"));
     copyFile(in, out);
     in.close();
     out.close();
     Runtime.getRuntime()
         .exec("/system/bin/chmod 755 " + getFilesDir().getAbsolutePath() + "/hid-gadget-test")
         .waitFor();
     in = getAssets().open("hid-gadget-test-" + android.os.Build.CPU_ABI);
     out =
         new BufferedOutputStream(
             new FileOutputStream(getFilesDir().getAbsolutePath() + "/hid-gadget-test"));
     copyFile(in, out);
     in.close();
     out.close();
     Runtime.getRuntime()
         .exec("/system/bin/chmod 755 " + getFilesDir().getAbsolutePath() + "/hid-gadget-test")
         .waitFor();
   } catch (Exception e) {
   }
 }
Example #14
0
  /**
   * It will call the external dot program, and return the image in binary format.
   *
   * @param dot Source of the graph (in dot language).
   * @return The image of the graph in .gif format.
   */
  private byte[] get_img_stream(File dot) {
    File img;
    byte[] img_stream = null;

    try {
      img = File.createTempFile("graph_", ".gif", new File(TEMP_DIR));
      String temp = img.getAbsolutePath();

      Runtime rt = Runtime.getRuntime();
      String cmd = DOT + " -Tgif " + dot.getAbsolutePath() + " -o" + temp;
      Process p = rt.exec(cmd);
      p.waitFor();

      FileInputStream in = new FileInputStream(temp);
      img_stream = new byte[in.available()];
      in.read(img_stream);
      // Close it if we need to
      if (in != null) in.close();

      if (img.delete() == false) System.err.println("Warning: " + temp + " could not be deleted!");
    } catch (java.io.IOException ioe) {
      System.err.println("Error:    in I/O processing of tempfile in dir " + TEMP_DIR + "\n");
      System.err.println("       or in calling external command");
      ioe.printStackTrace();
    } catch (java.lang.InterruptedException ie) {
      System.err.println("Error: the execution of the external program was interrupted");
      ie.printStackTrace();
    }

    return img_stream;
  }
Example #15
0
	public static void main(String[] args) throws Exception{
		//free和use和total均为KB 
		long free=0; 
		long use=0; 
		long total=0;  
		int kb=1024;

		Runtime rt=Runtime.getRuntime();
		total=rt.totalMemory();
		free=rt.freeMemory();
		use=total-free;
		
		System.out.println("系统内存已用的空间为:"+use/kb+" MB");
		System.out.println("系统内存的空闲空间为:"+free/kb+" MB");
		System.out.println("系统总内存空间为:"+total/kb+" MB");   

		OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
		
		long physicalFree=osmxb.getFreePhysicalMemorySize()/kb;
		long physicalTotal=osmxb.getTotalPhysicalMemorySize()/kb;
		long physicalUse=physicalTotal-physicalFree;
		String os=System.getProperty("os.name");
		System.out.println("操作系统的版本:"+os);
		System.out.println("系统物理内存已用的空间为:"+physicalFree+" MB");
		System.out.println("系统物理内存的空闲空间为:"+physicalUse+" MB");
		System.out.println("总物理内存:"+physicalTotal+" MB");

		// 获得线程总数 
        	ThreadGroup parentThread;
        	for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent())
			;
		int totalThread = parentThread.activeCount();

		System.out.println("获得线程总数:"+totalThread);
	}
Example #16
0
    public static String getGCStats() {
        long totalGC = 0;
        long gcTime = 0;

        for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
            long count = gc.getCollectionCount();

            if (count >= 0) {
                totalGC += count;
            }

            long time = gc.getCollectionTime();

            if (time >= 0) {
                gcTime += time;
            }
        }

        StringBuilder sb = new StringBuilder();

        sb.append(banner("memory stats"));
        sb.append("\n- total collections: " + totalGC);
        sb.append("\n- total collection time: " + formatTime(gcTime));

        Runtime runtime = Runtime.getRuntime();
        sb.append("\n- total memory: " + _.printMem(runtime.totalMemory()));

        return sb.toString();
    }
Example #17
0
  /**
   * Runs executable command
   *
   * @param command
   * @param config the configuration setting
   * @exception IOException
   */
  private Process run(String[] command, String[] config) throws IOException {
    try {
      Runtime rt = Runtime.getRuntime();
      return rt.exec(command, config);

    } catch (Exception e) {
      throw new IOException("Run process error: " + e.getMessage());
    }
  }
Example #18
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);
   }
 }
Example #19
0
 /**
  * processes the input String and produces an output String.
  *
  * @param input the String to input to the underlying process
  * @throws java.lang.Exception exceptions from Runtime and Process that this class uses
  * @return the output from the underlying process
  */
 public String process(String input) throws Exception {
   String returnValue = new String();
   StringBuffer buffer = new StringBuffer();
   if (socketServer == true) {
     returnValue = client.process(input);
     ServerThread current = getServer();
     if (current != null) {
       if (!current.isDaemon()) {
         current.getProcess().destroy();
       }
       current.interrupt();
     }
   } else { // not a socket server
     Runtime rt = Runtime.getRuntime();
     String output = "";
     String errors = "";
     try {
       p = rt.exec(getCodeCall() + " " + getParams());
       PrintStream processInputStream = new PrintStream(p.getOutputStream(), true, "utf-8");
       processInputStream.println(input + "\n\u0003"); // put in garbage to kill Bikel's loop
       StreamConsumer errorConsumer = new StreamConsumer(p.getErrorStream(), "error", 1);
       StreamConsumer outputConsumer = new StreamConsumer(p.getInputStream(), "output", 10);
       outputConsumer.start();
       errorConsumer.start();
       int countloops = 0;
       int time = 0;
       String message = "";
       while (!outputConsumer.isComplete()) {
         // wait
         Thread.sleep(100);
         countloops++;
         time += 100; // one tenth of a second
         if (time > waittime) { // just wait 5 minutes
           message = "exceeded waittime of " + waittime + " milliseconds";
           break;
         }
       }
       errors = errorConsumer.getOutput();
       output = outputConsumer.getOutput();
       if (!message.equals("")) {
         errors = message;
       }
     } catch (IOException ioe) {
       System.err.println("Module error: " + getModuleName());
       ioe.printStackTrace();
       System.exit(0);
     }
     p.destroy();
     if (errors.equals("")) {
       returnValue = output;
     } else {
       returnValue = errors;
     }
   }
   return returnValue;
 }
 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 #21
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();
  }
 public void destroyIOSWebKitProxy() throws IOException, InterruptedException {
   Thread.sleep(3000);
   if (appiumServerProcess.get(Thread.currentThread().getId()) != -1) {
     String process = "pgrep -P " + appiumServerProcess.get(Thread.currentThread().getId());
     Process p2 = Runtime.getRuntime().exec(process);
     BufferedReader r = new BufferedReader(new InputStreamReader(p2.getInputStream()));
     String command = "kill -9 " + r.readLine();
     System.out.println("Kills webkit proxy");
     System.out.println("******************" + command);
     Runtime.getRuntime().exec(command);
   }
 }
 private void WhenDeployBatchScriptIsCalled() {
   try {
     System.out.println("Running the batch script for Building Webserver Files");
     String command = "cmd /C start " + LocalMachine.home + "automate/autoBuild.bat";
     Runtime rt = Runtime.getRuntime();
     rt.exec(command);
     System.out.println("Finished running the autoBuild batch script");
   } catch (Exception e) {
     System.out.println("Error creating the FileInfo panel: " + e);
     e.printStackTrace();
   }
 }
  public static void export() {
    String initial =
        ("cmd /c C:\\mysql -uroot -pw89620c helicopterBackUpDatabase< d:\\helicopterDatabase.sql");
    Runtime rt = Runtime.getRuntime();
    try {
      setExec(rt.exec(initial));

    } catch (IOException ex) {
      Logger.getLogger(ReceivingDatabaseBackupFromHelicopter.class.getName())
          .log(Level.SEVERE, null, ex);
    }
  }
Example #25
0
  public static void textToMp3(String text, OutputStream os) {
    File txt = null;
    File wav = null;
    File mp3 = null;
    try {
      txt = File.createTempFile("txt", ".txt");
      FileWriter fw = new FileWriter(txt);
      fw.write(text);
      fw.close();

      wav = File.createTempFile("wav", ".wav");
      if (!wav.delete()) {
        throw new RuntimeException("couldn't delete wav");
      }
      mp3 = File.createTempFile("mp3", ".mp3");
      if (!mp3.delete()) {
        throw new RuntimeException("couldn't delete mp3");
      }

      String cmd =
          String.format(
              "/usr/bin/text2wave < %s -o %s", txt.getAbsolutePath(), wav.getAbsolutePath());

      Process p = Runtime.getRuntime().exec(new String[] {"/bin/bash", "-c", cmd});
      show(p.getErrorStream());
      System.out.println(p.waitFor()); // TODO check return code

      p =
          Runtime.getRuntime()
              .exec(new String[] {"/usr/bin/lame", wav.getAbsolutePath(), mp3.getAbsolutePath()});
      System.out.println(p.waitFor()); // TODO check return code
      FileInputStream fis = new FileInputStream(mp3);
      int read = fis.read();
      while (read != -1) {
        os.write(read);
        read = fis.read();
      }
    } catch (Throwable t) {
      throw new RuntimeException(t);
    } finally {
      // TODO check return codes
      if (mp3 != null) {
        mp3.delete();
      }
      if (txt != null) {
        txt.delete();
      }
      if (wav != null) {
        wav.delete();
      }
    }
  }
Example #26
0
  public static void main(String argv[]) {

    BMDriver bmt = new BMDriver();
    boolean dbstatus;

    dbstatus = bmt.runTests();

    if (dbstatus != true) {
      System.err.println("Error encountered during buffer manager tests:\n");
      Runtime.getRuntime().exit(1);
    }

    Runtime.getRuntime().exit(0);
  }
Example #27
0
  protected int getNumRunningMappers() throws IOException {
    int numRunningMappers = 0;
    Runtime runtime = Runtime.getRuntime();
    String cmds[] = {"ps", "-C", getCommandName(), "--no-headers"};
    Process proc = runtime.exec(cmds);
    InputStream inputstream = proc.getInputStream();
    InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
    BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
    while (bufferedreader.readLine() != null) {
      numRunningMappers++;
    }

    return numRunningMappers;
  }
Example #28
0
  public String call(String filename) throws IOException {
    // create runtime to execute external command
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec(filename);

    // retrieve output from python script
    BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line = "";
    while ((line = bfr.readLine()) != null) {
      // display each output line form python script
      return line;
    }
    return line;
  }
Example #29
0
  /**
   * Fired when a control is clicked. This is the equivalent of
   * ActionListener.actionPerformed(ActionEvent e).
   */
  protected void actionPerformed(GuiButton par1GuiButton) {
    if (par1GuiButton.enabled) {
      if (par1GuiButton.id == 5) {
        if (Minecraft.getOs() == EnumOS.MACOS) {
          try {
            this.mc.getLogAgent().logInfo(this.fileLocation);
            Runtime.getRuntime().exec(new String[] {"/usr/bin/open", this.fileLocation});
            return;
          } catch (IOException var7) {
            var7.printStackTrace();
          }
        } else if (Minecraft.getOs() == EnumOS.WINDOWS) {
          String var2 =
              String.format(
                  "cmd.exe /C start \"Open file\" \"%s\"", new Object[] {this.fileLocation});

          try {
            Runtime.getRuntime().exec(var2);
            return;
          } catch (IOException var6) {
            var6.printStackTrace();
          }
        }

        boolean var8 = false;

        try {
          Class var3 = Class.forName("java.awt.Desktop");
          Object var4 =
              var3.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]);
          var3.getMethod("browse", new Class[] {URI.class})
              .invoke(
                  var4,
                  new Object[] {(new File(Minecraft.getMinecraftDir(), "texturepacks")).toURI()});
        } catch (Throwable var5) {
          var5.printStackTrace();
          var8 = true;
        }

        if (var8) {
          this.mc.getLogAgent().logInfo("Opening via system class!");
          Sys.openURL("file://" + this.fileLocation);
        }
      } else if (par1GuiButton.id == 6) {
        this.mc.displayGuiScreen(this.guiScreen);
      } else {
        this.guiTexturePackSlot.actionPerformed(par1GuiButton);
      }
    }
  }
Example #30
0
  /**
   * Create the distribution and name the file according to the specified parameter.
   *
   * @param distribName The name of distribution
   * @return True if the distribution is built. False otherwise.
   */
  public boolean make(String distribName) {
    boolean createdDir = (new File(distribName)).mkdir();
    if (createdDir) {

      String currentFile = "";
      try {

        for (String filename : distFiles) {
          currentFile = filename;
          File destFile = new File(filename);
          String relativePath = distribName + "/" + destFile.getName();
          destFile = new File(relativePath);
          FileSystem.copyFile(new File(filename), destFile);
        }

        String tarFileName = String.format("%s.tar", distribName);
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(String.format("tar -cf %s %s/", tarFileName, distribName));

        if (p.waitFor() == 0) {

          File tarFile = new File(tarFileName);
          FileSystem.gzipFile(tarFile, new File(tarFileName + ".gz"));
          tarFile.delete();
          FileSystem.deleteDir(new File(distribName));

          lastCreatedDistribution = distribName;

          return true;

        } else {
          System.err.printf(
              "%s: Unable to create tar file %s\n", this.getClass().getName(), tarFileName);
        }
      } catch (IOException e) {
        System.err.printf(
            "%s: Unable to add file %s to distribution %s\n",
            this.getClass().getName(), currentFile, distribName);
      } catch (InterruptedException e) {
        System.err.printf(
            "%s: tar did not return from building %s.tar\n",
            this.getClass().getName(), distribName);
      }
    } else {
      System.err.printf(
          "%s: Unable to create temp directory %s\n", this.getClass().getName(), distribName);
    }

    return false;
  }