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:brut.apktool.Main.java

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

    // set verbosity default
    Verbosity verbosity = Verbosity.NORMAL;

    // cli parser
    CommandLineParser parser = new PosixParser();
    CommandLine commandLine = null;/* www  . j  a  v a 2s . c  om*/

    // load options
    _Options();

    try {
        commandLine = parser.parse(allOptions, args, false);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        usage(commandLine);
        return;
    }

    // check for verbose / quiet
    if (commandLine.hasOption("-v") || commandLine.hasOption("--verbose")) {
        verbosity = Verbosity.VERBOSE;
    } else if (commandLine.hasOption("-q") || commandLine.hasOption("--quiet")) {
        verbosity = Verbosity.QUIET;
    }
    setupLogging(verbosity);

    // check for advance mode
    if (commandLine.hasOption("advance") || commandLine.hasOption("advanced")) {
        setAdvanceMode(true);
    }

    // @todo use new ability of apache-commons-cli to check hasOption for non-prefixed items
    boolean cmdFound = false;
    for (String opt : commandLine.getArgs()) {
        if (opt.equalsIgnoreCase("d") || opt.equalsIgnoreCase("decode")) {
            cmdDecode(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("b") || opt.equalsIgnoreCase("build")) {
            cmdBuild(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("if") || opt.equalsIgnoreCase("install-framework")) {
            cmdInstallFramework(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("publicize-resources")) {
            cmdPublicizeResources(commandLine);
            cmdFound = true;
        }
    }

    // if no commands ran, run the version / usage check.
    if (cmdFound == false) {
        if (commandLine.hasOption("version") || commandLine.hasOption("version")) {
            _version();
        } else {
            usage(commandLine);
        }
    }
}

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;// w ww  . j ava2 s.co m
    }
    // Configure the command line options parser
    Options options = new Options();
    options.addOption("h", false, "help");
    options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https.");
    options.addOption("keystore", true, "Filepath for PokerFace certificate keystore.");
    options.addOption("storepass", true, "The store password of the keystore.");
    options.addOption("keypass", true, "The key password of the keystore.");
    options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target
    options.addOption("servercpu", true, "Number of cores the server should use.");
    options.addOption("targetcpu", true, "Number of cores the http targets should use.");
    options.addOption("trustany", false, "Ignore certificate identity errors from target servers.");
    options.addOption("files", true, "Filepath to a directory of static files.");
    options.addOption("config", true, "Path for XML Configuration file.");
    options.addOption("scripts", true, "Filepath for root scripts directory.");
    options.addOption("library", true, "JavaScript library to load into global context.");
    options.addOption("watch", false, "Dynamically watch scripts directory for changes.");
    options.addOption("dynamicTargetScripting", false,
            "WARNING! This option allows scripts to redirect requests to *any* other remote server.");

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

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

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

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

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

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

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

From source file:com.thed.zapi.cloud.sample.CycleExecutionReportByVersion.java

public static void main(String[] args) throws JSONException, URISyntaxException, ParseException, IOException {

    String API_GET_EXECUTIONS = "{SERVER}/public/rest/api/1.0/executions/search/cycle/";
    String API_GET_CYCLES = "{SERVER}/public/rest/api/1.0/cycles/search?";
    // Delimiter used in CSV file
    final String NEW_LINE_SEPARATOR = "\n";
    final String fileName = "F:\\cycleExecutionReport.csv";

    /** Declare JIRA,Zephyr URL,access and secret Keys */
    // JIRA Cloud URL of the instance
    String jiraBaseURL = "https://demo.atlassian.net";
    // Replace zephyr baseurl <ZAPI_Cloud_URL> shared with the user for ZAPI Cloud Installation
    String zephyrBaseUrl = "<ZAPI_Cloud_URL>";
    // zephyr accessKey , we can get from Addons >> zapi section
    String accessKey = "YjE2MjdjMGEtNzExNy0zYjY1LWFkMzQtNjcwMDM3OTljFkbWluIGFkbWlu";
    // zephyr secretKey , we can get from Addons >> zapi section
    String secretKey = "qufnbimi96Ob2hq3ISF08yZ8Qw4c1eHGeGlk";

    /** Declare parameter values here */
    String userName = "admin";
    String versionId = "-1";
    String projectId = "10100";
    String projectName = "Support";
    String versionName = "Unscheduled";

    ZFJCloudRestClient client = ZFJCloudRestClient.restBuilder(zephyrBaseUrl, accessKey, secretKey, userName)
            .build();//  w ww.j a  v  a2  s  .  c  om
    /**
     * Get List of Cycles by Project and Version
     */

    final String getCyclesUri = API_GET_CYCLES.replace("{SERVER}", zephyrBaseUrl) + "projectId=" + projectId
            + "&versionId=" + versionId;

    Map<String, String> cycles = getCyclesByProjectVersion(getCyclesUri, client, accessKey);
    // System.out.println("cycles :"+ cycles.toString());

    /**
     * Iterating over the Cycles and writing the report to CSV
     * 
     */

    FileWriter fileWriter = null;
    System.out.println("Writing CSV file.....");
    try {
        fileWriter = new FileWriter(fileName);

        // Write the CSV file header

        fileWriter.append("Cycle Execution Report By Version and Project");
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("PROJECT:" + "," + projectName);
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("VERSION:" + "," + versionName);
        fileWriter.append(NEW_LINE_SEPARATOR);

        JSONArray executions;
        int totalUnexecutedCount = 0;
        int totalExecutionCount = 0;

        for (String key : cycles.keySet()) {
            int executionCount = 0;
            int unexecutedCount = 0;
            final String getExecutionsUri = API_GET_EXECUTIONS.replace("{SERVER}", zephyrBaseUrl) + key
                    + "?projectId=" + projectId + "&versionId=" + versionId;
            fileWriter.append("Cycle:" + "," + cycles.get(key));
            fileWriter.append(NEW_LINE_SEPARATOR);
            executions = getExecutionsByCycleId(getExecutionsUri, client, accessKey);
            // System.out.println("executions :" + executions.toString());

            HashMap<String, Integer> counter = new HashMap<String, Integer>();

            String[] statusName = new String[executions.length()];
            for (int i = 0; i < executions.length(); i++) {
                JSONObject executionObj = executions.getJSONObject(i).getJSONObject("execution");
                // System.out.println("executionObj
                // "+executionObj.toString());
                JSONObject statusObj = executionObj.getJSONObject("status");
                // System.out.println("statusObj :"+statusObj.toString());
                statusName[i] = statusObj.getString("name");
            }

            if (statusName.length != 0) {
                // System.out.println(statusName.toString());
                for (String a : statusName) {
                    if (counter.containsKey(a)) {
                        int oldValue = counter.get(a);
                        counter.put(a, oldValue + 1);
                    } else {
                        counter.put(a, 1);
                    }
                }
                for (String status : counter.keySet()) {
                    fileWriter.append(" " + "," + " " + "," + status + "," + counter.get(status));
                    fileWriter.append(NEW_LINE_SEPARATOR);
                    if (status.equalsIgnoreCase("UNEXECUTED")) {
                        unexecutedCount += counter.get(status);
                    } else {
                        executionCount += counter.get(status);
                    }

                }
            }
            totalExecutionCount += executionCount;
            totalUnexecutedCount += unexecutedCount;

            fileWriter.append(NEW_LINE_SEPARATOR);
        }

        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("TOTAL CYCLES:" + "," + cycles.size());
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("TOTAL EXECUTIONS:" + "," + totalExecutionCount);
        fileWriter.append(NEW_LINE_SEPARATOR);
        fileWriter.append("TOTAL ASSIGNED:" + "," + (totalUnexecutedCount + totalExecutionCount));

        System.out.println("CSV file was created successfully !!!");
    } catch (Exception e) {
        System.out.println("Error in CsvFileWriter !!!");
        e.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter !!!");
            e.printStackTrace();
        }
    }

}

