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

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

Introduction

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

Prototype

HelpFormatter

Source Link

Usage

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//  www . j a  v  a 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);

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        String name = UUID.randomUUID().toString();
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            JavaQueries.renameAllMethods(resource, name);
            long end = System.currentTimeMillis();
            resource.save(Collections.emptyMap());
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.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:com.bytelightning.opensource.pokerface.PokerFaceApp.java

public static void main(String[] args) {
    if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) {
        System.err.println("PokerFace requires at least Java v8 to run.");
        return;//from w  ww .  j a  v a2s .c  o  m
    }
    // Configure the command line options parser
    Options options = new Options();
    options.addOption("h", false, "help");
    options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https.");
    options.addOption("keystore", true, "Filepath for PokerFace certificate keystore.");
    options.addOption("storepass", true, "The store password of the keystore.");
    options.addOption("keypass", true, "The key password of the keystore.");
    options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target
    options.addOption("servercpu", true, "Number of cores the server should use.");
    options.addOption("targetcpu", true, "Number of cores the http targets should use.");
    options.addOption("trustany", false, "Ignore certificate identity errors from target servers.");
    options.addOption("files", true, "Filepath to a directory of static files.");
    options.addOption("config", true, "Path for XML Configuration file.");
    options.addOption("scripts", true, "Filepath for root scripts directory.");
    options.addOption("library", true, "JavaScript library to load into global context.");
    options.addOption("watch", false, "Dynamically watch scripts directory for changes.");
    options.addOption("dynamicTargetScripting", false,
            "WARNING! This option allows scripts to redirect requests to *any* other remote server.");

    CommandLine cmdLine = null;
    // parse the command line.
    try {
        CommandLineParser parser = new PosixParser();
        cmdLine = parser.parse(options, args);
        if (args.length == 0 || cmdLine.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.setWidth(120);
            formatter.printHelp(PokerFaceApp.class.getSimpleName(), options);
            return;
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        return;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return;
    }

    XMLConfiguration config = new XMLConfiguration();
    try {
        if (cmdLine.hasOption("config")) {
            Path tmp = Utils.MakePath(cmdLine.getOptionValue("config"));
            if (!Files.exists(tmp))
                throw new FileNotFoundException("Configuration file does not exist.");
            if (Files.isDirectory(tmp))
                throw new FileNotFoundException("'config' path is not a file.");
            // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it.
            config.setEntityResolver(new DefaultEntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
                    InputSource retVal = super.resolveEntity(publicId, systemId);
                    if ((retVal == null) && (systemId != null)) {
                        try {
                            URL entityURL;
                            if (systemId.endsWith("/PokerFace_v1Config.xsd"))
                                entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd");
                            else
                                entityURL = new URL(systemId);
                            URLConnection connection = entityURL.openConnection();
                            connection.setUseCaches(false);
                            InputStream stream = connection.getInputStream();
                            retVal = new InputSource(stream);
                            retVal.setSystemId(entityURL.toExternalForm());
                        } catch (Throwable e) {
                            return retVal;
                        }
                    }
                    return retVal;
                }

            });
            config.setSchemaValidation(true);
            config.setURL(tmp.toUri().toURL());
            config.load();
            if (cmdLine.hasOption("listen"))
                System.out.println("IGNORING 'listen' option because a configuration file was supplied.");
            if (cmdLine.hasOption("target"))
                System.out.println("IGNORING 'target' option(s) because a configuration file was supplied.");
            if (cmdLine.hasOption("scripts"))
                System.out.println("IGNORING 'scripts' option because a configuration file was supplied.");
            if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option(s) because a configuration file was supplied.");
        } else {
            String[] serverStrs;
            String[] addr = { null };
            String[] port = { null };
            serverStrs = cmdLine.getOptionValues("listen");
            if (serverStrs == null)
                throw new MissingOptionException("No listening addresses specified specified");
            for (int i = 0; i < serverStrs.length; i++) {
                String addrStr;
                String alias = null;
                String protocol = null;
                Boolean https = null;
                int addrPos = serverStrs[i].indexOf('=');
                if (addrPos >= 0) {
                    if (addrPos < 2)
                        throw new IllegalArgumentException("Invalid http argument.");
                    else if (addrPos + 1 >= serverStrs[i].length())
                        throw new IllegalArgumentException("Invalid http argument.");
                    addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length());
                    String[] types = serverStrs[i].substring(0, addrPos).split(",");
                    for (String type : types) {
                        if (type.equalsIgnoreCase("http"))
                            break;
                        else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure"))
                            https = true;
                        else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl"))
                            protocol = type.toUpperCase();
                        else
                            alias = type;
                    }
                } else
                    addrStr = serverStrs[i];
                ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80);
                config.addProperty("server.listen(" + i + ")[@address]", addr[0]);
                config.addProperty("server.listen(" + i + ")[@port]", port[0]);
                if (alias != null)
                    config.addProperty("server.listen(" + i + ")[@alias]", alias);
                if (protocol != null)
                    config.addProperty("server.listen(" + i + ")[@protocol]", protocol);
                if (https != null)
                    config.addProperty("server.listen(" + i + ")[@secure]", https);
            }
            String servercpu = cmdLine.getOptionValue("servercpu");
            if (servercpu != null)
                config.setProperty("server[@cpu]", servercpu);
            String clientcpu = cmdLine.getOptionValue("targetcpu");
            if (clientcpu != null)
                config.setProperty("targets[@cpu]", clientcpu);

            // Configure static files
            if (cmdLine.hasOption("files")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("files"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Files directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'files' path is not a directory.");
                config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri());
            }

            // Configure scripting
            if (cmdLine.hasOption("scripts")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Scripts directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'scripts' path is not a directory.");
                config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri());
                config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch"));
                String[] libraries = cmdLine.getOptionValues("library");
                if (libraries != null) {
                    for (int i = 0; i < libraries.length; i++) {
                        Path lib = Utils.MakePath(libraries[i]);
                        if (!Files.exists(lib))
                            throw new FileNotFoundException(
                                    "Script library does not exist [" + libraries[i] + "].");
                        if (Files.isDirectory(lib))
                            throw new FileNotFoundException(
                                    "Script library is not a file [" + libraries[i] + "].");
                        config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri());
                    }
                }
            } else if (cmdLine.hasOption("watch"))
                System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified.");
            else if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option as no 'scripts' directory was specified.");
        }
        String keyStorePath = cmdLine.getOptionValue("keystore");
        if (keyStorePath != null)
            config.setProperty("keystore", keyStorePath);
        String keypass = cmdLine.getOptionValue("keypass");
        if (keypass != null)
            config.setProperty("keypass", keypass);
        String storepass = cmdLine.getOptionValue("storepass");
        if (storepass != null)
            config.setProperty("storepass", keypass);
        if (cmdLine.hasOption("trustany"))
            config.setProperty("targets[@trustAny]", true);

        config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting"));

        String[] targetStrs = cmdLine.getOptionValues("target");
        if (targetStrs != null) {
            for (int i = 0; i < targetStrs.length; i++) {
                int uriPos = targetStrs[i].indexOf('=');
                if (uriPos < 2)
                    throw new IllegalArgumentException("Invalid target argument.");
                else if (uriPos + 1 >= targetStrs[i].length())
                    throw new IllegalArgumentException("Invalid target argument.");
                String patternStr = targetStrs[i].substring(0, uriPos);
                String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length());
                String alias;
                try {
                    URL url = new URL(urlStr);
                    alias = url.getUserInfo();
                    String scheme = url.getProtocol();
                    if ((!"http".equals(scheme)) && (!"https".equals(scheme)))
                        throw new IllegalArgumentException("Invalid target uri scheme.");
                    int port = url.getPort();
                    if (port < 0)
                        port = url.getDefaultPort();
                    urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath();
                    String ref = url.getRef();
                    if (ref != null)
                        urlStr += "#" + ref;
                } catch (MalformedURLException ex) {
                    throw new IllegalArgumentException("Malformed target uri");
                }
                config.addProperty("targets.target(" + i + ")[@pattern]", patternStr);
                config.addProperty("targets.target(" + i + ")[@url]", urlStr);
                if (alias != null)
                    config.addProperty("targets.target(" + i + ")[@alias]", alias);
            }
        }
        //         config.save(System.out);
    } catch (Throwable e) {
        e.printStackTrace(System.err);
        return;
    }
    // If we get here, we have a possibly valid configuration.
    try {
        final PokerFace p = new PokerFace();
        p.config(config);
        if (p.start()) {
            PokerFace.Logger.warn("Started!");
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        PokerFace.Logger.warn("Initiating shutdown...");
                        p.stop();
                        PokerFace.Logger.warn("Shutdown completed!");
                    } catch (Throwable e) {
                        PokerFace.Logger.error("Failed to shutdown cleanly!");
                        e.printStackTrace(System.err);
                    }
                }
            });
        } else {
            PokerFace.Logger.error("Failed to start!");
            System.exit(-1);
        }
    } catch (Throwable e) {
        e.printStackTrace(System.err);
    }
}

