Exemplo n.º 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));
  }
Exemplo n.º 2
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;
  }
Exemplo n.º 3
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;
  }
 @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) {
   }
 }
Exemplo n.º 5
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);
     }
   }
 }
Exemplo n.º 6
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;
  }
 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);
   }
 }
Exemplo n.º 8
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();
      }
    }
  }
Exemplo n.º 9
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);
      }
    }
  }
Exemplo n.º 10
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);
  }
Exemplo n.º 11
0
 public String execRecognizer() {
   try {
     String inputFile = new File(tmpdir, "input").getAbsolutePath();
     String[] args =
         new String[] {"java", "-classpath", tmpdir + pathSep + CLASSPATH, "Test", inputFile};
     // String cmdLine = "java -classpath "+CLASSPATH+pathSep+tmpdir+" Test " + new File(tmpdir,
     // "input").getAbsolutePath();
     // System.out.println("execParser: "+cmdLine);
     Process process = Runtime.getRuntime().exec(args, null, new File(tmpdir));
     StreamVacuum stdoutVacuum = new StreamVacuum(process.getInputStream());
     StreamVacuum stderrVacuum = new StreamVacuum(process.getErrorStream());
     stdoutVacuum.start();
     stderrVacuum.start();
     process.waitFor();
     stdoutVacuum.join();
     stderrVacuum.join();
     String output = null;
     output = stdoutVacuum.toString();
     if (stderrVacuum.toString().length() > 0) {
       this.stderrDuringParse = stderrVacuum.toString();
       System.err.println("exec stderrVacuum: " + stderrVacuum);
     }
     return output;
   } catch (Exception e) {
     System.err.println("can't exec recognizer");
     e.printStackTrace(System.err);
   }
   return null;
 }
