Example usage for org.apache.commons.cli OptionBuilder withLongOpt

List of usage examples for org.apache.commons.cli OptionBuilder withLongOpt

Introduction

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

Prototype

public static OptionBuilder withLongOpt(String newLongopt) 

Source Link

Document

The next Option created will have the following long option value.

Usage

From source file:de.peregrinus.autocopyreport.AutoCopyReport.java

public static void main(String[] args) {
    SongInfo si;//from ww  w.j  a  v  a 2s .c  o m

    String openlpPath = "";
    String crPath = "";
    String crDataPath = "";
    String crPassword = "";

    System.out.println("AutoCopyReport v.1.00.00");
    System.out.println("(c) 2014 Volksmission Freudenstadt");
    System.out.println("Author: Christoph Fischer <christoph.fischer@volksmission.de>");
    //System.out.println("Available under the General Public License (GPL) v2");
    System.out.println();

    // get options
    Options options = new Options();
    options.addOption("h", "help", false, "display a list of available options");
    options.addOption(OptionBuilder.withLongOpt("openlp-path").withDescription("path to OpenLP data directory")
            .hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-path")
            .withDescription("path to the CopyReport program directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-data-path")
            .withDescription("path to the CopyReport data directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("password")
            .withDescription("internal password for the CopyReport database").hasArg().withArgName("PASSWORD")
            .create());

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

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("AutoCopyReport", options);
            System.exit(0);
        } else {
            if (line.hasOption("openlp-path")) {
                openlpPath = line.getOptionValue("openlp-path") + "/songs/songs.sqlite";
                System.out.println("OpenLP data path: " + openlpPath);
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your OpenLP data folder by using the --openlp-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-path")) {
                crPath = line.getOptionValue("copyreport-path");
                System.out.println("Copyreport application database: " + crPath + "/ccldata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport program folder by using the --copyreport-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-data-path")) {
                crDataPath = line.getOptionValue("copyreport-data-path");
                System.out.println("Copyreport user database: " + crDataPath + "/userdata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport data folder by using the --copyreport-data-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("password")) {
                crPassword = line.getOptionValue("password");
            } else {
                System.out.println(
                        "ERROR: Please supply the internal password for the CopyReport database by using the --password parameter.");
                System.exit(0);
            }
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        System.exit(0);
    }

    SongDatabaseConnector sdb = new SongDatabaseConnector(openlpPath);
    SongRepository cdb = new SongRepository(crPath + "/ccldata", "sa", crPassword);

    CopyReport rpt = new CopyReport(crDataPath + "/userdata", "sa", crPassword);
    //rpt.createPeriod("2014");

    List<Song> songs = sdb.findLicensedSongs();
    for (Song song : songs) {
        System.out.println(song.title + ": " + song.ccliNumber);
        if (song.ccliNumber.matches("-?\\d+(\\.\\d+)?")) {
            si = cdb.findById(song.ccliNumber);
            if (si != null)
                rpt.reportSong(si);
        } else {
            System.out.println("Format error: '" + song.ccliNumber + "' is not numeric.");
        }
    }

    // wrap up: close the databases
    cdb.close();
    rpt.close();
    sdb.close();

}

From source file:RedPenRunner.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", "version", false, "print the version information and exit");

    OptionBuilder.withLongOpt("port");
    OptionBuilder.withDescription("port number");
    OptionBuilder.hasArg();//from w  w w .  j a va 2  s. c o  m
    OptionBuilder.withArgName("PORT");
    options.addOption(OptionBuilder.create("p"));

    OptionBuilder.withLongOpt("key");
    OptionBuilder.withDescription("stop key");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("STOP_KEY");
    options.addOption(OptionBuilder.create("k"));

    OptionBuilder.withLongOpt("conf");
    OptionBuilder.withDescription("configuration file");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("CONFIG_FILE");
    options.addOption(OptionBuilder.create("c"));

    OptionBuilder.withLongOpt("lang");
    OptionBuilder.withDescription("Language of error messages");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("LANGUAGE");
    options.addOption(OptionBuilder.create("L"));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(options);
        System.exit(-1);
    }

    int portNum = 8080;
    String language = "en";
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    if (commandLine.hasOption("v")) {
        System.out.println(RedPen.VERSION);
        System.exit(0);
    }
    if (commandLine.hasOption("p")) {
        portNum = Integer.parseInt(commandLine.getOptionValue("p"));
    }
    if (commandLine.hasOption("L")) {
        language = commandLine.getOptionValue("L");
    }
    if (isPortTaken(portNum)) {
        System.err.println("port is taken...");
        System.exit(1);
    }

    // set language
    if (language.equals("ja")) {
        Locale.setDefault(new Locale("ja", "JA"));
    } else {
        Locale.setDefault(new Locale("en", "EN"));
    }

    final String contextPath = System.getProperty("redpen.home", "/");

    Server server = new Server(portNum);
    ProtectionDomain domain = RedPenRunner.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    HandlerList handlerList = new HandlerList();
    if (commandLine.hasOption("key")) {
        // Add Shutdown handler only when STOP_KEY is specified
        ShutdownHandler shutdownHandler = new ShutdownHandler(commandLine.getOptionValue("key"));
        handlerList.addHandler(shutdownHandler);
    }

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    if (location.toExternalForm().endsWith("redpen-server/target/classes/")) {
        // use redpen-server/target/redpen-server instead, because target/classes doesn't contain web resources.
        webapp.setWar(location.toExternalForm() + "../redpen-server/");
    } else {
        webapp.setWar(location.toExternalForm());
    }
    if (commandLine.hasOption("c")) {
        webapp.setInitParameter("redpen.conf.path", commandLine.getOptionValue("c"));
    }

    handlerList.addHandler(webapp);
    server.setHandler(handlerList);

    server.start();
    server.join();
}

