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:com.yahoo.yqlplus.engine.tools.YQLPlusRun.java

@SuppressWarnings("unchecked")
public int run(CommandLine command) throws Exception {
    String script = null;/*  w  w  w.j a v a  2 s . c  om*/
    String filename = null;
    if (command.hasOption("command")) {
        script = command.getOptionValue("command");
        filename = "<command line>";
    }
    List<String> scriptAndArgs = (List<String>) command.getArgList();
    if (filename == null && scriptAndArgs.size() < 1) {
        System.err.println("No script specified.");
        return -1;
    } else if (script == null) {
        filename = scriptAndArgs.get(0);
        Path scriptPath = Paths.get(filename);
        if (!Files.isRegularFile(scriptPath)) {
            System.err.println(scriptPath + " is not a file.");
            return -1;
        }
        script = Charsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(scriptPath))).toString();
    }
    List<String> paths = Lists.newArrayList();
    if (command.hasOption("path")) {
        paths.addAll(Arrays.asList(command.getOptionValues("path")));
    }
    // TODO: this isn't going to be very interesting without some sources
    Injector injector = Guice.createInjector(new JavaEngineModule());
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(script);
    if (command.hasOption("source")) {
        program.dump(System.out);
        return 0;
    }
    // TODO: read command line arguments to pass to program
    ExecutorService outputThreads = Executors.newSingleThreadExecutor();
    ProgramResult result = program.run(Maps.<String, Object>newHashMap(), true);
    for (String name : result.getResultNames()) {
        final ListenableFuture<YQLResultSet> future = result.getResult(name);
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    YQLResultSet resultSet = future.get();
                    System.out.println(new String((byte[]) resultSet.getResult()));
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

            }
        }, outputThreads);
    }
    Future<TraceRequest> done = result.getEnd();
    try {
        done.get(10000L, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
    outputThreads.awaitTermination(1L, TimeUnit.SECONDS);
    return 0;
}

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

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void run(CommandLine commandLine, String command) throws Exception {
    String path = commandLine.getOptionValue("path");
    String bufferName = commandLine.getOptionValue("buffer");
    List<String> argList = commandLine.getArgList();

    if (path != null && bufferName != null) {
        PadoShell.printlnError(this, "Specifying both path and buffer not allowed. Only one option allowed.");
        return;/*  w w  w  .  j a  v a 2s .  c  o m*/
    }
    if (path == null && bufferName == null) {
        path = padoShell.getCurrentPath();
    }

    if (path != null) {

        if (commandLine.getArgList().size() < 2) {
            PadoShell.printlnError(this, "Invalid command. Key or key fields must be specified.");
            return;
        }
        String input = (String) commandLine.getArgList().get(1);
        Object key = null;
        Object value;
        if (input.startsWith("'")) {
            int lastIndex = -1;
            if (input.endsWith("'") == false) {
                lastIndex = input.length();
            } else {
                lastIndex = input.lastIndexOf("'");
            }
            if (lastIndex <= 1) {
                PadoShell.printlnError(this, "Invalid key. Empty string not allowed.");
                return;
            }
            key = input.subSequence(1, lastIndex); // lastIndex exclusive
        } else {
            key = ObjectUtil.getPrimitive(padoShell, input, false);
            if (key == null) {
                key = padoShell.getQueryKey(argList, 1);
            }
        }
        if (key == null) {
            return;
        }
        // long startTime = System.currentTimeMillis();
        if (padoShell.isShowTime() && padoShell.isShowResults()) {
            TimerUtil.startTimer();
        }

        String fullPath = padoShell.getFullPath(path);
        String gridPath = GridUtil.getChildPath(fullPath);
        String gridId = SharedCache.getSharedCache().getGridId(fullPath);
        IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IGridMapBiz.class, gridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
        value = gridMapBiz.get(key);

        if (value == null) {
            PadoShell.printlnError(this, "Key not found.");
            return;
        }

        HashMap map = new HashMap();
        map.put(key, value);
        if (padoShell.isShowResults()) {
            PrintUtil.printEntries(map, map.size(), null);
        }

    } else {
        // Get key from the buffer
        BufferInfo bufferInfo = SharedCache.getSharedCache().getBufferInfo(bufferName);
        if (bufferInfo == null) {
            PadoShell.printlnError(this, bufferName + ": Buffer undefined.");
            return;
        }
        String gridId = bufferInfo.getGridId();
        String gridPath = bufferInfo.getGridPath();
        if (gridId == null || gridPath == null) {
            PadoShell.printlnError(this, bufferName + ": Invalid buffer. This buffer does not contain keys.");
            return;
        }
        Map<Integer, Object> keyMap = bufferInfo.getKeyMap(argList, 1);
        if (keyMap.size() > 0) {
            IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                    .newInstance(IGridMapBiz.class, gridPath);
            gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
            Map map = gridMapBiz.getAll(keyMap.values());
            PrintUtil.printEntries(map, map.size(), null);
        }
    }
}

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

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   ww  w  . jav  a  2 s . c  o  m*/
public void run(CommandLine commandLine, String command) throws Exception {
    boolean isRecursive = commandLine.hasOption("-r") || commandLine.hasOption("-R");

    List<String> argList = (List<String>) commandLine.getArgList();
    if (argList.size() < 3) {
        PadoShell.printlnError(this, "Invalid number of arguments.");
        return;
    }
    String sourcePath = argList.get(1);
    String targetPath = argList.get(2);

    String sourceGridId = padoShell.getGridId(sourcePath);
    String targetGridId = padoShell.getGridId(targetPath);
    String sourceGridPath = padoShell.getGridPath(sourcePath);
    String targetGridPath = padoShell.getGridPath(targetPath);
    String sourceFullPath = padoShell.getFullPath(sourcePath);
    String targetFullPath = padoShell.getFullPath(targetPath);

    // If source and target are in the same grid then do copy in the grid,
    // otherwise, do it from here.
    if (sourceGridId.equals(targetGridId)) {

        // Do copy in the grid.
        IPathBiz pathBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IPathBiz.class);
        pathBiz.copy(sourceGridId, sourceGridPath, targetGridPath);

    } else {

        IPathBiz pathBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IPathBiz.class);
        if (pathBiz.exists(sourceGridId, sourceGridPath) == false) {
            PadoShell.printlnError(this, sourcePath + ": Source path does not exist.");
            return;
        }
        IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IGridMapBiz.class);
        gridMapBiz.setGridPath(sourceGridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(sourceGridId);
        Map.Entry sourceEntry = gridMapBiz.getRandomEntry();
        if (sourceEntry == null) {
            return;
        }

        // Get target entry if the target grid path exists
        if (pathBiz.exists(targetGridId, targetGridPath) == false) {
            // See if we can create the path
            IPathBiz.PathType pathType = pathBiz.getPathType(sourceGridId, sourceGridPath);
            if (pathType == IPathBiz.PathType.NOT_SUPPORTED) {
                PadoShell.printlnError(this, "Unable to copy. Path type not supported.");
                return;
            }
            boolean created = pathBiz.createPath(targetGridId, targetGridPath, pathType, false);
            if (created == false) {
                PadoShell.printlnError(this, targetGridPath + ": Target path creation failed.");
                return;
            }
            // refresh required to get the newly created path info
            SharedCache.getSharedCache().refresh();
        } else {

            // Get a target entry to determine the key and value types.
            gridMapBiz.setGridPath(targetGridPath);
            gridMapBiz.getBizContext().getGridContextClient().setGridIds(targetGridId);
            Map.Entry targetEntry = gridMapBiz.getRandomEntry();
            if (targetEntry != null) {
                checkIncompatibleTypes(sourceEntry.getKey(), sourceEntry.getValue(), targetEntry.getKey(),
                        targetEntry.getValue());
            }
        }

        gridMapBiz.setGridPath(targetGridPath);
        gridMapBiz.getBizContext().getGridContextClient().setGridIds(targetGridId);
        IIndexMatrixBiz imBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(IIndexMatrixBiz.class, true);
        imBiz.setQueryType(QueryType.OQL);
        imBiz.setGridIds(sourceGridId);
        // imBiz.setFetchSize(10000);
        String queryString = String.format(less.QUERY_KEYS_VALUES, sourceFullPath);
        IScrollableResultSet rs = imBiz.execute(queryString);
        HashMap map = new HashMap(imBiz.getFetchSize());
        do {
            List<Struct> list = rs.toList();
            for (Struct struct : list) {
                map.put(struct.getFieldValues()[0], struct.getFieldValues()[1]);
            }
            gridMapBiz.putAll(map);
            map.clear();
        } while (rs.nextSet());
        SharedCache.getSharedCache().refresh();
    }
}

