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

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

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:edu.msu.cme.rdp.seqmatch.cli.SeqMatchMain.java

public static void main(String[] args) throws Exception {

    if (args.length == 0) {
        System.err.println("USAGE: SeqMatchMain [train|seqmatch] <args>");
        return;//from w ww . jav  a2 s. c o m
    }

    String cmd = args[0];
    args = Arrays.copyOfRange(args, 1, args.length);

    if (cmd.equals("train")) {
        if (args.length != 2) {
            System.err.println("USAGE: train <reference sequences> <trainee_out_file_prefix>"
                    + "\nMultiple trainee output files might be created, each containing maximum "
                    + Trainee.MAX_NUM_SEQ + " sequences");
            return;
        }

        File refSeqs = new File(args[0]);
        File traineeFileOut = new File(args[1]);

        //maybe more than 1 trainee files need to be created, depending on the number of seqs
        CreateMultiMatchFromFile.getMultiTrainee(refSeqs, traineeFileOut);
    } else if (cmd.equals("seqmatch")) {
        File refFile = null;
        File queryFile = null;
        HashMap<String, String> descMap = new HashMap<String, String>();
        PrintStream out = new PrintStream(System.out);
        int knn = 20;
        float minSab = .5f;

        try {
            CommandLine line = new PosixParser().parse(options, args);

            if (line.hasOption("knn")) {
                knn = Integer.parseInt(line.getOptionValue("knn"));
            }

            if (line.hasOption("sab")) {
                minSab = Float.parseFloat(line.getOptionValue("sab"));
            }
            if (line.hasOption("desc")) {
                descMap = readDesc(new File(line.getOptionValue("desc")));
            }
            if (line.hasOption("outFile")) {
                out = new PrintStream(new File(line.getOptionValue("outFile")));
            }

            args = line.getArgs();

            if (args.length != 2) {
                throw new Exception("Unexpected number of command line arguments");
            }

            refFile = new File(args[0]);
            queryFile = new File(args[1]);

        } catch (Exception e) {
            new HelpFormatter().printHelp("seqmatch <refseqs | trainee_file_or_dir> <query_file>\n"
                    + " trainee_file_or_dir is a single trainee file or a directory containing multiple trainee files",
                    options);
            System.err.println("Error: " + e.getMessage());
            return;
        }

        SeqMatch seqmatch = null;
        if (refFile.isDirectory()) { // a directory of trainee files
            List<SeqMatch> engineList = new ArrayList<SeqMatch>();
            for (File f : refFile.listFiles()) {
                if (!f.isHidden()) {
                    TwowaySeqMatch match = new TwowaySeqMatch(new SeqMatchEngine(new StorageTrainee(f)));
                    engineList.add(match);
                }
            }
            seqmatch = new MultiTraineeSeqMatch(engineList);
        } else { // a single fasta file or trainee file
            if (SeqUtils.guessFileFormat(refFile) == SequenceFormat.UNKNOWN) {
                seqmatch = CLISeqMatchFactory.trainTwowaySeqMatch(new StorageTrainee(refFile));
            } else {
                seqmatch = CreateMultiMatchFromFile.getMultiMatch(refFile);
            }
        }

        out.println("query name\tmatch seq\torientation\tS_ab score\tunique oligomers\tdescription");

        SeqReader reader = new SequenceReader(queryFile);
        Sequence seq;

        while ((seq = reader.readNextSequence()) != null) {
            SeqMatchResultSet resultSet = seqmatch.match(seq, knn);
            for (SeqMatchResult result : resultSet) {
                char r = '+';
                if (result.isReverse()) {
                    r = '-';
                }

                if (result.getScore() > minSab) {
                    out.println(seq.getSeqName() + "\t" + result.getSeqName() + "\t" + r + "\t"
                            + result.getScore() + "\t" + resultSet.getQueryWordCount() + "\t"
                            + descMap.get(result.getSeqName()));
                }
            }
        }

        out.close();
    } else {
        throw new IllegalArgumentException("USAGE: SeqMatchMain [train|seqmatch] <args>");
    }
}

