Example usage for org.apache.commons.exec CommandLine CommandLine

List of usage examples for org.apache.commons.exec CommandLine CommandLine

Introduction

In this page you can find the example usage for org.apache.commons.exec CommandLine CommandLine.

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:it.drwolf.ridire.index.cwb.CWBConcordancer.java

private void executeCQPQuery(File queryFile, boolean inverse) throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("LC_ALL=C && ");
    String corpusName = this.cqpCorpusName;
    if (inverse) {
        corpusName += "INV";
    }//www. j  a  va2s.c  o  m
    stringBuffer.append(this.cqpExecutable + " -f " + queryFile.getAbsolutePath() + " -D " + corpusName + " -r "
            + this.cqpRegistry + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempSh);
}

From source file:it.drwolf.ridire.index.cwb.CWBConcordancer.java

private void executeQueryForContext(CWBResult item, File contextFile, boolean left)
        throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireCTX", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("LC_ALL=C && ");
    if (left) {// ww w . jav  a2s . com
        stringBuffer.append(this.cwbdecodeExecutable + " -r " + this.cqpRegistry + " -C -s "
                + Math.max(0, item.getStartPosition() - 101) + " -e " + (item.getStartPosition() - 1) + " "
                + this.cqpCorpusName + " -P word" + " > " + contextFile.getAbsolutePath() + "\n");
    } else {
        stringBuffer.append(this.cwbdecodeExecutable + " -r " + this.cqpRegistry + " -C -s "
                + (item.getEndPosition() + 1) + " -e " + (item.getEndPosition() + 101) + " "
                + this.cqpCorpusName + " -P word" + " > " + contextFile.getAbsolutePath() + "\n");
    }
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempSh);
}

From source file:beans.ServerBootstrapperImpl.java

