Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:com.hpe.nv.samples.basic.BasicAnalyzeNVTest.java

public static void main(String[] args) {
    try {/*  w w w .ja  va2s  . com*/
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("z", "zip-result-file-path", true,
                "[optional] File path to store the analysis results as a .zip file");
        options.addOption("k", "analysis-ports", true,
                "[optional] A comma-separated list of ports for test analysis");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicAnalyzeNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("zip-result-file-path")) {
            zipResultFilePath = line.getOptionValue("zip-result-file-path");
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("analysis-ports")) {
            String analysisPortsStr = line.getOptionValue("analysis-ports");
            analysisPorts = analysisPortsStr.split(",");
        } else {
            analysisPorts = new String[] { "80", "8080" };
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                                                      ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                                                  ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                                                    ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website                               ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                                       ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   Finally, the sample stops the NV test, analyzes it, and prints the path of the analysis .zip file to the console.   ***"
                + newLine
                + "***                                                                                                                       ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicAnalyzeNVTest.java file.                                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                            *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                                    *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                                       *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test, analyze it and print the results to the console                        *****/
        printPartDescription(
                "------    Part 4 - Stop the NV test, analyze it and print the results to the console");
        stopTestAndAnalyze();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

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

    // create Options object
    Options options = new Options();
    options.addOption(create_bucket);/* ww w  . ja  v  a 2  s .c  om*/
    options.addOption(create_key);
    options.addOption(delete_bucket);
    options.addOption(get);
    options.addOption(help);
    options.addOption(inspect);
    options.addOption(keyfile);
    options.addOption(list_buckets);
    options.addOption(list_objects);
    options.addOption(put);
    options.addOption(remove);
    options.addOption(rotate);
    options.addOption(rotateall);
    options.addOption(rotateKey);

    //      CommandLineParser parser = new GnuParser();
    //       Changed from above GnuParser to below PosixParser because I found code which allows for multiple arguments 
    PosixParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        Logger.getRootLogger().setLevel(Level.OFF);

        if (cmd.hasOption("help")) {
            HelpFormatter help = new HelpFormatter();
            System.out.println();
            help.printHelp("S3Encrypt", options);
            System.out.println();
            System.exit(1);
        } else if (cmd.hasOption("create_key")) {
            keyname = cmd.getOptionValue("keyfile");
            createKeyFile(keyname);
            key = new File(keyname);
        } else {
            if (cmd.hasOption("keyfile")) {
                keyname = cmd.getOptionValue("keyfile");
            }
            key = new File(keyname);
        }

        if (!(key.exists())) {
            System.out.println("Key does not exist or not provided");
            System.exit(1);
        }

        //         AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
        ClasspathPropertiesFileCredentialsProvider credentials = new ClasspathPropertiesFileCredentialsProvider(
                ".s3encrypt");
        EncryptionMaterials encryptionMaterials = new EncryptionMaterials(getKeyFile(keyname));
        AmazonS3EncryptionClient s3 = new AmazonS3EncryptionClient(credentials.getCredentials(),
                encryptionMaterials);
        //          Region usWest2 = Region.getRegion(Regions.US_WEST_2);
        //          s3.setRegion(usWest2);

        if (cmd.hasOption("create_bucket")) {
            String bucket = cmd.getOptionValue("create_bucket");
            System.out.println("Creating bucket " + bucket + "\n");
            s3.createBucket(bucket);
        } else if (cmd.hasOption("delete_bucket")) {
            String bucket = cmd.getOptionValue("delete_bucket");
            System.out.println("Deleting bucket " + bucket + "\n");
            s3.deleteBucket(bucket);
        } else if (cmd.hasOption("get")) {
            String[] searchArgs = cmd.getOptionValues("get");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            getS3Object(cmd, s3, bucket, filename);
        } else if (cmd.hasOption("inspect")) {
            String[] searchArgs = cmd.getOptionValues("inspect");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            String keyname = "encryption_key";
            String metadata = inspectS3Object(cmd, s3, bucket, filename, keyname);
            System.out.println(metadata);
        } else if (cmd.hasOption("list_buckets")) {
            System.out.println("Listing buckets");
            for (Bucket bucket : s3.listBuckets()) {
                System.out.println(bucket.getName());
            }
            System.out.println();
        } else if (cmd.hasOption("list_objects")) {
            String bucket = cmd.getOptionValue("list_objects");
            System.out.println("Listing objects");
            ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucket));
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
            }
            System.out.println();
        } else if (cmd.hasOption("put")) {
            String[] searchArgs = cmd.getOptionValues("put");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            String metadataKeyname = "encryption_key";
            String key = keyname;
            putS3Object(cmd, s3, bucket, filename, metadataKeyname, key);
        } else if (cmd.hasOption("remove")) {
            String[] searchArgs = cmd.getOptionValues("remove");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            System.out.println("Removing object in S3 from BUCKET = " + bucket + " FILENAME = " + filename);
            s3.deleteObject(new DeleteObjectRequest(bucket, filename));
            System.out.println();
        } else if (cmd.hasOption("rotate")) {
            String[] searchArgs = cmd.getOptionValues("rotate");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            String key1 = cmd.getOptionValue("keyfile");
            String key2 = cmd.getOptionValue("rotateKey");
            String metadataKeyname = "encryption_key";
            System.out.println("Supposed to get object from here OPTION VALUE = " + bucket + " FILENAME = "
                    + filename + " KEY1 = " + key1 + " KEY2 = " + key2);

            EncryptionMaterials rotateEncryptionMaterials = new EncryptionMaterials(getKeyFile(key2));
            AmazonS3EncryptionClient rotateS3 = new AmazonS3EncryptionClient(credentials.getCredentials(),
                    rotateEncryptionMaterials);

            getS3Object(cmd, s3, bucket, filename);
            putS3Object(cmd, rotateS3, bucket, filename, metadataKeyname, key2);
        } else if (cmd.hasOption("rotateall")) {
            String[] searchArgs = cmd.getOptionValues("rotateall");
            String bucket = searchArgs[0];
            String key1 = searchArgs[1];
            String key2 = searchArgs[2];
            System.out.println("Supposed to rotateall here for BUCKET NAME = " + bucket + " KEY1 = " + key1
                    + " KEY2 = " + key2);
        } else {
            System.out.println("Something went wrong... ");
            System.exit(1);
        }

    } catch (ParseException e) {
        e.printStackTrace();
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                + "an internal error while trying to " + "communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

}