From source file:com.hortonworks.registries.storage.tool.sql.TablesInitializer.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH)
            .desc("Root directory of script path").build());

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CREATE.toString())
            .desc("Run sql migrations from scatch").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.DROP.toString())
            .desc("Drop all the tables in the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.CHECK_CONNECTION.toString())
            .desc("Check the connection for configured data source").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.MIGRATE.toString())
            .desc("Execute schema migration from last check point").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.INFO.toString())
            .desc("Show the status of the schema migration compared to the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.VALIDATE.toString())
            .desc("Validate the target database changes with the migration scripts").build());

    options.addOption(Option.builder().hasArg(false).longOpt(SchemaMigrationOption.REPAIR.toString()).desc(
            "Repairs the DATABASE_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script")
            .build());//from  w  ww .j a  v  a  2s.  c om

    options.addOption(Option.builder().hasArg(false).longOpt(DISABLE_VALIDATE_ON_MIGRATE)
            .desc("Disable flyway validation checks while running migrate").build());

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) {
        usage(options);
        System.exit(1);
    }

    boolean isSchemaMigrationOptionSpecified = false;
    SchemaMigrationOption schemaMigrationOptionSpecified = null;
    for (SchemaMigrationOption schemaMigrationOption : SchemaMigrationOption.values()) {
        if (commandLine.hasOption(schemaMigrationOption.toString())) {
            if (isSchemaMigrationOptionSpecified) {
                System.out.println(
                        "Only one operation can be execute at once, please select one of 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection'.");
                System.exit(1);
            }
            isSchemaMigrationOptionSpecified = true;
            schemaMigrationOptionSpecified = schemaMigrationOption;
        }
    }

    if (!isSchemaMigrationOptionSpecified) {
        System.out.println(
                "One of the option 'create', ',migrate', 'validate', 'info', 'drop', 'repair', 'check-connection' must be specified to execute.");
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    StorageProviderConfiguration storageProperties;
    Map<String, Object> conf;
    try {
        conf = Utils.readConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        storageProperties = confReader.readStorageConfig(conf);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        Proxy proxy = Proxy.NO_PROXY;
        String httpProxyUrl = (String) conf.get(HTTP_PROXY_URL);
        String httpProxyUsername = (String) conf.get(HTTP_PROXY_USERNAME);
        String httpProxyPassword = (String) conf.get(HTTP_PROXY_PASSWORD);
        if ((httpProxyUrl != null) && !httpProxyUrl.isEmpty()) {
            URL url = new URL(httpProxyUrl);
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
            if ((httpProxyUsername != null) && !httpProxyUsername.isEmpty()) {
                Authenticator.setDefault(getBasicAuthenticator(url.getHost(), url.getPort(), httpProxyUsername,
                        httpProxyPassword));
            }
        }
        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl, proxy);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    boolean disableValidateOnMigrate = commandLine.hasOption(DISABLE_VALIDATE_ON_MIGRATE);
    if (disableValidateOnMigrate) {
        System.out.println("Disabling validation on schema migrate");
    }
    SchemaMigrationHelper schemaMigrationHelper = new SchemaMigrationHelper(
            SchemaFlywayFactory.get(storageProperties, scriptRootPath, !disableValidateOnMigrate));
    try {
        schemaMigrationHelper.execute(schemaMigrationOptionSpecified);
        System.out
                .println(String.format("\"%s\" option successful", schemaMigrationOptionSpecified.toString()));
    } catch (Exception e) {
        System.err.println(
                String.format("\"%s\" option failed : %s", schemaMigrationOptionSpecified.toString(), e));
        System.exit(1);
    }

}

From source file:edu.msu.cme.rdp.classifier.ClassifierCmd.java

