Example usage for org.apache.commons.cli CommandLine getArgs

List of usage examples for org.apache.commons.cli CommandLine getArgs

Introduction

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

Prototype

public String[] getArgs() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:com.aliyun.odps.ship.common.OptionsBuilder.java

public static void buildHelpOption(String[] args) throws ParseException {

    DshipContext.INSTANCE.clear();//from w w w .j a va 2s.co m

    CommandLineParser parser = new GnuParser();
    Options opts = getGlobalOptions();

    CommandLine line = parser.parse(opts, args);

    String[] remains = line.getArgs();
    if (remains.length > 2) {
        throw new IllegalArgumentException(
                "Unknown command: too many subcommands.\nType 'tunnel help' for usage.");
    }
    if (remains.length > 1) {
        try {
            CommandType.fromString(remains[1]);
            DshipContext.INSTANCE.put(Constants.HELP_SUBCOMMAND, remains[1]);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(
                    "Unknown command: " + remains[1] + "\nType 'tunnel help' for usage.");
        }
    }
}

From source file:com.aliyun.odps.ship.common.OptionsBuilder.java

public static void buildPurgeOption(String[] args) throws ParseException {

    DshipContext.INSTANCE.clear();// ww  w . j a  v a  2 s. com

    CommandLineParser parser = new GnuParser();
    Options opts = getPurgeOptions();
    CommandLine line = parser.parse(opts, args);

    String[] remains = line.getArgs();
    if (remains.length == 1) {
        DshipContext.INSTANCE.put(Constants.PURGE_NUMBER, Constants.DEFAULT_PURGE_NUMBER);
    } else if (remains.length == 2) {
        // check parameter

        try {
            Integer.valueOf(remains[1]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Illegal number\nType 'tunnel help purge' for usage.");
        }
        DshipContext.INSTANCE.put(Constants.PURGE_NUMBER, remains[1]);
    } else if (remains.length > 2) {
        throw new IllegalArgumentException("Unknown command\nType 'tunnel help purge' for usage.");
    }

}

From source file:illarion.compile.Compiler.java

private static void processFileMode(@Nonnull final CommandLine cmd) throws IOException {
    storagePaths = new EnumMap<>(CompilerType.class);
    String npcPath = cmd.getOptionValue('n');
    if (npcPath != null) {
        storagePaths.put(CompilerType.easyNPC, Paths.get(npcPath));
    }//from w  ww . ja  va  2s  .com
    String questPath = cmd.getOptionValue('q');
    if (questPath != null) {
        storagePaths.put(CompilerType.easyQuest, Paths.get(questPath));
    }

    for (String file : cmd.getArgs()) {
        Path path = Paths.get(file);
        if (Files.isDirectory(path)) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    FileVisitResult result = super.visitFile(file, attrs);
                    if (result == FileVisitResult.CONTINUE) {
                        processPath(file);
                        return FileVisitResult.CONTINUE;
                    }
                    return result;
                }
            });
        } else {
            processPath(path);
        }
    }
}

From source file:com.aliyun.openservices.odps.console.pub.ShowInstanceCommand.java