From source file:com.hurence.logisland.runner.SparkJobLauncher.java

/**
 * main entry point/*from ww  w. ja v a 2 s . co m*/
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName(AGENT);
    OptionBuilder.withLongOpt("agent-quorum");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option agent = OptionBuilder.create(AGENT);
    options.addOption(agent);

    OptionBuilder.withArgName(JOB);
    OptionBuilder.withLongOpt("job-name");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("logisland agent quorum like host1:8081,host2:8081");
    Option job = OptionBuilder.create(JOB);
    options.addOption(job);

    String logisland = "                      \n"
            + "     ????????   ?????     ??  ??\n"
            + "                    \n"
            + "             ????     ??  \n"
            + "??     ?\n"
            + "??????? ??????  ??????   ??????????????????  ????  ??????????   v0.10.0-SNAPSHOT\n\n\n";

    System.out.println(logisland);
    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String agentQuorum = line.getOptionValue(AGENT);
        String jobName = line.getOptionValue(JOB);

        // instanciate engine and all the processor from the config
        engineInstance = new RestComponentFactory(agentQuorum).getEngineContext(jobName);
        assert engineInstance.isPresent();
        assert engineInstance.get().isValid();

        logger.info("starting Logisland session version {}", engineInstance.get());
    } catch (Exception e) {
        logger.error("unable to launch runner : {}", e.toString());
    }

    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        engineInstance.get().getEngine().start(engineContext);
    } catch (Exception e) {
        logger.error("something went bad while running the job : {}", e);
        System.exit(-1);
    }

}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());// w ww  . ja  v a2  s  .  co m
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:cd.what.DutchBot.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException, IrcException, InterruptedException,
        ConfigurationException, InstantiationException, IllegalAccessException {
    String configfile = "irc.properties";
    DutchBot bot = null;//w w  w.  j  a  v  a 2  s. co  m

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("config").withArgName("configfile").hasArg()
            .withDescription("Load configuration from configfile, or use the default irc.cfg").create("c"));
    options.addOption(OptionBuilder.withLongOpt("server").withArgName("<url>").hasArg()
            .withDescription("Connect to this server").create("s"));
    options.addOption(OptionBuilder.withLongOpt("port").hasArg().withArgName("port")
            .withDescription("Connect to the server with this port").create("p"));
    options.addOption(OptionBuilder.withLongOpt("password").hasArg().withArgName("password")
            .withDescription("Connect to the server with this password").create("pw"));
    options.addOption(OptionBuilder.withLongOpt("nick").hasArg().withArgName("nickname")
            .withDescription("Connect to the server with this nickname").create("n"));
    options.addOption(OptionBuilder.withLongOpt("nspass").hasArg().withArgName("password")
            .withDescription("Sets the password for NickServ").create("ns"));
    options.addOption("h", "help", false, "Displays this menu");

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cli = parser.parse(options, args);
        if (cli.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("DutchBot", options);
            return;
        }
        // check for override config file
        if (cli.hasOption("c"))
            configfile = cli.getOptionValue("c");

        bot = new DutchBot(configfile);

        // Read the cli parameters
        if (cli.hasOption("pw"))
            bot.setServerPassword(cli.getOptionValue("pw"));
        if (cli.hasOption("s"))
            bot.setServerAddress(cli.getOptionValue("s"));
        if (cli.hasOption("p"))
            bot.setIrcPort(Integer.parseInt(cli.getOptionValue("p")));
        if (cli.hasOption("n"))
            bot.setBotName(cli.getOptionValue("n"));
        if (cli.hasOption("ns"))
            bot.setNickservPassword(cli.getOptionValue("ns"));

    } catch (ParseException e) {
        System.err.println("Error parsing command line vars " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DutchBot", options);
        System.exit(1);
    }

    boolean result = bot.tryConnect();

    if (result)
        bot.logMessage("Connected");
    else {
        System.out.println(" Connecting failed :O");
        System.exit(1);
    }
}