From source file:com.antsdb.saltedfish.nosql.DumpRow.java

private void run(String[] args) throws Exception {
    CommandLine line = parse(getOptions(), args);

    // help/*from   w  w w .j  av  a  2s.  c  o  m*/

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("dumprow <table id> <row key base64>", getOptions());
        return;
    }

    // arguments

    if (line.getArgList().size() != 2) {
        println("error: invalid command line arguments");
        return;
    }
    this.tableId = Integer.parseInt(line.getArgList().get(0));
    this.key = Base64.getDecoder().decode(line.getArgList().get(1));
    this.pKey = KeyBytes.allocSet(this.heap, this.key).getAddress();

    // options

    this.home = new File(line.getOptionValue("home"));
    this.isVerbose = line.hasOption('v');
    this.dumpHex = line.hasOption("hex");
    this.dumpValues = line.hasOption("values");

    // validate

    if (!this.home.isDirectory()) {
        println("error: invalid home directory {}", this.home);
        return;
    }
    if (!new File(this.home, "checkpoint.bin").exists()) {
        println("error: invalid home directory {}", this.home);
        return;
    }

    // init space manager

    this.spaceman = new SpaceManager(this.home, false);
    spaceman.init();

    // proceed

    dump();
}

From source file:com.monami_ya.mwe2.launch.runtime.AWorkflowLauncher.java

