Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

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

Click Source Link

Usage

From source file:org.josso.tooling.gshell.install.installer.WeblogicInstaller.java

@Override
public void installComponentFromSrc(JOSSOArtifact artifact, boolean replace) throws InstallException {

    try {//from  ww  w .ja  v a 2  s. c  o  m

        if (!artifact.getBaseName().contains(this.wlVersionStr))
            return;

        // Prepare paths

        FileObject homeDir = getFileSystemManager().resolveFile(System.getProperty("josso-gsh.home"));
        FileObject srcDir = homeDir
                .resolveFile("dist/agents/src/josso-weblogic" + wlVersionStr + "-agent-mbeans-src");
        FileObject jossoLibDir = homeDir.resolveFile("dist/agents/bin");
        FileObject thrdPartyLibDir = jossoLibDir.resolveFile("3rdparty");

        FileObject descriptorFile = srcDir.resolveFile(
                "org/josso/wls" + wlVersionStr + "/agent/mbeans/JOSSOAuthenticatorProviderImpl.xml");
        FileObject mbeanFile = this.targetJOSSOMBeansDir
                .resolveFile("josso-weblogic" + wlVersionStr + "-agent-mbeans.jar");

        FileObject javaDir = getFileSystemManager().resolveFile(System.getProperty("java.home") + "/../");
        FileObject javaToolsFile = javaDir.resolveFile("lib/tools.jar");
        FileObject javaFile = javaDir.resolveFile("bin/java");

        getPrinter().printMsg("Using JAVA JDK at " + getLocalFilePath(javaDir));

        if (!javaDir.exists()) {
            getPrinter().printActionErrStatus("Generate", "WL MBeans Descriptors",
                    "JAVA JDK is required : " + getLocalFilePath(javaDir));
            throw new InstallException("JAVA JDK is required for WL : " + getLocalFilePath(javaDir));
        }

        if (!javaToolsFile.exists()) {
            getPrinter().printActionErrStatus("Generate", "WL MBeans Descriptors",
                    "JAVA JDK is required : " + getLocalFilePath(javaToolsFile));
            throw new InstallException("JAVA JDK is required for WL : " + getLocalFilePath(javaToolsFile));
        }

        if (!javaToolsFile.exists()) {
            getPrinter().printActionErrStatus("Generate", "WL MBeans Descriptors",
                    "JAVA JDK is required : " + getLocalFilePath(javaToolsFile));
            throw new InstallException("JAVA JDK is required for WL : " + getLocalFilePath(javaToolsFile));
        }

        // Java CMD and Class path :
        String javaCmd = getLocalFilePath(javaFile);

        String classpath = "";
        String pathSeparator = "";

        // JOSSO Jars
        for (FileObject child : jossoLibDir.getChildren()) {
            if (!child.getName().getBaseName().endsWith(".jar"))
                continue;

            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        // JOSSO 3rd party Jars
        for (FileObject child : thrdPartyLibDir.getChildren()) {
            if (!child.getName().getBaseName().endsWith(".jar"))
                continue;

            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        for (FileObject child : this.targetDir.resolveFile("server/lib").getChildren()) {
            if (!child.getName().getBaseName().endsWith(".jar"))
                continue;
            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        classpath += pathSeparator + getLocalFilePath(javaToolsFile);
        pathSeparator = System.getProperty("path.separator");

        for (FileObject child : javaDir.resolveFile("jre/lib").getChildren()) {
            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        //  ----------------------------------------------------------------
        // 1. Create the MBean Descriptor Files
        //  ----------------------------------------------------------------

        {
            /*
               <argument>-Dfiles=${basedir}/target/generated-sources</argument>
               <argument>-DMDF=${project.build.directory}/generated-sources/org/josso/wls92/agent/mbeans/JOSSOAuthenticatorProviderImpl.xml</argument>
               <argument>-DtargetNameSpace=urn:org:josso:wls92:agent:mbeans</argument>
               <argument>-DpreserveStubs=false</argument>
               <argument>-DcreateStubs=true</argument>
               <argument>-classpath</argument>
               <classpath/>
               <argument>weblogic.management.commo.WebLogicMBeanMaker</argument>
            */

            ProcessBuilder generateMBeanDescriptorProcessBuilder = new ProcessBuilder(javaCmd,
                    "-Dfiles=" + getLocalFilePath(srcDir), "-DMDF=" + getLocalFilePath(descriptorFile),
                    "-DtargetNameSpace=urn:org:josso:wls" + wlVersionStr + ":agent:mbeans",
                    "-DpreserveStubs=false", "-DcreateStubs=true", "-classpath", classpath,
                    "weblogic.management.commo.WebLogicMBeanMaker");

            log.info("Executing: " + generateMBeanDescriptorProcessBuilder.command());

            Process generateMBeanDescriptorProcess = generateMBeanDescriptorProcessBuilder.start();

            PumpStreamHandler generateMBeanHandler = new PumpStreamHandler(getPrinter().getIo().inputStream,
                    getPrinter().getIo().outputStream, getPrinter().getIo().errorStream);
            generateMBeanHandler.attach(generateMBeanDescriptorProcess);
            generateMBeanHandler.start();

            log.debug("Waiting for process to exit...");
            int statusDescr = generateMBeanDescriptorProcess.waitFor();

            log.info("Process exited w/status: " + statusDescr);

            generateMBeanHandler.stop();
            getPrinter().printActionOkStatus("Generate", "WL MBeans Descriptors", "");
        }

        //  ----------------------------------------------------------------
        // 2. Create the MBean JAR File
        //  ----------------------------------------------------------------
        {
            /*
            <argument>-Dfiles=${project.build.directory}/generated-sources</argument>
            <argument>-DMJF=${project.build.directory}/josso-weblogic92-agent-mbeans-${pom.version}.jar</argument>
            <argument>-DpreserveStubs=false</argument>
            <argument>-DcreateStubs=true</argument>
            <argument>-classpath</argument>
            <classpath/>
            <argument>weblogic.management.commo.WebLogicMBeanMaker</argument>
                    
            */

            ProcessBuilder generateMBeanJarProcessBuilder = new ProcessBuilder(javaCmd,
                    "-Dfiles=" + getLocalFilePath(srcDir), "-DMJF=" + getLocalFilePath(mbeanFile),
                    "-DpreserveStubs=false", "-DcreateStubs=true", "-classpath", classpath,
                    "weblogic.management.commo.WebLogicMBeanMaker");

            log.info("Executing: " + generateMBeanJarProcessBuilder.command());

            Process generateMBeanJarProcess = generateMBeanJarProcessBuilder.start();

            PumpStreamHandler generateMBeanJarHandler = new PumpStreamHandler(getPrinter().getIo().inputStream,
                    getPrinter().getIo().outputStream, getPrinter().getIo().errorStream);
            generateMBeanJarHandler.attach(generateMBeanJarProcess);
            generateMBeanJarHandler.start();

            log.debug("Waiting for process to exit...");
            int statusJar = generateMBeanJarProcess.waitFor();
            log.info("Process exited w/status: " + statusJar);

            generateMBeanJarHandler.stop();
            getPrinter().printActionOkStatus("Generate", "WL MBeans JAR", getLocalFilePath(mbeanFile));

        }
    } catch (Exception e) {
        getPrinter().printActionErrStatus("Generate", "WL MBeans", e.getMessage());
        throw new InstallException("Cannot generate WL MBeans Descriptors : " + e.getMessage(), e);
    }

    // 2. Create the MBean JAR File

    // 3. Install the file in the target platform

    // We need to create WL Mbeans using MBean Maker!

}

From source file:org.roqmessaging.management.HostConfigManager.java

/**
 * @param qName the name of queue for which we need to create the scaling process
 * @param port the listener port on wich the sclaing process will scubscribe to configuration update
 * @return true if the creation was OK/*from   w w w  .  j  av  a2s . c om*/
 */
private boolean startNewScalingProcess(String qName) {
    if (this.qMonitorStatMap.containsKey(qName)) {
        //1. Compute the stat monitor port+2
        int basePort = this.serializationUtils.extractBasePort(this.qMonitorStatMap.get(qName));
        basePort += 2;
        //2. Check wether we need to launch it locally or in its own process
        if (this.properties.isQueueInHcmVm()) {
            logger.info("Starting the scaling process  for queue " + qName + ", using a listener port= "
                    + basePort + ", GCM =" + this.properties.getGcmAddress());
            //Local startup in the same VM as the host config Monitor
            ScalingProcess scalingProcess = new ScalingProcess(this.properties.getGcmAddress(), qName,
                    basePort);
            //Here is the problem we still do not have registred the queue at the GCM
            //scalingProcess.subscribe();
            // Launch the thread
            new Thread(scalingProcess).start();
        } else {
            //Start in its own VM
            // 2. Launch script
            try {
                ProcessBuilder pb = new ProcessBuilder("java",
                        "-Djava.library.path=" + System.getProperty("java.library.path"), "-cp",
                        System.getProperty("java.class.path"), ScalingProcessLauncher.class.getCanonicalName(),
                        this.properties.getGcmAddress(), qName, new Integer((basePort)).toString());
                logger.debug("Starting: " + pb.command());
                final Process process = pb.start();
                pipe(process.getErrorStream(), System.err);
                pipe(process.getInputStream(), System.out);
            } catch (IOException e) {
                logger.error("Error while executing script", e);
                return false;
            }
        }
        //4. Add the configuration information
        logger.debug("Storing scaling process information");
        this.qScalingProcessAddr.put(qName, (basePort + 1));
    } else {
        return false;
    }
    return true;
}

From source file:org.roqmessaging.management.HostConfigManager.java

/**
 * Start a new Monitor process//w  w w.j  a  v  a 2 s  .co  m
 * <p>
 * 1. Check the number of local monitor present in the host 2. Start a new
 * monitor with port config + nMonitor*4 because the monitor needs to book 4
 * ports + stat
 * 
 * @param qName
 *            the name of the queue to create
 * @return the monitor address as tcp://IP:port of the newly created monitor
 *         +"," tcp://IP: statport
 */
private String startNewMonitorProcess(String qName) {
    // 1. Get the number of installed queues on this host
    int frontPort = getMonitorPort();
    int statPort = getStatMonitorPort();
    logger.debug(" This host contains already " + this.qMonitorMap.size() + " Monitor");
    String argument = frontPort + " " + statPort;
    logger.debug("Starting monitor process by script launch on " + argument);
    //Monitor configuration
    String monitorAddress = "tcp://" + RoQUtils.getInstance().getLocalIP() + ":" + frontPort;
    String statAddress = "tcp://" + RoQUtils.getInstance().getLocalIP() + ":" + statPort;
    //Checking whether we must create the monitor, stat monitor and the scaling process in the same VM
    if (this.properties.isQueueInHcmVm()) {
        logger.info("Creating the Monitor of the " + qName + " on the same VM as the local HCM");
        Monitor monitor = new Monitor(frontPort, statPort, qName,
                new Integer(this.properties.getStatPeriod()).toString());
        new Thread(monitor).start();
    } else {
        // 2. Launch script in its onw VM
        // ProcessBuilder pb = new ProcessBuilder(this.monitorScript,
        // argument);
        ProcessBuilder pb = new ProcessBuilder("java",
                "-Djava.library.path=" + System.getProperty("java.library.path"), "-cp",
                System.getProperty("java.class.path"), MonitorLauncher.class.getCanonicalName(),
                new Integer(frontPort).toString(), new Integer(statPort).toString(), qName,
                new Integer(this.properties.getStatPeriod()).toString());
        try {
            logger.debug("Starting: " + pb.command());
            final Process process = pb.start();
            pipe(process.getErrorStream(), System.err);
            pipe(process.getInputStream(), System.out);
        } catch (IOException e) {
            logger.error("Error while executing script", e);
            return null;
        }
    }
    //add the monitor configuration
    this.qMonitorMap.put(qName, (monitorAddress));
    this.qMonitorStatMap.put(qName, statAddress);
    return monitorAddress + "," + statAddress;
}

From source file:com.thebuzzmedia.exiftool.ExifToolNew3.java

/**
 * There is a bug that prevents exiftool to read unicode file names. We can get the windows filename if necessary
 * with getMSDOSName//w  w w . ja  v  a 2 s. co m
 * 
 * @link(http://perlmaven.com/unicode-filename-support-suggested-solution)
 * @link(http://stackoverflow.com/questions/18893284/how-to-get-short-filenames-in-windows-using-java)
 */
public static String getMSDOSName(File file) {
    try {
        String path = getAbsolutePath(file);
        String path2 = file.getAbsolutePath();
        System.out.println(path2);
        // String toExecute = "cmd.exe /c for %I in (\"" + path2 + "\") do @echo %~fsI";
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","for","%I","in","(" + path2 + ")","do","@echo","%~sI");
        path2 = new File(
                "d:\\aaaaaaaaaaaaaaaaaaaaaaaaaaaa\\bbbbbbbbbbbbbbbbbb\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg")
                        .getAbsolutePath();
        path2 = new File(
                "d:\\personal\\photos-tofix\\2013-proposed1-bad\\2013-12-22--12-10-42------Bulevardul-Petrochimitilor.jpg")
                        .getAbsolutePath();

        System.out.println(path2);
        ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "for", "%I", "in", "(\"" + path2 + "\")", "do",
                "@echo", "%~fsI");
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","chcp 65001 & dir",path2);
        // ProcessBuilder pb = new ProcessBuilder("cmd","/c","ls",path2);
        Process process = pb.start();
        // Process process = Runtime.getRuntime().exec(execLine);
        // Process process = Runtime.getRuntime().exec(new String[]{"cmd","/c","for","%I","in","(\"" + path2 +
        // "\")","do","@echo","%~fsI"});
        process.waitFor();
        byte[] data = new byte[65536];
        // InputStreamReader isr = new InputStreamReader(process.getInputStream(), "UTF-8");
        // String charset = Charset.defaultCharset().name();
        String charset = "UTF-8";
        String lines = IOUtils.toString(process.getInputStream(), charset);
        // int size = process.getInputStream().read(data);
        // String path3 = path;
        // if (size > 0)
        // path3 = new String(data, 0, size).replaceAll("\\r\\n", "");
        String path3 = lines;
        System.out.println(pb.command());
        System.out.println(path3);
        byte[] data2 = new byte[65536];
        int size2 = process.getErrorStream().read(data2);
        if (size2 > 0) {
            String error = new String(data2, 0, size2);
            System.out.println(error);
            throw new RuntimeException("Error was thrown " + error);
        }
        return path3;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

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

private int runScript(String script) throws IOException {
    try {/* w w  w  .  j a v  a2 s  .  c  o m*/
        ProcessBuilder pb = new ProcessBuilder();
        pb.command(script);
        Process p = pb.start();
        return p.waitFor();
    } catch (InterruptedException ex) {
        Logger.getLogger(JDeploy.class.getName()).log(Level.SEVERE, null, ex);
        return 1;
    }
}

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

private int runAntTask(String antFile, String target) throws IOException {
    try {//  w  w  w  . jav a 2  s .  com
        ProcessBuilder pb = new ProcessBuilder();
        pb.command("ant", "-f", antFile, target);
        Process p = pb.start();
        return p.waitFor();

    } catch (InterruptedException ex) {
        Logger.getLogger(JDeploy.class.getName()).log(Level.SEVERE, null, ex);
        return 1;
    }
}

From source file:functionaltests.matlab.AbstractMatlabTest.java

protected ProcessBuilder initCommand(String testName, int nb_iter) throws Exception {
    ProcessBuilder pb = new ProcessBuilder();
    pb.directory(mat_tb_home);/*ww  w.  j  ava2  s  .c  o m*/
    pb.redirectErrorStream(true);
    int runAsMe = 0;

    if (System.getProperty("proactive.test.runAsMe") != null) {
        runAsMe = 1;
    }

    logFile = new File(mat_tb_home, testName + ".log");
    if (logFile.exists()) {
        logFile.delete();
    }
    // If no property specified for matlab exe suppose it's in the PATH
    String matlabExe = System.getProperty("matlab.bin.path", "matlab");
    // Build the matlab command that will run the test
    String matlabCmd = String.format("addpath('%s');", this.test_home);
    if (System.getProperty("disable.popup") != null) {
        matlabCmd += "PAoptions('EnableDisconnectedPopup', false);";
    }
    matlabCmd += getMatlabFunction(nb_iter, testName, runAsMe);
    return pb.command(matlabExe, "-nodesktop", "-nosplash", "-logfile", logFile.getAbsolutePath(), "-r",
            matlabCmd);
}

From source file:net.technicpack.autoupdate.Relauncher.java

public void launch(String launchPath, Class mainClass, String[] args) {
    if (launchPath == null) {
        try {//from  w  ww .j ava 2 s  .  c o m
            launchPath = getRunningPath(mainClass);
        } catch (UnsupportedEncodingException ex) {
            return;
        }
    }

    ProcessBuilder processBuilder = new ProcessBuilder();
    ArrayList<String> commands = new ArrayList<String>();
    if (!launchPath.endsWith(".exe")) {
        if (OperatingSystem.getOperatingSystem().equals(OperatingSystem.WINDOWS))
            commands.add("javaw");
        else
            commands.add("java");
        commands.add("-Xmx256m");
        commands.add("-Djava.net.preferIPv4Stack=true");
        commands.add("-Dawt.useSystemAAFontSettings=lcd");
        commands.add("-Dswing.aatext=true");
        commands.add("-cp");
        commands.add(launchPath);
        commands.add(mainClass.getName());
    } else
        commands.add(launchPath);
    commands.addAll(Arrays.asList(args));

    String command = "";

    for (String token : commands) {
        command += token + " ";
    }

    Utils.getLogger().info("Launching command: '" + command + "'");

    processBuilder.command(commands);

    try {
        processBuilder.start();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Your OS has prevented this relaunch from completing.  You may need to add an exception in your security software.",
                "Relaunch Failed", JOptionPane.ERROR_MESSAGE);
        ex.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.exit(0);
}

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

private void publish() throws IOException {
    try {/*from ww w .  ja  v  a 2 s. c  om*/
        ProcessBuilder pb = new ProcessBuilder();
        pb.inheritIO();
        pb.command(npm, "publish");
        Process p = pb.start();
        int result = p.waitFor();
        if (result != 0) {
            System.exit(result);
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(JDeploy.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException(ex);
    }
}

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

private void install() throws IOException {

    _package();/*  w  w w . j  a  v a  2s .c o  m*/
    try {
        ProcessBuilder pb = new ProcessBuilder();
        pb.inheritIO();
        pb.command(npm, "link");
        Process p = pb.start();
        int result = p.waitFor();
        if (result != 0) {
            System.exit(result);
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(JDeploy.class.getName()).log(Level.SEVERE, null, ex);
        throw new RuntimeException(ex);
    }
}