Exemplo n.º 12
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;
  }
  public static int RefreshDatabase() {
    if (ERROR == SendHttp("http://" + HOST + ":" + REST_PORT + "/" + DATABASEINDEX, REQ_DELETE)) {
      System.out.println(PROMPT + "Delete log database index failed!");
      return ERROR;
    }
    if (ERROR == SendHttp("http://" + HOST + ":" + REST_PORT + "/" + DATABASEINDEX, REQ_PUT)) {
      System.out.println(PROMPT + "Create log database index failed!");
      return ERROR;
    }
    // Set mapping manually
    try {
      String cmd =
          "curl -XPUT "
              + HOST
              + ':'
              + REST_PORT
              + "/"
              + DATABASEINDEX
              + '/'
              + DATABASETYPE
              + "/_mapping --data-binary @./data/Log/map.json";
      Process ps = Runtime.getRuntime().exec(cmd);
      ps.waitFor();

      BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
      String line;
      while ((line = br.readLine()) != null) {
        System.out.println(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
      return ERROR;
    }
    return SUCCESS;
  }
Exemplo n.º 14
0
  /**
   * Creates a transcoded input stream by executing the given command. If <code>in</code> is not
   * null, data from it is copied to the command.
   *
   * @param command The command to execute.
   * @param in Data to feed to the command. May be <code>null</code>.
   * @throws IOException If an I/O error occurs.
   */
  public TranscodeInputStream(String[] command, final InputStream in) throws IOException {

    StringBuffer buf = new StringBuffer("Starting transcoder: ");
    for (String s : command) {
      buf.append('[').append(s).append("] ");
    }
    LOG.debug(buf);

    process = Runtime.getRuntime().exec(command);
    processOutputStream = process.getOutputStream();
    processInputStream = process.getInputStream();

    // Must read stderr from the process, otherwise it may block.
    final String name = command[0];
    new InputStreamReaderThread(process.getErrorStream(), name, true).start();

    // Copy data in a separate thread
    if (in != null) {
      new Thread(name + " TranscodedInputStream copy thread") {
        public void run() {
          try {
            IOUtils.copy(in, processOutputStream);
          } catch (IOException x) {
            // Intentionally ignored. Will happen if the remote player closes the stream.
          } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(processOutputStream);
          }
        }
      }.start();
    }
  }
Exemplo n.º 15
0
  // Method: runTest
  // Runs the script specified in the test case object
  public void runTest() {
    try {
      Process p = Runtime.getRuntime().exec(this.execCommandLine);

      InputStreamReader esr = new InputStreamReader(p.getErrorStream());
      BufferedReader ereader = new BufferedReader(esr);
      InputStreamReader isr = new InputStreamReader(p.getInputStream());
      BufferedReader ireader = new BufferedReader(isr);

      String line = null;
      String line1 = null;
      while ((line = ireader.readLine()) != null) {
        // System.out.println("Output: " + line);
        System.out.println(line);
      }
      while ((line1 = ereader.readLine()) != null) {
        System.err.println("Error: " + line1);
      }

      int exitValue = p.waitFor();
      tcInstanceTools.LogMessage('d', "Test Case exit value: " + exitValue);
      if (exitValue == 0) {
        setTestCaseResult(Result.Pass);
      } else {
        setTestCaseResult(Result.Fail);
      }
    } catch (IOException ioe) {
      System.out.println("Error: " + ioe.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
Exemplo n.º 16
0
  /**
   * Gets the number of cores available in this device, across all processors. Requires: Ability to
   * peruse the filesystem at "/sys/devices/system/cpu"
   *
   * @return The number of cores, or available processors if failed to get result
   */
  public static int getCoresNumbers() {
    if (CPU_CORES != 0) {
      return CPU_CORES;
    }
    // Private Class to display only CPU devices in the directory listing
    class CpuFilter implements FileFilter {
      @Override
      public boolean accept(File pathname) {
        // Check if filename is "cpu", followed by a single digit number
        if (Pattern.matches("cpu[0-9]+", pathname.getName())) {
          return true;
        }
        return false;
      }
    }

    try {
      // Get directory containing CPU info
      File dir = new File("/sys/devices/system/cpu/");
      // Filter to only list the devices we care about
      File[] files = dir.listFiles(new CpuFilter());
      // Return the number of cores (virtual CPU devices)
      CPU_CORES = files.length;
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (CPU_CORES < 1) {
      CPU_CORES = Runtime.getRuntime().availableProcessors();
    }
    if (CPU_CORES < 1) {
      CPU_CORES = 1;
    }
    return CPU_CORES;
  }
Exemplo n.º 17
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();
    }
  }
Exemplo n.º 18
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);
	}
Exemplo n.º 19
0
Arquivo: Macro.java Projeto: bramk/bnd
  /**
   * System command. Execute a command and insert the result.
   *
   * @param args
   * @param help
   * @param patterns
   * @param low
   * @param high
   */
  public String system_internal(boolean allowFail, String args[]) throws Exception {
    verifyCommand(
        args,
        "${"
            + (allowFail ? "system-allow-fail" : "system")
            + ";<command>[;<in>]}, execute a system command",
        null,
        2,
        3);
    String command = args[1];
    String input = null;

    if (args.length > 2) {
      input = args[2];
    }

    Process process = Runtime.getRuntime().exec(command, null, domain.getBase());
    if (input != null) {
      process.getOutputStream().write(input.getBytes("UTF-8"));
    }
    process.getOutputStream().close();

    String s = IO.collect(process.getInputStream(), "UTF-8");
    int exitValue = process.waitFor();
    if (exitValue != 0) return exitValue + "";

    if (!allowFail && (exitValue != 0)) {
      domain.error("System command " + command + " failed with " + exitValue);
    }
    return s.trim();
  }
Exemplo n.º 20
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();
    }
 public String startIOSWebKit(String udid) throws IOException, InterruptedException {
   input = new FileInputStream("config.properties");
   prop.load(input);
   String serverPath = prop.getProperty("APPIUM_JS_PATH");
   File file = new File(serverPath);
   File curentPath = new File(file.getParent());
   System.out.println(curentPath);
   file = new File(curentPath + "/.." + "/..");
   String ios_web_lit_proxy_runner =
       file.getCanonicalPath() + "/bin/ios-webkit-debug-proxy-launcher.js";
   String webkitRunner =
       ios_web_lit_proxy_runner + " -c " + udid + ":" + deviceMap.get(udid) + " -d";
   System.out.println(webkitRunner);
   p1 = Runtime.getRuntime().exec(webkitRunner);
   System.out.println(
       "WebKit Proxy is started on device "
           + udid
           + " and with port number "
           + deviceMap.get(udid)
           + " and in thread "
           + Thread.currentThread().getId());
   // Add the Process ID to hashMap, which would be needed to kill IOSwebProxywhen required
   appiumServerProcess.put(Thread.currentThread().getId(), getPid(p1));
   System.out.println("Process ID's:" + appiumServerProcess);
   Thread.sleep(1000);
   return deviceMap.get(udid);
 }
Exemplo n.º 22
0
 public static TByteArrayList transformByExternalCommand(
     final String command, final InputStream input) throws IOException {
   final Process process = Runtime.getRuntime().exec(command);
   final InputStream in = process.getInputStream();
   final OutputStream out = process.getOutputStream();
   final TByteArrayList bytes = new TByteArrayList(100500);
   final byte[] buffer = new byte[1024 * 1024];
   try {
     int read;
     while ((read = input.read(buffer)) > 0) {
       out.write(buffer, 0, read);
       if (in.available() > 0) {
         read = in.read(buffer);
         bytes.add(buffer, 0, read);
       }
     }
     out.close();
     while ((read = in.read(buffer)) > 0) {
       bytes.add(buffer, 0, read);
     }
     in.close();
   } catch (IOException ioe) {
     System.err.println(readByteStream(process.getErrorStream()));
     LOG.error(ioe);
     throw ioe;
   }
   return bytes;
 }
