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

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

Introduction

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

Prototype

public static OptionBuilder hasArg() 

Source Link

Document

The next Option created will require an argument value.

Usage

From source file:net.sf.mcf2pdf.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option o = OptionBuilder.hasArg().isRequired()
            .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i');
    options.addOption(o);/*from w  ww  .  j av  a 2  s  . c o m*/
    options.addOption("h", false, "Prints this help and exits.");
    options.addOption("t", true, "Location of MCF temporary files.");
    options.addOption("w", true, "Location for temporary images generated during conversion.");
    options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150.");
    options.addOption("n", true, "Sets the page number to render up to. Default renders all pages.");
    options.addOption("b", false, "Prevents rendering of binding between double pages.");
    options.addOption("x", false, "Generates only XSL-FO content instead of PDF content.");
    options.addOption("q", false, "Quiet mode - only errors are logged.");
    options.addOption("d", false, "Enables debugging logging output.");

    CommandLine cl;
    try {
        CommandLineParser parser = new PosixParser();
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        printUsage(options, pe);
        System.exit(3);
        return;
    }

    if (cl.hasOption("h")) {
        printUsage(options, null);
        return;
    }

    if (cl.getArgs().length != 2) {
        printUsage(options,
                new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList()));
        System.exit(3);
        return;
    }

    File installDir = new File(cl.getOptionValue("i"));
    if (!installDir.isDirectory()) {
        printUsage(options, new ParseException("Specified installation directory does not exist."));
        System.exit(3);
        return;
    }

    File tempDir = null;
    String sTempDir = cl.getOptionValue("t");
    if (sTempDir == null) {
        tempDir = new File(new File(System.getProperty("user.home")), ".mcf");
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("MCF temporary location not specified and default location "
                    + tempDir + " does not exist."));
            System.exit(3);
            return;
        }
    } else {
        tempDir = new File(sTempDir);
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("Specified temporary location does not exist."));
            System.exit(3);
            return;
        }
    }

    File mcfFile = new File(cl.getArgs()[0]);
    if (!mcfFile.isFile()) {
        printUsage(options, new ParseException("MCF input file does not exist."));
        System.exit(3);
        return;
    }
    mcfFile = mcfFile.getAbsoluteFile();

    File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf");
    if (cl.hasOption("w")) {
        tempImages = new File(cl.getOptionValue("w"));
        if (!tempImages.mkdirs() && !tempImages.isDirectory()) {
            printUsage(options,
                    new ParseException("Specified working dir does not exist and could not be created."));
            System.exit(3);
            return;
        }
    }

    int dpi = 150;
    if (cl.hasOption("r")) {
        try {
            dpi = Integer.valueOf(cl.getOptionValue("r")).intValue();
            if (dpi < 30 || dpi > 600)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options,
                    new ParseException("Parameter for option -r must be an integer between 30 and 600."));
        }
    }

    int maxPageNo = -1;
    if (cl.hasOption("n")) {
        try {
            maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue();
            if (maxPageNo < 0)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0."));
        }
    }

    boolean binding = true;
    if (cl.hasOption("b")) {
        binding = false;
    }

    OutputStream finalOut;
    if (cl.getArgs()[1].equals("-"))
        finalOut = System.out;
    else {
        try {
            finalOut = new FileOutputStream(cl.getArgs()[1]);
        } catch (IOException e) {
            printUsage(options, new ParseException("Output file could not be created."));
            System.exit(3);
            return;
        }
    }

    // configure logging, if no system property is present
    if (System.getProperty("log4j.configuration") == null) {
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties"));

        Logger.getRootLogger().setLevel(Level.INFO);
        if (cl.hasOption("q"))
            Logger.getRootLogger().setLevel(Level.ERROR);
        if (cl.hasOption("d"))
            Logger.getRootLogger().setLevel(Level.DEBUG);
    }

    // start conversion to XSL-FO
    // if -x is specified, this is the only thing we do
    OutputStream xslFoOut;
    if (cl.hasOption("x"))
        xslFoOut = finalOut;
    else
        xslFoOut = new ByteArrayOutputStream();

    Log log = LogFactory.getLog(Main.class);

    try {
        new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding,
                maxPageNo);
        xslFoOut.flush();

        if (!cl.hasOption("x")) {
            // convert to PDF
            log.debug("Converting XSL-FO data to PDF");
            byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray();
            PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi);
            finalOut.flush();
        }
    } catch (Exception e) {
        log.error("An exception has occured", e);
        System.exit(1);
        return;
    } finally {
        if (finalOut instanceof FileOutputStream) {
            try {
                finalOut.close();
            } catch (Exception e) {
            }
        }
    }
}

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