@Override
public void run(String[] args) {
    Options options = getOptions();//from w  w  w  . j ava  2 s . c  o m
    final CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.getArgs().length == 0)
            throw new ParseException("No module name specified.");
        if (line.getArgs().length > 1)
            throw new ParseException("Only one module name expected. But " + line.getArgs().length
                    + " were passed (" + line.getArgList() + ")");

        String moduleName = line.getArgs()[0];
        Map<String, String> params = new HashMap<String, String>();
        String[] optionValues = line.getOptionValues(PARAM);
        if (optionValues != null) {
            for (String string : optionValues) {
                int index = string.indexOf('=');
                if (index == -1) {
                    throw new ParseException(
                            "Incorrect parameter syntax '" + string + "'. It should be 'name=value'");
                }
                String name = string.substring(0, index);
                String value = string.substring(index + 1);
                if (params.put(name, value) != null) {
                    throw new ParseException("Duplicate parameter '" + name + "'.");
                }
            }
        }
        // check OperationCanceledException is accessible
        OperationCanceledException.class.getName();

        Injector injector = new AWorkflowStandaloneSetup().createInjectorAndDoEMFRegistration();
        Mwe2Runner mweRunner = injector.getInstance(Mwe2Runner.class);
        if (moduleName.contains("/")) {
            mweRunner.run(URI.createURI(moduleName), params);
        } else {
            mweRunner.run(moduleName, params);
        }
    } catch (NoClassDefFoundError e) {
        if ("org/eclipse/core/runtime/OperationCanceledException".equals(e.getMessage())) {
            System.err.println("Could not load class: org.eclipse.core.runtime.OperationCanceledException");
            System.err.println("Add org.eclipse.equinox.common to the class path.");
        } else {
            throw e;
        }
    } catch (final ParseException exp) {
        final HelpFormatter formatter = new HelpFormatter();
        System.err.println("Parsing arguments failed.  Reason: " + exp.getMessage());
        formatter.printHelp("java " + AWorkflowLauncher.class.getName() + " some.mwe2.Module [options]\n",
                options);
        return;
    }
}

