Exemple #1
0
  /**
   * 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();
  }
Exemple #2
0
  // function to do the compute use case
  public static void compute() throws Exception {
    HttpPost method = new HttpPost(url + "/compute");

    method.setEntity(new StringEntity(username, "UTF-8"));

    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    System.out.println("Give the file name which has to be put in the grid for computation");

    // input of the file name to be computed
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String name = in.readLine();

    // get the absolute path of the current working directory
    File directory = new File(".");
    String pwd = directory.getAbsolutePath();

    // get present time
    date = new Date();
    long start = date.getTime();

    String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp;
    System.out.println(cmd);

    // Execute the vishwa compute process
    Process p = Runtime.getRuntime().exec(cmd);

    // wait till the compute process is completed
    // check for the status code (0 for successful termination)
    int status = p.waitFor();

    if (status == 0) {
      System.out.println("Compute operation successful. Check the directory for results");
    }

    date = new Date();
    long end = date.getTime();
    long durationInt = end - start;

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/computeAck");
    method.setEntity(new StringEntity(username + ";" + duration, "UTF-8"));
    try {
      client.execute(method);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      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);
 }
 private String createTemporaryPreinstallFile() {
   try {
     File tempFile = File.createTempFile("preinstall", null);
     tempFile.deleteOnExit();
     InstallUtil.copyResourceToFile("/gnu/io/installer/resources/macosx/preinstall", tempFile);
     String absPath = tempFile.getAbsolutePath();
     Process p = Runtime.getRuntime().exec(new String[] {"chmod", "a+x", absPath});
     p.waitFor();
     return absPath;
   } catch (Throwable t) {
   }
   return null;
 }
 /*
  * Run the given command.
  */
 protected static int run(String message, String[] commandArray) {
   try {
     Process process = Runtime.getRuntime().exec(commandArray, null, output);
     StreamProcessor.start(process.getErrorStream(), StreamProcessor.STDERR, true);
     StreamProcessor.start(process.getInputStream(), StreamProcessor.STDOUT, true);
     process.waitFor();
     return process.exitValue();
   } catch (IOException e) {
     fail(message, e);
   } catch (InterruptedException e) {
     fail(message, e);
   }
   return -1;
 }
Exemple #6
0
  public static String[] runCommand(String cmd, File dir) throws IOException {

    Process p = Runtime.getRuntime().exec(cmd.split(" +"), new String[] {}, dir);
    String[] results =
        new String[] {
          IOUtil.readStringFully(p.getInputStream()), IOUtil.readStringFully(p.getErrorStream())
        };
    try {
      if (p.waitFor() != 0)
        throw new RuntimeException(
            "command failed [" + cmd + "]\n" + results[0] + "\n" + results[1]);
    } catch (InterruptedException ie) {
      throw new RuntimeException("uh oh");
    }
    return results;
  }
Exemple #7
0
  public static boolean exec(String cmd) throws Exception {
    int exitVal = -1;
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(new String[] {"/bin/bash", "-c", cmd});

      OutputHandler err = new OutputHandler(proc.getErrorStream(), cmd);
      err.start();

      OutputHandler out = new OutputHandler(proc.getInputStream(), cmd);
      out.start();

      exitVal = proc.waitFor();

    } catch (Throwable t) {
      t.printStackTrace();
    }
    return (exitVal == 0);
  }
  /**
   * Checks if address can be reached using one argument InetAddress.isReachable() version or ping
   * command if failed.
   *
   * @param addr Address to check.
   * @param reachTimeout Timeout for the check.
   * @return {@code True} if address is reachable.
   */
  public static boolean reachableByPing(InetAddress addr, int reachTimeout) {
    try {
      if (addr.isReachable(reachTimeout)) return true;

      String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress());

      Process myProc = Runtime.getRuntime().exec(cmd);

      myProc.waitFor();

      return myProc.exitValue() == 0;
    } catch (IOException ignore) {
      return false;
    } catch (InterruptedException ignored) {
      Thread.currentThread().interrupt();

      return false;
    }
  }