From source file:DokeosConverter.java

public static void main(String[] arguments) throws Exception {
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);

    int port = SocketOpenOfficeConnection.DEFAULT_PORT;
    if (commandLine.hasOption(OPTION_PORT.getOpt())) {
        port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
    }//  w w w  .  j a  va 2s.  c  o m

    String outputFormat = null;
    if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
        outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
    }

    boolean verbose = false;
    if (commandLine.hasOption(OPTION_VERBOSE.getOpt())) {
        verbose = true;
    }

    String dokeosMode = "woogie";
    if (commandLine.hasOption(OPTION_DOKEOS_MODE.getOpt())) {
        dokeosMode = commandLine.getOptionValue(OPTION_DOKEOS_MODE.getOpt());
    }
    int width = 800;
    if (commandLine.hasOption(OPTION_WIDTH.getOpt())) {
        width = Integer.parseInt(commandLine.getOptionValue(OPTION_WIDTH.getOpt()));
    }

    int height = 600;
    if (commandLine.hasOption(OPTION_HEIGHT.getOpt())) {
        height = Integer.parseInt(commandLine.getOptionValue(OPTION_HEIGHT.getOpt()));
    }

    String[] fileNames = commandLine.getArgs();
    if ((outputFormat == null && fileNames.length != 2 && dokeosMode != null) || fileNames.length < 1) {
        String syntax = "convert [options] input-file output-file; or\n"
                + "[options] -f output-format input-file [input-file...]";
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(syntax, OPTIONS);
        System.exit(EXIT_CODE_TOO_FEW_ARGS);
    }

    OpenOfficeConnection connection = new DokeosSocketOfficeConnection(port);
    try {
        if (verbose) {
            System.out.println("-- connecting to OpenOffice.org on port " + port);
        }
        connection.connect();
    } catch (ConnectException officeNotRunning) {
        System.err.println(
                "ERROR: connection failed. Please make sure OpenOffice.org is running and listening on port "
                        + port + ".");
        System.exit(EXIT_CODE_CONNECTION_FAILED);
    }
    try {

        // choose the good constructor to deal with the conversion
        DocumentConverter converter;
        if (dokeosMode.equals("oogie")) {
            converter = new OogieDocumentConverter(connection, new DokeosDocumentFormatRegistry(), width,
                    height);
        } else if (dokeosMode.equals("woogie")) {
            converter = new WoogieDocumentConverter(connection, new DokeosDocumentFormatRegistry(), width,
                    height);
        } else {
            converter = new OpenOfficeDocumentConverter(connection);
        }

        if (outputFormat == null) {
            File inputFile = new File(fileNames[0]);
            File outputFile = new File(fileNames[1]);
            convertOne(converter, inputFile, outputFile, verbose);
        } else {
            for (int i = 0; i < fileNames.length; i++) {
                File inputFile = new File(fileNames[i]);
                File outputFile = new File(FilenameUtils.getFullPath(fileNames[i])
                        + FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat);
                convertOne(converter, inputFile, outputFile, verbose);
            }
        }
    } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
        connection.disconnect();
        System.err.println("ERROR: conversion failed.");
        System.exit(EXIT_CODE_CONVERSION_FAILED);
    } finally {
        if (verbose) {
            System.out.println("-- disconnecting");
        }
        connection.disconnect();
    }
}

