Example usage for org.apache.commons.cli Options addOption

List of usage examples for org.apache.commons.cli Options addOption

Introduction

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

Prototype

public Options addOption(String opt, boolean hasArg, String description) 

Source Link

Document

Add an option that only contains a short-name.

Usage

From source file:net.dinkla.mof2ecore.MOF2Ecore.java

/**
 * The main method./*from   w  ww.  j  ava  2 s  . com*/
 * 
 * @param args      Command line arguments.
 * 
 */
public static void main(String[] args) {

    // create the options
    Options options = new Options();
    options.addOption("input", true, "The MOF/XML file to be processed");
    options.addOption("output", true, "The ecore/XMI file to be created");
    options.addOption("xslt", true, "The XSLT file to use");
    options.addOption("package", true, "The name of the toplevel package");
    options.addOption("container", true, "The suffix for the ecore containers");
    options.addOption(new Option("debug", ""));

    // create the parser
    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        inputFile = line.getOptionValue("input");
        outputFile = line.getOptionValue("output");
        xsltFile = line.getOptionValue("xslt");
        if (null == xsltFile) {
            xsltFile = xsltFileDefault;
        }
        namePackage = line.getOptionValue("package");
        if (null == namePackage) {
            namePackage = namePackageDefault;
        }
        suffixContainer = line.getOptionValue("container");
        if (null == suffixContainer) {
            suffixContainer = suffixContainerDefault;
        }
        debug = line.hasOption("debug");

        if (null == inputFile) {
            System.err.println("ERROR: the input file has to be specified.");
            formatter.printHelp("mof2ecore", options);
        } else if (null == outputFile) {
            System.err.println("ERROR: the output file has to be specified.");
            formatter.printHelp("mof2ecore", options);
        } else if (null == xsltFile) {
            System.err.println("ERROR: the XSLT file has to be specified.");
            formatter.printHelp("mof2ecore", options);
        } else {
            if (debug) {
                System.out.println("Command line options:");
                System.out.println("input=" + inputFile);
                System.out.println("output=" + outputFile);
                System.out.println("xslt=" + xsltFile);
                System.out.println("package=" + namePackage);
                System.out.println("container=" + suffixContainer);
                System.out.println("");
            }
            mof2ecore(xsltFile, inputFile, outputFile);
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("mof2ecore", options);
    }
}

From source file:com.cloudera.recordbreaker.schemadict.SchemaDictionary.java

public static void main(String argv[]) throws IOException {
    boolean shouldDump = false;
    boolean shouldAdd = false;
    File avroDataFile = null;// ww w  . j  a  v  a2s  .  co m
    String dictMessage = null;

    CommandLine cmd = null;
    Options options = new Options();
    options.addOption("?", false, "Help for command-line");
    options.addOption("d", false, "Dump contents of schema dictionary");
    options.addOption("a", true, "Add datafile to new schema dictionary element");
    options.addOption("m", true, "Add comment message as part of new schema dictionary element");

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, argv);
    } catch (ParseException e) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(-1);
    }

    if (cmd.hasOption("?")) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(0);
    }

    if (cmd.hasOption("d")) {
        shouldDump = true;
    }

    if (cmd.hasOption("a")) {
        avroDataFile = new File(cmd.getOptionValue("a")).getCanonicalFile();
    }
    if (cmd.hasOption("m")) {
        dictMessage = cmd.getOptionValue("m");
        if (cmd.hasOption("a")) {
            shouldAdd = true;
        }
    }
    if ((!shouldAdd) && (cmd.hasOption("a") || cmd.hasOption("m"))) {
        System.err.println("Must indicate -a AND -m to add new schema dictionary item");
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(0);
    }

    String[] argArray = cmd.getArgs();
    if (argArray.length == 0) {
        System.err.println("No schema dictionary path provided.");
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaDictionary", options, true);
        System.err.println("Required input: <schemadictionary>");
        System.exit(0);
    }

    File dictionaryDir = new File(argArray[0]).getCanonicalFile();
    SchemaDictionary dict = new SchemaDictionary(dictionaryDir);

    if (shouldAdd) {
        dict.addDictionaryElt(avroDataFile, dictMessage);
    }

    if (shouldDump) {
        int counter = 1;
        for (SchemaDictionaryEntry entry : dict.contents()) {
            System.err.println("" + counter + ".  " + entry.getInfo());
            System.err.println(entry.getSchema());
            System.err.println();
            counter++;
        }
        int numItems = counter - 1;
        System.err.println(
                "Dictionary at " + dictionaryDir.getCanonicalPath() + " has " + numItems + " item(s).");
    }
}