public static ShowInstanceCommand parse(String commandString, ExecutionContext sessionContext)
        throws ODPSConsoleException {

    String upCommandText = commandString.toUpperCase().trim();
    if (upCommandText.toUpperCase().matches("\\s*SHOW\\s+P\\s*")
            || upCommandText.toUpperCase().matches("\\s*SHOW\\s+PROCESSLIST\\s*")
            || upCommandText.toUpperCase().matches("\\s*SHOW\\s+PROC\\s*")
            || upCommandText.toUpperCase().matches("\\s*SHOW\\s+P\\s+[\\s\\S]*")

            // bug #262924
            || upCommandText.toUpperCase().matches("\\s*SHOW\\s+INSTANCES\\s*")
            || upCommandText.toUpperCase().matches("\\s*SHOW\\s+INSTANCES\\s+[\\s\\S]*")
            || upCommandText.toUpperCase().matches("\\s*(LS|LIST)\\s+INSTANCES\\s*")
            || upCommandText.toUpperCase().matches("\\s*(LS|LIST)\\s+INSTANCES\\s+[\\s\\S]*")) {
        List<String> paraList = new ArrayList<String>(Arrays.asList(upCommandText.trim().split("\\s+")));

        // ??/*from w  w  w.  j a v a 2s.co  m*/
        String firstCmd = paraList.remove(0);
        paraList.remove(0);

        int length = paraList.size();
        if (length == 0) {

            // ???50?,
            return new ShowInstanceCommand(commandString, sessionContext, null, getTime(new Date(), 0), null,
                    50);
        }

        // ls instances -p project_name
        // ls instances --limit 100
        String project = null;

        // 50
        Integer number = 50;

        if (firstCmd.equals("LS") || firstCmd.equals("LIST")) {
            AntlrObject antlr = new AntlrObject(commandString);
            List<String> commandList = Arrays.asList(antlr.getTokenStringArray());

            CommandLine cl = getCommandLine(commandList.toArray(new String[length]));
            if (2 < cl.getArgs().length) {
                throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "[invalid parameters]");
            }

            project = cl.getOptionValue("p");

            if (cl.hasOption("limit")) {
                try {
                    number = Integer.parseInt(cl.getOptionValue("limit"));
                    if (number < 1) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "[number should >=1]");
                    }
                } catch (NumberFormatException e) {
                    // ?
                    throw new ODPSConsoleException(
                            ODPSConsoleConstants.BAD_COMMAND + "[number is not integer]");
                }

            } else if (project == null) {
                throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "[invalid paras]");
            }

            return new ShowInstanceCommand(commandString, sessionContext, project, getTime(new Date(), 0), null,
                    number);

        }

        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");

        Date fromDate = null;
        Date toDate = null;
        try {
            // fromto???
            int fromIndex = paraList.indexOf("FROM");
            if (fromIndex >= 0 && fromIndex + 1 < paraList.size()) {

                String fromString = paraList.get(fromIndex + 1);
                fromDate = formatDate.parse(fromString);

                paraList.remove(fromIndex + 1);
                paraList.remove(fromIndex);
            }

            int toIndex = paraList.indexOf("TO");
            if (toIndex >= 0 && toIndex + 1 < paraList.size()) {
                String toString = paraList.get(toIndex + 1);
                toDate = formatDate.parse(toString);

                paraList.remove(toIndex + 1);
                paraList.remove(toIndex);
            }
        } catch (ParseException e1) {
            // ?
            throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "[invalid date]");
        }

        // ?linenumber
        if (paraList.size() == 1) {

            try {
                number = Integer.valueOf(paraList.get(0));
            } catch (NumberFormatException e) {
                // ?
                throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "[number is not integer]");
            }

            paraList.remove(0);
        }

        if (paraList.size() == 0) {

            // 
            if (fromDate == null && toDate == null) {
                fromDate = new Date();
            }

            return new ShowInstanceCommand(commandString, sessionContext, project, getTime(fromDate, 0),
                    getTime(toDate, 24), number);
        } else {
            // ?
            throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "[more parameter]");
        }
    }
    return null;
}

From source file:ch.admin.hermes.etl.load.HermesETLApplication.java

/**
 * CommandLine parse und fehlende Argumente verlangen
 * @param args Args/*ww w.j  av a 2 s  . c  o  m*/
 * @throws ParseException
 */