From source file:com.hp.mqm.clt.CliParser.java

private boolean addInputFilesToSettings(CommandLine cmd, Settings settings) {
    List<String> argList = cmd.getArgList();
    List<String> inputFiles = new LinkedList<String>();
    for (String inputFile : argList) {
        if (!new File(inputFile).isFile()) {
            System.out.println("Path '" + inputFile + "' does not lead to a file");
            continue;
        }/*from www .  j  a  v a  2  s.  c o m*/
        if (!new File(inputFile).canRead()) {
            System.out.println("File '" + inputFile + "' is not readable");
            continue;
        }
        inputFiles.add(inputFile);
    }

    if (inputFiles.isEmpty()) {
        System.out.println("No readable files with tests to push");
        return false;
    }

    settings.setInputXmlFileNames(inputFiles);
    return true;
}

From source file:com.izforge.izpack.compiler.cli.CliAnalyzer.java

/**
 * Analyze commandLine and fill compilerData.
 *
 * @param commandLine CommandLine to analyze
 * @return filled compilerData with informations
 *//*from  w ww  .  j  av  a2 s  .  c o  m*/
private CompilerData analyzeCommandLine(CommandLine commandLine) {
    validateCommandLine(commandLine);
    String installFile;
    String baseDir = ".";
    String output = "install.jar";

    if (commandLine.hasOption("?")) {
        printHelp();
        throw new HelpRequestedException();
    }
    List argList = commandLine.getArgList();
    installFile = (String) argList.get(0);
    if (commandLine.hasOption(ARG_BASEDIR)) {
        baseDir = commandLine.getOptionValue(ARG_BASEDIR).trim();
    }
    if (commandLine.hasOption(ARG_OUTPUT)) {
        output = commandLine.getOptionValue(ARG_OUTPUT).trim();
    }
    CompilerData compilerData = new CompilerData(installFile, baseDir, output, false);

    if (commandLine.hasOption(ARG_COMPRESSION_FORMAT)) {
        compilerData.setComprFormat(commandLine.getOptionValue(ARG_COMPRESSION_FORMAT).trim());
    }
    if (commandLine.hasOption(ARG_COMPRESSION_LEVEL)) {
        compilerData.setComprLevel(Integer.parseInt(commandLine.getOptionValue(ARG_COMPRESSION_LEVEL).trim()));
    }
    if (commandLine.hasOption(ARG_IZPACK_HOME)) {
        CompilerData.setIzpackHome(commandLine.getOptionValue(ARG_IZPACK_HOME).trim());
    }
    if (commandLine.hasOption(ARG_KIND)) {
        compilerData.setKind(commandLine.getOptionValue(ARG_KIND).trim());
    }

    return compilerData;
}

From source file:com.facebook.stetho.dumpapp.Dumper.java

/**
 * @throws ParseException If any args syntax constraint is violated and the dump was not able to
 *     proceed./*from   w  ww.ja  va  2  s .com*/
 * @throws DumpException Human readable error executing the dump command.
 */
private int doDump(InputStream input, PrintStream out, PrintStream err, String[] args)
        throws ParseException, DumpException {
    CommandLine parsedArgs = mParser.parse(mGlobalOptions.options, args, true /* stopAtNonOption */);

    if (parsedArgs.hasOption(mGlobalOptions.optionHelp.getOpt())) {
        dumpUsage(out);
        return 0;
    } else if (parsedArgs.hasOption(mGlobalOptions.optionListPlugins.getOpt())) {
        dumpAvailablePlugins(out);
        return 0;
    } else if (!parsedArgs.getArgList().isEmpty()) {
        dumpPluginOutput(input, out, err, parsedArgs);
        return 0;
    } else {
        // Didn't understand the options, spit out help but use a non-success exit code.
        dumpUsage(err);
        return 1;
    }
}