From source file:com.hurence.logisland.runner.StreamProcessingRunner.java

/**
 * main entry point/*from   www.j av  a 2s  .  c  o  m*/
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName("conf");
    OptionBuilder.withLongOpt("config-file");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("config file path");
    Option conf = OptionBuilder.create("conf");
    options.addOption(conf);

    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        System.out.println(BannerLoader.loadBanner());

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String configFile = line.getOptionValue("conf");

        // load the YAML config
        LogislandConfiguration sessionConf = ConfigReader.loadConfig(configFile);

        // instantiate engine and all the processor from the config
        engineInstance = ComponentFactory.getEngineContext(sessionConf.getEngine());
        if (!engineInstance.isPresent()) {
            throw new IllegalArgumentException("engineInstance could not be instantiated");
        }
        if (!engineInstance.get().isValid()) {
            throw new IllegalArgumentException("engineInstance is not valid with input configuration !");
        }
        logger.info("starting Logisland session version {}", sessionConf.getVersion());
        logger.info(sessionConf.getDocumentation());
    } catch (Exception e) {
        logger.error("unable to launch runner", e);
        System.exit(-1);
    }
    String engineName = engineInstance.get().getEngine().getIdentifier();
    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        logger.info("start engine {}", engineName);
        engineInstance.get().getEngine().start(engineContext);
        logger.info("awaitTermination for engine {}", engineName);
        engineContext.getEngine().awaitTermination(engineContext);
        System.exit(0);
    } catch (Exception e) {
        logger.error("something went bad while running the job {} : {}", engineName, e);
        System.exit(-1);
    }

}

From source file:com.cloudera.impala.testutil.SentryServicePinger.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    // Parse command line options to get config file path.
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("config_file")
            .withDescription("Absolute path to a sentry-site.xml config file (string)").hasArg()
            .withArgName("CONFIG_FILE").isRequired().create('c'));
    options.addOption(OptionBuilder.withLongOpt("num_pings")
            .withDescription("Max number of pings to try before failing (int)").hasArg().isRequired()
            .withArgName("NUM_PINGS").create('n'));
    options.addOption(//  w w w  .j ava2  s. c  om
            OptionBuilder.withLongOpt("sleep_secs").withDescription("Time (s) to sleep between pings (int)")
                    .hasArg().withArgName("SLEEP_SECS").create('s'));
    BasicParser optionParser = new BasicParser();
    CommandLine cmdArgs = optionParser.parse(options, args);

    SentryConfig sentryConfig = new SentryConfig(cmdArgs.getOptionValue("config_file"));
    int numPings = Integer.parseInt(cmdArgs.getOptionValue("num_pings"));
    int maxPings = numPings;
    int sleepSecs = Integer.parseInt(cmdArgs.getOptionValue("sleep_secs"));

    sentryConfig.loadConfig();
    while (numPings > 0) {
        SentryPolicyService policyService = new SentryPolicyService(sentryConfig);
        try {
            policyService.listAllRoles(new User(System.getProperty("user.name")));
            LOG.info("Sentry Service ping succeeded.");
            System.exit(0);
        } catch (Exception e) {
            LOG.error(String.format("Error issing RPC to Sentry Service (attempt %d/%d): ",
                    maxPings - numPings + 1, maxPings), e);
            Thread.sleep(sleepSecs * 1000);
        }
        --numPings;
    }
    System.exit(1);
}

From source file:com.sanaldiyar.projects.nanohttpd.nanoinstaller.App.java

