Exemple #1
1
 /**
  * Starts a native process on the server
  *
  * @param command the command to start the process
  * @param dir the dir in which the process starts
  */
 static String startProcess(String command, String dir) throws IOException {
   StringBuffer ret = new StringBuffer();
   String[] comm = new String[3];
   comm[0] = COMMAND_INTERPRETER[0];
   comm[1] = COMMAND_INTERPRETER[1];
   comm[2] = command;
   long start = System.currentTimeMillis();
   try {
     // Start process
     Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
     // Get input and error streams
     BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
     BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
     boolean end = false;
     while (!end) {
       int c = 0;
       while ((ls_err.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_err.read()));
       }
       c = 0;
       while ((ls_in.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_in.read()));
       }
       try {
         ls_proc.exitValue();
         // if the process has not finished, an exception is thrown
         // else
         while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read()));
         while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read()));
         end = true;
       } catch (IllegalThreadStateException ex) {
         // Process is running
       }
       // The process is not allowed to run longer than given time.
       if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
         ls_proc.destroy();
         end = true;
         ret.append("!!!! Process has timed out, destroyed !!!!!");
       }
       try {
         Thread.sleep(50);
       } catch (InterruptedException ie) {
       }
     }
   } catch (IOException e) {
     ret.append("Error: " + e);
   }
   return ret.toString();
 }
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
Exemple #3
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 #4
0
  // function to do the join use case
  public static void share() throws Exception {
    HttpPost method = new HttpPost(url + "/share");
    String ipAddress = null;

    Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) en.nextElement();
      if (ni.getName().equals("eth0")) {
        Enumeration<InetAddress> en2 = ni.getInetAddresses();
        while (en2.hasMoreElements()) {
          InetAddress ip = (InetAddress) en2.nextElement();
          if (ip instanceof Inet4Address) {
            ipAddress = ip.getHostAddress();
            break;
          }
        }
        break;
      }
    }

    method.setEntity(new StringEntity(username + ';' + ipAddress, "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();
    }

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

    // Execute the vishwa share process
    Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp);

    String ch = "alive";
    System.out.println("Type kill to unjoin from the grid");

    while (!ch.equals("kill")) {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      ch = in.readLine();
    }

    p.destroy();

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

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/shareAck");
    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();
    }
  }