From source file:com.genentech.chemistry.tool.SDFFilter.java

public static void main(String args[]) {
    String usage = "java sdfFilter [options]\n" + "Filters out molecules that contain the following:\n"
            + "1. More than maxHeavy atoms (default is 100)\n" + "2. Have more than one component\n"
            + "3. Does not have any atoms\n" + "4. Have invalid atoms, like R, * etc ...\n"
            + "5. Have atomic number greater than 53 (Iodine)";

    // create Options object
    Options options = new Options();
    // add  options
    options.addOption("h", false, "");
    options.addOption("in", true, "inFile in OE formats: Ex: a.sdf or .sdf");
    options.addOption("out", true, "outFile in OE formats. Ex: a.sdf or .sdf");
    options.addOption("filtered", true, "Optional: filteredFile in OE formats. Ex: a.sdf or .sdf");
    options.addOption("maxHeavy", true, "Number of heavy atom cutoff. Default is 100");
    CommandLineParser parser = new PosixParser();

    try {/*from w  w w . j  a v a 2 s  .c om*/
        CommandLine cmd = parser.parse(options, args);
        String inFile = cmd.getOptionValue("in");
        if (inFile == null) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }

        String outFile = cmd.getOptionValue("out");
        if (outFile == null) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }

        String filteredFile = null;
        if (cmd.hasOption("filtered")) {
            filteredFile = cmd.getOptionValue("filtered");
        }

        int maxHeavy = 100;
        if (cmd.hasOption("maxHeavy")) {
            maxHeavy = Integer.parseInt(cmd.getOptionValue("maxHeavy"));
            maxAtoms = maxHeavy;
        }

        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }

        oemolistream ifs = new oemolistream(inFile);
        oemolostream ofs = new oemolostream(outFile);
        oemolostream ffs = null;
        if (filteredFile != null) {
            ffs = new oemolostream(filteredFile);
        }
        /*it appears that we don't have license to molprop toolkit
        oeisstream iss = new oeisstream();
        OEFilter filter = new OEFilter(iss);
        filter.SetTypeCheck(true);
        oechem.OEThrow.SetLevel(OEErrorLevel.Warning);
        */

        OEGraphMol mol = new OEGraphMol();

        while (oechem.OEReadMolecule(ifs, mol)) {
            //            if (passFilters(mol, filter)) { //needs license to molprop toolkit
            if (passFilters(mol)) {
                oechem.OEWriteMolecule(ofs, mol);
            } else {
                if (ffs != null) {
                    oechem.OEWriteMolecule(ffs, mol);
                }
            }
        }

    } catch (ParseException e) { // TODO print explaination
        throw new Error(e);
    }
}

From source file:com.github.aptd.simulation.CMain.java

/**
 * main method/*from w  w w. ja  v a2  s.  c o  m*/
 * @param p_args command-line parameters
 * @throws IOException error on io errors
 */
