Java Code Examples for org.apache.commons.cli.CommandLine#getArgList()

The following examples show how to use org.apache.commons.cli.CommandLine#getArgList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CWLEngineLauncherTest.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCommands0() {
    try {
        CWLExecLauncher launcher = new CWLExecLauncher();
        Options options = launcher.getCommandOptions();
        // case 0
        String[] args = new String[3];
        args[0] = "run";
        args[1] = "/opt/cwl/workflow.cwl";
        args[2] = "/opt/cwl/workflow.settings";
        CommandLine commandLine = parser.parse(options, args);
        List<String> argList = commandLine.getArgList();
        Assert.assertNotNull(argList);
        Assert.assertEquals(3, argList.size());
        Assert.assertFalse(commandLine.hasOption("o"));
        Assert.assertNull(commandLine.getOptionValue("o"));
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}
 
Example 2
Source File: Dumper.java    From weex with Apache License 2.0 6 votes vote down vote up
private void dumpPluginOutput(InputStream input,
    PrintStream out,
    PrintStream err,
    CommandLine parsedArgs) throws DumpException {
  List<String> args = new ArrayList(parsedArgs.getArgList());
  if (args.size() < 1) {
    throw new DumpException("Expected plugin argument");
  }
  String pluginName = args.remove(0);

  DumperPlugin plugin = mDumperPlugins.get(pluginName);
  if (plugin == null) {
    throw new DumpException("No plugin named '" + pluginName + "'");
  }

  DumperContext dumperContext = new DumperContext(input, out, err, mParser, args);
  plugin.dump(dumperContext);
}
 
