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

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

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:de.prozesskraft.pkraft.Merge.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file// ww  w  .  j  a v  a  2s.  com
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] instance you want to merge another instance into.")
            //            .isRequired()
            .create("instance");

    Option oguest = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] this instance will be merged into -instance.")
            //            .isRequired()
            .create("guest");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.")
            //            .isRequired()
            .create("basedir");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oguest);
    options.addOption(obasedir);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("merge", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("instance"))) {
        System.err.println("option -instance is mandatory");
        exiter();
    }
    if (!(commandline.hasOption("guest"))) {
        System.err.println("at least one option -guest is mandatory");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);

    String[] pathToGuest = commandline.getOptionValues("guest");

    String baseDir = null;
    if (commandline.hasOption("basedir")) {
        java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath());
            exiter();
        } else if (!fileBaseDir.isDirectory()) {
            System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath());
            exiter();
        }
        baseDir = commandline.getOptionValue("basedir");
    }

    // ueberpruefen ob die process.pmb files vorhanden sind
    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }
    for (String pathGuest : pathToGuest) {
        java.io.File fileGuest = new java.io.File(pathGuest);

        // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
        if (!fileGuest.exists()) {
            System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath());
            exiter();
        }
    }

    // base - instance einlesen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    p1.setOutfilebinary(pathToInstance);
    Process p2 = p1.readBinary();

    // alle guests einlesen
    ArrayList<Process> alleGuests = new ArrayList<Process>();
    for (String actPathGuest : pathToGuest) {
        Process p30 = new Process();
        p30.setInfilebinary(actPathGuest);
        Process pGuest = p30.readBinary();

        // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind
        if (!p2.getName().equals(pGuest.getName())) {
            System.err.println("error: instances are not from the same type (-instance=" + p2.getName()
                    + " != -guest=" + pGuest.getName());
            exiter();
        }

        // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind
        if (!p2.getVersion().equals(pGuest.getVersion())) {
            System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!="
                    + pGuest.getVersion());
            exiter();
        }

        alleGuests.add(pGuest);
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p3 = new Process();
    p3.setInfilebinary(pathToInstance);
    Process process = p3.readBinary();

    // den main-prozess ueber die static function klonen
    // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess);
                // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir()
                        + "/process.pmb";
                System.err.println("info: calling: " + call2);

                try {
                    java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
                } catch (IOException e) {
                    System.err.println("error: " + e.getMessage());
                }
            }
        }
    }

    // alle dependent steps der zielinstanz einsammeln
    // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden
    Map<Step, String> dependentSteps = new HashMap<Step, String>();

    // alle guest prozesse merge durchfuehren
    for (Process actGuestProcess : alleGuests) {
        System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary());

        // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren
        for (Step actStep : actGuestProcess.getStep()) {
            if (actStep.isAFannedMultistep()) {
                System.err.println("info: merging from guest instance step " + actStep.getName());
                Step clonedStepForIntegrationInClonedProcess = actStep.clone();
                if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) {
                    System.err.println("info: merging step successfully.");
                    // die downstream steps vom merge-punkt merken
                    for (Step actStepToResetBecauseOfDependency : clonedProcess
                            .getStepDependent(actStep.getName())) {
                        dependentSteps.put(actStepToResetBecauseOfDependency, "dummy");
                    }

                    // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden
                    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
                    if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null
                            && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) {
                        String call5 = ini.get("apps", "pradar-attend") + " -instance "
                                + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb";
                        System.err.println("info: calling: " + call5);
                        try {
                            java.lang.Process sysproc = Runtime.getRuntime().exec(call5);
                        } catch (IOException e) {
                            System.err.println("error: " + e.getMessage());
                        }
                    }
                } else {
                    System.err.println("error: merging step failed.");
                }
            } else {
                System.err.println("debug: because it's not a multistep, ignoring from guest instance step "
                        + actStep.getName());
            }
        }
    }

    // alle steps downstream der merge-positionen resetten
    for (Step actStep : dependentSteps.keySet()) {
        actStep.resetBecauseOfDependency();
    }

    // speichern der ergebnis instanz
    clonedProcess.writeBinary();

    // den prozess in pradar anmelden durch aufruf des tools: pradar-attend
    String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir()
            + "/process.pmb";
    System.err.println("info: calling: " + call2);

    try {
        java.lang.Process sysproc = Runtime.getRuntime().exec(call2);
    } catch (IOException e) {
        System.err.println("error: " + e.getMessage());
    }

}

From source file:de.phillme.PhotoSorter.java

public static void main(String[] args) {
    PhotoConfig photoConfig = new PhotoConfig();

    // create the parser
    CommandLineParser parser = new DefaultParser();
    try {//from  w  w w.  ja  v a2 s.  c o  m
        // parse the command line arguments
        CommandLine line = parser.parse(photoConfig.getOptions(), args);

        if (line.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("PhotoSorter", photoConfig.getOptions());
            return;
        }

        PhotoSorter photoSorter = new PhotoSorter(line);
        List<PhotoFile> photoFileList;
        List<PhotoFile> sortedList;

        //photoSorter.probeFiletypes();
        photoFileList = photoSorter.listSourceFiles();
        sortedList = photoSorter.sortList(photoFileList);

        LOGGER.finest(sortedList.toString());
        photoSorter.flagAllEvents(sortedList);

        photoSorter.printEventList(photoSorter.getEventList());

        //LOGGER.info(pathList.toString());

    } catch (org.apache.commons.cli.ParseException e) {
        LOGGER.severe(e.getMessage());
    } catch (IOException e) {
        LOGGER.severe(e.getMessage());
    } catch (ImageProcessingException e) {
        LOGGER.severe(e.getMessage());
    }

}

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  ww  w  . j  a va  2s .c  om
    }
    // 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:com.example.dlp.RiskAnalysis.java

