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:com.dattack.dbtools.ping.PingAnalyzer.java

/**
 * The <code>main</code> method.
 *
 * @param args/*from w w  w . j  a va 2 s  .  c  o m*/
 *            the program arguments
 */
public static void main(final String[] args) {

    try {

        // create Options object
        final Options options = new Options();

        // add t option
        options.addOption(START_DATE_OPTION, true, "the date for an analysis run to begin");
        options.addOption(END_DATE_OPTION, true, "the date for an analysis run to finish");
        options.addOption(SPAN_OPTION, true, "the period of time between points");
        options.addOption(DATA_FILE_OPTION, true, "the data file to analyze");
        options.addOption(METRIC_OPTION, true, "the metric to analyze");
        options.addOption(MAX_VALUE_OPTION, true, "the maximum value to use");
        options.addOption(MIN_VALUE_OPTION, true, "the minimum value to use");

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

        final ReportContext context = new ReportContext();
        context.setStartDate(TimeUtils.parseDate(cmd.getOptionValue(START_DATE_OPTION)));
        context.setEndDate(TimeUtils.parseDate(cmd.getOptionValue(END_DATE_OPTION)));
        context.setTimeSpan(TimeUtils.parseTimeSpanMillis(cmd.getOptionValue(SPAN_OPTION)));
        context.setMaxValue(parseLong(cmd.getOptionValue(MAX_VALUE_OPTION)));
        context.setMinValue(parseLong(cmd.getOptionValue(MIN_VALUE_OPTION)));
        if (cmd.hasOption(METRIC_OPTION)) {
            for (final String metricName : cmd.getOptionValues(METRIC_OPTION)) {
                context.addMetricNameFilter(MetricName.parse(metricName));
            }
        }

        final PingAnalyzer ping = new PingAnalyzer();
        for (final String file : cmd.getOptionValues(DATA_FILE_OPTION)) {
            ping.execute(new File(file), context);
        }

    } catch (final ParseException | ConfigurationException e) {
        System.err.println(e.getMessage());
    }
}

From source file:de.zazaz.iot.bosch.indego.util.CmdLineTool.java

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

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }//from   ww w  . j  a  va  2s  .c o  m
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder() //
            .longOpt("base-url") //
            .desc("Sets the base URL of the web service") //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("u") //
            .longOpt("username") //
            .desc("The username for authentication (usually mail address)") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("p") //
            .longOpt("password") //
            .desc("The password for authentication") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("c") //
            .longOpt("command") //
            .desc(String.format("The command, which should be sent to the device (%s)", commandList)) //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("q") //
            .longOpt("query-status") //
            .desc("Queries the status of the device") //
            .build());
    options.addOption(Option //
            .builder() //
            .longOpt("query-calendar") //
            .desc("Queries the calendar of the device") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    String baseUrl = cmds.getOptionValue("base-url");
    String username = cmds.getOptionValue('u');
    String password = cmds.getOptionValue('p');
    String commandStr = cmds.getOptionValue('c');
    boolean doQueryState = cmds.hasOption('q');
    boolean doQueryCalendar = cmds.hasOption("query-calendar");

    DeviceCommand command = null;
    if (commandStr != null) {
        try {
            command = DeviceCommand.valueOf(commandStr.toUpperCase());
        } catch (IllegalArgumentException ex) {
            System.err.println("Unknown command: " + commandStr);
            System.exit(1);
        }
    }

    IndegoController controller = new IndegoController(baseUrl, username, password);
    try {
        System.out.println("Connecting to device");
        controller.connect();
        System.out.println(String.format("...Connection established. Device serial number is: %s",
                controller.getDeviceSerialNumber()));
        if (command != null) {
            System.out.println(String.format("Sending command (%s)...", command));
            controller.sendCommand(command);
            System.out.println("...Command sent successfully!");
        }
        if (doQueryState) {
            System.out.println("Querying device state");
            DeviceStateInformation state = controller.getState();
            printState(System.out, state);
        }
        if (doQueryCalendar) {
            System.out.println("Querying device calendar");
            DeviceCalendar calendar = controller.getCalendar();
            printCalendar(System.out, calendar);
        }
    } catch (IndegoException ex) {
        ex.printStackTrace();
        System.exit(2);
    } finally {
        controller.disconnect();
    }
}

From source file:ktdiedrich.imagek.SegmentationCMD.java

/**
 * @author ktdiedrich@gmail.com/*from  ww  w  .j  a  v  a2s  . c o m*/
 * @param ags:  [file path] [Median filter size] [imageId]
 * Command line segmentation
 * @throws org.apache.commons.cli.ParseException 
 */