public static void main(final String[] p_args) throws IOException {
    // --- define CLI options ------------------------------------------------------------------------------------------------------------------------------

    final Options l_clioptions = new Options();
    l_clioptions.addOption("help", false, "shows this information");
    l_clioptions.addOption("generateconfig", false, "generate default configuration");
    l_clioptions.addOption("config", true,
            "path to configuration directory (default: <user home>/.asimov/configuration.yaml)");
    l_clioptions.addOption("interactive", false, "start web server for interactive execution");
    l_clioptions.addOption("sequential", false, "run simulation in sequential (default is parallel)");
    l_clioptions.addOption("iteration", true, "number of iterations");
    l_clioptions.addOption("scenariotype", true, "comma-separated list of scenario types (default: xml)");
    l_clioptions.addOption("scenario", true, "comma-separated list of scenario files");
    l_clioptions.addOption("timemodel", true, "jump for jumping time, step for stepping time (default: step)");
    l_clioptions.addOption("changetimeseed", true,
            "seed for uniform random generator of passenger platform change duration (default: 1)");
    l_clioptions.addOption("changetimemin", true,
            "minimum value for uniform random generator of passenger platform chnge duration in seconds (default: 100)");
    l_clioptions.addOption("changetimemax", true,
            "maximum value for uniform random generator of passenger platform change duration in seconds (default: 100)");
    l_clioptions.addOption("numberofpassengers", true, "number of passengers (default: 20)");
    l_clioptions.addOption("lightbarrierminfreetime", true,
            "minimum duration how long the light barrier has to be free before the door can close (default: 3)");
    l_clioptions.addOption("delayseconds", true, "primary delay of first train in seconds (default: 0)");

    final CommandLine l_cli;
    try {
        l_cli = new DefaultParser().parse(l_clioptions, p_args);
    } catch (final Exception l_exception) {
        System.err.println("command-line arguments parsing error");
        System.exit(-1);
        return;
    }

    // --- process CLI arguments and initialize configuration ----------------------------------------------------------------------------------------------

    if (l_cli.hasOption("help")) {
        new HelpFormatter().printHelp(
                new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                        .getName(),
                l_clioptions);
        return;
    }

    if (l_cli.hasOption("generateconfig")) {
        System.out
                .println(CCommon.languagestring(CMain.class, "generateconfig", CConfiguration.createdefault()));
        return;
    }

    if (!l_cli.hasOption("scenario")) {
        System.out.println(CCommon.languagestring(CMain.class, "noscenario", CConfiguration.createdefault()));
        System.exit(-1);
        return;
    }

    execute(l_cli);
}

From source file:iac.cnr.it.TestSearcher.java

public static void main(String[] args) throws IOException, ParseException {
    /** Command line parser and options */
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption(OPT_INDEX, true, "Index path");
    options.addOption(OPT_QUERY, true, "The query");

    CommandLine cmd = null;//from   ww  w  .j  a va2  s .  c  o  m
    try {
        cmd = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.fatal("Error while parsing command line arguments");
        System.exit(1);
    }

    /** Check for mandatory options */
    if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) {
        usage();
        System.exit(0);
    }

    /** Read options */
    File casePath = new File(cmd.getOptionValue(OPT_INDEX));
    String query = cmd.getOptionValue(OPT_QUERY);

    /** Check correctness of the path containing an ISODAC case */
    if (!casePath.exists() || !casePath.isDirectory()) {
        logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid");
        System.exit(1);
    }

    /** Check existance of the info.dat file */
    File infoFile = new File(casePath, INFO_FILENAME);
    if (!infoFile.exists()) {
        logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")");
        System.exit(1);
    }

    /** Load the mapping image_uuid --> image_filename */
    imagesMap = new HashMap<Integer, String>();
    BufferedReader reader = new BufferedReader(new FileReader(infoFile));
    while (reader.ready()) {
        String line = reader.readLine();

        logger.info("Read the line: " + line);
        String currentID = line.split("\t")[0];
        String currentImgFile = line.split("\t")[1];
        imagesMap.put(Integer.parseInt(currentID), currentImgFile);
        logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map");

    }
    reader.close();

    /** Load all the directories containing an index */
    ArrayList<String> indexesDirs = new ArrayList<String>();
    for (File f : casePath.listFiles()) {
        logger.info("Analyzing: " + f);
        if (f.isDirectory())
            indexesDirs.add(f.getAbsolutePath());
    }
    logger.info(indexesDirs.size() + " directories found!");

    /** Set-up the searcher */
    Searcher searcher = null;
    try {
        String[] array = indexesDirs.toArray(new String[indexesDirs.size()]);
        searcher = new Searcher(array);
        TopDocs results = searcher.search(query, Integer.MAX_VALUE);

        ScoreDoc[] hits = results.scoreDocs;
        int numTotalHits = results.totalHits;

        System.out.println(numTotalHits + " total matching documents");

        for (int i = 0; i < numTotalHits; i++) {
            Document doc = searcher.doc(hits[i].doc);

            String path = doc.get(FIELD_PATH);
            String filename = doc.get(FIELD_FILENAME);
            String image_uuid = doc.get(FIELD_IMAGE_ID);

            if (path != null) {
                //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score);
                //               System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid);
                System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: "
                        + imagesMap.get(Integer.parseInt(image_uuid)));
            } else {
                System.out.println((i + 1) + ". " + "No path for this document");
            }
        }

    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (searcher != null)
            searcher.close();
    }
}

