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.esminis.server.mariadb.server.MariaDbServerLauncher.java

void stop(Process process, File binary) {
    final int pid;
    synchronized (lock) {
        pid = managerProcess.getPid(binary);
        if (pid == 0) {
            return;
        }/*from  w  w w  .  j  a v  a  2 s .  c  o  m*/
        android.os.Process.sendSignal(pid, 15);
        for (int i = 0; i < 20; i++) {
            if (process != null) {
                try {
                    process.exitValue();
                    break;
                } catch (IllegalThreadStateException ignored) {
                }
            } else if ((pid != managerProcess.getPid(binary))) {
                break;
            }
            try {
                Thread.sleep(250);
            } catch (InterruptedException ignored) {
            }
        }
    }
}

From source file:com.telefonica.euro_iaas.sdc.util.CommandExecutorShellImpl.java

/**
 * <p>/* w w w .j  av a2 s.c  om*/
 * executeCommand
 * </p>
 * 
 * @param command
 *            a {@link java.lang.String} object.
 * @return an array of {@link java.lang.String} objects.
 * @throws java.io.IOException
 *             if any.
 */
public String[] executeCommand(String command) throws ShellCommandException {
    String[] outputCommand = new String[2];

    try {
        // Command is executed
        logger.log(Level.INFO, "Executing command: " + command);
        Process p = Runtime.getRuntime().exec(command);

        // Leemos la salida del comando
        outputCommand[0] = IOUtils.toString(p.getInputStream());
        outputCommand[1] = IOUtils.toString(p.getErrorStream());

        Integer exitValue = null;
        // this bucle is because sometimes the flows continues and the
        // comand
        // does not finish yet.
        while (exitValue == null) {
            try {
                exitValue = p.exitValue();
            } catch (IllegalThreadStateException e) {
                logger.log(Level.FINEST, "The command does not finished yet");
            }
        }

        if (!exitValue.equals(0)) {
            logger.log(Level.SEVERE, "Error executing command: " + outputCommand[1]);
            throw new ShellCommandException(outputCommand[1]);
        }
        return outputCommand;
    } catch (IOException e) {
        throw new ShellCommandException("Unexpected exception", e);
    }
}

From source file:com.raspoid.network.pushbullet.Pushbullet.java

/**
 * Upload a file on the Pushbullet servers.
 * @param url authorized url to post the file.
 * @param filePath the local path of the file to post.
 * @return the response from the HTTP request.
 *///  w  ww. j  a  v  a 2s  .  c o m
public int postFile(String url, String filePath) {
    String cmd = "curl -i -X POST " + url + " -F file=@" + filePath;
    Process process;
    try {
        process = Runtime.getRuntime().exec(cmd);
        process.waitFor();
        return process.exitValue();
    } catch (IOException | InterruptedException e) {
        throw new RaspoidException("[Pushbullet] Error when uploading a file.", e);
    }
}

From source file:org.fusesource.mq.itests.MQDistroTest.java

@Test
public void testWebConsoleAndClient() throws Exception {
    // send message via webconsole, consume from jms openwire
    HttpClient client = new HttpClient();

    // set credentials
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD));

    // need to first get the secret
    GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp");
    get.setDoAuthentication(true);/*from  w  ww  .j av a2  s.c o  m*/

    // Give console some time to start
    for (int i = 0; i < 20; i++) {
        Thread.currentThread().sleep(1000);
        try {
            i = client.executeMethod(get);
        } catch (java.net.ConnectException ignored) {
        }
    }
    assertEquals("get succeeded on " + get, 200, get.getStatusCode());

    String response = get.getResponseBodyAsString();
    final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\"";
    String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length());
    secret = secret.substring(0, secret.indexOf("\"/>"));

    final String destination = "validate.console.send";
    final String content = "Hi for the " + Math.random() + "' time";

    PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action");
    post.setDoAuthentication(true);
    post.addParameter("secret", secret);

    post.addParameter("JMSText", content);
    post.addParameter("JMSDestination", destination);
    post.addParameter("JMSDestinationType", "queue");

    // execute the send
    assertEquals("post succeeded, " + post, 302, client.executeMethod(post));

    // consume what we sent
    ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory()
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connection.start();
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination))
                .receive(10 * 1000);
        assertNotNull("got a message", textMessage);
        assertEquals("it is ours", content, textMessage.getText());
    } finally {
        connection.close();
    }

    // verify osgi registration of cf
    ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class);
    assertTrue(connectionFactory instanceof ActiveMQConnectionFactory);
    ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connectionFromOsgiFactory.start();
    try {
        assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName());
    } finally {
        connectionFromOsgiFactory.close();
    }

    // verify mq-client
    Process process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("producer worked, exit(0)?", 0, process.exitValue());

    process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("consumer worked, exit(0)?", 0, process.exitValue());

    System.out.println(executeCommand("activemq:bstat"));
}

