Java Code Examples for java.lang.ProcessBuilder.Redirect

The following are top voted examples for showing how to use java.lang.ProcessBuilder.Redirect. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ansible-http   File: ProcessBuilderTests.java   Source Code and License 7 votes vote down vote up
@Ignore
public void login() throws Exception {
  List<String> commands = new ArrayList<>();
  commands.add("ssh");
  // commands.add("-t");
  // commands.add ("-o StrictHostKeyChecking=no");
  commands.add("[email protected]");
  ProcessBuilder processBuilder = new ProcessBuilder();
  processBuilder.command(commands);
  processBuilder.redirectErrorStream(true);
  Process process = processBuilder.start();
  processBuilder.redirectOutput(Redirect.PIPE);
  processBuilder.redirectInput(Redirect.PIPE);
  processBuilder.redirectError(Redirect.PIPE);

  String passwd = "fortis90";
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
  writer.write(passwd, 0, passwd.length());
  writer.newLine();
  writer.close();


  Integer exitStatus = process.waitFor();
  System.out.println(exitStatus);
  process.destroy();
}
 
Example 2
Project: scorekeeperfrontend   File: DockerContainer.java   Source Code and License 6 votes vote down vote up
@Override
public boolean dumpDatabase(Path path, boolean compress)
{
    ProcessBuilder p = Exec.build(machineenv, "docker", "exec", name, "pg_dumpall", "-U", "postgres", "-c");
    p.redirectOutput(Redirect.appendTo(path.toFile()));
    int ret = Exec.execit(p, null);
    if ((ret == 0) && compress) {
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(path.toFile()+".zip"));
            out.putNextEntry(new ZipEntry(path.getFileName().toString()));
            FileInputStream in = new FileInputStream(path.toFile());
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
            Files.deleteIfExists(path);
        } catch (Exception ioe) {
            log.log(Level.INFO, "Unable to compress database backup: " + ioe, ioe);
        }
    }
    return ret == 0;
}
 
Example 3
Project: rcom   File: StreamSourceVnc.java   Source Code and License 6 votes vote down vote up
public void start(Client client, String streamName) throws IOException {
	conn=client.conn;
	oss=new OutputStreamSender(client.getMultiplexer(), StreamShareVNC.bufferSize, true);
	try(ServerSocket ss=new ServerSocket())
	{
		ss.bind(new InetSocketAddress("localhost", 0));
		int localport=ss.getLocalPort();
		System.out.println("Local port: "+localport);
		params=new StreamParametersVNC(streamName, client.id);
		StreamDataDuplex data=(StreamDataDuplex)client.conn.shareStream(oss.getId(), params);
		isr=new InputStreamReceiver(StreamShareVNC.bufferSize, true);
		client.getMultiplexer().register(isr, data.backChannel);
		ChainList<String> command=new ChainList<>(client.getArgs().program_x11vnc,"-connect", "localhost:"+localport);
		//command.addcs("-clip", "200x200+50+50");
		command.add("-localhost");
		new ProcessBuilder(command).redirectError(Redirect.INHERIT)
				.redirectOutput(Redirect.INHERIT)
				.start();
		s=ss.accept();
		os=new LogFilterOutpurStream(s.getOutputStream());
		System.out.println("CONNECTED!");
		ConnectStreams.startStreamThread(s.getInputStream(), oss.os);
		ConnectStreams.startStreamThread(isr.in, os);
	}
}
 
Example 4
Project: rcom   File: StreamSinkVNC.java   Source Code and License 6 votes vote down vote up
@Override
public void start(AbstractRcomArgs args, IVideocomConnection conn, IMultiplexer multiplexer)
		throws Exception {
	int n=9;
	int port=5900+n;
	try(ServerSocket ss=new ServerSocket())
	{
		ss.bind(new InetSocketAddress("localhost", port));
		ChainList<String> command=new ChainList<>(args.program_vncviewer, "-ViewOnly", "localhost:"+n);
		p=new ProcessBuilder(command).redirectError(Redirect.INHERIT).redirectOutput(Redirect.INHERIT).start();
		s=ss.accept();
	}
	oss=new OutputStreamSender(multiplexer, StreamShareVNC.bufferSize, true);
	StreamDataDuplex stream=(StreamDataDuplex)conn.registerStream(streamParametersVNC.name, oss.getId());
	isr=new InputStreamReceiver(StreamShareVNC.bufferSize, true);
	isr.register(multiplexer, stream.backChannel);
	conn.launchStream(streamParametersVNC.name);
	ConnectStreams.startStreamThread(isr.in, s.getOutputStream());
	ConnectStreams.startStreamThread(s.getInputStream(), oss.os);
}
 