Exemplo n.º 23
0
  // ## operation runReactor()
  public void runReactor() {
    // #[ operation runReactor()
    // run reactor
    String dir = System.getProperty("RMG.workingDirectory");

    try {
      // system call for reactor
      String[] command = {dir + "/software/reactorModel/reactor.exe"};
      File runningDir = new File("chemkin");
      Process reactor = Runtime.getRuntime().exec(command, null, runningDir);
      InputStream ips = reactor.getInputStream();
      InputStreamReader is = new InputStreamReader(ips);
      BufferedReader br = new BufferedReader(is);
      String line = null;
      while ((line = br.readLine()) != null) {
        // System.out.println(line);
      }
      int exitValue = reactor.waitFor();
    } catch (Exception e) {
      System.out.println("Error in running reactor!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
  public static void main(String[] Args) {
    // System.setProperty("KEY", "HNY81514525MALVIYA");
    // Map<String, String> env = System.getenv();
    // for (String envName : env.keySet())
    // System.out.format("%s = %s%n", envName, env.get(envName));

    // reg add HKCU\\Environment /v developer /d \"Honey Keny Malviya" /f"

    try {
      String PERSONAL_FOLDER_CMD = "reg query HKCU\\Environment /v developer";
      String REGSTR_TOKEN = "REG_SZ";
      Process process = Runtime.getRuntime().exec(PERSONAL_FOLDER_CMD);
      StreamReader reader = new StreamReader(process.getInputStream());
      reader.start();
      process.waitFor();
      reader.join();
      String result = reader.getResult();
      int p = result.indexOf(REGSTR_TOKEN);
      if (p == -1) return;
      System.out.println(result.substring(p + REGSTR_TOKEN.length()).trim());
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }
  }
    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.
      }
    }
Exemplo n.º 26
0
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
Exemplo n.º 27
0
  /**
   * Gives the same basic functionality of File.exists but can be used to look for removable media
   * without showing a system dialog if the media is not present. Workaround pulled from the <A
   * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on
   * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start
   * requiring Java 6.
   */
  protected static boolean fileExists(File file) {
    try {
      Process process =
          Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()});

      // We need to consume all available output or the process will block.
      boolean haveExitCode = false;
      int exitCode = -1;
      InputStream out = process.getInputStream();
      InputStream err = process.getErrorStream();

      while (!haveExitCode) {
        while (out.read() >= 0) {}
        while (err.read() >= 0) {}

        try {
          exitCode = process.exitValue();
          haveExitCode = true;
        } catch (IllegalThreadStateException e) {
          // Not yet complete.
          Thread.sleep(100);
        }
      }
      // int exitCode = process.waitFor();
      return exitCode == 0;

    } catch (IOException e) {
      System.out.println("Unable to check for file: " + file + " : " + e);
      return false;

    } catch (InterruptedException e) {
      System.out.println("Unable to check for file.  Interrupted: " + file + " : " + e);
      return false;
    }
  }
 private void clearLog() {
   try {
     Runtime.getRuntime().exec("logcat -c");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 29
0
  /**
   * Gets the token.
   *
   * @param scope the scope
   * @return the token
   */
  private String getToken(String scope) {
    Process curlProc;
    String outputString;
    DataInputStream curlIn = null;
    String access_token = null;
    String command =
        "curl -X POST -H Content-Type:application/x-www-form-urlencoded "
            + adminUrl
            + "/oauth2/token --insecure --data"
            + " client_id="
            + client_id
            + "&"
            + "client_secret="
            + client_secret
            + "&grant_type=client_credentials&scope="
            + scope;
    try {
      curlProc = Runtime.getRuntime().exec(command);

      curlIn = new DataInputStream(curlProc.getInputStream());

      while ((outputString = curlIn.readLine()) != null) {
        JSONObject obj = new JSONObject(outputString);
        access_token = obj.getString("access_token");
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
    return access_token;
  }
Exemplo n.º 30
0
  public static void main(String[] args) throws Exception {

    final Main main = new Main();
    main.init();

    // Automatic shutdown
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                main.disconnectAll();
              }
            });

    // Manual shutdown
    log.info("========================================================");
    log.info("OpenDevice Middleware - started on port {}", main.port);
    log.info("Type [quit] or [CTRL+C] to stop the server");
    log.info("========================================================");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String a = "";
    while (!("quit".equals(a))) {
      a = br.readLine();
    }

    System.out.println("Disconnecting all...");
    main.disconnectAll();
    Thread.sleep(800);
    System.exit(-1);
  }