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

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

Introduction

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

Prototype

PosixParser

Source Link

Usage

From source file:com.addthis.bark.ZkCmdLine.java

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

    Options options = new Options();
    options.addOption("h", "help", false, "something helpful.");
    options.addOption("z", "zk", true, "zk servers,port");
    options.addOption("c", "chroot", true, "chroot");
    options.addOption("n", "znode", true, "znode");
    options.addOption("d", "dir", true, "directory root");
    options.addOption("p", "put-data", true, "directory root");
    // for copying
    options.addOption("", "to-zk", true, "zk servers,port");
    options.addOption("", "to-chroot", true, "chroot");
    options.addOption("", "to-znode", true, "znode");

    CommandLineParser parser = new PosixParser();
    CommandLine cmdline = null;//from  www . j av  a  2s . co  m
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(0);
    }

    HelpFormatter formatter = new HelpFormatter();
    if (cmdline.hasOption("help") || cmdline.getArgList().size() < 1) {
        System.out.println("commands: get jclean jcleanrecur kids grandkids");
        formatter.printHelp("ZkCmdLine", options);
        System.exit(0);
    }

    ZkCmdLine zkcl = new ZkCmdLine(cmdline);
    zkcl.runCmd((String) cmdline.getArgList().get(0));
}

From source file:de.huberlin.german.korpling.laudatioteitool.App.java

