Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

To view the source code for java.lang ProcessBuilder command.

Click Source Link

Usage

From source file:org.apache.nifi.processors.standard.ExecuteStreamCommand.java

@Override
public void onTrigger(ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile inputFlowFile = session.get();
    if (null == inputFlowFile) {
        return;//from  ww w . jav a2  s .  c  o m
    }

    final ArrayList<String> args = new ArrayList<>();
    final boolean putToAttribute = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).isSet();
    final Integer attributeSize = context.getProperty(PUT_ATTRIBUTE_MAX_LENGTH).asInteger();
    final String attributeName = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).getValue();

    final String executeCommand = context.getProperty(EXECUTION_COMMAND)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    args.add(executeCommand);
    final String commandArguments = context.getProperty(EXECUTION_ARGUMENTS)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    final boolean ignoreStdin = Boolean.parseBoolean(context.getProperty(IGNORE_STDIN).getValue());
    if (!StringUtils.isBlank(commandArguments)) {
        for (String arg : ArgumentUtils.splitArgs(commandArguments,
                context.getProperty(ARG_DELIMITER).getValue().charAt(0))) {
            args.add(arg);
        }
    }
    final String workingDir = context.getProperty(WORKING_DIR).evaluateAttributeExpressions(inputFlowFile)
            .getValue();

    final ProcessBuilder builder = new ProcessBuilder();

    logger.debug("Executing and waiting for command {} with arguments {}",
            new Object[] { executeCommand, commandArguments });
    File dir = null;
    if (!StringUtils.isBlank(workingDir)) {
        dir = new File(workingDir);
        if (!dir.exists() && !dir.mkdirs()) {
            logger.warn("Failed to create working directory {}, using current working directory {}",
                    new Object[] { workingDir, System.getProperty("user.dir") });
        }
    }
    final Map<String, String> environment = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (entry.getKey().isDynamic()) {
            environment.put(entry.getKey().getName(), entry.getValue());
        }
    }
    builder.environment().putAll(environment);
    builder.command(args);
    builder.directory(dir);
    builder.redirectInput(Redirect.PIPE);
    builder.redirectOutput(Redirect.PIPE);
    final Process process;
    try {
        process = builder.start();
    } catch (IOException e) {
        logger.error("Could not create external process to run command", e);
        throw new ProcessException(e);
    }
    try (final OutputStream pos = process.getOutputStream();
            final InputStream pis = process.getInputStream();
            final InputStream pes = process.getErrorStream();
            final BufferedInputStream bis = new BufferedInputStream(pis);
            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pes))) {
        int exitCode = -1;
        final BufferedOutputStream bos = new BufferedOutputStream(pos);
        FlowFile outputFlowFile = putToAttribute ? inputFlowFile : session.create(inputFlowFile);

        ProcessStreamWriterCallback callback = new ProcessStreamWriterCallback(ignoreStdin, bos, bis, logger,
                attributeName, session, outputFlowFile, process, putToAttribute, attributeSize);
        session.read(inputFlowFile, callback);

        outputFlowFile = callback.outputFlowFile;
        if (putToAttribute) {
            outputFlowFile = session.putAttribute(outputFlowFile, attributeName,
                    new String(callback.outputBuffer, 0, callback.size));
        }

        exitCode = callback.exitCode;
        logger.debug("Execution complete for command: {}.  Exited with code: {}",
                new Object[] { executeCommand, exitCode });

        Map<String, String> attributes = new HashMap<>();

        final StringBuilder strBldr = new StringBuilder();
        try {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                strBldr.append(line).append("\n");
            }
        } catch (IOException e) {
            strBldr.append("Unknown...could not read Process's Std Error");
        }
        int length = strBldr.length() > 4000 ? 4000 : strBldr.length();
        attributes.put("execution.error", strBldr.substring(0, length));

        final Relationship outputFlowFileRelationship = putToAttribute ? ORIGINAL_RELATIONSHIP
                : OUTPUT_STREAM_RELATIONSHIP;
        if (exitCode == 0) {
            logger.info("Transferring flow file {} to {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName() });
        } else {
            logger.error("Transferring flow file {} to {}. Executable command {} ended in an error: {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName(), executeCommand,
                            strBldr.toString() });
        }

        attributes.put("execution.status", Integer.toString(exitCode));
        attributes.put("execution.command", executeCommand);
        attributes.put("execution.command.args", commandArguments);
        outputFlowFile = session.putAllAttributes(outputFlowFile, attributes);

        // This transfer will transfer the FlowFile that received the stream out put to it's destined relationship.
        // In the event the stream is put to the an attribute of the original, it will be transferred here.
        session.transfer(outputFlowFile, outputFlowFileRelationship);

        if (!putToAttribute) {
            logger.info("Transferring flow file {} to original", new Object[] { inputFlowFile });
            inputFlowFile = session.putAllAttributes(inputFlowFile, attributes);
            session.transfer(inputFlowFile, ORIGINAL_RELATIONSHIP);
        }

    } catch (final IOException ex) {
        // could not close Process related streams
        logger.warn("Problem terminating Process {}", new Object[] { process }, ex);
    } finally {
        process.destroy(); // last ditch effort to clean up that process.
    }
}

