Example usage for java.lang Process destroy

List of usage examples for java.lang Process destroy

Introduction

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

Prototype

public abstract void destroy();

Source Link

Document

Kills the process.

Usage

From source file:com.isecpartners.gizmo.ThirdIdea.java

public String exec(String command_string, String[] env) {
    StringBuffer display_text = new StringBuffer();
    try {/*from  w  ww  .  j  ava2  s.c o m*/
        String shell = defaultShellField.getText();
        Process proc = null;

        command_string = apply_macros(command_string);

        if (System.getProperty("os.name").toUpperCase().contains("WINDOWS")) {
            String[] args = translateCommandline(shell + " " + command_string);
            proc = Runtime.getRuntime().exec(args, env);
        } else {
            String[] shell_pieces = shell.split("\\s+");
            String args[] = new String[shell_pieces.length + 1];
            System.arraycopy(shell_pieces, 0, args, 0, shell_pieces.length);
            args[args.length - 1] = command_string;
            proc = Runtime.getRuntime().exec(args, env);
        }
        String out = readOutput(proc);
        String err = readError(proc);
        proc.waitFor();
        proc.destroy();
        display_text.append("\n\n" + out + err);
    } catch (InterruptedException ex) {
        Logger.getLogger(ThirdIdea.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ThirdIdea.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        GizmoView.log(e.toString());
    }

    return display_text.toString();
}

From source file:org.wso2.appserver.integration.tests.wsdl2java.HelloServiceCodeGenTestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = "wso2.as", description = "test the generated source by running relevant main client", dependsOnMethods = "testExtractGeneratedCode")
public void testGeneratedSource() throws Exception {
    String resourcePath = FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "AS"
            + File.separator + "codegen";

    String clientClassPath = resourcePath + File.separator + "HelloServiceClient.txt";
    String buildXMLPath = resourcePath + File.separator + "build.xml";
    List<File> filePath = getAllJavaFiles(new File(codeGenPath));
    String generatedJavaFileLocation;

    if (filePath.size() > 0) {
        generatedJavaFileLocation = filePath.get(0).getParent() + File.separator + "HelloServiceClient.java";
    } else {/*from   w  w w.  ja va2  s. c  om*/
        throw new Exception("Code generation failed");
    }

    FileManipulator.copyFile(new File(clientClassPath), new File(generatedJavaFileLocation));
    axis2Home = System.getProperty(ServerConstants.CARBON_HOME);

    log.info("AXIS2_HOME - " + axis2Home);
    System.setProperty("AXIS2_HOME", axis2Home);

    editBuildXmlFile(buildXMLPath);
    Process tempProcessAnt = null;
    try {
        if (new File(generatedJavaFileLocation).exists()) {
            String[] cmdArray;
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {

                cmdArray = new String[] { "cmd.exe", "/c", "ant" };
                tempProcessAnt = Runtime.getRuntime().exec(cmdArray, null,
                        new File(codeGenPath + File.separator + "generated-sources"));

            } else {
                cmdArray = new String[] { "ant" };
                System.setProperty("user.dir", codeGenPath);
                tempProcessAnt = Runtime.getRuntime().exec(cmdArray, null,
                        new File(codeGenPath + File.separator + "generated-sources"));
            }

            boolean status = waitForMessage(tempProcessAnt.getInputStream(), "Hello World, Krishantha");
            assertTrue(status, "Invocation successful");

        }
    } finally {
        if (tempProcessAnt != null) {
            tempProcessAnt.destroy();
        }
    }
}

From source file:com.symbian.driver.plugins.romflash.Activator.java