public static void main(String[] args) {
    Options opts = new Options()
            .addOption(new Option("merge", true,
                    messages.getString("MERGE CONTENT FROM INPUT DIRECTORY INTO ONE TEI HEADER")))
            .addOption(new Option("split", true,
                    messages.getString("SPLIT ONE TEI HEADER INTO SEVERAL HEADER FILES")))
            .addOption(new Option("validate", true, messages.getString("VALIDATE DIRECTORY OR FILE")))
            .addOption(new Option("config", true, messages.getString("CONFIG FILE LOCATION")))
            .addOption(new Option("schemecorpus", true, messages.getString("CORPUS SCHEME LOCATION")))
            .addOption(new Option("schemedoc", true, messages.getString("DOCUMENT SCHEME LOCATION")))
            .addOption(new Option("schemeprep", true, messages.getString("PREPARATION SCHEME LOCATION")))
            .addOption(new Option("help", false, messages.getString("SHOW THIS HELP")));

    HelpFormatter fmt = new HelpFormatter();
    String usage = "java -jar teitool.jar [options] [output directory/file]";
    String header = messages.getString("HELP HEADER");
    String footer = messages.getString("HELP FOOTER");

    try {//from   ww w .  j  a  v  a  2  s. co  m
        CommandLineParser cliParser = new PosixParser();

        CommandLine cmd = cliParser.parse(opts, args);

        Properties props = new Properties();
        if (cmd.hasOption("config")) {
            props = readConfig(cmd.getOptionValue("config"));
        } // end if "config" given
        fillPropertiesFromCommandLine(props, cmd);

        if (cmd.hasOption("help")) {
            fmt.printHelp(usage, header, opts, footer);
        } else if (cmd.hasOption("validate")) {
            validate(cmd.getOptionValue("validate"), props.getProperty("schemecorpus"),
                    props.getProperty("schemedoc"), props.getProperty("schemeprep"));
        } else if (cmd.hasOption("merge")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT FILE AS ARGUMENT"));
                System.exit(-1);
            }
            MergeTEI merge = new MergeTEI(new File(cmd.getOptionValue("merge")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            merge.merge();

            System.exit(0);
        } else if (cmd.hasOption("split")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT DIRECTORY AS ARGUMENT"));
                System.exit(-1);
            }
            SplitTEI split = new SplitTEI(new File(cmd.getOptionValue("split")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            split.split();
            System.exit(0);
        } else {
            fmt.printHelp(usage, header, opts, footer);
        }

    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        fmt.printHelp(usage, header, opts, footer);
    } catch (LaudatioException ex) {
        System.err.println(ex.getMessage());
    } catch (UnsupportedOperationException ex) {
        System.err.println(ex.getMessage());
    }

    System.exit(1);

}

From source file:edu.mit.lib.tools.Modernize.java

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

    // create an options object and populate it
    CommandLineParser parser = new PosixParser();

    Options options = new Options();

    options.addOption("i", "identifier", true, "root handle to migrate - 'all' for entire repo");
    options.addOption("t", "target", true, "URL of mds repository to import into");
    options.addOption("s", "scratch", true, "scratch directory for processing");
    options.addOption("m", "migrate", false,
            "export for migration (remove handle and metadata that will be re-created in new system)");
    options.addOption("h", "help", false, "help");

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

    if (line.hasOption('h')) {
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("Modernize\n", options);
        System.out.println(/*from w w w .  j  a  va 2  s  .  c o m*/
                "\nentire repository: Modernize -i all -t http://my-mds-repo.org/webapi -s /dspace/export");
        System.out.println(
                "\ncontent subtree: Modernize -i 123456789/1 -t http://my-mds-repo.org/webapi -s /dspace/export");
        System.exit(0);
    }

    String scratch = null;
    if (line.hasOption('s')) {
        scratch = line.getOptionValue('s');
        if (scratch == null) {
            System.out.println("Scratch directory required!");
            System.exit(1);
        }
    }

    Modernize mod = new Modernize(Paths.get(scratch));

    if (line.hasOption('i')) {
        String id = line.getOptionValue('i');
        if (id != null) {
            mod.exportIdentifier(id);
        } else {
            mod.bail("Must provide an identifer!");
        }
    }

    if (line.hasOption('t')) {
        String targetUrl = line.getOptionValue('t');
        if (targetUrl != null) {
            mod.importToMds(targetUrl);
        } else {
            mod.bail("Must provide an URL to an mds repository!");
        }
    }

    mod.finish();
}

From source file:com.opengamma.masterdb.batch.cmd.BatchRunner.java

public static void main(String[] args) throws Exception { // CSIGNORE
    if (args.length == 0) {
        usage();/*from ww  w. ja v a2  s  .com*/
        System.exit(-1);
    }

    CommandLine line = null;
    try {
        CommandLineParser parser = new PosixParser();
        line = parser.parse(getOptions(), args);
        initialize(line);
    } catch (ParseException e) {
        usage();
        System.exit(-1);
    }

    AbstractApplicationContext appContext = null;

    try {
        appContext = getApplicationContext();
        appContext.start();

        ViewProcessor viewProcessor = appContext.getBean("viewProcessor", ViewProcessor.class);

        ViewClient viewClient = viewProcessor.createViewClient(UserPrincipal.getLocalUser());
        MarketDataSpecification marketDataSpec = new FixedHistoricalMarketDataSpecification(
                s_observationDateTime.toLocalDate());
        ViewCycleExecutionOptions cycleOptions = ViewCycleExecutionOptions.builder()
                .setValuationTime(s_valuationInstant).setMarketDataSpecification(marketDataSpec)
                .setResolverVersionCorrection(VersionCorrection.of(s_versionAsOf, s_correctedTo)).create();
        ViewCycleExecutionSequence executionSequence = ArbitraryViewCycleExecutionSequence.of(cycleOptions);

        ExecutionOptions executionOptions = new ExecutionOptions(executionSequence,
                ExecutionFlags.none().awaitMarketData().get(), null, null);

        viewClient.attachToViewProcess(UniqueId.parse(s_viewDefinitionUid), executionOptions);
    } finally {
        if (appContext != null) {
            appContext.close();
        }
    }

    /*if (failed) {
      s_logger.error("Batch failed.");
      System.exit(-1);
    } else {
      s_logger.info("Batch succeeded.");
      System.exit(0);
    }*/
}

From source file:de.cwclan.cwsa.serverendpoint.main.ServerEndpoint.java

/**
 * @param args the command line arguments
 *///from  www  .  j  ava 2 s .  c  o m
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription(
            "Used to enter path of configfile. Default file is endpoint.properties. NOTE: If the file is empty or does not exsist, a default config is created.")
            .create("config"));
    options.addOption("h", "help", false, "displays this page");
    CommandLineParser parser = new PosixParser();
    Properties properties = new Properties();
    try {
        /*
         * parse default config shipped with jar
         */
        CommandLine cmd = parser.parse(options, args);

        /*
         * load default configuration
         */
        InputStream in = ServerEndpoint.class.getResourceAsStream("/endpoint.properties");
        if (in == null) {
            throw new IOException("Unable to load default config from JAR. This should not happen.");
        }
        properties.load(in);
        in.close();
        log.debug("Loaded default config base: {}", properties.toString());
        if (cmd.hasOption("help")) {
            printHelp(options);
            System.exit(0);
        }

        /*
         * parse cutom config if exists, otherwise create default cfg
         */
        if (cmd.hasOption("config")) {
            File file = new File(cmd.getOptionValue("config", "endpoint.properties"));
            if (file.exists() && file.canRead() && file.isFile()) {
                in = new FileInputStream(file);
                properties.load(in);
                log.debug("Loaded custom config from {}: {}", file.getAbsoluteFile(), properties);
            } else {
                log.warn("Config file does not exsist. A default file will be created.");
            }
            FileWriter out = new FileWriter(file);
            properties.store(out,
                    "Warning, this file is recreated on every startup to merge missing parameters.");
        }

        /*
         * create and start endpoint
         */
        log.info("Config read successfull. Values are: {}", properties);
        ServerEndpoint endpoint = new ServerEndpoint(properties);
        Runtime.getRuntime().addShutdownHook(endpoint.getShutdownHook());
        endpoint.start();
    } catch (IOException ex) {
        log.error("Error while reading config.", ex);
    } catch (ParseException ex) {
        log.error("Error while parsing commandline options: {}", ex.getMessage());
        printHelp(options);
        System.exit(1);
    }
}