Example 3
Source File: CWLEngineLauncherTest.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCommands4() {
    try {
        CWLExecLauncher launcher = new CWLExecLauncher();
        Options options = launcher.getCommandOptions();
        // case 0
        String[] args = new String[1];
        args[0] = "list";
        CommandLine commandLine = parser.parse(options, args);
        List<String> argList = commandLine.getArgList();
        Assert.assertNotNull(argList);
        Assert.assertEquals(1, argList.size());
        Assert.assertNull(commandLine.getOptionValue("o"));
        Assert.assertNull(commandLine.getOptionValue("w"));
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}
 
Example 4
Source File: CWLEngineLauncherTest.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCommands5() {
    try {
        CWLExecLauncher launcher = new CWLExecLauncher();
        Options options = launcher.getCommandOptions();
        // case 0
        String[] args = new String[2];
        args[0] = "info";
        args[1] = "12345";
        CommandLine commandLine = parser.parse(options, args);
        List<String> argList = commandLine.getArgList();
        Assert.assertNotNull(argList);
        Assert.assertEquals(2, argList.size());
        Assert.assertNull(commandLine.getOptionValue("o"));
        Assert.assertNull(commandLine.getOptionValue("w"));
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}
 
Example 5
Source File: CWLEngineLauncherTest.java    From cwlexec with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCommands6() {
    try {
        CWLExecLauncher launcher = new CWLExecLauncher();
        Options options = launcher.getCommandOptions();
        // case 0
        String[] args = new String[2];
        args[0] = "-l";
        args[1] = "12345";
        CommandLine commandLine = parser.parse(options, args);
        List<String> argList = commandLine.getArgList();
        Assert.assertNotNull(argList);
        Assert.assertEquals(1, argList.size());
        Assert.assertEquals("12345", argList.get(0));
        Assert.assertTrue(commandLine.hasOption("l"));
        Assert.assertNull(commandLine.getOptionValue("w"));
    } catch (Exception e) {
        Assert.assertTrue(false);
    }
}
 
Example 6
Source File: AbstractCodahaleFixtureGenerator.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
public AbstractCodahaleFixtureGenerator(String[] args,
                                        Options options) throws Exception {
  Preconditions.checkNotNull(args);
  Preconditions.checkNotNull(options);

  CommandLineParser parser = new DefaultParser();
  try {
    CommandLine cmdLine = parser.parse(options, args);
    if (!cmdLine.getArgList().isEmpty()) {
      throw new ParseException("Unexpected extra arguments: " +
                               cmdLine.getArgList());
    }
    config = new MapConfiguration(Maps.<String, Object>newHashMap());
    for (Option option : cmdLine.getOptions()) {
      config.addProperty(option.getLongOpt(), option.getValue());
    }
  } catch (ParseException ex) {
    IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
    printUsageMessage(System.err, options);
    throw ex;
  }
}
 
Example 7
Source File: ImporterCLI.java    From pygradle with Apache License 2.0 5 votes vote down vote up
private static void importPackages(CommandLine line, File repoPath) {
    final DependencySubstitution replacements = new DependencySubstitution(buildSubstitutionMap(line), buildForceMap(line));
    Set<String> processedDependencies = new HashSet<>();
    for (String dependency : line.getArgList()) {
        DependencyDownloader artifactDownloader;

        if (dependency.split(":").length == 2) {
            artifactDownloader = new SdistDownloader(dependency, repoPath, replacements, processedDependencies);
        } else if (dependency.split(":").length == 3) {
            artifactDownloader = new WheelsDownloader(dependency, repoPath, replacements, processedDependencies);
        } else {
            String errMsg = "Unable to parse the dependency "
                + dependency
                + ".\nThe format of dependency should be either <module>:<revision> for source distribution "
                + "or <module>:<revision>:<classifier> for Wheels.";

            if (line.hasOption("lenient")) {
                logger.error(errMsg);
                continue;
            }
            throw new IllegalArgumentException(errMsg);
        }

        artifactDownloader.download(
            line.hasOption("latest"),
            line.hasOption("pre"),
            line.hasOption("extras"),
            line.hasOption("lenient")
        );
    }
}
 
Example 8
Source File: RegistryCli.java    From big-c with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public int ls(String[] args) {

  Options lsOption = new Options();
  CommandLineParser parser = new GnuParser();
  try {
    CommandLine line = parser.parse(lsOption, args);

    List<String> argsList = line.getArgList();
    if (argsList.size() != 2) {
      return usageError("ls requires exactly one path argument", LS_USAGE);
    }
    if (!validatePath(argsList.get(1))) {
      return -1;
    }

    try {
      List<String> children = registry.list(argsList.get(1));
      for (String child : children) {
        sysout.println(child);
      }
      return 0;

    } catch (Exception e) {
      syserr.println(analyzeException("ls", e, argsList));
    }
    return -1;
  } catch (ParseException exp) {
    return usageError("Invalid syntax " + exp, LS_USAGE);
  }
}
 
Example 9
Source File: PruneColumnsCommand.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(CommandLine options) throws Exception {
  List<String> args = options.getArgList();
  Path inputFile = new Path(args.get(0));
  Path outputFile = new Path(args.get(1));
  List<String> cols = args.subList(2, args.size());

  Set<ColumnPath> prunePaths = convertToColumnPaths(cols);

  ParquetMetadata pmd = ParquetFileReader.readFooter(conf, inputFile, ParquetMetadataConverter.NO_FILTER);
  FileMetaData metaData = pmd.getFileMetaData();
  MessageType schema = metaData.getSchema();
  List<String> paths = new ArrayList<>();
  getPaths(schema, paths, null);

  for (String col : cols) {
    if (!paths.contains(col)) {
      LOG.warn("Input column name {} doesn't show up in the schema of file {}", col, inputFile.getName());
    }
  }

  ParquetFileWriter writer = new ParquetFileWriter(conf,
    pruneColumnsInSchema(schema, prunePaths), outputFile, ParquetFileWriter.Mode.CREATE);

  writer.start();
  writer.appendFile(HadoopInputFile.fromPath(inputFile, conf));
  writer.end(metaData.getKeyValueMetaData());
}
 
Example 10
Source File: RegistryCli.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public int rm(String[] args) {
  Option recursive = OptionBuilder.withArgName("recursive")
                                  .withDescription("delete recursively")
                                  .create("r");

  Options rmOption = new Options();
  rmOption.addOption(recursive);

  boolean recursiveOpt = false;

  CommandLineParser parser = new GnuParser();
  try {
    CommandLine line = parser.parse(rmOption, args);

    List<String> argsList = line.getArgList();
    if (argsList.size() != 2) {
      return usageError("RM requires exactly one path argument", RM_USAGE);
    }
    if (!validatePath(argsList.get(1))) {
      return -1;
    }

    try {
      if (line.hasOption("r")) {
        recursiveOpt = true;
      }

      registry.delete(argsList.get(1), recursiveOpt);
      return 0;
    } catch (Exception e) {
      syserr.println(analyzeException("rm", e, argsList));
    }
    return -1;
  } catch (ParseException exp) {
    return usageError("Invalid syntax " + exp.toString(), RM_USAGE);
  }
}
 
Example 11
Source File: RegistryCli.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public int mknode(String[] args) {
  Options mknodeOption = new Options();
  CommandLineParser parser = new GnuParser();
  try {
    CommandLine line = parser.parse(mknodeOption, args);

    List<String> argsList = line.getArgList();
    if (argsList.size() != 2) {
      return usageError("mknode requires exactly one path argument",
          MKNODE_USAGE);
    }
    if (!validatePath(argsList.get(1))) {
      return -1;
    }

    try {
      registry.mknode(args[1], false);
      return 0;
    } catch (Exception e) {
      syserr.println(analyzeException("mknode", e, argsList));
    }
    return -1;
  } catch (ParseException exp) {
    return usageError("Invalid syntax " + exp.toString(), MKNODE_USAGE);
  }
}
 
Example 12
Source File: RegistryCli.java    From big-c with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public int rm(String[] args) {
  Option recursive = OptionBuilder.withArgName("recursive")
                                  .withDescription("delete recursively")
                                  .create("r");

  Options rmOption = new Options();
  rmOption.addOption(recursive);

  boolean recursiveOpt = false;

  CommandLineParser parser = new GnuParser();
  try {
    CommandLine line = parser.parse(rmOption, args);

    List<String> argsList = line.getArgList();
    if (argsList.size() != 2) {
      return usageError("RM requires exactly one path argument", RM_USAGE);
    }
    if (!validatePath(argsList.get(1))) {
      return -1;
    }

    try {
      if (line.hasOption("r")) {
        recursiveOpt = true;
      }

      registry.delete(argsList.get(1), recursiveOpt);
      return 0;
    } catch (Exception e) {
      syserr.println(analyzeException("rm", e, argsList));
    }
    return -1;
  } catch (ParseException exp) {
    return usageError("Invalid syntax " + exp.toString(), RM_USAGE);
  }
}
 
Example 13
Source File: CsvBulkLoadTool.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the commandline arguments, throws IllegalStateException if mandatory arguments are
 * missing.
 *
 * @param args supplied command line arguments
 * @return the parsed command line
 */
CommandLine parseOptions(String[] args) {

    Options options = getOptions();

    CommandLineParser parser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = parser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit("Error parsing command line options: " + e.getMessage(), options);
    }

    if (cmdLine.hasOption(HELP_OPT.getOpt())) {
        printHelpAndExit(options, 0);
    }

    if (!cmdLine.hasOption(TABLE_NAME_OPT.getOpt())) {
        throw new IllegalStateException(TABLE_NAME_OPT.getLongOpt() + " is a mandatory " +
                "parameter");
    }

    if (!cmdLine.getArgList().isEmpty()) {
        throw new IllegalStateException("Got unexpected extra parameters: "
                + cmdLine.getArgList());
    }

    if (!cmdLine.hasOption(INPUT_PATH_OPT.getOpt())) {
        throw new IllegalStateException(INPUT_PATH_OPT.getLongOpt() + " is a mandatory " +
                "parameter");
    }

    return cmdLine;
}
 
Example 14
Source File: MergeCommand.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(CommandLine options) throws Exception {
  // Prepare arguments
  List<String> args = options.getArgList();
  List<Path> inputFiles = getInputFiles(args.subList(0, args.size() - 1));
  Path outputFile = new Path(args.get(args.size() - 1));

  // Merge schema and extraMeta
  FileMetaData mergedMeta = mergedMetadata(inputFiles);
  PrintWriter out = new PrintWriter(Main.out, true);

  // Merge data
  ParquetFileWriter writer = new ParquetFileWriter(conf,
          mergedMeta.getSchema(), outputFile, ParquetFileWriter.Mode.CREATE);
  writer.start();
  boolean tooSmallFilesMerged = false;
  for (Path input: inputFiles) {
    if (input.getFileSystem(conf).getFileStatus(input).getLen() < TOO_SMALL_FILE_THRESHOLD) {
      out.format("Warning: file %s is too small, length: %d\n",
        input,
        input.getFileSystem(conf).getFileStatus(input).getLen());
      tooSmallFilesMerged = true;
    }

    writer.appendFile(HadoopInputFile.fromPath(input, conf));
  }

  if (tooSmallFilesMerged) {
    out.println("Warning: you merged too small files. " +
      "Although the size of the merged file is bigger, it STILL contains small row groups, thus you don't have the advantage of big row groups, " +
      "which usually leads to bad query performance!");
  }
  writer.end(mergedMeta.getKeyValueMetaData());
}
 
Example 15
Source File: AbstractBulkLoadTool.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the commandline arguments, throws IllegalStateException if mandatory arguments are
 * missing.
 *
 * @param args supplied command line arguments
 * @return the parsed command line
 */
protected CommandLine parseOptions(String[] args) {

    Options options = getOptions();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = parser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit("Error parsing command line options: " + e.getMessage(), options);
    }

    if (cmdLine.hasOption(HELP_OPT.getOpt())) {
        printHelpAndExit(options, 0);
    }

    if (!cmdLine.hasOption(TABLE_NAME_OPT.getOpt())) {
        throw new IllegalStateException(TABLE_NAME_OPT.getLongOpt() + " is a mandatory " +
                "parameter");
    }

    if (!cmdLine.getArgList().isEmpty()) {
        throw new IllegalStateException("Got unexpected extra parameters: "
                + cmdLine.getArgList());
    }

    if (!cmdLine.hasOption(INPUT_PATH_OPT.getOpt())) {
        throw new IllegalStateException(INPUT_PATH_OPT.getLongOpt() + " is a mandatory " +
                "parameter");
    }

    return cmdLine;
}
 
