org.zeroturnaround.exec.stream.slf4j.Slf4jStream Java Examples

The following examples show how to use org.zeroturnaround.exec.stream.slf4j.Slf4jStream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProjectCommandExecutor.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
ProcessExecutor processExecutor(String[] commands, String workingDir) {
	String[] commandsToRun = commands;
	String lastArg = String.join(" ", commands);
	if (Arrays.stream(OS_OPERATORS).anyMatch(lastArg::contains)) {
		commandsToRun = commandToExecute(lastArg);
	}
	log.info("Will run the command [{}]", Arrays.toString(commandsToRun));
	return new ProcessExecutor().command(commandsToRun).destroyOnExit()
			.readOutput(true)
			// releaser.commands logger should be configured to redirect
			// only to a file (with additivity=false). ideally the root logger should
			// append to same file on top of whatever root appender, so that file
			// contains the most output
			.redirectOutputAlsoTo(Slf4jStream.of("releaser.commands").asInfo())
			.redirectErrorAlsoTo(Slf4jStream.of("releaser.commands").asWarn())
			.directory(new File(workingDir));
}
 
Example #2
Source File: DynamicInstrumentationLoader.java    From invesdwin-instrument with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void loadAgent(final File tempAgentJar, final String pid) throws Exception {
    if (DynamicInstrumentationReflections.isBeforeJava9()) {
        DynamicInstrumentationLoadAgentMain.loadAgent(pid, tempAgentJar.getAbsolutePath());
    } else {
        //-Djdk.attach.allowAttachSelf https://www.bountysource.com/issues/45231289-self-attach-fails-on-jdk9
        //workaround this limitation by attaching from a new process
        final File loadAgentJar = createTempJar(DynamicInstrumentationLoadAgentMain.class, false,
                de.invesdwin.instrument.internal.DummyAttachProvider.class);
        final String javaExecutable = getJavaHome() + File.separator + "bin" + File.separator + "java";
        final List<String> command = new ArrayList<String>();
        command.add(javaExecutable);
        command.add("-classpath");
        command.add(loadAgentJar.getAbsolutePath()); //tools.jar not needed since java9
        command.add(DynamicInstrumentationLoadAgentMain.class.getName());
        command.add(pid);
        command.add(tempAgentJar.getAbsolutePath());
        new ProcessExecutor().command(command)
                .destroyOnExit()
                .exitValueNormal()
                .redirectOutput(Slf4jStream.of(DynamicInstrumentationLoader.class).asInfo())
                .redirectError(Slf4jStream.of(DynamicInstrumentationLoader.class).asWarn())
                .execute();
    }
}
 
Example #3
Source File: ProcessExecutorMainTest.java    From zt-exec with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaVersionLogInfoAndOutputFuture() throws Exception {
  // Just expect no errors - don't check the log file itself
  ProcessResult result = new ProcessExecutor().command("java", "-version").redirectOutput(Slf4jStream.of("testJavaVersionLogInfoAndOutputFuture").asInfo()).readOutput(true).start().getFuture().get();
  String str = result.outputUTF8();
  Assert.assertFalse(StringUtils.isEmpty(str));
}
 
Example #4
Source File: MitmproxyJava.java    From mitmproxy-java with Apache License 2.0 5 votes vote down vote up
public MitmproxyJava start() throws IOException, TimeoutException {
    log.info("Starting mitmproxy on port {}", proxyPort);

    server = new MitmproxyServer(new InetSocketAddress(LOCALHOST_IP, WEBSOCKET_PORT), messageInterceptor);
    server.start();

    // python script file is zipped inside our jar. extract it into a temporary file.
    String pythonScriptPath = extractPythonScriptToFile();

    final List<String> mitmproxyStartParams = new ArrayList<>();
    mitmproxyStartParams.add(mitmproxyPath);
    mitmproxyStartParams.add("--anticache");
    mitmproxyStartParams.add("-p");
    mitmproxyStartParams.add(String.valueOf(proxyPort));
    mitmproxyStartParams.add("-s");
    mitmproxyStartParams.add(pythonScriptPath);

    // adding params if needed for mitmproxy
    if (isNotEmpty(this.extraMitmdumpParams)) {
        mitmproxyStartParams.addAll(this.extraMitmdumpParams);
    }

    mitmproxyProcess = new ProcessExecutor()
            .command(mitmproxyStartParams)
            .redirectOutput(Slf4jStream.ofCaller().asInfo())
            .destroyOnExit()
            .start()
            .getFuture();

    waitForPortToBeInUse(proxyPort);
    log.info("Mitmproxy started on port {}", proxyPort);
    return this;
}
 