From source file:com.github.enr.markdownj.extras.MarkdownApp.java

public static void main(String[] args) {
    MarkdownApp app = new MarkdownApp();
    app.log().debug("Markdown app starting with args: {}", Arrays.toString(args));
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("s", "source", true, "The source directory for markdown files");
    options.addOption("d", "destination", true, "The destination directory for html files");
    options.addOption("h", "header", true, "The path to the html header file");
    options.addOption("f", "footer", true, "The path to the html footer file");
    options.addOption("t", "code-template", true, "The template for code blocks");
    options.addOption("e", "extensions", true,
            "A comma separated list of file extensions to process. If setted, files with extension not in list won't be processed");
    options.addOption("c", "char-encoding", true, "The encoding to read and write files");
    HelpFormatter formatter = new HelpFormatter();
    String helpHeader = String.format("%s", MarkdownApp.class.getName());
    try {/*www.  jav  a2s.c  o  m*/
        CommandLine line = parser.parse(options, args);
        app.process(line);
    } catch (ParseException e) {
        app.log().warn(e.getMessage(), e);
        formatter.printHelp(helpHeader, options);
    }
}

From source file:de.prozesskraft.ptest.Fingerprint.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//from www .j a v  a  2s .c o m
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option opath = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription(
                    "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.")
            //            .isRequired()
            .create("path");

    Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription(
            "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]")
            //            .isRequired()
            .create("sizetol");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes")
            //            .isRequired()
            .create("md5");

    Option oignore = OptionBuilder.withArgName("STRING").hasArgs()
            .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignore");

    Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint")
            //            .isRequired()
            .create("ignorefile");

    Option ooutput = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file")
            //            .isRequired()
            .create("output");

    Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(opath);
    options.addOption(osizetol);
    options.addOption(omd5);
    options.addOption(oignore);
    options.addOption(oignorefile);
    options.addOption(ooutput);
    options.addOption(of);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     " + web);
        System.out.println("author: " + author);
        System.out.println("version:" + version);
        System.out.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    String path = "";
    String sizetol = "";
    boolean md5 = false;
    Float sizetolFloat = null;
    String output = "";
    java.io.File ignorefile = null;
    ArrayList<String> ignore = new ArrayList<String>();

    if (!(commandline.hasOption("path"))) {
        System.err.println("setting default for -path=.");
        path = ".";
    } else {
        path = commandline.getOptionValue("path");
    }

    if (!(commandline.hasOption("sizetol"))) {
        System.err.println("setting default for -sizetol=0.02");
        sizetol = "0.02";
        sizetolFloat = 0.02F;
    } else {
        sizetol = commandline.getOptionValue("sizetol");
        sizetolFloat = Float.parseFloat(sizetol);

        if ((sizetolFloat > 1) || (sizetolFloat < 0)) {
            System.err.println("use only values >=0.0 and <1.0 for -sizetol");
            System.exit(1);
        }
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default for -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    if (commandline.hasOption("ignore")) {
        ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore")));
    }

    if (commandline.hasOption("ignorefile")) {
        ignorefile = new java.io.File(commandline.getOptionValue("ignorefile"));
        if (!ignorefile.exists()) {
            System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath());
        }
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("setting default for -output=" + path + "/fingerprint.xml");
        output = path + "/fingerprint.xml";
    } else {
        output = commandline.getOptionValue("output");
    }

    // wenn output bereits existiert -> abbruch
    java.io.File outputFile = new File(output);
    if (outputFile.exists()) {
        if (commandline.hasOption("f")) {
            outputFile.delete();
        } else {
            System.err
                    .println("error: output file (" + output + ") already exists. use -f to force overwrite.");
            System.exit(1);
        }
    }

    //      if ( !( commandline.hasOption("output")) )
    //      {
    //         System.err.println("option -output is mandatory.");
    //         exiter();
    //      }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Dir dir = new Dir();
    dir.setBasepath(path);
    dir.setOutfilexml(output);

    // ignore file in ein Array lesen
    if ((ignorefile != null) && (ignorefile.exists())) {
        Scanner sc = new Scanner(ignorefile);
        while (sc.hasNextLine()) {
            ignore.add(sc.nextLine());
        }
        sc.close();
    }

    //      // autoignore hinzufuegen
    //      String autoIgnoreString = ini.get("autoignore", "autoignore");
    //      ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(",")));

    //      // debug
    //      System.out.println("ignorefile content:");
    //      for(String actLine : ignore)
    //      {
    //         System.out.println("line: "+actLine);
    //      }

    try {
        dir.genFingerprint(sizetolFloat, md5, ignore);
    } catch (NullPointerException e) {
        System.err.println("file/dir does not exist " + path);
        e.printStackTrace();
        exiter();
    } catch (IOException e) {
        e.printStackTrace();
        exiter();
    }

    System.out.println("writing to file: " + dir.getOutfilexml());
    dir.writeXml();

}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {/*from  ww  w .  j  ava 2 s  . c o  m*/
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

From source file:de.prozesskraft.ptest.Compare.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//w w w. j  a v a 2  s. com
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Compare.class) + "/" + "../etc/ptest-compare.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oref = OptionBuilder.withArgName("PATH").hasArg()
            .withDescription("[mandatory] directory or fingerprint, that the --exam will be checked against")
            //            .isRequired()
            .create("ref");

    Option oexam = OptionBuilder.withArgName("PATH").hasArg().withDescription(
            "[optional; default: parent directory of -ref] directory or fingerprint, that will be checked against --ref")
            //            .isRequired()
            .create("exam");

    Option oresult = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory; default: result.txt] the result (success|failed) of the comparison will be printed to this file")
            //            .isRequired()
            .create("result");

    Option osummary = OptionBuilder.withArgName("all|error|debug").hasArg().withDescription(
            "[optional] 'error' prints a summary reduced to failed matches. 'all' prints a full summary. 'debug' is like 'all' plus debug statements")
            //            .isRequired()
            .create("summary");

    Option omd5 = OptionBuilder.withArgName("no|yes").hasArg()
            .withDescription("[optional; default: yes] to ignore md5 information in comparison use -md5=no")
            //            .isRequired()
            .create("md5");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oref);
    options.addOption(oexam);
    options.addOption(oresult);
    options.addOption(osummary);
    options.addOption(omd5);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("compare", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.err.println("web:     " + web);
        System.err.println("author: " + author);
        System.err.println("version:" + version);
        System.err.println("date:     " + date);
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    boolean error = false;
    String result = "";
    boolean md5 = false;
    String ref = null;
    String exam = null;

    if (!(commandline.hasOption("ref"))) {
        System.err.println("option -ref is mandatory");
        error = true;
    } else {
        ref = commandline.getOptionValue("ref");
    }

    if (!(commandline.hasOption("exam"))) {
        java.io.File refFile = new java.io.File(ref).getCanonicalFile();
        java.io.File examFile = refFile.getParentFile();
        exam = examFile.getCanonicalPath();

        System.err.println("setting default: -exam=" + exam);
    } else {
        exam = commandline.getOptionValue("exam");
    }

    if (error) {
        exiter();
    }

    if (!(commandline.hasOption("result"))) {
        System.err.println("setting default: -result=result.txt");
        result = "result.txt";
    }

    if (!(commandline.hasOption("md5"))) {
        System.err.println("setting default: -md5=yes");
        md5 = true;
    } else if (commandline.getOptionValue("md5").equals("no")) {
        md5 = false;
    } else if (commandline.getOptionValue("md5").equals("yes")) {
        md5 = true;
    } else {
        System.err.println("use only values no|yes for -md5");
        System.exit(1);
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // einlesen der referenzdaten
    java.io.File refPath = new java.io.File(ref);

    Dir refDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (refPath.exists() && refPath.isDirectory()) {
        refDir.setBasepath(refPath.getCanonicalPath());
        refDir.genFingerprint(0f, true, new ArrayList<String>());
        refDir.setRespectMd5Recursive(md5);
        System.err.println("-ref is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (refPath.exists()) {
        refDir.setInfilexml(refPath.getCanonicalPath());
        System.err.println("-ref is a fingerprint");
        try {
            refDir.readXml();
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        refDir.setRespectMd5Recursive(md5);
    } else if (!refPath.exists()) {
        System.err.println("-ref does not exist! " + refPath.getAbsolutePath());
        exiter();
    }

    // einlesen der prueflingsdaten
    java.io.File examPath = new java.io.File(exam);

    Dir examDir = new Dir();

    // wenn es ein directory ist, muss der fingerprint erzeugt werden
    if (examPath.exists() && examPath.isDirectory()) {
        examDir.setBasepath(examPath.getCanonicalPath());
        examDir.genFingerprint(0f, true, new ArrayList<String>());
        examDir.setRespectMd5Recursive(md5);
        System.err.println("-exam is a directory");
    }
    // wenn es ein fingerprint ist, muss er eingelesen werden
    else if (examPath.exists()) {
        examDir.setInfilexml(examPath.getCanonicalPath());
        System.err.println("-exam is a fingerprint");
        try {
            examDir.readXml();
        } catch (JAXBException e) {
            System.err.println("error while reading xml");
            e.printStackTrace();
        }
        examDir.setRespectMd5Recursive(md5);
    } else if (!examPath.exists()) {
        System.err.println("-exam does not exist! " + examPath.getAbsolutePath());
        exiter();
    }

    // durchfuehren des vergleichs
    refDir.runCheck(examDir);

    //      if(examDir.isMatchSuccessfullRecursive() && refDir.isMatchSuccessfullRecursive())
    if (refDir.isMatchSuccessfullRecursive()) {
        System.out.println("SUCCESS");
    } else {
        System.out.println("FAILED");
    }

    // printen der csv-ergebnis-tabelle
    if (commandline.hasOption("summary")) {
        if (commandline.getOptionValue("summary").equals("error")) {
            System.err.println("the results of the reference are crucial for result FAILED|SUCCESS");
            System.err.println(refDir.sprintSummaryAsCsv("error"));
            System.err.println(examDir.sprintSummaryAsCsv("error"));
        } else if (commandline.getOptionValue("summary").equals("all")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
        } else if (commandline.getOptionValue("summary").equals("debug")) {
            System.err.println(refDir.sprintSummaryAsCsv("all"));
            System.err.println(examDir.sprintSummaryAsCsv("all"));
            // printen des loggings
            System.err.println("------ logging of reference --------");
            System.err.println(refDir.getLogAsStringRecursive());
            System.err.println("------ logging of examinee --------");
            System.err.println(examDir.getLogAsStringRecursive());
        } else {
            System.err.println("for option -summary you only may use all|error");
            exiter();
        }
    }

}

From source file:br.com.estudogrupo.principal.Principal.java

public static void main(String[] args) throws ParseException {
    Dicionario dicionario = new Dicionario();
    Dicionario1 dicionario1 = new Dicionario1();
    Dicionario2 dicionario2 = new Dicionario2();
    Dicionario3 dicionario3 = new Dicionario3();
    Dicionario4 dicionario4 = new Dicionario4();
    Dicionario5 dicionario5 = new Dicionario5();
    Dicionario6 dicionario6 = new Dicionario6();
    Dicionario7 dicionario7 = new Dicionario7();
    DicionarioSha1 dicionarioSha1 = new DicionarioSha1();
    DicionarioSha2 dicionarioSha2 = new DicionarioSha2();
    DicionarioSha3 dicionarioSha3 = new DicionarioSha3();
    DicionarioSha4 dicionarioSha4 = new DicionarioSha4();
    DicionarioSha5 dicionarioSha5 = new DicionarioSha5();
    DicionarioSha6 dicionarioSha6 = new DicionarioSha6();
    DicionarioSha7 dicionarioSha7 = new DicionarioSha7();
    DicionarioSha8 dicionarioSha8 = new DicionarioSha8();
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("m", "MD5", true, "Md5 hash");
    options.addOption("s", "SHA1", true, "Sha1 hash");
    options.addOption("b", "BASE64", true, "Base64 hash");
    options.addOption("l1", "Lista 1", true, "WordList");
    options.addOption("l2", "Lista 2", true, "WordList");
    options.addOption("l3", "Lista 3", true, "WordList");
    options.addOption("l4", "Lista 4", true, "WordList");
    options.addOption("l5", "Lista 5", true, "WordList");
    options.addOption("l6", "Lista 6", true, "WordList");
    options.addOption("l7", "Lista 7", true, "WordList");
    options.addOption("l8", "Lista 8", true, "WordList");
    options.addOption("oM", "ONLINE", true, "Busca md5 hash Online");
    int contador = 0;
    int contadodorSha = 0;
    CommandLine line = null;/*w  ww  . j a  va2 s  .c o  m*/
    try {
        line = parser.parse(options, args);
    } catch (Exception e) {

    }

    try {
        if (line.hasOption("oM")) {
            String pegar = line.getOptionValue("oM");
            DicionarioOnline01 dicionarioOnline01 = new DicionarioOnline01();
            dicionarioOnline01.setRecebe(pegar);
            Thread t1Online = new Thread(dicionarioOnline01);
            t1Online.start();

            //Segunda Thread
            DicionarioOnline02 dicionarioOnline02 = new DicionarioOnline02();
            dicionarioOnline02.setRecebe(pegar);
            Thread t2Online = new Thread(dicionarioOnline02);
            t2Online.start();

            //Terceira Thread
            DicionarioOnline03 dicionarioOnline03 = new DicionarioOnline03();
            dicionarioOnline03.setRecebe(pegar);
            Thread t3Online = new Thread(dicionarioOnline03);
            t3Online.start();

            //Quarta Thread
            DicionarioOnline04 dicionarioOnline04 = new DicionarioOnline04();
            dicionarioOnline04.setRecebe(pegar);
            Thread t4Online = new Thread(dicionarioOnline04);
            t4Online.start();
            //Quinta Thread
            DicionarioOnline05 dicionarioOnline05 = new DicionarioOnline05();
            dicionarioOnline05.setRecebe(pegar);
            Thread t5Online = new Thread(dicionarioOnline05);
            t5Online.start();

            System.out.println(" _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                    + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                    + "| |  / ____ \\| |__| || |_| |\\  |\n" + "|_| /_/    \\_\\_____/_____|_| \\_|\n"
                    + "                                \n" + "            ");
            System.out.println("Executando...");

        } else if (line.hasOption('m')) {
            if (line.hasOption("l1")) {
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l1");
                dicionario.setRecebe(recebe);
                dicionario.setLista(lista);
                contador++;
                Thread t1 = new Thread(dicionario);

                t1.start();

            }
            if (line.hasOption("l2")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l2");
                dicionario1.setRecebe(recebe);
                dicionario1.setLista(lista);
                Thread t2 = new Thread(dicionario1);

                t2.start();

            }
            if (line.hasOption("l3")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l3");
                dicionario2.setRecebe(recebe);
                dicionario2.setLista(lista);
                Thread t3 = new Thread(dicionario2);

                t3.start();
            }
            if (line.hasOption("l4")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l3");
                dicionario3.setRecebe(recebe);
                dicionario3.setLista(lista);
                Thread t4 = new Thread(dicionario3);

                t4.start();

            }
            if (line.hasOption("l5")) {
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l5");
                dicionario4.setRecebe(recebe);
                dicionario4.setLista(lista);
                Thread t5 = new Thread(dicionario4);
                contador++;

                t5.start();

            }
            if (line.hasOption("l6")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l6");
                dicionario5.setRecebe(recebe);
                dicionario5.setLista(lista);
                Thread t6 = new Thread(dicionario5);

                t6.start();
            }
            if (line.hasOption("l7")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l7");
                dicionario6.setRecebe(recebe);
                dicionario6.setLista(lista);
                Thread t6 = new Thread(dicionario6);

                t6.start();
            }
            if (line.hasOption("l8")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l8");
                dicionario7.setRecebe(recebe);
                dicionario7.setLista(lista);
                Thread t7 = new Thread(dicionario7);

                t7.start();

            }
            if (contador > 0) {
                System.out.println(" _____        _____ _____ _   _ \n"
                        + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n" + "| |__) /  \\  | |  | || | |  \\| |\n"
                        + "|  ___/ /\\ \\ | |  | || | | . ` |\n" + "| |  / ____ \\| |__| || |_| |\\  |\n"
                        + "|_| /_/    \\_\\_____/_____|_| \\_|\n" + "                                \n"
                        + "            ");
                System.out.println("Executando...");
                contador = 0;

            }
        } else if (line.hasOption('s')) {
            if (line.hasOption("l1")) {
                contadodorSha++;
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l1");
                dicionarioSha1.setRecebe(pegar);
                dicionarioSha1.setLista(lista);
                Thread t1 = new Thread(dicionarioSha1);

                t1.start();
            } else if (line.hasOption("l2")) {
                contadodorSha++;
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l2");
                dicionarioSha2.setRecebe(pegar);
                dicionarioSha2.setLista(lista);
                Thread t2 = new Thread(dicionarioSha2);

                t2.start();
            } else if (line.hasOption("l3")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l3");
                dicionarioSha3.setRecebe(pegar);
                dicionarioSha3.setLista(lista);
                Thread t3 = new Thread(dicionarioSha3);
                contadodorSha++;
                t3.start();
            } else if (line.hasOption("l4")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l4");
                dicionarioSha4.setRecebe(pegar);
                dicionarioSha4.setLista(lista);
                Thread t4 = new Thread(dicionarioSha4);
                contadodorSha++;
                t4.start();
            } else if (line.hasOption("l5")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l5");
                dicionarioSha5.setRecebe(pegar);
                dicionarioSha5.setLista(lista);
                Thread t5 = new Thread(dicionarioSha5);
                contador++;
                t5.start();
            } else if (line.hasOption("l6")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l6");
                dicionarioSha6.setRecebe(pegar);
                dicionarioSha6.setLista(lista);
                Thread t6 = new Thread(dicionarioSha6);
                contadodorSha++;
                t6.start();
            } else if (line.hasOption("l7")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l7");
                dicionarioSha7.setRecebe(pegar);
                dicionarioSha7.setLista(lista);
                Thread t7 = new Thread(dicionarioSha7);
                contadodorSha++;
                t7.start();
            } else {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(" _____        _____ _____ _   _ \n"
                        + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n" + "| |__) /  \\  | |  | || | |  \\| |\n"
                        + "|  ___/ /\\ \\ | |  | || | | . ` |\n" + "| |  / ____ \\| |__| || |_| |\\  |\n"
                        + "|_| /_/    \\_\\_____/_____|_| \\_|\n\n\n" + "                                \n"
                        + "   \n" + "                              \n" + "\n" + "\n" + "\n " + "\n", options);
            }
            if (contadodorSha > 0) {
                System.out.println(" _____        _____ _____ _   _ \n"
                        + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n" + "| |__) /  \\  | |  | || | |  \\| |\n"
                        + "|  ___/ /\\ \\ | |  | || | | . ` |\n" + "| |  / ____ \\| |__| || |_| |\\  |\n"
                        + "|_| /_/    \\_\\_____/_____|_| \\_|\n" + "                                \n"
                        + "            ");
                System.out.println("Executando...");
                contadodorSha = 0;
            }

        } else if (line.hasOption('b')) {
            String pegar = line.getOptionValue('b');
            System.out.println(" _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                    + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                    + "| |  / ____ \\| |__| || |_| |\\  |\n" + "|_| /_/    \\_\\_____/_____|_| \\_|\n"
                    + "                                \n" + "            ");
            System.out.println("executando...");
            byte[] decoder = Base64.decodeBase64(pegar.getBytes());
            System.out.println("Senha : " + new String(decoder));

        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    " _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                            + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                            + "| |  / ____ \\| |__| || |_| |\\  |\n"
                            + "|_| /_/    \\_\\_____/_____|_| \\_|\n\n\n" + "                                \n"
                            + "   \n" + "                              \n" + "\n" + "\n" + "\n " + "\n",
                    options);
        }

    } catch (NullPointerException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(" _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                + "| |  / ____ \\| |__| || |_| |\\  |\n" + "|_| /_/    \\_\\_____/_____|_| \\_|\n\n\n"
                + "                                \n" + "   \n" + "                              \n" + "\n"
                + "\n" + "\n " + "\n", options);
    }

}