From source file:org.apache.axis.components.compiler.Jikes.java

/**
 * Execute the compiler/*www . jav a2 s.c  om*/
 */
public boolean compile() throws IOException {

    List args = new ArrayList();
    // command line name
    args.add("jikes");
    // indicate Emacs output mode must be used
    args.add("+E");
    // avoid warnings
    // Option nowarn with one hyphen only
    args.add("-nowarn");

    int exitValue;
    ByteArrayOutputStream tmpErr = new ByteArrayOutputStream(OUTPUT_BUFFER_SIZE);

    try {
        Process p = Runtime.getRuntime().exec(toStringArray(fillArguments(args)));

        BufferedInputStream compilerErr = new BufferedInputStream(p.getErrorStream());

        StreamPumper errPumper = new StreamPumper(compilerErr, tmpErr);

        errPumper.start();

        p.waitFor();
        exitValue = p.exitValue();

        // Wait until the complete error stream has been read
        errPumper.join();
        compilerErr.close();

        p.destroy();

        tmpErr.close();
        this.errors = new ByteArrayInputStream(tmpErr.toByteArray());

    } catch (InterruptedException somethingHappened) {
        log.debug("Jikes.compile():SomethingHappened", somethingHappened);
        return false;
    }

    // Jikes returns 0 even when there are some types of errors.
    // Check if any error output as well
    // Return should be OK when both exitValue and
    // tmpErr.size() are 0 ?!
    return ((exitValue == 0) && (tmpErr.size() == 0));
}

From source file:org.atilika.kuromoji.server.KuromojiServer.java

private String getViterbiSVG(String dot) {
    Process process = null;
    try {//  w  w w . j  a  va 2 s  .  c  o  m
        log.info("Running " + DOT_COMMAND);
        process = Runtime.getRuntime().exec(DOT_COMMAND);
        process.getOutputStream().write(dot.getBytes("utf-8"));
        process.getOutputStream().close();

        InputStream input = process.getInputStream();
        String svg = new Scanner(input, "utf-8").useDelimiter("\\A").next();

        int exitValue = process.exitValue();

        log.debug("Read " + svg.getBytes("utf-8").length + " bytes of SVG output");
        log.info("Process exited with exit value " + exitValue);
        return svg;
    } catch (IOException e) {
        log.error("Error running process " + process, e.getCause());
        return null;
    } finally {
        if (process != null) {
            log.info("Destroying process " + process);
            process.destroy();
        }
    }
}

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

private void doCheckScriptPath() {

    String scriptPath = scriptPathField.getText().trim();

    BackgroundTask<Either<String, String>, Void> task = new BackgroundTask<Either<String, String>, Void>(
            "Checking...", true) {
        @Override/* w  w  w .ja v  a2s .c o  m*/
        public Either<String, String> generateResult(Closure<Void> arg0) throws Exception {

            ProcessBuilder findRScript = new ProcessBuilder(scriptPath, "--version");

            Process p = findRScript.start();

            while (!p.waitFor(1000, TimeUnit.MILLISECONDS)) {
                if (backgroundRunner.isCancelRequested()) {
                    p.destroy();
                    throw new CancellationException();
                }
            }

            if (0 == p.exitValue()) {
                String output = Algorithms.readContent(null, p.getInputStream());
                versionNumber = Algorithms.readContent(null, p.getErrorStream());
                return Either.right(output);
            }

            errorOutput = Algorithms.readContent("Error Output:", p.getErrorStream());
            if (errorOutput.isEmpty()) {
                errorOutput = "No error output available";
                return Either.left(errorOutput);
            }
            return Either.left(errorOutput);
        }

        @Override
        public void onException(Throwable t) {
            onScriptPathChecked.accept(Either.left(t));
        }

        @Override
        public void onCancel(CancellationException ce) {
            onScriptPathChecked.accept(Either.left(ce));
        }

        @Override
        public void onTaskComplete(Either<String, String> either) {
            if (either.isLeft()) {
                MsgBox.error(RscriptFinderPanel.this, either.left(), "Error Output");
            } else {
                TrialDesignPreferences.getInstance().setRscriptPath(scriptPath);
                onScriptPathChecked.accept(Either.right(scriptPath));
                checkOutput = either.right();
            }
        }
    };

    backgroundRunner.runBackgroundTask(task);
}

