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

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

Introduction

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

Prototype

public CommandLine addArgument(final String argument) 

Source Link

Document

Add a single argument.

Usage

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

/**
 * Creates a new MySQL database./*from w w  w . j  ava 2 s . c  o m*/
 * 
 * @param databaseName The name for the new database
 * @param username Username of the MySQL administration user
 * @param password Password of the MySQL administration user
 */
public static void createDatabase(final String databaseName, final String username, final String password) {
    CommandLine command = new CommandLine("mysqladmin");
    addCredentials(command, username, password);
    command.addArgument("create");
    command.addArgument(databaseName);

    execute(command);
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

/**
 * Drops an existing MySQL database.// w w  w . j a  v a2s  .  c om
 * 
 * @param databaseName The name of the database to be dropped
 * @param username Username of the MySQL administration user
 * @param password Password of the MySQL administration user
 */
public static void dropDatabase(final String databaseName, final String username, final String password) {
    CommandLine command = new CommandLine("mysqladmin");
    addCredentials(command, username, password);
    command.addArgument("drop");
    command.addArgument("-f");
    command.addArgument(databaseName);

    execute(command);
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

/**
 * Restores a MySQL database from a file.
 * /*  w w  w  .j  av  a  2  s. c  om*/
 * @param databaseName The name of the database
 * @param fileName Backup file
 * @param username Username of the database user
 * @param password Password of the database user
 */
public static void restore(final String databaseName, final String fileName, final String username,
        final String password) {
    LogFactory.getLog().log("Restoring from " + fileName + " into " + databaseName);

    CommandLine command = new CommandLine("mysql");
    addCredentials(command, username, password);
    command.addArgument(databaseName);

    try (FileInputStream input = new FileInputStream(fileName)) {
        executeWithInput(command, input);
    } catch (IOException ioe) {
        throw new UtilException("Error restoring a database", ioe);
    }
}

From source file:com.magnet.tools.tests.WebLogicStepDefs.java

public static void ensureStartServer(String location, String httpPingUrl) throws Exception {
    Executor exec = new DefaultExecutor();
    CommandLine cl = new CommandLine(getScriptsDir() + File.separator + START_WLS_SERVER_SCRIPT);
    if (getArchetypeSettings() != null && getArchetypeSettings().length() != 0) {
        cl.addArgument("--s");
        cl.addArgument(getArchetypeSettings());
    }//from   w w w . j a  v  a2  s. c om
    cl.addArgument(String.format("-DdomainHome=%s", location));
    cl.addArgument(String.format("-DhttpPingUrl=%s", httpPingUrl));
    cl.setSubstitutionMap(getSubstitutionMap());
    int exitValue = exec.execute(cl);
    ensureBuildSuccessful("start-server.log");
    String msg = String.format("server failed to start at %s", expandVariables(location));
    Assert.assertEquals(msg, 0, exitValue);
}

From source file:com.magnet.tools.tests.WebLogicStepDefs.java

public static void ensureDeployApp(String url, String name, String location) throws Exception {
    Executor exec = new DefaultExecutor();
    CommandLine cl = new CommandLine(getScriptsDir() + File.separator + REDEPLOY_WLS_APP_SCRIPT);
    if (getArchetypeSettings() != null && getArchetypeSettings().length() != 0) {
        cl.addArgument(getArchetypeSettings());
    }/*  w ww  . j ava  2 s.  c om*/
    cl.addArgument(url);
    cl.addArgument(name);
    cl.addArgument(location);
    cl.setSubstitutionMap(getSubstitutionMap());
    int exitValue = exec.execute(cl);
    String msg = String.format("Server running at %s failed to deploy app %s at %s", url, name,
            expandVariables(location));
    ensureBuildSuccessful("redeploy.log");
    Assert.assertEquals(msg, 0, exitValue);
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

/**
 * Backs up a MySQL database to a file.//from  w  ww .ja va2  s.  c o m
 * 
 * @param databaseName The name of the database
 * @param fileName Backup file to be created
 * @param username Username of the database user
 * @param password Password of the database user
 */
public static void backup(final String databaseName, final String fileName, final String username,
        final String password) {
    LogFactory.getLog().log("Backing up " + databaseName + " into " + fileName);

    CommandLine command = new CommandLine("mysqldump");
    addCredentials(command, username, password);
    command.addArgument(databaseName);

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(executeAndGetOutput(command)));
            PrintWriter writer = new PrintWriter(new File(fileName))) {
        String line = reader.readLine();
        while (line != null) {
            writer.println(line);
            line = reader.readLine();
        }
    } catch (IOException ioe) {
        throw new UtilException("Error backing up a database", ioe);
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

public static void reset() throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("kill-server");
    LOG.debug("{}", cmdLine.toString());
    Executor executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }/*from  ww  w  . ja  v  a2s  .c om*/
    cmdLine = new CommandLine(ADB);
    cmdLine.addArgument("devices");
    LOG.debug("{}", cmdLine.toString());
    executor = new DefaultExecutor();
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

private static void loadAllSerials() {
    SERIALS.clear();//from  w  ww . j  a  v a2 s . com
    String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS);
    if (null != serials) {
        LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials);
        SERIALS.addAll(Lists.newArrayList(serials.split(",")));
    } else {
        CommandLine cmdLine = new CommandLine(ADB);
        cmdLine.addArgument("devices");
        LOG.debug("{}", cmdLine.toString());
        List<String> output = new ArrayList<>();
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new ESH(output));
        try {
            if (executor.execute(cmdLine) != 0) {
                throw new RuntimeException(cmdLine + " failed");
            }
        } catch (IOException ex) {
            throw new RuntimeException(cmdLine + " failed", ex);
        }
        output.stream().filter((line) -> (line.endsWith("device"))).forEach((line) -> {
            String s = line.split("\\t")[0];
            LOG.info("serial {}", s);
            SERIALS.add(s);
        });
    }
    if (SERIALS.isEmpty()) {
        throw new RuntimeException("No device detected.");
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

private static void loadSerialProductMap() {
    SERIAL_PRODUCT.clear();//  w w w  .  j  a  va  2s .  co m
    String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS);
    if (null != serials) {
        LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials);
        Lists.newArrayList(serials.split(",")).forEach(s -> SERIAL_PRODUCT.put(s, "na"));
    } else {
        CommandLine cmdLine = new CommandLine(ADB);
        cmdLine.addArgument("devices");
        cmdLine.addArgument("-l");
        LOG.debug("{}", cmdLine.toString());
        List<String> output = new ArrayList<>();
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new ESH(output));
        try {
            if (executor.execute(cmdLine) != 0) {
                throw new RuntimeException(cmdLine + " failed");
            }
        } catch (IOException ex) {
            throw new RuntimeException(cmdLine + " failed", ex);
        }
        output.stream().map(line -> StringUtils.split(line, " ", 3))
                .filter(ss -> ss.length == 3 && ss[1].equals("device")).forEach(ss -> {
                    LOG.info("device {} -> {}", ss[0], ss[2]);
                    SERIAL_PRODUCT.put(ss[0], ss[2]);
                });
    }
    if (SERIAL_PRODUCT.isEmpty()) {
        throw new RuntimeException("No device detected.");
    }
    SERIALS.addAll(SERIAL_PRODUCT.keySet());
}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command//from   www .  j av  a2 s  . c  om
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}