Example 16
Source File: CWLExecLauncher.java    From cwlexec with Apache License 2.0 5 votes vote down vote up
private void runCommand(CommandLine commandLine) {
    List<String> argList = commandLine.getArgList();
    int exitCode = 255;
    if (argList != null) {
        try {
            CWLExec.cwlexec().start();
            CWLExecService engineService = CWLServiceFactory.getService(CWLExecService.class);
            if (argList.size() == 1) {
                bindShutdownHook();
                exitCode = engineService.submit(owner, argList.get(0), null, this.execConfPath).getExitCode();
            } else if (argList.size() == 2) {
                bindShutdownHook();
                exitCode = engineService.submit(owner, argList.get(0), argList.get(1), this.execConfPath)
                        .getExitCode();
            } else {
                CWLExecUtil.printStderrMsg(ResourceLoader.getMessage(COMMAND_NO_INPUT_MSG));
                this.printHelp();
            }
        } catch (CWLException ce) {
            CWLExecUtil.printStderrMsg(ce.getMessage());
            exitCode = ce.getExceptionCode();
        } catch (Exception e) {
            String errMsg = e.getMessage();
            if (errMsg == null || errMsg.length() == 0) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                errMsg = ResourceLoader.getMessage("cwl.unexpected.exception", sw.toString());
            }
            CWLExecUtil.printStderrMsg(errMsg);
        }
    } else {
        CWLExecUtil.printStderrMsg(ResourceLoader.getMessage(COMMAND_NO_INPUT_MSG));
        this.printHelp();
    }
    System.exit(exitCode);
}
 