From source file:com.fusesource.customer.wssec.client.Main.java

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

    try {/*from   www .j av  a2  s  .  co m*/
        CommandLine cli = new PosixParser().parse(opts, args);

        timestamp = cli.hasOption("timestamp");
        encrypt = cli.hasOption("encrypt");
        sign = cli.hasOption("sign");
        usernameToken = cli.hasOption("username-token");
        passwordDigest = cli.hasOption("password-digest");
        user = cli.getOptionValue("user");
        pw = cli.getOptionValue("pw");
        disableCNCheck = !cli.hasOption("ecnc");

        if (cli.hasOption("help") || !(sign | encrypt | usernameToken | timestamp)) {
            printUsageAndExit();
        }

        if (sign) {
            sigCertAlias = cli.getOptionValue("sa");
            sigCertPw = cli.getOptionValue("spw");
            sigKsLoc = cli.getOptionValue("sk");
            sigKsPw = cli.getOptionValue("skpw");

            if (sigCertAlias == null || sigKsLoc == null || sigKsPw == null || sigCertPw == null) {
                printUsageAndExit(
                        "You must provide keystore, keystore password, cert alias and cert password for signing certificate");
            }
        }

        if (encrypt) {
            encCertAlias = cli.getOptionValue("ea");
            encKsLoc = cli.getOptionValue("ek");
            encKsPw = cli.getOptionValue("ekpw");

            if (encCertAlias == null || encKsLoc == null || encKsPw == null) {
                printUsageAndExit(
                        "You must provide keystore, keystore password, and cert alias for encryption certificate");
            }
        }

    } catch (ParseException ex) {
        printUsageAndExit();
    }

    // Here we set the truststore for the client - by trusting the CA (in the 
    // truststore.jks file) we implicitly trust all services presenting certificates
    // signed by this CA.
    //
    System.setProperty("javax.net.ssl.trustStore", "../certs/truststore.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "truststore");

    URL wsdl = new URL("https://localhost:8443/cxf/Customers?wsdl");

    // The demo certs provided with this example configure the server with a certificate 
    // called 'fuse-esb'. As this probably won't match the fully-qualified domain
    // name of the machine you're running on, we need to disable Common Name matching
    // to allow the JVM runtime to happily resolve the WSDL for the server. Note that
    // we also have to do something similar on the CXf proxy itself (see below).
    //
    if (disableCNCheck) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        });
    }

    // Initialise the bus
    //
    Bus bus = SpringBusFactory.newInstance().createBus();
    SpringBusFactory.setDefaultBus(bus);

    // Define the properties to configure the WS Security Handler
    //
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(WSHandlerConstants.ACTION, getWSSecActions());

    // Specify the callback handler for passwords.
    //
    PasswordCallback passwords = new PasswordCallback();
    props.put(WSHandlerConstants.PW_CALLBACK_REF, passwords);

    if (usernameToken) {
        passwords.addUser(user, pw);
        props.put(WSHandlerConstants.USER, user);
        props.put(WSHandlerConstants.PASSWORD_TYPE, passwordDigest ? "PasswordDigest" : "PasswordText");
    }

    if (encrypt) {
        props.put(WSHandlerConstants.ENCRYPTION_USER, encCertAlias);
        props.put(WSHandlerConstants.ENC_PROP_REF_ID, "encProps");
        props.put("encProps", merlinCrypto(encKsLoc, encKsPw, encCertAlias));
        props.put(WSHandlerConstants.ENC_KEY_ID, "IssuerSerial");
        props.put(WSHandlerConstants.ENCRYPTION_PARTS, TIMESTAMP_AND_BODY);
    }

    if (sign) {
        props.put(WSHandlerConstants.SIGNATURE_USER, sigCertAlias);
        props.put(WSHandlerConstants.SIG_PROP_REF_ID, "sigProps");
        props.put("sigProps", merlinCrypto(sigKsLoc, sigKsPw, sigCertAlias));
        props.put(WSHandlerConstants.SIG_KEY_ID, "DirectReference");
        props.put(WSHandlerConstants.SIGNATURE_PARTS, TIMESTAMP_AND_BODY);

        passwords.addUser(sigCertAlias, sigCertPw);
    }

    // Here we add the WS Security interceptor to perform security processing
    // on the outgoing SOAP messages. Also, we configure a logging interceptor
    // to log the message payload for inspection. 
    //
    bus.getOutInterceptors().add(new WSS4JOutInterceptor(props));
    bus.getOutInterceptors().add(new LoggingOutInterceptor());

    CustomerService svc = new CustomerService_Service(wsdl).getPort(
            new QName("http://demo.fusesource.com/wsdl/CustomerService/", "SOAPOverHTTP"),
            CustomerService.class);

    // The demo certs provided with this example configure the server with a certificate 
    // called 'fuse-esb'. As this probably won't match the fully-qualified domain
    // name of the machine you're running on, we need to disable Common Name matching
    // to allow the CXF runtime to happily invoke on the server.
    //
    if (disableCNCheck) {
        HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(svc).getConduit();
        TLSClientParameters tls = new TLSClientParameters();
        tls.setDisableCNCheck(true);
        httpConduit.setTlsClientParameters(tls);
    }
    System.out.println("Looking up the customer...");

    // Here's the part where we invoke on the web service. 
    //
    Customer c = svc.lookupCustomer("007");

    System.out.println("Got customer " + c.getFirstName());

}

