Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:elh.eus.absa.NLPpipelineWrapper.java

public static int eustaggerCall(String taggerCommand, String string, String fname) {

    try {//  w  w w .  j av  a 2s .com
        File temp = new File(fname);
        //System.err.println("eustaggerCall: created temp file: "+temp.getAbsolutePath());
        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
        bw.write(string + "\n");
        bw.close();

        String[] command = { taggerCommand, temp.getName() };
        System.err.println("Eustagger agindua: " + Arrays.toString(command));

        ProcessBuilder eustBuilder = new ProcessBuilder().command(command);
        eustBuilder.directory(new File(temp.getParent()));
        //.redirectErrorStream(true);
        Process eustagger = eustBuilder.start();
        int success = eustagger.waitFor();
        //System.err.println("eustagger succesful? "+success);
        if (success != 0) {
            System.err.println("eustaggerCall: eustagger error");
        } else {
            String tagged = fname + ".kaf";
            BufferedReader reader = new BufferedReader(new InputStreamReader(eustagger.getInputStream()));
            //new Eustagger_lite outputs to stdout. Also called ixa-pipe-pos-eu
            if (taggerCommand.contains("eustagger") || taggerCommand.contains("ixa-pipe")) {
                Files.copy(eustagger.getInputStream(), Paths.get(tagged));
            }
            // old eustagger (euslem)
            else {
                FileUtilsElh.renameFile(temp.getAbsolutePath() + ".etiketatua3", tagged);
            }
        }
        //
        // delete all temporal files used in the process.
        temp.delete();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return -1;
    }

    return 0;
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSUtil.java

public static void executeCommand(FileObject workingFolder, ProgressHandler handler, String... command) {
    try {/*from   w  w w.j  a v  a 2s  .co  m*/
        ProcessBuilder pb = new ProcessBuilder(command);

        //                Map<String, String> env = pb.environment();
        // If you want clean environment, call env.clear() first
        //                env.put("VAR1", "myValue");
        //                env.remove("OTHERVAR");
        //                env.put("VAR2", env.get("VAR1") + "suffix");
        pb.directory(FileUtil.toFile(workingFolder));
        Process proc = pb.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        // read the output from the command
        String s;
        while ((s = stdInput.readLine()) != null) {
            handler.append(Console.wrap(s, FG_BLUE));
        }

        // read any errors from the attempted command
        while ((s = stdError.readLine()) != null) {
            handler.append(Console.wrap(s, FG_DARK_RED));
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:org.zenoss.zep.dao.impl.DaoUtils.java

public static int executeCommand(String command) {
    String response = "";

    ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
    pb.redirectErrorStream(true);//from   w ww .  j  a v  a  2  s .  c o  m

    int shellExitStatus = -1;
    InputStream shellIn = null;

    try {
        Process shell = pb.start();
        // To capture output from the shell
        shellIn = shell.getInputStream();

        // Wait for the shell to finish and get the return code
        shellExitStatus = shell.waitFor();
        if (shellExitStatus != 0) {
            response = DaoUtils.convertStreamToStr(shellIn);
            logger.error("Error (return code: " + shellExitStatus + ") from \"" + command + "\": \nOutput: "
                    + response);
        }
        shellIn.close();
    } catch (IOException e) {
        logger.error("Error occured while executing Linux command. Error Description: " + e.getMessage());
    } catch (InterruptedException e) {
        logger.error("Error occured while executing Linux command. Error Description: " + e.getMessage());
    }

    return shellExitStatus;
}

From source file:io.werval.cli.DamnSmallDevShell.java

static void rebuild(URL[] applicationClasspath, URL[] runtimeClasspath, Set<File> sourcesRoots,
        File classesDir) {/*ww w.  j  a  v  a 2 s .  c o m*/
    System.out.println("Compiling Application...");
    String javacOutput = EMPTY;
    try {
        // Collect java files
        String javaFiles = EMPTY;
        for (File sourceRoot : sourcesRoots) {
            if (sourceRoot.exists()) {
                ProcessBuilder findBuilder = new ProcessBuilder("find", sourceRoot.getAbsolutePath(), "-type",
                        "f", "-iname", "*.java");
                Process find = findBuilder.start();
                int returnCode = find.waitFor();
                if (returnCode != 0) {
                    throw new IOException("Unable to find java source files in " + sourceRoot);
                }
                javaFiles += NEWLINE + readAllAsString(find.getInputStream(), 4096, UTF_8);
            }
        }
        if (hasText(javaFiles)) {
            // Write list in a temporary file
            File javaListFile = new File(classesDir, ".devshell-java-list");
            try (FileWriter writer = new FileWriter(javaListFile)) {
                writer.write(javaFiles);
                writer.close();
            }
            // Compile
            String[] classpathStrings = new String[runtimeClasspath.length];
            for (int idx = 0; idx < runtimeClasspath.length; idx++) {
                classpathStrings[idx] = runtimeClasspath[idx].toURI().toASCIIString();
            }
            ProcessBuilder javacBuilder = new ProcessBuilder("javac", "-encoding", "UTF-8", "-source", "1.8",
                    "-d", classesDir.getAbsolutePath(), "-classpath", join(classpathStrings, ":"),
                    "@" + javaListFile.getAbsolutePath());
            Process javac = javacBuilder.start();
            int returnCode = javac.waitFor();
            if (returnCode != 0) {
                throw new IOException("Unable to build java source files.");
            }
            javacOutput = readAllAsString(javac.getInputStream(), 4096, UTF_8);
        }
    } catch (InterruptedException | IOException | URISyntaxException ex) {
        throw new WervalException("Unable to rebuild" + (isEmpty(javacOutput) ? "" : "\n" + javacOutput), ex);
    }
}

From source file:com.clavain.alerts.Methods.java

public static boolean sendTTSMessage(String message, String mobile_nr) {
    boolean retval = false;

    try {/*from   w w  w  .ja v a  2s  . c  om*/
        if (p.getProperty("tts.provider").equals("smsflatrate")) {
            String key = p.getProperty("smsflatrate.key");
            String gw = p.getProperty("smsflatrate.ttsgw");

            String msg = URLEncoder.encode(message);
            URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr
                    + "&voice=Dave&repeat=2&rate=1&type=" + gw + "&text=" + msg);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().equals("100")) {
                retval = true;
            }
        } else if (p.getProperty("tts.provider").equals("script")) {
            List<String> commands = new ArrayList<String>();
            // add global timeout script
            commands.add(p.getProperty("tts.script"));
            commands.add(mobile_nr);
            commands.add(message);
            ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true);
            logger.info("tts.script - Running: " + commands);
            Process p = pb.start();
            Integer rv = p.waitFor();

        }
    } catch (Exception ex) {
        retval = false;
        logger.error("sendTTSMessage Error: " + ex.getLocalizedMessage());
    }
    return retval;
}

From source file:com.photon.phresco.framework.commons.ApplicationsUtil.java

public static List<PBXNativeTarget> getXcodeConfiguration(String projectCode)
        throws PhrescoException, JAXBException, IOException, PhrescoPomException {
    S_LOGGER.debug("Iphone technology target retrivel initiated");
    StringBuilder builder = new StringBuilder(Utility.getProjectHome());
    builder.append(projectCode);//ww  w .  j a  va2s .c  o  m
    builder.append(File.separatorChar);
    builder.append(POM_XML);
    File pomPath = new File(builder.toString());
    PomProcessor pomProcessor = new PomProcessor(pomPath);
    StringBuilder projPath = new StringBuilder(Utility.getProjectHome());
    projPath.append(projectCode);
    projPath.append(pomProcessor.getSourceDirectory());
    File file = new File(projPath.toString());
    FilenameFilter filter = new FileListFilter("", IPHONE_XCODE_PROJ_EXTN);
    File[] listFiles = file.listFiles(filter);
    projPath.append(File.separator);
    // Get firest xcode proj file name
    projPath.append(listFiles[0].getName());
    S_LOGGER.debug("Iphone technology listFile name" + listFiles[0].getName());
    String pbxprojLocation = projPath.toString();

    // plutil location in mac
    File plutilCommandLine = new File("/usr/bin/plutil");
    List<PBXNativeTarget> targets = null;
    S_LOGGER.debug("Before entering plutilCommandLine ");
    if (!plutilCommandLine.exists()) {
        S_LOGGER.debug("Invalid path for plutil");
        throw new PhrescoException("Invalid path for plutil");
    }
    File xcodeprojJson = new File(pbxprojLocation, "xcodeInfo.json");
    S_LOGGER.debug("Before plutil try!!!");
    try {
        String[] commands = { "plutil", "-convert", "json", "-o", xcodeprojJson.getAbsolutePath(),
                pbxprojLocation + "/project.pbxproj" };
        ProcessBuilder probuilder = new ProcessBuilder(commands);
        probuilder.directory(new File(pbxprojLocation));
        probuilder.start();
    } catch (Exception e) {
        S_LOGGER.error("Error While Executing" + e);
        throw new PhrescoException("Error while executing ");
    }
    S_LOGGER.error("Before While loop");
    while (!xcodeprojJson.exists()) {

    }
    S_LOGGER.error("After While loop Completed");
    if (xcodeprojJson.exists()) {
        S_LOGGER.error("File exists");
        XcodeprojParser parser = new XcodeprojParser(xcodeprojJson);
        try {
            PBXProject project = parser.parseXcodeFile();
            if (project != null) {
                targets = project.getTargets();
            }
        } catch (Exception e) {
            throw new PhrescoException(e);
        }
    }
    S_LOGGER.error("File reading completed");
    xcodeprojJson.delete();
    S_LOGGER.debug("Going to return from applications util");
    return targets;
}

From source file:com.samczsun.helios.Helios.java

public static Process launchProcess(ProcessBuilder launch) throws IOException {
    Process process = launch.start();
    processes.add(process);//from   ww  w  .  jav a2s . c o  m
    submitBackgroundTask(() -> {
        try {
            process.waitFor();
            if (!process.isAlive()) {
                processes.remove(process);
            }
        } catch (InterruptedException e) {
            ExceptionHandler.handle(e);
        }
    });
    return process;
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

public static String executeLocalScript(String path, List<String> args) throws Exception {
    List<String> pargs = new ArrayList<String>();
    pargs.add("/bin/bash");
    pargs.add(path);/*ww  w  .ja  v  a2s  .c om*/
    if (args != null) {
        pargs.addAll(args);
    }
    ProcessBuilder pb = new ProcessBuilder(pargs);
    pb.environment().putAll(EventDriver.getEnvironment());
    pb.environment().put("IP_LOCATION", EventDriver.CLIENT_NODE.getClusterIp());
    Process p = pb.start();
    BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
    StringWriter writer = new StringWriter();
    IOUtils.copy(bis, writer, "UTF-8");
    return writer.toString();
}

From source file:com.clavain.alerts.Methods.java

public static boolean sendSMSMessage(String message, String mobile_nr) {
    boolean retval = false;
    // http://smsflatrate.net/schnittstelle.php?key=ff&to=00491734631526&type=4&text=ALERT:%20Notification%20Test%20(HTTPS)%20-%20HTTP%20Critical-%20OK%20String%20not%20found
    try {//  w  w  w.java 2  s  . c  om
        if (p.getProperty("sms.provider").equals("smsflatrate")) {
            String key = p.getProperty("smsflatrate.key");
            String gw = p.getProperty("smsflatrate.gw");
            if (mobile_nr.startsWith("0049")) {
                gw = p.getProperty("smsflatrate.gwde");
            }
            String msg = URLEncoder.encode(message);
            URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr
                    + "&type=" + gw + "&text=" + msg);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().equals("100")) {
                retval = true;
            }
        } else if (p.getProperty("sms.provider").equals("bulksms")) {
            // http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username=ff&password=yt89hjfff98&message=Hey%20Fucker&msisdn=491734631526
            String msg = URLEncoder.encode(message);
            URL url = new URL("http://bulksms.de:5567/eapi/submission/send_sms/2/2.0?username="
                    + p.getProperty("bulksms.username") + "&password=" + p.getProperty("bulksms.password")
                    + "&message=" + msg + "&msisdn=" + mobile_nr);
            URLConnection conn = url.openConnection();
            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            String resp = "";
            while ((inputLine = br.readLine()) != null) {
                resp = inputLine;
            }
            //conn.getContent();      
            if (resp.trim().startsWith("0")) {
                retval = true;
            }
        } else if (p.getProperty("sms.provider").equals("twilio")) {
            // reformat number?
            if (mobile_nr.startsWith("00")) {
                mobile_nr = "+" + mobile_nr.substring(2, mobile_nr.length());
            } else if (mobile_nr.startsWith("0")) {
                mobile_nr = "+" + mobile_nr.substring(1, mobile_nr.length());
            }
            TwilioRestClient client = new TwilioRestClient(p.getProperty("twilio.accountsid"),
                    p.getProperty("twilio.authtoken"));
            //String msg = URLEncoder.encode(message);
            // Build the parameters 
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("To", mobile_nr));
            params.add(new BasicNameValuePair("From", p.getProperty("twilio.fromnr")));
            params.add(new BasicNameValuePair("Body", message));

            MessageFactory messageFactory = client.getAccount().getMessageFactory();
            Message tmessage = messageFactory.create(params);
            logger.info("twilio: msg send to " + mobile_nr + " sid: " + tmessage.getSid() + " status: "
                    + tmessage.getStatus() + " twilio emsg: " + tmessage.getErrorMessage());

        } else if (p.getProperty("sms.provider").equals("script")) {
            List<String> commands = new ArrayList<String>();
            // add global timeout script
            commands.add(p.getProperty("sms.script"));
            commands.add(mobile_nr);
            commands.add(message);
            ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true);
            logger.info("sms.script - Running: " + commands);
            Process p = pb.start();
            Integer rv = p.waitFor();
        }
    } catch (Exception ex) {
        retval = false;
        logger.error("sendSMSMessage Error: " + ex.getLocalizedMessage());
    }
    return retval;
}

From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java

private static List<String> system(ProcessBuilder.Redirect errorRedirector,
        ProcessBuilder.Redirect outputRedirector, String... command) {
    try {/*from  w w  w .  j av  a  2 s.  c o m*/
        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectError(errorRedirector);
        builder.redirectOutput(outputRedirector);
        final Process process = builder.start();
        Verify.verify(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command),
                IOUtils.toString(process.getErrorStream()));
        try (InputStream stream = process.getInputStream()) {
            return IOUtils.readLines(stream);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}