Example usage for java.lang String equalsIgnoreCase

List of usage examples for java.lang String equalsIgnoreCase

Introduction

In this page you can find the example usage for java.lang String equalsIgnoreCase.

Prototype

public boolean equalsIgnoreCase(String anotherString) 

Source Link

Document

Compares this String to another String , ignoring case considerations.

Usage

From source file:com.cc.apptroy.baksmali.main.java

/**
 * Run!//from   www. j a  va  2 s . c  o  m
 */
public static void main(String[] args) throws IOException {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    baksmaliOptions options = new baksmaliOptions();

    boolean disassemble = true;
    boolean doDump = false;
    String dumpFileName = null;
    boolean setBootClassPath = false;

    String[] remainingArgs = commandLine.getArgs();
    Option[] clOptions = commandLine.getOptions();

    for (int i = 0; i < clOptions.length; i++) {
        Option option = clOptions[i];
        String opt = option.getOpt();

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < clOptions.length) {
                if (clOptions[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            options.outputDirectory = commandLine.getOptionValue("o");
            break;
        case 'p':
            options.noParameterRegisters = true;
            break;
        case 'l':
            options.useLocalsDirective = true;
            break;
        case 's':
            options.useSequentialLabels = true;
            break;
        case 'b':
            options.outputDebugInfo = false;
            break;
        case 'd':
            options.bootClassPathDirs.add(option.getValue());
            break;
        case 'f':
            options.addCodeOffsets = true;
            break;
        case 'r':
            String[] values = commandLine.getOptionValues('r');
            int registerInfo = 0;

            if (values == null || values.length == 0) {
                registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST;
            } else {
                for (String value : values) {
                    if (value.equalsIgnoreCase("ALL")) {
                        registerInfo |= baksmaliOptions.ALL;
                    } else if (value.equalsIgnoreCase("ALLPRE")) {
                        registerInfo |= baksmaliOptions.ALLPRE;
                    } else if (value.equalsIgnoreCase("ALLPOST")) {
                        registerInfo |= baksmaliOptions.ALLPOST;
                    } else if (value.equalsIgnoreCase("ARGS")) {
                        registerInfo |= baksmaliOptions.ARGS;
                    } else if (value.equalsIgnoreCase("DEST")) {
                        registerInfo |= baksmaliOptions.DEST;
                    } else if (value.equalsIgnoreCase("MERGE")) {
                        registerInfo |= baksmaliOptions.MERGE;
                    } else if (value.equalsIgnoreCase("FULLMERGE")) {
                        registerInfo |= baksmaliOptions.FULLMERGE;
                    } else {
                        usage();
                        return;
                    }
                }

                if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) {
                    registerInfo &= ~baksmaliOptions.MERGE;
                }
            }
            options.registerInfo = registerInfo;
            break;
        case 'c':
            String bcp = commandLine.getOptionValue("c");
            if (bcp != null && bcp.charAt(0) == ':') {
                options.addExtraClassPath(bcp);
            } else {
                setBootClassPath = true;
                options.setBootClassPath(bcp);
            }
            break;
        case 'x':
            options.deodex = true;
            break;
        case 'X':
            options.experimental = true;
            break;
        case 'm':
            options.noAccessorComments = true;
            break;
        case 'a':
            options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            options.jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'i':
            String rif = commandLine.getOptionValue("i");
            options.setResourceIdFiles(rif);
            break;
        case 't':
            options.useImplicitReferences = true;
            break;
        case 'e':
            options.dexEntry = commandLine.getOptionValue("e");
            break;
        case 'k':
            options.checkPackagePrivateAccess = true;
            break;
        case 'N':
            disassemble = false;
            break;
        case 'D':
            doDump = true;
            dumpFileName = commandLine.getOptionValue("D");
            break;
        case 'I':
            options.ignoreErrors = true;
            break;
        case 'T':
            options.customInlineDefinitions = new File(commandLine.getOptionValue("T"));
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length != 1) {
        usage();
        return;
    }

    if (options.jobs <= 0) {
        options.jobs = Runtime.getRuntime().availableProcessors();
        if (options.jobs > 6) {
            options.jobs = 6;
        }
    }

    String inputDexFileName = remainingArgs[0];

    File dexFileFile = new File(inputDexFileName);
    if (!dexFileFile.exists()) {
        System.err.println("Can't find the file " + inputDexFileName);
        System.exit(1);
    }

    //Read in and parse the dex file
    DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.dexEntry, options.apiLevel,
            options.experimental);

    if (dexFile.isOdexFile()) {
        if (!options.deodex) {
            System.err.println("Warning: You are disassembling an odex file without deodexing it. You");
            System.err.println("won't be able to re-assemble the results unless you deodex it with the -x");
            System.err.println("option");
            options.allowOdex = true;
        }
    } else {
        options.deodex = false;
    }

    if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) {
        if (dexFile instanceof DexBackedOdexFile) {
            options.bootClassPathEntries = ((DexBackedOdexFile) dexFile).getDependencies();
        } else {
            options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel,
                    options.experimental);
        }
    }

    if (options.customInlineDefinitions == null && dexFile instanceof DexBackedOdexFile) {
        options.inlineResolver = InlineMethodResolver
                .createInlineMethodResolver(((DexBackedOdexFile) dexFile).getOdexVersion());
    }

    boolean errorOccurred = false;
    if (disassemble) {
        errorOccurred = !baksmali.disassembleDexFile(dexFile, options);
    }

    if (doDump) {
        if (dumpFileName == null) {
            dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump");
        }
        dump.dump(dexFile, dumpFileName, options.apiLevel, options.experimental);
    }

    if (errorOccurred) {
        System.exit(1);
    }
}

