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

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

Introduction

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

Prototype

Options

Source Link

Usage

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);/* w w  w  .  j av  a2  s .  c om*/
    inputOpt.setRequired(true);

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

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryGrabats.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<ClassDeclaration> list = JavaQueries.grabats09(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiCreator.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);//from  ww  w.j av a 2 s. com
    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(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

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

    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 = XmiCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.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.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        targetResource.unload();

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:io.github.gsteckman.doorcontroller.INA219Util.java

/**
 * Reads the Current from the INA219 with an I2C address and for a duration specified on the command line.
 * /*  ww w  .ja v  a2 s .  c o  m*/
 * @param args
 *            Command line arguments.
 * @throws IOException
 *             If an error occurs reading/writing to the INA219
 * @throws ParseException
 *             If the command line arguments could not be parsed.
 */
public static void main(String[] args) throws IOException, ParseException {
    Options options = new Options();
    options.addOption("addr", true, "I2C Address");
    options.addOption("d", true, "Acquisition duration, in seconds");
    options.addOption("bv", false, "Also read bus voltage");
    options.addOption("sv", false, "Also read shunt voltage");

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

    Address addr = Address.ADDR_40;
    if (cmd.hasOption("addr")) {
        int opt = Integer.parseInt(cmd.getOptionValue("addr"), 16);
        Address a = Address.getAddress(opt);
        if (a != null) {
            addr = a;
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("INA219Util", options);
            return;
        }
    }

    int duration = 0;
    if (cmd.hasOption("d")) {
        String opt = cmd.getOptionValue("d");
        duration = Integer.parseInt(opt);
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("INA219Util", options);
        return;

    }

    boolean readBusVoltage = false;
    if (cmd.hasOption("bv")) {
        readBusVoltage = true;
    }

    boolean readShuntVoltage = false;
    if (cmd.hasOption("sv")) {
        readShuntVoltage = true;
    }

    INA219 i219 = new INA219(addr, 0.1, 3.2, INA219.Brng.V16, INA219.Pga.GAIN_8, INA219.Adc.BITS_12,
            INA219.Adc.SAMPLES_128);

    System.out.printf("Time\tCurrent");
    if (readBusVoltage) {
        System.out.printf("\tBus");
    }
    if (readShuntVoltage) {
        System.out.printf("\tShunt");
    }
    System.out.printf("\n");
    long start = System.currentTimeMillis();
    do {
        try {
            System.out.printf("%d\t%f", System.currentTimeMillis() - start, i219.getCurrent());
            if (readBusVoltage) {
                System.out.printf("\t%f", i219.getBusVoltage());
            }
            if (readShuntVoltage) {
                System.out.printf("\t%f", i219.getShuntVoltage());
            }
            System.out.printf("\n");
            Thread.sleep(100);
        } catch (IOException e) {
            LOG.error("Exception while reading I2C bus", e);
        } catch (InterruptedException e) {
            break;
        }
    } while (System.currentTimeMillis() - start < duration * 1000);
}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args// w ww . j av  a  2s  .c om
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:dhtaccess.tools.Get.java

public static void main(String[] args) {
    boolean details = false;

    // parse properties
    Properties prop = System.getProperties();
    String gateway = prop.getProperty("dhtaccess.gateway");
    if (gateway == null || gateway.length() <= 0) {
        gateway = DEFAULT_GATEWAY;/* w w w.  j a v  a2 s .co  m*/
    }

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt");
    options.addOption("d", "details", false, "print secret hash and TTL");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    optVal = cmd.getOptionValue('g');
    if (optVal != null) {
        gateway = optVal;
    }
    if (cmd.hasOption('d')) {
        details = true;
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 1) {
        usage(COMMAND);
        System.exit(1);
    }

    // prepare for RPC
    DHTAccessor accessor = null;
    try {
        accessor = new DHTAccessor(gateway);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    for (int index = 0; index < args.length; index++) {
        byte[] key = null;
        try {
            key = args[index].getBytes(ENCODE);
        } catch (UnsupportedEncodingException e1) {
            // NOTREACHED
        }

        // RPC
        if (args.length > 1) {
            System.out.println(args[index] + ":");
        }

        if (details) {
            Set<DetailedGetResult> results = accessor.getDetails(key);

            for (DetailedGetResult r : results) {
                String valString = null;
                try {
                    valString = new String((byte[]) r.getValue(), ENCODE);
                } catch (UnsupportedEncodingException e) {
                    // NOTREACHED
                }

                BigInteger hashedSecure = new BigInteger(1, (byte[]) r.getHashedSecret());

                System.out.println(valString + " " + r.getTTL() + " " + r.getHashType() + " 0x"
                        + ("0000000" + hashedSecure.toString(16)).substring(0, 8));
            }
        } else {
            Set<byte[]> results = accessor.get(key);

            for (byte[] valBytes : results) {
                try {
                    System.out.println(new String((byte[]) valBytes, ENCODE));
                } catch (UnsupportedEncodingException e) {
                    // NOTREACHED
                }
            }
        }
    } // for (int index = 0...
}

From source file:net.bican.wordpress.Main.java

/**
 * @param args execute with "-?" for an explanation of args
 * @throws ParseException When the command line options cannot be parsed
 *///ww  w  . ja v a 2s .  c o  m
public static void main(String[] args) throws ParseException {
    try {
        Options options = new Options();
        options.addOption("?", "help", false, "Print usage information");
        options.addOption("h", "url", true, "Specify the url to xmlrpc.php");
        options.addOption("u", "user", true, "User name");
        options.addOption("p", "pass", true, "Password");
        options.addOption("a", "authors", false, "Get author list");
        options.addOption("s", "slug", true, "Slug for categories");
        options.addOption("pi", "parentid", true, "Parent id for categories");
        options.addOption("oi", "postid", true, "Post id for pages and posts");
        options.addOption("c", "categories", false, "Get category list");
        options.addOption("cn", "newcategory", true, "New category (uses --slug and --parentid)");
        options.addOption("pg", "pages", false, "Get page list (full)");
        options.addOption("pl", "pagelist", false, "Get page list");
        options.addOption("ps", "page", true, "Get page");
        options.addOption("pn", "newpage", true, "New page from file <arg> (needs --publish)");
        options.addOption("pe", "editpage", true, "Edit page (needs --postid and --publish");
        options.addOption("pd", "deletepage", true, "Delete page (needs --publish)");
        options.addOption("l", "publish", true, "Publish status for \"new\" options");
        options.addOption("us", "userinfo", false, "Get user information");
        options.addOption("or", "recentposts", true, "Get recent posts");
        options.addOption("os", "getpost", true, "Get post");
        options.addOption("on", "newpost", true, "New post from file <arg> (needs --publish)");
        options.addOption("oe", "editpost", true, "Edit post (needs --postid and --publish");
        options.addOption("od", "deletepost", true, "Delete post (needs --publish)");
        options.addOption("sm", "supportedmethods", false, "List supported methods");
        options.addOption("st", "supportedfilters", false, "List supported text filters");
        options.addOption("mn", "newmedia", true, "New media file (uses --overwrite)");
        options.addOption("ov", "overwrite", false, "Allow overwrite in uploading new media");
        options.addOption("so", "supportedstatus", false, "Print supported page and post status values");
        options.addOption("cs", "commentstatus", false, "Print comment status names for the blog");
        options.addOption("cc", "commentcount", true, "Get comment count for a post (-1 for all posts)");
        options.addOption("ca", "newcomment", true, "New comment from file");
        options.addOption("cd", "deletecomment", true, "Delete comment");
        options.addOption("ce", "editcomment", true, "Edit comment from file");
        options.addOption("cg", "getcomment", true, "Get comment");
        options.addOption("ct", "getcomments", true, "Get comments for the post");
        options.addOption("cs", "commentstatus", true, "Comment status (for --getcomments)");
        options.addOption("co", "commentoffset", true, "Comment offset # (for --getcomments)");
        options.addOption("cm", "commentnumber", true, "Comment # (for --getcomments)");
        try {
            WpCliConfiguration config = new WpCliConfiguration(args, options, Main.class);
            if (config.hasOption("help")) {
                showHelp(options);
            } else if ((!config.hasOption("url")) || (!config.hasOption("user"))
                    || (!config.hasOption("pass"))) {
                System.err.println("Specify --user, --pass and --url");
            } else {
                try {
                    Wordpress wp = new Wordpress(config.getOptionValue("user"), config.getOptionValue("pass"),
                            config.getOptionValue("url"));
                    if (config.hasOption("authors")) {
                        printList(wp.getAuthors(), Author.class, true);
                    } else if (config.hasOption("categories")) {
                        printList(wp.getCategories(), Category.class, true);
                    } else if (config.hasOption("newcategory")) {
                        String slug = config.getOptionValue("slug");
                        Integer parentId = getInteger("parentid", config);
                        if (slug == null)
                            slug = "";
                        if (parentId == null)
                            parentId = 0;
                        System.out
                                .println(wp.newCategory(config.getOptionValue("newcategory"), slug, parentId));
                    } else if (config.hasOption("pages")) {
                        printList(wp.getPages(), Page.class, false);
                    } else if (config.hasOption("pagelist")) {
                        printList(wp.getPageList(), PageDefinition.class, false);
                    } else if (config.hasOption("page")) {
                        printItem(wp.getPage(getInteger("page", config)), Page.class);
                    } else if (config.hasOption("userinfo")) {
                        printItem(wp.getUserInfo(), User.class);
                    } else if (config.hasOption("recentposts")) {
                        printList(wp.getRecentPosts(getInteger("recentposts", config)), Page.class, false);
                    } else if (config.hasOption("getpost")) {
                        printItem(wp.getPost(getInteger("getpost", config)), Page.class);
                    } else if (config.hasOption("supportedmethods")) {
                        printList(wp.supportedMethods(), String.class, false);
                    } else if (config.hasOption("supportedfilters")) {
                        printList(wp.supportedTextFilters(), String.class, false);
                    } else if (config.hasOption("newpage")) {
                        if (!config.hasOption("publish")) {
                            showHelp(options);
                        } else {
                            System.out.println(
                                    wp.newPage(Page.fromFile(new File(config.getOptionValue("newpage"))),
                                            config.getOptionValue("publish")));
                        }
                    } else if (config.hasOption("editpage")) {
                        edit(options, config, wp, "editpage", true);
                    } else if (config.hasOption("editpost")) {
                        edit(options, config, wp, "editpost", false);
                    } else if (config.hasOption("deletepage")) {
                        delete(options, config, wp, "deletepage", true);
                    } else if (config.hasOption("deletepost")) {
                        delete(options, config, wp, "deletepost", false);
                    } else if (config.hasOption("newpost")) {
                        if (!config.hasOption("publish")) {
                            showHelp(options);
                        } else {
                            System.out.println(
                                    wp.newPost(Page.fromFile(new File(config.getOptionValue("newpost"))),
                                            Boolean.valueOf(config.getOptionValue("publish"))));
                        }
                    } else if (config.hasOption("newmedia")) {
                        String fileName = config.getOptionValue("newmedia");
                        File file = new File(fileName);
                        String mimeType = new MimetypesFileTypeMap().getContentType(file);
                        Boolean overwrite = Boolean.FALSE;
                        if (config.hasOption("overwrite"))
                            overwrite = Boolean.TRUE;
                        MediaObject result = wp.newMediaObject(mimeType, file, overwrite);
                        if (result != null) {
                            System.out.println(result);
                        }
                    } else if (config.hasOption("supportedstatus")) {
                        System.out.println("Recognized status values for posts:");
                        printList(wp.getPostStatusList(), PostAndPageStatus.class, true);
                        System.out.println("\nRecognized status values for pages:");
                        printList(wp.getPageStatusList(), PostAndPageStatus.class, true);
                    } else if (config.hasOption("commentstatus")) {
                        showCommentStatus(wp);
                    } else if (config.hasOption("commentcount")) {
                        showCommentCount(config, wp);
                    } else if (config.hasOption("newcomment")) {
                        editComment(wp, config.getOptionValue("newcomment"), "newcomment");
                    } else if (config.hasOption("editcomment")) {
                        editComment(wp, config.getOptionValue("editcomment"), "editcomment");
                    } else if (config.hasOption("deletecomment")) {
                        System.err.println(Integer.valueOf(config.getOptionValue("deletecomment")));
                        deleteComment(wp, Integer.valueOf(config.getOptionValue("deletecomment")));
                    } else if (config.hasOption("getcomment")) {
                        printComment(wp, Integer.valueOf(config.getOptionValue("getcomment")));
                    } else if (config.hasOption("getcomments")) {
                        Integer postID = Integer.valueOf(config.getOptionValue("getcomments"));
                        String commentStatus = config.getOptionValue("commentstatus");
                        Integer commentOffset;
                        try {
                            commentOffset = Integer.valueOf(config.getOptionValue("commentoffset"));
                        } catch (NumberFormatException e) {
                            commentOffset = null;
                        }
                        Integer commentNumber;
                        try {
                            commentNumber = Integer.valueOf(config.getOptionValue("commentnumber"));
                        } catch (Exception e) {
                            commentNumber = null;
                        }
                        printComments(wp, postID, commentStatus, commentOffset, commentNumber);
                    } else {
                        showHelp(options);
                    }
                } catch (MalformedURLException e) {
                    System.err.println("URL \"" + config.getOptionValue("url") + "\" is invalid, reason is: "
                            + e.getLocalizedMessage());
                } catch (IOException e) {
                    System.err.println("Can't read from file, reason is: " + e.getLocalizedMessage());
                } catch (InvalidPostFormatException e) {
                    System.err.println("Input format is invalid.");
                }
            }
        } catch (ParseException e) {
            System.err.println("Can't process command line arguments, reason is: " + e.getLocalizedMessage());
        }
    } catch (XmlRpcFault e) {
        String reason = e.getLocalizedMessage();
        System.err.println("Operation failed, reason is: " + reason);
    }
}

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

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

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

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

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQuery.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsList(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result (list) contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsLoop(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result (loops) contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:gov.lanl.adore.djatoka.DjatokaExtract.java

/**
 * Uses apache commons cli to parse input args. Passes parsed
 * parameters to IExtract implementation.
 * @param args command line parameters to defined input,output,etc.
 *//*www  .  j a  v  a 2s  .c  o  m*/
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", "input", true, "Filepath of the input file.");
    options.addOption("o", "output", true, "Filepath of the output file.");
    options.addOption("l", "level", true, "Resolution level to extract.");
    options.addOption("d", "reduce", true, "Resolution levels to subtract from max resolution.");
    options.addOption("r", "region", true, "Format: Y,X,H,W. ");
    options.addOption("c", "cLayer", true, "Compositing Layer Index.");
    options.addOption("s", "scale", true,
            "Format: Option 1. Define a long-side dimension (e.g. 96); Option 2. Define absolute w,h values (e.g. 1024,768); Option 3. Define a single dimension (e.g. 1024,0) with or without Level Parameter; Option 4. Use a single decimal scaling factor (e.g. 0.854)");
    options.addOption("t", "rotate", true, "Number of degrees to rotate image (i.e. 90, 180, 270).");
    options.addOption("f", "format", true,
            "Mimetype of the image format to be provided as response. Default: image/jpeg");
    options.addOption("a", "AltImpl", true, "Alternate IExtract Implemenation");

    try {
        if (args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gov.lanl.adore.djatoka.DjatokaExtract", options);
            System.exit(0);
        }

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String input = line.getOptionValue("i");
        String output = line.getOptionValue("o");

        DjatokaDecodeParam p = new DjatokaDecodeParam();
        String level = line.getOptionValue("l");
        if (level != null)
            p.setLevel(Integer.parseInt(level));
        String reduce = line.getOptionValue("d");
        if (level == null && reduce != null)
            p.setLevelReductionFactor(Integer.parseInt(reduce));
        String region = line.getOptionValue("r");
        if (region != null)
            p.setRegion(region);
        String cl = line.getOptionValue("c");
        if (cl != null) {
            int clayer = Integer.parseInt(cl);
            if (clayer > 0)
                p.setCompositingLayer(clayer);
        }
        String scale = line.getOptionValue("s");
        if (scale != null) {
            String[] v = scale.split(",");
            if (v.length == 1) {
                if (v[0].contains("."))
                    p.setScalingFactor(Double.parseDouble(v[0]));
                else {
                    int[] dims = new int[] { -1, Integer.parseInt(v[0]) };
                    p.setScalingDimensions(dims);
                }
            } else if (v.length == 2) {
                int[] dims = new int[] { Integer.parseInt(v[0]), Integer.parseInt(v[1]) };
                p.setScalingDimensions(dims);
            }
        }
        String rotate = line.getOptionValue("t");
        if (rotate != null)
            p.setRotationDegree(Integer.parseInt(rotate));
        String format = line.getOptionValue("f");
        if (format == null)
            format = "image/jpeg";
        String alt = line.getOptionValue("a");
        if (output == null)
            output = input + ".jpg";

        long x = System.currentTimeMillis();
        IExtract ex = new KduExtractExe();
        if (alt != null)
            ex = (IExtract) Class.forName(alt).newInstance();
        DjatokaExtractProcessor e = new DjatokaExtractProcessor(ex);
        e.extractImage(input, output, p, format);
        logger.info("Extraction Time: " + ((double) (System.currentTimeMillis() - x) / 1000) + " seconds");

    } catch (ParseException e) {
        logger.error("Parse exception:" + e.getMessage(), e);
    } catch (DjatokaException e) {
        logger.error("djatoka Extraction exception:" + e.getMessage(), e);
    } catch (InstantiationException e) {
        logger.error("Unable to initialize alternate implemenation:" + e.getMessage(), e);
    } catch (Exception e) {
        logger.error("Unexpected exception:" + e.getMessage(), e);
    }
}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);/*from  w  w w .j  ava  2s  .  com*/
    inputOpt.setRequired(true);

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

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryOrphanNonPrimitiveTypes.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<Type> list = JavaQueries.getOrphanNonPrimitivesTypes(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);/* ww  w.ja  va  2 s. co m*/
    inputOpt.setRequired(true);

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

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(repoOpt);

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

        Class<?> inClazz = CdoQueryUnusedMethodsList.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsList(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}