From source file:com.cisco.dvbu.ps.common.util.ScriptExecutor.java

public int executeCommand(String errorFile) {
    int exitValue = -99;

    String prefix = "ScriptExecutor::";
    String command = "";
    try {/* www .ja  v  a  2 s.  c  om*/
        // Print out the command and execution directory
        for (int i = 0; i < scriptArgsList.size(); i++) {
            command = command + scriptArgsList.get(i) + " ";
        }
        if (logger.isDebugEnabled()) {
            logger.debug(prefix + "-------------------------------------------------");
            logger.debug(prefix + "Command:  " + CommonUtils.maskCommand(command));
            logger.debug(prefix + "Exec Dir: " + execFromDir.toString());
        }

        // Build a new process to execute
        ProcessBuilder pb = new ProcessBuilder(scriptArgsList);

        // Setup the environment variables
        Map<String, String> env = pb.environment();
        for (int i = 0; i < envList.size(); i++) {
            String envVar = envList.get(i).toString();
            StringTokenizer st = new StringTokenizer(envVar, "=");
            if (st.hasMoreTokens()) {
                String property = st.nextToken();
                String propertyVal = "";
                try {
                    propertyVal = st.nextToken();
                } catch (Exception e) {
                }
                env.put(property, propertyVal);

                if (logger.isDebugEnabled()) {
                    logger.debug(prefix + "Env Var:  " + CommonUtils.maskCommand(envVar));
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug(prefix + "-------------------------------------------------");
        }

        // Setup up the execute from directory
        File execDir = new File(execFromDir);
        pb.directory(execDir);

        if (logger.isDebugEnabled()) {
            logger.debug("");
            logger.debug("ProcessBuilder::pb.command:                    "
                    + CommonUtils.maskCommand(pb.command().toString()));
            logger.debug("ProcessBuilder::pb.directory:                  " + pb.directory().toString());
            logger.debug("ProcessBuilder::pb.directory.getAbsolutePath:  " + pb.directory().getAbsolutePath());
            logger.debug("ProcessBuilder::pb.directory.getCanonicalPath: " + pb.directory().getCanonicalPath());
            logger.debug("");
            logger.debug("ProcessBuilder::pb.environment:                "
                    + CommonUtils.maskCommand(pb.environment().toString()));
            logger.debug(prefix + "-------------------------------------------------");
            logger.debug("");
        }

        // Execute the command
        Process process = pb.start();

        OutputStream stdOutput = process.getOutputStream();

        InputStream inputStream = process.getInputStream();
        InputStream errorStream = process.getErrorStream();

        inputStreamHandler = new ScriptStreamHandler(inputStream, stdOutput);
        errorStreamHandler = new ScriptStreamHandler(errorStream);

        inputStreamHandler.start();
        errorStreamHandler.start();

        exitValue = process.waitFor();

        if (logger.isDebugEnabled()) {
            logger.debug(prefix + "exitValue for process.waitFor is: " + exitValue);
        }

        if (exitValue > 0) {
            logger.error("Error executing command=" + CommonUtils.maskCommand(command));
            logger.error("Error=" + CommonUtils.maskCommand(getStandardErrorFromCommand().toString()));
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("Successfully executed command:\n" + CommonUtils.maskCommand(command));
                logger.info("Output:\n" + getStandardOutputFromCommand().toString());
            }
        }

    } catch (IOException e) {
        CompositeLogger.logException(e, e.getMessage());
        throw new CompositeException(e);
    } catch (InterruptedException e) {
        CompositeLogger.logException(e, e.getMessage());
        throw new CompositeException(e);
    }
    return exitValue;

}

From source file:com.codesourcery.internal.installer.InstallManager.java

@Override
public void launch(LaunchItem item) throws CoreException {
    IPath installLocation = getInstallDescription().getRootLocation();

    try {/*from  w  ww. j av  a  2  s . c  om*/
        String program;
        // Executable item
        if (item.getType() == LaunchItemType.EXECUTABLE) {
            IPath toRun = installLocation.append(item.getPath());
            if (!toRun.toFile().exists())
                Installer.fail(InstallMessages.Error_FileNotFound + toRun.toOSString());

            // Add paths to environment and launch.
            ProcessBuilder pb = new ProcessBuilder();
            String[] paths = installDescription.getEnvironmentPaths();

            if (paths != null) {
                Map<String, String> env = pb.environment();
                String pathKey = "PATH";
                String pathVar = env.get(pathKey);

                if (pathVar == null) {
                    pathVar = "";
                }

                for (String path : paths) {
                    IPath resolvedPath = installDescription.getRootLocation().append(path);
                    pathVar = resolvedPath.toString() + File.pathSeparatorChar + pathVar;
                }
                env.put(pathKey, pathVar);
            }

            program = toRun.toOSString();
            pb.command(program);
            pb.start();
        }
        // File item
        else if (item.getType() == LaunchItemType.FILE) {
            IPath toRun = installLocation.append(item.getPath());
            if (!toRun.toFile().exists())
                Installer.fail(InstallMessages.Error_FileNotFound + toRun.toOSString());

            program = "file://" + toRun.toOSString();
            Program.launch(program);
        }
        // HTML item
        else if (item.getType() == LaunchItemType.HTML) {
            program = item.getPath();
            Program.launch(program);
        } else {
            throw new NullPointerException(InstallMessages.Error_NoLaunchItemType);
        }
    } catch (Exception e) {
        Installer.fail(NLS.bind(InstallMessages.Error_LaunchFailed0, item.getPath()), e);
    }
    // SWT Program.launch() can throw an UnsatisfiedLinkError if it is
    // unable to launch the file.
    catch (UnsatisfiedLinkError e) {
        Installer.fail(NLS.bind(InstallMessages.Error_LaunchFailed0, item.getPath()), e);
    }
}

From source file:org.tinymediamanager.ui.MainWindow.java

public void closeTmmAndStart(ProcessBuilder pb) {
    int confirm = JOptionPane.YES_OPTION;
    // if there are some threads running, display exit confirmation
    if (TmmTaskManager.getInstance().poolRunning()) {
        confirm = JOptionPane.showOptionDialog(null, BUNDLE.getString("tmm.exit.runningtasks"),
                BUNDLE.getString("tmm.exit.confirmation"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, null, null); // $NON-NLS-1$
    }// ww w  .j a va 2 s .  c  om
    if (confirm == JOptionPane.YES_OPTION) {
        LOGGER.info("bye bye");
        try {
            Utils.trackEvent("shutdown");
            // send shutdown signal
            TmmTaskManager.getInstance().shutdown();
            // save unsaved settings
            Globals.settings.saveSettings();
            // hard kill
            TmmTaskManager.getInstance().shutdownNow();
            // close database connection
            TmmModuleManager.getInstance().shutDown();
        } catch (Exception ex) {
            LOGGER.warn("", ex);
        }
        dispose();

        // spawn our process
        if (pb != null) {
            try {
                LOGGER.info("Going to execute: " + pb.command());
                pb.start();
            } catch (IOException e) {
                LOGGER.error("Cannot spawn process:", e);
            }
        }

        System.exit(0); // calling the method is a must
    }
}

From source file:org.taverna.server.localworker.impl.WorkerCore.java

/**
 * Fire up the workflow. This causes a transition into the operating state.
 * //w ww  . j  av a2s  . com
 * @param executeWorkflowCommand
 *            The command to run to execute the workflow.
 * @param workflow
 *            The workflow document to execute.
 * @param workingDir
 *            What directory to use as the working directory.
 * @param inputBaclava
 *            The baclava file to use for inputs, or <tt>null</tt> to use
 *            the other <b>input*</b> arguments' values.
 * @param inputFiles
 *            A mapping of input names to files that supply them. Note that
 *            we assume that nothing mapped here will be mapped in
 *            <b>inputValues</b>.
 * @param inputValues
 *            A mapping of input names to values to supply to them. Note
 *            that we assume that nothing mapped here will be mapped in
 *            <b>inputFiles</b>.
 * @param outputBaclava
 *            What baclava file to write the output from the workflow into,
 *            or <tt>null</tt> to have it written into the <tt>out</tt>
 *            subdirectory.
 * @param token
 *            The name of the workflow run.
 * @throws IOException
 *             If any of quite a large number of things goes wrong.
 */
@Override
public void initWorker(String executeWorkflowCommand, String workflow, File workingDir, File inputBaclava,
        Map<String, File> inputFiles, Map<String, String> inputValues, File outputBaclava, File securityDir,
        char[] password, Map<String, String> environment, String token) throws IOException {
    ProcessBuilder pb = new ProcessBuilder();
    /*
     * WARNING! HERE THERE BE DRAGONS! BE CAREFUL HERE!
     * 
     * Work around _Maven_ bug with permissions in zip files! The executable
     * bit is stripped by Maven's handling of file permissions, and there's
     * no practical way to work around it without massively increasing the
     * pain in other ways. Only want this on Unix - Windows isn't affected
     * by this - so we use the file separator as a proxy for whether this is
     * a true POSIX system. Ugly! Ugly ugly ugly...
     * 
     * http://jira.codehaus.org/browse/MASSEMBLY-337 is relevant, but not
     * the whole story as we don't want to use a non-standard packaging
     * method as there's a real chance of it going wrong in an unexpected
     * way then. Other parts of the story are that the executable bit isn't
     * preserved when unpacking with the dependency plugin, and there's no
     * way to be sure that the servlet container will preserve the bit
     * either (as that's probably using a Java-based ZIP engine).
     */
    if (File.separatorChar == '/')
        pb.command().add("/bin/sh");
    pb.command().add(executeWorkflowCommand);

    // Enable verbose logging
    pb.command().add("-logfile");
    pb.command().add(new File(new File(workingDir, "logs"), "detail.log").getAbsolutePath());

    if (securityDir != null) {
        pb.command().add(CREDENTIAL_MANAGER_DIRECTORY);
        pb.command().add(securityDir.getAbsolutePath());
        out.println("security dir location: " + securityDir);
    }
    if (password != null) {
        pb.command().add(CREDENTIAL_MANAGER_PASSWORD);
        out.println("password of length " + password.length + " will be written to subprocess stdin");
    }

    // Add arguments denoting inputs
    if (inputBaclava != null) {
        pb.command().add("-inputdoc");
        pb.command().add(inputBaclava.getAbsolutePath());
        if (!inputBaclava.exists())
            throw new IOException("input baclava file doesn't exist");
    } else {
        for (Entry<String, File> port : inputFiles.entrySet()) {
            if (port.getValue() != null) {
                pb.command().add("-inputfile");
                pb.command().add(port.getKey());
                pb.command().add(port.getValue().getAbsolutePath());
                if (!port.getValue().exists())
                    throw new IOException("input file for port \"" + port + "\" doesn't exist");
            }
        }
        for (Entry<String, String> port : inputValues.entrySet()) {
            if (port.getValue() != null) {
                pb.command().add("-inputvalue");
                pb.command().add(port.getKey());
                pb.command().add(port.getValue());
            }
        }
    }

    // Add arguments denoting outputs
    if (outputBaclava != null) {
        pb.command().add("-outputdoc");
        pb.command().add(outputBaclava.getAbsolutePath());
        if (!outputBaclava.getParentFile().exists())
            throw new IOException("parent directory of output baclava file does not exist");
        if (outputBaclava.exists())
            throw new IOException("output baclava file exists");
    } else {
        File out = new File(workingDir, "out");
        if (!out.mkdir()) {
            throw new IOException("failed to make output directory \"out\"");
        }
        if (!out.delete()) {
            // Taverna needs the dir to *not* exist now
            throw new IOException("failed to delete output directory \"out\"");
        }
        pb.command().add("-outputdir");
        pb.command().add(out.getAbsolutePath());
    }

    // Add an argument holding the workflow
    File tmp = createTempFile("taverna", ".t2flow");
    Writer w = new OutputStreamWriter(new FileOutputStream(tmp), "UTF-8");
    try {
        w.write(workflow);
    } finally {
        w.close();
    }
    tmp.deleteOnExit();
    pb.command().add(tmp.getAbsolutePath());

    // Indicate what working directory to use
    pb.directory(workingDir);
    wd = workingDir;

    Map<String, String> env = pb.environment();

    // Merge any options we have had imposed on us from outside
    env.putAll(environment);

    // Patch the environment to deal with TAVUTILS-17
    assert env.get("PATH") != null;
    env.put("PATH", new File(System.getProperty("java.home"), "bin") + pathSeparator + env.get("PATH"));
    // Patch the environment to deal with TAVSERV-189
    env.put("RAVEN_APPHOME", workingDir.getCanonicalPath());
    // Patch the environment to deal with TAVSERV-224
    env.put("TAVERNA_RUN_ID", token);
    if (interactionHost != null) {
        env.put("INTERACTION_HOST", interactionHost);
        env.put("INTERACTION_PORT", interactionPort);
        env.put("INTERACTION_WEBDAV", interactionWebdavPath);
        env.put("INTERACTION_FEED", interactionFeedPath);
    }

    // Start the subprocess
    out.println("starting " + pb.command() + " in directory " + workingDir);
    subprocess = pb.start();
    if (subprocess == null)
        throw new IOException("unknown failure creating process");
    start = new Date();

    // Capture its stdout and stderr
    new AsyncCopy(subprocess.getInputStream(), stdout);
    new AsyncCopy(subprocess.getErrorStream(), stderr);
    if (password != null)
        new AsyncPrint(subprocess.getOutputStream(), password);
}

From source file:adalid.commons.velocity.Writer.java

private void executeFile(VelocityContext fileContext, File templatePropertiesFile) {
    Properties properties = mergeProperties(fileContext, templatePropertiesFile);
    String command = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_COMMAND));
    String directory = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_DIRECTORY));
    if (command != null) {
        StrTokenizer tokenizer = new StrTokenizer(command);
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(tokenizer.getTokenArray());
        if (directory != null) {
            File dir = new File(directory);
            if (dir.exists() && dir.isDirectory()) {
                if (dir.isAbsolute()) {
                    processBuilder.directory(dir);
                } else {
                    processBuilder.directory(dir.getAbsoluteFile());
                }//  www .  j ava 2 s. c  om
            }
        }
        try {
            Process process = processBuilder.start();
            int w = process.waitFor();
            int x = process.exitValue();
            logger.info(command + " = " + w + "," + x);
        } catch (IOException | InterruptedException ex) {
            error(ex);
        }
    }
}