/**
 * Command line application to perform risk analysis using the Data Loss Prevention API.
 * Supported data format: BigQuery tables
 *//*from w  w  w  .  j  a v a 2 s  . c  om*/
public static void main(String[] args) throws Exception {

    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);

    Option numericalAnalysisOption = new Option("n", "numerical");
    optionsGroup.addOption(numericalAnalysisOption);

    Option categoricalAnalysisOption = new Option("c", "categorical");
    optionsGroup.addOption(categoricalAnalysisOption);

    Option kanonymityOption = new Option("k", "kAnonymity");
    optionsGroup.addOption(kanonymityOption);

    Option ldiversityOption = new Option("l", "lDiversity");
    optionsGroup.addOption(ldiversityOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option datasetIdOption = Option.builder("datasetId").hasArg(true).required(false).build();
    commandLineOptions.addOption(datasetIdOption);

    Option tableIdOption = Option.builder("tableId").hasArg(true).required(false).build();
    commandLineOptions.addOption(tableIdOption);

    Option projectIdOption = Option.builder("projectId").hasArg(true).required(false).build();
    commandLineOptions.addOption(projectIdOption);

    Option columnNameOption = Option.builder("columnName").hasArg(true).required(false).build();
    commandLineOptions.addOption(columnNameOption);

    Option sensitiveAttributeOption = Option.builder("sensitiveAttribute").hasArg(true).required(false).build();
    commandLineOptions.addOption(sensitiveAttributeOption);

    Option quasiIdColumnNamesOption = Option.builder("quasiIdColumnNames").hasArg(true).required(false).build();
    commandLineOptions.addOption(quasiIdColumnNamesOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(RiskAnalysis.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    String datasetId = cmd.getOptionValue(datasetIdOption.getOpt());
    String tableId = cmd.getOptionValue(tableIdOption.getOpt());
    // use default project id when project id is not specified
    String projectId = cmd.getOptionValue(projectIdOption.getOpt(), ServiceOptions.getDefaultProjectId());

    if (cmd.hasOption("n")) {
        // numerical stats analysis
        String columnName = cmd.getOptionValue(columnNameOption.getOpt());
        calculateNumericalStats(projectId, datasetId, tableId, columnName);
    } else if (cmd.hasOption("c")) {
        // categorical stats analysis
        String columnName = cmd.getOptionValue(columnNameOption.getOpt());
        calculateCategoricalStats(projectId, datasetId, tableId, columnName);
    } else if (cmd.hasOption("k")) {
        // k-anonymity analysis
        List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt()));
        calculateKAnonymity(projectId, datasetId, tableId, quasiIdColumnNames);
    } else if (cmd.hasOption("l")) {
        // l-diversity analysis
        String sensitiveAttribute = cmd.getOptionValue(sensitiveAttributeOption.getOpt());
        List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt()));
        calculateLDiversity(projectId, datasetId, tableId, sensitiveAttribute, quasiIdColumnNames);
    }
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public static void main(String[] args) throws Exception {
    RunJasperReports runJasperReports = new RunJasperReports();
    // Set up command line parser
    Options options = new Options();
    Option reports = OptionBuilder.withArgName("reportlist").hasArg()
            .withDescription("Comma separated list of JasperReport XML input files").create("reports");
    options.addOption(reports);//w w  w. ja va  2 s .  c  o  m
    Option emailTo = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Email address to send generated reports to").create("emailto");
    options.addOption(emailTo);
    Option emailFrom = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Sender email address").create("emailfrom");
    options.addOption(emailFrom);
    Option emailSubjectLine = OptionBuilder.withArgName("emailsubject").hasArg()
            .withDescription("Subject line of email").create("emailsubject");
    options.addOption(emailSubjectLine);
    Option emailHostOption = OptionBuilder.withArgName("emailhost").hasArg()
            .withDescription("Address of email server").create("emailhost");
    options.addOption(emailHostOption);
    Option emailUsernameOption = OptionBuilder.withArgName("emailuser").hasArg()
            .withDescription("Username if email server requires authentication").create("emailuser");
    options.addOption(emailUsernameOption);
    Option emailPasswordOption = OptionBuilder.withArgName("emailpass").hasArg()
            .withDescription("Password if email server requires authentication").create("emailpass");
    options.addOption(emailPasswordOption);
    Option outputFolder = OptionBuilder.withArgName("foldername").hasArg()
            .withDescription(
                    "Folder to write generated reports to, with trailing separator (slash or backslash)")
            .create("folder");
    options.addOption(outputFolder);
    Option dbTypeOption = OptionBuilder.withArgName("databasetype").hasArg()
            .withDescription("Currently supported types are: " + Arrays.asList(DatabaseType.values()))
            .create("dbtype");
    options.addOption(dbTypeOption);
    Option dbNameOption = OptionBuilder.withArgName("databasename").hasArg()
            .withDescription("Name of the database to run reports against").create("dbname");
    options.addOption(dbNameOption);

    Option dbUserOption = OptionBuilder.withArgName("username").hasArg()
            .withDescription("Username to connect to databasewith").create("dbuser");
    options.addOption(dbUserOption);
    Option dbPassOption = OptionBuilder.withArgName("password").hasArg().withDescription("Database password")
            .create("dbpass");
    options.addOption(dbPassOption);
    Option outputTypeOption = OptionBuilder.withArgName("outputtype").hasArg()
            .withDescription("Output type, one of: " + Arrays.asList(OutputType.values())).create("output");
    options.addOption(outputTypeOption);
    Option outputFilenameOption = OptionBuilder.withArgName("outputfilename").hasArg()
            .withDescription("Output filename (excluding filetype suffix)").create("filename");
    options.addOption(outputFilenameOption);
    Option dbHostOption = OptionBuilder.withArgName("host").hasArg().withDescription("Database host address")
            .create("dbhost");
    options.addOption(dbHostOption);
    Option paramsOption = OptionBuilder.withArgName("parameters").hasArg().withDescription(
            "Parameters, e.g. param1=boolean:true,param2=string:ABC,param3=double:134.2,param4=integer:85")
            .create("params");
    options.addOption(paramsOption);
    // Parse command line
    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = parser.parse(options, args);
    String reportsDefinitionFileNamesCvs = commandLine.getOptionValue("reports");
    if (reportsDefinitionFileNamesCvs == null) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar RunJasperReports.jar", options);
        System.out.println();
        System.out.println("See www.agilebase.co.uk/opensource for further documentation");
        System.out.println();
        throw new IllegalArgumentException("No reports specified");
    }
    String outputPath = commandLine.getOptionValue("folder");
    List<String> reportDefinitionFileNames = Arrays.asList(reportsDefinitionFileNamesCvs.split(","));
    List<String> outputFileNames = new ArrayList<String>();
    DatabaseType databaseType = DatabaseType.POSTGRESQL;
    String databaseTypeString = commandLine.getOptionValue("dbtype");
    if (databaseTypeString != null) {
        databaseType = DatabaseType.valueOf(commandLine.getOptionValue("dbtype").toUpperCase());
    }
    String databaseName = commandLine.getOptionValue("dbname");
    String databaseUsername = commandLine.getOptionValue("dbuser");
    String databasePassword = commandLine.getOptionValue("dbpass");
    String databaseHost = commandLine.getOptionValue("dbhost");
    if (databaseHost == null) {
        databaseHost = "localhost";
    }
    OutputType outputType = OutputType.PDF;
    String outputTypeString = commandLine.getOptionValue("output");
    if (outputTypeString != null) {
        outputType = OutputType.valueOf(outputTypeString.toUpperCase());
    }
    String parametersString = commandLine.getOptionValue("params");
    Map parameters = runJasperReports.prepareParameters(parametersString);
    String outputFilenameSpecified = commandLine.getOptionValue("filename");
    if (outputFilenameSpecified == null) {
        outputFilenameSpecified = "";
    }
    // Iterate over reports, generating output for each
    for (String reportsDefinitionFileName : reportDefinitionFileNames) {
        String outputFilename = null;
        if ((reportDefinitionFileNames.size() == 1) && (!outputFilenameSpecified.equals(""))) {
            outputFilename = outputFilenameSpecified;
        } else {
            outputFilename = outputFilenameSpecified + reportsDefinitionFileName.replaceAll("\\..*$", "");
            outputFilename = outputFilename.replaceAll("^.*\\/", "");
            outputFilename = outputFilename.replaceAll("^.*\\\\", "");
        }
        outputFilename = outputFilename.replaceAll("\\W", "").toLowerCase() + "."
                + outputType.toString().toLowerCase();
        if (outputPath != null) {
            if (!outputPath.endsWith("\\") && !outputPath.endsWith("/")) {
                outputPath += java.io.File.separator;
            }
            outputFilename = outputPath + outputFilename;
        }
        System.out.println("Going to generate report " + outputFilename);
        if (outputType.equals(OutputType.PDF)) {
            runJasperReports.generatePdfReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        } else if (outputType.equals(OutputType.TEXT)) {
            runJasperReports.generateTextReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        } else if (outputType.equals(OutputType.CSV)) {
            runJasperReports.generateCSVReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        } else if (outputType.equals(OutputType.XLS)) {
            // NB: parameters are in a different order for XLS for some reasons
            runJasperReports.generateJxlsReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseHost, databaseName, databaseUsername, databasePassword, parameters);
        } else {
            runJasperReports.generateHtmlReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        }
        outputFileNames.add(outputFilename);
    }
    String emailRecipientList = commandLine.getOptionValue("emailto");
    if (emailRecipientList != null) {
        Set<String> emailRecipients = new HashSet<String>(Arrays.asList(emailRecipientList.split(",")));
        String emailSender = commandLine.getOptionValue("emailfrom");
        String emailSubject = commandLine.getOptionValue("emailsubject");
        if (emailSubject == null) {
            emailSubject = "Report attached";
        }
        String emailHost = commandLine.getOptionValue("emailhost");
        if (emailHost == null) {
            emailHost = "localhost";
        }
        String emailUser = commandLine.getOptionValue("emailuser");
        String emailPass = commandLine.getOptionValue("emailpass");
        System.out.println("Emailing reports to " + emailRecipients);
        runJasperReports.emailReport(emailHost, emailUser, emailPass, emailRecipients, emailSender,
                emailSubject, outputFileNames);
    } else {
        System.out.println("Email not generated (no recipients specified)");
    }
}