Example #5
Source File: ProcessExecutorMainTest.java    From zt-exec with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaVersionLogInfoAndOutput() throws Exception {
  // Just expect no errors - don't check the log file itself
  ProcessResult result = new ProcessExecutor().command("java", "-version").redirectOutput(Slf4jStream.of("testJavaVersionLogInfoAndOutput").asInfo()).readOutput(true).execute();
  String str = result.outputUTF8();
  Assert.assertFalse(StringUtils.isEmpty(str));
}
 
Example #6
Source File: ProcessExecutorLoggerTest.java    From zt-exec with Apache License 2.0 5 votes vote down vote up
private void testSlf4jLoggerName(String fullName, Slf4jStream stream) {
  ProcessExecutor executor = new ProcessExecutor();
  executor.redirectOutput(stream.asInfo());
  PumpStreamHandler pumps = executor.pumps();
  OutputStream out = pumps.getOut();
  Assert.assertTrue("Slf4jInfoOutputStream expected", out instanceof Slf4jInfoOutputStream);
  Assert.assertEquals(fullName, ((Slf4jInfoOutputStream) out).getLogger().getName());
}
 
Example #7
Source File: ReadmeExamples.java    From zt-exec with Apache License 2.0 5 votes vote down vote up
String pumpErrorToLoggerAndGetOutput() throws Exception {
  String output = new ProcessExecutor().command("java", "-version")
      .redirectError(Slf4jStream.of(getClass()).asInfo())
      .readOutput(true).execute()
      .outputUTF8();
  return output;
}
 
Example #8
Source File: PostgresqlBackupProcessor.java    From gocd with Apache License 2.0 5 votes vote down vote up
ProcessExecutor createProcessExecutor(File targetDir, DbProperties dbProperties) {
    Properties connectionProperties = dbProperties.connectionProperties();
    Properties pgProperties = Driver.parseURL(dbProperties.url(), connectionProperties);

    ArrayList<String> argv = new ArrayList<>();
    LinkedHashMap<String, String> env = new LinkedHashMap<>();
    if (isNotBlank(dbProperties.password())) {
        env.put("PGPASSWORD", dbProperties.password());
    }

    // override with any user specified environment
    env.putAll(dbProperties.extraBackupEnv());

    String dbName = pgProperties.getProperty("PGDBNAME");
    argv.add("pg_dump");
    argv.add("--no-password");
    argv.add("--host=" + pgProperties.getProperty("PGHOST"));
    argv.add("--port=" + pgProperties.getProperty("PGPORT"));
    if (isNotBlank(dbProperties.user())) {
        argv.add("--username=" + dbProperties.user());
    }
    argv.add(pgProperties.getProperty("PGDBNAME"));
    // append any user specified args for pg_dump
    if (isNotBlank(dbProperties.extraBackupCommandArgs())) {
        Collections.addAll(argv, Commandline.translateCommandline(dbProperties.extraBackupCommandArgs()));
    }
    argv.add("--file=" + new File(targetDir, "db." + dbName).toString());
    ProcessExecutor processExecutor = new ProcessExecutor();
    processExecutor.redirectOutputAlsoTo(Slf4jStream.of(getClass()).asDebug());
    processExecutor.redirectErrorAlsoTo(Slf4jStream.of(getClass()).asDebug());
    processExecutor.environment(env);
    processExecutor.command(argv);
    return processExecutor;
}
 
Example #9
Source File: MySQLBackupProcessor.java    From gocd with Apache License 2.0 5 votes vote down vote up
private ProcessExecutor createProcessExecutor(File targetDir, DbProperties dbProperties) {
    ConnectionUrl connectionUrlInstance = ConnectionUrl.getConnectionUrlInstance(dbProperties.url(), dbProperties.connectionProperties());

    LinkedHashMap<String, String> env = new LinkedHashMap<>();
    if (isNotBlank(dbProperties.password())) {
        env.put("MYSQL_PWD", dbProperties.password());
    }
    // override with any user specified environment
    env.putAll(dbProperties.extraBackupEnv());

    ArrayList<String> argv = new ArrayList<>();
    argv.add("mysqldump");


    String dbName = connectionUrlInstance.getDatabase();
    HostInfo mainHost = connectionUrlInstance.getMainHost();

    if (mainHost != null) {
        argv.add("--host=" + mainHost.getHost());
        argv.add("--port=" + mainHost.getPort());
    }
    if (isNotBlank(dbProperties.user())) {
        argv.add("--user=" + dbProperties.user());
    }

    // append any user specified args for mysqldump
    if (isNotBlank(dbProperties.extraBackupCommandArgs())) {
        Collections.addAll(argv, Commandline.translateCommandline(dbProperties.extraBackupCommandArgs()));
    }

    argv.add("--result-file=" + new File(targetDir, "db." + dbName).toString());
    argv.add(connectionUrlInstance.getDatabase());

    ProcessExecutor processExecutor = new ProcessExecutor();
    processExecutor.redirectOutputAlsoTo(Slf4jStream.of(getClass()).asDebug());
    processExecutor.redirectErrorAlsoTo(Slf4jStream.of(getClass()).asDebug());
    processExecutor.environment(env);
    processExecutor.command(argv);
    return processExecutor;
}
 