private static void parseCommandLine(String[] args) throws Exception {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

    // HACK um UTF-8 CharSet fuer alle Dateien zu setzen (http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding)
    System.setProperty("file.encoding", "UTF-8");
    Field charset = Charset.class.getDeclaredField("defaultCharset");
    charset.setAccessible(true);
    charset.set(null, null);

    // commandline Options - FremdsystemSite, Username und Password
    Options options = new Options();
    options.addOption("s", true, "Zielsystem - URL");
    options.addOption("u", true, "Zielsystem - Username");
    options.addOption("p", true, "Zielsystem - Password");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    site = cmd.getOptionValue("s");
    user = cmd.getOptionValue("u");
    passwd = cmd.getOptionValue("p");

    // restliche Argumente pruefen - sonst usage ausgeben
    String[] others = cmd.getArgs();
    if (others.length >= 1 && (others[0].endsWith(".js") || others[0].endsWith(".ftl")))
        script = others[0];
    if (others.length >= 2 && others[1].endsWith(".xml"))
        model = others[1];

    // Dialog mit allen Werten zusammenstellen
    JComboBox<String> scenarios = new JComboBox<String>(crawler.getScenarios());

    JTextField tsite = new JTextField(45);
    tsite.setText(site);
    JTextField tuser = new JTextField(16);
    tuser.setText(user);
    JPasswordField tpasswd = new JPasswordField(16);
    tpasswd.setText(passwd);
    final JTextField tscript = new JTextField(45);
    tscript.setText(script);
    final JTextField tmodel = new JTextField(45);
    tmodel.setText(model);

    JPanel myPanel = new JPanel(new GridLayout(6, 2));
    myPanel.add(new JLabel("Szenario (von http://www.hermes.admin.ch):"));
    myPanel.add(scenarios);

    myPanel.add(new JLabel("XML Model:"));
    myPanel.add(tmodel);
    JPanel pmodel = new JPanel();
    pmodel.add(tmodel);
    JButton bmodel = new JButton("...");
    pmodel.add(bmodel);
    bmodel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model = getFile("Szenario XML Model", new String[] { "XML Model" }, new String[] { ".xml" });
            if (model != null)
                tmodel.setText(model);
        }
    });
    myPanel.add(pmodel);

    scenarios.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            try {
                Object o = e.getItem();
                tmodel.setText(crawler.getModelURL(o.toString()));
                scenario = o.toString();
            } catch (Exception e1) {
            }
        }
    });

    // Script
    myPanel.add(new JLabel("Umwandlungs-Script:"));
    JPanel pscript = new JPanel();
    pscript.add(tscript);
    JButton bscript = new JButton("...");
    pscript.add(bscript);
    myPanel.add(pscript);
    bscript.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            script = getFile("JavaScript/Freemarker Umwandlungs-Script",
                    new String[] { "JavaScript", "Freemarker" }, new String[] { ".js", ".ftl" });
            if (script != null)
                tscript.setText(script);
        }
    });

    // Zielsystem Angaben
    myPanel.add(new JLabel("Zielsystem URL:"));
    myPanel.add(tsite);
    myPanel.add(new JLabel("Zielsystem Benutzer:"));
    myPanel.add(tuser);
    myPanel.add(new JLabel("Zielsystem Password:"));
    myPanel.add(tpasswd);

    // Trick um Feld scenario und model zu setzen.
    if (scenarios.getItemCount() >= 8)
        scenarios.setSelectedIndex(8);

    // Dialog
    int result = JOptionPane.showConfirmDialog(null, myPanel, "HERMES 5 XML Model nach Fremdsystem/Format",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        site = tsite.getText();
        user = tuser.getText();
        passwd = new String(tpasswd.getPassword());
        model = tmodel.getText();
        script = tscript.getText();
    } else
        System.exit(1);

    if (model == null || script == null || script.trim().length() == 0)
        usage();

    if (script.endsWith(".js"))
        if (site == null || user == null || passwd == null || user.trim().length() == 0
                || passwd.trim().length() == 0)
            usage();
}

From source file:com.shieldsbetter.sbomg.Cli.java