Example 17
Source File: PythonDriverOptionsParserFactory.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public PythonDriverOptions createResult(@Nonnull CommandLine commandLine) throws FlinkParseException {
	String entrypointModule = null;
	final List<Path> pythonLibFiles = new ArrayList<>();

	if (commandLine.hasOption(PY_OPTION.getOpt()) && commandLine.hasOption(PYMODULE_OPTION.getOpt())) {
		throw new FlinkParseException("Cannot use options -py and -pym simultaneously.");
	} else if (commandLine.hasOption(PY_OPTION.getOpt())) {
		Path file = new Path(commandLine.getOptionValue(PY_OPTION.getOpt()));
		String fileName = file.getName();
		if (fileName.endsWith(".py")) {
			entrypointModule = fileName.substring(0, fileName.length() - 3);
			pythonLibFiles.add(file);
		}
	} else if (commandLine.hasOption(PYMODULE_OPTION.getOpt())) {
		entrypointModule = commandLine.getOptionValue(PYMODULE_OPTION.getOpt());
	} else {
		throw new FlinkParseException(
			"The Python entrypoint has not been specified. It can be specified with options -py or -pym");
	}

	if (commandLine.hasOption(PYFILES_OPTION.getOpt())) {
		pythonLibFiles.addAll(
			Arrays.stream(commandLine.getOptionValue(PYFILES_OPTION.getOpt()).split(","))
				.map(Path::new)
				.collect(Collectors.toCollection(ArrayList::new)));
	} else if (commandLine.hasOption(PYMODULE_OPTION.getOpt())) {
		throw new FlinkParseException("Option -pym must be used in conjunction with `--pyFiles`");
	}

	return new PythonDriverOptions(entrypointModule, pythonLibFiles, commandLine.getArgList());
}
 