/**
 * This is the main method to do classification.
 * <p>Usage: java ClassifierCmd queryFile outputFile [property file].
 * <br>//from  www. j av  a 2  s  .com
 * queryFile can be one of the following formats: Fasta, Genbank and EMBL. 
 * <br>
 * outputFile will be used to save the classification output.
 * <br>
 * property file contains the mapping of the training files.
 * <br>
 * Note: the training files and the property file should be in the same directory.
 * The default property file is set to data/classifier/16srrna/rRNAClassifier.properties.
 */
public static void main(String[] args) throws Exception {

    String queryFile = null;
    String outputFile = null;
    String propFile = null;
    String gene = null;
    ClassificationResultFormatter.FORMAT format = CmdOptions.DEFAULT_FORMAT;
    int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            outputFile = line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT);
        } else {
            throw new Exception("outputFile must be specified");
        }

        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else {
                throw new IllegalArgumentException(
                        "Not valid output format, only allrank, fixrank, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (propFile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)) {
                throw new IllegalArgumentException(gene + " is NOT valid, only allows "
                        + ClassifierFactory.RRNA_16S_GENE + " and " + ClassifierFactory.FUNGALLSU_GENE);
            }
        }
        if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) {
            min_bootstrap_words = Integer
                    .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT));
            if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) {
                throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT
                        + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS);
            }
        }

        args = line.getArgs();
        if (args.length != 1) {
            throw new Exception("Expect one query file");
        }
        queryFile = args[0];

    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120,
                "ClassifierCmd [options] <samplefile>\nNote this is the legacy command for one sample classification ",
                "", options, "");

        return;
    }

    if (propFile == null && gene == null) {
        gene = CmdOptions.DEFAULT_GENE;
    }
    ClassifierCmd classifierCmd = new ClassifierCmd();

    printLicense();
    classifierCmd.doClassify(queryFile, outputFile, propFile, format, gene, min_bootstrap_words);

}

From source file:com.adobe.aem.demomachine.Json2Csv.java

public static void main(String[] args) throws IOException {

    String inputFile1 = null;/*from   ww w  .  j  av  a 2 s  . c  o m*/
    String inputFile2 = null;
    String outputFile = null;

    HashMap<String, String> hmReportSuites = new HashMap<String, String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("c", true, "Filename 1");
    options.addOption("r", true, "Filename 2");
    options.addOption("o", true, "Filename 3");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("c")) {
            inputFile1 = cmd.getOptionValue("c");
        }

        if (cmd.hasOption("r")) {
            inputFile2 = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("o")) {
            outputFile = cmd.getOptionValue("o");
        }

        if (inputFile1 == null || inputFile1 == null || outputFile == null) {
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    // List of customers and report suites for these customers
    String sInputFile1 = readFile(inputFile1, Charset.defaultCharset());
    sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

    // Processing the list of report suites for each customer
    try {

        JSONArray jCustomers = new JSONArray(sInputFile1.trim());
        for (int i = 0, size = jCustomers.length(); i < size; i++) {
            JSONObject jCustomer = jCustomers.getJSONObject(i);
            Iterator<?> keys = jCustomer.keys();
            String companyName = null;
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("company")) {
                    companyName = jCustomer.getString(key);
                }
            }
            keys = jCustomer.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();

                if (key.equals("report_suites")) {
                    JSONArray jReportSuites = jCustomer.getJSONArray(key);
                    for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) {
                        hmReportSuites.put(jReportSuites.getString(j), companyName);
                        System.out.println(jReportSuites.get(j) + " for company " + companyName);
                    }

                }
            }
        }

        // Creating the out put file
        PrintWriter writer = new PrintWriter(outputFile, "UTF-8");
        writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents"
                + "\",\"" + "Last Updated" + "\"");

        // Processing the list of SOLR collections
        String sInputFile2 = readFile(inputFile2, Charset.defaultCharset());
        sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

        JSONObject jResults = new JSONObject(sInputFile2.trim());
        JSONArray jCollections = jResults.getJSONArray("result");
        for (int i = 0, size = jCollections.length(); i < size; i++) {
            JSONObject jCollection = jCollections.getJSONObject(i);
            String id = null;
            String number = null;
            String lastupdate = null;

            Iterator<?> keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("_id")) {
                    id = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("noOfDocs")) {
                    number = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("latestUpdateDate")) {
                    lastupdate = jCollection.getString(key);
                }
            }

            Date d = new Date(Long.parseLong(lastupdate));
            System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + ","
                    + new SimpleDateFormat("MM-dd-yyyy").format(d));
            writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\""
                    + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\"");

        }

        writer.close();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.jbrisbin.vcloud.cache.Bootstrap.java