private static Plan makePlan(CommandLine cmd) throws OperationException {
    Plan result;/*from   ww  w  .j  a  va  2  s. c om*/
    String[] args = cmd.getArgs();

    switch (args.length) {
    case 0: {
        File projectFile = new File("sbomg.yaml");
        if (!projectFile.exists()) {
            throw new OperationException("Zero-argument form must be "
                    + "run in a directory with an sbomg.yaml project " + "descriptor file.");
        }
        result = planFromProjectDescriptor(parseProjectDescriptor(projectFile));
        break;
    }
    case 1: {
        File inputFile = new File(args[0]);
        if (inputFile.getName().equals("sbomg.yaml")) {
            result = planFromProjectDescriptor(parseProjectDescriptor(inputFile));
        } else if (inputFile.getName().endsWith((".sbomg"))) {
            inputFile = inputFile.getAbsoluteFile();

            result = singleFilePlan(inputFile, findProjectDescriptor(inputFile));
        } else {
            throw new OperationException(
                    "Input file to one-argument " + "form must indicate an sbomg.yaml project "
                            + "descriptor file or a .sbomg model file rooted "
                            + "in a directory with a project descriptor file.");
        }

        break;
    }
    default: {
        if (args.length > 3) {
            throw new OperationException("Too many arguments.");
        }

        String packageSpec = args[1];
        String outputPathFilename;
        if (args.length == 3) {
            outputPathFilename = args[2];
        } else {
            outputPathFilename = System.getProperty("user.dir");
        }

        result = explicitPlan(new File(args[0]), packageSpec, new File(outputPathFilename));
    }
    }

    return result;
}

From source file:com.aliyun.odps.ship.common.OptionsBuilder.java

public static void buildUploadOption(String[] args) throws ParseException, IOException, ODPSConsoleException {

    DshipContext.INSTANCE.clear();// w ww  . j a  va 2s .  co  m

    CommandLineParser parser = new GnuParser();
    Options opts = getUploadOptions();
    CommandLine line = parser.parse(opts, args);

    initContext();
    // load context from config file
    loadConfig();
    processOptions(line);
    processArgs(line.getArgs(), true);
    checkParameters("upload");

    setContextValue(Constants.COMMAND, buildCommand(args));
    setContextValue(Constants.COMMAND_TYPE, "upload");
}

From source file:com.aliyun.odps.ship.common.OptionsBuilder.java

public static void buildDownloadOption(String[] args) throws ParseException, IOException, ODPSConsoleException {

    DshipContext.INSTANCE.clear();//from   ww w.  j a  va2s . c  om

    CommandLineParser parser = new GnuParser();
    Options opts = getDownloadOptions();
    CommandLine line = parser.parse(opts, args);

    initContext();
    // load context from config file
    loadConfig();
    processOptions(line);
    processArgs(line.getArgs(), false);
    setContextValue(Constants.COMMAND, buildCommand(args));
    setContextValue(Constants.COMMAND_TYPE, "download");

    checkParameters("download");

}

From source file:com.aliyun.odps.ship.common.OptionsBuilder.java

public static void buildResumeOption(String[] args) throws ParseException {

    DshipContext.INSTANCE.clear();/*from  ww  w  . j  a v  a 2s  .c o  m*/

    CommandLineParser parser = new GnuParser();
    Options opts = getResumeOptions();

    CommandLine line = parser.parse(opts, args);
    if (line.hasOption("force")) {
        DshipContext.INSTANCE.put("resume-force", "true");
    }

    String[] remains = line.getArgs();
    if (remains.length == 2) {
        DshipContext.INSTANCE.put(Constants.SESSION_ID, remains[1]);
    } else if (remains.length > 2) {
        throw new IllegalArgumentException("Unknown command\nType 'tunnel help resume' for usage.");
    }
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateRemote(String node, String target, String name, CommandLine cmd)
        throws InterruptedException {
    System.out.format("Validating %s environment on %s...%n", target, node);
    if (!Utils.isAddressReachable(node, 22)) {
        System.err.format("Unable to reach ssh port 22 on node %s.%n", node);
        return false;
    }//from   w ww  . j a  va2 s  . c om

    // args is not null.
    String argStr = String.join(" ", cmd.getArgs());
    String homeDir = Configuration.get(PropertyKey.HOME);
    String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target,
            name == null ? "" : name, argStr);
    String localCommand = String.format(
            "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand);
    String[] command = { "bash", "-c", localCommand };
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        process.waitFor();
        return process.exitValue() == 0;
    } catch (IOException e) {
        System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage());
        return false;
    }
}