private void createNewMachine(ServerNode serverNode) {
    File cloudFolder = null;/*from   w  w  w .j a v  a2 s  .c  o m*/
    ComputeServiceContext jCloudsContext = null;
    try {
        // no existing management machine - create new server
        String project = serverNode.getProject();
        String secretKey = serverNode.getSecretKey();
        String apiKey = serverNode.getKey();
        logger.info("Creating cloud folder with specific user credentials. Project: [{}], api key: [{}]",
                project, apiKey);
        jCloudsContext = CloudifyUtils.createJcloudsContext(project, apiKey, secretKey);
        cloudFolder = CloudifyUtils.createCloudFolder(project, apiKey, secretKey, jCloudsContext);
        logger.info("cloud folder is at [{}]", cloudFolder);

        logger.info("Creating security group for user.");
        CloudifyUtils.createCloudifySecurityGroup(jCloudsContext);

        //Command line for bootstrapping remote cloud.
        CommandLine cmdLine = new CommandLine(conf.server.cloudBootstrap.remoteBootstrap.getAbsoluteFile());
        cmdLine.addArgument(cloudFolder.getName());

        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ProcExecutor bootstrapExecutor = executorFactory.getBootstrapExecutor(serverNode);

        logger.info("Executing command line: " + cmdLine);
        bootstrapExecutor.execute(cmdLine, ApplicationContext.get().conf().server.environment.getEnvironment(),
                resultHandler);
        logger.info("waiting for output");
        resultHandler.waitFor();
        logger.info("finished waiting , exit value is [{}]", resultHandler.getExitValue());

        String output = Utils.getOrDefault(Utils.getCachedOutput(serverNode), "");
        if (resultHandler.getException() != null) {
            logger.info("we have exceptions, checking for known issues");
            if (output.contains("found existing management machines")) {
                logger.info(
                        "found 'found existing management machines' - issuing cloudify already exists message");
                throw new ServerException(Messages.get("cloudify.already.exists"));
            }
            logger.info("Command execution ended with errors: {}", output);
            throw new RuntimeException("Failed to bootstrap cloudify machine: " + output,
                    resultHandler.getException());
        }

        logger.info("finished handling errors, extracting IP");
        String publicIp = Utils.extractIpFromBootstrapOutput(output);
        if (StringUtils.isEmpty(publicIp)) {
            logger.warn("No public ip address found in bootstrap output. " + output);
            throw new RuntimeException("Bootstrap failed. No IP address found in bootstrap output." + output,
                    resultHandler.getException());
        }
        logger.info("ip is [{}], saving to serverNode", publicIp);

        String privateKey = CloudifyUtils.getCloudPrivateKey(cloudFolder);
        if (StringUtils.isEmpty(privateKey)) {
            throw new RuntimeException("Bootstrap failed. No pem file found in cloud directory.");
        }
        logger.info("found PEM string");
        logger.info("Bootstrap cloud command ended successfully");

        logger.info("updating server node with new info");
        serverNode.setPublicIP(publicIp);
        serverNode.setPrivateKey(privateKey);

        serverNode.save();
        logger.info("server node updated and saved");
    } catch (Exception e) {
        serverNode.errorEvent("Invalid Credentials").save();
        throw new RuntimeException("Unable to bootstrap cloud", e);
    } finally {
        if (cloudFolder != null && conf.server.cloudBootstrap.removeCloudFolder) {
            FileUtils.deleteQuietly(cloudFolder);
        }
        if (jCloudsContext != null) {
            jCloudsContext.close();
        }
        serverNode.setStopped(true);

    }
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS tracejob command./*from  www .  ja  v  a 2  s.  c o  m*/
 * <p>
 * Equivalent to tracejob -n [numberOfDays] [jobId]
 *
 * @param jobId job id
 * @param numberOfDays number of days to look for the job
 * @param quiet quiet mode flag
 * @return tracejob output
 */
public static CommandOutput traceJob(String jobId, int numberOfDays, boolean quiet) {
    final CommandLine cmdLine = new CommandLine(COMMAND_TRACEJOB);
    cmdLine.addArgument(PARAMETER_NUMBER_OF_DAYS);
    cmdLine.addArgument(Integer.toString(numberOfDays));
    if (quiet) {
        cmdLine.addArgument(PARAMETER_QUIET_MODE);
    }
    cmdLine.addArgument(jobId);

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, null, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute tracejob command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute tracejob command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute tracejob command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("tracejob exit value: " + exitValue);
    LOGGER.fine("tracejob output: " + out.toString());

    return new CommandOutput(out.toString(), err.toString());
}

From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java

/**
 * XNDisc Server  ? ?  ?//  w  w w. jav  a  2  s  .c o  m
 * 
 * @return ?? true,  false
 */
private static boolean isXNDiscServerAlive() {
    boolean isAlive = false;

    String HOST = XNDiscConfig.getString(XNDiscConfig.HOST, XNDiscConfig.LOCAL_HOST);
    String PORT = XNDiscConfig.getString(XNDiscConfig.PORT);

    Scanner scanner = null;
    ByteArrayOutputStream baos = null;
    try {
        String os = System.getProperty("os.name").toLowerCase();
        String ostype = (os.contains("windows")) ? "W" : "U";
        CommandLine cmdline = new CommandLine("netstat");
        cmdline.addArgument("-an");
        if (ostype.equals("W")) {
            cmdline.addArgument("-p");
            cmdline.addArgument("\"TCP\"");
        } else { // UNIX ? ? -an ? ?  ?  
            if (XNDiscUtils.isSolaris()) {
                cmdline.addArgument("-P");
                cmdline.addArgument("tcp");
            } else if (XNDiscUtils.isAix()) {
                cmdline.addArgument("-p");
                cmdline.addArgument("TCP");
            }
        }
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        baos = new ByteArrayOutputStream();
        PumpStreamHandler sh = new PumpStreamHandler(baos);
        executor.setStreamHandler(sh);
        executor.execute(cmdline);
        String str = baos.toString();
        if (str != null && str.length() > 0) { // ?  XNDisc alive ?(XNDisc Server ? ?)
            scanner = new Scanner(str);
            while (scanner.hasNextLine()) {
                String readline = scanner.nextLine();
                if (readline.contains(HOST) && readline.contains(PORT)
                        && readline.contains(XNDISC_LISTEN_STATUS)) {
                    isAlive = true;
                    break;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        isAlive = false;
    } finally {
        try {
            if (scanner != null) {
                scanner.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return isAlive;
}

From source file:net.hasor.maven.ExecMojo.java

CommandLine getExecutablePath(Map<String, String> enviro, File dir) {
    File execFile = new File(executable);
    String exec = null;//  w  ww . j a  va 2  s .  c o  m
    if (execFile.isFile()) {
        getLog().debug("Toolchains are ignored, 'executable' parameter is set to " + executable);
        exec = execFile.getAbsolutePath();
    }
    if (exec == null) {
        Toolchain tc = getToolchain();
        // if the file doesn't exist & toolchain is null, the exec is probably in the PATH...
        // we should probably also test for isFile and canExecute, but the second one is only
        // available in SDK 6.
        if (tc != null) {
            getLog().info("Toolchain in exec-maven-plugin: " + tc);
            exec = tc.findTool(executable);
        } else {
            if (OS.isFamilyWindows()) {
                List<String> paths = this.getExecutablePaths(enviro);
                for (String extension : WINDOWS_SPECIAL_EXTS) {
                    String ex = !executable.contains(".") ? executable + extension : executable;
                    File f = new File(dir, ex);
                    if (f.isFile()) {
                        exec = ex;
                    }
                    if (exec == null) {
                        for (String elem : paths) {
                            f = new File(new File(elem), ex);
                            if (f.isFile()) {
                                exec = ex;
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    if (exec == null) {
        exec = executable;
    }
    CommandLine toRet;
    if ((OS.isFamilyWindows() && exec.toLowerCase(Locale.getDefault()).endsWith(".bat"))
            || OS.isFamilyWindows() && exec.toLowerCase(Locale.getDefault()).endsWith(".cmd")) {
        // run the windows batch script in isolation and exit at the end
        toRet = new CommandLine("cmd");
        toRet.addArgument("/c");
        toRet.addArgument(exec);
    } else {
        toRet = new CommandLine(exec);
    }
    return toRet;
}

From source file:kr.motd.maven.exec.ExecMojo.java

CommandLine getExecutablePath(Map<String, String> enviro, File dir) {
    File execFile = new File(executable);
    String exec = null;//  ww  w . j  ava2 s  . c  o m
    if (execFile.isFile()) {
        getLog().debug("Toolchains are ignored, 'executable' parameter is set to " + executable);
        exec = execFile.getAbsolutePath();
    }

    if (exec == null) {
        Toolchain tc = getToolchain();

        // if the file doesn't exist & toolchain is null, the exec is probably in the PATH...
        // we should probably also test for isFile and canExecute, but the second one is only
        // available in SDK 6.
        if (tc != null) {
            getLog().info("Toolchain in exec-maven-plugin: " + tc);
            exec = tc.findTool(executable);
        } else {
            if (OS.isFamilyWindows()) {
                String ex = !executable.contains(".") ? executable + ".bat" : executable;
                File f = new File(dir, ex);
                if (f.isFile()) {
                    exec = ex;
                }

                if (exec == null) {
                    // now try to figure the path from PATH, PATHEXT env vars
                    // if bat file, wrap in cmd /c
                    String path = enviro.get("PATH");
                    if (path != null) {
                        String[] elems = StringUtils.split(path, File.pathSeparator);
                        for (String elem : elems) {
                            f = new File(new File(elem), ex);
                            if (f.isFile()) {
                                exec = ex;
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    if (exec == null) {
        exec = executable;
    }

    CommandLine toRet;
    if (OS.isFamilyWindows() && exec.toLowerCase(Locale.getDefault()).endsWith(".bat")) {
        toRet = new CommandLine("cmd");
        toRet.addArgument("/c");
        toRet.addArgument(exec);
    } else {
        toRet = new CommandLine(exec);
    }

    return toRet;
}

From source file:it.drwolf.ridire.index.cwb.CWBCollocatesExtractor.java

private File tabulate() throws IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    File tmpAwk = File.createTempFile("ridireAWK", ".awk");
    String awk = this.createAWKString();
    FileUtils.writeStringToFile(tmpAwk, awk);
    File tmpTabulate = File.createTempFile("ridireTAB", ".tab");
    String tabulate = this.createTabulateString(tmpAwk, tmpTabulate);
    File tempSh = File.createTempFile("ridireSH", ".sh");
    FileUtils.writeStringToFile(tempSh, tabulate);
    tempSh.setExecutable(true);// w w w.ja  v  a2  s . com
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBCollocatesExtractor.CWB_COLLOCATES_EXTRACTOR_TIMEOUT);
    executor.setWatchdog(watchdog);
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(tempSh.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tmpAwk);
    FileUtils.deleteQuietly(tempSh);
    return tmpTabulate;
}

From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.java

private Integer getCQPQueryResultsSize(File queryFile, String cqpSizeQuery)
        throws ExecuteException, IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    Executor executor = new DefaultExecutor();
    File tempSize = File.createTempFile("ridireSZ", ".size");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(queryFile.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    String commLineString = commandLine.toString() + " > " + tempSize.getAbsolutePath();
    FileUtils.writeStringToFile(tempSh, commLineString);
    tempSh.setExecutable(true);//from  www .jav a2s  .c  o  m
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT);
    executor.setWatchdog(watchdog);
    commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

From source file:it.drwolf.ridire.index.cwb.CWBConcordancer.java

private Integer getCQPQueryResultsSize(File queryFile) throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    File tempSize = File.createTempFile("ridireSZ", ".size");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    stringBuffer.append(this.cqpExecutable + " -f " + queryFile.getAbsolutePath() + " -D " + this.cqpCorpusName
            + " -r " + this.cqpRegistry + " > " + tempSize.getAbsolutePath() + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);//from   w w w  .  j  av  a  2s .c  o m
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}