Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

In this page you can find the example usage for java.lang Process exitValue.

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void addDictToArray(String dict, String array) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("Plist file '" + plist + "' not found.");
    }//from  w w w  .j  av  a  2 s .c o  m

    try {
        String command = "/usr/libexec/PlistBuddy -x -c \"Add :" + array + ":" + dict + " dict " + "\" \""
                + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();
        int exitValue = p.exitValue();
        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public void createPlist() throws IOException {

    try {/*from   w  w  w.ja va2  s .  c o m*/
        String command = "/usr/libexec/PlistBuddy -x -c \"Save \" \"" + plist.getAbsolutePath() + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };

        Process p = Runtime.getRuntime().exec(args);

        p.waitFor();

        int exitValue = p.exitValue();

        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.diversityarrays.kdxplore.trialdesign.JobRunningTask.java

@Override
public Either<String, AlgorithmRunResult> generateResult(Closure<Void> arg0) throws Exception {

    AlgorithmRunResult result = new AlgorithmRunResult(algorithmName, algorithmFolder);
    ProcessBuilder pb = new ProcessBuilder(command);

    File tempAlgorithmOutputFile = new File(algorithmFolder, "stdout.txt");
    File tempAlgorithmErrorFile = new File(algorithmFolder, "stderr.txt");

    //pb.redirectErrorStream(true);
    tempAlgorithmErrorFile.createNewFile();
    tempAlgorithmOutputFile.createNewFile();

    pb.redirectOutput(tempAlgorithmOutputFile);
    pb.redirectError(tempAlgorithmErrorFile);

    Process process = pb.start();

    while (!process.waitFor(1000, TimeUnit.MILLISECONDS)) {
        if (backgroundRunner.isCancelRequested()) {
            process.destroy();//from   w ww .j a va  2s  . c  o m
            throw new CancellationException();
        }
    }

    int exitCode = process.exitValue();
    if (exitCode != 0) {
        String errtxt = Algorithms.readContent("Error Output: (code=" + exitCode + ")",
                new FileInputStream(tempAlgorithmErrorFile));
        return Either.left(errtxt);
    }

    if (!kdxploreOutputFile.exists()) {
        return Either.left("Missing output file: " + kdxploreOutputFile.getPath());
    }

    result.addTrialEntries(kdxploreOutputFile, userTrialEntries);

    return Either.right(result);
}

From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.jaxb.JAXBPlistParser.java

public void convert(File projectFile, File destinationProjectFile) throws IOException {
    if (!SystemUtils.IS_OS_MAC_OSX) {
        throw new UnsupportedOperationException(
                "The pbxproj file conversion can only be performed on a Mac OS X "
                        + "operating system as the Mac OS X specific tool 'plutil' gets called.");
    }/*from w w w .  j  av  a 2 s.  co  m*/
    Process exec = Runtime.getRuntime().exec(new String[] { "plutil", "-convert", "xml1", "-o",
            destinationProjectFile.getAbsolutePath(), projectFile.getAbsolutePath() });
    try {
        exec.waitFor();
    } catch (InterruptedException e) {
    }

    if (exec.exitValue() != 0) {
        throw new RuntimeException("Could not convert file (Exit Code: " + exec.exitValue() + ")");
    }
}

From source file:org.opencastproject.util.FileSupport.java

/**
 * Links the specified file or directory from <code>sourceLocation</code> to <code>targetLocation</code>. If
 * <code>targetLocation</code> does not exist, it will be created.
 * <p>/*from www.  j  a v a 2s.com*/
 * If this fails (because linking is not supported on the current filesystem, then a copy is made.
 * </p>
 * If <code>overwrite</code> is set to <code>false</code>, this method throws an {@link IOException} if the target
 * file already exists.
 * 
 * @param sourceLocation
 *          the source file or directory
 * @param targetLocation
 *          the targetLocation
 * @param overwrite
 *          <code>true</code> to overwrite existing files
 * @return the created link
 * @throws IOException
 *           if linking of the file or directory failed
 */
public static File link(File sourceLocation, File targetLocation, boolean overwrite) throws IOException {
    if (sourceLocation == null)
        throw new IllegalArgumentException("Source location must not by null");
    if (targetLocation == null)
        throw new IllegalArgumentException("Target location must not by null");

    File dest = determineDestination(targetLocation, sourceLocation, overwrite);

    // Special treatment for directories as sources
    if (sourceLocation.isDirectory()) {
        if (!dest.exists()) {
            dest.mkdir();
        }
        logger.trace("Linking files in " + sourceLocation + " to " + dest);
        Process p = null;
        StreamHelper stdout = null;
        StreamHelper stderr = null;
        StringBuffer error = new StringBuffer();
        try {
            p = createLinkDirectoryProcess(sourceLocation, dest, overwrite);
            stdout = new StreamHelper(p.getInputStream());
            stderr = new LinkErrorStreamHelper(p.getErrorStream(), error);
            p.waitFor();
            stdout.stopReading();
            stderr.stopReading();
            // Find does not return with an error if -exec fails
            if (p.exitValue() != 0 || error.length() > 0) {
                logger.debug("Unable to link files from " + sourceLocation + " to " + dest + ": " + error);
                copy(sourceLocation, dest, overwrite);
            }
        } catch (InterruptedException e) {
            throw new IOException("Interrupted while creating links from " + sourceLocation + " to " + dest
                    + ": " + e.getMessage());
        } finally {
            IoSupport.closeQuietly(stdout);
            IoSupport.closeQuietly(stderr);
            IoSupport.closeQuietly(p);
        }

        // Link nested directories
        File[] children = sourceLocation.listFiles();
        for (int i = 0; i < children.length; i++) {
            if (children[i].isDirectory())
                link(children[i], dest, overwrite);
        }
    }

    // Normal file
    else {
        logger.trace("Creating link from " + sourceLocation + " to " + dest);
        Process p = null;
        StreamHelper stdout = null;
        StreamHelper stderr = null;
        StringBuffer error = new StringBuffer();
        try {
            p = createLinkFileProcess(sourceLocation, dest, overwrite);
            stdout = new StreamHelper(p.getInputStream());
            stderr = new LinkErrorStreamHelper(p.getErrorStream(), error);
            p.waitFor();
            stdout.stopReading();
            stderr.stopReading();
            // Find does not return with an error if -exec fails
            if (p.exitValue() != 0 || error.length() > 0) {
                logger.debug("Unable to create a link from " + sourceLocation + " to " + dest + ": " + error);
                copy(sourceLocation, dest, overwrite);
            }
            if (sourceLocation.length() != dest.length()) {
                logger.warn(
                        "Source " + sourceLocation + " and target " + dest + " do not have the same length");
                // TOOD: Why would this happen?
                // throw new IOException("Source " + sourceLocation + " and target " +
                // dest + " do not have the same length");
            }
        } catch (InterruptedException e) {
            throw new IOException(
                    "Interrupted while creating a link from " + sourceLocation + " to " + dest + ": " + error);
        } finally {
            IoSupport.closeQuietly(stdout);
            IoSupport.closeQuietly(stderr);
            IoSupport.closeQuietly(p);
        }
    }
    return dest;
}

From source file:org.jts.gui.exportCJSIDL.Export.java

public static void exportServiceSetCJSIDL(com.u2d.generated.ServiceSet serviceSet, File outputFile)
        throws ExportException {
    lastServiceSetExportPath = outputFile.getParentFile();

    java.util.List<File> files = new ArrayList<File>();
    File tmpfolder = null;/*from  w  ww . ja va2 s .com*/
    try {
        tmpfolder = org.jts.gui.importCJSIDL.Import.createTempDir();
    } catch (IOException ex) {
        Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
    }
    File tmpfile = null;

    RelationalList defs = serviceSet.getServiceDefs();
    com.u2d.app.Context.getInstance().getViewMechanism().message("Exporting ServiceDefs from ServiceSet... ");

    java.util.List<Object> items = defs.getItems();
    java.util.List<Object> jsidlDefs = new ArrayList<Object>();

    for (Object def : items) {
        if (def instanceof com.u2d.generated.ServiceDef) {

            org.jts.jsidl.binding.ServiceDef sd = org.jts.gui.jmatterToJAXB.ServiceDef
                    .convert((com.u2d.generated.ServiceDef) def);
            RemoveJSIDLPlus.removeJSIDLPlus(sd);
            jsidlDefs.add(sd);

            try {
                tmpfile = serializeJAXB(sd, tmpfolder.getCanonicalPath());
                files.add(tmpfile);
            } catch (IOException ex) {
                Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            String message = "Invalid object type found when processing serviceDefs: "
                    + def.getClass().getName();
            System.out.println(message);
            throw new ExportException(message);
        }
    }
    // this could replace the following section of code, if the antlr lib conflicts can be resolved
    //        try {
    //
    //            Conversion conv = new Conversion();
    //            System.err.println(tmpfolder.getCanonicalPath());
    //            System.err.println(outputFile.getCanonicalPath());
    //
    //            conv.convertFromJSIDL(tmpfolder.getCanonicalPath(), outputFile.getCanonicalPath());
    //
    //            com.u2d.app.Context.getInstance().getViewMechanism().message(
    //                    "ServiceDef Export Complete!  ");
    //        } catch (ConversionException e) {
    //            System.out.println("SAXException: ");
    //            e.printStackTrace();
    //        } catch (IOException ex) {
    //            String message = "Invalid path or file name when exporting a service def: " + outputFile;
    //            System.out.println(message);
    //            throw new ExportException(message, ex);
    //        }

    try {
        System.out.println("Initiating Conversion process 'convertFromJSIDL'");
        String execStr = ("java " + classpath
                + " org.jts.eclipse.conversion.cjsidl.Conversion \"convertFromJSIDL\" \""
                + tmpfolder.getCanonicalPath() + "\" \"" + outputFile.getCanonicalPath() + "\"");
        // if this is Linux or Mac OS X, we can't have double quotes around the
        // parameters, and classpath uses : instead of ;
        if (!System.getProperty("os.name").startsWith("Windows")) {
            execStr = execStr.replace("\"", "");
            execStr = execStr.replace(";", ":");
        }

        java.lang.Runtime rt = java.lang.Runtime.getRuntime();
        java.lang.Process p = rt.exec(execStr);
        StreamReader gerrors = new StreamReader(p.getErrorStream(), "ERROR");
        StreamReader goutput = new StreamReader(p.getInputStream(), "OUTPUT");
        gerrors.start();
        goutput.start();
        try {
            p.waitFor();
        } catch (InterruptedException ex) {
            Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
        }
        String errors = gerrors.getData();
        String log = goutput.getData();
        if (!errors.isEmpty()) {
            Logger.getLogger(Export.class.getName()).log(Level.SEVERE, errors);
            JOptionPane.showMessageDialog(GUI.getFrame(), errors, "CJSIDL Export Error",
                    JOptionPane.ERROR_MESSAGE);
        }

        System.out.println("Process exited with code = " + p.exitValue());
    } catch (IOException ex) {
        Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.blackducksoftware.integration.hub.docker.executor.Executor.java

public String[] executeCommand(final String commandString)
        throws IOException, InterruptedException, HubIntegrationException {
    final List<String> commandStringList = Arrays.asList(commandString.split(" "));
    final ProcessBuilder builder = new ProcessBuilder();
    builder.command(commandStringList.toArray(new String[commandStringList.size()]));
    builder.directory(new File("."));
    final Process process = builder.start();
    final boolean finished = process.waitFor(this.commandTimeout, TimeUnit.MILLISECONDS);
    if (!finished) {
        throw new HubIntegrationException(String.format(
                "Execution of command %s timed out (timeout: %d milliseconds)", commandString, commandTimeout));
    }/*from  www  . j a  v a  2s.c  om*/
    final int errCode = process.exitValue();
    if (errCode == 0) {
        logger.debug(String.format("Execution of command: %s: Succeeded", commandString));
    } else {
        throw new HubIntegrationException(
                String.format("Execution of command: %s: Error code: %d", commandString, errCode));
    }
    final InputStream inputStream = process.getInputStream();
    final String outputString = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    logger.debug(String.format("Command output:/n%s", outputString));
    return outputString.split(System.lineSeparator());
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public String getStringValue(String key) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("The Plist " + plist.getAbsolutePath() + " does not exist.");
    }/*from w w w. ja v  a2  s .  c  om*/

    try {
        String command = "/usr/libexec/PlistBuddy -c \"Print :" + key + "\" \"" + plist.getAbsolutePath()
                + "\"";

        System.out.println("[INFO] PlistBuddy Print command is: '" + command + "'.");

        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();

        int exitValue = p.exitValue();

        if (exitValue == 0) {
            InputStream is = p.getInputStream();
            try {
                return new Scanner(is, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
            } finally {
                closeQuietly(is);
            }
        }

        String errorMessage = "<n/a>";

        try {
            errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name()).useDelimiter("\\Z")
                    .next();
        } catch (Exception ex) {
            System.out.println("[ERROR] Exception caught during retrieving error message of command '" + command
                    + "': " + ex);
        }

        if (errorMessage.contains(":" + key + "\", Does Not Exist")) {
            // ugly string parsing above, but no other known way ...
            return null;
        }

        throw new IllegalStateException(
                "Execution of \"" + StringUtils.join(args, " ") + "\" command failed. Error message is: "
                        + errorMessage + ". Return code was: '" + exitValue + "'.");
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:nz.co.fortytwo.freeboard.server.util.ChartProcessor.java

/**
 * Executes a script which invokes GDAL and imagemagick to process the chart
 * into a tile pyramid//from  w  w w. j  a v  a2 s  . co  m
 * 
 * @param config2
 * @param chartFile
 * @param chartName
 * @param list 
 * @throws IOException 
 * @throws InterruptedException 
 */
@SuppressWarnings("static-access")
private void executeGdal(File chartFile, String chartName, List<String> argList, List<String> tilesList)
        throws IOException, InterruptedException {
    File processDir = chartFile.getParentFile();
    //mkdir $1
    //gdal_translate -of vrt -expand rgba $1.kap temp.vrt
    ProcessBuilder pb = new ProcessBuilder(argList);
    pb.directory(processDir);
    //pb.inheritIO();
    if (manager) {
        ForkWorker fork = new ForkWorker(textArea, pb);
        fork.execute();
        while (!fork.isDone()) {
            Thread.currentThread().sleep(500);
            //System.out.print(".");
        }
    } else {
        Process p = pb.start();
        p.waitFor();
        if (p.exitValue() > 0) {
            if (manager) {
                System.out.print("ERROR:gdal_translate did not complete normally\n");
            }
            logger.error("gdal_translate did not complete normally");
            return;
        } else {
            System.out.print("Completed gdal_translate\n");
        }
    }
    //gdal2tiles.py temp.vrt $1
    File tileDir = new File(processDir, chartName);
    tileDir.mkdir();
    pb = new ProcessBuilder("gdal2tiles.py", "temp.vrt", chartName);
    pb.directory(processDir);
    //pb.inheritIO();
    if (manager) {
        ForkWorker fork = new ForkWorker(textArea, pb);
        fork.execute();
        while (!fork.isDone()) {
            Thread.currentThread().sleep(500);
            //System.out.print(".");
        }
        System.out.print("Completed gdal2tiles\n");
    } else {
        Process p = pb.start();
        p.waitFor();
        if (p.exitValue() > 0) {
            if (manager) {
                System.out.print("ERROR:gdal2tiles did not complete normally\n");
            }
            logger.error("gdal2tiles did not complete normally");
            return;
        } else {
            System.out.print("Completed gdal2tiles\n");
        }
    }

    //now make images transparent
    //recurse dirs
    recurseDirs(tileDir);

}

From source file:org.jboss.test.cluster.httpsessionreplication.HttpSessionReplicationUnitTestCase.java

/**
 * Shuts down an instance of JBoss.//from w w w  . ja  va  2  s.c  o m
 * @throws Exception
 */
private void shutDownInstance(int instancenum) throws Exception {
    String command = getCommand(instancenum);

    getLog().debug("Going to execute:" + command);
    Process child = Runtime.getRuntime().exec(command);
    sleepThread(10 * 1000);
    getLog().debug("Process exit value=" + child.exitValue());
}