From source file:com.flaptor.indextank.index.IndexEngine.java

public static void main(String[] args) throws IOException {
    String log4jConfigPath = com.flaptor.util.FileUtil.getFilePathFromClasspath("log4j.properties");
    if (null != log4jConfigPath) {
        org.apache.log4j.PropertyConfigurator.configureAndWatch(log4jConfigPath);
    } else {/*  ww  w  .j  av  a  2  s.  c o m*/
        logger.warn("log4j.properties not found on classpath!");
    }
    // create the parser
    CommandLineParser parser = new PosixParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            printHelp(getOptions(), null);
            System.exit(1);
        }

        File baseDir = new File(line.getOptionValue("dir"));
        int basePort = Integer.parseInt(line.getOptionValue("port", String.valueOf(DEFAULT_BASE_PORT)));
        int boostsSize = Integer.parseInt(line.getOptionValue("boosts", String.valueOf(1)));
        int rtiSize = Integer.parseInt(line.getOptionValue("rti-size", String.valueOf(DEFAULT_RTI_SIZE)));
        boolean loadState = line.hasOption("load-state");

        SuggestValues suggest;
        if (line.hasOption("suggest")) {
            String value = line.getOptionValue("suggest");
            if (value.equalsIgnoreCase("queries")) {
                suggest = SuggestValues.QUERIES;
            } else if (value.equalsIgnoreCase("documents")) {
                suggest = SuggestValues.DOCUMENTS;
            } else {
                throw new IllegalArgumentException(
                        "Invalid value for suggest: can only be \"queries\" or \"documents\".");
            }
        } else {
            suggest = SuggestValues.NO;
        }

        StorageValues storageValue = StorageValues.RAM;
        int bdbCache = 0;
        if (line.hasOption("storage")) {
            String storageType = line.getOptionValue("storage");
            if ("bdb".equals(storageType)) {
                storageValue = StorageValues.BDB;
                bdbCache = Integer
                        .parseInt(line.getOptionValue("bdb-cache", String.valueOf(DEFAULT_BDB_CACHE)));
            } else if ("cassandra".equals(storageType)) {
                storageValue = StorageValues.CASSANDRA;
            } else if ("ram".equals(storageType)) {
                storageValue = StorageValues.RAM;
            } else {
                throw new IllegalArgumentException(
                        "storage has to be 'cassandra', 'bdb' or 'ram'. '" + storageType + "' given.");
            }
        }

        String functions = null;
        if (line.hasOption("functions")) {
            functions = line.getOptionValue("functions");
        }

        String environment;
        String val = line.getOptionValue("environment-prefix", null);
        if (null != val) {
            environment = val;
        } else {
            environment = "";
        }
        logger.info("Command line option 'environment-prefix' set to " + environment);

        boolean facets = line.hasOption("facets");
        logger.info("Command line option 'facets' set to " + facets);
        String indexCode = line.getOptionValue("index-code");
        logger.info("Command line option 'index-code' set to " + indexCode);

        Map<Object, Object> configuration = Maps.newHashMap();

        String configFile = line.getOptionValue("conf-file", null);
        logger.info("Command line option 'conf-file' set to " + configFile);

        if (configFile != null) {
            configuration = (Map<Object, Object>) JSONValue.parse(FileUtil.readFile(new File(configFile)));
        }
        IndexEngine ie = new IndexEngine(baseDir, basePort, rtiSize, loadState, boostsSize, suggest,
                storageValue, bdbCache, functions, facets, indexCode, environment, configuration);

        BoostingIndexer indexer = ie.getIndexer();
        DocumentSearcher searcher = ie.getSearcher();
        Suggestor suggestor = ie.getSuggestor();
        DocumentStorage storage = ie.getStorage();

        if (line.hasOption("snippets")) {
            // shouldn't this be set based on storageValue? 
            indexer = new DocumentStoringIndexer(indexer, storage);
            ie.setIndexer(indexer);
            searcher = new SnippetSearcher(searcher, storage, ie.getParser());
        }

        if (line.hasOption("didyoumean")) {
            if (suggest != SuggestValues.DOCUMENTS) {
                throw new IllegalArgumentException("didyoumean requires --suggest documents");
            }
            DidYouMeanSuggestor dym = new DidYouMeanSuggestor((TermSuggestor) ie.getSuggestor());
            searcher = new DidYouMeanSearcher(searcher, dym);
        }

        searcher = new TrafficLimitingSearcher(searcher);
        Runtime.getRuntime().addShutdownHook(new ShutdownThread(indexer));

        new SearcherServer(searcher, ie.getParser(), ie.boostsManager, ie.scorer, basePort + 2).start();
        new SuggestorServer(suggestor, basePort + 3).start();
        IndexerServer indexerServer = new IndexerServer(ie, indexer, basePort + 1);
        indexerServer.start();

    } catch (ParseException exp) {
        printHelp(getOptions(), exp.getMessage());
    }

}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;/*from  w ww  .  j ava 2s  .  c  om*/
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:ZipImploder.java