From source file:com.cloudera.recordbreaker.learnstructure.test.GenerateRandomData.java

/**
 *//* w  w w.ja  v  a  2 s  .c o  m*/
public static void main(String argv[]) throws IOException {
    CommandLine cmd = null;
    Options options = new Options();
    options.addOption("?", false, "Help for command-line");
    options.addOption("n", true, "Number elts to emit");

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, argv);
    } catch (ParseException pe) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateRandomData", options, true);
        System.exit(-1);
    }

    if (cmd.hasOption("?")) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateRandomData", options, true);
        System.exit(0);
    }

    int numToEmit = 100;
    if (cmd.hasOption("n")) {
        try {
            numToEmit = Integer.parseInt(cmd.getOptionValue("n"));
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }

    String[] argArray = cmd.getArgs();
    if (argArray.length == 0) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateRandomData", options, true);
        System.exit(0);
    }
    File inputSchemaFile = new File(argArray[0]).getCanonicalFile();
    File outputDataFile = new File(argArray[1]).getCanonicalFile();
    if (outputDataFile.exists()) {
        System.err.println("Output file already exists: " + outputDataFile.getCanonicalPath());
        System.exit(0);
    }

    GenerateRandomData grd = new GenerateRandomData();
    Schema schema = Schema.parse(inputSchemaFile);

    GenericDatumWriter datum = new GenericDatumWriter(schema);
    DataFileWriter out = new DataFileWriter(datum);
    out.create(schema, outputDataFile);
    try {
        for (int i = 0; i < numToEmit; i++) {
            out.append((GenericData.Record) grd.generateData(schema));
        }
    } finally {
        out.close();
    }
}