From source file:de.fau.cs.osr.hddiff.perfsuite.RunXyDiff.java

private String runXyDiff(File fileA, File fileB, File fileDiff) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(new String[] { xyDiffBin, "-o", fileDiff.getAbsolutePath(),
            fileA.getAbsolutePath(), fileB.getAbsolutePath() });

    try (StringWriter w = new StringWriter()) {
        Process p = pb.start();
        new ThreadedStreamReader(p.getErrorStream(), "ERROR", w);
        new ThreadedStreamReader(p.getInputStream(), "OUTPUT", w);

        try {/*  w  w w .j  av  a2  s  .c  o  m*/
            TimeoutProcess.waitFor(p, 2000);
        } catch (Exception e) {
            throw new XyDiffException(e);
        }

        if (p.exitValue() == 0)
            return w.toString();
        else
            throw new XyDiffException(w.toString());
    }
}

From source file:org.fcrepo.importexport.integration.ExecutableJarIT.java

@Test
public void testImport() throws FcrepoOperationFailedException, IOException, InterruptedException {
    final String exportPath = TARGET_DIR + "/" + UUID.randomUUID() + "/testPeartreeAmbiguity";
    final String parentTitle = "parent";
    final String childTitle = "child";
    final String binaryText = "binary";

    final URI parent = URI.create(serverAddress + UUID.randomUUID());
    final URI child = URI.create(parent.toString() + "/child");
    final URI binary = URI.create(child + "/binary");
    assertEquals(SC_CREATED, create(parent).getStatusCode());
    assertEquals(SC_CREATED, create(child).getStatusCode());
    assertEquals(SC_NO_CONTENT, client.patch(parent).body(insertTitle(parentTitle)).perform().getStatusCode());
    assertEquals(SC_NO_CONTENT, client.patch(child).body(insertTitle(childTitle)).perform().getStatusCode());
    assertEquals(SC_CREATED,/*from www .jav a2  s.  c o m*/
            client.put(binary).body(new ByteArrayInputStream(binaryText.getBytes("UTF-8")), "text/plain")
                    .perform().getStatusCode());

    // Run an export process
    final Process exportProcess = startJarProcess("-m", "export", "-d", exportPath, "-b", exportPath, "-r",
            parent.toString(), "-u", "fedoraAdmin:password");

    // Verify
    assertTrue("Process did not exit before timeout!", exportProcess.waitFor(1000, TimeUnit.SECONDS));
    assertEquals("Did not exit with success status!", 0, exportProcess.exitValue());

    // Remove the resources
    client.delete(parent).perform();
    final FcrepoResponse getResponse = client.get(parent).perform();
    assertEquals("Resource should have been deleted!", SC_GONE, getResponse.getStatusCode());
    assertEquals("Failed to delete the tombstone!", SC_NO_CONTENT,
            client.delete(getResponse.getLinkHeaders("hasTombstone").get(0)).perform().getStatusCode());

    // Run the import process
    final Process importProcess = startJarProcess("-m", "import", "-d", exportPath, "-b", exportPath, "-s",
            parent.toString(), "-r", parent.toString(), "-u", "fedoraAdmin:password");

    // Verify
    assertTrue("Process did not exit before timeout!", importProcess.waitFor(1000, TimeUnit.SECONDS));
    assertEquals("Did not exit with success status!", 0, importProcess.exitValue());

    assertHasTitle(parent, parentTitle);
    assertHasTitle(child, childTitle);
    assertEquals("Binary should have been imported!", binaryText,
            IOUtils.toString(client.get(binary).perform().getBody(), "UTF-8"));

}