From source file:MainClass.java

License:asdf

public static void main(String[] args) throws Exception {
    String characterName = "asdf";
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(new File("r.xml"));
    List actList = document.getRootElement().getChildren("ACT");
    allDone: for (int act = 0; act < actList.size(); act++) {
        List sceneList = ((Element) actList.get(act)).getChildren("SCENE");
        for (int scene = 0; scene < sceneList.size(); scene++) {
            List speechList = ((Element) sceneList.get(scene)).getChildren("SPEECH");
            for (int speech = 0; speech < speechList.size(); speech++) {
                if (characterName
                        .equalsIgnoreCase(((Element) speechList.get(speech)).getChildText("SPEAKER"))) {
                    System.out.println(characterName);
                    break allDone;
                }/*w w  w.  j  a va2 s  .  c o m*/
            }
        }
    }
}

From source file:com.opensoc.json.serialization.JSONKafkaSerializer.java

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

    //String Input = "/home/kiran/git/opensoc-streaming/OpenSOC-Common/BroExampleOutput";
    String Input = "/tmp/test";

    BufferedReader reader = new BufferedReader(new FileReader(Input));

    // String jsonString =
    // "{\"dns\":{\"ts\":[14.0,12,\"kiran\"],\"uid\":\"abullis@mail.csuchico.edu\",\"id.orig_h\":\"10.122.196.204\", \"endval\":null}}";
    String jsonString = "";// reader.readLine();
    JSONParser parser = new JSONParser();
    JSONObject json = null;//w w w  .  jav a2s . c o m
    int count = 1;

    if (args.length > 0)
        count = Integer.parseInt(args[0]);

    //while ((jsonString = reader.readLine()) != null) 
    jsonString = reader.readLine();
    {
        try {
            json = (JSONObject) parser.parse(jsonString);
            System.out.println(json);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String jsonString2 = null;

        JSONKafkaSerializer ser = new JSONKafkaSerializer();

        for (int i = 0; i < count; i++) {
            byte[] bytes = ser.toBytes(json);

            jsonString2 = ((JSONObject) ser.fromBytes(bytes)).toJSONString();
        }
        System.out.println((jsonString2));
        System.out.println(jsonString2.equalsIgnoreCase(json.toJSONString()));
    }

}