From source file:com.crushpaper.Main.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("properties", true, "file system path to the crushpaper properties file");

    // Parse the command line.
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;/*from w  ww .  j a v  a2  s  . c  o  m*/

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("crushpaper: Sorry, could not parse command line because `" + e.getMessage() + "`.");
        System.exit(1);
    }

    if (commandLine == null || commandLine.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("crushpaper", options);
        return;
    }

    // Get the properties path.
    String properties = null;
    if (commandLine.hasOption("properties")) {
        properties = commandLine.getOptionValue("properties");
    }

    if (properties == null || properties.isEmpty()) {
        System.err.println("crushpaper: Sorry, the `properties` command argument must be specified.");
        System.exit(1);
    }

    Configuration configuration = new Configuration();
    if (!configuration.load(new File(properties))) {
        System.exit(1);
    }

    // Get values.
    File databaseDirectory = configuration.getDatabaseDirectory();
    File keyStorePath = configuration.getKeyStoreFile();
    Integer httpPort = configuration.getHttpPort();
    Integer httpsPort = configuration.getHttpsPort();
    Integer httpsProxiedPort = configuration.getHttpsProxiedPort();
    String keyStorePassword = configuration.getKeyStorePassword();
    String keyManagerPassword = configuration.getKeyManagerPassword();
    File temporaryDirectory = configuration.getTemporaryDirectory();
    String singleUserName = configuration.getSingleUserName();
    Boolean allowSelfSignUp = configuration.getAllowSelfSignUp();
    Boolean allowSaveIfNotSignedIn = configuration.getAllowSaveIfNotSignedIn();
    File logDirectory = configuration.getLogDirectory();
    Boolean loopbackIsAdmin = configuration.getLoopbackIsAdmin();
    File sessionStoreDirectory = configuration.getSessionStoreDirectory();
    Boolean isOfficialSite = configuration.getIsOfficialSite();
    File extraHeaderFile = configuration.getExtraHeaderFile();

    // Validate the values.
    if (httpPort != null && httpsPort != null && httpPort.equals(httpsPort)) {
        System.err.println("crushpaper: Sorry, `" + configuration.getHttpPortKey() + "` and `"
                + configuration.getHttpsPortKey() + "` must not be set to the same value.");
        System.exit(1);
    }

    if ((httpsPort == null) != (keyStorePath == null)) {
        System.err.println("crushpaper: Sorry, `" + configuration.getHttpsPortKey() + "` and `"
                + configuration.getKeyStoreKey() + "` must either both be set or not set.");
        System.exit(1);
    }

    if (httpsProxiedPort != null && httpsPort == null) {
        System.err.println("crushpaper: Sorry, `" + configuration.getHttpsProxiedPortKey()
                + "` can only be set if `" + configuration.getHttpsPortKey() + "` is set.");
        System.exit(1);
    }

    if (databaseDirectory == null) {
        System.err.println("crushpaper: Sorry, `" + configuration.getDatabaseDirectoryKey() + "` must be set.");
        System.exit(1);
    }

    if (singleUserName != null && !AccountAttributeValidator.isUserNameValid(singleUserName)) {
        System.err.println(
                "crushpaper: Sorry, the username in `" + configuration.getSingleUserKey() + "` is not valid.");
        return;
    }

    if (allowSelfSignUp == null || allowSaveIfNotSignedIn == null || loopbackIsAdmin == null) {
        System.exit(1);
    }

    String extraHeader = null;
    if (extraHeaderFile != null) {
        extraHeader = readFile(extraHeaderFile);
        if (extraHeader == null) {
            System.err.println("crushpaper: Sorry, the file `" + extraHeaderFile.getPath() + "` set in `"
                    + configuration.getExtraHeaderKey() + "` could not be read.");
            System.exit(1);
        }
    }

    final DbLogic dbLogic = new DbLogic(databaseDirectory);
    dbLogic.createDb();
    final Servlet servlet = new Servlet(dbLogic, singleUserName, allowSelfSignUp, allowSaveIfNotSignedIn,
            loopbackIsAdmin, httpPort, httpsPort, httpsProxiedPort, keyStorePath, keyStorePassword,
            keyManagerPassword, temporaryDirectory, logDirectory, sessionStoreDirectory, isOfficialSite,
            extraHeader);
    servlet.run();
}

From source file:com.alexoree.jenkins.Main.java

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

    options.addOption("t", false, "throttle the downloads, waits 5 seconds in between each d/l");

    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("jenkins-sync", options);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    boolean throttle = cmd.hasOption("t");

    String plugins = "https://updates.jenkins-ci.org/latest/";
    List<String> ps = new ArrayList<String>();
    Document doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".hpi") || file.attr("href").endsWith(".war")) {
            ps.add(file.attr("href"));
        }//w  ww .  j  a v  a2  s.c o m
    }

    File root = new File(".");
    //https://updates.jenkins-ci.org/latest/AdaptivePlugin.hpi
    new File("./latest").mkdirs();

    //output zip file
    String zipFile = "jenkinsSync.zip";
    // create byte buffer
    byte[] buffer = new byte[1024];
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    //download the plugins
    for (int i = 0; i < ps.size(); i++) {
        System.out.println("[" + i + "/" + ps.size() + "] downloading " + plugins + ps.get(i));
        String outputFile = download(root.getAbsolutePath() + "/latest/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(outputFile);
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(outputFile.replace(root.getAbsolutePath(), "")
                .replace("updates.jenkins-ci.org/", "").replace("https:/", "")));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        if (throttle)
            Thread.sleep(WAIT);
        new File(root.getAbsolutePath() + "/latest/" + ps.get(i)).deleteOnExit();
    }

    //download the json metadata
    plugins = "https://updates.jenkins-ci.org/";
    ps = new ArrayList<String>();
    doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".json")) {
            ps.add(file.attr("href"));
        }
    }
    for (int i = 0; i < ps.size(); i++) {
        download(root.getAbsolutePath() + "/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(root.getAbsolutePath() + "/" + ps.get(i));
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(plugins + ps.get(i)));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        new File(root.getAbsolutePath() + "/" + ps.get(i)).deleteOnExit();
        if (throttle)
            Thread.sleep(WAIT);
    }

    // close the ZipOutputStream
    zos.close();
}