Example 5
Project: Mastering-Mesos   File: SingularityExecutorTaskLogManager.java   Source Code and License 6 votes vote down vote up
private void copyLogTail() {
  if (configuration.getTailLogLinesToSave() <= 0) {
    return;
  }

  final Path tailOfLogPath = taskDefinition.getTaskDirectoryPath().resolve(configuration.getServiceFinishedTailLog());

  if (Files.exists(tailOfLogPath)) {
    log.debug("{} already existed, skipping tail", tailOfLogPath);
    return;
  }

  final List<String> cmd = ImmutableList.of(
      "tail",
      "-n",
      Integer.toString(configuration.getTailLogLinesToSave()),
      taskDefinition.getServiceLogOut());

  try {
    new SimpleProcessManager(log).runCommand(cmd, Redirect.to(tailOfLogPath.toFile()));
  } catch (Throwable t) {
    log.error("Failed saving tail of log {} to {}", taskDefinition.getServiceLogOut(), configuration.getServiceFinishedTailLog(), t);
  }
}
 
Example 6
Project: Mastering-Mesos   File: LogViewerController.java   Source Code and License 6 votes vote down vote up
/**
 * Create a process builder to launch the log viewer
 * @param logDirectory
 * @return
 */
protected ProcessBuilder createProcessBuilder() {
  ProcessBuilder pb = new ProcessBuilder(
      Paths.get(System.getProperty("user.dir"), "/bin/storm").toString(),
      "logviewer",
      "-c",
      "storm.log.dir=" + System.getenv("MESOS_SANDBOX") + "/logs",
      "-c",
      Config.LOGVIEWER_PORT + "=" + port
  );

  // If anything goes wrong at startup we want to see it.
  Path logPath = Paths.get(System.getenv("MESOS_SANDBOX"), "/logs");
  if (!logPath.toFile().exists() && !logPath.toFile().mkdirs()) {
    throw new RuntimeException("Couldn't create log directory");
  }
  File log = Paths.get(System.getenv("MESOS_SANDBOX"), "/logs/logviewer-startup.log").toFile();
  pb.redirectErrorStream(true);
  pb.redirectOutput(Redirect.appendTo(log));
  return pb;
}
 
Example 7
Project: embedded-elasticsearch   File: ElasticSearchInstaller.java   Source Code and License 6 votes vote down vote up
private void installPlugins() throws IOException, InterruptedException {
    File pluginManager = pluginManagerExecutable();
    setExecutable(pluginManager);

    for (InstallationDescription.Plugin plugin : installationDescription.getPlugins()) {
        logger.info("> " + pluginManager + " install " + plugin.getExpression());
        ProcessBuilder builder = new ProcessBuilder();
        builder.redirectOutput(Redirect.INHERIT);
        builder.redirectError(Redirect.INHERIT);
        builder.command(prepareInstallCommand(pluginManager, plugin));
        Process process = builder.start();
        if (process.waitFor() != 0) {
            throw new EmbeddedElasticsearchStartupException("Unable to install plugin: " + plugin);
        }
    }
}
 
Example 8
Project: demo-java-9   File: PipeProcessesAndAwaitCompletion.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	ProcessBuilder ls = new ProcessBuilder()
			.command("tree", "-i")
			.directory(Paths.get("/home/nipa").toFile());
	ProcessBuilder grepPdf = new ProcessBuilder()
			.command("grep", "pdf")
			.redirectOutput(Redirect.INHERIT);
	List<Process> lsThenGrep = ProcessBuilder.startPipeline(asList(ls, grepPdf));

	System.out.println("Started processes...");

	CompletableFuture[] lsThenGrepFutures = lsThenGrep.stream()
			// onExit returns a CompletableFuture<Process>
			.map(Process::onExit)
			.map(processFuture -> processFuture.thenAccept(
					process -> System.out.println("Process " + process.getPid() + " finished.")))
			.toArray(CompletableFuture[]::new);
	// wait until all processes are finished
	CompletableFuture
			.allOf(lsThenGrepFutures)
			.join();
}
 
Example 9
Project: pkb   File: MalletWrapper.java   Source Code and License 6 votes vote down vote up
public static void createCrfModel(String featFilepath, String modelFilepath,
        String modelPrintFilepath)
                throws IOException, InterruptedException, ClassNotFoundException {
  // preparation
  File featFile = new File(featFilepath);
  File modelFile = new File(modelFilepath);
  List<String> trainCommand = Arrays.asList("java", "-cp", "mallet.jar:mallet-deps.jar",
          "cc.mallet.fst.SimpleTagger", "--train", "true", "--model-file",
          modelFile.getAbsolutePath(), "--weights", "sparse", "--fully-connected", "false",
          featFile.getAbsolutePath());
  File commandDir = new File("mallet-2.0.7");
  // execute train
  Process trainProcess = new ProcessBuilder(trainCommand).directory(commandDir)
          .redirectError(Redirect.INHERIT).start();
  trainProcess.waitFor();
  // read model
  @SuppressWarnings("resource")
  ObjectInputStream ois = new ObjectInputStream(new FileInputStream(modelFile));
  CRF crf = (CRF) ois.readObject();
  PrintWriter out = new PrintWriter(modelPrintFilepath);
  crf.print(out);
  out.close();
}
 
Example 10
Project: Stud.IP-Client   File: UpdateModel.java   Source Code and License 6 votes vote down vote up
/**
 * Restarts the StudIP Client.
 */
public void launchAndExit() {
	Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
		public void run() {
			// Start Updater
			ProcessBuilder pb = new ProcessBuilder("java", "-Dname=StudIP_Client", "-jar", clientApp);
			pb.redirectOutput(Redirect.INHERIT);
			pb.redirectError(Redirect.INHERIT);
			try {
				pb.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}));

	System.exit(0);
}
 
Example 11
Project: bixie   File: AbstractIcTest.java   Source Code and License 6 votes vote down vote up
protected File compileJavaFile(File sourceFile) throws IOException {
	final File tempDir = getTempDir();
	final String javac_command = String.format("javac -g -cp %s %s -d %s", System.getProperty("java.class.path"),
			sourceFile.getAbsolutePath(), tempDir.getAbsolutePath());

	ProcessBuilder pb = new ProcessBuilder(javac_command.split(" "));
	pb.redirectOutput(Redirect.INHERIT);
	pb.redirectError(Redirect.INHERIT);
	Process p = pb.start();

	try {
		p.waitFor();
	} catch (InterruptedException e) {
		e.printStackTrace();
		return null;
	}

	return tempDir;
}
 
Example 12
Project: bixie   File: AbstractIcTest.java   Source Code and License 6 votes vote down vote up
protected File compileJavaFile(File sourceFile) throws IOException {
	final File tempDir = getTempDir();
	final String javac_command = String.format("javac -g %s -d %s",
			sourceFile.getAbsolutePath(), tempDir.getAbsolutePath());

	ProcessBuilder pb = new ProcessBuilder(javac_command.split(" "));
	pb.redirectOutput(Redirect.INHERIT);
	pb.redirectError(Redirect.INHERIT);
	Process p = pb.start();

	try {
		p.waitFor();
	} catch (InterruptedException e) {
		e.printStackTrace();
		return null;
	}

	return tempDir;
}
 
Example 13
Project: bixie   File: AbstractIcTest.java   Source Code and License 6 votes vote down vote up
protected File compileJavaFiles(File[] sourceFiles) throws IOException {
	final File tempDir = getTempDir();
    StringBuilder sb = new StringBuilder();
    for (File f : sourceFiles) {
    	sb.append(f.getAbsolutePath());
    	sb.append(" ");
    }
	final String javac_command = String.format("javac -g -d %s %s",
			tempDir.getAbsolutePath(), sb.toString());

	System.out.println(javac_command);
	
	ProcessBuilder pb = new ProcessBuilder(javac_command.split(" "));
	pb.redirectOutput(Redirect.INHERIT);
	pb.redirectError(Redirect.INHERIT);
	Process p = pb.start();

	try {
		p.waitFor();
	} catch (InterruptedException e) {
		e.printStackTrace();
		return null;
	}

	return tempDir;
}
 
Example 14
Project: amstore-daemon   File: AmstoreResource.java   Source Code and License 6 votes vote down vote up
@GET 
	@Path("/restart-ambari")
    @Produces(MediaType.TEXT_PLAIN)
    public String restartAmbari() throws IOException {

		ProcessBuilder p = new ProcessBuilder();
//		p.command("/etc/init.d/ambari-server", "restart");
		p.command("/bin/bash", "/usr/lib/amstore-daemon/ambari-restarter.sh");
		p.redirectOutput(Redirect.appendTo(new File(
				"/var/log/amstore-daemon.log")));
		p.redirectErrorStream(true);
		p.start();

		// Runtime.getRuntime().exec("/etc/init.d/ambari-server restart");
		return "Ambari restart initiated.";
    }
 
Example 15
Project: varnish-exec   File: VarnishExec.java   Source Code and License 6 votes vote down vote up
/**
 * @throws UncheckedIOException if an I/O error occurs. This can happen if cannot run varnishd because of invalid varnishd command path.
 */
public VarnishProcess start(VarnishCommand command) {
    String[] commandArray = command.asArray();
    processBuilder.command(commandArray);
    processBuilder.redirectOutput(Redirect.INHERIT).redirectError(Redirect.INHERIT);
    System.out.println("Starting varnish using command: " + Arrays.stream(commandArray).collect(joining(" ")));
    Process process = start(processBuilder);
    try {
        do {
            sleep();
        } while (!listeningOrCrashed(command.getAddress(), process));
    } catch (InterruptedException e) {
        killProcess(process);
        Thread.currentThread().interrupt();
        return null;
    }
    return new VarnishProcess(process, command);
}
 
Example 16
Project: event-detection   File: SubprocessHelpers.java   Source Code and License 6 votes vote down vote up
/**
 * Executes a python script with the given arguments
 * 
 * @param scriptPath
 *            the {@link Path} to the script.
 * @param directory
 *            a {@link Path} to the directory from which to run the script
 * @param args
 *            the arguments to the script. Arguments that include spaces must be quoted
 * @return a started {@link Process}
 * @throws IOException
 *             if an error occurs while starting the process
 */
public static Process executePythonProcess(Path scriptPath, Path directory, String... args) throws IOException {
	Path relPath;
	try {
		relPath = directory.relativize(scriptPath);
	}
	catch (IllegalArgumentException e) {
		relPath = scriptPath;
	}
	String[] command = {bashPath, "-c", pythonPath.toString() + " \"[email protected]\"", "-", relPath.normalize().toString()};
	command = Arrays.copyOf(command, command.length + args.length);
	for (int i = 0; i < args.length; i++) //The command has 5 components that come before the arguments
		command[i + 5] = args[i];
	
	ProcessBuilder pb = new ProcessBuilder(command);
	pb.redirectError(Redirect.INHERIT); //So that errors can be seen
	pb.directory(directory.toFile());
	return pb.start();
}
 
Example 17
Project: lttng-ust-java-tests   File: ShellUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Execute a shell command and retrieve its return value.
 *
 * @param command
 *            The command to execute, as a list of individual arguments (do
 *            not use spaces)
 * @return If the command returned successfully (ret code = 0)
 */
public static boolean executeCommand(List<String> command) {
    try {
        /* "echo" the command to stdout */
        StringJoiner sj = new StringJoiner(" ", "$ ", "");
        command.stream().forEach(sj::add);
        System.out.println(sj.toString());

        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        builder.redirectOutput(Redirect.INHERIT);

        Process p = builder.start();
        int ret = p.waitFor();

        System.out.println("(returned from command)");

        return (ret == 0);

    } catch (IOException | InterruptedException e) {
        return false;
    }
}
 
Example 18
Project: google-java-format   File: MainTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testMain() throws Exception {
  Process process =
      new ProcessBuilder(
              ImmutableList.of(
                  Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(),
                  "-cp",
                  System.getProperty("java.class.path"),
                  Main.class.getName()))
          .redirectError(Redirect.PIPE)
          .redirectOutput(Redirect.PIPE)
          .start();
  process.waitFor();
  String err = new String(ByteStreams.toByteArray(process.getErrorStream()), UTF_8);
  assertThat(err).contains("Usage: google-java-format");
  assertThat(process.exitValue()).isEqualTo(0);
}
 
Example 19
Project: google-java-format   File: MainTest.java   Source Code and License 6 votes vote down vote up
@Test
public void exitIfChangedStdin() throws Exception {
  Path path = testFolder.newFile("Test.java").toPath();
  Files.write(path, "class Test {\n}\n".getBytes(UTF_8));
  Process process =
      new ProcessBuilder(
              ImmutableList.of(
                  Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(),
                  "-cp",
                  System.getProperty("java.class.path"),
                  Main.class.getName(),
                  "-n",
                  "--set-exit-if-changed",
                  "-"))
          .redirectInput(path.toFile())
          .redirectError(Redirect.PIPE)
          .redirectOutput(Redirect.PIPE)
          .start();
  process.waitFor();
  String err = new String(ByteStreams.toByteArray(process.getErrorStream()), UTF_8);
  String out = new String(ByteStreams.toByteArray(process.getInputStream()), UTF_8);
  assertThat(err).isEmpty();
  assertThat(out).isEqualTo("<stdin>" + System.lineSeparator());
  assertThat(process.exitValue()).isEqualTo(1);
}
 
Example 20
Project: google-java-format   File: MainTest.java   Source Code and License 6 votes vote down vote up
@Test
public void exitIfChangedFiles() throws Exception {
  Path path = testFolder.newFile("Test.java").toPath();
  Files.write(path, "class Test {\n}\n".getBytes(UTF_8));
  Process process =
      new ProcessBuilder(
              ImmutableList.of(
                  Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(),
                  "-cp",
                  System.getProperty("java.class.path"),
                  Main.class.getName(),
                  "-n",
                  "--set-exit-if-changed",
                  path.toAbsolutePath().toString()))
          .redirectError(Redirect.PIPE)
          .redirectOutput(Redirect.PIPE)
          .start();
  process.waitFor();
  String err = new String(ByteStreams.toByteArray(process.getErrorStream()), UTF_8);
  String out = new String(ByteStreams.toByteArray(process.getInputStream()), UTF_8);
  assertThat(err).isEmpty();
  assertThat(out).isEqualTo(path.toAbsolutePath().toString() + System.lineSeparator());
  assertThat(process.exitValue()).isEqualTo(1);
}
 
Example 21
Project: sequence-mining   File: IntervalClassification.java   Source Code and License 6 votes vote down vote up
/** Run shell script with command line arguments */
public static void runScript(final String cmd[], final File outFile) {

	try {
		final ProcessBuilder pb = new ProcessBuilder(cmd);
		if (outFile != null)
			pb.redirectOutput(outFile);
		else
			pb.redirectOutput(Redirect.INHERIT);
		pb.redirectError(Redirect.INHERIT);
		final Process process = pb.start();
		process.waitFor();
		process.destroy();
	} catch (final Exception e) {
		e.printStackTrace();
	}

}
 
Example 22
Project: sequence-mining   File: StatisticalSequenceMining.java   Source Code and License 6 votes vote down vote up
/** Run shell script with command line arguments */
public static void runScript(final String cmd[], final File outFile) {

	try {
		final ProcessBuilder pb = new ProcessBuilder(cmd);
		if (outFile != null)
			pb.redirectOutput(outFile);
		else
			pb.redirectOutput(Redirect.INHERIT);
		pb.redirectError(Redirect.INHERIT);
		final Process process = pb.start();
		process.waitFor();
		process.destroy();
	} catch (final Exception e) {
		e.printStackTrace();
	}

}
 
Example 23
Project: livestreamer_twitch_gui   File: LivestreamerUtils.java   Source Code and License 6 votes vote down vote up
public static JsonObject getQualityJsonFromLivestreamer(final String url) {
    LOGGER.trace("Get available quality options for {}", url);
    JsonObject jsonQualities = new JsonObject();
    try {
        final ProcessBuilder processBuilder = new ProcessBuilder(getQualityCommand(url));
        processBuilder.redirectError(Redirect.INHERIT);
        final Process process = processBuilder.start();
        final InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(),
                StandardCharsets.UTF_8);
        final JsonReader jsonReader = new JsonReader(inputStreamReader);
        jsonQualities = PARSER.parse(jsonReader).getAsJsonObject();
        process.waitFor();
    } catch (IOException | InterruptedException e) {
        LOGGER.error("failed to retrieve stream qualites for " + url + "," + " reason: " + e.getMessage(), e);
    }
    LOGGER.trace("Return {}", jsonQualities);
    return jsonQualities;
}
 
Example 24
Project: livestreamer_twitch_gui   File: LivestreamerUtils.java   Source Code and License 6 votes vote down vote up
public static void startLivestreamer(final String url, final String quality) {
    LOGGER.info("Starting Stream {} with Quality {}", url, quality);
    final Thread t = new Thread(() -> {
        try {
            final ProcessBuilder processBuilder = new ProcessBuilder(getRunCommand(url, quality));
            processBuilder.redirectOutput(Redirect.INHERIT);
            processBuilder.redirectError(Redirect.INHERIT);
            final Process process = processBuilder.start();
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            LOGGER.error("ERROR while running livestreamer", e);
        }
    });
    t.setDaemon(true);
    t.start();
}
 