From source file:com.ctriposs.rest4j.tools.idlgen.Rest4JResourceModelExporterCmdLineApp.java

/**
 * @param args rest4jexporter -sourcepath sourcepath -resourcepackages packagenames [-name api_name] [-outdir outdir]
 *//*from  w w  w.  ja v  a  2s.com*/
public static void main(String[] args) {
    //    args = new String[] {"-name", "groups",
    //                         "-resourcepackages", "com.ctriposs.groups.server.rest1.impl com.ctriposs.groups.server.rest2.impl ",
    //                         "-resourceclasses", "com.ctriposs.groups.server.restX.impl.FooResource",
    //                         "-sourcepath", "src/main/java",
    //                         "-outdir", "src/codegen/idl",
    //                         "-split"};

    CommandLine cl = null;
    try {
        final CommandLineParser parser = new GnuParser();
        cl = parser.parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println("Invalid arguments: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "rest4jexporter -sourcepath sourcepath [-resourcepackages packagenames] [-resourceclasses classnames]"
                        + "[-name api_name] [-outdir outdir]",
                OPTIONS);
        System.exit(0);
    }

    try {
        new Rest4JResourceModelExporter().export(cl.getOptionValue("name"), null,
                cl.getOptionValues("sourcepath"), cl.getOptionValues("resourcepackages"),
                cl.getOptionValues("resourceclasses"), cl.getOptionValue("outdir", "."));
    } catch (Throwable e) {
        log.error("Error writing IDL files", e);
        System.exit(1);
    }
}