From source file:com.arainfor.thermostat.daemon.HvacMonitor.java

/**
 * @param args The Program Arguments//from   w  ww  .j av  a 2 s.  com
 */
public static void main(String[] args) throws IOException {

    Logger log = LoggerFactory.getLogger(HvacMonitor.class);

    //System.err.println(APPLICATION_NAME + " v" + APPLICATION_VERSION_MAJOR + "." + APPLICATION_VERSION_MINOR + "." + APPLICATION_VERSION_BUILD);
    Options options = new Options();
    options.addOption("help", false, "This message isn't very helpful");
    options.addOption("version", false, "Print the version number");
    options.addOption("monitor", false, "Start GUI Monitor");
    options.addOption("config", true, "The configuration file");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp(APPLICATION_NAME, options);
            return;
        }
        if (cmd.hasOption("version")) {
            System.out.println("The " + APPLICATION_NAME + " v" + APPLICATION_VERSION_MAJOR + "."
                    + APPLICATION_VERSION_MINOR + "." + APPLICATION_VERSION_BUILD);
        }
    } catch (ParseException e) {
        e.printStackTrace();
        return;
    }

    String propFileName = "thermostat.properties";
    if (cmd.getOptionValue("config") != null)
        propFileName = cmd.getOptionValue("config");

    log.info("loading...{}", propFileName);

    try {
        Properties props = new PropertiesLoader(propFileName).getProps();

        // Append the system properties with our application properties
        props.putAll(System.getProperties());
        System.setProperties(props);
    } catch (FileNotFoundException fnfe) {
        log.warn("Cannot load file:", fnfe);
    }

    new HvacMonitor().start();

}

From source file:mecard.MetroService.java

public static void main(String[] args) {
    // First get the valid options
    Options options = new Options();
    // add t option c to config directory true=arg required.
    options.addOption("c", true,
            "configuration file directory path, include all sys dependant dir seperators like '/'.");
    // add t option c to config directory true=arg required.
    options.addOption("v", false, "Metro server version information.");
    try {/*from   w  ww  . ja  v a 2s.  c o  m*/
        // parse the command line.
        CommandLineParser parser = new BasicParser();
        CommandLine cmd;
        cmd = parser.parse(options, args);
        if (cmd.hasOption("v")) {
            System.out.println("Metro (MeCard) server version " + PropertyReader.VERSION);
        }
        // get c option value
        String configDirectory = cmd.getOptionValue("c");
        PropertyReader.setConfigDirectory(configDirectory);
    } catch (ParseException ex) {
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(
                new Date() + "Unable to parse command line option. Please check your service configuration.");
        System.exit(799);
    }

    Properties properties = PropertyReader.getProperties(ConfigFileTypes.ENVIRONMENT);
    String portString = properties.getProperty(LibraryPropertyTypes.METRO_PORT.toString(), defaultPort);

    try {
        int port = Integer.parseInt(portString);
        serverSocket = new ServerSocket(port);
    } catch (IOException ex) {
        String msg = " Could not listen on port: " + portString;
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    } catch (NumberFormatException ex) {
        String msg = "Could not parse port number defined in configuration file.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    }

    while (listening) {
        try {
            new SocketThread(serverSocket.accept()).start();
        } catch (IOException ex) {
            String msg = "unable to start server socket; either accept or start failed.";
            //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
            System.out.println(new Date() + msg);
        }
    }
    try {
        serverSocket.close();
    } catch (IOException ex) {
        String msg = "failed to close the server socket.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg);
    }
}