From source file:com.genentech.application.property.SDFCalculate.java

public static void main(String args[]) {
    String usage = "java SDFCalculate [options] <list of space separated properties>\n";

    Options options = new Options();
    // add  options
    options.addOption("TPSA_P", false, "Count phosphorus atoms, default is false. (optional)");
    options.addOption("TPSA_S", false, "Count sulfur atoms, default is false. (optional)");
    options.addOption("cLogP", true, "SDtag where cLogP is stored, default is cLogP (optional)");
    options.addOption("in", true, "inFile in OE formats: Ex: a.sdf or .sdf");
    options.addOption("out", true, "outputfile in OE formats. Ex: a.sdf or .sdf ");

    try {/*from   w  ww.  j  av a2s  .c  o m*/
        boolean countS = false;
        boolean countP = false;

        // append list of valid properties and their descriptions to the usage statement
        Iterator<Entry<String, String>> i = propsMap.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, String> me = i.next();
            usage = usage + me.getKey() + ":\t" + me.getValue() + "\n";
        }

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("TPSA_P"))
            countP = true;
        if (cmd.hasOption("TPSA_S"))
            countS = true;

        // get list of properties
        Vector<String> propsList = new Vector<String>(Arrays.asList(cmd.getArgs()));
        if (propsList.isEmpty()) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }
        //make sure list of requested pros are valid props
        for (String p : propsList) {
            if (!propsMap.containsKey(p)) {
                System.err.println(p + " is not a valid property.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(usage, options);
                System.exit(1);
            }
        }

        // get cLogP SD label tag option value
        String cLogPTag = "cLogP";

        if (cmd.hasOption("cLogP")) {
            cLogPTag = cmd.getOptionValue("cLogP");
        }

        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 filename = "smarts.xml";
        URL url = SDFCalculate.class.getResource(filename);
        Element root = XMLUtil.getRootElement(url, false);

        SDFCalculate test = new SDFCalculate(outFile, cLogPTag, countP, countS, root);
        test.calcProperties(inFile, propsList);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usage, options);
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cohesionforce.AvroToParquet.java