From source file:au.edu.flinders.ehl.filmweekly.FwImporter.java

/**
 * Main method for the class/*from www .ja va2 s.c o  m*/
 * 
 * @param args array of command line arguments
 */
public static void main(String[] args) {

    // before we do anything, output some useful information
    for (int i = 0; i < APP_HEADER.length; i++) {
        System.out.println(APP_HEADER[i]);
    }

    // parse the command line options
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(createOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        // something bad happened so output help message
        printCliHelp("Error in parsing options:\n" + e.getMessage());
    }

    // get and check on the log4j properties path option if required
    if (cmd.hasOption("log4j") == true) {
        String log4jPath = cmd.getOptionValue("log4j");
        if (FileUtils.isAccessible(log4jPath) == false) {
            printCliHelp("Unable to access the specified log4j properties file\n   " + log4jPath);
        }

        // configure the log4j framework
        PropertyConfigurator.configure(log4jPath);
    }

    // get and check on the properties path option
    String propertiesPath = cmd.getOptionValue("properties");
    if (FileUtils.isAccessible(propertiesPath) == false) {
        printCliHelp("Unable to access the specified properties file\n   " + propertiesPath);
    }

    // get and check on the input file path option
    String inputPath = cmd.getOptionValue("input");
    if (FileUtils.isAccessible(inputPath) == false) {
        printCliHelp("Unable to access the specified input file");
    }

    // open the properties file
    Configuration config = null;
    try {
        config = new PropertiesConfiguration(propertiesPath);
    } catch (ConfigurationException e) {
        printCliHelp("Unable to read the properties file file: \n" + e.getMessage());
    }

    // check to make sure all of the required configuration properties are present
    for (int i = 0; i < REQD_PROPERTIES.length; i++) {
        if (config.containsKey(REQD_PROPERTIES[i]) == false) {
            printCliHelp("Unable to find the required property: " + REQD_PROPERTIES[i]);
        }
    }

    if (cmd.hasOption("debug_coord_list") == true) {

        // output debug info
        logger.debug("undertaking the debug-coord-list task");

        // undertake the debug coordinate list task
        if (FileUtils.doesFileExist(cmd.getOptionValue("debug_coord_list")) == true) {
            printCliHelp("the debug_coord_list file already exists");
        } else {
            CoordList list = new CoordList(inputPath, cmd.getOptionValue("debug_coord_list"));

            try {
                list.openFiles();
                list.doTask();
            } catch (IOException e) {
                logger.error("unable to undertake the debug-coord-list task", e);
                errorExit();
            }

            System.out.println("Task completed");
            System.exit(0);
        }
    }

    if (cmd.hasOption("debug_json_list") == true) {

        // output debug info
        logger.debug("undertaking the debug-json-list task");

        // undertake the debug coordinate list task
        if (FileUtils.doesFileExist(cmd.getOptionValue("debug_json_list")) == true) {
            printCliHelp("the debug_json_list file already exists");
        } else {
            JsonList list = new JsonList(inputPath, cmd.getOptionValue("debug_json_list"));

            try {
                list.openFiles();
                list.doTask();
            } catch (IOException e) {
                logger.error("unable to undertake the debug_json_list task", e);
                errorExit();
            }

            System.out.println("Task completed");
            System.exit(0);
        }
    }

    // if no debug options present assume import
    System.out.println("Importing data into the database.");
    System.out.println(
            "*Note* if this input file has been processed before duplicate records *will* be created.");

    // get a connection to the database
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception e) {
        logger.error("unable to load the MySQL database classes", e);
        errorExit();
    }

    Connection database = null;

    //private static final String[] REQD_PROPERTIES = {"db-host", "db-user", "db-password", "db-name"};

    String connectionString = "jdbc:mysql://" + config.getString(REQD_PROPERTIES[0]) + "/"
            + config.getString(REQD_PROPERTIES[1]) + "?user=" + config.getString(REQD_PROPERTIES[2])
            + "&password=" + config.getString(REQD_PROPERTIES[3]);

    try {
        database = DriverManager.getConnection(connectionString);
    } catch (SQLException e) {
        logger.error("unable to connect to the MySQL database", e);
        errorExit();
    }

    // do the import
    DataImporter importer = new DataImporter(database, inputPath);

    try {
        importer.openFiles();
        importer.doTask();

        System.out.println("Task completed");
        System.exit(0);
    } catch (IOException e) {
        logger.error("unable to complete the import");
        errorExit();
    } catch (ImportException e) {
        logger.error("unable to complete the import");
        errorExit();
    } finally {
        // play nice and tidy up
        try {
            database.close();
        } catch (SQLException e) {
            logger.error("Unable to close the database connection: ", e);
        }

    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.Migrator.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);//w ww  .  j  av a  2  s . c  o m
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(IN_EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of input EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option outClassOpt = OptionBuilder.create(OUT_EPACKAGE_CLASS);
    outClassOpt.setArgName("CLASS");
    outClassOpt.setDescription("FQN of output EPackage implementation class");
    outClassOpt.setArgs(1);
    outClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(outputOpt);
    options.addOption(inClassOpt);
    options.addOption(outClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createFileURI(commandLine.getOptionValue(OUT));
        Class<?> inClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        Class<?> outClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(OUT_EPACKAGE_CLASS));

        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);
        EPackage outEPackage = (EPackage) outClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.getResource(sourceUri, true);
        Resource targetResource = resourceSet.createResource(targetUri);

        targetResource.getContents().clear();
        LOG.log(Level.INFO, "Start migration");
        targetResource.getContents()
                .add(MigratorUtil.migrate(sourceResource.getContents().get(0), outEPackage));
        LOG.log(Level.INFO, "Migration finished");

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        saveOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saving done");
    } catch (ParseException e) {
        showError(e.toString());
        showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        showError(e.toString());
    }
}

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;/*from w  w  w  .  j a v  a2 s .c  om*/
    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:gpframework.RunExperiment.java