Example #10
Source File: ExternalProcess.java    From sputnik with Apache License 2.0 5 votes vote down vote up
public String executeCommand(String... args) {
    try {
        log.debug("Executing command " + Arrays.asList(args));
        return executor().command(args)
                .timeout(60, TimeUnit.SECONDS)
                .redirectError(Slf4jStream.of(getClass()).asInfo())
                .readOutput(true).execute()
                .outputUTF8();
    } catch (Exception e) {
        log.warn("Exception while calling command " + Arrays.asList(args) + ": " + e);
        throw new ExternalProcessException(e);
    }
}
 
Example #11
Source File: RabbitMqCommand.java    From embedded-rabbitmq with Apache License 2.0 5 votes vote down vote up
@Override
public StartedProcess call() throws RabbitMqCommandException {

  List<String> fullCommand = new ArrayList<>(arguments);
  fullCommand.add(0, executableFile.toString());

  Slf4jStream loggingStream = Slf4jStream.of(processOutputLogger);
  LoggingProcessListener loggingListener = new LoggingProcessListener(processOutputLogger);

  ProcessExecutor processExecutor = processExecutorFactory.createInstance()
      .environment(envVars)
      .directory(appFolder)
      .command(fullCommand)
      .destroyOnExit()
      .addListener(loggingListener)               // Logs process events (like start, stop...)
      .addListener(eventsListener)                // Notifies asynchronously of process events (start/finish/stop)
      .redirectError(loggingStream.as(stdErrLogLevel))     // Logging for output made to STDERR
      .redirectOutput(loggingStream.as(stdOutLogLevel))     // Logging for output made to STDOUT
      .redirectOutputAlsoTo(outputStream)         // Pipe stdout to this stream for the application to process
      .redirectErrorAlsoTo(errorOutputStream)     // Pipe stderr to this stream for the application to process
      .readOutput(storeOutput);                   // Store the output in the ProcessResult as well.

  try {
    return processExecutor.start();
  } catch (IOException e) {
    throw new RabbitMqCommandException("Failed to execute: " + StringUtils.join(fullCommand, " "), e);
  }
}
 
Example #12
Source File: ErlangShell.java    From embedded-rabbitmq with Apache License 2.0 5 votes vote down vote up
/**
 * @return a String representing the Erlang version, such as {@code "18.2.1"}
 * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly.
 */
public String getErlangVersion() throws ErlangShellException {
  String erlangShell = UNIX_ERL_COMMAND;

  Logger processOutputLogger = LoggerFactory.getLogger(
      String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell));

  Slf4jStream stream = Slf4jStream.of(processOutputLogger);

  final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance()
      .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().")
      .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS)
      .redirectError(stream.as(Level.WARN))
      .destroyOnExit()
      .readOutput(true);

  try {
    ProcessResult processResult = processExecutor.execute();
    int exitValue = processResult.getExitValue();
    if (exitValue == 0) {
      return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1"
    } else {
      throw new ErlangShellException("Erlang exited with status " + exitValue);
    }
  } catch (IOException | InterruptedException | TimeoutException e) {
    throw new ErlangShellException("Exception executing Erlang shell command", e);
  }
}
 
Example #13
Source File: ReadmeExamples.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
void pumpOutputToLogger() throws Exception {
  new ProcessExecutor().command("java", "-version")
  .redirectOutput(Slf4jStream.of(LoggerFactory.getLogger(getClass().getName() + ".MyProcess")).asInfo()).execute();
}
 