/**
 * main entry point/*from  ww  w .j av a 2  s  .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:edu.harvard.med.screensaver.io.libraries.LibraryCreator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    CommandLineApplication app = new CommandLineApplication(args);
    try {/*from ww  w  .  j  a v  a2 s  . c om*/
        DateTimeFormatter dateFormat = DateTimeFormat.forPattern(CommandLineApplication.DEFAULT_DATE_PATTERN);

        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("library name")
                .withLongOpt("name").withDescription("full, official name for the library").create("n"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("short name").withLongOpt("short-name")
                        .withDescription("a short name for identifying the library").create("s"));
        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("library type")
                .withLongOpt("library-type").withDescription(StringUtils.makeListString(Lists.transform(
                        Lists.newArrayList(LibraryType.values()), new Function<LibraryType, String>() {
                            @Override
                            public String apply(LibraryType arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .create("lt"));
        app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("screen type")
                .withLongOpt("screen-type").withDescription(StringUtils.makeListString(Lists
                        .transform(Lists.newArrayList(ScreenType.values()), new Function<ScreenType, String>() {
                            @Override
                            public String apply(ScreenType arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .create("st"));
        app.addCommandLineOption(OptionBuilder.hasArg(false).withLongOpt("is-pool")
                .withDescription("well contents are pools of reagents (only valid when library-type=RNAI)")
                .create("ip"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("start-plate").create("sp"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("end-plate").create("ep"));

        app.addCommandLineOption(
                OptionBuilder.hasArg().withArgName("name").withLongOpt("provider").create("lp"));
        app.addCommandLineOption(
                OptionBuilder.hasArg().withArgName("text").withLongOpt("description").create("d"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName(CommandLineApplication.DEFAULT_DATE_PATTERN)
                .withLongOpt("date-received").create("dr"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName(CommandLineApplication.DEFAULT_DATE_PATTERN)
                .withLongOpt("date-screenable").create("ds"));
        app.addCommandLineOption(OptionBuilder.hasArg().withArgName("plate size")
                .withDescription(StringUtils.makeListString(Lists
                        .transform(Lists.newArrayList(PlateSize.values()), new Function<PlateSize, String>() {
                            @Override
                            public String apply(PlateSize arg0) {
                                return arg0.name();
                            }
                        }), ", "))
                .withLongOpt("plate-size").create("ps"));

        app.processOptions(true, true);

        String libraryName = app.getCommandLineOptionValue("n");
        String shortName = app.getCommandLineOptionValue("s");
        LibraryType libraryType = app.getCommandLineOptionEnumValue("lt", LibraryType.class);
        boolean isPool = app.isCommandLineFlagSet("ip");
        ScreenType screenType = app.getCommandLineOptionEnumValue("st", ScreenType.class);
        int startPlate = app.getCommandLineOptionValue("sp", Integer.class);
        int endPlate = app.getCommandLineOptionValue("ep", Integer.class);
        String vendor = app.isCommandLineFlagSet("lp") ? app.getCommandLineOptionValue("lp") : null;
        String description = app.isCommandLineFlagSet("d") ? app.getCommandLineOptionValue("d") : null;
        LocalDate dateReceived = app.isCommandLineFlagSet("dr")
                ? app.getCommandLineOptionValue("dr", dateFormat).toLocalDate()
                : null;
        LocalDate dateScreenable = app.isCommandLineFlagSet("ds")
                ? app.getCommandLineOptionValue("ds", dateFormat).toLocalDate()
                : null;
        PlateSize plateSize = app.isCommandLineFlagSet("ps")
                ? app.getCommandLineOptionEnumValue("ps", PlateSize.class)
                : ScreensaverConstants.DEFAULT_PLATE_SIZE;

        Library library = new Library(app.findAdministratorUser(), libraryName, shortName, screenType,
                libraryType, startPlate, endPlate, plateSize);
        library.setPool(isPool);
        library.setDescription(description);
        library.setProvider(vendor);
        library.setDateReceived(dateReceived);
        library.setDateScreenable(dateScreenable);

        edu.harvard.med.screensaver.service.libraries.LibraryCreator libraryCreator = (edu.harvard.med.screensaver.service.libraries.LibraryCreator) app
                .getSpringBean("libraryCreator");
        libraryCreator.createLibrary(library);
        log.info("library succesfully added to database");
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e.toString());
        System.err.println("error: " + e.getMessage());
        System.exit(1);
    }
}

From source file:edu.harvard.med.screensaver.io.screens.ScreenCreator.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws ParseException {
    final CommandLineApplication app = new CommandLineApplication(args);

    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("first name")
            .withLongOpt("lead-screener-first-name").create("lf"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("last name")
            .withLongOpt("lead-screener-last-name").create("ll"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("email")
            .withLongOpt("lead-screener-email").create("le"));

    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("first name")
            .withLongOpt("lab-head-first-name").create("hf"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("last name")
            .withLongOpt("lab-head-last-name").create("hl"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("email")
            .withLongOpt("lab-head-email").create("he"));

    List<String> desc = new ArrayList<String>();
    for (ScreenType t : EnumSet.allOf(ScreenType.class))
        desc.add(t.name());// ww  w. j av a 2 s  . c om
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("screen type")
            .withLongOpt("screen-type").withDescription(StringUtils.makeListString(desc, ", ")).create("st"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("summary").withLongOpt("summary").create("s"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("title").withLongOpt("title").create("t"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().withArgName("protocol").withLongOpt("protocol").create("p"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("facilityId").create("i"));
    app.addCommandLineOption(OptionBuilder.hasArg(false).withLongOpt("replace")
            .withDescription("replace an existing Screen with the same facilityId").create("r"));

    app.processOptions(/* acceptDatabaseOptions= */false, /* acceptAdminUserOptions= */true);

    try {
        execute(app);
    } catch (Exception e) {
        log.error("Failed to create the screen", e);
        System.exit(1);
    }

}

From source file:edu.harvard.med.screensaver.io.libraries.LibraryContentsLoader.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    CommandLineApplication application = new CommandLineApplication(args);
    application.addCommandLineOption(// w  ww.ja v a  2 s  .co  m
            OptionBuilder.hasArg().withArgName(LIBRARY_SHORT_NAME_OPTION[SHORT_OPTION_INDEX]).isRequired()
                    .withDescription(LIBRARY_SHORT_NAME_OPTION[DESCRIPTION_INDEX])
                    .withLongOpt(LIBRARY_SHORT_NAME_OPTION[LONG_OPTION_INDEX])
                    .create(LIBRARY_SHORT_NAME_OPTION[SHORT_OPTION_INDEX]));
    application.addCommandLineOption(OptionBuilder.hasArg().withArgName(INPUT_FILE_OPTION[SHORT_OPTION_INDEX])
            .isRequired().withDescription(INPUT_FILE_OPTION[DESCRIPTION_INDEX])
            .withLongOpt(INPUT_FILE_OPTION[LONG_OPTION_INDEX]).create(INPUT_FILE_OPTION[SHORT_OPTION_INDEX]));
    application.addCommandLineOption(
            OptionBuilder.isRequired(false).withDescription(RELEASE_IF_SUCCESS_OPTION[DESCRIPTION_INDEX])
                    .withLongOpt(RELEASE_IF_SUCCESS_OPTION[LONG_OPTION_INDEX])
                    .create(RELEASE_IF_SUCCESS_OPTION[SHORT_OPTION_INDEX]));

    application.processOptions(true, true);
    String libraryShortName = application
            .getCommandLineOptionValue(LIBRARY_SHORT_NAME_OPTION[SHORT_OPTION_INDEX]);
    File libraryContentsFile = application.getCommandLineOptionValue(INPUT_FILE_OPTION[SHORT_OPTION_INDEX],
            File.class);
    boolean releaseIfSuccess = application.isCommandLineFlagSet(RELEASE_IF_SUCCESS_OPTION[SHORT_OPTION_INDEX]);

    edu.harvard.med.screensaver.service.libraries.LibraryContentsLoader libraryContentsLoader = (edu.harvard.med.screensaver.service.libraries.LibraryContentsLoader) application
            .getSpringBean("libraryContentsLoader");
    edu.harvard.med.screensaver.service.libraries.LibraryContentsVersionManager libraryContentsVersionManager = (edu.harvard.med.screensaver.service.libraries.LibraryContentsVersionManager) application
            .getSpringBean("libraryContentsVersionManager");
    GenericEntityDAO dao = (GenericEntityDAO) application.getSpringBean("genericEntityDao");

    try {
        AdministratorUser admin = application.findAdministratorUser();
        Library library = dao.findEntityByProperty(Library.class, "shortName", libraryShortName);
        if (library == null) {
            throw new IllegalArgumentException("no library with short name: " + libraryShortName);
        }
        LibraryContentsVersion lcv = libraryContentsLoader.loadLibraryContents(library, admin, null /*TODO*/,
                new FileInputStream(libraryContentsFile));
        if (releaseIfSuccess) {
            log.info("releasing...");
            libraryContentsVersionManager.releaseLibraryContentsVersion(lcv, admin);
        }
    } catch (ParseErrorsException e) {
        for (ParseError error : e.getErrors()) {
            log.error(error.toString(), e);
        }
        System.exit(1);
    } catch (Exception e) {
        log.error("application exception", e);
        System.exit(1);
    }
}

From source file:com.kappaware.logtrawler.Main.java

@SuppressWarnings("static-access")
static public void main(String[] argv) throws Throwable {

    Config config;//from   w  w  w . j av a  2 s  .  com

    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("config-file")
            .withDescription("JSON configuration file").create("c"));
    options.addOption(OptionBuilder.hasArg().withArgName("folder").withLongOpt("folder")
            .withDescription("Folder to monitor").create("f"));
    options.addOption(OptionBuilder.hasArg().withArgName("exclusion").withLongOpt("exclusion")
            .withDescription("Exclusion regex").create("x"));
    options.addOption(OptionBuilder.hasArg().withArgName("adminEndpoint").withLongOpt("admin-endpoint")
            .withDescription("Endpoint for admin REST").create("e"));
    options.addOption(OptionBuilder.hasArg().withArgName("outputFlow").withLongOpt("output-flow")
            .withDescription("Target to post result on").create("o"));
    options.addOption(OptionBuilder.hasArg().withArgName("hostname").withLongOpt("hostname")
            .withDescription("This hostname").create("h"));
    options.addOption(OptionBuilder.withLongOpt("displayDot").withDescription("Display Dot").create("d"));
    options.addOption(OptionBuilder.hasArg().withArgName("mimeType").withLongOpt("mime-type")
            .withDescription("Valid MIME type").create("m"));
    options.addOption(OptionBuilder.hasArg().withArgName("allowedAdmin").withLongOpt("allowedAdmin")
            .withDescription("Allowed admin network").create("a"));
    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("gen-config-file")
            .withDescription("Generate JSON configuration file").create("g"));
    options.addOption(OptionBuilder.hasArg().withArgName("maxBatchSize").withLongOpt("max-batch-size")
            .withDescription("Max JSON batch (array) size").create("b"));

    CommandLineParser clParser = new BasicParser();
    CommandLine line;
    String configFile = null;
    try {
        // parse the command line argument
        line = clParser.parse(options, argv);
        if (line.hasOption("c")) {
            configFile = line.getOptionValue("c");
            config = Json.fromJson(Config.class,
                    new BufferedReader(new InputStreamReader(new FileInputStream(configFile))));
        } else {
            config = new Config();
        }
        if (line.hasOption("f")) {
            String[] fs = line.getOptionValues("f");
            // Get the first agent (Create it if needed)
            if (config.getAgents() == null || config.getAgents().size() == 0) {
                Config.Agent agent = new Config.Agent("default");
                config.addAgent(agent);
            }
            Config.Agent agent = config.getAgents().iterator().next();
            for (String f : fs) {
                agent.addFolder(new Config.Agent.Folder(f, false));
            }
        }
        if (line.hasOption("e")) {
            String e = line.getOptionValue("e");
            config.setAdminEndpoint(e);
        }
        if (line.hasOption("o")) {
            String[] es = line.getOptionValues("o");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    for (String s : es) {
                        agent.addOuputFlow(s);
                    }
                }
            }
        }
        if (line.hasOption("h")) {
            String e = line.getOptionValue("h");
            config.setHostname(e);
        }
        if (line.hasOption("x")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    if (agent.getFolders() != null) {
                        for (Folder folder : agent.getFolders()) {
                            String[] exs = line.getOptionValues("x");
                            for (String ex : exs) {
                                folder.addExcludedPath(ex);
                            }
                        }
                    }
                }
            }
        }
        if (line.hasOption("m")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    String[] exs = line.getOptionValues("m");
                    for (String ex : exs) {
                        agent.addLogMimeType(ex);
                    }
                }
            }
        }
        if (line.hasOption("a")) {
            String[] exs = line.getOptionValues("a");
            for (String ex : exs) {
                config.addAdminAllowedNetwork(ex);
            }
        }
        if (line.hasOption("d")) {
            config.setDisplayDot(true);
        }
        if (line.hasOption("b")) {
            Integer i = getIntegerParameter(line, "b");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    agent.setOutputMaxBatchSize(i);
                }
            }
        }
        config.setDefault();
        if (line.hasOption("g")) {
            String fileName = line.getOptionValue("g");
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
            out.println(Json.toJson(config, true));
            out.flush();
            out.close();
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        usage(options, exp.getMessage());
        return;
    }

    try {
        // Check config
        if (config.getAgents() == null || config.getAgents().size() < 1) {
            throw new ConfigurationException("At least one folder to monitor must be provided!");
        }
        Map<String, AgentHandler> agentHandlerByName = new HashMap<String, AgentHandler>();
        for (Config.Agent agent : config.getAgents()) {
            agentHandlerByName.put(agent.getName(), new AgentHandler(agent));
        }
        if (!Utils.isNullOrEmpty(config.getAdminEndpoint())) {
            new AdminServer(config, agentHandlerByName);
        }
    } catch (ConfigurationException e) {
        log.error(e.toString());
        System.exit(1);
    } catch (Throwable t) {
        log.error("Error in main", t);
        System.exit(2);
    }
}

From source file:edu.harvard.med.screensaver.io.libraries.WellDeprecator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    final CommandLineApplication app = new CommandLineApplication(args);
    app.addCommandLineOption(/*from   ww  w  .j  a v  a  2s . c o  m*/
            OptionBuilder.hasArg().isRequired().withArgName("admin user ID").withLongOpt("admin-approved-by")
                    .withDescription("user ID of administrator that approved this well deprecation activity")
                    .create("aa"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("yyyy-mm-dd").withLongOpt("approval-date")
                    .withDescription("date this well deprecation activity was approved").create("d"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("text").withLongOpt("comments").create("c"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("file").withLongOpt("input-file")
            .withDescription("workbook file containing list of wells to be deprecated").create("f"));
    app.processOptions(true, true);

    final GenericEntityDAO dao = (GenericEntityDAO) app.getSpringBean("genericEntityDao");

    dao.doInTransaction(new DAOTransaction() {
        public void runTransaction() {
            try {
                int size = updateWells(app, dao);
                System.out.println("WellDeprecator read in and added comments for " + size + " wells.");
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.toString());
                System.exit(1);
            }
        }
    });

}

From source file:edu.harvard.med.screensaver.io.screens.StudyCreator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    final CommandLineApplication app = new CommandLineApplication(args);

    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("first name")
            .withLongOpt("lead-screener-first-name").create("lf"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("last name")
            .withLongOpt("lead-screener-last-name").create("ll"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("email")
            .withLongOpt("lead-screener-email").create("le"));

    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("first name")
            .withLongOpt("lab-head-first-name").create("hf"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("last name")
            .withLongOpt("lab-head-last-name").create("hl"));
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("email")
            .withLongOpt("lab-head-email").create("he"));

    List<String> desc = new ArrayList<String>();
    for (ScreenType t : EnumSet.allOf(ScreenType.class))
        desc.add(t.name());//ww w  .  j a  va  2s  . co  m
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("screen type")
            .withLongOpt("screen-type").withDescription(StringUtils.makeListString(desc, ", ")).create("y"));
    desc.clear();
    for (StudyType t : EnumSet.allOf(StudyType.class))
        desc.add(t.name());
    app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName("study type")
            .withLongOpt("study-type").withDescription(StringUtils.makeListString(desc, ", ")).create("yy"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("summary").withLongOpt("summary").create("s"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("title").withLongOpt("title").create("t"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().withArgName("protocol").withLongOpt("protocol").create("p"));
    app.addCommandLineOption(
            OptionBuilder.hasArg().isRequired().withArgName("#").withLongOpt("facilityId").create("i"));
    app.addCommandLineOption(OptionBuilder.hasArg(false).withLongOpt("replace")
            .withDescription("replace an existing Screen with the same facilityId").create("r"));

    app.addCommandLineOption(OptionBuilder.withLongOpt("key-input-by-wellkey")
            .withDescription("default value is to key by reagent vendor id").create("keyByWellId"));
    app.addCommandLineOption(OptionBuilder.withLongOpt("key-input-by-facility-id")
            .withDescription("default value is to key by reagent vendor id").create("keyByFacilityId"));
    app.addCommandLineOption(OptionBuilder.withLongOpt("key-input-by-compound-name")
            .withDescription("default value is to key by reagent vendor id").create("keyByCompoundName"));
    app.addCommandLineOption(OptionBuilder.withDescription(
            "optional: pivot the input col/rows so that the AT names are in Col1, and the AT well_id/rvi's are in Row1")
            .withLongOpt("annotation-names-in-col1").create("annotationNamesInCol1"));
    app.addCommandLineOption(OptionBuilder.hasArg().withArgName("file").withLongOpt("data-file").create("f"));

    app.addCommandLineOption(OptionBuilder.withArgName("parseLincsSpecificFacilityID")
            .withLongOpt("parseLincsSpecificFacilityID").create("parseLincsSpecificFacilityID"));
    app.processOptions(/* acceptDatabaseOptions= */true, /* acceptAdminUserOptions= */true);
    execute(app);
}

From source file:eu.fbk.utils.twm.FormPageSearcher.java

public static void main(final String args[]) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "configuration/log-config.txt";
    }/*from   w w w  . ja  v  a  2 s .  c o m*/

    PropertyConfigurator.configure(logConfig);
    final Options options = new Options();
    try {
        OptionBuilder.withArgName("index");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("open an index with the specified name");
        OptionBuilder.isRequired();
        OptionBuilder.withLongOpt("index");
        final Option indexNameOpt = OptionBuilder.create("i");
        OptionBuilder.withArgName("interactive-mode");
        OptionBuilder.withDescription("enter in the interactive mode");
        OptionBuilder.withLongOpt("interactive-mode");
        final Option interactiveModeOpt = OptionBuilder.create("t");
        OptionBuilder.withArgName("search");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("search for the specified key");
        OptionBuilder.withLongOpt("search");
        final Option searchOpt = OptionBuilder.create("s");
        OptionBuilder.withArgName("key-freq");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription("read the keys' frequencies from the specified file");
        OptionBuilder.withLongOpt("key-freq");
        final Option freqFileOpt = OptionBuilder.create("f");
        OptionBuilder.withArgName("minimum-freq");
        // Option keyFieldNameOpt =
        // OptionBuilder.withArgName("key-field-name").hasArg().withDescription("use the specified name for the field key").withLongOpt("key-field-name").create("k");
        // Option valueFieldNameOpt =
        // OptionBuilder.withArgName("value-field-name").hasArg().withDescription("use the specified name for the field value").withLongOpt("value-field-name").create("v");
        final Option minimumKeyFreqOpt = OptionBuilder.hasArg()
                .withDescription("minimum key frequency of cached values (default is " + DEFAULT_MIN_FREQ + ")")
                .withLongOpt("minimum-freq").create("m");
        OptionBuilder.withArgName("int");
        final Option notificationPointOpt = OptionBuilder.hasArg()
                .withDescription(
                        "receive notification every n pages (default is " + DEFAULT_NOTIFICATION_POINT + ")")
                .withLongOpt("notification-point").create("b");
        options.addOption("h", "help", false, "print this message");
        options.addOption("v", "version", false, "output version information and exit");

        options.addOption(indexNameOpt);
        options.addOption(interactiveModeOpt);
        options.addOption(searchOpt);
        options.addOption(freqFileOpt);
        // options.addOption(keyFieldNameOpt);
        // options.addOption(valueFieldNameOpt);
        options.addOption(minimumKeyFreqOpt);
        options.addOption(notificationPointOpt);

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

        if (line.hasOption("help") || line.hasOption("version")) {
            throw new ParseException("");
        }

        int minFreq = DEFAULT_MIN_FREQ;
        if (line.hasOption("minimum-freq")) {
            minFreq = Integer.parseInt(line.getOptionValue("minimum-freq"));
        }

        int notificationPoint = DEFAULT_NOTIFICATION_POINT;
        if (line.hasOption("notification-point")) {
            notificationPoint = Integer.parseInt(line.getOptionValue("notification-point"));
        }

        final FormPageSearcher pageFormSearcher = new FormPageSearcher(line.getOptionValue("index"));
        pageFormSearcher.setNotificationPoint(notificationPoint);
        /*
         * logger.debug(line.getOptionValue("key-field-name") + "\t" +
         * line.getOptionValue("value-field-name")); if (line.hasOption("key-field-name")) {
         * pageFormSearcher.setKeyFieldName(line.getOptionValue("key-field-name")); } if
         * (line.hasOption("value-field-name")) {
         * pageFormSearcher.setValueFieldName(line.getOptionValue("value-field-name")); }
         */
        if (line.hasOption("key-freq")) {
            pageFormSearcher.loadCache(line.getOptionValue("key-freq"), minFreq);
        }
        if (line.hasOption("search")) {
            logger.debug("searching " + line.getOptionValue("search") + "...");
            final FreqSetSearcher.Entry[] result = pageFormSearcher.search(line.getOptionValue("search"));
            logger.info(Arrays.toString(result));
        }
        if (line.hasOption("interactive-mode")) {
            pageFormSearcher.interactive();
        }
    } catch (final ParseException e) {
        // oops, something went wrong
        if (e.getMessage().length() > 0) {
            System.out.println("Parsing failed: " + e.getMessage() + "\n");
        }
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(400,
                "java -cp dist/thewikimachine.jar org.fbk.cit.hlt.thewikimachine.index.FormPageSearcher", "\n",
                options, "\n", true);
    }
}

From source file:com.browseengine.bobo.index.MakeBobo.java

/**
 * @param args//  w w w  . j  a  v  a 2 s .  c  o  m
 */
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    Option help = new Option("help", false, "print this message");

    OptionBuilder.withArgName("path");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("data source - required");
    Option src = OptionBuilder.create("source");
    src.setRequired(true);

    OptionBuilder.withArgName("path");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("index to create - required");
    Option index = OptionBuilder.create("index");
    index.setRequired(true);

    OptionBuilder.withArgName("file");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("field configuration - optional");
    Option conf = OptionBuilder.create("conf");

    OptionBuilder.withArgName("class");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("class name of the data digester - default: xml digester");
    Option digesterOpt = OptionBuilder.create("digester");

    OptionBuilder.withArgName("name");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("character set name - default: UTF-8");
    Option charset = OptionBuilder.create("charset");

    OptionBuilder.withArgName("maxdocs");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("maximum number of documents - default: 100");
    Option maxdocs = OptionBuilder.create("maxdocs");

    Options options = new Options();
    options.addOption(help);
    options.addOption(conf);
    options.addOption(index);
    options.addOption(src);
    options.addOption(charset);
    options.addOption(digesterOpt);
    options.addOption(maxdocs);

    //       create the parser

    CommandLineParser parser = new BasicParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String output = line.getOptionValue("index");
        File data = new File(line.getOptionValue("source"));

        Class digesterClass;
        if (line.hasOption("digester"))
            digesterClass = Class.forName(line.getOptionValue("digester"));
        else
            throw new RuntimeException("digester not specified");

        Charset chset;
        if (line.hasOption("charset")) {
            chset = Charset.forName(line.getOptionValue("charset"));
        } else {
            chset = Charset.forName("UTF-8");
        }

        int maxDocs;
        try {
            maxDocs = Integer.parseInt(line.getOptionValue("maxdocs"));
        } catch (Exception e) {
            maxDocs = 100;
        }

        FileDigester digester;
        try {
            Constructor constructor = digesterClass.getConstructor(new Class[] { File.class });
            digester = (FileDigester) constructor.newInstance(new Object[] { data });
            digester.setCharset(chset);
            digester.setMaxDocs(maxDocs);
        } catch (Exception e) {
            throw new RuntimeException("Invalid digester class.", e);
        }

        BoboIndexer indexer = new BoboIndexer(digester, FSDirectory.open(new File(output)));
        indexer.index();
    } catch (ParseException exp) {
        exp.printStackTrace();
        usage(options);
    } catch (ClassNotFoundException e) {
        System.out.println("Invalid digester class.");
        usage(options);
    }
}