From source file:com.anjlab.sat3.Program.java

public static void main(String[] args) throws Exception {
    System.out.println("Reference Implementation of Romanov's Polynomial Algorithm for 3-SAT Problem"
            + "\nCopyright (c) 2010 AnjLab" + "\nThis program comes with ABSOLUTELY NO WARRANTY."
            + "\nThis is free software, and you are welcome to redistribute it under certain conditions."
            + "\nSee LICENSE.txt file or visit <http://www.gnu.org/copyleft/lesser.html> for details.");

    LOGGER.debug("Reading version number from manifest");
    String implementationVersion = Helper.getImplementationVersionFromManifest("3-SAT Core RI");
    System.out.println("Version: " + implementationVersion + "\n");

    Options options = getCommandLineOptions();

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

    if (commandLine.getArgs().length != 1 || commandLine.hasOption(HELP_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Program.class.getName() + " [OPTIONS] <input-file-name>"
                + "\nWhere <input-file-name> is a path to file containing k-SAT formula instance in DIMACS CNF or Romanov SKT file format.",
                options);/*from  w  w  w  .j  av  a  2  s  .c  om*/
        System.exit(0);
    }

    String formulaFile = commandLine.getArgs()[0];

    Helper.UsePrettyPrint = commandLine.hasOption(USE_PRETTY_PRINT_OPTION);
    Helper.EnableAssertions = !commandLine.hasOption(DISABLE_ASSERTIONS_OPTION);
    Helper.UseUniversalVarNames = !commandLine.hasOption(USE_ABC_VAR_NAMES_OPTION);

    Properties statistics = new Properties();
    StopWatch stopWatch = new StopWatch();

    try {
        statistics.put(Helper.IMPLEMENTATION_VERSION, implementationVersion);

        stopWatch.start("Load formula");
        ITabularFormula formula = Helper.loadFromFile(formulaFile);
        long timeElapsed = stopWatch.stop();

        statistics.put(Helper.INITIAL_FORMULA_LOAD_TIME, String.valueOf(timeElapsed));

        if (commandLine.hasOption(GENERATE_3SAT_OPTION)) {
            String generated3SatFilename = formulaFile + "-3sat.cnf";

            LOGGER.info("Saving 3-SAT formula to {}...", generated3SatFilename);
            Helper.saveToDIMACSFileFormat(formula, generated3SatFilename);
        }

        if (formula.getVarCount() > 26) {
            LOGGER.info("Variables count > 26 => force using universal names for variables.");
            Helper.UseUniversalVarNames = true;
        }

        statistics.put(Helper.INITIAL_FORMULA_VAR_COUNT, String.valueOf(formula.getVarCount()));
        statistics.put(Helper.INITIAL_FORMULA_CLAUSES_COUNT, String.valueOf(formula.getClausesCount()));

        Helper.prettyPrint(formula);
        stopWatch.printElapsed();

        if (commandLine.hasOption(FIND_HSS_ROUTE_OPTION)) {
            String hssPath = commandLine.getOptionValue(FIND_HSS_ROUTE_OPTION);

            stopWatch.start("Load HSS from " + hssPath);
            ObjectArrayList hss = Helper.loadHSS(hssPath);
            stopWatch.stop();
            stopWatch.printElapsed();

            findHSSRoute(commandLine, formulaFile, statistics, stopWatch, formula, null, null, hss, hssPath);

            return;
        }

        if (commandLine.hasOption(EVALUATE_OPTION)) {
            String resultsFilename = commandLine.getOptionValue(EVALUATE_OPTION);
            boolean satisfiable = evaluateFormula(stopWatch, formula, resultsFilename);
            if (satisfiable) {
                System.out.println("Formula evaluated as SAT");
            } else {
                System.out.println("Formula evaluated as UNSAT");
            }
            //  Only evaluate formula value
            return;
        }

        //  Find if formula is SAT

        //  Clone initial formula to verify formula satisfiability later
        ITabularFormula formulaClone = null;
        if (Helper.EnableAssertions) {
            stopWatch.start("Clone initial formula");
            formulaClone = formula.clone();
            stopWatch.stop();
            stopWatch.printElapsed();
        }

        stopWatch.start("Create CTF");
        ObjectArrayList ct = Helper.createCTF(formula);
        timeElapsed = stopWatch.stop();
        printFormulas(ct);
        stopWatch.printElapsed();

        statistics.put(Helper.CTF_CREATION_TIME, String.valueOf(timeElapsed));
        statistics.put(Helper.CTF_COUNT, String.valueOf(ct.size()));

        LOGGER.info("CTF count: {}", ct.size());

        if (Helper.EnableAssertions) {
            assertNoTripletsLost(formula, ct);
        }

        //  Clone CTF to verify formula satisfiability against it later
        ObjectArrayList ctfClone = null;

        if (Helper.EnableAssertions) {
            ctfClone = Helper.cloneStructures(ct);
        }

        stopWatch.start("Create CTS");
        Helper.completeToCTS(ct, formula.getPermutation());
        timeElapsed = stopWatch.stop();
        printFormulas(ct);
        stopWatch.printElapsed();

        statistics.put(Helper.CTS_CREATION_TIME, String.valueOf(timeElapsed));

        if (commandLine.hasOption(CREATE_SKT_OPTION)) {
            String sktFilename = formulaFile + ".skt";
            stopWatch.start("Convert CTS to " + sktFilename);
            Helper.convertCTStructuresToRomanovSKTFileFormat(ct, sktFilename);
            stopWatch.stop();
            stopWatch.printElapsed();

            return;
        }

        ObjectArrayList hss = unifyAndCreateHSS(statistics, stopWatch, ct);

        String hssPath = formulaFile + "-hss";
        stopWatch.start("Save HSS to " + hssPath + "...");
        Helper.saveHSS(hssPath, hss);
        stopWatch.stop();
        stopWatch.printElapsed();

        findHSSRoute(commandLine, formulaFile, statistics, stopWatch, formula, formulaClone, ctfClone, hss,
                hssPath);
    } catch (EmptyStructureException e) {
        stopWatch.stop();
        stopWatch.printElapsed();

        LOGGER.info("One of the structures was built empty", e);

        String resultsFilename = getResultsFilename(commandLine, formulaFile);
        stopWatch.start("Saving current statictics of calculations to " + resultsFilename);
        writeUnsatToFile(resultsFilename, statistics);
        stopWatch.stop();
        stopWatch.printElapsed();

        System.out.println("Formula not satisfiable");
    } finally {
        System.out.println("Program completed");
    }
}