Exemple #9
0
  public void run() {

    while (1 == 1) {

      System.out.println("Start run OneTimeTimer.bat...");
      try {
        Runtime rt = Runtime.getRuntime();
        // this.sProcess = rt.exec("GuardEternal.bat");
        this.sProcess = rt.exec("OneTimeTimer.bat");

        Process pr = this.sProcess;

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

        String line = null;

        System.out.println(
            "========================= OneTimeTimer.bat Start =========================");

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

        int exitVal = pr.waitFor();

        System.out.println(
            "========================= OneTimeTimer.bat end =========================");

      } catch (Exception e) {
        System.out.println("Execute bat failed: " + e.getMessage());
      }

      try {
        System.out.println("Sleep 10 mins");
        Thread.sleep(10 * 60 * 1000);
      } catch (InterruptedException e) {
        System.out.println("Server thread sleep(1000) failed: " + e.getMessage());
      }
    }
  }
  public void run() {

    try {
      // opens a new buffered reader from the socket input stream
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      os = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

      // String used to read the lines of data
      String inputLine;

      // reads the first line of data This should contain the command
      inputLine = in.readLine();
      StringTokenizer s = new StringTokenizer(inputLine);
      // sets the command to the first token of the first line
      String command = s.nextToken();

      if (s.hasMoreTokens()) {
        inputLine = s.nextToken();

        // check password
        if (inputLine.equals("passwd")) if (!passwd(s)) return;
      }

      String time = getTime();

      // change to input file
      String outDir = docRoot + command + time;
      os.println("output/" + command + time);

      // Checks for possible security holes in command
      if ((command.charAt(0) == '/')
          || (command.charAt(0) == '.')
          || (command.charAt(0) == '~')
          || (command.indexOf(";") > 0)) {
        System.out.println("invalid operation name : " + inputLine);
        return;
      }

      // creates the new directory where the files will be stored
      Process p = Runtime.getRuntime().exec("mkdir " + outDir);
      p.waitFor();

      // reads in the e-mail address
      String email = in.readLine();

      // reads the command args
      // these are passed to the shell script as parameters
      String args = in.readLine();

      PrintWriter outStream = null;
      String input = "";

      while (((input = in.readLine()) != null) && (!input.equals("quit"))) {
        // for debuging purposes
        System.out.println(input);

        // starts a new file
        if (input.equals("***NEW***")) {
          // closes old file if new one needed
          if (outStream != null) outStream.close();

          input = in.readLine();

          // for debuging purposes
          System.out.println(input);

          File f = new File(outDir + "/" + input);
          outStream = new PrintWriter(new FileOutputStream(f), true);
        } else outStream.println(input);
      }
      System.out.println("Closing outStream");
      outStream.close();
      System.out.println("Closing inStream");
      in.close();

      // os.println("http://www.jwave.vt.edu/output/"+command+time);
      System.out.println("Running " + commandDir + command + " " + args + " in " + outDir);
      // runs the associated script file
      Process n = Runtime.getRuntime().exec(commandDir + command + " " + outDir + " " + args);
      System.out.println("Ran" + commandDir + command + " in " + outDir);
      n.waitFor();

      os.close();
      // closes the socket
      socket.close();

      new ReceiverMailer(command, "/output/" + command + time, email);
    } catch (UnknownHostException e) {
      System.err.println("Don't know about host:.");
    } catch (IOException e) {
      System.err.println("Having trouble sending e-mail");
    } catch (InterruptedException e) {
      System.err.println("Having trouble sending email");
    }
  }
Exemple #11
0
  public static void main(String[] args) {
    /** Define a host server */
    String host = "localhost";
    /** Define a port */
    int port = 19999;
    int port2 = 19990;
    // int port3 = 19980;
    StringBuffer instr = new StringBuffer();
    String TimeStamp;
    Parser parser = new Parser();
    System.out.println("SocketClient initialized");

    try {

      // parsing
      // DataStream ds =
      // new PlainTextByLineDataStream(
      // new FileReader(new File("input.txt")));
      BufferedReader inputReader = new BufferedReader(new FileReader("input.txt"));
      String sent;
      while ((sent = inputReader.readLine()) != null) {
        // String sentence = (String)ds.nextToken() + (char) 13;
        String sentence = sent + (char) 13;
        // System.out.println(str);
        System.out.println("Parsing....");

        Tree tree = parser.parse(sentence);
        System.out.println(tree);

        System.out.println("Extracting features...");
        String srlIdentifier = "python srl-identifier.py " + '"' + tree + '"';
        // System.out.println(srlIdentifier);
        Runtime rr = Runtime.getRuntime();
        Process pp = rr.exec(srlIdentifier);
        BufferedReader brr = new BufferedReader(new InputStreamReader(pp.getInputStream()));
        pp.waitFor();

        BufferedReader reader = new BufferedReader(new FileReader("identifier.test"));
        BufferedReader classifier = new BufferedReader(new FileReader("classifier.test"));
        String line;
        PrintWriter identifierOutput = new PrintWriter("identifier-output.txt");
        PrintWriter classifierOutput = new PrintWriter("classifier-output.txt");
        BufferedReader preds = new BufferedReader(new FileReader("pred.test"));

        while ((line = reader.readLine()) != null) {

          String pred = preds.readLine();
          String features = line + (char) 13;
          String classifierFeature = classifier.readLine() + (char) 13;

          InetAddress address = InetAddress.getByName(host);
          // Establish a socket connetion
          Socket connection = new Socket(address, port);
          Socket connection2 = new Socket(address, port2);

          // Instantiate a BufferedOutputStream object
          BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());

          // Instantiate an OutputStreamWriter object with the optional character
          // encoding.
          //

          OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

          BufferedReader fromServer =
              new BufferedReader(new InputStreamReader(connection.getInputStream()));

          // Write across the socket connection and flush the buffer

          osw.write(features);
          osw.flush();
          String identifierResponse = fromServer.readLine();
          identifierOutput.println(identifierResponse);

          BufferedOutputStream bos2 = new BufferedOutputStream(connection2.getOutputStream());

          // Instantiate an OutputStreamWriter object with the optional character
          // encoding.
          //
          OutputStreamWriter osw2 = new OutputStreamWriter(bos2, "US-ASCII");

          BufferedReader fromServer2 =
              new BufferedReader(new InputStreamReader(connection2.getInputStream()));

          osw2.write(classifierFeature);
          osw2.flush();
          String ClassifierResponse = fromServer2.readLine();
          classifierOutput.println(pred + ' ' + ClassifierResponse);
        }
        identifierOutput.close();
        classifierOutput.close();

        Runtime rlabeler = Runtime.getRuntime();
        String srlClassifier = "python concept-formulator.py";
        Process p = rlabeler.exec(srlClassifier);
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        p.waitFor();
        // System.out.println("here i am");
        String line2;
        while ((line2 = br.readLine()) != null) {
          System.out.println(line2);
          // while (br.ready())
          // System.out.println(br.readLine());
        }
      }

    } catch (Exception e) {
      String cause = e.getMessage();
      if (cause.equals("python: not found")) System.out.println("No python interpreter found.");
    }
  }