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

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

Introduction

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

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:cli.CLI.java

protected void runJobManager(CommandLine cmd) {
    // String logFilename = null
    try {/*w  ww. ja  v  a 2  s.c  om*/
        // System.out.println("Initializing PIE JobManager")
        List<String> args = cmd.getArgList();
        JobManager jobManager = new JobManager(_settings, _job, args);

        for (int i = 0; i < args.size(); i++) {
            String[] keyValuePair = args.get(i).split("=");
            jobManager.getSession().addToken("Local", keyValuePair[0], keyValuePair[1]);
        }
        // logFilename = jobManager.getLogFilename()
        // viewlog(logFilename)
        // System.out.println("Running job definition " + _job)
        jobManager.runJob();
        // System.out.println("Job definition processing completed.")
        System.exit(0);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.github.lindenb.j4make.J4Make.java

public int instanceMain(final String args[]) {
    FORMAT fmt = FORMAT.DOT;/*from  w  w  w  .j a v a2s. c  o m*/
    BufferedReader in = null;
    FileOutputStream fos = null;
    try {
        final Options options = new Options();
        options.addOption(Option.builder("f").longOpt("format").argName("FORMAT")
                .desc("output format one of " + Arrays.toString(FORMAT.values())).hasArg().build());
        options.addOption(
                Option.builder("h").longOpt("help").desc("Print Help and exit").hasArg(false).build());
        options.addOption(
                Option.builder("v").longOpt("version").desc("Print version and exit").hasArg(false).build());
        options.addOption(
                Option.builder("o").longOpt("out").desc("Output file (default stdout)").hasArg().build());
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cmdLine = parser.parse(options, args);
        final List<String> arglist = cmdLine.getArgList();

        if (cmdLine.hasOption("h")) {
            HelpFormatter format = new HelpFormatter();
            format.printHelp("j4make. Pierre Lindenbaum PhD 2015 @yokofakun", options);
            return 0;
        }
        if (cmdLine.hasOption("v")) {
            System.out.println("Version: " + getVersion());
            return 0;
        }
        if (cmdLine.hasOption("f")) {
            fmt = FORMAT.valueOf(cmdLine.getOptionValue("f").toUpperCase());
        }

        if (arglist.isEmpty()) {
            LOG.debug("parsing stdin");
            in = new BufferedReader(new InputStreamReader(System.in));
        } else if (arglist.size() == 1) {
            LOG.debug("parsing " + arglist.get(0));
            in = new BufferedReader(new FileReader(arglist.get(0)));
        } else {
            LOG.error("Illegal number of arguments.");
            return -1;
        }
        this.graph = Graph.parse(in);
        in.close();
        LOG.debug("parsing done");
        GraphWriter gw = new DotWriter();
        switch (fmt) {
        case XML:
            gw = new XmlWriter();
            break;
        case GEXF:
            gw = new GexfWriter();
            break;
        case DOT:
            gw = new DotWriter();
            break;
        case RDF:
            gw = new RdfWriter();
            break;
        default:
            throw new IllegalArgumentException("" + fmt);
        }
        final OutputStream out;
        if (cmdLine.hasOption("o")) {
            final File fileout = new File(cmdLine.getOptionValue("o"));
            LOG.info("opening " + fileout);
            fos = new FileOutputStream(fileout);
            out = fos;
        } else {
            out = System.out;
        }

        gw.write(this.graph, out);

        out.flush();

        if (fos != null) {
            fos.flush();
            fos.close();
            fos = null;
        }

        return 0;
    } catch (final Exception e) {
        LOG.error("FAILURE", e);
        return -1;
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (Exception er2) {
            }
    }
}

From source file:com.netcrest.pado.tools.pado.command.history.java

@SuppressWarnings("unchecked")
@Override//from  ww w  . ja  v a  2s .  c o m
public void run(CommandLine commandLine, String command) throws Exception {
    List<String> argList = commandLine.getArgList();
    if (argList.size() > 2) {
        PadoShell.printlnError(this, "Too many arguments.");
        return;
    }
    int numEntries = 100;
    if (argList.size() == 2) {
        try {
            numEntries = Integer.parseInt(argList.get(1));
        } catch (NumberFormatException ex) {
            PadoShell.printlnError(this, "Numeric argument required.");
            return;
        } catch (Exception ex) {
            throw ex;
        }
    }
    if (commandLine.hasOption("n")) {
        history_n(numEntries);
    } else if (commandLine.hasOption("d")) {
        String value = commandLine.getOptionValue("d");
        try {
            int offset = Integer.parseInt(value);
            history_d(offset);
        } catch (NumberFormatException ex) {
            PadoShell.printlnError(this, "Numeric argument required.");
            return;
        } catch (Exception ex) {
            throw ex;
        }
    } else if (commandLine.hasOption("c")) {
        history_c();
    } else if (commandLine.hasOption("w")) {
        history_w();
    } else {
        history_l(numEntries);
    }
}

From source file:com.netcrest.pado.tools.pado.command.buffer.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*  w  w  w .ja  v  a2s  .c  om*/
public void run(CommandLine commandLine, String command) throws Exception {
    String deleteBufferName = commandLine.getOptionValue("delete");
    List<String> argList = commandLine.getArgList();
    String bufferName = null;
    if (argList.size() > 2) {
        PadoShell.printlnError(this, "Invalid command. Only one buffer name allowed.");
        return;
    } else if (argList.size() == 2) {
        bufferName = argList.get(1);
    }

    boolean isList = argList.size() == 1 && bufferName == null;

    if (deleteBufferName != null) {
        SharedCache.getSharedCache().deleteBufferInfo(deleteBufferName);
    } else if (isList) {
        if (bufferName == null) {
            Map<String, BufferInfo> map = SharedCache.getSharedCache().getBufferInfoMap();
            List list = new ArrayList(map.size());
            for (BufferInfo bi : map.values()) {
                list.add(createBufferInfoMap(bi));
            }
            PrintUtil.printList(list);
        } else {
            BufferInfo bufferInfo = SharedCache.getSharedCache().getBufferInfo(bufferName);
            if (bufferInfo == null) {
                PadoShell.printlnError(this, bufferName + ": Buffer undefined.");
            } else {
                List list = new ArrayList(1);
                list.add(createBufferInfoMap(bufferInfo));
                PrintUtil.printList(list);
            }
        }
    } else if (bufferName != null) {
        padoShell.runCommand("less -buffer " + bufferName, false);
    }
}

From source file:de.weltraumschaf.groundzero.opt.commons.OptionsParser.java

/**
 * Set all left-over non-recognized options and arguments as file names to reports.
 *
 * @param cmd must not be {@code null}//from  ww  w  .ja  v a 2 s.c  o  m
 * @param options must not be {@code null}
 */
@SuppressWarnings("unchecked") // Commons CLI uses no generics.
private void reportFileArguments(final CommandLine cmd, final CliOptions options) {
    Validate.notNull(cmd);
    Validate.notNull(options);
    options.setReportFiles(cmd.getArgList());
}

From source file:by.heap.remark.Main.java

private void checkInput(CommandLine cl, Args result, List<String> error) {
    List leftover = cl.getArgList();
    if (leftover.isEmpty()) {
        error.add("No input file or URL specified.");
    } else if (leftover.size() > 1) {
        error.add("Too many arguments.");
    } else {/*from  w  w w.  jav a2s. c  o m*/
        String arg = (String) leftover.get(0);
        if (arg.contains("://")) {
            try {
                result.urlInput = new URL(arg);
            } catch (MalformedURLException ex) {
                error.add("Malformed URL: " + ex.getMessage());
            }
        } else {
            File input = new File(arg);
            if (input.isFile()) {
                if (input.canRead()) {
                    result.fileInput = input;
                } else {
                    error.add(String.format("Unable to read input file: %s", arg));
                }
            } else {
                error.add(String.format("Input file does not exist or is not a file: %s", arg));
            }
        }
    }
}

From source file:com.netcrest.pado.tools.pado.command.mkpath.java

@SuppressWarnings({ "unchecked" })
private void handleRefid(CommandLine commandLine) {
    List<String> argList = commandLine.getArgList();
    String refid = commandLine.getOptionValue("refid");
    boolean temporal = commandLine.hasOption("temporal");
    boolean temporalLucene = commandLine.hasOption("temporalLucene");
    boolean recursive = PadoShellUtil.hasSingleLetterOption(commandLine, 'p', excludes);
    boolean verbose = PadoShellUtil.hasSingleLetterOption(commandLine, 'v', excludes);

    // Create path(s)
    List<String> fullPathList = getFullPathList(commandLine);
    if (fullPathList == null) {
        return;//www.  j ava 2s.  co m
    }

    if (temporalLucene) {
        temporal = true;
    }

    boolean createdAtLeastOnePath = false;
    IPathBiz pathBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IPathBiz.class);
    for (String fullPath : fullPathList) {
        String gridId = pathBiz.getBizContext().getGridService().getGridId(fullPath);
        if (gridId == null) {
            PadoShell.printlnError(this, fullPath + ": Unable to determine grid ID");
        } else {
            String gridPath = GridUtil.getChildPath(fullPath);
            boolean created = pathBiz.createPath(gridId, gridPath, refid, temporal, temporalLucene, recursive);
            if (created == false) {
                PadoShell.printlnError(this, fullPath + ": Path creation failed");
            } else {
                createdAtLeastOnePath = true;
                if (verbose) {
                    PadoShell.println(this, "Created path '" + fullPath + "'");
                }
            }
        }
    }
    if (createdAtLeastOnePath) {
        SharedCache.getSharedCache().refresh();
    }
}

From source file:com.netcrest.pado.tools.pado.command.mkpath.java

@SuppressWarnings("unchecked")
@Override// w w  w  .  j  ava 2  s .c  om
public void run(CommandLine commandLine, String command) throws Exception {
    List<String> argList = commandLine.getArgList();
    if (argList.size() < 1) {
        PadoShell.printlnError(this, "Path(s) must be specified.");
        return;
    }
    String refid = commandLine.getOptionValue("refid");
    if (refid != null) {
        handleRefid(commandLine);
    } else {
        handlePathType(commandLine);
    }
}

From source file:com.opengamma.integration.tool.config.ConfigImportExportTool.java

@Override
protected void doRun() {
    ToolContext toolContext = getToolContext();
    ConfigMaster configMaster = toolContext.getConfigMaster();
    PortfolioMaster portfolioMaster = toolContext.getPortfolioMaster();
    CommandLine commandLine = getCommandLine();
    @SuppressWarnings("unchecked")
    List<String> fileList = commandLine.getArgList();
    boolean portPortfolioRefs = commandLine.hasOption("portable-portfolios");
    boolean verbose = commandLine.hasOption("verbose");
    if (commandLine.hasOption("load")) {
        checkForInvalidOption("type");
        checkForInvalidOption("name");
        checkForInvalidOption("save");
        boolean persist = !commandLine.hasOption("do-not-persist"); // NOTE: inverted logic here
        ConfigLoader configLoader = new ConfigLoader(configMaster, portfolioMaster, portPortfolioRefs, persist,
                verbose);/*w  w w  .j  a  va 2s  .c om*/
        if (fileList.size() > 0) {
            boolean problems = false;
            for (String fileName : fileList) {
                File file = new File(fileName);
                if (!file.exists()) {
                    s_logger.error("Could not find file:" + fileName);
                    problems = true;
                }
                if (!file.canRead()) {
                    s_logger.error("Not able to read file (permissions?):" + fileName);
                    problems = true;
                }
            }
            if (problems) {
                s_logger.error("Problems with one or more files, aborting.");
                System.exit(1);
            }
            try {
                for (String fileName : fileList) {
                    if (verbose) {
                        s_logger.info("Processing " + fileName);
                    }
                    FileInputStream inputStream = new FileInputStream(fileName);
                    configLoader.loadConfig(inputStream);
                }
            } catch (IOException ioe) {
                if (verbose) {
                    s_logger.error(
                            "An I/O error occurred while processing a file (run with -v to see stack trace)");
                } else {
                    s_logger.error("An I/O error occurred while processing a file", ioe);
                }
            }
        } else {
            if (verbose) {
                s_logger.info("No file name given, assuming STDIN");
            }
            configLoader.loadConfig(System.in);
        }
    } else if (commandLine.hasOption("save")) {
        if (verbose) {
            s_logger.info("Save option active");
        }
        checkForInvalidOption("do-not-persist");
        List<String> types = getTypes();
        List<String> names = getNames();
        PrintStream outputStream;
        if (fileList.size() == 1) {
            try {
                outputStream = new PrintStream(new FileOutputStream(fileList.get(0)));
            } catch (FileNotFoundException ex) {
                s_logger.error("Couldn't file file " + fileList.get(0));
                System.exit(1);
                return;
            }
        } else {
            outputStream = System.out;
        }
        ConfigSaver configSaver = new ConfigSaver(configMaster, portfolioMaster, names, types,
                portPortfolioRefs, verbose);
        configSaver.saveConfigs(outputStream);
        System.out.println("Warning: file may have been created in installation base directory");
    }
}

From source file:com.netcrest.pado.tools.pado.command.export.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from   w  w w .j  ava  2 s.com
public void run(CommandLine commandLine, String command) throws Exception {
    List<String> argList = commandLine.getArgList();
    if (argList.size() < 3) {
        PadoShell.printlnError(this, "Invalid number of arguments.");
        return;
    }

    String fromPath = argList.get(1);
    String toFilePath = argList.get(2);

    boolean isRefresh = commandLine.hasOption("refresh");
    boolean isForce = PadoShellUtil.hasSingleLetterOption(commandLine, 'f', "refresh");
    boolean includeKeys = PadoShellUtil.hasSingleLetterOption(commandLine, 'k', "refresh");
    boolean includeValues = PadoShellUtil.hasSingleLetterOption(commandLine, 'v', "refresh");
    boolean isSchema = includeKeys && includeValues || (includeKeys == false && includeValues == false);

    IPathBiz pathBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IPathBiz.class);
    String gridId = padoShell.getGridId(fromPath);
    String gridPath = padoShell.getGridPath(fromPath);
    if (pathBiz.exists(gridId, gridPath) == false) {
        PadoShell.printlnError(this, fromPath + ": Path does not exist.");
        return;
    }

    less l = (less) padoShell.getCommand("less");
    IScrollableResultSet rs = l.queryPath(fromPath, isRefresh, includeKeys, includeValues);
    if (rs == null || rs.toList() == null || rs.toList().size() == 0) {
        PadoShell.printlnError(this, fromPath + ": Path empty. File not created.");
        return;
    }

    File csvFile;
    if (toFilePath.endsWith(".csv") == false) {
        csvFile = new File(toFilePath + ".csv");
    } else {
        csvFile = new File(toFilePath);
    }
    String fn = csvFile.getName().substring(0, csvFile.getName().lastIndexOf(".csv"));
    File schemaFile = new File(fn + ".schema");

    if (isForce == false && padoShell.isInteractiveMode() && csvFile.exists()) {
        PadoShell.println(this, toFilePath + ": File exists. Do you want to overwrite?");
        PadoShell.println("Enter 'continue' to continue or any other keys to abort:");
        String line = padoShell.readLine("");
        if (line.equals("continue") == false) {
            PadoShell.println("Command aborted.");
            return;
        }
    }

    if (isSchema) {
        List list = rs.toList();
        Struct struct = (Struct) list.get(0);
        Object key = struct.getFieldValues()[0];
        Object value = struct.getFieldValues()[1];
        PrintWriter schemaWriter = new PrintWriter(schemaFile);
        List keyList = null;
        if (value instanceof Map) {
            // Must iterate the entire map to get all unique keys
            Map valueMap = (Map) value;
            Set keySet = valueMap.keySet();
            HashSet set = new HashSet(keySet.size(), 1f);
            set.addAll(keySet);
            keyList = new ArrayList(set);
            Collections.sort(keyList);
        }
        OutputUtil.printSchema(schemaWriter, gridPath, key, value, keyList, OutputUtil.TYPE_KEYS_VALUES, ",",
                PadoShellUtil.getIso8601DateFormat(), true, true);
        schemaWriter.close();
    }

    PrintWriter csvWriter = new PrintWriter(csvFile);
    int printType;
    if (includeKeys && includeValues == false) {
        printType = OutputUtil.TYPE_KEYS;
    } else if (includeKeys == false && includeValues) {
        printType = OutputUtil.TYPE_VALUES;
    } else {
        printType = OutputUtil.TYPE_KEYS_VALUES;
    }
    try {
        OutputUtil.printScrollableResultSet(csvWriter, rs, ",", printType,
                PadoShellUtil.getIso8601DateFormat());
    } finally {
        if (csvWriter != null) {
            csvWriter.close();
        }
    }
}