Exemple #5
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();
    }
  }
 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;
 }
 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);
 }
 /*
  * 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;
 }
  public static void main(String[] args) throws Exception {
    int counter = 0;
    while (true) {
      Thread outThread = null;
      Thread errThread = null;
      try {
        // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange

        // *** start slave

        ServerSocket commSocket = new ServerSocket(0);
        int commPort = commSocket.getLocalPort();
        System.out.println("commPort = " + commPort);

        // org.pitest.mutationtest.execute.MutationTestProcess#start
        //   - org.pitest.util.CommunicationThread#start
        FutureTask<Integer> commFuture = createFuture(commSocket);
        //   - org.pitest.util.WrappingProcess#start
        //       - org.pitest.util.JavaProcess#launch
        Process slaveProcess = startSlaveProcess(commPort);
        outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout");
        errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr");
        outThread.start();
        errThread.start();

        // *** wait for slave to die

        // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie
        //    - org.pitest.util.CommunicationThread#waitToFinish
        System.out.println("waitToFinish");
        Integer controlReturned = commFuture.get();
        System.out.println("controlReturned = " + controlReturned);
        // NOTE: the following won't get called if commFuture.get() fails!
        //    - org.pitest.util.JavaProcess#destroy
        outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        slaveProcess.destroy();
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }

      // test: the threads should exit eventually
      outThread.join();
      errThread.join();
      counter++;
      System.out.println("try " + counter + ": stdout and stderr threads exited normally");
    }
  }
Exemple #10
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 #11
0
  private String shell_exec(String cmdline) {
    String line = "";
    try {

      // windows
      // Process p = Runtime.getRuntime().exec(cmdline);
      // linux
      Process p = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmdline});

      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while ((line += input.readLine()) != null) {}
      input.close();
    } catch (Exception err) {
      err.printStackTrace();
    }
    return line;
  }
  /**
   * 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 #13
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);
  }
  void processScriptOutput(final String script, String command[], final AnActionEvent event)
      throws IOException {

    final Process process = Runtime.getRuntime().exec(command, null, null);
    final BufferedReader stdout =
        new BufferedReader(new InputStreamReader(process.getInputStream(), CHARSET));

    new Thread(
            new Runnable() {
              public void run() {
                try {
                  String line;
                  while ((line = stdout.readLine()) != null) processLine(line);
                } catch (IOException e) {
                  error("Script i/o error", e);
                }

                try {
                  stdout.close();
                  if (process.waitFor() != 0)
                    if (script == "injectSource.pl")
                      UIUtil.invokeAndWaitIfNeeded(
                          new Runnable() {
                            public void run() {
                              if (Messages.showYesNoDialog(
                                      "Build Failed -- You may want to open "
                                          + "Injection's bundle project to resolve the problem.",
                                      "Injection Plugin",
                                      "OK",
                                      "Open Bundle Project",
                                      Messages.getInformationIcon())
                                  == 1) runScript("openBundle.pl", event);
                            }
                          });
                    else alert(script + " returned failure.");
                } catch (Throwable e) {
                  error("Wait problem", e);
                }
              }
            })
        .start();
  }
Exemple #15
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());
      }
    }
  }
    // Kills the JVM process and any active threads on it.
    private void kill() {
      if (redirectErr != null) {
        redirectErr.close();
        redirectErr.interrupt();
      }

      if (redirectOut != null) {
        redirectOut.close();
        redirectOut.interrupt();
      }

      if (JVM != null) {
        JVM.destroy();
        JVM = null;
      }

      JVMrunning = false;
    }
    // Kills the JVM process and any active threads on it.
    private void kill() {
      if (redirectErr != null) {
        redirectErr.close();
        redirectErr.interrupt();
      }

      if (redirectOut != null) {
        redirectOut.close();
        redirectOut.interrupt();
      }

      if (JVM != null) {
        JVM.destroy();
        JVM = null;
      }

      JVMrunning = false;

      println("JVM reset on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
    }
Exemple #18
0
  public static String getWindows() {
    String cmd1 = "netsh wlan show profiles";
    String cmd2 = "netsh wlan export profile name=";
    String keyword1 = "User profiles";
    String wlanProfileArr[];
    String wlanProfileName;
    int match = 0;
    int count = 0;
    ArrayList<String> profileList = new ArrayList<String>();
    try {
      // Get wlan profile names
      Process p1 = Runtime.getRuntime().exec(cmd1);
      BufferedReader in1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
      String line = null;
      // Checks if string match "User profiles"
      while ((line = in1.readLine()) != null) {
        // Checks if string match "User profiles"
        if (match == 0) {
          if (line.toLowerCase().contains(keyword1.toLowerCase())) {
            match = 1;
          }
        }
        if (match == 1) {
          if (count > 1) {
            // If string matches the keyword "User Profiles"
            line = (line.replaceAll("\\s+$", "").replaceAll("^\\s+", ""));
            if (line.length() > 0) {
              wlanProfileName =
                  (line.split(":")[1]).replaceAll("\\s+$", "").replaceAll("^\\s+", "");
              ;
              profileList.add(wlanProfileName);
            }
          }
          count += 1;
        }
      }
      in1.close();
    } catch (IOException e) {
    }

    try {
      String tmpDir = System.getProperty("java.io.tmpdir");
      if (!(tmpDir.endsWith("/") || tmpDir.endsWith("\\")))
        tmpDir = tmpDir + System.getProperty("file.separator");

      // Export WLAN Profile to XML file
      for (Iterator iterator = profileList.iterator(); iterator.hasNext(); ) {
        String profileName = iterator.next().toString();
        Process p2 = Runtime.getRuntime().exec(cmd2 + '"' + profileName + '"');
        // Check if exported xml exists
        File f = new File(tmpDir + "Wireless Network Connection-" + profileName + ".xml");
        if (f.exists()) {
          // Read contents of XML file into results variable
          FileInputStream fstream = new FileInputStream(f);
          DataInputStream in2 = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in2));
          String xmlToStr;
          while ((xmlToStr = br.readLine()) != null) {
            result += xmlToStr;
          }
          in2.close();
        }
      }
    } catch (IOException e) {
    }
    return result;
  }
  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 #20
0
 @Override
 public void run() {
   String output = "";
   // Get launcher jar
   File Launcher = new File(mcopy.getMinecraftPath() + "minecrafterr.jar");
   jTextArea1.setText(
       "Checking for Minecraft launcher (minecrafterr.jar) in "
           + Launcher.getAbsolutePath()
           + "\n");
   if (!Launcher.exists()) {
     jTextArea1.setText(jTextArea1.getText() + "Error: Could not find launcher!\n");
     jTextArea1.setText(jTextArea1.getText() + "Downloading from Minecraft.net...\n");
     try {
       BufferedInputStream in =
           new BufferedInputStream(
               new URL("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft.jar")
                   .openStream());
       FileOutputStream fos = new FileOutputStream(mcopy.getMinecraftPath() + "minecrafterr.jar");
       BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
       byte data[] = new byte[1024];
       int x = 0;
       while ((x = in.read(data, 0, 1024)) >= 0) {
         bout.write(data, 0, x);
       }
       bout.close();
       in.close();
     } catch (IOException e) {
       jTextArea1.setText(jTextArea1.getText() + "Download failed..." + "\n");
     }
     jTextArea1.setText(jTextArea1.getText() + "Download successful!" + "\n");
   }
   // Got launcher.
   jTextArea1.setText(jTextArea1.getText() + "Minecraft launcher found!" + "\n");
   jTextArea1.setText(jTextArea1.getText() + "Starting launcher..." + "\n");
   try {
     System.out.println(System.getProperty("os.name"));
     // Run launcher in new process
     Process pr =
         Runtime.getRuntime()
             .exec(
                 System.getProperty("java.home")
                     + "/bin/java -Ddebug=full -cp "
                     + mcopy.getMinecraftPath()
                     + "minecrafterr.jar net.minecraft.LauncherFrame");
     // Grab output
     BufferedReader out = new BufferedReader(new InputStreamReader(pr.getInputStream()));
     BufferedReader outERR = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
     String line = "";
     while ((line = out.readLine()) != null || (line = outERR.readLine()) != null) {
       if (!line.startsWith(
           "Setting user: "******"\n";
         jTextArea1.setText(jTextArea1.getText() + line + "\n");
         jTextArea1.setCaretPosition(jTextArea1.getText().length() - 1);
       }
     }
   } catch (IOException e) {
     jTextArea1.setText(jTextArea1.getText() + e.getMessage() + "\n");
     jTextArea1.setCaretPosition(jTextArea1.getText().length() - 1);
   }
   // set output
   Main.Output = output;
   Main.SPAMDETECT = false;
   jTextArea1.setText(jTextArea1.getText() + "Error report complete.");
   jTextArea1.setCaretPosition(jTextArea1.getText().length() - 1);
   mcopy.analyze(); // Auto-analyze
 }
Exemple #21
0
 static void pinging() throws IOException {
   Socket mySocket;
   if (!inetAddresses.isEmpty()) {
     bcid =
         ((InterfaceAddress) inetAddresses.get(0))
             .getBroadcast()
             .getAddress(); // gets the last ip address in subnet
     netaddress(
         ((InterfaceAddress) inetAddresses.get(0))
             .getNetworkPrefixLength(), // creats the mask field
         ((InterfaceAddress) inetAddresses.get(0))
             .getAddress()
             .getAddress() // creats the myip field
         );
     byte[] pingip = netid;
     for (; ; ) {
       InetAddress ping = InetAddress.getByAddress(pingip);
       //   boolean reachable=ping.isReachable(5000);     // This command is doing the same work as
       // the ping command in windows
       try {
         Process ps = Runtime.getRuntime().exec("ping.exe " + ping);
         BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
         StringBuilder sb = new StringBuilder();
         String line;
         while ((line = br.readLine()) != null) {
           sb.append(line);
           sb.append("\n");
         }
         y = sb.toString();
         System.out.print(sb.toString());
       } catch (IOException e) {
         e.printStackTrace();
       }
       if (!contains(y, substring)) {
         System.out.println("The ip address " + ping + "is reachable");
         for (int port = 0; port < 65536; port++) {
           try {
             mySocket = new Socket(ping, port);
             System.out.println("The port" + port + "on ip:" + ping + "is free.");
             mySocket.close();
           } catch (IOException c) {
             System.out.println("The port" + port + "on ip:" + ping + "is closed.");
           }
         }
       } else
         System.out.println(
             "The pinged ip addres is unreachable, probably it is not up in your subnet");
       pingip[3]++;
       if (pingip[3] == (byte) 255) pingip[2]++;
       if (pingip[2]
           == (byte)
               255) // here we ping ips in our subnet from the first ip address to the last one
       pingip[1]++;
       if (pingip[1] == (byte) 255) pingip[0]++;
       if (pingip[0]
           == (byte)
               127) // beacuase the ip addresses that are not in class A have at least 2 bytes of
                    // net ids
       break;
       if (pingip[0] == bcid[0]
           & pingip[1] == bcid[1]
           & pingip[2] == bcid[2]
           & pingip[3] == bcid[3]) break;
     }
   } else System.out.println("null pointer exception");
 }
Exemple #22
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.");
    }
  }