public static void main(String[] args) {
    try {//from ww w .  jav a2s .  c  o  m
        String executableName = new File(
                App.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
        Options options = new Options();

        Option destination = OptionBuilder.withArgName("folder").withLongOpt("destination").hasArgs(1)
                .withDescription("destionation folder").withType(String.class).create("d");

        Option lrfolder = OptionBuilder.withArgName("folder").withLongOpt("localrepo").hasArgs(1)
                .withDescription("local repository folder").withType(String.class).create("lr");

        Option rmlrfolder = OptionBuilder.withLongOpt("deletelocalrepo").hasArg(false)
                .withDescription("delete local repository after installation").create("dlr");

        Option help = OptionBuilder.withLongOpt("help").withDescription("print this help").create("h");

        options.addOption(destination);
        options.addOption(lrfolder);
        options.addOption(rmlrfolder);
        options.addOption(help);

        HelpFormatter helpFormatter = new HelpFormatter();

        CommandLineParser commandLineParser = new PosixParser();
        CommandLine commands;
        try {
            commands = commandLineParser.parse(options, args);
        } catch (ParseException ex) {
            System.out.println("Error at parsing arguments");
            helpFormatter.printHelp("java -jar " + executableName, options);
            return;
        }

        if (commands.hasOption("h")) {
            helpFormatter.printHelp("java -jar " + executableName, options);
            return;
        }

        String sdest = commands.getOptionValue("d", "./nanosystem");
        System.out.println("The nano system will be installed into " + sdest);
        File dest = new File(sdest);
        if (dest.exists()) {
            FileUtils.deleteDirectory(dest);
        }
        dest.mkdirs();
        File bin = new File(dest, "bin");
        bin.mkdir();
        File bundle = new File(dest, "bundle");
        bundle.mkdir();
        File conf = new File(dest, "conf");
        conf.mkdir();
        File core = new File(dest, "core");
        core.mkdir();
        File logs = new File(dest, "logs");
        logs.mkdir();
        File nanohttpdcore = new File(dest, "nanohttpd-core");
        nanohttpdcore.mkdir();
        File nanohttpdservices = new File(dest, "nanohttpd-services");
        nanohttpdservices.mkdir();
        File temp = new File(dest, "temp");
        temp.mkdir();
        File apps = new File(dest, "apps");
        apps.mkdir();

        File local = new File(commands.getOptionValue("lr", "./local-repository"));
        Collection<RemoteRepository> repositories = Arrays.asList(
                new RemoteRepository("sanaldiyar-snap", "default", "http://maven2.sanaldiyar.com/snap-repo"),
                new RemoteRepository("central", "default", "http://repo1.maven.org/maven2/"));
        Aether aether = new Aether(repositories, local);

        //Copy core felix main
        System.out.println("Downloading Felix main executable");
        List<Artifact> felixmain = aether.resolve(
                new DefaultArtifact("org.apache.felix", "org.apache.felix.main", "jar", "LATEST"), "runtime");
        for (Artifact artifact : felixmain) {
            if (artifact.getArtifactId().equals("org.apache.felix.main")) {
                FileUtils.copyFile(artifact.getFile(), new File(bin, "felix-main.jar"));
                System.out.println(artifact.getArtifactId());
                break;
            }
        }
        System.out.println("OK");

        //Copy core felix bundles
        System.out.println("Downloading Felix core bundles");
        Collection<String> felixcorebundles = Arrays.asList("fileinstall", "bundlerepository", "gogo.runtime",
                "gogo.shell", "gogo.command");
        for (String felixcorebunlde : felixcorebundles) {
            List<Artifact> felixcore = aether.resolve(new DefaultArtifact("org.apache.felix",
                    "org.apache.felix." + felixcorebunlde, "jar", "LATEST"), "runtime");
            for (Artifact artifact : felixcore) {
                if (artifact.getArtifactId().equals("org.apache.felix." + felixcorebunlde)) {
                    FileUtils.copyFileToDirectory(artifact.getFile(), core);
                    System.out.println(artifact.getArtifactId());
                }
            }
        }
        System.out.println("OK");

        //Copy nanohttpd core bundles
        System.out.println("Downloading nanohttpd core bundles and configurations");
        List<Artifact> nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "nanohttpd", "jar", "LATEST"),
                "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            if (!artifact.getArtifactId().equals("org.osgi.core")) {
                FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
                System.out.println(artifact.getArtifactId());
            }
        }

        nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("com.sanaldiyar.projects", "engender", "jar", "LATEST"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("org.codehaus.jackson", "jackson-mapper-asl", "jar", "1.9.5"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        nanohttpdcorebundle = aether
                .resolve(new DefaultArtifact("org.mongodb", "mongo-java-driver", "jar", "LATEST"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        //Copy nanohttpd conf
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/nanohttpd.conf"),
                new File(dest, "nanohttpd.conf"));
        System.out.println("Configuration: nanohttpd.conf");

        //Copy nanohttpd start script
        File startsh = new File(dest, "start.sh");
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/start.sh"), startsh);
        startsh.setExecutable(true);
        System.out.println("Script: start.sh");

        System.out.println("OK");

        //Copy nanohttpd service bundles
        System.out.println("Downloading nanohttpd service bundles");
        List<Artifact> nanohttpdservicebundle = aether
                .resolve(new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "mongodbbasedsessionhandler",
                        "jar", "1.0-SNAPSHOT"), "runtime");
        for (Artifact artifact : nanohttpdservicebundle) {
            if (artifact.getArtifactId().equals("mongodbbasedsessionhandler")) {
                FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdservices);
                System.out.println(artifact.getArtifactId());
                break;
            }
        }

        //Copy nanohttpd mongodbbasedsessionhandler conf
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/mdbbasedsh.conf"),
                new File(dest, "mdbbasedsh.conf"));
        System.out.println("Configuration: mdbbasedsh.conf");

        System.out.println("OK");

        if (commands.hasOption("dlr")) {
            System.out.println("Local repository is deleting");
            FileUtils.deleteDirectory(local);
            System.out.println("OK");
        }

        System.out.println("You can reconfigure nanohttpd and services. To start system run start.sh script");

    } catch (Exception ex) {
        System.out.println("Error at installing.");
    }
}