From source file:org.apache.sling.maven.slingstart.run.LauncherCallable.java

private ProcessDescription start(final File jar) throws Exception {
    final ProcessDescription cfg = new ProcessDescription(this.configuration.getId(),
            this.configuration.getFolder());

    final ProcessBuilder builder = new ProcessBuilder();
    final List<String> args = new ArrayList<String>();

    args.add("java");
    add(args, this.configuration.getVmOpts());
    add(args, this.configuration.getVmDebugOpts(this.environment.getDebug()));

    args.add("-cp");
    args.add("bin");
    args.add(Main.class.getName());
    // first three arguments: jar, listener port, verbose
    args.add(jar.getPath());/*  w  w  w . ja  v  a  2  s. c om*/
    args.add(String.valueOf(cfg.getControlListener().getPort()));
    args.add("true");

    // from here on launchpad properties
    add(args, this.configuration.getOpts());

    final String contextPath = this.configuration.getContextPath();
    if (contextPath != null && contextPath.length() > 0 && !contextPath.equals("/")) {
        args.add("-r");
        args.add(contextPath);
    }

    if (this.configuration.getPort() != null) {
        args.add("-p");
        args.add(this.configuration.getPort());
    }

    if (this.configuration.getControlPort() != null) {
        args.add("-j");
        args.add(this.configuration.getControlPort());
    }
    if (this.configuration.getRunmode() != null && this.configuration.getRunmode().length() > 0) {
        args.add("-Dsling.run.modes=" + this.configuration.getRunmode());
    }
    if (!this.environment.isShutdownOnExit()) {
        args.add("start");
    }

    builder.command(args.toArray(new String[args.size()]));
    builder.directory(this.configuration.getFolder());
    builder.redirectErrorStream(true);
    builder.redirectOutput(Redirect.INHERIT);
    builder.redirectError(Redirect.INHERIT);

    logger.info("Starting Launchpad " + this.configuration.getId() + "...");
    logger.debug("Launchpad cmd: " + builder.command());
    logger.debug("Launchpad dir: " + builder.directory());

    try {
        cfg.setProcess(builder.start());
    } catch (final IOException e) {
        if (cfg.getProcess() != null) {
            cfg.getProcess().destroy();
            cfg.setProcess(null);
        }
        throw new Exception("Could not start the Launchpad", e);
    }

    return cfg;
}