From source file:com.ingby.socbox.bischeck.Execute.java

public static void main(String[] args) {

    // create the command line parser
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;/* w ww  . ja v a  2  s  .co  m*/

    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("d", "deamon", false, "start as a deamon");

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

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bischeck", options);
        Util.ShellExit(Util.FAILED);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bischeck", options);
        Util.ShellExit(Util.OKAY);
    }

    dumpthread = new Thread() {
        public void run() {
            try {
                CacheFactory.destroy();
            } catch (CacheException e) {
                LOGGER.warn("Cache could not be destoryed", e);
            }
        }
    };

    dumpthread.setName("dumpcache");

    int retStat = Util.OKAY;
    do {
        try {
            if (line.hasOption("deamon")) {
                ConfigurationManager.init();
            } else {
                ConfigurationManager.initonce();
            }
        } catch (Exception e) {
            LOGGER.error("Creating bischeck Configuration Manager failed with: {}", e.getMessage(), e);
            Util.ShellExit(Util.FAILED);
        }

        retStat = Execute.getInstance().deamon();
        LOGGER.debug("Method Execute returned {}", retStat);
    } while (retStat == RESTART);

    dumpthread.start();

    LOGGER.info("******************* Shutdown ********************");

    Util.ShellExit(retStat);
}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*from  w ww  . j a  v a 2s . 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);

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        {
            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)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.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:apps.quantification.QuantifySVMPerf.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = QuantifySVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <quantificationModelDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("d");
    OptionBuilder.withDescription("Dump confidences file");
    OptionBuilder.withLongOpt("d");
    OptionBuilder.isRequired(false);//from ww  w  .  jav a 2  s  .c om
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary files in svm_perf format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmPerfClassifierCustomizer customizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]);

        if (line.hasOption("v"))
            customizer.printSvmPerfOutput(true);

        if (line.hasOption("s")) {
            System.out.println("Keeping temporary files.");
            customizer.setDeleteTestFiles(false);
            customizer.setDeletePredictionsFiles(false);
        }

        if (line.hasOption("t"))
            customizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 3) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String quantifierFilename = remainingArgs[2];

    FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false);
    indexFssm.open();

    IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    indexFssm.close();

    FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false);
    quantifierFssm.open();

    SvmPerfDataManager classifierDataManager = new SvmPerfDataManager(customizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false);
    fssm.open();

    IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager,
            ClassificationMode.PER_CATEGORY);
    fssm.close();

    quantifierFssm.close();

    Quantification ccQuantification = quantifiers[0].quantify(test);
    Quantification paQuantification = quantifiers[1].quantify(test);
    Quantification accQuantification = quantifiers[2].quantify(test);
    Quantification maxQuantification = quantifiers[3].quantify(test);
    Quantification sccQuantification = quantifiers[4].quantify(test);
    Quantification spaQuantification = quantifiers[5].quantify(test);
    Quantification trueQuantification = new Quantification("True", test.getClassificationDB());

    File quantifierFile = new File(quantifierFilename);

    String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_"
            + quantifierFile.getName() + ".txt";

    BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName));
    IShortIterator iterator = test.getCategoryDB().getCategories();
    while (iterator.hasNext()) {
        short category = iterator.next();
        String prefix = quantifierFile.getName() + "\t" + indexName + "\t"
                + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t"
                + trueQuantification.getQuantification(category) + "\t";

        writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category)
                + "\n");
    }
    writer.close();

    BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator()
            + indexName + "_" + quantifierFile.getName() + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs();
    TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleTPRs();
    TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs();

    ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet();
    ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3])
            .getInternalQuantifier()).getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = test.getCategoryDB().getCategoryName(cat);
        ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat);
        ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double maxTPR = maxTPRs.get(cat);
        double maxFPR = maxFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat
                + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t"
                + simpleFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t"
                + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn()
                + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t"
                + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t"
                + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//from ww w. j ava 2 s .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);

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

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

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        {
            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)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.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:apps.quantification.QuantifySVMLight.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = QuantifySVMLight.class.getName()
            + " [OPTIONS] <path to svm_light_classify> <testIndexDirectory> <quantificationModelDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("d");
    OptionBuilder.withDescription("Dump confidences file");
    OptionBuilder.withLongOpt("d");
    OptionBuilder.isRequired(false);/*from   w  w w  .j a  va 2s  .com*/
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary files in svm_light format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmLightClassifierCustomizer customizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        customizer = new SvmLightClassifierCustomizer(remainingArgs[0]);

        if (line.hasOption("v"))
            customizer.printSvmLightOutput(true);

        if (line.hasOption("s")) {
            System.out.println("Keeping temporary files.");
            customizer.setDeleteTestFiles(false);
            customizer.setDeletePredictionsFiles(false);
        }

        if (line.hasOption("t"))
            customizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 3) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String quantifierFilename = remainingArgs[2];

    FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false);
    indexFssm.open();

    IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    indexFssm.close();

    FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false);
    quantifierFssm.open();

    SvmLightDataManager classifierDataManager = new SvmLightDataManager(customizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false);
    fssm.open();

    IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager,
            ClassificationMode.PER_CATEGORY);
    fssm.close();

    quantifierFssm.close();

    Quantification ccQuantification = quantifiers[0].quantify(test);
    Quantification paQuantification = quantifiers[1].quantify(test);
    Quantification accQuantification = quantifiers[2].quantify(test);
    Quantification maxQuantification = quantifiers[3].quantify(test);
    Quantification sccQuantification = quantifiers[4].quantify(test);
    Quantification spaQuantification = quantifiers[5].quantify(test);
    Quantification trueQuantification = new Quantification("True", test.getClassificationDB());

    File quantifierFile = new File(quantifierFilename);

    String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_"
            + quantifierFile.getName() + ".txt";

    BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName));
    IShortIterator iterator = test.getCategoryDB().getCategories();
    while (iterator.hasNext()) {
        short category = iterator.next();
        String prefix = quantifierFile.getName() + "\t" + indexName + "\t"
                + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t"
                + trueQuantification.getQuantification(category) + "\t";

        writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category)
                + "\n");
    }
    writer.close();

    BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator()
            + indexName + "_" + quantifierFile.getName() + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs();
    TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleTPRs();
    TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs();

    ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet();
    ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3])
            .getInternalQuantifier()).getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = test.getCategoryDB().getCategoryName(cat);
        ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat);
        ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double maxTPR = maxTPRs.get(cat);
        double maxFPR = maxFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat
                + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t"
                + simpleFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t"
                + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn()
                + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t"
                + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t"
                + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:eu.freme.bpt.Main.java