public static void main(String[] args) throws org.apache.commons.cli.ParseException {
    int imageIds[] = null;
    int medianFilterSize = 0;
    float seed = Extractor3D.SEED_HIST_THRES;
    String paths[] = null;

    Options options = new Options();
    options.addOption("p", true, "path name to file including filename");
    options.addOption("m", true, "median filter size, m*2+1");
    options.addOption("i", true, "image ID");
    options.addOption("f", true, "Image ID from");
    options.addOption("t", true, "Image ID to, (inclusive)");
    options.addOption("s", true, "Seed threshold default " + seed);
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("s")) {
        seed = Float.parseFloat(cmd.getOptionValue("s"));
    }
    if (cmd.hasOption("i")) {
        imageIds = new int[1];
        imageIds[0] = Integer.parseInt(cmd.getOptionValue("i"));
        paths = new String[1];
        paths[0] = getImageIdPath(imageIds[0]);
        // TODO get path to image ID from database and properties file. 
    }
    if (cmd.hasOption("f") && cmd.hasOption("t")) {
        int from = Integer.parseInt(cmd.getOptionValue("f"));
        int to = Integer.parseInt(cmd.getOptionValue("t"));
        int range = to - from + 1;
        paths = new String[range];
        imageIds = new int[range];
        for (int i = 0, imId = from; i < range; i++, imId++) {
            imageIds[i] = imId;
            paths[i] = getImageIdPath(imId);
        }
    }
    if (paths == null && cmd.hasOption("p")) {
        paths = new String[1];
        paths[0] = cmd.getOptionValue("p");
    }
    if (cmd.hasOption("m")) {
        medianFilterSize = Integer.parseInt(cmd.getOptionValue("m"));
    }

    // System.out.println("ImageID: "+imageId+" Path: "+paths+" Median filter: "+medianFilterSize);
    if (paths != null) {
        int i = 0;
        for (String path : paths) {
            String p[] = parseDirectoryFileName(path);
            String dirPath = p[0];
            ImagePlus segImage = segment(path, medianFilterSize, imageIds[i], seed);
            String title = segImage.getShortTitle();
            if (title.contains(File.separator))
                ;
            {
                title = parseDirectoryFileName(title)[1];
            }
            String outputPath = null;
            if (!dirPath.endsWith(File.separator))
                dirPath = dirPath + File.separator;
            outputPath = dirPath + title + ".zip";

            FileSaver fs = new FileSaver(segImage);
            fs.saveAsZip(outputPath);
            System.out.println("Saved: " + outputPath);
            ImagePlus mipYim = MIP.createShortMIP(segImage, MIP.Y_AXIS);
            fs = new FileSaver(mipYim);
            title = mipYim.getShortTitle();
            if (title.contains(File.separator))
                ;
            {
                title = parseDirectoryFileName(title)[1];
            }
            outputPath = dirPath + title + ".png";
            fs.saveAsPng(outputPath);
            System.out.println("Saved: " + outputPath + "\n");
            i++;
        }
    }
}

From source file:com.ibm.crail.namenode.NameNode.java