From source file:org.apache.giraph.zk.ZooKeeperManager.java

/**
 * If this task has been selected, online a ZooKeeper server.  Otherwise,
 * wait until this task knows that the ZooKeeper servers have been onlined.
 *///w ww  . ja v  a 2s . c  o  m
public void onlineZooKeeperServers() {
    Integer taskId = zkServerPortMap.get(myHostname);
    if ((taskId != null) && (taskId.intValue() == taskPartition)) {
        File zkDirFile = new File(this.zkDir);
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("onlineZooKeeperServers: Trying to delete old " + "directory " + this.zkDir);
            }
            FileUtils.deleteDirectory(zkDirFile);
        } catch (IOException e) {
            LOG.warn("onlineZooKeeperServers: Failed to delete " + "directory " + this.zkDir, e);
        }
        generateZooKeeperConfigFile(new ArrayList<String>(zkServerPortMap.keySet()));
        ProcessBuilder processBuilder = new ProcessBuilder();
        List<String> commandList = Lists.newArrayList();
        String javaHome = System.getProperty("java.home");
        if (javaHome == null) {
            throw new IllegalArgumentException("onlineZooKeeperServers: java.home is not set!");
        }
        commandList.add(javaHome + "/bin/java");
        String zkJavaOptsString = GiraphConstants.ZOOKEEPER_JAVA_OPTS.get(conf);
        String[] zkJavaOptsArray = zkJavaOptsString.split(" ");
        if (zkJavaOptsArray != null) {
            commandList.addAll(Arrays.asList(zkJavaOptsArray));
        }
        commandList.add("-cp");
        Path fullJarPath = new Path(conf.get(GiraphConstants.ZOOKEEPER_JAR));
        commandList.add(fullJarPath.toString());
        commandList.add(QuorumPeerMain.class.getName());
        commandList.add(configFilePath);
        processBuilder.command(commandList);
        File execDirectory = new File(zkDir);
        processBuilder.directory(execDirectory);
        processBuilder.redirectErrorStream(true);
        if (LOG.isInfoEnabled()) {
            LOG.info("onlineZooKeeperServers: Attempting to " + "start ZooKeeper server with command "
                    + commandList + " in directory " + execDirectory.toString());
        }
        try {
            synchronized (this) {
                zkProcess = processBuilder.start();
                zkProcessCollector = new StreamCollector(zkProcess.getInputStream());
                zkProcessCollector.start();
            }
            Runnable runnable = new Runnable() {
                public void run() {
                    LOG.info("run: Shutdown hook started.");
                    synchronized (this) {
                        if (zkProcess != null) {
                            LOG.warn("onlineZooKeeperServers: " + "Forced a shutdown hook kill of the "
                                    + "ZooKeeper process.");
                            zkProcess.destroy();
                            int exitCode = -1;
                            try {
                                exitCode = zkProcess.waitFor();
                            } catch (InterruptedException e) {
                                LOG.warn("run: Couldn't get exit code.");
                            }
                            LOG.info("onlineZooKeeperServers: ZooKeeper process exited " + "with " + exitCode
                                    + " (note that 143 " + "typically means killed).");
                        }
                    }
                }
            };
            Runtime.getRuntime().addShutdownHook(new Thread(runnable));
            LOG.info("onlineZooKeeperServers: Shutdown hook added.");
        } catch (IOException e) {
            LOG.error("onlineZooKeeperServers: Failed to start " + "ZooKeeper process", e);
            throw new RuntimeException(e);
        }

        // Once the server is up and running, notify that this server is up
        // and running by dropping a ready stamp.
        int connectAttempts = 0;
        final int maxConnectAttempts = conf.getZookeeperConnectionAttempts();
        while (connectAttempts < maxConnectAttempts) {
            try {
                if (LOG.isInfoEnabled()) {
                    LOG.info("onlineZooKeeperServers: Connect attempt " + connectAttempts + " of "
                            + maxConnectAttempts + " max trying to connect to " + myHostname + ":" + zkBasePort
                            + " with poll msecs = " + pollMsecs);
                }
                InetSocketAddress zkServerAddress = new InetSocketAddress(myHostname, zkBasePort);
                Socket testServerSock = new Socket();
                testServerSock.connect(zkServerAddress, 5000);
                if (LOG.isInfoEnabled()) {
                    LOG.info("onlineZooKeeperServers: Connected to " + zkServerAddress + "!");
                }
                break;
            } catch (SocketTimeoutException e) {
                LOG.warn("onlineZooKeeperServers: Got " + "SocketTimeoutException", e);
            } catch (ConnectException e) {
                LOG.warn("onlineZooKeeperServers: Got " + "ConnectException", e);
            } catch (IOException e) {
                LOG.warn("onlineZooKeeperServers: Got " + "IOException", e);
            }

            ++connectAttempts;
            try {
                Thread.sleep(pollMsecs);
            } catch (InterruptedException e) {
                LOG.warn("onlineZooKeeperServers: Sleep of " + pollMsecs + " interrupted - " + e.getMessage());
            }
        }
        if (connectAttempts == maxConnectAttempts) {
            throw new IllegalStateException(
                    "onlineZooKeeperServers: Failed to connect in " + connectAttempts + " tries!");
        }
        Path myReadyPath = new Path(serverDirectory, myHostname + HOSTNAME_TASK_SEPARATOR + taskPartition);
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("onlineZooKeeperServers: Creating my filestamp " + myReadyPath);
            }
            fs.createNewFile(myReadyPath);
        } catch (IOException e) {
            LOG.error("onlineZooKeeperServers: Failed (maybe previous " + "task failed) to create filestamp "
                    + myReadyPath, e);
        }
    } else {
        List<String> foundList = new ArrayList<String>();
        int readyRetrievalAttempt = 0;
        while (true) {
            try {
                FileStatus[] fileStatusArray = fs.listStatus(serverDirectory);
                foundList.clear();
                if ((fileStatusArray != null) && (fileStatusArray.length > 0)) {
                    for (int i = 0; i < fileStatusArray.length; ++i) {
                        String[] hostnameTaskArray = fileStatusArray[i].getPath().getName()
                                .split(HOSTNAME_TASK_SEPARATOR);
                        if (hostnameTaskArray.length != 2) {
                            throw new RuntimeException("getZooKeeperServerList: Task 0 failed " + "to parse "
                                    + fileStatusArray[i].getPath().getName());
                        }
                        foundList.add(hostnameTaskArray[0]);
                    }
                    if (LOG.isInfoEnabled()) {
                        LOG.info("onlineZooKeeperServers: Got " + foundList + " " + foundList.size()
                                + " hosts from " + fileStatusArray.length + " ready servers when " + serverCount
                                + " required (polling period is " + pollMsecs + ") on attempt "
                                + readyRetrievalAttempt);
                    }
                    if (foundList.containsAll(zkServerPortMap.keySet())) {
                        break;
                    }
                } else {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("onlineZooKeeperSErvers: Empty " + "directory " + serverDirectory
                                + ", waiting " + pollMsecs + " msecs.");
                    }
                }
                Thread.sleep(pollMsecs);
                ++readyRetrievalAttempt;
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                LOG.warn("onlineZooKeeperServers: Strange interrupt from " + e.getMessage(), e);
            }
        }
    }
}