/**
 * Main command line entry point.//from   www .  j a v a  2  s . c o  m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    String zipName = null;
    String jarName = null;
    String manName = null;
    String sourceDir = null;
    String leadDir = null;
    boolean jarActive = false, manActive = false, zipActive = false, sourceDirActive = false,
            leadDirActive = false;
    boolean verbose = false;
    boolean noDirs = false;
    // process arguments
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.charAt(0) == '-') { // switch
            arg = arg.substring(1);
            if (arg.equalsIgnoreCase("jar")) {
                jarActive = true;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("manifest")) {
                jarActive = false;
                manActive = true;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("zip")) {
                zipActive = true;
                manActive = false;
                jarActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("dir")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = true;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("lead")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = true;
            } else if (arg.equalsIgnoreCase("noDirs")) {
                noDirs = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else {
                reportError("Invalid switch - " + arg);
            }
        } else {
            if (jarActive) {
                if (jarName != null) {
                    reportError("Duplicate value - " + arg);
                }
                jarName = arg;
            } else if (manActive) {
                if (manName != null) {
                    reportError("Duplicate value - " + arg);
                }
                manName = arg;
            } else if (zipActive) {
                if (zipName != null) {
                    reportError("Duplicate value - " + arg);
                }
                zipName = arg;
            } else if (sourceDirActive) {
                if (sourceDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                sourceDir = arg;
            } else if (leadDirActive) {
                if (leadDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                leadDir = arg;
            } else {
                reportError("Too many parameters - " + arg);
            }
        }
    }
    if (sourceDir == null || (zipName == null && jarName == null)) {
        reportError("Missing parameters");
    }
    if (manName != null && zipName != null) {
        reportError("Manifests not supported on ZIP files");
    }
    if (leadDir == null) {
        leadDir = new File(sourceDir).getAbsolutePath().replace('\\', '/') + '/';
    }
    if (verbose) {
        System.out.println("Effective command: " + ZipImploder.class.getName()
                + (jarName != null ? " -jar " + jarName + (manName != null ? " -manifest " + manName : "") : "")
                + (zipName != null ? " -zip " + zipName : "") + " -dir " + sourceDir + " -lead " + leadDir
                + (noDirs ? " -noDirs" : "") + (verbose ? " -verbose" : ""));
    }
    try {
        ZipImploder zi = new ZipImploder(verbose);
        if (leadDir != null) {
            zi.setBaseDir(leadDir);
        }
        if (manName != null) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(manName));
            try {
                zi.setManifest(new Manifest(bis));
            } finally {
                bis.close();
            }
        }
        zi.setIncludeDirs(!noDirs);
        zi.process(zipName, jarName, sourceDir);
        if (verbose) {
            System.out.println("\nDone Directories=" + zi.getDirCount() + " Files=" + zi.getFileCount());
        }
    } catch (IOException ioe) {
        System.err.println("Exception - " + ioe.getMessage());
        // ioe.printStackTrace(); // *** debug ***
        System.exit(2);
    }
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public static void main(String[] args) {
    int i = 0;// w ww. j  a v  a 2 s .co  m
    for (String s : args) {
        if (s.equalsIgnoreCase("-dir")) {
            downloadDir = args[i + 1];
            if (!new File(downloadDir).exists()) {
                try {
                    new File(downloadDir).mkdir();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    progress = "Failed to create download directory";
                    fail = "Errors occurred; see console for details";
                    launcher.paintImmediately(0, 0, width, height);
                }
            }
        }
        i += 1;
    }
    try {
        JSONObject info = ((JSONObject) new JSONParser()
                .parse(new InputStreamReader(Launcher.class.getResourceAsStream("/gameinfo.json"))));
        NAME = (String) info.get("name");
        FOLDER_NAME = "." + NAME.toLowerCase();
        JSON_LOCATION = (String) info.get("resource-info");
    } catch (Exception ex) {
        ex.printStackTrace();
        progress = "Failed to retrieve program information!";
        fail = "Errors occurred; see log for details";
        createExceptionLog(ex);
        launcher.paintImmediately(0, 0, width, height);
    }

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

From source file:IndexService.Indexer.java

public static void main(String[] args) throws IOException {
    System.out.println("input cmd:   indexdir  idx  type  startvalue  endvalue");
    String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
    StringTokenizer st = new StringTokenizer(str);
    String indexdir = st.nextToken();
    int idx = Integer.parseInt(st.nextToken());
    String type = st.nextToken();
    String startvalue = st.nextToken();
    String endvalue = null;/*from www .  j av  a2s  .c o  m*/
    if (st.hasMoreTokens())
        endvalue = st.nextToken();
    else
        endvalue = startvalue;
    ArrayList<IRecord.IFValue> values = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values.add(new IRecord.IFValue(Byte.parseByte(startvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values.add(new IRecord.IFValue(Short.parseShort(startvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values.add(new IRecord.IFValue(Integer.parseInt(startvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values.add(new IRecord.IFValue(Long.parseLong(startvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values.add(new IRecord.IFValue(Float.parseFloat(startvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values.add(new IRecord.IFValue(Double.parseDouble(startvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values.add(new IRecord.IFValue(startvalue, idx));
    ArrayList<IRecord.IFValue> values1 = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values1.add(new IRecord.IFValue(Byte.parseByte(endvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values1.add(new IRecord.IFValue(Short.parseShort(endvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values1.add(new IRecord.IFValue(Integer.parseInt(endvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values1.add(new IRecord.IFValue(Long.parseLong(endvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values1.add(new IRecord.IFValue(Float.parseFloat(endvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values1.add(new IRecord.IFValue(Double.parseDouble(endvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values1.add(new IRecord.IFValue(endvalue, idx));
    Indexer indexer = new Indexer();
    List<IRecord> recs = indexer.getRange(indexdir, null, values, values1, 100, null, -1);
    for (IRecord rec : recs) {
        rec.show();
    }

}

From source file:edu.cuhk.hccl.cmd.AppSearchEngine.java

public static void main(String[] args) throws IOException {

    // Get parameters
    CommandLineParser parser = new BasicParser();
    Options options = createOptions();/*from   w  w  w.  j a v  a  2 s  .  c o  m*/

    File dataFolder = null;
    String queryStr = null;
    int topK = 0;
    File resultFile = null;
    String queryType = null;
    File similarityFile = null;

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

        dataFolder = new File(line.getOptionValue('d'));
        queryStr = line.getOptionValue('q');
        queryType = line.getOptionValue('t');

        topK = Integer.parseInt(line.getOptionValue('k'));
        resultFile = new File(line.getOptionValue('f'));
        similarityFile = new File(line.getOptionValue('s'));

        if (line.hasOption('m')) {
            String modelPath = line.getOptionValue('m');

            if (queryType.equalsIgnoreCase("WordVector")) {
                expander = new WordVectorExpander(modelPath);
            } else if (queryType.equalsIgnoreCase("WordNet")) {
                expander = new WordNetExpander(modelPath);
            } else {
                System.out.println("Please choose a correct expander: WordNet or WordVector!");
                System.exit(-1);
            }
        }

    } catch (ParseException exp) {
        System.out.println("Error in parameters: \n" + exp.getMessage());
        System.exit(-1);
    }

    // Create Index
    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory index = createIndex(dataFolder, analyzer);

    // Build query
    Query query = buildQuery(analyzer, queryStr, queryType);

    // Search index for topK hits
    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopScoreDocCollector collector = TopScoreDocCollector.create(topK, true);
    searcher.search(query, collector);
    ScoreDoc[] hits = collector.topDocs().scoreDocs;

    // Show search results
    System.out.println("\n[INFO] " + hits.length + " hits were returned:");
    List<String> hitLines = new ArrayList<String>();

    for (int i = 0; i < hits.length; i++) {
        int docId = hits[i].doc;
        Document d = searcher.doc(docId);

        String line = (i + 1) + "\t" + d.get(PATH_FIELD) + "\t" + hits[i].score;

        System.out.println(line);

        hitLines.add(line);
    }

    // Compute cosine similarity between documents
    List<String> simLines = new ArrayList<String>();
    for (int m = 0; m < hits.length; m++) {
        int doc1 = hits[m].doc;
        Terms terms1 = reader.getTermVector(doc1, CONTENT_FIELD);

        for (int n = m + 1; n < hits.length; n++) {
            int doc2 = hits[n].doc;
            Terms terms2 = reader.getTermVector(doc2, CONTENT_FIELD);

            CosineDocumentSimilarity cosine = new CosineDocumentSimilarity(terms1, terms2);
            double similarity = cosine.getCosineSimilarity();
            String line = searcher.doc(doc1).get(PATH_FIELD) + "\t" + searcher.doc(doc2).get(PATH_FIELD) + "\t"
                    + similarity;
            simLines.add(line);
        }
    }

    // Release resources
    reader.close();
    if (expander != null) {
        expander.close();
    }

    // Save search results
    System.out.println("\n[INFO] Search results are saved in file: " + resultFile.getPath());
    FileUtils.writeLines(resultFile, hitLines, false);

    System.out.println("\n[INFO] Cosine similarities are saved in file: " + similarityFile.getPath());
    FileUtils.writeLines(similarityFile, simLines, false);
}

From source file:InstallJars.java

/**
 * Main command line entry point.// w  ww  .j  a  va 2  s  .c  o  m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    String propName = null;
    boolean expand = true;
    boolean verbose = true;
    boolean run = true;
    String params = "cmd /c java";
    // process arguments
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.charAt(0) == '-') { // switch
            arg = arg.substring(1);
            if (arg.equalsIgnoreCase("quiet")) {
                verbose = false;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
            } else if (arg.equalsIgnoreCase("expand")) {
                expand = true;
            } else if (arg.equalsIgnoreCase("noexpand")) {
                expand = false;
            } else if (arg.equalsIgnoreCase("run")) {
                run = true;
            } else if (arg.equalsIgnoreCase("norun")) {
                run = false;
            } else if (arg.equalsIgnoreCase("java")) {
                run = false;
                if (i < args.length - 1) {
                    params = args[++i];
                }
            } else {
                System.err.println("Invalid switch - " + arg);
                System.exit(1);
            }
        } else {
            if (propName == null) {
                propName = arg;
            } else {
                System.err.println("Too many parameters - " + arg);
                System.exit(1);
            }
        }
    }
    if (propName == null) {
        propName = "InstallJars.properties";
    }
    // do the install
    try {
        InstallJars ij = new InstallJars(expand, verbose, run, propName, params);
        ij.printUsage();
        String cp = ij.install();
        System.out.println("\nRecomended additions to your classpath - " + cp);
    } catch (Exception e) {
        System.err.println("\n" + e.getClass().getName() + ": " + e.getMessage());
        if (verbose) {
            e.printStackTrace(); // *** debug ***
        }
        System.exit(2);
    }
}

From source file:com.imaginary.home.controller.HomeController.java

static public void main(String... args) throws Exception {
    if (args.length < 1) {
        System.err.println("No work");
    }/*from   w w  w.ja  v a 2 s  . c  om*/
    String action = args[0];

    if (action.equalsIgnoreCase("pair")) {
        String name = args[1];
        String endpoint = args[2];
        String pairingToken = args[3];
        String proxyHost = null;
        int proxyPort = 0;

        if (args.length == 6) {
            proxyHost = args[4];
            proxyPort = Integer.parseInt(args[5]);
        }
        HomeController.getInstance().pairService(name, endpoint, proxyHost, proxyPort, pairingToken);
    } else if (action.equalsIgnoreCase("run")) {
        while (true) {
            try {
                Thread.sleep(60000L);
            } catch (InterruptedException e) {
            }
        }
    } else {
        System.err.println("No such action: " + action);
    }
}

From source file:com.jgaap.backend.CLI.java

/**
 * Parses the arguments passed to jgaap from the command line. Will either
 * display the help or run jgaap on an experiment.
 * /*from ww  w . jav  a2s  .  c  o m*/
 * @param args
 *            command line arguments
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption('h')) {
        String command = cmd.getOptionValue('h');
        if (command == null) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.setLeftPadding(5);
            helpFormatter.setWidth(100);
            helpFormatter.printHelp(
                    "jgaap -c [canon canon ...] -es [event] -ec [culler culler ...] -a [analysis] <-d [distance]> -l [file] <-s [file]>",
                    "Welcome to JGAAP the Java Graphical Authorship Attribution Program.\nMore information can be found at http://jgaap.com",
                    options, "Copyright 2013 Evaluating Variation in Language Lab, Duquesne University");
        } else {
            List<Displayable> list = new ArrayList<Displayable>();
            if (command.equalsIgnoreCase("c")) {
                list.addAll(Canonicizers.getCanonicizers());
            } else if (command.equalsIgnoreCase("es")) {
                list.addAll(EventDrivers.getEventDrivers());
            } else if (command.equalsIgnoreCase("ec")) {
                list.addAll(EventCullers.getEventCullers());
            } else if (command.equalsIgnoreCase("a")) {
                list.addAll(AnalysisDrivers.getAnalysisDrivers());
            } else if (command.equalsIgnoreCase("d")) {
                list.addAll(DistanceFunctions.getDistanceFunctions());
            } else if (command.equalsIgnoreCase("lang")) {
                list.addAll(Languages.getLanguages());
            }
            for (Displayable display : list) {
                if (display.showInGUI())
                    System.out.println(display.displayName() + " - " + display.tooltipText());
            }
            if (list.isEmpty()) {
                System.out.println("Option " + command + " was not found.");
                System.out.println("Please use c, es, d, a, or lang");
            }
        }
    } else if (cmd.hasOption('v')) {
        System.out.println("Java Graphical Authorship Attribution Program version 5.2.0");
    } else if (cmd.hasOption("ee")) {
        String eeFile = cmd.getOptionValue("ee");
        String lang = cmd.getOptionValue("lang");
        ExperimentEngine.runExperiment(eeFile, lang);
        System.exit(0);
    } else {
        JGAAP.commandline = true;
        API api = API.getPrivateInstance();
        String documentsFilePath = cmd.getOptionValue('l');
        if (documentsFilePath == null) {
            throw new Exception("No Documents CSV specified");
        }
        List<Document> documents;
        if (documentsFilePath.startsWith(JGAAPConstants.JGAAP_RESOURCE_PACKAGE)) {
            documents = Utils.getDocumentsFromCSV(
                    CSVIO.readCSV(com.jgaap.JGAAP.class.getResourceAsStream(documentsFilePath)));
        } else {
            documents = Utils.getDocumentsFromCSV(CSVIO.readCSV(documentsFilePath));
        }
        for (Document document : documents) {
            api.addDocument(document);
        }
        String language = cmd.getOptionValue("lang", "english");
        api.setLanguage(language);
        String[] canonicizers = cmd.getOptionValues('c');
        if (canonicizers != null) {
            for (String canonicizer : canonicizers) {
                api.addCanonicizer(canonicizer);
            }
        }
        String[] events = cmd.getOptionValues("es");
        if (events == null) {
            throw new Exception("No EventDriver specified");
        }
        for (String event : events) {
            api.addEventDriver(event);
        }
        String[] eventCullers = cmd.getOptionValues("ec");
        if (eventCullers != null) {
            for (String eventCuller : eventCullers) {
                api.addEventCuller(eventCuller);
            }
        }
        String analysis = cmd.getOptionValue('a');
        if (analysis == null) {
            throw new Exception("No AnalysisDriver specified");
        }
        AnalysisDriver analysisDriver = api.addAnalysisDriver(analysis);
        String distanceFunction = cmd.getOptionValue('d');
        if (distanceFunction != null) {
            api.addDistanceFunction(distanceFunction, analysisDriver);
        }
        api.execute();
        List<Document> unknowns = api.getUnknownDocuments();
        OutputStreamWriter outputStreamWriter;
        String saveFile = cmd.getOptionValue('s');
        if (saveFile == null) {
            outputStreamWriter = new OutputStreamWriter(System.out);
        } else {
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(saveFile));
        }
        Writer writer = new BufferedWriter(outputStreamWriter);
        for (Document unknown : unknowns) {
            writer.append(unknown.getFormattedResult(analysisDriver));
        }
        writer.append('\n');
    }
}