Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

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

Click Source Link

Usage

From source file:org.apache.oodt.cas.workflow.misc.WingsTask.java

public void run(Metadata metadata, WorkflowTaskConfiguration config) {
    Properties props = config.getProperties();
    // Component Info
    String compid = props.getProperty("COMPONENT_ID");
    String tname = props.getProperty("TASKNAME");
    String jobid = props.getProperty("JOBID");
    String argstring = props.getProperty("ARGUMENT");
    ArrayList<String> inputs = fetchFromProps(props, "INPUT");
    ArrayList<String> outputs = fetchFromProps(props, "OUTPUT");

    // Following paths should be Shared across the cluster
    //String script = props.getProperty("SCRIPT_PATH");
    String origjobdir = props.getProperty("JOB_DIR");
    String jobdir = origjobdir;//ww  w . j  av  a2  s .  c o  m
    //String datadir = props.getProperty("DATA_DIR");

    // File Manager Access
    String fmurl = props.getProperty("FM_URL");
    String fmprefix = props.getProperty("FM_PREFIX");

    // Logging specific info
    String logfile = props.getProperty("LOGFILE");
    String wlogfile = props.getProperty("W_LOGFILE");
    String tplid = wlogfile.replace(".log", "");

    PrintStream wlogout = null;
    PrintStream logout = null;

    XmlRpcFileManagerClient fmclient = null;
    try {
        fmclient = new XmlRpcFileManagerClient(new URL(fmurl));
        DataTransfer dt = new RemoteDataTransferFactory().createDataTransfer();
        dt.setFileManagerUrl(new URL(fmurl));

        // Check if outputs already exist in the file manager
        boolean outputs_already_present = true;
        for (String op : outputs) {
            String prodid = fmprefix + op;
            Product prod = null;
            try {
                prod = fmclient.getProductById(prodid);
            } catch (Exception e) {
            }
            if (prod == null) {
                outputs_already_present = false;
            }
        }
        // If outputs already present, no need to execute
        if (outputs_already_present)
            return;

        File tmpdir = File.createTempFile("oodt-run-", "");
        if (tmpdir.delete() && tmpdir.mkdirs())
            jobdir = tmpdir.getAbsolutePath() + File.separator;

        argstring = argstring.replace(origjobdir, jobdir);

        wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true));
        logout = new PrintStream(jobdir + logfile);

        wlogout.println(jobid + " (" + tname + "): RUNNING");
        wlogout.close();
        this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(),
                fmclient);

        wlogout = new PrintStream(new FileOutputStream(jobdir + wlogfile, true));
        logout.println("[INFO]: Component Initializing");
        logout.println(tname + " " + argstring);

        // Fetch input files from file manager if not already present in directory
        for (String ip : inputs) {
            File f = new File(jobdir + ip);
            if (!f.exists()) {
                logout.println("[INFO] Fetching Input from File Manager: " + ip);
                Product prod = fmclient.getProductById(fmprefix + ip);
                prod.setProductReferences(fmclient.getProductReferences(prod));
                dt.retrieveProduct(prod, new File(jobdir));
            }
        }
        logout.flush();

        // Fetch component from file manager
        File compdir = new File(jobdir + File.separator + "comp");
        compdir.mkdir();
        Product cprod = fmclient.getProductById(compid);
        cprod.setProductReferences(fmclient.getProductReferences(cprod));
        dt.retrieveProduct(cprod, compdir);
        String scriptPath = null;
        for (File czip : compdir.listFiles()) {
            if (czip.getName().endsWith(".zip")) {
                this.unZipIt(czip.getAbsolutePath(), compdir.getAbsolutePath());
                File tmpf = new File(compdir.getAbsolutePath() + File.separator + "run");
                if (!tmpf.exists())
                    tmpf = new File(compdir.getAbsolutePath() + File.separator + "run.bat");
                scriptPath = tmpf.getAbsolutePath();
            } else
                scriptPath = czip.getAbsolutePath();
        }
        File scriptf = new File(scriptPath);
        scriptf.setExecutable(true);

        // Create command execution
        ArrayList<String> command = new ArrayList<String>();
        command.add(scriptf.getAbsolutePath());
        for (String s : argstring.split(" ")) {
            command.add(s);
        }

        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(jobdir));
        builder.redirectErrorStream(true);

        final Process process = builder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            logout.println(line);
        }
        process.waitFor();
        int exitStatus = process.exitValue();
        if (exitStatus != 0)
            throw new Exception("[ERROR] Component failed with a non-zero exit code");

        // Ingest output files to file manager
        for (String op : outputs) {
            File f = new File(jobdir + op);

            File metf = new File(jobdir + op + ".met");
            HashMap<String, String> cmeta = new HashMap<String, String>();
            if (metf.exists()) {
                for (Object ln : FileUtils.readLines(metf)) {
                    String metline = (String) ln;
                    String[] kv = metline.split("\\s*=\\s*");
                    if (kv.length == 2)
                        cmeta.put(kv[0], kv[1]);
                }
            }
            if (!f.exists())
                throw new Exception("[ERROR] Missing Output " + op);
            if (f.exists()) {
                logout.println("[INFO] Putting Output into File Manager: " + op);

                // Get Output Metadata & Product Type
                String typeid = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
                Metadata meta = metadata.getSubMetadata(op);
                String prodtypeid = meta.getMetadata(typeid);
                meta.removeMetadata(typeid);

                // Override metadata with custom metadata (if any)
                for (String key : meta.getAllKeys()) {
                    String[] nsname = key.split("#");
                    if (nsname.length == 2) {
                        if (cmeta.containsKey(nsname[1])) {
                            meta.removeMetadata(key);
                            meta.addMetadata(key, cmeta.get(nsname[1]));
                        }
                    }
                }

                // Upload output to file manager
                String prodid = fmprefix + op;
                this.uploadProduct(prodid, op, prodtypeid, f, meta, fmclient);
            }

            if (metf.exists()) {
                String metname = op + ".met";
                String prodid = fmprefix + metname;
                this.uploadProduct(prodid, metname, "GenericFile", metf, new Metadata(), fmclient);
            }
        }
        logout.println("SUCCESS: Component finished successfully !");
        logout.close();
        wlogout.println(jobid + " (" + tname + "): SUCCESS");
        wlogout.close();
    } catch (Exception e) {
        if (logout != null) {
            logout.println(e.getMessage());
            logout.println("FAILURE: Component Failed");
            logout.close();
            wlogout.println(jobid + " (" + tname + "): FAILURE");
            wlogout.close();
        }
    }
    try {
        if (fmclient != null) {
            this.uploadProduct(wlogfile, wlogfile, "GenericFile", new File(jobdir + wlogfile), new Metadata(),
                    fmclient);
            String logid = tplid + "-" + logfile;
            this.uploadProduct(logid, logid, "GenericFile", new File(jobdir + logfile), new Metadata(),
                    fmclient);
        }
    } catch (CatalogException e) {
        e.printStackTrace();
    } catch (RepositoryManagerException e) {
        e.printStackTrace();
    }
}

From source file:com.redhat.jenkins.plugins.ci.integration.FedMsgMessagingPluginIntegrationTest.java

private Process logProcessBuilderIssues(ProcessBuilder pb, String commandName)
        throws InterruptedException, IOException {
    String dir = "";
    if (pb.directory() != null) {
        dir = pb.directory().getAbsolutePath();
    }//ww w. ja  v  a 2s. c om
    System.out.println("Running : " + pb.command() + " => directory: " + dir);
    Process processToRun = pb.start();
    int result = processToRun.waitFor();
    if (result != 0) {
        StringWriter writer = new StringWriter();
        IOUtils.copy(processToRun.getErrorStream(), writer);
        System.out.println("Issue occurred during command \"" + commandName + "\":\n" + writer.toString());
        writer.close();
    }
    return processToRun;
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Generates symlink to the latest version.
 */// w w w.  j  a  va2 s  . c om
protected void createLatestSymlink(PluginHistory hpi, HPI latest) throws InterruptedException, IOException {
    File dir = new File(download, "plugins/" + hpi.artifactId);
    new File(dir, "latest").delete();

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("ln", "-s", latest.version, "latest");
    pb.directory(dir);
    int r = pb.start().waitFor();
    if (r != 0)
        throw new IOException("ln failed: " + r);
}

From source file:com.google.dart.tools.debug.core.configs.DartServerLaunchConfigurationDelegate.java

protected void launchVM(ILaunch launch, DartLaunchConfigWrapper launchConfig, boolean enableDebugging,
        IProgressMonitor monitor) throws CoreException {
    // Usage: dart [options] script.dart [arguments]

    File currentWorkingDirectory = getCurrentWorkingDirectory(launchConfig);

    String scriptPath = launchConfig.getApplicationName();

    scriptPath = translateToFilePath(currentWorkingDirectory, scriptPath);

    String vmExecPath = "";

    if (DartSdkManager.getManager().hasSdk()) {
        File vmExec = DartSdkManager.getManager().getSdk().getVmExecutable();

        if (vmExec != null) {
            vmExecPath = vmExec.getAbsolutePath().toString();
        }//from w w  w.ja  v a 2s .c  o m
    } else {
        vmExecPath = DartDebugCorePlugin.getPlugin().getDartVmExecutablePath();
    }

    if (vmExecPath.length() == 0) {
        throw new CoreException(
                DartDebugCorePlugin.createErrorStatus("The executable path for the Dart VM has not been set."));
    }

    List<String> commandsList = new ArrayList<String>();

    int connectionPort = NetUtils.findUnusedPort(DEFAULT_PORT_NUMBER);

    commandsList.add(vmExecPath);
    commandsList.addAll(Arrays.asList(launchConfig.getVmArgumentsAsArray()));

    if (enableDebugging) {
        commandsList.add("--debug:" + connectionPort);
    }

    observatoryPort = NetUtils.findUnusedPort(0);

    launchConfig.setObservatoryPort(observatoryPort);
    launchConfig.save();

    commandsList.add("--enable-vm-service:" + observatoryPort);
    commandsList.add("--trace_service_pause_events");

    if (launchConfig.getPauseIsolateOnExit()) {
        commandsList.add("--pause-isolates-on-exit");
    }

    if (launchConfig.getPauseIsolateOnStart()) {
        commandsList.add("--pause-isolates-on-start");
    }

    // This lets us debug isolates.
    if (enableDebugging) {
        commandsList.add("--break-at-isolate-spawn");
    }

    String coverageTempDir = null;
    if (DartCoreDebug.ENABLE_COVERAGE) {
        coverageTempDir = CoverageManager.createTempDir();
        commandsList.add("--coverage_dir=" + coverageTempDir);
    }

    String packageRoot = DartCore.getPlugin().getVmPackageRoot(launchConfig.getProject());
    if (packageRoot != null) {
        String fileSeparator = System.getProperty("file.separator");
        if (!packageRoot.endsWith(fileSeparator)) {
            packageRoot += fileSeparator;
        }
        commandsList.add("--package-root=" + packageRoot);
    }

    commandsList.add(scriptPath);
    commandsList.addAll(Arrays.asList(launchConfig.getArgumentsAsArray()));
    String[] commands = commandsList.toArray(new String[commandsList.size()]);
    ProcessBuilder processBuilder = new ProcessBuilder(commands);

    if (currentWorkingDirectory != null) {
        processBuilder.directory(currentWorkingDirectory);
    }

    Process runtimeProcess = null;

    try {
        runtimeProcess = processBuilder.start();
        if (coverageTempDir != null) {
            UriToFileResolver uriToFileResolver = new UriToFileResolver(launch);
            CoverageManager.registerProcess(uriToFileResolver, coverageTempDir,
                    launchConfig.getApplicationName(), runtimeProcess);
        }
    } catch (IOException ioe) {
        throw new CoreException(
                new Status(IStatus.ERROR, DartDebugCorePlugin.PLUGIN_ID, ioe.getMessage(), ioe));
    }

    IProcess eclipseProcess = null;

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

    String programName = "dart";
    processAttributes.put(IProcess.ATTR_PROCESS_TYPE, programName);
    processAttributes.put(IProcess.ATTR_CMDLINE, describe(processBuilder));

    if (runtimeProcess != null) {
        monitor.beginTask("Dart", IProgressMonitor.UNKNOWN);

        eclipseProcess = DebugPlugin.newProcess(launch, runtimeProcess,
                launchConfig.getApplicationName() + " (" + new Date() + ")", processAttributes);
    }

    if (runtimeProcess == null || eclipseProcess == null) {
        if (runtimeProcess != null) {
            runtimeProcess.destroy();
        }

        throw new CoreException(DartDebugCorePlugin.createErrorStatus("Error starting Dart VM process"));
    }

    eclipseProcess.setAttribute(IProcess.ATTR_CMDLINE, describe(processBuilder));

    if (enableDebugging) {
        ServerDebugTarget debugTarget = new ServerDebugTarget(launch, eclipseProcess, connectionPort);

        try {
            debugTarget.connect();

            launch.addDebugTarget(debugTarget);
        } catch (DebugException ex) {
            // We don't throw an exception if the process died before we could connect.
            if (!isProcessDead(runtimeProcess)) {
                throw ex;
            }
        }
    }

    monitor.done();
}

From source file:de.uni_luebeck.inb.knowarc.usecases.invocation.local.LocalUseCaseInvocation.java

@Override
protected void submit_generate_job_inner() throws InvocationException {
    tags.put("uniqueID", "" + getSubmissionID());
    String command = usecase.getCommand();
    for (String cur : tags.keySet()) {
        command = command.replaceAll("\\Q%%" + cur + "%%\\E", Matcher.quoteReplacement(tags.get(cur)));
    }/*  w w w.  j  ava 2  s.c  om*/

    List<String> cmds = new ArrayList<String>();
    if ((shellPrefix != null) && !shellPrefix.isEmpty()) {
        String[] prefixCmds = shellPrefix.split(" ");
        for (int i = 0; i < prefixCmds.length; i++) {
            cmds.add(prefixCmds[i]);
        }
        cmds.add(command);
    } else {
        String[] splitCmds = command.split(" ");
        for (int i = 0; i < splitCmds.length; i++) {
            cmds.add(splitCmds[i]);
        }
    }

    ProcessBuilder builder = new ProcessBuilder(cmds);
    builder.directory(tempDir);

    for (int i = 0; i < cmds.size(); i++) {
        logger.info("cmds[" + i + "] = " + cmds.get(i));
    }
    logger.info("Command is " + command + " in directory " + tempDir);
    try {
        running = builder.start();
        if (stdInReader != null) {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(running.getOutputStream()));
            IOUtils.copyLarge(stdInReader, writer);
            writer.close();
        }
    } catch (IOException e) {
        throw new InvocationException(e);
    }
}

From source file:com.asakusafw.testdriver.DefaultJobExecutor.java

private int runCommand(List<String> commandLine, Map<String, String> environmentVariables) throws IOException {
    LOG.info(MessageFormat.format(Messages.getString("DefaultJobExecutor.infoEchoCommandLine"), //$NON-NLS-1$
            toCommandLineString(commandLine)));

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    builder.redirectErrorStream(true);//from   w  w w  .  j a v a 2  s.co  m
    builder.environment().putAll(environmentVariables);
    File hadoopCommand = configurations.getHadoopCommand();
    if (hadoopCommand != null) {
        builder.environment().put("HADOOP_CMD", hadoopCommand.getAbsolutePath()); //$NON-NLS-1$
    }
    builder.directory(new File(System.getProperty("user.home", "."))); //$NON-NLS-1$ //$NON-NLS-2$

    int exitCode;
    Process process = builder.start();
    try (InputStream is = process.getInputStream()) {
        InputStreamThread it = new InputStreamThread(is);
        it.start();
        exitCode = process.waitFor();
        it.join();
    } catch (InterruptedException e) {
        throw new IOException(
                MessageFormat.format(Messages.getString("DefaultJobExecutor.errorExecutionInterrupted"), //$NON-NLS-1$
                        toCommandLineString(commandLine)),
                e);
    } finally {
        process.getOutputStream().close();
        process.getErrorStream().close();
        process.destroy();
    }
    return exitCode;
}

From source file:org.trancecode.xproc.step.ExecStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) throws Exception {
    final String pathSeparator = input.getOptionValue(XProcOptions.PATH_SEPARATOR);
    final String command;
    if (pathSeparator != null) {
        command = input.getOptionValue(XProcOptions.COMMAND).replace(pathSeparator, File.separator);
    } else {// www. jav  a2s  .c  o  m
        command = input.getOptionValue(XProcOptions.COMMAND);
    }

    final String argSeparator = input.getOptionValue(XProcOptions.ARG_SEPARATOR, " ");
    final Iterable<String> rawArgs = TcStrings.split(input.getOptionValue(XProcOptions.ARGS), argSeparator);
    final Iterable<String> args = Iterables.transform(rawArgs, arg -> {
        if (pathSeparator != null) {
            return arg.replace(pathSeparator, File.separator);
        }

        return arg;
    });
    final String cwd = input.getOptionValue(XProcOptions.CWD);

    final List<XdmNode> inputDocuments = ImmutableList.copyOf(input.readNodes(XProcPorts.SOURCE));
    if (inputDocuments.size() > 1) {
        throw XProcExceptions.xd0006(input.getStep().getLocation(),
                input.getStep().getPortReference(XProcPorts.SOURCE));
    }
    final boolean sourceIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.SOURCE_IS_XML));
    final boolean resultIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.RESULT_IS_XML));
    final boolean wrapResultLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_RESULT_LINES));
    final boolean errorsIsXml = Boolean.parseBoolean(input.getOptionValue(XProcOptions.ERRORS_IS_XML));
    final boolean wrapErrorLines = Boolean.parseBoolean(input.getOptionValue(XProcOptions.WRAP_ERROR_LINES));
    if ((resultIsXml && wrapResultLines) || (errorsIsXml && wrapErrorLines)) {
        throw XProcExceptions.xc0035(input.getStep().getLocation());
    }

    final List<String> commandLine = Lists.newArrayList();
    commandLine.add(command);
    Iterables.addAll(commandLine, Iterables.filter(args, StringPredicates.isNotEmpty()));
    LOG.trace("  commandLine = {}", commandLine);
    final ProcessBuilder processBuilder = new ProcessBuilder(commandLine.toArray(new String[0]));
    processBuilder.redirectErrorStream(false);
    if (cwd != null) {
        final Path newDirectory = Paths.get(cwd);
        if (!Files.isDirectory(newDirectory)) {
            throw XProcExceptions.xc0034(input.getLocation());
        }
        processBuilder.directory(new File(cwd));
    }
    final Process process;
    try {
        process = processBuilder.start();
    } catch (IOException e) {
        throw XProcExceptions.xc0033(input.getLocation());
    }

    if (!inputDocuments.isEmpty()) {
        final String inputContent;
        if (sourceIsXml) {
            inputContent = inputDocuments.get(0).toString();
        } else {
            inputContent = SaxonAxis.childElement(inputDocuments.get(0)).getStringValue();
        }

        new Thread(() -> {
            try {
                IOUtils.write(inputContent, process.getOutputStream());
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            } finally {
                Closeables.closeQuietly(process.getOutputStream());
            }
        }).start();
    }

    final Supplier<File> stdout = TcByteStreams.copyToTempFile(process.getInputStream());
    final Supplier<File> stderr = TcByteStreams.copyToTempFile(process.getErrorStream());

    final int exitCode = process.waitFor();
    LOG.trace("exitCode = {}", exitCode);
    final String failureThreshold = input.getOptionValue(XProcOptions.FAILURE_THRESHOLD);
    if (failureThreshold != null) {
        LOG.trace("failureThreshold  = {}", failureThreshold);
        final int numericFailureThreshold = Integer.parseInt(failureThreshold);
        if (exitCode > numericFailureThreshold) {
            throw XProcExceptions.xc0064(input.getLocation(), exitCode, numericFailureThreshold);
        }
    }

    final File stdoutFile = stdout.get();
    final File stderrFile = stderr.get();
    process.destroy();

    final Processor processor = input.getPipelineContext().getProcessor();
    output.writeNodes(XProcPorts.RESULT,
            parseOutput(stdoutFile, resultIsXml, wrapResultLines, input.getStep().getNode(), processor));
    output.writeNodes(XProcPorts.ERRORS,
            parseOutput(stderrFile, errorsIsXml, wrapErrorLines, input.getStep().getNode(), processor));
    output.writeNodes(XProcPorts.EXIT_STATUS, input.newResultElement(Integer.toString(exitCode)));
}

From source file:de.jcup.egradle.core.process.SimpleProcessExecutor.java

@Override
public int execute(ProcessConfiguration wdProvider, EnvironmentProvider envProvider,
        ProcessContext processContext, String... commands) throws IOException {
    notNull(wdProvider, "'wdProvider' may not be null");
    notNull(envProvider, "'envProvider' may not be null");
    String wd = wdProvider.getWorkingDirectory();
    /* Working directory */
    File workingDirectory = null;
    if (StringUtils.isNotBlank(wd)) {
        workingDirectory = new File(wd);
    }//  w  ww.j  a  v  a  2  s. c  o  m
    if (workingDirectory != null) {
        if (!workingDirectory.exists()) {
            throw new FileNotFoundException("Working directory does not exist:" + workingDirectory);
        }
    }
    /* Create process with dedicated environment */
    ProcessBuilder pb = new ProcessBuilder(commands);
    Map<String, String> env = envProvider.getEnvironment();
    /* init environment */
    if (env != null) {
        Map<String, String> pbEnv = pb.environment();
        for (String key : env.keySet()) {
            pbEnv.put(key, env.get(key));
        }
    }
    /* init working directory */
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    Date started = new Date();
    Process p = startProcess(pb);
    ProcessTimeoutTerminator timeoutTerminator = null;
    if (timeOutInSeconds != ENDLESS_RUNNING) {
        timeoutTerminator = new ProcessTimeoutTerminator(p, outputHandler, timeOutInSeconds);
        timeoutTerminator.start();
    }
    ProcessCancelTerminator cancelTerminator = new ProcessCancelTerminator(p,
            processContext.getCancelStateProvider());
    Thread cancelCheckThread = new Thread(cancelTerminator, "process-cancel-terminator");
    cancelCheckThread.start();

    handleProcessStarted(envProvider, p, started, workingDirectory, commands);

    handleOutputStreams(p, timeoutTerminator, processContext.getCancelStateProvider());

    /* wait for execution */
    try {
        while (isAlive(p)) {
            waitFor(p);
        }
    } catch (InterruptedException e) {
        /* ignore */
    }
    /* done */
    int exitValue = p.exitValue();
    handleProcessEnd(p);
    return exitValue;
}

From source file:acoli.controller.Controller.java

private void killProcessID(String path, String scriptCommand, String aScriptParam) throws IOException {
    // Run bash .sh script here.
    ProcessBuilder pb = null;
    // Call the startup script on the uploaded and unzipped grammar directory.
    pb = new ProcessBuilder(scriptCommand, aScriptParam);
    if (pb != null) {
        //System.out.println("Running bash script....");
        // Point to where the script is located.
        pb.directory(new File(path + "/resources/uploads/"));
        Process p = pb.start();//  www.j a v  a 2  s.  c om

        BufferedReader output = getOutput(p);
        BufferedReader error = getError(p);
        String line = "";
        while ((line = output.readLine()) != null) {
            System.out.println("out: " + line);
        }
        while ((line = error.readLine()) != null) {
            System.out.println("err: " + line);
        }
    }
}

From source file:org.apache.jxtadoop.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    boolean completed = false;

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }//  w  w  w .j av a  2  s.  c  o  m
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed = true;
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}