/**
 * Application's entry point./*  w ww  .j  av  a  2s  . com*/
 * 
 * @param args
 * @throws ParseException
 * @throws ParameterException 
 */
public static void main(String[] args) throws ParseException, ParameterException {
    // Failsafe parameters
    if (args.length == 0) {
        args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf",
                "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP",
                "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" };
    }

    // Create options
    Options options = new Options();
    setupOptions(options);

    // Read options from the command line
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    // Print help if parameter requirements are not met
    try {
        cmd = parser.parse(options, args);
    }

    // If some parameters are missing, print help
    catch (MissingOptionException e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar GPFramework \n", options);
        System.out.println();
        System.out.println("Missing parameters: " + e.getMissingOptions());
        return;
    }

    // Re-initialize PRNG
    long seed = System.currentTimeMillis();
    Utils.random = new Random(seed);

    // Set the problem size
    int problemSize = Integer.parseInt(cmd.getOptionValue("n"));

    // Set debug mode and cluster mode
    Utils.debug = cmd.hasOption("d");
    RunExperiment.cluster = cmd.hasOption("c");

    // Initialize fitness function and some factories
    FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize);
    MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf"));
    Selection selectionCriterion = fromName(cmd.getOptionValue("s"));
    FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff"));
    TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize);
    ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory);

    // Initialize algorithm
    Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion);
    algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e"));
    algorithm.setParameter("timeBudget", cmd.getOptionValue("t"));

    // Initialize problem
    Problem problem = new Problem(programFactory, fitnessFunction);
    Program solution = algorithm.solve(problem);

    Utils.debug("Population results: ");
    Utils.debug(algorithm.getPopulation().toString());
    Utils.debug(algorithm.getPopulation().parse());

    Map<String, Object> entry = new HashMap<String, Object>();

    // Copy algorithm setup
    for (Object o : options.getRequiredOptions()) {
        Option option = options.getOption(o.toString());
        entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt()));
    }
    entry.put("seed", seed);

    // Copy results
    entry.put("bestProgram", solution.toString());
    entry.put("bestSolution", fitnessFunction.normalize(solution));

    // Copy all statistics
    entry.putAll(algorithm.getStatistics());

    Utils.debug("Maximum encountered population size: "
            + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront"));
    Utils.debug("Maximum encountered tree size: "
            + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront"));
    Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1));
}