Example usage for java.lang ProcessBuilder redirectOutput

List of usage examples for java.lang ProcessBuilder redirectOutput

Introduction

In this page you can find the example usage for java.lang ProcessBuilder redirectOutput.

Prototype

public Redirect redirectOutput() 

Source Link

Document

Returns this process builder's standard output destination.

Usage

From source file:Main.java

public static void main(String[] args) {

    // create a new list of arguments for our process
    String[] list = { "notepad.exe", "test.txt" };

    // create the process builder
    ProcessBuilder pb = new ProcessBuilder(list);
    try {//from   w  w  w. ja v  a 2s .c  o m

        pb.start();
        System.out.println(pb.redirectOutput());
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:Test.java

public static void main(String[] args) throws Exception {
    File commands = new File("C:/Projects/ProcessCommands.txt");
    File output = new File("C:/Projects/ProcessLog.txt");
    File errors = new File("C:/Projects/ErrorLog.txt");

    ProcessBuilder pb = new ProcessBuilder("cmd");
    System.out.println(pb.redirectInput().toString());
    System.out.println(pb.redirectOutput().toString());
    System.out.println(pb.redirectError().toString());

    pb.redirectInput(commands);/*from  w w w.  ja  va 2s .  com*/
    pb.redirectError(errors);
    pb.redirectOutput(output);
    System.out.println(pb.redirectInput().toString());
    System.out.println(pb.redirectOutput().toString());
    System.out.println(pb.redirectError().toString());

    pb.start();
}

From source file:xbdd.webapp.resource.feature.PrintPDF.java

public void generatePDF(final List<String> commands) throws IOException {
    final ProcessBuilder probuilder = new ProcessBuilder(commands);
    probuilder.redirectError();//from   w w w.j a  v  a  2 s  .c o  m
    probuilder.redirectOutput();
    probuilder.redirectInput();
    final Process process = probuilder.start();
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }
    process.destroy();
}

From source file:com.kurento.kmf.repository.test.OneRecordingServerTest.java

protected void uploadFileWithCURL(String uploadURL, File fileToUpload)
        throws FileNotFoundException, IOException {

    log.info("Start uploading file with curl");
    long startTime = System.currentTimeMillis();

    ProcessBuilder builder = new ProcessBuilder("curl", "-i", "-F",
            "filedata=@" + fileToUpload.getAbsolutePath(), uploadURL);
    builder.redirectOutput();
    Process process = builder.start();
    try {/*from  ww w  .  jav  a  2s  . c o  m*/
        process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    long duration = System.currentTimeMillis() - startTime;
    log.info("Finished uploading content in " + (((double) duration) / 1000) + " seconds.");
}

From source file:org.kurento.repository.test.OneRecordingServerTest.java

protected void uploadFileWithCURL(String uploadURL, File fileToUpload)
        throws FileNotFoundException, IOException {

    log.debug("Start uploading file with curl");
    long startTime = System.currentTimeMillis();

    ProcessBuilder builder = new ProcessBuilder("curl", "-i", "-F",
            "filedata=@" + fileToUpload.getAbsolutePath(), uploadURL);
    builder.redirectOutput();
    Process process = builder.start();
    try {/*from  w ww  .  j  a  va2  s.  c  o  m*/
        process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    long duration = System.currentTimeMillis() - startTime;
    log.debug("Finished uploading content in " + (double) duration / 1000 + " seconds.");
}

From source file:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public String startAppForSimultion(String appId, String runtimeOptions, Map simulationContext) {

    String simulationId = simulationContext.get("simulationId").toString();

    appId = appId.trim();/*from  w  w w. j  a  va  2  s. co m*/
    String instanceId = appId + "-" + new Date().getTime();
    // get execution path
    AppInfo appInfo = apps.get(appId);
    if (appInfo == null) {
        throw new RuntimeException("App not found: " + appId);
    }

    // are multiple allowed? if not check to see if it is already running,
    // if it is then fail
    if (!appInfo.isMultiple_instances() && listRunningApps(appId).size() > 0) {
        throw new RuntimeException("App is already running and multiple instances are not allowed: " + appId);
    }

    // build options
    // might need a standard method for replacing things like SIMULATION_ID
    // in the input/output options
    /*String optionsString = appInfo.getOptions();
    if (simulationId != null) {
       if (optionsString.contains("SIMULATION_ID")) {
    optionsString = optionsString.replace("SIMULATION_ID",
          simulationId);
       }
       if (runtimeOptions.contains("SIMULATION_ID")) {
    runtimeOptions = runtimeOptions.replace("SIMULATION_ID",
          simulationId);
       }
    }*/

    File appDirectory = new File(getAppConfigDirectory().getAbsolutePath() + File.separator + appId);

    Process process = null;
    // something like
    if (AppType.PYTHON.equals(appInfo.getType())) {
        List<String> commands = new ArrayList<String>();
        commands.add("python");
        commands.add(appInfo.getExecution_path());

        //Check if static args contain any replacement values
        List<String> staticArgsList = appInfo.getOptions();
        for (String staticArg : staticArgsList) {
            if (staticArg != null) {
                if (staticArg.contains("(")) {
                    String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")");
                    for (String args : replaceArgs) {
                        staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString());
                    }
                }
                commands.add(staticArg);
            }
        }

        if (runtimeOptions != null && !runtimeOptions.isEmpty()) {
            String runTimeString = runtimeOptions.replace(" ", "").replace("\n", "");
            commands.add(runTimeString);
        }

        ProcessBuilder processAppBuilder = new ProcessBuilder(commands);
        processAppBuilder.redirectErrorStream(true);
        processAppBuilder.redirectOutput();
        processAppBuilder.directory(appDirectory);
        logManager.log(new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                "Starting app with command " + String.join(" ", commands), LogLevel.DEBUG,
                ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId);
        try {
            process = processAppBuilder.start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // fncsBridgeBuilder.redirectErrorStream(true);
        // fncsBridgeBuilder.redirectOutput(new
        // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log"));
        // fncsBridgeProcess = fncsBridgeBuilder.start();
        // // Watch the process
        // watch(fncsBridgeProcess, "FNCS GOSS Bridge");
        // during watch, send stderr/out to logmanager

    } else if (AppType.JAVA.equals(appInfo.getType())) {
        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // fncsBridgeBuilder.redirectErrorStream(true);
        // fncsBridgeBuilder.redirectOutput(new
        // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log"));
        // fncsBridgeProcess = fncsBridgeBuilder.start();
        // // Watch the process
        // watch(fncsBridgeProcess, "FNCS GOSS Bridge");
        // during watch, send stderr/out to logmanager

    } else if (AppType.WEB.equals(appInfo.getType())) {
        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // fncsBridgeBuilder.redirectErrorStream(true);
        // fncsBridgeBuilder.redirectOutput(new
        // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log"));
        // fncsBridgeProcess = fncsBridgeBuilder.start();
        // // Watch the process
        // watch(fncsBridgeProcess, "FNCS GOSS Bridge");
        // during watch, send stderr/out to logmanager

    } else {
        throw new RuntimeException("Type not recognized " + appInfo.getType());
    }

    // create appinstance object
    AppInstance appInstance = new AppInstance(instanceId, appInfo, runtimeOptions, simulationId, simulationId,
            process);
    appInstance.setApp_info(appInfo);
    watch(appInstance);
    // add to app instances map
    appInstances.put(instanceId, appInstance);

    return instanceId;
}

From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java

@Override
public String startServiceForSimultion(String serviceId, String runtimeOptions,
        Map<String, Object> simulationContext) {

    String instanceId = serviceId + "-" + new Date().getTime();
    // get execution path
    ServiceInfo serviceInfo = services.get(serviceId);
    if (serviceInfo == null) {
        //TODO: publish error on status topic
        throw new RuntimeException("Service not found: " + serviceId);
    }/*from   w w w . j av a 2s . com*/

    // are multiple allowed? if not check to see if it is already running, if it is then fail
    if (!serviceInfo.isMultiple_instances() && listRunningServices(serviceId).size() > 0) {
        throw new RuntimeException(
                "Service is already running and multiple instances are not allowed: " + serviceId);
    }

    File serviceDirectory = new File(
            getServiceConfigDirectory().getAbsolutePath() + File.separator + serviceId);

    ProcessBuilder processServiceBuilder = new ProcessBuilder();
    Process process = null;
    List<String> commands = new ArrayList<String>();
    Map<String, String> envVars = processServiceBuilder.environment();

    //set environment variables
    List<EnvironmentVariable> envVarList = serviceInfo.getEnvironmentVariables();
    for (EnvironmentVariable envVar : envVarList) {
        String value = envVar.getEnvValue();
        //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null
        if (simulationContext != null) {
            if (value.contains("(")) {
                String[] replaceValue = StringUtils.substringsBetween(envVar.getEnvValue(), "(", ")");
                for (String args : replaceValue) {
                    value = value.replace("(" + args + ")", simulationContext.get(args).toString());
                }
            }
        }
        envVars.put(envVar.getEnvName(), value);
    }

    //add executation command           
    commands.add(serviceInfo.getExecution_path());

    //Check if static args contain any replacement values
    List<String> staticArgsList = serviceInfo.getStatic_args();
    for (String staticArg : staticArgsList) {
        if (staticArg != null) {
            //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null
            if (simulationContext != null) {
                if (staticArg.contains("(")) {
                    String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")");
                    for (String args : replaceArgs) {
                        staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString());
                    }
                }
            }
            commands.add(staticArg);
        }
    }

    if (runtimeOptions != null) {
        commands.add(runtimeOptions);
    }

    try {
        if (serviceInfo.getType().equals(ServiceType.PYTHON)) {

            commands.add(0, "python");
            processServiceBuilder.command(commands);
            if (serviceDirectory.exists())
                processServiceBuilder.directory(serviceDirectory);
            processServiceBuilder.redirectErrorStream(true);
            processServiceBuilder.redirectOutput();

            logManager.log(
                    new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                            "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG,
                            ProcessStatus.RUNNING, true),
                    GridAppsDConstants.topic_simulationLog + simulationId);
            process = processServiceBuilder.start();

        } else if (serviceInfo.getType().equals(ServiceType.EXE)) {

            processServiceBuilder.command(commands);
            if (serviceDirectory.exists())
                processServiceBuilder.directory(serviceDirectory);
            processServiceBuilder.redirectErrorStream(true);
            processServiceBuilder.redirectOutput();
            logManager.log(
                    new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                            "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG,
                            ProcessStatus.RUNNING, true),
                    GridAppsDConstants.topic_simulationLog + simulationId);
            process = processServiceBuilder.start();

        } else if (serviceInfo.getType().equals(ServiceType.JAVA)) {

            commands.add(0, "java -jar");
            processServiceBuilder.command(commands);
            if (serviceDirectory.exists())
                processServiceBuilder.directory(serviceDirectory);
            processServiceBuilder.redirectErrorStream(true);
            processServiceBuilder.redirectOutput();
            logManager.log(
                    new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                            "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG,
                            ProcessStatus.RUNNING, true),
                    GridAppsDConstants.topic_simulationLog + simulationId);
            process = processServiceBuilder.start();

        } else if (serviceInfo.getType().equals(ServiceType.WEB)) {

        } else {
            throw new RuntimeException("Type not recognized " + serviceInfo.getType());
        }
    } catch (IOException e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String sStackTrace = sw.toString(); // stack trace as a string
        System.out.println(sStackTrace);

        StringBuilder commandString = new StringBuilder();
        for (String s : commands) {
            commandString.append(s);
            commandString.append(" ");
        }

        logManager.log(
                new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                        "Error running command + " + commandString, LogLevel.ERROR, ProcessStatus.ERROR, true),
                GridAppsDConstants.topic_simulationLog + simulationId);
        logManager.log(
                new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), sStackTrace,
                        LogLevel.ERROR, ProcessStatus.ERROR, true),
                GridAppsDConstants.topic_simulationLog + simulationId);
    }

    //create serviceinstance object
    ServiceInstance serviceInstance = new ServiceInstance(instanceId, serviceInfo, runtimeOptions, simulationId,
            process);
    serviceInstance.setService_info(serviceInfo);

    //add to service instances map
    serviceInstances.put(instanceId, serviceInstance);

    return instanceId;

}