Example #14
Source File: ReadmeExamples.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
void pumpOutputToLoggerShorter() throws Exception {
  new ProcessExecutor().command("java", "-version")
  .redirectOutput(Slf4jStream.of("MyProcess").asInfo()).execute();
}
 
Example #15
Source File: ReadmeExamples.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
void pumpOutputToLoggerOfCaller() throws Exception {
  new ProcessExecutor().command("java", "-version")
  .redirectOutput(Slf4jStream.ofCaller().asInfo()).execute();
}
 
Example #16
Source File: ReadmeExamples.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
String pumpOutputToLoggerAndGetOutput() throws Exception {
  String output = new ProcessExecutor().command("java", "-version")
      .redirectOutput(Slf4jStream.of(getClass()).asInfo())
      .readOutput(true).execute().outputUTF8();
  return output;
}
 
Example #17
Source File: ProcessExecutorLoggerTest.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
@Test
public void testFullName() throws Exception {
  String fullName = "my.full.Logger";
  testSlf4jLoggerName(fullName, Slf4jStream.of(fullName));
}
 
Example #18
Source File: ProcessExecutorLoggerTest.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
@Test
public void testShortName() throws Exception {
  String shortName = "MyLogger";
  String fullName = getClass().getName() + "." + shortName;
  testSlf4jLoggerName(fullName, Slf4jStream.of(shortName));
}
 
Example #19
Source File: ProcessExecutorLoggerTest.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
@Test
public void testClassNameWithShortName() throws Exception {
  String shortName = "MyLogger";
  String fullName = getClass().getName() + "." + shortName;
  testSlf4jLoggerName(fullName, Slf4jStream.of(getClass(), shortName));
}
 
Example #20
Source File: ProcessExecutorLoggerTest.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
@Test
public void testMyClassName() throws Exception {
  String fullName = getClass().getName();
  testSlf4jLoggerName(fullName, Slf4jStream.ofCaller());
}
 
Example #21
Source File: ProcessExecutorMainTest.java    From zt-exec with Apache License 2.0 4 votes vote down vote up
@Test
public void testJavaVersionLogInfo() throws Exception {
  // Just expect no errors - don't check the log file itself
  new ProcessExecutor().command("java", "-version").redirectOutput(Slf4jStream.of("testJavaVersionLogInfo").asInfo()).execute();
}
 
Example #22
Source File: Downloader.java    From nju-lib-downloader with GNU General Public License v3.0 4 votes vote down vote up
public void mergePDF(File inputFileArray[], int start, int end, File outputFile) throws IOException, InterruptedException {
        //获取输入文件列表
        StringBuffer inputPDFList = new StringBuffer();

        for (int i = start; i < end; i++) {
            File file = inputFileArray[i];
            inputPDFList.append(parsePathWithWhiteSpace(file.getAbsolutePath()));
            inputPDFList.append(" ");
        }
/*        for (File file : inputFileArray) {
            if (file.getName().endsWith(".pdf")) {
*//*                inputPDFList.append(file.toPath().getRoot());

                Iterator<Path>pathIterator=file.toPath().iterator();
                String firstPath=pathIterator.next().toString();
                if(firstPath!=null){
                    inputPDFList.append(firstPath);
                }
                while(pathIterator.hasNext()){
                    inputPDFList.append(System.getProperty("file.separator"));
                    inputPDFList.append(parsePathWithWhiteSpace(pathIterator.next().toString()));
                }*//*
                inputPDFList.append(parsePathWithWhiteSpace(file.getAbsolutePath()));
                inputPDFList.append(" ");
            }
        }*/
        // File outputFile = path.resolve(book.getId() +"-"+partID+ ".pdf").toFile();
        String command = (isWindows ? "gswin64c" : "gs") + " -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=\"" + outputFile.getPath() + "\" " + inputPDFList;

        try {
            if (isWindows) {
                new ProcessExecutor().command(command.split(" "))
                        .redirectOutput(Slf4jStream.of(getClass()).asInfo())
                        .readOutput(true).execute().outputUTF8();
            } else {
                File bashFile = path.resolve(book.getId() + (isWindows ? ".bat" : ".sh")).toFile();
                FileWriter fileWriter = new FileWriter(bashFile);
                fileWriter.write(command);
                fileWriter.close();
                new ProcessExecutor().command("bash", parsePathWithWhiteSpace(bashFile.getName()))
                        .redirectOutput(Slf4jStream.of(getClass()).asInfo())
                        .readOutput(true).execute().outputUTF8();
                bashFile.delete();
            }
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }