Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

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

Prototype

boolean redirectErrorStream

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

Click Source Link

Usage

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

protected void pkill(int pid, String dir) throws Exception {

    // Use pkill, seems to kill all of the tree more reliably
    ProcessBuilder pb = new ProcessBuilder();

    // Can adjust env if needed:
    // Map<String, String> env = pb.environment();
    pb.directory(new File(dir));

    File log = new File(dir, "xia2_kill.txt");
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(log));

    pb.command("bash", "-c", "pkill -9 -s " + pid);

    Process p = pb.start();/* w  w  w .jav  a 2s.  c  o m*/
    p.waitFor();
}

From source file:net.pms.io.ThreadedProcessWrapper.java

/**
 * Runs a process with the given command {@link List}.
 *
 * @param command an array of {@link String} used to build the command line.
 * @param timeoutMS the process timeout in milliseconds after which the
 *            process is terminated. Use zero for no timeout, but be aware
 *            of the <a href=/*from w w w  .j  a v a 2s.c o m*/
 *            "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9"
 *            >pitfalls</a>
 * @param terminateTimeoutMS the timeout in milliseconds to wait for each
 *            termination attempt.
 * @return The {@link ProcessWrapperResult} from running the process.
 * @throws IllegalArgumentException If {@code command} is {@code null} or
 *             empty.
 */
@Nonnull
public Future<R> runProcess(@Nonnull final List<String> command, final long timeoutMS,
        final long terminateTimeoutMS) {
    if (command == null || command.isEmpty()) {
        throw new IllegalArgumentException("command can't be null or empty");
    }
    final String executableName;
    if (isNotBlank(command.get(0))) {
        Path executable = Paths.get(command.get(0)).getFileName();
        if (executable != null) {
            executableName = executable.toString();
        } else {
            executableName = command.get(0);
        }
    } else {
        executableName = command.get(0);
    }
    final int threadId = PROCESS_COUNTER.getAndIncrement();

    Callable<R> callable = new Callable<R>() {

        @Override
        public R call() throws InterruptedException {
            boolean manageProcess = timeoutMS > 0;
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            if (LOGGER.isTraceEnabled()) {
                //XXX: Replace with String.join() in Java 8
                LOGGER.trace("Executing \"{}\"", StringUtils.join(command, " "));
            }
            Process process;
            try {
                process = processBuilder.start();
            } catch (IOException e) {
                LOGGER.debug("IOException when trying to start \"{}\" process: {}", executableName,
                        e.getMessage());
                LOGGER.trace("", e);
                return consumer.createResult(null, Integer.MIN_VALUE, e);
            }
            Future<T> output = consumer.consume(process.getInputStream(),
                    "TPW \"" + executableName + "\" consumer " + threadId);
            if (manageProcess) {
                Services.processManager().addProcess(process, executableName, timeoutMS, terminateTimeoutMS);
            }
            int exitCode = Integer.MIN_VALUE;
            boolean interrupted = false;
            boolean shutdown = false;
            do {
                interrupted = false;
                try {
                    exitCode = process.waitFor();
                } catch (InterruptedException e) {
                    interrupted = Thread.interrupted();
                    if (!shutdown) {
                        if (manageProcess) {
                            Services.processManager().shutdownProcess(process, executableName);
                            manageProcess = false;
                        } else {
                            Services.processManager().addProcess(process, executableName, 0,
                                    terminateTimeoutMS);
                        }
                        shutdown = true;
                    }
                }
            } while (interrupted);
            if (manageProcess) {
                Services.processManager().removeProcess(process, executableName);
            }
            try {
                return consumer.createResult(output.get(), exitCode, null);
            } catch (ExecutionException e) {
                Throwable cause = e.getCause() != null ? e.getCause() : e;
                LOGGER.error("ExecutionException in \"{}\" consumer, no output will be returned: {}",
                        executableName, cause.getMessage());
                LOGGER.trace("", e);
                return consumer.createResult(null, exitCode, cause);
            }
        }
    };
    FutureTask<R> result = new FutureTask<R>(callable);
    Thread runner = new Thread(result, "TPW \"" + executableName + "\" " + threadId);
    runner.start();
    return result;
}

From source file:org.nuxeo.ecm.platform.commandline.executor.service.executors.ShellExecutor.java

protected ExecResult exec1(CommandLineDescriptor cmdDesc, CmdParameters params, EnvironmentDescriptor env)
        throws IOException {
    // split the configured parameters while keeping quoted parts intact
    List<String> list = new ArrayList<>();
    list.add(cmdDesc.getCommand());//from   w  w w . j av a 2s  .c  om
    Matcher m = COMMAND_SPLIT.matcher(cmdDesc.getParametersString());
    while (m.find()) {
        String word;
        if (m.group(1) != null) {
            word = m.group(1); // double-quoted
        } else if (m.group(2) != null) {
            word = m.group(2); // single-quoted
        } else {
            word = m.group(); // word
        }
        List<String> words = replaceParams(word, params);
        list.addAll(words);
    }

    List<Process> processes = new LinkedList<>();
    List<Thread> pipes = new LinkedList<>();
    List<String> command = new LinkedList<>();
    Process process = null;
    for (Iterator<String> it = list.iterator(); it.hasNext();) {
        String word = it.next();
        boolean build;
        if (word.equals("|")) {
            build = true;
        } else {
            // on Windows, look up the command in the PATH first
            if (command.isEmpty() && SystemUtils.IS_OS_WINDOWS) {
                command.add(getCommandAbsolutePath(word));
            } else {
                command.add(word);
            }
            build = !it.hasNext();
        }
        if (!build) {
            continue;
        }
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        command = new LinkedList<>(); // reset for next loop
        processBuilder.directory(new File(env.getWorkingDirectory()));
        processBuilder.environment().putAll(env.getParameters());
        processBuilder.redirectErrorStream(true);
        Process newProcess = processBuilder.start();
        processes.add(newProcess);
        if (process == null) {
            // first process, nothing to input
            IOUtils.closeQuietly(newProcess.getOutputStream());
        } else {
            // pipe previous process output into new process input
            // needs a thread doing the piping because Java has no way to connect two children processes directly
            // except through a filesystem named pipe but that can't be created in a portable manner
            Thread pipe = pipe(process.getInputStream(), newProcess.getOutputStream());
            pipes.add(pipe);
        }
        process = newProcess;
    }

    // get result from last process
    @SuppressWarnings("null")
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    List<String> output = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        output.add(line);
    }
    reader.close();

    // wait for all processes, get first non-0 exit status
    int returnCode = 0;
    for (Process p : processes) {
        try {
            int exitCode = p.waitFor();
            if (returnCode == 0) {
                returnCode = exitCode;
            }
        } catch (InterruptedException e) {
            ExceptionUtils.checkInterrupt(e);
        }
    }

    // wait for all pipes
    for (Thread t : pipes) {
        try {
            t.join();
        } catch (InterruptedException e) {
            ExceptionUtils.checkInterrupt(e);
        }
    }

    return new ExecResult(null, output, 0, returnCode);
}

From source file:com.photon.phresco.plugins.xcode.AppDeploy.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*  w  w w.j a va2 s  .  c om*/
        if (!deviceDeploy && !SdkVerifier.isAvailable(simVersion)) {
            throw new MojoExecutionException("Selected version " + simVersion + " is not available!");
        }
    } catch (IOException e2) {
        throw new MojoExecutionException("SDK verification failed!");
    } catch (InterruptedException e2) {
        throw new MojoExecutionException("SDK verification interrupted!");
    }
    //get the correct simhome if xCode 4.3 is installed simhome is in /Application/Xcode.app/Contents
    //Fix for artf462004
    File simHomeFile = new File(simHome);
    if (!simHomeFile.exists()) {
        simHome = "/Applications/Xcode.app/Contents" + simHome;
    }

    getLog().info("Simulator home" + simHome);

    if (!deviceDeploy) {
        //copy the files into simulation directory
        String home = System.getProperty("user.home");
        getLog().info("Application.path = " + appPath);
        appName = getAppFileName(appPath);
        getLog().info("Application name = " + appName);
        String deployHome = "";
        if (StringUtils.isNotBlank(appDeployHome)) {
            deployHome = appDeployHome;
        } else {
            deployHome = home + "/Library/Application Support/iPhone Simulator/" + simVersion + "/Applications";
        }
        simHomeAppLocation = new File(
                deployHome + File.separator + project.getName() + File.separator + appName);
        if (!simHomeAppLocation.exists()) {
            getLog().info("directory created");
            simHomeAppLocation.mkdirs();
        }
        getLog().info("Desired location " + simHomeAppLocation.getAbsolutePath());
        try {
            String alignedPath = alignedPath(appPath);
            getLog().info("path to copy source :" + alignedPath);
            XcodeUtil.copyFolder(new File(alignedPath), simHomeAppLocation);
            getLog().info("copy the application " + appPath + " to " + simHomeAppLocation);
        } catch (IOException e1) {
            getLog().error("couldn't copy the application " + appPath + " to " + simHomeAppLocation);
        }
    }
    Runnable runnable = new Runnable() {
        public void run() {

            ProcessBuilder pb;
            if (deviceDeploy) {
                pb = new ProcessBuilder("transporter_chief.rb");
                pb.command().add(appPath);
            } else {
                pb = new ProcessBuilder(simHome);
                // Include errors in output
                pb.redirectErrorStream(true);

                pb.command().add(action);
                pb.command()
                        .add(simHomeAppLocation + File.separator + appName.substring(0, appName.indexOf('.')));
            }
            //               pb.command().add(appName);
            getLog().info("List of commands" + pb.command());
            Process child;
            try {
                //               if(ProcessHelper.isProcessRunning()) {
                //                  ProcessHelper.killSimulatorProcess();
                //               }
                child = pb.start();
                // Consume subprocess output and write to stdout for debugging
                InputStream is = new BufferedInputStream(child.getInputStream());
                int singleByte = 0;
                while ((singleByte = is.read()) != -1) {
                    System.out.write(singleByte);
                }
            } catch (IOException e) {
                getLog().error("error occured in launching simulator ");
                getLog().error(e);
            }
        }
    };

    Thread t = new Thread(runnable, "iPhoneSimulator");
    t.start();
    try {
        t.join(5000);
    } catch (InterruptedException e1) {
        //Intentionally left blank.
    }

}

From source file:org.opencastproject.composer.impl.AbstractCmdlineEncoderEngine.java

/**
 * Executes the command line encoder with the given set of files and properties and using the provided encoding
 * profile.//  w w w .j  a  v a  2 s  . c  om
 * 
 * @param audioSource
 *          the audio file (used when muxing)
 * @param videoSource
 *          the video file
 * @param profile
 *          the profile identifier
 * @param properties
 *          the encoding properties to be interpreted by the actual encoder implementation
 * @return the processed file
 * @throws EncoderException
 *           if processing fails
 */
protected Option<File> process(File audioSource, File videoSource, EncodingProfile profile,
        Map<String, String> properties) throws EncoderException {
    // Fist, update the parameters
    if (properties != null)
        params.putAll(properties);
    // build command
    BufferedReader in = null;
    Process encoderProcess = null;
    if (videoSource == null && audioSource == null) {
        throw new IllegalArgumentException("At least one track must be specified.");
    }
    try {
        // Set encoding parameters
        String audioInput = null;
        if (audioSource != null) {
            audioInput = FilenameUtils.normalize(audioSource.getAbsolutePath());
            params.put("in.audio.path", audioInput);
            params.put("in.audio.name", FilenameUtils.getBaseName(audioInput));
            params.put("in.audio.suffix", FilenameUtils.getExtension(audioInput));
            params.put("in.audio.filename", FilenameUtils.getName(audioInput));
            params.put("in.audio.mimetype",
                    MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(audioInput));
        }
        if (videoSource != null) {
            String videoInput = FilenameUtils.normalize(videoSource.getAbsolutePath());
            params.put("in.video.path", videoInput);
            params.put("in.video.name", FilenameUtils.getBaseName(videoInput));
            params.put("in.video.suffix", FilenameUtils.getExtension(videoInput));
            params.put("in.video.filename", FilenameUtils.getName(videoInput));
            params.put("in.video.mimetype",
                    MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(videoInput));
        }
        File parentFile;
        if (videoSource == null) {
            parentFile = audioSource;
        } else {
            parentFile = videoSource;
        }
        String outDir = parentFile.getAbsoluteFile().getParent();
        String outFileName = FilenameUtils.getBaseName(parentFile.getName());
        String outSuffix = processParameters(profile.getSuffix());

        if (params.containsKey("time")) {
            outFileName += "_" + properties.get("time");
        }

        // generate random name if multiple jobs are producing file with identical name (MH-7673)
        outFileName += "_" + UUID.randomUUID().toString();

        params.put("out.dir", outDir);
        params.put("out.name", outFileName);
        params.put("out.suffix", outSuffix);

        // create encoder process.
        // no special working dir is set which means the working dir of the
        // current java process is used.
        // TODO: Parallelisation (threading)
        List<String> command = buildCommand(profile);
        StringBuilder sb = new StringBuilder();
        for (String cmd : command) {
            sb.append(cmd);
            sb.append(" ");
        }
        logger.info("Executing encoding command: {}", sb);
        ProcessBuilder pbuilder = new ProcessBuilder(command);
        pbuilder.redirectErrorStream(REDIRECT_ERROR_STREAM);
        encoderProcess = pbuilder.start();

        // tell encoder listeners about output
        in = new BufferedReader(new InputStreamReader(encoderProcess.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            handleEncoderOutput(profile, line, audioSource, videoSource);
        }

        // wait until the task is finished
        encoderProcess.waitFor();
        int exitCode = encoderProcess.exitValue();
        if (exitCode != 0) {
            throw new EncoderException(this, "Encoder exited abnormally with status " + exitCode);
        }

        if (audioSource != null) {
            logger.info("Audio track {} and video track {} successfully encoded using profile '{}'",
                    new String[] { (audioSource == null ? "N/A" : audioSource.getName()),
                            (videoSource == null ? "N/A" : videoSource.getName()), profile.getIdentifier() });
        } else {
            logger.info("Video track {} successfully encoded using profile '{}'",
                    new String[] { videoSource.getName(), profile.getIdentifier() });
        }
        fireEncoded(this, profile, audioSource, videoSource);
        if (profile.getOutputType() != EncodingProfile.MediaType.Nothing)
            return some(new File(parentFile.getParent(), outFileName + outSuffix));
        else
            return none();
    } catch (EncoderException e) {
        if (audioSource != null) {
            logger.warn("Error while encoding audio track {} and video track {} using '{}': {}",
                    new String[] { (audioSource == null ? "N/A" : audioSource.getName()),
                            (videoSource == null ? "N/A" : videoSource.getName()), profile.getIdentifier(),
                            e.getMessage() });
        } else {
            logger.warn("Error while encoding video track {} using '{}': {}",
                    new String[] { (videoSource == null ? "N/A" : videoSource.getName()),
                            profile.getIdentifier(), e.getMessage() });
        }
        fireEncodingFailed(this, profile, e, audioSource, videoSource);
        throw e;
    } catch (Exception e) {
        logger.warn("Error while encoding audio {} and video {} to {}:{}, {}",
                new Object[] { (audioSource == null ? "N/A" : audioSource.getName()),
                        (videoSource == null ? "N/A" : videoSource.getName()), profile.getName(),
                        e.getMessage() });
        fireEncodingFailed(this, profile, e, audioSource, videoSource);
        throw new EncoderException(this, e.getMessage(), e);
    } finally {
        IoSupport.closeQuietly(in);
        IoSupport.closeQuietly(encoderProcess);
    }
}

From source file:org.apache.kudu.client.MiniKdc.java

private Process startProcessWithKrbEnv(String... argv) throws IOException {

    ProcessBuilder procBuilder = new ProcessBuilder(argv);
    procBuilder.environment().putAll(getEnvVars());
    LOG.debug("executing '{}', env: '{}'", Joiner.on(" ").join(procBuilder.command()),
            Joiner.on(", ").withKeyValueSeparator("=").join(procBuilder.environment()));
    return procBuilder.redirectErrorStream(true).start();
}

From source file:com.cloud.utils.script.Script.java

public String execute(OutputInterpreter interpreter) {
    String[] command = _command.toArray(new String[_command.size()]);

    if (_logger.isDebugEnabled()) {
        _logger.debug("Executing: " + buildCommandLine(command));
    }//from   www.  j ava2 s.  co  m

    try {
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        if (_workDir != null)
            pb.directory(new File(_workDir));

        _process = pb.start();
        if (_process == null) {
            _logger.warn("Unable to execute: " + buildCommandLine(command));
            return "Unable to execute the command: " + command[0];
        }

        BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream()));

        _thread = Thread.currentThread();
        ScheduledFuture<String> future = null;
        if (_timeout > 0) {
            future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS);
        }

        Task task = null;
        if (interpreter != null && interpreter.drain()) {
            task = new Task(interpreter, ir);
            s_executors.execute(task);
        }

        while (true) {
            try {
                if (_process.waitFor() == 0) {
                    _logger.debug("Execution is successful.");
                    if (interpreter != null) {
                        return interpreter.drain() ? task.getResult() : interpreter.interpret(ir);
                    } else {
                        // null return exitValue apparently
                        return String.valueOf(_process.exitValue());
                    }
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                if (!_isTimeOut) {
                    /*
                     * This is not timeout, we are interrupted by others,
                     * continue
                     */
                    _logger.debug("We are interrupted but it's not a timeout, just continue");
                    continue;
                }

                TimedOutLogger log = new TimedOutLogger(_process);
                Task timedoutTask = new Task(log, ir);

                timedoutTask.run();
                if (!_passwordCommand) {
                    _logger.warn("Timed out: " + buildCommandLine(command) + ".  Output is: "
                            + timedoutTask.getResult());
                } else {
                    _logger.warn("Timed out: " + buildCommandLine(command));
                }

                return ERR_TIMEOUT;
            } finally {
                if (future != null) {
                    future.cancel(false);
                }
                Thread.interrupted();
            }
        }

        _logger.debug("Exit value is " + _process.exitValue());

        BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128);

        String error;
        if (interpreter != null) {
            error = interpreter.processError(reader);
        } else {
            error = String.valueOf(_process.exitValue());
        }

        if (_logger.isDebugEnabled()) {
            _logger.debug(error);
        }
        return error;
    } catch (SecurityException ex) {
        _logger.warn("Security Exception....not running as root?", ex);
        return stackTraceAsString(ex);
    } catch (Exception ex) {
        _logger.warn("Exception: " + buildCommandLine(command), ex);
        return stackTraceAsString(ex);
    } finally {
        if (_process != null) {
            IOUtils.closeQuietly(_process.getErrorStream());
            IOUtils.closeQuietly(_process.getOutputStream());
            IOUtils.closeQuietly(_process.getInputStream());
            _process.destroy();
        }
    }
}

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;//from  ww w  .j  ava2  s. c  om
    //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.blackberry.logtools.LogTools.java

public String parseDate(String time) throws Exception {
    String parsedTime = time;/*from  w  ww  .  ja va  2  s .co  m*/
    if (Pattern.matches("[0-9]+", time) == false) {
        String[] dateCmd = { "/bin/sh", "-c", "date -d '" + time + "' +%s" };
        ProcessBuilder pBuilder = new ProcessBuilder(dateCmd);
        pBuilder.redirectErrorStream(true);
        Process p = pBuilder.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        parsedTime = br.readLine() + "000";
        if (parsedTime.contains("invalid date")) {
            logConsole(true, true, error, "Could not parse start time, invalid date.");
            System.exit(1);
        }
    } else if (time.length() != 13) {
        logConsole(true, true, error, "Could not parse start time.");
        logConsole(true, true, error, "Epoch date time must be in miliseconds. (13 digits)");
        System.exit(1);
    }
    return parsedTime;
}

From source file:net.pms.configuration.DownloadPlugins.java

private void doExec(String args) throws IOException, InterruptedException, ConfigurationException {
    int pos = args.indexOf(',');
    if (pos == -1) { // weird stuff
        return;/*from w w  w  .  ja va  2 s .  c  o m*/
    }

    // Everything after the "," is what we're supposed to run
    // First make note of jars we got
    File[] oldJar = new File(configuration.getPluginDirectory()).listFiles();

    // Before we start external installers better save the config
    configuration.save();
    ProcessBuilder pb = new ProcessBuilder(args.substring(pos + 1));
    pb.redirectErrorStream(true);
    Map<String, String> env = pb.environment();
    env.put("PROFILE_PATH", configuration.getProfilePath());
    env.put("UMS_VERSION", PMS.getVersion());

    LOGGER.debug("running '" + args + "'");
    Process pid = pb.start();
    // Consume and log any output
    Scanner output = new Scanner(pid.getInputStream());
    while (output.hasNextLine()) {
        LOGGER.debug("[" + args + "] " + output.nextLine());
    }
    configuration.reload();
    pid.waitFor();

    File[] newJar = new File(configuration.getPluginDirectory()).listFiles();
    for (File f : newJar) {
        if (!f.getAbsolutePath().endsWith(".jar")) {
            // skip non jar files
            continue;
        }
        for (File oldJar1 : oldJar) {
            if (f.getAbsolutePath().equals(oldJar1.getAbsolutePath())) {
                // old jar file break out, and set f to null to skip adding it
                f = null;
                break;
            }
        }
        // if f is null this is an jar that is old
        if (f != null) {
            jars.add(f.toURI().toURL());
        }
    }
}