Example usage for org.apache.commons.cli ParseException ParseException

List of usage examples for org.apache.commons.cli ParseException ParseException

Introduction

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

Prototype

public ParseException(String message) 

Source Link

Document

Construct a new ParseException with the specified detail message.

Usage

From source file:com.garethahealy.quotalimitsgenerator.cli.parsers.DefaultCLIParser.java

private Map<String, Pair<Integer, Integer>> parseLines(String instanceTypeCsv)
        throws IOException, URISyntaxException, ParseException {
    InputStreamReader inputStreamReader;
    if (instanceTypeCsv.equalsIgnoreCase("classpath")) {
        inputStreamReader = new InputStreamReader(
                getClass().getClassLoader().getResourceAsStream("instancetypes.csv"), Charset.forName("UTF-8"));
    } else {/*from  w w w.  j  a va2 s  . c o  m*/
        URI uri = new URI(instanceTypeCsv);
        inputStreamReader = new InputStreamReader(new FileInputStream(new File(uri)), Charset.forName("UTF-8"));
    }

    CSVParser parser = null;
    List<CSVRecord> lines = null;
    try {
        parser = CSVFormat.DEFAULT.parse(new BufferedReader(inputStreamReader));
        lines = parser.getRecords();
    } finally {
        inputStreamReader.close();

        if (parser != null) {
            parser.close();
        }
    }

    if (lines == null || lines.size() <= 0) {
        throw new ParseException("instance-type-csv data is empty");
    }

    Map<String, Pair<Integer, Integer>> linesMap = new HashMap<String, Pair<Integer, Integer>>();
    for (CSVRecord current : lines) {
        linesMap.put(current.get(1), new ImmutablePair<Integer, Integer>(Integer.parseInt(current.get(2)),
                Integer.parseInt(current.get(3))));
    }

    return linesMap;
}

From source file:at.tfr.securefs.client.SecurefsFileServiceClient.java

public void parse(String[] args) throws ParseException {
    CommandLineParser clp = new DefaultParser();
    CommandLine cmd = clp.parse(options, args);

    // validate://from w  w  w . ja  v a 2 s.  co m
    if (!cmd.hasOption("f")) {
        throw new ParseException("file name is mandatory");
    }

    fileServiceUrl = cmd.getOptionValue("u", fileServiceUrl);
    if (cmd.hasOption("f")) {
        Arrays.stream(cmd.getOptionValue("f").split(",")).forEach(f -> files.add(Paths.get(f)));
    }
    asyncTest = Boolean.parseBoolean(cmd.getOptionValue("a", "false"));
    threads = Integer.parseInt(cmd.getOptionValue("t", "1"));
    if (cmd.hasOption("r") || cmd.hasOption("w") || cmd.hasOption("d")) {
        read = write = delete = false;
        read = cmd.hasOption("r");
        write = cmd.hasOption("w");
        delete = cmd.hasOption("d");
    }

}

From source file:it.crs4.seal.common.SealToolParser.java