From source file:com.hp.mqm.clt.CliParser.java

private boolean areCmdArgsValid(CommandLine cmd) {
    List<String> argList = cmd.getArgList();
    if (argList.isEmpty()) {
        System.out.println("At least one XML file must be specified as input for push");
        return false;
    }//from   w w  w  . j av  a 2  s  .  c o m

    for (String arg : argsWithSingleOccurrence) {
        if (cmd.getOptionProperties(arg).size() > 1) {
            System.out.println("Only single occurrence is allowed for argument: '" + arg + "'");
            return false;
        }
    }

    if (cmd.hasOption("i")) {
        for (String arg : argsRestrictedForInternal) {
            if (cmd.hasOption(arg)) {
                System.out.println("Invalid argument for internal mode: '" + arg + "'");
                return false;
            }
        }
    }

    if (!isTagFormatValid(cmd, "t") || !isTagFormatValid(cmd, "f")) {
        return false;
    }

    String configurationFile = cmd.getOptionValue("c");
    if (configurationFile != null && !(new File(configurationFile).canRead())) {
        System.out.println("Can not read the configuration file: " + configurationFile);
        return false;
    }

    String passwordFile = cmd.getOptionValue("password-file");
    if (passwordFile != null && !(new File(passwordFile).canRead())) {
        System.out.println("Can not read the password file: " + passwordFile);
        return false;
    }

    String proxyPasswordFile = cmd.getOptionValue("proxy-password-file");
    if (proxyPasswordFile != null && !new File(proxyPasswordFile).canRead()) {
        System.out.println("Can not read the proxy password file: " + passwordFile);
        return false;
    }

    String outputFilePath = cmd.getOptionValue("o");
    if (outputFilePath != null) {
        if (argList.size() != 1) {
            System.out.println("Only single JUnit input file is allowed for output mode");
            return false;
        }
        File outputFile = new File(outputFilePath);
        if (!outputFile.exists()) {
            try {
                if (!outputFile.createNewFile()) {
                    System.out.println("Can not create the output file: " + outputFile.getAbsolutePath());
                    return false;
                }
            } catch (IOException e) {
                System.out.println("Can not create the output file: " + outputFile.getAbsolutePath());
                return false;
            }
        }
        if (!outputFile.canWrite()) {
            System.out.println("Can not write to the output file: " + outputFile.getAbsolutePath());
            return false;
        }
    }
    return true;
}

From source file:com.ery.dimport.daemon.DImportMasterStart.java

public int run(String args[]) throws Exception {
    Options opt = new Options();// ?? --param
    opt.addOption("debug", true, "debug type");// EStormConstant.DebugType
    CommandLine cmd;
    try {//from w w w.j av  a2  s.  c o m
        cmd = new GnuParser().parse(opt, args);
    } catch (ParseException e) {
        LOG.error("Could not parse: ", e);
        usage(null);
        return 1;
    }
    // if (test() > 0)
    // return 1;
    String debug = cmd.getOptionValue("debug");
    if (debug != null) {
        DImportConstant.DebugType = Integer.parseInt(debug);
    }
    List<String> remainingArgs = cmd.getArgList();
    if (remainingArgs.size() < 1) {
        usage(null);
        return 1;
    }
    String command = remainingArgs.get(0);
    if (command.equals("start")) {
        return startMaster();
    } else if (command.equals("stop")) {
        if (remainingArgs.size() == 1) {
            LOG.error("need taskId for stop order");
            usage("need taskId for stop order");
        }
        usage("??task");
        String taskId = remainingArgs.get(1);
        return 0;
    }
    return 0;
}