From source file:it.cnr.icar.eric.client.ui.thin.security.SecurityUtil.java

/** Generate a key pair and add it to the keystore.
  *//from   w  ww.j  a va 2  s.c  o m
  * @param alias
  * @return
  *     A HashSet of X500PrivateCredential objects.
  * @throws Exception
  */
private Set<Object> generateCredentials(String alias) throws JAXRException {

    try {
        HashSet<Object> credentials = new HashSet<Object>();

        // The keystore file is at ${jaxr-ebxml.home}/security/keystore.jks. If
        // the 'jaxr-ebxml.home' property is not set, ${user.home}/jaxr-ebxml/ is
        // used.
        File keyStoreFile = KeystoreUtil.getKeystoreFile();
        String storepass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storepass",
                "ebxmlrr");
        String keypass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.keypass");
        if (keypass == null) {
            // keytool utility requires a six character minimum password.
            // pad passwords with < six chars
            if (alias.length() >= 6) {
                keypass = alias;
            } else if (alias.length() == 5) {
                keypass = alias + "1";
            } else if (alias.length() == 4) {
                keypass = alias + "12";
            } else if (alias.length() == 3) {
                keypass = alias + "123";
            }
            // alias should have at least 3 chars
        }
        log.debug("Generating key pair for '" + alias + "' in '" + keyStoreFile.getAbsolutePath() + "'");

        // When run in S1WS 6.0, this caused some native library errors. It appears that S1WS
        // uses different encryption spis than those in the jdk. 
        //            String[] args = {
        //                "-genkey", "-alias", uid, "-keypass", "keypass",
        //                "-keystore", keyStoreFile.getAbsolutePath(), "-storepass",
        //                new String(storepass), "-dname", "uid=" + uid + ",ou=People,dc=sun,dc=com"
        //            };
        //            KeyTool keytool = new KeyTool();
        //            ByteArrayOutputStream keytoolOutput = new ByteArrayOutputStream();
        //            try {
        //                keytool.run(args, new PrintStream(keytoolOutput));
        //            }
        //            finally {
        //                log.info(keytoolOutput.toString());
        //            }
        // To work around this problem, generate the key pair using keytool (which executes
        // in its own vm. Note that all the parameters must be specified, or keytool prompts
        // for their values and this 'hangs'
        String[] cmdarray = { "keytool", "-genkey", "-alias", alias, "-keypass", keypass, "-keystore",
                keyStoreFile.getAbsolutePath(), "-storepass", storepass, "-dname", "cn=" + alias };
        Process keytool = Runtime.getRuntime().exec(cmdarray);
        try {
            keytool.waitFor();
        } catch (InterruptedException ie) {
        }
        if (keytool.exitValue() != 0) {
            log.error(WebUIResourceBundle.getInstance().getString("message.keytoolCommandFailedDetails"));
            Reader reader = new InputStreamReader(keytool.getErrorStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            while (bufferedReader.ready()) {
                log.error(bufferedReader.readLine());
            }
            throw new JAXRException(
                    WebUIResourceBundle.getInstance().getString("excKeyToolCommandFail") + keytool.exitValue());
        }
        log.debug("Key pair generated successfully.");

        // After generating the keypair in the keystore file, we have to reload
        // SecurityUtil's KeyStore object.
        KeyStore keyStore = it.cnr.icar.eric.client.xml.registry.util.SecurityUtil.getInstance().getKeyStore();
        keyStore.load(new FileInputStream(keyStoreFile), storepass.toCharArray());

        credentials.add(it.cnr.icar.eric.client.xml.registry.util.SecurityUtil.getInstance()
                .aliasToX500PrivateCredential(alias));

        return credentials;
    } catch (Exception e) {
        if (e instanceof JAXRException) {
            throw (JAXRException) e;
        } else {
            throw new JAXRException(e);
        }
    }
}