public static void main(String[] args) {

    CommandLineParser parser = new BasicParser();
    CommandLine cmdLine = null;
    try {/*from   w  ww.j a  v  a 2  s.  c  o m*/
        cmdLine = parser.parse(opts, args);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    String configFile = "/etc/cloud/async-cache.xml";
    if (null != cmdLine) {
        if (cmdLine.hasOption('c')) {
            configFile = cmdLine.getOptionValue('c');
        }
    }

    ApplicationContext context = new FileSystemXmlApplicationContext(configFile);
    RabbitMQAsyncCacheProvider cacheProvider = context.getBean(RabbitMQAsyncCacheProvider.class);
    while (cacheProvider.isActive()) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }

}

From source file:ca.uhn.hunit.run.TestRunner.java

/**
 * @param args// w  ww .ja  va  2  s  .co m
 * @throws URISyntaxException
 * @throws JAXBException
 * @throws ConfigurationException
 * @throws InterfaceWontStartException
 * @throws FileNotFoundException
 * @throws ParseException
 */
public static void main(String[] theArgs) throws URISyntaxException, JAXBException, InterfaceWontStartException,
        ConfigurationException, FileNotFoundException, ParseException {
    Options options = new Options();

    OptionGroup fileOptionGroup = new OptionGroup();
    fileOptionGroup.setRequired(false);

    Option option = new Option("f", "file", true, "The path to the file to load the test battery from");
    option.setValueSeparator('=');
    fileOptionGroup.addOption(option);
    option = new Option("c", "classpath", true, "The classpath path to the file to load the test battery from");
    option.setValueSeparator('=');
    fileOptionGroup.addOption(option);
    options.addOptionGroup(fileOptionGroup);

    OptionGroup uiOptionGroup = new OptionGroup();
    option = new Option("g", "gui", false, "Start hUnit in GUI mode (default)");
    uiOptionGroup.addOption(option);
    option = new Option("x", "text", false, "Start hUnit in Text mode");
    uiOptionGroup.addOption(option);
    options.addOptionGroup(uiOptionGroup);

    option = new Option("t", "tests", true, "A comma separated list of tests to execute (default is all)");
    option.setValueSeparator('=');
    option.setRequired(false);
    options.addOption(option);

    Resource defFile = null;
    CommandLine parser;
    boolean textMode = false;

    try {
        parser = new PosixParser().parse(options, theArgs);

        if (parser.hasOption("f")) {
            defFile = new FileSystemResource(parser.getOptionValue("f"));
        } else if (parser.hasOption("c")) {
            defFile = new ClassPathResource(parser.getOptionValue("c"));
        }

        if (parser.hasOption("x")) {
            textMode = true;
        }
    } catch (Exception e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar hunit-[version]-jar-with-dependencies.jar [-c FILE|-f FILE] [options]",
                options);

        return;
    }

    String[] testsToExecute = null;

    if (parser.hasOption("t")) {
        testsToExecute = parser.getOptionValue("t").split(",");
    }

    if (textMode) {
        executeInTextMode(defFile, testsToExecute);
    } else {
        executeInGuiMode(defFile, testsToExecute);
    }
}

From source file:de.moritzrupp.stockreader.Main.java

/**
 * main//  w  ww. j  ava2s . com
 * @param args
 */