From source file:edu.scripps.fl.pubchem.app.CIDDownloader.java

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

    CommandLineHandler clh = new CommandLineHandler() {
        public void configureOptions(Options options) {
            options.addOption(OptionBuilder.withLongOpt("input_file").withType("").withValueSeparator('=')
                    .hasArg().create());
            options.addOption(OptionBuilder.withLongOpt("output_file").withType("").withValueSeparator('=')
                    .hasArg().isRequired().create());
        }//from   www.  ja v a 2  s .  c o m
    };
    args = clh.handle(args);
    String inputFile = clh.getCommandLine().getOptionValue("input_file");
    String outputFile = clh.getCommandLine().getOptionValue("output_file");

    fetcher.setOutputFile(outputFile);
    Iterator<?> iterator;
    if (null == inputFile) {
        if (args.length == 0) {
            log.info("Running query to find CIDs in PCAssayResult but not in PCCompound");
            SQLQuery query = PubChemDB.getSession().createSQLQuery(
                    "select distinct r.cid from pcassay_result r left join pccompound c on r.cid = c.cid where (r.cid is not null and r.cid > 0 ) and c.cid is null order by r.cid");
            ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
            iterator = new ScrollableResultsIterator<Integer>(Integer.class, scroll);
        } else {
            iterator = Arrays.asList(args).iterator();
        }
    } else if ("-".equals(inputFile)) {
        log.info("Reading CIDs (one per line) from STDIN");
        iterator = new LineIterator(new InputStreamReader(System.in));
    } else {
        log.info("Reading CIDs (one per line) from " + inputFile);
        iterator = new LineIterator(new FileReader(inputFile));
    }
    fetcher.process(iterator);
    System.exit(0);
}

From source file:edu.scripps.fl.pubchem.app.AssayDownloader.java

public static void main(String[] args) throws Exception {
    CommandLineHandler clh = new CommandLineHandler() {
        public void configureOptions(Options options) {
            options.addOption(OptionBuilder.withLongOpt("data_url").withType("").withValueSeparator('=')
                    .hasArg().create());
            options.addOption(//  www.j a va 2s  .c o  m
                    OptionBuilder.withLongOpt("days").withType(0).withValueSeparator('=').hasArg().create());
            options.addOption(OptionBuilder.withLongOpt("mlpcn").withType(false).create());
            options.addOption(OptionBuilder.withLongOpt("notInDb").withType(false).create());
        }
    };
    args = clh.handle(args);
    String data_url = clh.getCommandLine().getOptionValue("data_url");
    if (null == data_url)
        data_url = "ftp://ftp.ncbi.nlm.nih.gov/pubchem/Bioassay/CSV/";
    //         data_url = "file:///C:/Home/temp/PubChemFTP/";

    AssayDownloader main = new AssayDownloader();
    main.dataUrl = new URL(data_url);

    if (clh.getCommandLine().hasOption("days"))
        main.days = Integer.parseInt(clh.getCommandLine().getOptionValue("days"));
    if (clh.getCommandLine().hasOption("mlpcn"))
        main.mlpcn = true;
    if (clh.getCommandLine().hasOption("notInDb"))
        main.notInDb = true;

    if (args.length == 0)
        main.process();
    else {
        Long[] list = (Long[]) ConvertUtils.convert(args, Long[].class);
        List<Long> l = (List<Long>) Arrays.asList(list);
        log.info("AID to process: " + l);
        main.process(new HashSet<Long>(Arrays.asList(list)));
    }
}