Example 25
Project: livestreamer_twitch_gui   File: LivestreamerUtils.java   Source Code and License 6 votes vote down vote up
public static void recordLivestreamer(final String url, final String quality, final File filePath) {
    LOGGER.info("Record Stream {} with Quality {} to file {}", url, quality, filePath);
    Thread t = new Thread(() -> {
        try {
            String path = "\"" + filePath.getAbsolutePath() + "\"";
            path = path.replace('\\', '/');
            Settings.getInstance().recordingPathProperty().set(path);
            ProcessBuilder pb = new ProcessBuilder(
                    Arrays.asList(getLivestreamerExe(), "-o", path, url, quality + ",best,worst"));
            pb.redirectOutput(Redirect.INHERIT);
            pb.redirectError(Redirect.INHERIT);
            Process prc = pb.start();
            prc.waitFor();
        } catch (IOException | InterruptedException e) {
            LOGGER.error("ERROR while recording", e);
        }
    });
    t.setDaemon(true);
    t.start();
}
 
Example 26
Project: corvoid   File: Corvoid.java   Source Code and License 6 votes vote down vote up
private void run(String[] args) throws XMLStreamException, IOException {
	if (args.length < 2) {
		System.err.println("Usage: corvoid run main-class args...");
		System.exit(1);
	}
	DependencyTree tree = tree();
	String classpath = tree.classpath();
	List<String> command = new ArrayList<>();
	command.add("java");
	command.add("-cp");
	command.add("target/classes:" + classpath);
	command.addAll(Arrays.asList(args).subList(1, args.length));
	try {
		new ProcessBuilder().command(command)
		.redirectError(Redirect.INHERIT)
		.redirectOutput(Redirect.INHERIT)
		.redirectInput(Redirect.INHERIT)
		.start().waitFor();
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
}
 
Example 27
Project: corvoid   File: Corvoid.java   Source Code and License 6 votes vote down vote up
private void compileExternal(CompilerOptions options) throws IOException {
	List<String> cmd = options.buildCommandLine();
	for (String s : cmd) {
		System.out.print(s);
		System.out.print(" ");
	}
	System.out.println();
	try {
		new ProcessBuilder().command(cmd)
				.redirectError(Redirect.INHERIT)
				.redirectOutput(Redirect.INHERIT)
				.start().waitFor();
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
}
 
Example 28
Project: jar2bpl   File: ReflectionTest.java   Source Code and License 6 votes vote down vote up
protected File compileJavaFile(File sourceFile) throws IOException {
	final File tempDir = getTempDir();
	final String javac_command = String.format("javac -g %s -d %s",
			sourceFile.getAbsolutePath(), tempDir.getAbsolutePath());

	ProcessBuilder pb = new ProcessBuilder(javac_command.split(" "));
	pb.redirectOutput(Redirect.INHERIT);
	pb.redirectError(Redirect.INHERIT);
	Process p = pb.start();

	try {
		p.waitFor();
	} catch (InterruptedException e) {
		e.printStackTrace();
		return null;
	}

	return tempDir;
}
 
Example 29
Project: jar2bpl   File: SnippetTest.java   Source Code and License 6 votes vote down vote up
protected File compileJavaFile(File sourceFile) throws IOException {
	final File tempDir = getTempDir();
	final String javac_command = String.format("javac -g %s -d %s",
			sourceFile.getAbsolutePath(), tempDir.getAbsolutePath());

	ProcessBuilder pb = new ProcessBuilder(javac_command.split(" "));
	pb.redirectOutput(Redirect.INHERIT);
	pb.redirectError(Redirect.INHERIT);
	Process p = pb.start();

	try {
		p.waitFor();
	} catch (InterruptedException e) {
		e.printStackTrace();
		return null;
	}

	return tempDir;
}
 
Example 30
Project: GdxStudio   File: ToolBar.java   Source Code and License 6 votes vote down vote up
void run(){
	if(!Style.btnMap.get("stop").isEnabled()){
		Style.btnMap.get("stop").setEnabled(true);
		Style.btnMap.get("go").setEnabled(false);
	}
	if(!new File(Content.getProject()+new File(Content.getProject()).getName()+".jar").exists())
		Export.createJar();
	pb = new ProcessBuilder("java", "-jar", Content.getProject()+new File(Content.getProject()).getName()+".jar");
	pb.redirectOutput(Redirect.INHERIT);
	pb.redirectError(Redirect.INHERIT);
	pb.redirectInput(Redirect.INHERIT);
	try {
		runningProcess = pb.start();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 31
Project: gaffer   File: Process.java   Source Code and License 6 votes vote down vote up
public void start() throws ProcessException {
  final ProcessBuilder pb = new ProcessBuilder(cmd);

  final Map<String, String> env = pb.environment();
  env.put("PORT", String.valueOf(port));

  pb.directory(new File(dir));
  pb.redirectInput(Redirect.INHERIT);
  pb.redirectErrorStream();

  try {
    p = pb.start();
    pool.execute(new StdoutRunnable(new BufferedInputStream(p.getInputStream())));
    pool.execute(new StdoutRunnable(new BufferedInputStream(p.getErrorStream())));
  } catch (final Exception e) {
    logger.error(e.getMessage());
    throw new ProcessException(e.getMessage());
  } finally {
    pool.shutdown();
  }
}
 
Example 32
Project: btrbck   File: SshService.java   Source Code and License 6 votes vote down vote up
private ProcessBuilder processBuilder(SshTarget target,
        List<String> commands) {
    // construct command
    LinkedList<String> list = new LinkedList<String>();
    list.add("ssh");

    // add port
    if (target.getPort() != null) {
        list.add("-p");
        list.add(target.getPort().toString());
    }

    // add host
    list.add(target.getHost());

    // add commands
    list.addAll(commands);

    return new ProcessBuilder().redirectError(Redirect.INHERIT).command(
            list);
}
 
Example 33
Project: btrbck   File: BtrfsService.java   Source Code and License 6 votes vote down vote up
public void receive(Path destinationPath, Consumer<OutputStream> callback) {
    try {
        Process process = processBuilder("btrfs", "receive", "-e",
                destinationPath.toAbsolutePath().toString())
                .redirectOutput(Redirect.PIPE).start();
        callback.consume(process.getOutputStream());
        process.getOutputStream().close();
        int exitValue = process.waitFor();
        if (exitValue != 0) {
            throw new IOException("exit code: " + exitValue);
        }
    }
    catch (IOException | InterruptedException e) {
        throw new RuntimeException(
                "Error while receiving snapshot sub volume in "
                        + destinationPath, e);
    }
}
 
Example 34
Project: bazel   File: JavaSubprocessFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a {@link java.lang.ProcessBuilder.Redirect} appropriate for the parameters. If a file
 * redirected to exists, deletes the file before redirecting to it.
 */
private Redirect getRedirect(StreamAction action, File file) {
  switch (action) {
    case DISCARD:
      return Redirect.to(new File("/dev/null"));

    case REDIRECT:
      // We need to use Redirect.appendTo() here, because on older Linux kernels writes are
      // otherwise not atomic and might result in lost log messages:
      // https://lkml.org/lkml/2014/3/3/308
      if (file.exists()) {
        file.delete();
      }
      return Redirect.appendTo(file);

    case STREAM:
      return Redirect.PIPE;

    default:
      throw new IllegalStateException();
  }
}
 
Example 35
Project: KoPeMe   File: TestKoPeMeKiekerPremain.java   Source Code and License 6 votes vote down vote up
@Test
public void run() throws Exception {
	// TODO adjust for windows machines if needed
	String jarFileName = getFileInTarget("-agent.jar");
	String instractableMethod = "a";
	String agentInputArgs = new KoPeMeClassFileTransformaterDataForKieker(
			TestDataSingleton.Transformable.class.getName(),
			instractableMethod, 1).getCommand();
	ProcessBuilder pb = new ProcessBuilder(
			"java", // "-Xdebug",
					// "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044",
			"-cp", System.getProperty("java.class.path"),
			String.format("-javaagent:target/%s=%s", jarFileName,
					agentInputArgs),
			TestKoPeMeKiekerPremain.class.getName());
	pb.redirectError(Redirect.INHERIT);
	pb.redirectOutput(Redirect.INHERIT);
	Process start = pb.start();
	int ret = start.waitFor();
	assertEquals("the return value of the forked vm was not null", 0, ret);
}
 
Example 36
Project: KoPeMe   File: TestJavassistPremain.java   Source Code and License 6 votes vote down vote up
@Test
public void run() throws Exception {
	// TODO adjust for windows machines if needed
	String jarFileName = TestKoPeMeKiekerPremain.getFileInTarget("-javassist_agent.jar");
	String instractableMethod = "b";
	String agentInputArgs = TestKoPeMeClassFileTransformator.createTestData(instractableMethod, 3).toString();
	ProcessBuilder pb = new ProcessBuilder("java", "-cp", System.getProperty("java.class.path"),  
											String.format("-javaagent:target/%s=%s", jarFileName, agentInputArgs),
											TestJavassistPremain.class.getName());
	pb.redirectError(Redirect.INHERIT);
	pb.redirectOutput(Redirect.INHERIT);
	Process start = pb.start();
	int ret = start.waitFor();
	assertEquals("the return value of the forked vm was not null", 0, ret);
	try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PICKLED_PATH))){
		@SuppressWarnings("unchecked")
		Collection<TestJoinPointData> readObject = (Collection<TestJoinPointData>) ois.readObject();
		assertEquals(4, readObject.size());
	}
}
 
Example 37
Project: Singularity   File: SingularityExecutorTaskLogManager.java   Source Code and License 6 votes vote down vote up
private void copyLogTail() {
  if (configuration.getTailLogLinesToSave() <= 0) {
    return;
  }

  final Path tailOfLogPath = taskDefinition.getServiceFinishedTailLogPath();

  if (Files.exists(tailOfLogPath)) {
    log.debug("{} already existed, skipping tail", tailOfLogPath);
    return;
  }

  final List<String> cmd = ImmutableList.of(
      "tail",
      "-n",
      Integer.toString(configuration.getTailLogLinesToSave()),
      taskDefinition.getServiceLogOut());

  try {
    new SimpleProcessManager(log).runCommand(cmd, Redirect.to(tailOfLogPath.toFile()));
  } catch (Throwable t) {
    log.error("Failed saving tail of log {} to {}", taskDefinition.getServiceLogOut(), taskDefinition.getServiceFinishedTailLogPath(), t);
  }
}
 
Example 38
Project: gravel   File: VMTargetStarter.java   Source Code and License 6 votes vote down vote up
public Process startSecondJVM(Class<?> mainClassToStart) throws IOException {
	String separator = System.getProperty("file.separator");
	String classpath = System.getProperty("java.class.path");
	String path = System.getProperty("java.home") + separator + "bin"
			+ separator + "java";

	ProcessBuilder processBuilder = new ProcessBuilder(path, "-Xdebug",
			"-Xrunjdwp:transport=dt_socket,address=" + debugPort
					+ ",server=y,suspend=y", "-cp", classpath,
			mainClassToStart.getCanonicalName());
	processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
	final Process process = processBuilder.start();
	Thread closeChildThread = new Thread() {
		public void run() {
			process.destroy();
		}
	};
	Runtime.getRuntime().addShutdownHook(closeChildThread);
	return process;

}
 
Example 39
Project: amberdb   File: ExternalToolConverter.java   Source Code and License 6 votes vote down vote up
/**
 * Execute the command in a new operating system process.
 * @param cmd           the command along with the command line arguments to execute
 * @throws ExternalToolException if the command returned an exit code > 0
 */
protected void executeCmd(String... cmd) throws ExternalToolException {
    // Log command
    log.debug("Run command: {}", StringUtils.join(cmd, ' '));

    // Execute command
    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectError(Redirect.INHERIT).redirectOutput(Redirect.INHERIT);
    try {
        Process p = builder.start();
        p.waitFor();
        int exitVal = p.exitValue();
        if (exitVal > 0) {
            throw new ExternalToolException("Error in executeCmd", exitVal);
        }
    } catch (IOException | InterruptedException e) {
        throw new ExternalToolException("Error in executeCmd", e); 
    }
}
 
Example 40
Project: ndex-common   File: TestProcessBuilder.java   Source Code and License 6 votes vote down vote up
private ProcessBuilder createBelcProcessBuilder() {
	List<String> command = Lists.newArrayList();
	command.add(BELC_SH);
	command.add("-f " +this.belFileName);
	command.add("-k test_kam");
	command.add("-d Test KAM");
	ProcessBuilder pb = new ProcessBuilder(command);
	// set envrionment variables
	pb.environment().put("BELFRAMEWORK_HOME", "/opt/ndex/OpenBEL_Framework-3.0.0");
	pb.environment().put("BELCOMPILER_DIR", "/opt/ndex/OpenBEL_Framework-3.0.0");
	pb.directory(new File("/tmp/belc"));
	File log = new File("belc.log");
	pb.redirectErrorStream(true);
	pb.redirectOutput(Redirect.appendTo(log));
	
	
	return pb;
}