public static void main(String[] args) {

    String inputFile = null;//from ww  w  .  j  a va2s  . c  o  m
    String outputFile = null;

    HelpFormatter formatter = new HelpFormatter();
    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("i", true, "input avro file");
    options.addOption("o", true, "ouptut Parquet file");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        inputFile = cmd.getOptionValue("i");
        if (inputFile == null) {
            formatter.printHelp("AvroToParquet", options);
            return;
        }
        outputFile = cmd.getOptionValue("o");
    } catch (ParseException exc) {
        System.err.println("Problem with command line parameters: " + exc.getMessage());
        return;
    }

    File avroFile = new File(inputFile);

    if (!avroFile.exists()) {
        System.err.println("Could not open file: " + inputFile);
        return;
    }
    try {

        DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>();
        DataFileReader<GenericRecord> dataFileReader;
        dataFileReader = new DataFileReader<GenericRecord>(avroFile, datumReader);
        Schema avroSchema = dataFileReader.getSchema();

        // choose compression scheme
        CompressionCodecName compressionCodecName = CompressionCodecName.SNAPPY;

        // set Parquet file block size and page size values
        int blockSize = 256 * 1024 * 1024;
        int pageSize = 64 * 1024;

        String base = FilenameUtils.removeExtension(avroFile.getAbsolutePath()) + ".parquet";
        if (outputFile != null) {
            File file = new File(outputFile);
            base = file.getAbsolutePath();
        }

        Path outputPath = new Path("file:///" + base);

        // the ParquetWriter object that will consume Avro GenericRecords
        ParquetWriter<GenericRecord> parquetWriter;
        parquetWriter = new AvroParquetWriter<GenericRecord>(outputPath, avroSchema, compressionCodecName,
                blockSize, pageSize);
        for (GenericRecord record : dataFileReader) {
            parquetWriter.write(record);
        }
        dataFileReader.close();
        parquetWriter.close();
    } catch (IOException e) {
        System.err.println("Caught exception: " + e.getMessage());
    }
}