public static void main(String[] args) {
    final List<String> services = new ArrayList<>();
    for (EService eService : EService.values()) {
        services.add(eService.getName());
    }//from  ww  w .ja v a2  s  .c  om

    Pair<EService, String[]> serviceAndArgs = extractService(args, services);

    EService service = serviceAndArgs.getName();

    // create options that will be parsed from the args
    /////// General BPT options ///////
    Option helpOption = new Option("h", "help", false, "Prints this message");
    Option inputOption = Option.builder("if").longOpt("input-file").argName("input file").desc(
            "The input file or directory to process. In case of a directory, each file in that directory is processed. "
                    + "If not given, standard in is used.")
            .hasArg().build();
    Option outputOption = Option.builder("od").longOpt("output-dir").argName("output dir")
            .desc("The output directory. If not given, output is written to standard out.").hasArg().build();
    Option propertiesOption = Option.builder("prop").longOpt("properties").argName("properties file")
            .desc("The properties file that contains configuration of the tool.").hasArg().build();

    Options options = new Options().addOption(helpOption).addOption(inputOption).addOption(outputOption)
            .addOption(propertiesOption);

    /////// Common service options ///////
    Option informatOption = Option.builder("f").longOpt("informat").argName("FORMAT")
            .desc("The format of the input document(s). Defaults to 'turtle'").hasArg().build();
    Option outformatOption = Option.builder("o").longOpt("outformat").argName("FORMAT")
            .desc("The desired output format of the service. Defaults to 'turtle'").hasArg().build();
    options.addOption(informatOption).addOption(outformatOption);

    /////// Service specific options ///////
    if (service != null) {
        switch (service) {
        case E_TRANSLATION:
            ETranslation.addOptions(options);
            break;
        case E_ENTITY:
            EEntity.addOptions(options);
            break;
        case E_LINK:
            ELink.addOptions(options);
            break;
        case E_TERMINOLOGY:
            ETerminology.addOptions(options);
            break;
        case PIPELINING:
            Pipelining.addOptions(options);
            break;
        case E_PUBLISHING:
            // TODO !
        default:
            logger.warn("Unknown service {}. Skipping!", service);
            break;
        }
    } else {
        ETranslation.addOptions(options);
        EEntity.addOptions(options);
        ELink.addOptions(options);
        ETerminology.addOptions(options);
        Pipelining.addOptions(options);
    }

    CommandLine commandLine = null;
    int exitValue;
    try {
        CommandLineParser parser = new DefaultParser();
        commandLine = parser.parse(options, serviceAndArgs.getValue());
        exitValue = 0;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        exitValue = 1;
    }
    if ((exitValue != 0) || commandLine.hasOption("h") || service == null) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(132);
        formatter.printHelp("java -jar <this jar file> <e-service> ", options, true);
        System.exit(exitValue);
    }

    logger.debug("Commandline successfully parsed!");

    try {
        BPT batchProcessingTool = new BPT();
        if (commandLine.hasOption("prop")) {
            batchProcessingTool.loadProperties(commandLine.getOptionValue("prop"));
        }
        if (commandLine.hasOption("if")) {
            batchProcessingTool.setInput(commandLine.getOptionValue("if"));
        }
        if (commandLine.hasOption("od")) {
            batchProcessingTool.setOutput(commandLine.getOptionValue("od"));
        }
        if (commandLine.hasOption('f')) {
            batchProcessingTool.setInFormat(Format.valueOf(commandLine.getOptionValue('f').replace('-', '_')));
        }
        if (commandLine.hasOption('o')) {
            batchProcessingTool.setOutFormat(Format.valueOf(commandLine.getOptionValue('o').replace('-', '_')));
        }

        switch (service) {
        case E_TRANSLATION:
            batchProcessingTool.eTranslation(commandLine.getOptionValue("source-lang"),
                    commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("system"),
                    commandLine.getOptionValue("domain"), commandLine.getOptionValue("key"));
            break;
        case E_ENTITY:
            batchProcessingTool.eEntity(commandLine.getOptionValue("language"),
                    commandLine.getOptionValue("dataset"), commandLine.getOptionValue("mode"));
            break;
        case E_LINK:
            batchProcessingTool.eLink(commandLine.getOptionValue("templateid"));
            break;
        case E_TERMINOLOGY:
            batchProcessingTool.eTerminology(commandLine.getOptionValue("source-lang"),
                    commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("collection"),
                    commandLine.getOptionValue("domain"), commandLine.getOptionValue("key"),
                    commandLine.getOptionValue("mode"));
            break;
        case PIPELINING:
            batchProcessingTool.pipelining(commandLine.getOptionValue("templateid"));
            break;
        case E_PUBLISHING:
        default:
            logger.error("Unknown service {}. Aborting!", service);
            System.exit(3);
        }
    } catch (Exception e) {
        logger.error("Cannot handle input or output. Reason: ", e);
        System.exit(2);
    }
}