public static void main(String args[]) throws Exception {
    LOG.info("initalizing namenode ");
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);

    URI uri = CrailUtils.getPrimaryNameNode();
    String address = uri.getHost();
    int port = uri.getPort();

    if (args != null) {
        Option addressOption = Option.builder("a").desc("ip address namenode is started on").hasArg().build();
        Option portOption = Option.builder("p").desc("port namenode is started on").hasArg().build();
        Options options = new Options();
        options.addOption(portOption);/*from   w  w w  .j  a v  a 2s .c o  m*/
        options.addOption(addressOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length));
            if (line.hasOption(addressOption.getOpt())) {
                address = line.getOptionValue(addressOption.getOpt());
            }
            if (line.hasOption(portOption.getOpt())) {
                port = Integer.parseInt(line.getOptionValue(portOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Namenode", options);
            System.exit(-1);
        }
    }

    String namenode = "crail://" + address + ":" + port;
    long serviceId = CrailUtils.getServiceId(namenode);
    long serviceSize = CrailUtils.getServiceSize();
    if (!CrailUtils.verifyNamenode(namenode)) {
        throw new Exception("Namenode address/port [" + namenode
                + "] has to be listed in crail.namenode.address " + CrailConstants.NAMENODE_ADDRESS);
    }

    CrailConstants.NAMENODE_ADDRESS = namenode + "?id=" + serviceId + "&size=" + serviceSize;
    CrailConstants.printConf();
    CrailConstants.verify();

    RpcNameNodeService service = RpcNameNodeService.createInstance(CrailConstants.NAMENODE_RPC_SERVICE);
    RpcBinding rpcBinding = RpcBinding.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcBinding.init(conf, null);
    rpcBinding.printConf(LOG);
    rpcBinding.run(service);
    System.exit(0);
    ;
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.MorsaCreator.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 . jav  a2s  . co m
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output directory");
    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.createURI("morsa://" + commandLine.getOptionValue(OUT));

        Class<?> inClazz = MorsaCreator.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());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put("morsa",
                new MorsaResourceFactoryImpl(new MongoDBMorsaBackendFactory()));

        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>();
        //URI of the MongoDB database (e.g. localhost)
        saveOpts.put(IMorsaResource.OPTION_SERVER_URI, "localhost");
        saveOpts.put(IMorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, 30000);
        saveOpts.put(IMorsaResource.OPTION_DEMAND_LOAD, false);
        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:com.commonsware.android.gcm.cmd.GCM.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option apiKeyOpt = OptionBuilder.withArgName("key").hasArg().isRequired().withDescription("GCM API key")
            .withLongOpt("apiKey").create('a');
    Option deviceOpt = OptionBuilder.withArgName("regId").hasArg().isRequired()
            .withDescription("device to send to").withLongOpt("device").create('d');
    Option dataOpt = OptionBuilder.withArgName("key=value").hasArgs(2).withDescription("datum to send")
            .withValueSeparator().withLongOpt("data").create('D');

    Options options = new Options();

    options.addOption(apiKeyOpt);/* w  ww . j av  a2  s.  c o  m*/
    options.addOption(deviceOpt);
    options.addOption(dataOpt);
    options.addOption(helpOpt);

    CommandLineParser parser = new PosixParser();

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

        if (line.hasOption('h') || !line.hasOption('a') || !line.hasOption('d')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gcm", options, true);
        } else {
            sendMessage(line.getOptionValue('a'), Arrays.asList(line.getOptionValues('d')),
                    line.getOptionProperties("data"));
        }
    } catch (org.apache.commons.cli.MissingOptionException moe) {
        System.err.println("Invalid command syntax");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("gcm", options, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.s4.MainApp.java

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

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from   w  w  w .  ja v  a2s  . co m
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.CdoQueryInvisibleMethodDeclarations.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  a v a 2 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 = CdoQueryInvisibleMethodDeclarations.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();
            {
                Runtime.getRuntime().gc();
                long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                        MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                EList<MethodDeclaration> list = ASE2015JavaQueries.getInvisibleMethodDeclarations(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)));
                Runtime.getRuntime().gc();
                long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
                LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
                LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                        MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
            }

            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:edu.cmu.lti.oaqa.knn4qa.apps.FilterTranTable.java

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

    options.addOption(INPUT_PARAM, null, true, INPUT_DESC);
    options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC);
    options.addOption(CommonParams.MEM_FWD_INDEX_PARAM, null, true, CommonParams.MEM_FWD_INDEX_DESC);
    options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_PARAM);
    options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_PARAM);
    options.addOption(CommonParams.MIN_PROB_PARAM, null, true, CommonParams.MIN_PROB_DESC);
    options.addOption(CommonParams.MAX_WORD_QTY_PARAM, null, true, CommonParams.MAX_WORD_QTY_PARAM);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//  w w  w  .  j  a  v a 2s  . c om
        CommandLine cmd = parser.parse(options, args);

        String outputFile = null;

        outputFile = cmd.getOptionValue(OUTPUT_PARAM);
        if (null == outputFile) {
            Usage("Specify 'A name of the output file'", options);
        }

        String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM);
        if (null == gizaRootDir) {
            Usage("Specify '" + CommonParams.GIZA_ROOT_DIR_DESC + "'", options);
        }

        String gizaIterQty = cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM);

        if (null == gizaIterQty) {
            Usage("Specify '" + CommonParams.GIZA_ITER_QTY_DESC + "'", options);
        }

        float minProb = 0;

        String tmpf = cmd.getOptionValue(CommonParams.MIN_PROB_PARAM);

        if (tmpf != null) {
            minProb = Float.parseFloat(tmpf);
        }

        int maxWordQty = Integer.MAX_VALUE;

        String tmpi = cmd.getOptionValue(CommonParams.MAX_WORD_QTY_PARAM);

        if (null != tmpi) {
            maxWordQty = Integer.parseInt(tmpi);
        }

        String memFwdIndxName = cmd.getOptionValue(CommonParams.MEM_FWD_INDEX_PARAM);
        if (null == memFwdIndxName) {
            Usage("Specify '" + CommonParams.MEM_FWD_INDEX_DESC + "'", options);
        }

        System.out.println("Filtering index: " + memFwdIndxName + " max # of frequent words: " + maxWordQty
                + " min. probability:" + minProb);

        VocabularyFilterAndRecoder filter = new FrequentIndexWordFilterAndRecoder(memFwdIndxName, maxWordQty);

        String srcVocFile = CompressUtils.findFileVariant(gizaRootDir + "/source.vcb");

        System.out.println("Source vocabulary file: " + srcVocFile);

        GizaVocabularyReader srcVoc = new GizaVocabularyReader(srcVocFile, filter);

        String dstVocFile = CompressUtils.findFileVariant(gizaRootDir + "/target.vcb");

        System.out.println("Target vocabulary file: " + dstVocFile);

        GizaVocabularyReader dstVoc = new GizaVocabularyReader(CompressUtils.findFileVariant(dstVocFile),
                filter);

        String inputFile = CompressUtils.findFileVariant(gizaRootDir + "/output.t1." + gizaIterQty);

        BufferedReader finp = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(inputFile)));

        BufferedWriter fout = new BufferedWriter(
                new OutputStreamWriter(CompressUtils.createOutputStream(outputFile)));

        try {
            String line;
            int prevSrcId = -1;
            int wordQty = 0;
            long addedQty = 0;
            long totalQty = 0;
            boolean isNotFiltered = false;

            for (totalQty = 0; (line = finp.readLine()) != null;) {
                ++totalQty;
                // Skip empty lines
                line = line.trim();
                if (line.isEmpty())
                    continue;

                GizaTranRec rec = new GizaTranRec(line);

                if (rec.mSrcId != prevSrcId) {
                    ++wordQty;
                }
                if (totalQty % REPORT_INTERVAL_QTY == 0) {
                    System.out.println(String.format(
                            "Processed %d lines (%d source word entries) from '%s', added %d lines", totalQty,
                            wordQty, inputFile, addedQty));
                }

                // isNotFiltered should be set after procOneWord
                if (rec.mSrcId != prevSrcId) {
                    if (rec.mSrcId == 0)
                        isNotFiltered = true;
                    else {
                        String wordSrc = srcVoc.getWord(rec.mSrcId);
                        isNotFiltered = filter == null || (wordSrc != null && filter.checkWord(wordSrc));
                    }
                }

                prevSrcId = rec.mSrcId;

                if (rec.mProb >= minProb && isNotFiltered) {
                    String wordDst = dstVoc.getWord(rec.mDstId);

                    if (filter == null || (wordDst != null && filter.checkWord(wordDst))) {
                        fout.write(String.format(rec.mSrcId + " " + rec.mDstId + " " + rec.mProb));
                        fout.newLine();
                        addedQty++;
                    }
                }
            }

            System.out.println(
                    String.format("Processed %d lines (%d source word entries) from '%s', added %d lines",
                            totalQty, wordQty, inputFile, addedQty));

        } finally {
            finp.close();
            fout.close();
        }
    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:com.booktrack.vader.Main.java