From source file:org.esa.s2tbx.dataio.s2.S2TileOpImage.java

protected void decompressTile(final File outputFile, int jp2TileX, int jp2TileY) throws IOException {
    final int tileIndex = tileLayout.numXTiles * jp2TileY + jp2TileX;

    ProcessBuilder builder;

    if (S2Config.OPJ_DECOMPRESSOR_EXE != null) {
        if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) {
            String inputFileName = Utils.GetIterativeShortPathName(imageFile.getPath());
            String outputFileName = outputFile.getPath();

            if (inputFileName.length() == 0) {
                inputFileName = imageFile.getPath();
            }/*from  w  ww.  j  av a 2  s.  c  om*/

            Guardian.assertTrue("Image file exists", new File(inputFileName).exists());

            builder = new ProcessBuilder(S2Config.OPJ_DECOMPRESSOR_EXE, "-i", inputFileName, "-o",
                    outputFileName, "-r", getLevel() + "", "-t", tileIndex + "");
        } else {
            SystemUtils.LOG.fine("Writing to " + outputFile.getPath());

            Guardian.assertTrue("Image file exists", imageFile.exists());

            builder = new ProcessBuilder(S2Config.OPJ_DECOMPRESSOR_EXE, "-i", imageFile.getPath(), "-o",
                    outputFile.getPath(), "-r", getLevel() + "", "-t", tileIndex + "");
        }
    } else {
        throw new UnexpectedException("OpenJpeg decompressor is not set");
    }

    builder = builder.directory(cacheDir);

    try {
        builder.redirectErrorStream(true);
        CommandOutput result = OpenJpegUtils.runProcess(builder);

        final int exitCode = result.getErrorCode();
        if (exitCode != 0) {
            SystemUtils.LOG.severe(String.format(
                    "Failed to uncompress tile: %s, exitCode = %d, command = [%s], command stdoutput = [%s], command stderr = [%s]",
                    imageFile.getPath(), exitCode, builder.command().toString(), result.getTextOutput(),
                    result.getErrorOutput()));
        }
    } catch (InterruptedException e) {
        SystemUtils.LOG.severe("Process was interrupted, InterruptedException: " + e.getMessage());
    }
}

From source file:com.paniclauncher.data.Settings.java

public void runUpdate(String currentPath, String temporaryUpdatePath) {
    List<String> arguments = new ArrayList<String>();

    String path = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    if (Utils.isWindows()) {
        path += "w";
    }//w  ww  .ja  v a  2s.co m
    arguments.add(path);
    arguments.add("-cp");
    arguments.add(temporaryUpdatePath);
    arguments.add("com.paniclauncher.Update");
    arguments.add(currentPath);
    arguments.add(temporaryUpdatePath);

    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command(arguments);

    log("Running launcher update with command " + arguments);

    try {
        processBuilder.start();
    } catch (IOException e) {
        this.console.logStackTrace(e);
    }

    System.exit(0);
}