public boolean FlashRom(String romLocation) {

    try {/*from   w  w  w  .j  a  v  a2s  .c  om*/
        File rom = new File(romLocation);
        if (method.compareToIgnoreCase("serial") == 0) {
            if (!(switchOff() && switchOn())) {
                LOGGER.log(Level.SEVERE, "Could not reboot device, so No rom flashing.");
                return false;
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File trgtTestFile = JarUtils.extractResource(Activator.class, "/resource/trgtest.exe");
            if (trgtTestFile.isFile()) {
                ProcessBuilder ld = new ProcessBuilder(trgtTestFile.getAbsolutePath(), portNumber,
                        rom.getCanonicalPath());
                ld.directory(trgtTestFile.getParentFile());
                Process pp = ld.start();
                LOGGER.log(Level.INFO, "started trgtest process");
                BufferedReader br = new BufferedReader(new InputStreamReader(pp.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                    LOGGER.log(Level.INFO, line);
                }
                //String answer = sb.toString();

                try {
                    LOGGER.log(Level.INFO, "going to wait now for trgtest to finish");
                    pp.waitFor();
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for trgtest.exe to finish.");
                }
                LOGGER.log(Level.INFO, "trgtest returned: " + pp.exitValue());
                pp.destroy();

            } else {
                LOGGER.log(Level.SEVERE, "Could not find trgtest.exe file.");
            }
        } else // usb rom loading
        {
            // switch the device off...
            switchOff();
            List<File> lis1 = Arrays.asList(File.listRoots());
            // get reboot plugin, and reboot the device
            switchOn(); // or just switch on as things may be
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File[] listRoots2 = File.listRoots();
            // find the drive that made the difference!!
            File diff = null;
            for (File root : listRoots2) {
                if (!lis1.contains(root)) // found new drive
                {
                    diff = root;
                    break;
                }
            }
            File romfl = new File(diff, rom.getName());
            romfl.delete();
            File aCopyFrom = new File(rom.getCanonicalPath());
            FileChannel lSrcChannel = new FileInputStream(aCopyFrom).getChannel();
            FileChannel lDstChannel = new FileOutputStream(romfl).getChannel();
            lDstChannel.transferFrom(lSrcChannel, 0, lSrcChannel.size());
            lSrcChannel.close();
            lDstChannel.close();

            File syncFile = JarUtils.extractResource(Activator.class, "/resource/sync.exe");
            if (syncFile.isFile()) {

                ProcessBuilder ld = new ProcessBuilder(syncFile.getAbsolutePath(), "-r", "-e", diff.toString());

                ld.directory(syncFile.getParentFile());
                ld.start();
                // wait 10 seconds for the rom to load ...
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
                }
            } else {
                LOGGER.log(Level.SEVERE, "Could not find sync.exe file.");
            }
        }
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE, "Could not flash ROM " + lIOException.getMessage());
        return false;
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
    }
    return true;
}

From source file:com.netease.dagger.BrowserEmulator.java

/**
 * Mimic system-level keyboard event with String
 * //from   ww  w.  j  av  a2 s.  c o  m
 * @param text
 * 
 */
public void inputKeyboard(String text) {
    String cmd = System.getProperty("user.dir") + "\\res\\SeleniumCommand.exe" + " sendKeys " + text;

    Process p = null;
    try {
        p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        p.destroy();
    }
    logger.info("Pressed key with string " + text);
}

From source file:com.isecpartners.gizmo.FourthIdea.java