/**
 * main entry point and demo case for Vader
 * @param args the arguments - explained below in the code
 * @throws Exception anything goes wrong - except
 *///from  w  ww. j a  v a 2  s . com
public static void main(String[] args) throws Exception {

    // create Options object for command line parsing
    Options options = new Options();
    options.addOption("file", true, "input text-file (-file) to read and analyse using Vader");

    CommandLineParser cmdParser = new DefaultParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = cmdParser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        logger.error("invalid command line: " + exp.getMessage());
        System.exit(0);
    }

    // get the command line argument -file
    String inputFile = line.getOptionValue("file");
    if (inputFile == null) {
        help(options);
        System.exit(0);
    }
    if (!new File(inputFile).exists()) {
        logger.error("file does not exist: " + inputFile);
        System.exit(0);
    }

    // example use of the classes
    // read the entire input file
    String fileText = new String(Files.readAllBytes(Paths.get(inputFile)));

    // setup Vader
    Vader vader = new Vader();
    vader.init(); // load vader

    // setup nlp processor
    VaderNLP vaderNLP = new VaderNLP();
    vaderNLP.init(); // load open-nlp

    // parse the text into a set of sentences
    List<List<Token>> sentenceList = vaderNLP.parse(fileText);

    // apply vader analysis to each sentence
    for (List<Token> sentence : sentenceList) {
        VScore vaderScore = vader.analyseSentence(sentence);
        logger.info("sentence:" + Token.tokenListToString(sentence));
        logger.info("Vader score:" + vaderScore.toString());
    }

}