public static void main(String[] args) {

    initOptions();
    clParser = new GnuParser();

    if (args.length == 0) { // if no arguments

        formatter.printHelp("stockreader", header, options, footer);
        System.exit(1);
    }

    try {

        CommandLine line = clParser.parse(options, args);

        if (line.hasOption("h")) {

            printHelp();
        }

        if (line.hasOption("v")) {

            System.out.println("stockreader version " + VERSION
                    + ". Copyright 2013 by Moritz Rupp. All rights reserved.\n"
                    + "This application is licensed under The MIT License (MIT). See https://github.com/moritzrupp/stockreader/blob/master/LICENSE.md");
            System.exit(0);
        }

        if (line.hasOption("p")) {

            priceArg = true;
        }

        if (line.hasOption("f")) {

            fileArg = true;
            theFile = new File(line.getOptionValue("f"));
        }

        host = line.getOptionValue("host");
        username = line.getOptionValue("user");
        passwd = line.getOptionValue("password");
        from = line.getOptionValue("from");
        to = line.getOptionValue("to");
    } catch (ParseException exp) {
        // TODO Auto-generated catch block
        exp.printStackTrace();
    }

    try {

        reader = new StockReader(';', new StockQuote(), "UTF-8",
                (fileArg) ? theFile.toString()
                        : new File(".").getCanonicalPath()
                                + ((System.getProperty("os.name").toLowerCase().startsWith("win")) ? "\\" : "/")
                                + "stocks.csv");

        for (int i = 0; i < args.length; i++) {

            switch (args[i].charAt(0)) {

            case '-':
                if (args[i].length() < 2) {

                    System.err.println("Not a valid argument: " + args[i]);
                    printHelp();
                    System.exit(1);
                }

                if (args[i].charAt(1) == 'f' || (args[i].charAt(1) == '-' && args[i].charAt(2) == 'f')) {

                    // get the path and set it to "nosymbol"
                    args[i + 1] = "nosymbol";
                }

                break;
            default:
                if (!args[i].equals("nosymbol")) {
                    reader.addSymbol(args[i]);
                }
                break;
            }
        }

        reader.getQuotes();
        reader.writeToCSV(priceArg);
        reader.sendmail(from, to, "Aktienkurse", host, username, passwd);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.artofsolving.jodconverter.cli.ConvertDocument.java

public static void main(String[] arguments) throws Exception {
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);

    int port = SocketOpenOfficeConnection.DEFAULT_PORT;
    if (commandLine.hasOption(OPTION_PORT.getOpt())) {
        port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
    }/*from   www. j  av  a2  s  .c  o m*/

    String outputFormat = null;
    if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
        outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
    }

    boolean verbose = false;
    if (commandLine.hasOption(OPTION_VERBOSE.getOpt())) {
        verbose = true;
    }

    DocumentFormatRegistry registry;
    if (commandLine.hasOption(OPTION_XML_REGISTRY.getOpt())) {
        File registryFile = new File(commandLine.getOptionValue(OPTION_XML_REGISTRY.getOpt()));
        if (!registryFile.isFile()) {
            System.err.println("ERROR: specified XML registry file not found: " + registryFile);
            System.exit(EXIT_CODE_XML_REGISTRY_NOT_FOUND);
        }
        registry = new XmlDocumentFormatRegistry(new FileInputStream(registryFile));
        if (verbose) {
            System.out.println("-- loaded document format registry from " + registryFile);
        }
    } else {
        registry = new DefaultDocumentFormatRegistry();
    }

    String[] fileNames = commandLine.getArgs();
    if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) {
        String syntax = "convert [options] input-file output-file; or\n"
                + "[options] -f output-format input-file [input-file...]";
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(syntax, OPTIONS);
        System.exit(EXIT_CODE_TOO_FEW_ARGS);
    }

    OpenOfficeConnection connection = new SocketOpenOfficeConnection(port);
    try {
        if (verbose) {
            System.out.println("-- connecting to OpenOffice.org on port " + port);
        }
        connection.connect();
    } catch (ConnectException officeNotRunning) {
        System.err.println(
                "ERROR: connection failed. Please make sure OpenOffice.org is running and listening on port "
                        + port + ".");
        System.exit(EXIT_CODE_CONNECTION_FAILED);
    }
    try {
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection, registry);
        if (outputFormat == null) {
            File inputFile = new File(fileNames[0]);
            File outputFile = new File(fileNames[1]);
            convertOne(converter, inputFile, outputFile, verbose);
        } else {
            for (int i = 0; i < fileNames.length; i++) {
                File inputFile = new File(fileNames[i]);
                File outputFile = new File(FilenameUtils.getFullPath(fileNames[i])
                        + FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat);
                convertOne(converter, inputFile, outputFile, verbose);
            }
        }
    } finally {
        if (verbose) {
            System.out.println("-- disconnecting");
        }
        connection.disconnect();
    }
}