From source file:io.anserini.index.UpdateIndex.java

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

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment"));
    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(//from  w w  w  .j  av  a2 s.  co m
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids")
            .create(DELETES_OPTION));
    options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(UpdateIndex.class.getName(), options);
        System.exit(-1);
    }

    String indexPath = cmdline.getOptionValue(INDEX_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    textOptions.setStoreTermVectors(true);

    LOG.info("index: " + indexPath);

    File file = new File("PittsburghUserTimeline");
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    final StatusStream stream = new JsonStatusCorpusReader(file);

    Status status;
    String s;
    HashMap<Long, String> hm = new HashMap<Long, String>();
    try {
        while ((s = stream.nextRaw()) != null) {
            try {
                status = DataObjectFactory.createStatus(s);

                if (status.getText() == null) {
                    continue;
                }

                hm.put(status.getUser().getId(),
                        hm.get(status.getUser().getId()) + status.getText().replaceAll("[\\r\\n]+", " "));

            } catch (Exception e) {

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        stream.close();
    }

    ArrayList<String> userIDList = new ArrayList<String>();
    try (BufferedReader br = new BufferedReader(new FileReader(new File("userID")))) {
        String line;
        while ((line = br.readLine()) != null) {
            userIDList.add(line.replaceAll("[\\r\\n]+", ""));

            // process the line.
        }
    }

    try {
        reader = DirectoryReader
                .open(FSDirectory.open(new File(cmdline.getOptionValue(INDEX_OPTION)).toPath()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final Directory dir = new SimpleFSDirectory(Paths.get(cmdline.getOptionValue(INDEX_OPTION)));
    final IndexWriterConfig config = new IndexWriterConfig(ANALYZER);

    config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

    final IndexWriter writer = new IndexWriter(dir, config);

    IndexSearcher searcher = new IndexSearcher(reader);
    System.out.println("The total number of docs indexed "
            + searcher.collectionStatistics(TweetStreamReader.StatusField.TEXT.name).docCount());

    for (int city = 0; city < cityName.length; city++) {

        // Pittsburgh's coordinate -79.976389, 40.439722

        Query q_long = NumericRangeQuery.newDoubleRange(TweetStreamReader.StatusField.LONGITUDE.name,
                new Double(longitude[city] - 0.05), new Double(longitude[city] + 0.05), true, true);
        Query q_lat = NumericRangeQuery.newDoubleRange(TweetStreamReader.StatusField.LATITUDE.name,
                new Double(latitude[city] - 0.05), new Double(latitude[city] + 0.05), true, true);

        BooleanQuery bqCityName = new BooleanQuery();

        Term t = new Term("place", cityName[city]);
        TermQuery query = new TermQuery(t);
        bqCityName.add(query, BooleanClause.Occur.SHOULD);
        System.out.println(query.toString());

        for (int i = 0; i < cityNameAlias[city].length; i++) {
            t = new Term("place", cityNameAlias[city][i]);
            query = new TermQuery(t);
            bqCityName.add(query, BooleanClause.Occur.SHOULD);
            System.out.println(query.toString());
        }

        BooleanQuery bq = new BooleanQuery();

        BooleanQuery finalQuery = new BooleanQuery();

        // either a coordinate match
        bq.add(q_long, BooleanClause.Occur.MUST);
        bq.add(q_lat, BooleanClause.Occur.MUST);

        finalQuery.add(bq, BooleanClause.Occur.SHOULD);
        // or a place city name match
        finalQuery.add(bqCityName, BooleanClause.Occur.SHOULD);

        TotalHitCountCollector totalHitCollector = new TotalHitCountCollector();

        // Query hasFieldQuery = new ConstantScoreQuery(new
        // FieldValueFilter("timeline"));
        //
        // searcher.search(hasFieldQuery, totalHitCollector);
        //
        // if (totalHitCollector.getTotalHits() > 0) {
        // TopScoreDocCollector collector =
        // TopScoreDocCollector.create(Math.max(0,
        // totalHitCollector.getTotalHits()));
        // searcher.search(finalQuery, collector);
        // ScoreDoc[] hits = collector.topDocs().scoreDocs;
        //
        //
        // HashMap<String, Integer> hasHit = new HashMap<String, Integer>();
        // int dupcount = 0;
        // for (int i = 0; i < hits.length; ++i) {
        // int docId = hits[i].doc;
        // Document d;
        //
        // d = searcher.doc(docId);
        //
        // System.out.println(d.getFields());
        // }
        // }

        // totalHitCollector = new TotalHitCountCollector();
        searcher.search(finalQuery, totalHitCollector);

        if (totalHitCollector.getTotalHits() > 0) {
            TopScoreDocCollector collector = TopScoreDocCollector
                    .create(Math.max(0, totalHitCollector.getTotalHits()));
            searcher.search(finalQuery, collector);
            ScoreDoc[] hits = collector.topDocs().scoreDocs;

            System.out.println("City " + cityName[city] + " " + collector.getTotalHits() + " hits.");

            HashMap<String, Integer> hasHit = new HashMap<String, Integer>();
            int dupcount = 0;
            for (int i = 0; i < hits.length; ++i) {
                int docId = hits[i].doc;
                Document d;

                d = searcher.doc(docId);

                if (userIDList.contains(d.get(IndexTweets.StatusField.USER_ID.name))
                        && hm.containsKey(Long.parseLong(d.get(IndexTweets.StatusField.USER_ID.name)))) {
                    //            System.out.println("Has timeline field?" + (d.get("timeline") != null));
                    //            System.out.println(reader.getDocCount("timeline"));
                    //            d.add(new Field("timeline", hm.get(Long.parseLong(d.get(IndexTweets.StatusField.USER_ID.name))),
                    //                textOptions));
                    System.out.println("Found a user hit");
                    BytesRefBuilder brb = new BytesRefBuilder();
                    NumericUtils.longToPrefixCodedBytes(Long.parseLong(d.get(IndexTweets.StatusField.ID.name)),
                            0, brb);
                    Term term = new Term(IndexTweets.StatusField.ID.name, brb.get());
                    //            System.out.println(reader.getDocCount("timeline"));

                    Document d_new = new Document();
                    //            for (IndexableField field : d.getFields()) {
                    //              d_new.add(field);
                    //            }
                    // System.out.println(d_new.getFields());
                    d_new.add(new StringField("userBackground", d.get(IndexTweets.StatusField.USER_ID.name),
                            Store.YES));
                    d_new.add(new Field("timeline",
                            hm.get(Long.parseLong(d.get(IndexTweets.StatusField.USER_ID.name))), textOptions));
                    // System.out.println(d_new.get());
                    writer.addDocument(d_new);
                    writer.commit();

                    //            t = new Term("label", "why");
                    //            TermQuery tqnew = new TermQuery(t);
                    //
                    //            totalHitCollector = new TotalHitCountCollector();
                    //
                    //            searcher.search(tqnew, totalHitCollector);
                    //
                    //            if (totalHitCollector.getTotalHits() > 0) {
                    //              collector = TopScoreDocCollector.create(Math.max(0, totalHitCollector.getTotalHits()));
                    //              searcher.search(tqnew, collector);
                    //              hits = collector.topDocs().scoreDocs;
                    //
                    //              System.out.println("City " + cityName[city] + " " + collector.getTotalHits() + " hits.");
                    //
                    //              for (int k = 0; k < hits.length; k++) {
                    //                docId = hits[k].doc;
                    //                d = searcher.doc(docId);
                    //                System.out.println(d.get(IndexTweets.StatusField.ID.name));
                    //                System.out.println(d.get(IndexTweets.StatusField.PLACE.name));
                    //              }
                    //            }

                    // writer.deleteDocuments(term);
                    // writer.commit();
                    // writer.addDocument(d);
                    // writer.commit();

                    //            System.out.println(reader.getDocCount("timeline"));
                    // writer.updateDocument(term, d);
                    // writer.commit();

                }

            }
        }
    }
    reader.close();
    writer.close();

}

From source file:ctlogger.CTlogger.java

public static void main(String args[]) {

    /**/*w  ww.j  a  va2  s.  co  m*/
     * 
     * Original code for command line parsing
     * (This has been replaced by code using Apache Commons CLI, see below)
     *
    String helpMsg = "CTlogger -x -r -z -g -k <skiplines> -f <flush_sec> -p <poll_sec> -n <nanVal> -i <leadingID> -s <SourceName> -H <HeaderLine> <logger.dat> <CTfolder>";
      int dirArg = 0;
      while((dirArg<args.length) && args[dirArg].startsWith("-")) {      // arg parsing
         if(args[dirArg].equals("-h"))    { 
     System.err.println(helpMsg);
     System.exit(0);
         }
         if(args[dirArg].equals("-x"))    { debug = true;   }
         if(args[dirArg].equals("-b"))    { noBackwards = true;   }
         if(args[dirArg].equals("-g"))    { gzipmode = true;   }         // default false
         if(args[dirArg].equals("-a"))    { appendMode = false;   }      // default true
         if(args[dirArg].equals("-z"))     { zipmode = false; }          // default true
         if(args[dirArg].equals("-N"))    { newFileMode = true;   }      // default false
         if(args[dirArg].equals("-f"))   { autoflush = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-p"))   { pollInterval = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-k"))   { skipLines = Long.parseLong(args[++dirArg]); }
         if(args[dirArg].equals("-r"))   { repeatFetch = true; }   
         if(args[dirArg].equals("-B"))   { blockMode = true; }   
         if(args[dirArg].equals("-t"))   { storeTime = true; }   
         if(args[dirArg].equals("-T"))   { trimTime = Double.parseDouble(args[++dirArg]); }
         if(args[dirArg].equals("-n"))   { nanVal = args[++dirArg]; }
         if(args[dirArg].equals("-i"))   { leadingID = args[++dirArg]; }
         if(args[dirArg].equals("-s"))   { SourceName = args[++dirArg]; }
         if(args[dirArg].equals("-H"))   { HeaderLine = args[++dirArg]; }
         dirArg++;
      }
    if(args.length < (dirArg+2)) {
       System.err.println(helpMsg);
       System.exit(0);
    }
    loggerFileName = args[dirArg++];      // args[0]:  logger.dat file
    CTrootfolder = args[dirArg++];         // args[1]:  CT destination folder        
    */

    //
    // Parse command line arguments
    //
    // 1. Setup command line options
    //
    Options options = new Options();
    // Boolean options (only the flag, no argument)
    options.addOption("h", "help", false, "Print this message");
    options.addOption("x", "debug", false, "turn on debug output");
    options.addOption("b", "nobackwards", false, "no backwards-going time allowed");
    options.addOption("g", "gzipmode", false, "turn on gzip for extra compression");
    options.addOption("a", "noappend", false,
            "turn off append mode (i.e., do not append to end of existing CT data)");
    options.addOption("z", "nozip", false, "turn off zip mode (it is on by default)");
    options.addOption("N", "newfilemode", false, "re-parse entire logger file every time it is checked");
    options.addOption("r", "repeatFetch", false, "turn on repeat fetch (auto-fetch data loop)");
    options.addOption("B", "blockMode", false,
            "turn on CloudTurbine writer block mode (multiple points per output data file, packed data)");
    options.addOption("t", "storeTime", false,
            "store time string as a channel; time is the first data entry in each line; if this option is not specified, then the time channel is skipped/not saved to CloudTurbine");
    // Options with an argument
    Option outputFolderOption = Option.builder("f").argName("autoflush").hasArg()
            .desc("flush interval (sec); default = \"" + autoflush + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("p").argName("pollInterval").hasArg().desc(
            "if repeatFetch option has been specified, recheck the logger data file at this polling interval (sec); default = \""
                    + pollInterval + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("k").argName("skipLines").hasArg().desc(
            "in logger file, the num lines to skip after the header line to get to the first line of data; default = \""
                    + skipLines + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("T").argName("trimTime").hasArg().desc(
            "trim (ring-buffer loop) time (sec) (trimTime=0 for indefinite); default = \"" + trimTime + "\"")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("n").argName("nanVal").hasArg()
            .desc("replace NAN with this; default = \"" + nanVal + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("i").argName("leadingID").hasArg()
            .desc("leading ID string (IWG1 compliant)").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("s").argName("sourceName").hasArg()
            .desc("CloudTurbine source name; default = \"" + SourceName + "\"").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("H").argName("HeaderLine").hasArg().desc(
            "optional CSV list of channel names; if not supplied, this is read from the first line in the logger file")
            .build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("l").argName("loggerfilename").hasArg()
            .desc("name of the logger data file; required argument").build();
    options.addOption(outputFolderOption);
    outputFolderOption = Option.builder("o").longOpt("outputfolder").argName("folder").hasArg()
            .desc("Location of output files (source is created under this folder); default = " + CTrootfolder)
            .build();
    options.addOption(outputFolderOption);

    //
    // 2. Parse command line options
    //
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException exp) {
        // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    //
    // 3. Retrieve the command line values
    //
    if (line.hasOption("help")) {
        // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("CTlogger", options);
        return;
    }
    debug = line.hasOption("x");
    noBackwards = line.hasOption("b");
    gzipmode = line.hasOption("g");
    appendMode = !line.hasOption("a");
    zipmode = !line.hasOption("z");
    newFileMode = line.hasOption("N");
    repeatFetch = line.hasOption("r");
    blockMode = line.hasOption("B");
    storeTime = line.hasOption("t");
    autoflush = Long.parseLong(line.getOptionValue("f", Long.toString(autoflush)));
    pollInterval = Long.parseLong(line.getOptionValue("p", Long.toString(pollInterval)));
    skipLines = Long.parseLong(line.getOptionValue("k", Long.toString(skipLines)));
    trimTime = Double.parseDouble(line.getOptionValue("T", Double.toString(trimTime)));
    nanVal = line.getOptionValue("n", nanVal);
    if (line.hasOption("i")) {
        leadingID = line.getOptionValue("i");
    }
    SourceName = line.getOptionValue("s", SourceName);
    if (line.hasOption("H")) {
        HeaderLine = line.getOptionValue("H");
    }
    if (line.hasOption("l")) {
        loggerFileName = line.getOptionValue("l");
    } else {
        System.err.println("ERROR: you must supply the logger file name.");
        return;
    }
    CTrootfolder = line.getOptionValue("o", CTrootfolder);

    if (!debug) {
        System.err.println("CTlogger: " + loggerFileName + ", CTrootfolder: " + CTrootfolder
                + ", pollInterval: " + pollInterval);
    } else {
        System.err.println("debug = " + debug);
        System.err.println("noBackwards = " + noBackwards);
        System.err.println("gzipmode = " + gzipmode);
        System.err.println("appendMode = " + appendMode);
        System.err.println("zipmode = " + zipmode);
        System.err.println("newFileMode = " + newFileMode);
        System.err.println("repeatFetch = " + repeatFetch);
        System.err.println("blockMode = " + blockMode);
        System.err.println("storeTime = " + storeTime);
        System.err.println("autoflush = " + autoflush);
        System.err.println("pollInterval = " + pollInterval);
        System.err.println("skipLines = " + skipLines);
        System.err.println("trimTime = " + trimTime);
        System.err.println("nanVal = " + nanVal);
        System.err.println("leadingID = " + leadingID);
        System.err.println("SourceName = " + SourceName);
        System.err.println("HeaderLine = " + HeaderLine);
        System.err.println("loggerFileName = " + loggerFileName);
        System.err.println("CTrootfolder = " + CTrootfolder);
    }

    //
    // Run CTlogger
    //
    if (!repeatFetch)
        getData(true); // run once
    else {
        Timer timer = new Timer();
        TimerTask fetchTask = new TimerTask() {
            @Override
            public void run() {
                if (newFileMode)
                    getData(true);
                else if (getData(false)) { // pick up from old data if you can
                    System.err.println("Failed to pick up from old data, refetch from start of file...");
                    boolean status = getData(true);
                    System.err.println("refetch status: " + status);
                }
                if (debug)
                    System.err.println("Waiting for data, pollInterval: " + pollInterval + " sec...");
            };
        };
        // repeatFetch@autoflush interval, convert to msec
        if ((autoflush > 0) && (pollInterval > autoflush))
            pollInterval = autoflush;
        timer.scheduleAtFixedRate(fetchTask, 0, pollInterval * 1000);
    }
}

From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();
    options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert")
            .longOpt("source").hasArg(true).build());
    options.addOption(Option.builder("t").argName("target").desc("the target file to store in")
            .longOpt("target").hasArg(true).build());
    options.addOption(Option.builder("h").desc("print help").build());

    try {/*from www .  j a  va2 s  . c om*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            formatter.printHelp("converter", options);
        }
        File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir")));
        String name = source.getName();
        if (source.isDirectory()) {
            PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter();
            String[] ext = { "properties" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true);
            while (fileIterator.hasNext()) {
                File next = fileIterator.next();
                System.out.println(next);
                String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath());
                System.out.println(s);
                String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0];
                System.out.println("key = " + f);
                Properties p = new Properties();
                try {
                    p.load(new FileReader(next));
                    yamlConverter.addProperties(f, p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            yamlConverter.writeYaml(fileWriter);
            fileWriter.close();
        } else {
            Properties p = new Properties();
            p.load(new FileReader(source));
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter);
            fileWriter.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        formatter.printHelp("converter", options);
    }
}

From source file:bamboo.openhash.fileshare.FileShare.java

public static void main(String[] args) throws Exception {
    PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n");
    ConsoleAppender ca = new ConsoleAppender(pl);
    Logger.getRoot().addAppender(ca);
    Logger.getRoot().setLevel(Level.INFO);

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

    // add t option
    options.addOption("r", "read", false, "read a file from the DHT");
    options.addOption("w", "write", false, "write a file to the DHT");
    options.addOption("g", "gateway", true, "the gateway IP:port");
    options.addOption("k", "key", true, "the key to read a file from");
    options.addOption("f", "file", true, "the file to read or write");
    options.addOption("s", "secret", true, "the secret used to hide data");
    options.addOption("t", "ttl", true, "how long in seconds data should persist");

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

    String gw = null;// w  w w .  java  2  s  .c o  m
    String mode = null;
    String secret = null;
    String ttl = null;
    String key = null;
    String file = null;

    if (cmd.hasOption("r")) {
        mode = "read";
    }
    if (cmd.hasOption("w")) {
        mode = "write";
    }
    if (cmd.hasOption("g")) {
        gw = cmd.getOptionValue("g");
    }
    if (cmd.hasOption("k")) {
        key = cmd.getOptionValue("k");
    }
    if (cmd.hasOption("f")) {
        file = cmd.getOptionValue("f");
    }
    if (cmd.hasOption("s")) {
        secret = cmd.getOptionValue("s");
    }
    if (cmd.hasOption("t")) {
        ttl = cmd.getOptionValue("t");
    }

    if (mode == null) {
        System.err.println("ERROR: either --read or --write is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (gw == null) {
        System.err.println("ERROR: --gateway is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (file == null) {
        System.err.println("ERROR: --file is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    if (secret == null) {
        System.err.println("ERROR: --secret is required");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fileshare", options);
        System.exit(1);
    }

    StringBuffer sbuf = new StringBuffer(1000);
    sbuf.append("<sandstorm>\n");
    sbuf.append("<global>\n");
    sbuf.append("<initargs>\n");
    sbuf.append("node_id localhost:3630\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</global>\n");
    sbuf.append("<stages>\n");
    sbuf.append("<GatewayClient>\n");
    sbuf.append("class bamboo.dht.GatewayClient\n");
    sbuf.append("<initargs>\n");
    sbuf.append("debug_level 0\n");
    sbuf.append("gateway " + gw + "\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</GatewayClient>\n");
    sbuf.append("\n");
    sbuf.append("<FileShare>\n");
    sbuf.append("class bamboo.openhash.fileshare.FileShare\n");
    sbuf.append("<initargs>\n");
    sbuf.append("debug_level 0\n");
    sbuf.append("secret " + secret + "\n");
    sbuf.append("mode " + mode + "\n");
    if (mode.equals("write")) {
        if (ttl == null) {
            System.err.println("ERROR: --ttl is required for write mode");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("fileshare", options);
            System.exit(1);
        }

        sbuf.append("ttl " + ttl + "\n");
        sbuf.append("file " + file + "\n");
    } else {
        if (key == null) {
            System.err.println("ERROR: --key is required for write mode");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("fileshare", options);
            System.exit(1);
        }

        sbuf.append("key " + key + "\n");
        sbuf.append("file " + file + "\n");
    }
    sbuf.append("client_stage_name GatewayClient\n");
    sbuf.append("</initargs>\n");
    sbuf.append("</FileShare>\n");
    sbuf.append("</stages>\n");
    sbuf.append("</sandstorm>\n");
    ASyncCore acore = new bamboo.lss.ASyncCoreImpl();
    DustDevil dd = new DustDevil();
    dd.set_acore_instance(acore);
    dd.main(new CharArrayReader(sbuf.toString().toCharArray()));
    acore.async_main();
}