From source file:eu.annocultor.converter.Analyser.java

static public void main(String... args) throws Exception {
    // Handling command line parameters with Apache Commons CLI
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName(OPT_FN).hasArg().isRequired()
            .withDescription("XML file name to be analysed").withValueSeparator(',').create(OPT_FN));

    options.addOption(OptionBuilder.withArgName(OPT_MAX_VALUE_SIZE).hasArg().withDescription(
            "Maximal size when values are counted separately. Longer values are counted altogether. Reasonable values are 100, 300, etc.")
            .create(OPT_MAX_VALUE_SIZE));

    options.addOption(OptionBuilder.withArgName(OPT_VALUES).hasArg().withDescription(
            "Maximal number of most frequent values displayed in the report. Reasonable values are 10, 25, 50")
            .create(OPT_VALUES));//ww w.j av  a 2  s  . c  o m

    // now lets parse the input
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, Utils.getCommandLineFromANNOCULTOR_ARGS(args));
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("analyse", options);
        return;
    }

    MAX_VALUE_SIZE = Integer.parseInt(cmd.getOptionValue(OPT_MAX_VALUE_SIZE, Integer.toString(MAX_VALUE_SIZE)));
    MAX_VALUES = Integer.parseInt(cmd.getOptionValue(OPT_VALUES, Integer.toString(MAX_VALUES)));

    Analyser analyser = new Analyser(new EnvironmentImpl());

    // undo:
    /*
    analyser.task.setSrcFiles(new File("."), cmd.getOptionValue(OPT_FN));
            
    if (analyser.task.getSrcFiles().size() > 1)
    {
       analyser.task.mergeSourceFiles();
    }
            
    if (analyser.task.getSrcFiles().size() == 0)
    {
       throw new Exception("No files to analyze, pattern " + cmd.getOptionValue(OPT_FN));
    }
            
    File trg = new File(analyser.task.getSrcFiles().get(0).getParentFile(), "rdf");
    if (!trg.exists())
       trg.mkdir();
            
    System.out.println("[Analysis] Analysing files "
    + cmd.getOptionValue(OPT_FN)
    + ", writing analysis to "
    + trg.getCanonicalPath()
    + ", max value length (long values are aggregated into one 'long value' value) "
    + MAX_VALUE_SIZE
    + ", number most fequently used values per field shown in report "
    + MAX_VALUES);
     */
    if (true)
        throw new Exception("unimplemented");
    System.exit(analyser.run());
}