From source file:de.bruse.c2x.cli.Main.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    Option input = new Option("i", INPUT, HAS_ARGS, "CityGML file to be converted.");
    input.setArgs(ONE);//from  ww w  . j  a  va  2 s  . c  om
    input.setArgName(INPUT);
    input.setRequired(Boolean.TRUE);
    options.addOption(input);

    Option levelOfDetail = new Option("l", LEVEL_OF_DETAIL, HAS_ARGS,
            "Level of detail to be converted. Possible values are LOD1 and LOD2.");
    levelOfDetail.setArgs(ONE);
    levelOfDetail.setArgName(LEVEL_OF_DETAIL);
    levelOfDetail.setRequired(Boolean.TRUE);
    options.addOption(levelOfDetail);

    Option geometryType = new Option("t", GEOMETRY_TYPE, HAS_ARGS,
            "Geometry type to be converted. Possible values are SOLID and MULTI_SURFACE.");
    geometryType.setArgs(ONE);
    geometryType.setArgName(GEOMETRY_TYPE);
    geometryType.setRequired(Boolean.TRUE);
    options.addOption(geometryType);

    Option output = new Option("o", OUTPUT, HAS_ARGS, "File path of the output file.");
    output.setArgs(ONE);
    output.setArgName(OUTPUT);
    output.setRequired(Boolean.FALSE);
    options.addOption(output);

    Option targetFormat = new Option("f", FORMAT, HAS_ARGS,
            "Format of the output file. Possible values are X3D and COLLADA.");
    targetFormat.setArgs(ONE);
    targetFormat.setArgName(FORMAT);
    targetFormat.setRequired(Boolean.TRUE);
    options.addOption(targetFormat);

    Option split = new Option("s", SPLIT, NO_ARGS, "Generate one scene node for each building (X3D only).");
    split.setArgName(SPLIT);
    split.setRequired(Boolean.FALSE);
    options.addOption(split);

    Option validate = new Option("v", VALIDATE, NO_ARGS, "Validate the CityGML file.");
    validate.setArgName(VALIDATE);
    validate.setRequired(Boolean.FALSE);
    options.addOption(validate);

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(INPUT) && line.hasOption(LEVEL_OF_DETAIL) && line.hasOption(GEOMETRY_TYPE)
                && line.hasOption(FORMAT)) {
            String inputValue = line.getOptionValue(INPUT);
            String levelOfDetailValue = line.getOptionValue(LEVEL_OF_DETAIL);
            String geometryTypeValue = line.getOptionValue(GEOMETRY_TYPE);
            String targetFormatValue = line.getOptionValue(FORMAT);
            String outputValue = line.getOptionValue(OUTPUT);
            LevelOfDetail lod = LevelOfDetail.valueOf(levelOfDetailValue);
            GeometryType type = GeometryType.valueOf(geometryTypeValue);
            if (Objects.isNull(lod) || Objects.isNull(type)
                    || (!targetFormatValue.equals(X3D) && !targetFormatValue.equals(COLLADA))) {
                printHelp(options);
            } else {
                if (line.hasOption(VALIDATE)) {
                    triggerValidation(inputValue);
                }
                if (targetFormatValue.equals(X3D)) {
                    boolean splitValue = false;
                    if (line.hasOption(SPLIT)) {
                        splitValue = true;
                    }
                    if (Objects.isNull(outputValue) || outputValue.isEmpty()) {
                        outputValue = inputValue + X3D_FILE_EXT;
                    }
                    triggerX3DConversion(inputValue, lod, type, outputValue, splitValue);
                } else if (targetFormatValue.equals(COLLADA)) {
                    if (Objects.isNull(outputValue) || outputValue.isEmpty()) {
                        outputValue = inputValue + COLLADA_FILE_EXT;
                    }
                    triggerColladaConversion(inputValue, lod, type, outputValue);
                }
                System.out.println("Conversion succeeded.");
            }
        } else {
            printHelp(options);
        }
    } catch (ParseException | IllegalArgumentException e) {
        printHelp(options);
    } catch (ValidationException e) {
        System.out.println("Input file is invalid. Operation canceled.\n" + e.getMessage());
    } catch (ConversionException e) {
        String message = "Failed to convert CityGML.";
        if (Objects.nonNull(e.getMessage())) {
            message += " " + e.getMessage();
        }
        System.out.println(message);
    } catch (IOException e) {
        System.out.println("Failed to read from file '" + input + "'.");
    }
}