Example 18
Source File: RegistryCli.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public int resolve(String[] args) {
  Options resolveOption = new Options();
  CommandLineParser parser = new GnuParser();
  try {
    CommandLine line = parser.parse(resolveOption, args);

    List<String> argsList = line.getArgList();
    if (argsList.size() != 2) {
      return usageError("resolve requires exactly one path argument",
          RESOLVE_USAGE);
    }
    if (!validatePath(argsList.get(1))) {
      return -1;
    }

    try {
      ServiceRecord record = registry.resolve(argsList.get(1));

      for (Endpoint endpoint : record.external) {
        sysout.println(" Endpoint(ProtocolType="
                       + endpoint.protocolType + ", Api="
                       + endpoint.api + ");"
                       + " Addresses(AddressType="
                       + endpoint.addressType + ") are: ");

        for (Map<String, String> address : endpoint.addresses) {
          sysout.println("[ ");
          for (Map.Entry<String, String> entry : address.entrySet()) {
            sysout.print("\t" + entry.getKey()
                           + ":" + entry.getValue());
          }

          sysout.println("\n]");
        }
        sysout.println();
      }
      return 0;
    } catch (Exception e) {
      syserr.println(analyzeException("resolve", e, argsList));
    }
    return -1;
  } catch (ParseException exp) {
    return usageError("Invalid syntax " + exp, RESOLVE_USAGE);
  }

}
 
Example 19
Source File: AppValidator.java    From tomee with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws SystemExitException {
    final CommandLineParser parser = new PosixParser();

    // create the Options
    final Options options = new Options();
    options.addOption(AppValidator.option("v", "version", "cmd.validate.opt.version"));
    options.addOption(AppValidator.option("h", "help", "cmd.validate.opt.help"));

    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (final ParseException exp) {
        AppValidator.help(options);
        throw new SystemExitException(-1);
    }

    if (line.hasOption("help")) {
        AppValidator.help(options);
        return;
    } else if (line.hasOption("version")) {
        OpenEjbVersion.get().print(System.out);
        return;
    }

    if (line.getArgList().size() == 0) {
        System.out.println("Must specify an module id.");
        AppValidator.help(options);
    }

    final DeploymentLoader deploymentLoader = new DeploymentLoader();

    try {
        final AppValidator validator = new AppValidator();
        for (final Object obj : line.getArgList()) {
            final String module = (String) obj;
            final File file = new File(module);
            final AppModule appModule = deploymentLoader.load(file, null);
            validator.validate(appModule);
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Source File: RegistryCli.java    From big-c with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public int resolve(String[] args) {
  Options resolveOption = new Options();
  CommandLineParser parser = new GnuParser();
  try {
    CommandLine line = parser.parse(resolveOption, args);

    List<String> argsList = line.getArgList();
    if (argsList.size() != 2) {
      return usageError("resolve requires exactly one path argument",
          RESOLVE_USAGE);
    }
    if (!validatePath(argsList.get(1))) {
      return -1;
    }

    try {
      ServiceRecord record = registry.resolve(argsList.get(1));

      for (Endpoint endpoint : record.external) {
        sysout.println(" Endpoint(ProtocolType="
                       + endpoint.protocolType + ", Api="
                       + endpoint.api + ");"
                       + " Addresses(AddressType="
                       + endpoint.addressType + ") are: ");

        for (Map<String, String> address : endpoint.addresses) {
          sysout.println("[ ");
          for (Map.Entry<String, String> entry : address.entrySet()) {
            sysout.print("\t" + entry.getKey()
                           + ":" + entry.getValue());
          }

          sysout.println("\n]");
        }
        sysout.println();
      }
      return 0;
    } catch (Exception e) {
      syserr.println(analyzeException("resolve", e, argsList));
    }
    return -1;
  } catch (ParseException exp) {
    return usageError("Invalid syntax " + exp, RESOLVE_USAGE);
  }

}