protected void loadConfig(Configuration conf, File fname) throws ParseException, IOException {
    ConfigFileParser parser = new ConfigFileParser();

    try {// w  ww .  j  a  v a 2 s.com
        parser.load(new FileReader(fname));

        Iterator<ConfigFileParser.KvPair> it = parser.getSectionIterator(configSection);
        ConfigFileParser.KvPair pair;
        while (it.hasNext()) {
            pair = it.next();
            conf.set(pair.getKey(), pair.getValue());
        }
    } catch (FormatException e) {
        throw new ParseException("Error reading config file " + fname + ". " + e);
    }
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.tools.Solve.java

/**
 * Parses a single variable specification from the command line.  This
 * method is case sensitive./*  ww w  . j  a  v  a 2s  .co  m*/
 * 
 * @param token the variable specification from the command line
 * @return the generated variable object
 * @throws ParseException if an error occurred while parsing the variable
 *         specification
 */
private Variable parseVariableSpecification(String token) throws ParseException {
    if (!token.endsWith(")")) {
        throw new ParseException("invalid variable specification '" + token + "', not properly formatted");
    }

    if (token.startsWith("R(")) {
        // real-valued decision variable
        String content = token.substring(2, token.length() - 1);
        int index = content.indexOf(';');

        if (index >= 0) {
            double lowerBound = Double.parseDouble(content.substring(0, index));
            double upperBound = Double.parseDouble(content.substring(index + 1, content.length()));
            return EncodingUtils.newReal(lowerBound, upperBound);
        } else {
            throw new ParseException("invalid real specification '" + token + "', expected R(<lb>,<ub>)");
        }
    } else if (token.startsWith("B(")) {
        String content = token.substring(2, token.length() - 1);

        try {
            int length = Integer.parseInt(content.trim());
            return EncodingUtils.newBinary(length);
        } catch (NumberFormatException e) {
            throw new ParseException("invalid binary specification '" + token + "', expected B(<length>)");
        }
    } else if (token.startsWith("P(")) {
        String content = token.substring(2, token.length() - 1);

        try {
            int length = Integer.parseInt(content.trim());
            return EncodingUtils.newPermutation(length);
        } catch (NumberFormatException e) {
            throw new ParseException("invalid permutation specification '" + token + "', expected P(<length>)");
        }
    } else {
        throw new ParseException("invalid variable specification '" + token + "', unknown type");
    }
}

From source file:com.archivas.clienttools.arcmover.cli.AbstractArcCli.java

public static String getProfileNameAndValidateItDoesNotExist(CommandLine cmdLine, String option)
        throws ParseException {
    if (!cmdLine.hasOption(option)) {
        throw new ParseException("Missing Option: " + option);
    }/*from   w  w  w  .j  a v a2s  . c o m*/

    String value = cmdLine.getOptionValue(option);
    String retval = null;

    if (value != null) {
        AbstractProfileBase profile = ProfileManager.getProfileByName(value);
        if (profile == null) {
            retval = value;
        } else {
            throw new ParseException("Profile already exists with name:  " + value);
        }

    }
    if (retval == null) {
        throw new ParseException("Invalid " + option + " : " + value);
    }
    return retval;
}

From source file:com.indeed.imhotep.index.builder.util.SmartArgs.java

/**
 * Parses an integer value, also gives a slightly more helpful error message
 * @param optionName The name of the option to parse
 * @return The parsed integer value/*from  w  w  w  .  j av a2  s . c o  m*/
 * @throws ParseException
 */
public int getIntValue(@Nonnull final String optionName) throws ParseException {
    final String value = results.getOptionValue(optionName);
    try {
        return Integer.parseInt(value);
    } catch (final IllegalArgumentException e) {
        throw new ParseException("Could not parse \"" + value + "\" into a valid Integer for " + optionName);
    }
}

From source file:net.ripe.rpki.validator.cli.CommandLineOptions.java

private void requireInputFileOption(CommandLine commandLine) throws ParseException {
    if (!commandLine.hasOption(FILE)) {
        throw new ParseException("Required option 'file' missing");
    }//from   w  ww.  j ava 2s.  c o  m
}

From source file:de.clusteval.data.dataset.generator.DataSetGenerator.java

/**
 * This method has to be invoked with command line arguments for this
 * generator. Valid arguments are defined by the options returned by
 * {@link #getOptions()}./* w w w .  j  a  v a 2  s  .  c o m*/
 * 
 * @param cliArguments
 * @return The generated {@link DataSet}.
 * @throws ParseException
 *             This exception is thrown, if the passed arguments are not
 *             valid.
 * @throws DataSetGenerationException
 * @throws GoldStandardGenerationException
 */
public DataSet generate(final String[] cliArguments)
        throws ParseException, DataSetGenerationException, GoldStandardGenerationException {
    CommandLineParser parser = new PosixParser();

    Options options = this.getAllOptions();

    CommandLine cmd = parser.parse(options, cliArguments);

    this.folderName = cmd.getOptionValue("folderName");
    this.fileName = cmd.getOptionValue("fileName");
    this.alias = cmd.getOptionValue("alias");

    this.handleOptions(cmd);

    // Ensure, that the dataset target file does not exist yet
    File targetFile = new File(
            FileUtils.buildPath(this.repository.getBasePath(DataSet.class), this.folderName, this.fileName));

    if (targetFile.exists())
        throw new ParseException("A dataset with the given name does already exist!");
    targetFile.getParentFile().mkdirs();

    DataSet dataSet = generateDataSet();

    if (this.generatesGoldStandard()) {
        // Ensure, that the goldstandard target file does not exist yet
        targetFile = new File(FileUtils.buildPath(this.repository.getBasePath(GoldStandard.class),
                this.folderName, this.fileName));

        if (targetFile.exists())
            throw new ParseException("A goldstandard with the given name does already exist!");
        targetFile.getParentFile().mkdirs();

        generateGoldStandard();
    }
    return dataSet;
}

From source file:com.aliyun.odps.ship.upload.BlockUploader.java

private boolean doUpload() throws TunnelException, IOException, ParseException {
    // clear bad data for new block upload
    sessionHistory.clearBadData(Long.valueOf(blockId));

    //init reader/writer
    BlockRecordReader reader = createReader();

    RecordConverter recordConverter = createRecordConverter(reader.getDetectedCharset());

    RecordWriter writer = uploadSession.getWriter(Long.valueOf(blockId));

    while (true) {
        try {//from  w w  w .  j ava2 s.  c om
            byte[][] textRecord = reader.readTextRecord();
            if (textRecord == null)
                break;

            Record r = recordConverter.parse(textRecord);
            writer.write(r);
            printProgress(reader.getReadBytes(), false);
        } catch (ParseException e) {
            String currentLine = reader.getCurrentLine();
            long offset = reader.getReadBytes() + blockInfo.getStartPos() - currentLine.length();
            if (currentLine.length() > 100) {
                currentLine = currentLine.substring(0, 100) + " ...";
            }
            String errMsg = e.getMessage() + "content: " + currentLine + "\noffset: " + offset + "\n";
            if (isDiscardBadRecord) {
                print(errMsg);
                checkDiscardBadData();
                // save bad data
                sessionHistory.saveBadData(
                        reader.getCurrentLine() + DshipContext.INSTANCE.get(Constants.RECORD_DELIMITER),
                        Long.valueOf(blockId));
            } else {
                DshipContext.INSTANCE.put(Constants.STATUS, SessionStatus.failed.toString());
                sessionHistory.saveContext();
                throw new ParseException(errMsg);
            }
        }
    }
    writer.close();
    reader.close();

    if (!isScan) {
        printProgress(reader.getReadBytes(), true);
        sessionHistory.saveFinishBlock(blockInfo);
    }
    return false;
}

From source file:goraci.Verify.java

@Override
public int run(String[] args) throws Exception {

    Options options = new Options();
    options.addOption("c", "concurrent", false, "run concurrently with generation");

    GnuParser parser = new GnuParser();
    CommandLine cmd = null;//w ww.  j a va 2s.c  o m
    try {
        cmd = parser.parse(options, args);
        if (cmd.getArgs().length != 4) {
            throw new ParseException("Did not see expected # of arguments, saw " + cmd.getArgs().length);
        }
    } catch (ParseException e) {
        System.err.println("Failed to parse command line " + e.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(getClass().getSimpleName() + " <output dir> <num reducers>", options);
        System.exit(-1);
    }

    String outputDir = cmd.getArgs()[0];
    int numReducers = Integer.parseInt(cmd.getArgs()[1]);
    String accessKey = cmd.getArgs()[2];
    String secretKey = cmd.getArgs()[3];

    return run(outputDir, numReducers, cmd.hasOption("c"), accessKey, secretKey);
}