From source file:com.leshazlewood.scms.cli.Main.java

public static void main(String[] args) throws Exception {

    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption(CONFIG).addOption(DEBUG).addOption(HELP).addOption(VERSION);

    boolean debug = false;
    File sourceDir = toFile(System.getProperty("user.dir"));
    File configFile = null;/* w  w w. j  a v  a  2s  . co m*/
    File destDir = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(VERSION.getOpt())) {
            printVersionAndExit();
        }
        if (line.hasOption(HELP.getOpt())) {
            printHelpAndExit(options, null, debug, 0);
        }
        if (line.hasOption(DEBUG.getOpt())) {
            debug = true;
        }
        if (line.hasOption(CONFIG.getOpt())) {
            String configFilePath = line.getOptionValue(CONFIG.getOpt());
            configFile = toFile(configFilePath);
        }

        String[] remainingArgs = line.getArgs();
        if (remainingArgs == null) {
            printHelpAndExit(options, null, debug, -1);
        }

        assert remainingArgs != null;

        if (remainingArgs.length == 1) {
            String workingDirPath = System.getProperty("user.dir");
            sourceDir = toFile(workingDirPath);
            destDir = toFile(remainingArgs[0]);
        } else if (remainingArgs.length == 2) {
            sourceDir = toFile(remainingArgs[0]);
            destDir = toFile((remainingArgs[1]));
        } else {
            printHelpAndExit(options, null, debug, -1);
        }

        assert sourceDir != null;
        assert destDir != null;

        if (configFile == null) {
            configFile = new File(sourceDir, DEFAULT_CONFIG_FILE_NAME);
        }

        if (configFile.exists()) {
            if (configFile.isDirectory()) {
                throw new IllegalArgumentException(
                        "Expected configuration file " + configFile + " is a directory, not a file.");
            }
        } else {
            String msg = "Configuration file not found.  Create a default " + DEFAULT_CONFIG_FILE_NAME
                    + " file in your source directory or specify the " + CONFIG
                    + " option to provide the file location.";
            throw new IllegalStateException(msg);
        }

        SiteExporter siteExporter = new SiteExporter();
        siteExporter.setSourceDir(sourceDir);
        siteExporter.setDestDir(destDir);
        siteExporter.setConfigFile(configFile);
        siteExporter.init();
        siteExporter.execute();

    } catch (IllegalArgumentException iae) {
        exit(iae, debug);
    } catch (IllegalStateException ise) {
        exit(ise, debug);
    } catch (Exception e) {
        printHelpAndExit(options, e, debug, -1);
    }
}