public String exec(String command_string, String[] env, byte[] requestBuf) {
    StringBuffer display_text = new StringBuffer();
    String out = "";
    try {//from w w w  . j  av  a2  s  . c  om
        String shell = defaultShellField.getText();
        Process proc = null;

        command_string = apply_macros(command_string);

        if (System.getProperty("os.name").toUpperCase().contains("WINDOWS")) {
            String[] args = translateCommandline(shell + " " + command_string);
            proc = Runtime.getRuntime().exec(args, env);
        } else {
            String[] shell_pieces = shell.split("\\s+");
            String args[] = new String[shell_pieces.length + 1];
            System.arraycopy(shell_pieces, 0, args, 0, shell_pieces.length);
            args[args.length - 1] = command_string;
            proc = Runtime.getRuntime().exec(args, env);
        }
        out = readOutput(proc);
        String err = readError(proc);
        proc.waitFor();
        proc.destroy();
        display_text.append("\n\n" + out + err);
        appendToOutputArea(display_text.toString());
    } catch (InterruptedException ex) {
        Logger.getLogger(FourthIdea.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FourthIdea.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        GizmoView.log(e.toString());
    }

    return out;
}

From source file:com.evolveum.midpoint.test.util.Lsof.java

private String execLsof(int pid) throws IOException, InterruptedException {
    Process process = null;
    String output = null;//from ww  w.  j  ava  2  s.c o m
    try {
        process = Runtime.getRuntime().exec(new String[] { "lsof", "-p", Integer.toString(pid) });
        InputStream inputStream = process.getInputStream();
        output = IOUtils.toString(inputStream, "UTF-8");
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IllegalStateException("Lsof process ended with error (" + exitCode + ")");
        }
    } finally {
        if (process != null) {
            try {
                process.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                process.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                process.getErrorStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            process.destroy();
        }
    }
    return output;
}

From source file:org.knime.knip.ilastik.nodes.headless.IlastikHeadlessNodeModel.java

/**
 * @param exec//from   w ww .j a va2  s .c  om
 * @throws IOException
 * @throws InterruptedException
 * @throws CanceledExecutionException
 * @throws URISyntaxException
 */
private void runIlastik(final String tmpDirPath, final List<String> inFiles, final ExecutionContext exec)
        throws IOException, InterruptedException {

    // get path of ilastik
    final String path = IlastikPreferencePage.getPath();

    String outpath;
    try {
        outpath = FileUtil.resolveToPath(FileUtil.toURL(m_pathToIlastikProjectFileModel.getStringValue()))
                .toAbsolutePath().toString();
    } catch (InvalidPathException | URISyntaxException e) {
        throw new IllegalArgumentException("The Path to the project file could not be resolved: " + e, e);
    }
    if (outpath == null) {
        throw new IllegalArgumentException("The Path to the project file could not be resolved.");
    }

    // DO NOT TOUCH THIS ORDER!
    inFiles.add(0, path);
    inFiles.add(1, "--headless");
    inFiles.add(2, "--project=".concat(outpath));
    inFiles.add(3, "--output_format=multipage tiff");
    inFiles.add(4, "--output_filename_format=".concat(tmpDirPath).concat("{nickname}" + RESULT_IMG_SUFFIX));

    KNIPGateway.log().debug("Executing ilastik with " + String.join(", ", inFiles));

    // build process with project and images
    ProcessBuilder pB = new ProcessBuilder(inFiles);

    // limit cpu + memory usage
    final Map<String, String> env = pB.environment();
    env.put("LAZYFLOW_THREADS", String.valueOf(m_ilastikThreadCount.getIntValue()));
    env.put("LAZYFLOW_TOTAL_RAM_MB", String.valueOf(m_ilastikMaxMemory.getIntValue()));

    // run ilastik
    Process p = pB.start();

    // write ilastik output to knime console
    redirectToKnimeConsole(p.getInputStream(), DirectedLogServiceFactory.debug());
    redirectToKnimeConsole(p.getErrorStream(), DirectedLogServiceFactory.error());

    try {
        while (!p.waitFor(500, TimeUnit.MILLISECONDS)) {
            exec.checkCanceled();
        }
    } catch (CanceledExecutionException cee) {
        KNIPGateway.log().error("Execution canceled, closing Ilastik now.");
        p.destroy();
    }

    // 0 indicates successful execution
    if (p.exitValue() != 0) {
        throw new IllegalStateException("Execution of ilastik was not successful.");
    }
}

From source file:c3.ops.priam.resources.BackupServlet.java

/**
 * Convert SSTable2Json and search for given key
 *//*from   w  w  w.ja  v a2s.c o  m*/
public void checkSSTablesForKey(String rowkey, String keyspace, String cf, String fileExtension,
        String jsonFilePath) throws Exception {
    try {
        logger.info("Starting SSTable2Json conversion ...");
        //Setting timeout to 10 Mins
        long TIMEOUT_PERIOD = 10l;
        String unixCmd = formulateCommandToRun(rowkey, keyspace, cf, fileExtension, jsonFilePath);

        String[] cmd = { "/bin/sh", "-c", unixCmd.toString() };
        final Process p = Runtime.getRuntime().exec(cmd);

        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int returnCode = p.waitFor();
                return returnCode;
            }
        };

        ExecutorService exeService = Executors.newSingleThreadExecutor();
        try {
            Future<Integer> future = exeService.submit(callable);
            int returnVal = future.get(TIMEOUT_PERIOD, TimeUnit.MINUTES);
            if (returnVal == 0)
                logger.info("Finished SSTable2Json conversion and search.");
            else
                logger.error("Error occurred during SSTable2Json conversion and search.");
        } catch (TimeoutException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
            throw e;
        } finally {
            p.destroy();
            exeService.shutdown();
        }

    } catch (IOException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:ca.weblite.jdeploy.JDeploy.java

private void init_old(String commandName) throws IOException {
    try {/*  w w  w .  j a  v a2 s  .  c  o m*/
        File packageJson = new File(directory, "package.json");
        if (!packageJson.exists()) {
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(npm, "init");
            pb.inheritIO();
            final Process p = pb.start();
            Timer t = new Timer();

            TimerTask tt = new TimerTask() {

                @Override
                public void run() {
                    if (packageJson.exists()) {
                        p.destroy();
                        cancel();
                    }
                }

            };
            t.schedule(tt, new Date(System.currentTimeMillis() + 1000), 1000);

            int code = p.waitFor();

            if (!packageJson.exists() && code != 0) {
                System.err.println("Stopped init because npm init failed");
                System.exit(code);
            }
        }

        String pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        // For some reason it never sticks in the package.json file the first time
        pkgJsonStr = FileUtils.readFileToString(packageJson, "UTF-8");
        if (!pkgJsonStr.contains("shelljs")) {
            System.out.println("Installing shelljs");
            ProcessBuilder pb = new ProcessBuilder();
            pb.inheritIO();
            pb.command(npm, "install", "shelljs", "--save");
            Process p = pb.start();
            int result = p.waitFor();
            if (result != 0) {
                System.err.println("Failed to install shelljs");
                System.exit(result);
            }
        }

        JSONParser parser = new JSONParser();
        Map contents = parser.parseJSON(new StringReader(pkgJsonStr));
        if (commandName == null) {
            commandName = (String) contents.get("name");
        }

        if (!contents.containsKey("bin")) {
            contents.put("bin", new HashMap());
        }
        Map bins = (Map) contents.get("bin");

        if (!bins.values().contains(getBinDir() + "/jdeploy.js")) {
            contents.put("preferGlobal", true);
            bins.put(commandName, getBinDir() + "/jdeploy.js");
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

        if (!contents.containsKey("files")) {
            contents.put("files", new ArrayList());
        }
        List files = (List) contents.get("files");
        if (!files.contains(getBinDir())) {
            files.add(getBinDir());
            Result res = Result.fromContent(contents);
            FileUtils.writeStringToFile(packageJson, res.toString(), "UTF-8");
        }

    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.Execute.java

/**
 * Runs a process defined by the command line and returns its exit status.
 *
 * @return the exit status of the subprocess or <code>INVALID</code>.
 * @exception java.io.IOException The exception is thrown, if launching
 *            of the subprocess failed.// ww  w  . j a va2 s.c om
 */
public int execute() throws IOException {
    if (workingDirectory != null && !workingDirectory.exists()) {
        throw new ProvisionerException(workingDirectory + " doesn't exist.");
    }
    final Process process = launch(getCommandline(), getEnvironment(), workingDirectory, useVMLauncher);
    try {
        streamHandler.setProcessInputStream(process.getOutputStream());
        streamHandler.setProcessOutputStream(process.getInputStream());
        streamHandler.setProcessErrorStream(process.getErrorStream());
    } catch (IOException e) {
        process.destroy();
        throw e;
    }
    streamHandler.start();

    try {

        waitFor(process);

        streamHandler.stop();
        closeStreams(process);

        return getExitValue();
    } catch (ThreadDeath t) {
        // #31928: forcibly kill it before continuing.
        process.destroy();
        throw t;
    } finally {
    }
}