From source file:io.anserini.search.SearchTweets.java

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

    options.addOption(new Option(RM3_OPTION, "apply relevance feedback with rm3"));

    options.addOption(/*from www . j  a v  a  2s.  c o m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("similarity").hasArg()
            .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_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(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchTweets.class.getName(), options);
        System.exit(-1);
    }

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

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    String topicsFile = cmdline.getOptionValue(QUERIES_OPTION);

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String similarity = "LM";
    if (cmdline.hasOption(SIMILARITY_OPTION)) {
        similarity = cmdline.getOptionValue(SIMILARITY_OPTION);
    }

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexLocation.getAbsolutePath())));
    IndexSearcher searcher = new IndexSearcher(reader);

    if (similarity.equalsIgnoreCase("BM25")) {
        searcher.setSimilarity(new BM25Similarity());
    } else if (similarity.equalsIgnoreCase("LM")) {
        searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
    }

    MicroblogTopicSet topics = MicroblogTopicSet.fromFile(new File(topicsFile));
    for (MicroblogTopic topic : topics) {
        Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(),
                true, true);
        Query query = AnalyzerUtils.buildBagOfWordsQuery(StatusField.TEXT.name, IndexTweets.ANALYZER,
                topic.getQuery());

        TopDocs rs = searcher.search(query, filter, numResults);

        RerankerContext context = new RerankerContext(searcher, query, topic.getQuery(), filter);
        RerankerCascade cascade = new RerankerCascade(context);

        if (cmdline.hasOption(RM3_OPTION)) {
            cascade.add(new Rm3Reranker(IndexTweets.ANALYZER, StatusField.TEXT.name));
            cascade.add(new RemoveRetweetsTemporalTiebreakReranker());
        } else {
            cascade.add(new RemoveRetweetsTemporalTiebreakReranker());
        }

        ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));

        for (int i = 0; i < docs.documents.length; i++) {
            String qid = topic.getId().replaceFirst("^MB0*", "");
            out.println(String.format("%s Q0 %s %d %f %s", qid,
                    docs.documents[i].getField(StatusField.ID.name).numericValue(), (i + 1), docs.scores[i],
                    runtag));
        }
    }
    reader.close();
    out.close();
}

From source file:com.apkTool.Main.java

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

    /**/* w w  w. j av  a2  s  . c om*/
     * ?apk 
     * ?.apk  
     *  + ExtDataInput.javaskipCheckChunkTypeInt 73
     *
     * .apk 
     * qq.apk  
     *  + ResTypeSpec.javaaddResSpec78
     *
     * .apk 
     * ?.apk
     */

    // ??
    args = new String[] { "d", "-f", "ApkTool/apk/qq.apk", "-o", "ApkTool/out" };

    // 
    // args = new String[]{"b", "out", "-o", "apk/zhifubao_build.apk"};

    // set verbosity default
    Verbosity verbosity = Verbosity.NORMAL;

    // cli parser
    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    // load options
    _Options();

    try {
        commandLine = parser.parse(allOptions, args, false);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        usage();
        return;
    }

    // check for verbose / quiet
    if (commandLine.hasOption("-v") || commandLine.hasOption("--verbose")) {
        verbosity = Verbosity.VERBOSE;
    } else if (commandLine.hasOption("-q") || commandLine.hasOption("--quiet")) {
        verbosity = Verbosity.QUIET;
    }
    setupLogging(verbosity);

    // check for advance mode
    if (commandLine.hasOption("advance") || commandLine.hasOption("advanced")) {
        setAdvanceMode(true);
    }

    // @todo use new ability of apache-commons-cli to check hasOption for non-prefixed items
    boolean cmdFound = false;
    for (String opt : commandLine.getArgs()) {
        if (opt.equalsIgnoreCase("d") || opt.equalsIgnoreCase("decode")) {
            cmdDecode(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("b") || opt.equalsIgnoreCase("build")) {
            cmdBuild(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("if") || opt.equalsIgnoreCase("install-framework")) {
            cmdInstallFramework(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("empty-framework-dir")) {
            cmdEmptyFrameworkDirectory(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("publicize-resources")) {
            cmdPublicizeResources(commandLine);
            cmdFound = true;
        }
    }

    // if no commands ran, run the version / usage check.
    if (!cmdFound) {
        if (commandLine.hasOption("version")) {
            _version();
        } else {
            usage();
        }
    }
}

From source file:com.linkedin.helix.controller.HelixControllerMain.java

public static void main(String[] args) throws Exception {
    // read the config;
    // check if the this process is the master wait indefinitely
    // other approach is always process the events but when updating the zk
    // check if this is master.
    // This is difficult to get right
    // get the clusters to manage
    // for each cluster create a manager
    // add the respective listeners for each manager
    CommandLine cmd = processCommandLineArgs(args);
    String zkConnectString = cmd.getOptionValue(zkServerAddress);
    String clusterName = cmd.getOptionValue(cluster);
    String controllerMode = STANDALONE;
    String controllerName = null;
    int propertyTransServicePort = -1;

    if (cmd.hasOption(mode)) {
        controllerMode = cmd.getOptionValue(mode);
    }//from ww w .ja  v  a2s  .  c  o m

    if (cmd.hasOption(propertyTransferServicePort)) {
        propertyTransServicePort = Integer.parseInt(cmd.getOptionValue(propertyTransferServicePort));
    }
    if (controllerMode.equalsIgnoreCase(DISTRIBUTED) && !cmd.hasOption(name)) {
        throw new IllegalArgumentException("A unique cluster controller name is required in DISTRIBUTED mode");
    }

    controllerName = cmd.getOptionValue(name);

    // Espresso_driver.py will consume this
    logger.info("Cluster manager started, zkServer: " + zkConnectString + ", clusterName:" + clusterName
            + ", controllerName:" + controllerName + ", mode:" + controllerMode);

    if (propertyTransServicePort > 0) {
        ZKPropertyTransferServer.getInstance().init(propertyTransServicePort, zkConnectString);
    }

    HelixManager manager = startHelixController(zkConnectString, clusterName, controllerName, controllerMode);
    try {
        Thread.currentThread().join();
    } catch (InterruptedException e) {
        logger.info("controller:" + controllerName + ", " + Thread.currentThread().getName() + " interrupted");
    } finally {
        manager.disconnect();
        ZKPropertyTransferServer.getInstance().shutdown();
    }

}

From source file:cc.twittertools.search.local.RunQueries.java

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

    options.addOption(/* w w  w .j  av  a2s  .  c o m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("similarity").hasArg()
            .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    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(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueries.class.getName(), options);
        System.exit(-1);
    }

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

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    String topicsFile = cmdline.getOptionValue(QUERIES_OPTION);

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String similarity = "LM";
    if (cmdline.hasOption(SIMILARITY_OPTION)) {
        similarity = cmdline.getOptionValue(SIMILARITY_OPTION);
    }

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation));
    IndexSearcher searcher = new IndexSearcher(reader);

    if (similarity.equalsIgnoreCase("BM25")) {
        searcher.setSimilarity(new BM25Similarity());
    } else if (similarity.equalsIgnoreCase("LM")) {
        searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
    }

    QueryParser p = new QueryParser(Version.LUCENE_43, StatusField.TEXT.name, IndexStatuses.ANALYZER);

    TrecTopicSet topics = TrecTopicSet.fromFile(new File(topicsFile));
    for (TrecTopic topic : topics) {
        Query query = p.parse(topic.getQuery());
        Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(),
                true, true);

        TopDocs rs = searcher.search(query, filter, numResults);

        int i = 1;
        for (ScoreDoc scoreDoc : rs.scoreDocs) {
            Document hit = searcher.doc(scoreDoc.doc);
            out.println(String.format("%s Q0 %s %d %f %s", topic.getId(),
                    hit.getField(StatusField.ID.name).numericValue(), i, scoreDoc.score, runtag));
            if (verbose) {
                out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
            }
            i++;
        }
    }
    reader.close();
    out.close();
}

From source file:net.minecraftforge.fml.common.patcher.GenDiffSet.java

public static void main(String[] args) throws IOException {
    String sourceJar = args[0]; //Clean Vanilla jar minecraft.jar or minecraft_server.jar
    String targetDir = args[1]; //Directory containing obfed output classes, typically mcp/reobf/minecraft
    String deobfData = args[2]; //Path to FML's deobfusication_data.lzma
    String outputDir = args[3]; //Path to place generated .binpatch
    String killTarget = args[4]; //"true" if we should destroy the target file if it generated a successful .binpatch

    LogManager.getLogger("GENDIFF").log(Level.INFO,
            String.format("Creating patches at %s for %s from %s", outputDir, sourceJar, targetDir));
    Delta delta = new Delta();
    FMLDeobfuscatingRemapper remapper = FMLDeobfuscatingRemapper.INSTANCE;
    remapper.setupLoadOnly(deobfData, false);
    JarFile sourceZip = new JarFile(sourceJar);
    boolean kill = killTarget.equalsIgnoreCase("true");

    File f = new File(outputDir);
    f.mkdirs();/* w  ww.jav a  2  s  . co m*/

    for (String name : remapper.getObfedClasses()) {
        //            Logger.getLogger("GENDIFF").info(String.format("Evaluating path for data :%s",name));
        String fileName = name;
        String jarName = name;
        if (RESERVED_NAMES.contains(name.toUpperCase(Locale.ENGLISH))) {
            fileName = "_" + name;
        }
        File targetFile = new File(targetDir, fileName.replace('/', File.separatorChar) + ".class");
        jarName = jarName + ".class";
        if (targetFile.exists()) {
            String sourceClassName = name.replace('/', '.');
            String targetClassName = remapper.map(name).replace('/', '.');
            JarEntry entry = sourceZip.getJarEntry(jarName);
            byte[] vanillaBytes = toByteArray(sourceZip, entry);
            byte[] patchedBytes = Files.toByteArray(targetFile);

            byte[] diff = delta.compute(vanillaBytes, patchedBytes);

            ByteArrayDataOutput diffOut = ByteStreams.newDataOutput(diff.length + 50);
            // Original name
            diffOut.writeUTF(name);
            // Source name
            diffOut.writeUTF(sourceClassName);
            // Target name
            diffOut.writeUTF(targetClassName);
            // exists at original
            diffOut.writeBoolean(entry != null);
            if (entry != null) {
                diffOut.writeInt(Hashing.adler32().hashBytes(vanillaBytes).asInt());
            }
            // length of patch
            diffOut.writeInt(diff.length);
            // patch
            diffOut.write(diff);

            File target = new File(outputDir, targetClassName + ".binpatch");
            target.getParentFile().mkdirs();
            Files.write(diffOut.toByteArray(), target);
            Logger.getLogger("GENDIFF").info(String.format("Wrote patch for %s (%s) at %s", name,
                    targetClassName, target.getAbsolutePath()));
            if (kill) {
                targetFile.delete();
                Logger.getLogger("GENDIFF").info(String.format("  Deleted target: %s", targetFile.toString()));
            }
        }
    }
    sourceZip.close();
}