Example usage for java.lang String charAt

List of usage examples for java.lang String charAt

Introduction

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

Prototype

public char charAt(int index) 

Source Link

Document

Returns the char value at the specified index.

Usage

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

/**
 * Run!//w w  w  . ja v a 2s . 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:edu.oregonstate.eecs.mcplan.domains.spbj.SpBjSimulator.java

public static void main(final String[] argv) throws IOException {
    final int seed = 43;
    final RandomGenerator rng = new MersenneTwister(seed);
    //      final Deck deck = new InfiniteSpanishDeck( rng );

    // TODO: Debugging code
    final Deque<Card> stacked = new ArrayDeque<Card>();
    for (int i = 0; i < 20; ++i) {
        stacked.push(Card.C_2c);//from   w  w w. j  a v a2  s.  c  o m
        stacked.push(Card.C_2d);
        stacked.push(Card.C_2h);
        stacked.push(Card.C_2s);
    }
    final Deck deck = new StackedDeck(stacked);

    //      final ArrayList<ArrayList<Card>> test_hands = new ArrayList<ArrayList<Card>>();
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_9h, Card.C_2c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6c, Card.C_7h, Card.C_8c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6c, Card.C_7c, Card.C_8c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_6s, Card.C_7s, Card.C_8s ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7c, Card.C_7h, Card.C_7c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7c, Card.C_7c, Card.C_7c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_7s, Card.C_7s, Card.C_7s ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_9c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_6c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c ) ) );
    //      test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_3c, Card.C_2c, Card.C_Ac ) ) );
    //
    //      final ArrayList<ArrayList<Card>> dealer_test_hands = new ArrayList<ArrayList<Card>>();
    //      dealer_test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_Kc ) ) );
    //      dealer_test_hands.add( new ArrayList<Card>( Arrays.asList( Card.C_Kc, Card.C_Ac ) ) );
    //
    //      for( final ArrayList<Card> dealer_cards : dealer_test_hands ) {
    //         for( final ArrayList<Card> cards : test_hands ) {
    //            final SpBjState s = new SpBjState( deck );
    //            s.init();
    //            s.dealer_hand.clear();
    //            s.dealer_hand.addAll( dealer_cards );
    //            s.player_hand.hands.set( 0, cards );
    //            final SpBjSimulator sim = new SpBjSimulator( s );
    //            sim.takeAction( new JointAction<SpBjAction>(
    //               new SpBjAction( new SpBjActionCategory[] { SpBjActionCategory.Pass } ) ) );
    //
    //            System.out.print( "Hand: " );
    //            System.out.print( sim.state().player_hand );
    //            System.out.print( " (" );
    //            final ArrayList<int[]> values = sim.state().player_hand.values();
    //            for( int i = 0; i < values.size(); ++i ) {
    //               if( i > 0 ) {
    //                  System.out.print( ", " );
    //               }
    //               System.out.print( Arrays.toString( values.get( i ) ) );
    //            }
    //            System.out.println( ")" );
    //
    //            System.out.print( "Reward: " );
    //            System.out.println( Arrays.toString( sim.reward() ) );
    //            System.out.print( "Dealer hand: " );
    //            System.out.print( sim.state().dealerHand().toString() );
    //            System.out.print( " (" );
    //            System.out.print( SpBjHand.handValue( sim.state().dealerHand() )[0] );
    //            System.out.println( ")" );
    //            System.out.println( "----------------------------------------" );
    //         }
    //      }

    while (true) {
        final SpBjState s = new SpBjState(deck);
        s.init();
        final SpBjSimulator sim = new SpBjSimulator(s);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (!s.isTerminal()) {
            System.out.print("Dealer showing: ");
            System.out.println(sim.state().dealerUpcard());

            System.out.print("Hand: ");
            System.out.print(sim.state().player_hand);
            System.out.print(" (");
            final ArrayList<int[]> values = sim.state().player_hand.values();
            for (int i = 0; i < values.size(); ++i) {
                if (i > 0) {
                    System.out.print(", ");
                }
                System.out.print(Arrays.toString(values.get(i)));
            }
            System.out.println(")");

            final SpBjActionGenerator actions = new SpBjActionGenerator();
            actions.setState(sim.state(), 0);
            for (final SpBjAction a : Fn.in(actions)) {
                System.out.println(a);
            }

            final String cmd = reader.readLine();
            assert (cmd.length() == sim.state().player_hand.Nhands);
            final SpBjActionCategory[] cat = new SpBjActionCategory[cmd.length()];
            for (int i = 0; i < cmd.length(); ++i) {
                final char c = cmd.charAt(i);
                if ('h' == c) {
                    cat[i] = SpBjActionCategory.Hit;
                } else if ('p' == c) {
                    cat[i] = SpBjActionCategory.Pass;
                } else if ('d' == c) {
                    cat[i] = SpBjActionCategory.Double;
                } else if ('s' == c) {
                    cat[i] = SpBjActionCategory.Split;
                }
            }
            sim.takeAction(new JointAction<SpBjAction>(new SpBjAction(cat)));
        }

        System.out.print("Hand: ");
        System.out.print(sim.state().player_hand);
        System.out.print(" (");
        final ArrayList<int[]> values = sim.state().player_hand.values();
        for (int i = 0; i < values.size(); ++i) {
            if (i > 0) {
                System.out.print(", ");
            }
            System.out.print(Arrays.toString(values.get(i)));
        }
        System.out.println(")");

        System.out.print("Reward: ");
        System.out.println(Arrays.toString(sim.reward()));
        System.out.print("Dealer hand: ");
        System.out.print(sim.state().dealerHand().toString());
        System.out.print(" (");
        System.out.print(SpBjHand.handValue(sim.state().dealerHand())[0]);
        System.out.println(")");
        System.out.println("----------------------------------------");
    }
}

From source file:bmsi.util.UnaryPredicate.java

public static void main(String[] argv) throws IOException {
    String filea = argv[argv.length - 2];
    String fileb = argv[argv.length - 1];
    String[] a = slurp(filea);//from ww w  . j a v  a  2  s  .  co  m
    String[] b = slurp(fileb);
    Diff d = new Diff(a, b);
    char style = 'n';
    d.heuristic = false;
    for (int i = 0; i < argv.length - 2; ++i) {
        String f = argv[i];
        if (f.startsWith("-")) {
            for (int j = 1; j < f.length(); ++j) {
                switch (f.charAt(j)) {
                case 'H': // heuristic on
                    d.heuristic = true;
                    break;
                case 'e': // Ed style
                    style = 'e';
                    break;
                case 'c': // Context diff
                    style = 'c';
                    break;
                case 'u':
                    style = 'u';
                    break;
                }
            }
        }
    }
    boolean reverse = style == 'e';
    Diff.Change script = d.diff_2(reverse);
    if (script == null)
        System.err.println("No differences");
    else {
        Base p;
        switch (style) {
        case 'e':
            p = new EdPrint(a, b);
            break;
        case 'c':
            p = new ContextPrint(a, b);
            break;
        case 'u':
            p = new UnifiedPrint(a, b);
            break;
        default:
            p = new NormalPrint(a, b);
        }
        p.print_header(filea, fileb);
        p.print_script(script);
    }
}

From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;/*from w w w  .  j a  va2 s  . com*/
    Options options = getOptions();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("RmiIndexerStub -h <hostName> -p <basePort> [options] ", options);
        System.exit(1);
    }

    boolean doOptimize = line.hasOption("optimize");
    boolean doCheckpoint = line.hasOption("checkpoint");
    boolean doStop = line.hasOption("stop");
    Integer port = ((Long) line.getOptionObject("port")).intValue();
    String host = line.getOptionValue("host");

    try {
        RmiIndexerStub stub = new RmiIndexerStub(port, host);

        if (line.hasOption("deleteUrl")) {
            String url = line.getOptionValue("deleteUrl");
            Document dom = generateDeleteDocument(url);
            indexOrFail(stub, dom, "Could not delete " + url);
            System.out.println("delete " + url + " command accepted by indexer");
        }

        if (line.hasOption("deleteFile")) {

            BufferedReader reader = new BufferedReader(new FileReader(line.getOptionValue("deleteFile")));
            while (reader.ready()) {
                String url = reader.readLine();
                if (url.length() > 0 && url.charAt(0) != '#') { // ignore empty lines and comments
                    Document dom = generateDeleteDocument(url);
                    indexOrFail(stub, dom, "Could not delete " + url);
                    System.out.println("delete " + url + " command accepted by indexer");
                }
            }
            reader.close();
        }

        if (doOptimize) {
            Document dom = generateCommandDocument("optimize");
            indexOrFail(stub, dom, "Could not send optimize command.");
            System.out.println("optimize command accepted by indexer");
        }

        if (doCheckpoint) {
            Document dom = generateCommandDocument("checkpoint");
            indexOrFail(stub, dom, "Could not send checkpoint command.");
            System.out.println("checkpoint command accepted by indexer");

        }
        if (doStop) {
            Document dom = generateCommandDocument("close");
            indexOrFail(stub, dom, "Could not send stop command.");
            System.out.println("stop command accepted by indexer");
        }
    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:InstallJars.java

/**
 * Main command line entry point.//from   w  ww  .  ja  va  2s  . co  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.gzj.tulip.jade.statement.SystemInterpreter.java

public static void main(String[] args) throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("table", "my_table_name");
    parameters.put("id", "my_id");
    parameters.put(":1", "first_param");

    final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)");

    String sql = "select form ##(:table) {name} where {id}='{1}'";

    StringBuilder sb = new StringBuilder(sql.length() + 200);
    Matcher matcher = PATTERN.matcher(sql);
    int start = 0;
    while (matcher.find(start)) {
        sb.append(sql.substring(start, matcher.start()));
        String group = matcher.group();
        String key = null;
        if (group.startsWith("{")) {
            key = matcher.group(1);/*w  ww  .ja va 2 s.c  o  m*/
        } else if (group.startsWith("##(")) {
            key = matcher.group(2);
        }
        System.out.println(key);
        if (key == null || key.length() == 0) {
            continue;
        }
        Object value = parameters.get(key); // {paramName}?{:1}?
        if (value == null) {
            if (key.startsWith(":") || key.startsWith("$")) {
                value = parameters.get(key.substring(1)); // {:paramName}
            } else {
                char ch = key.charAt(0);
                if (ch >= '0' && ch <= '9') {
                    value = parameters.get(":" + key); // {1}?
                }
            }
        }
        if (value == null) {
            value = parameters.get(key); // ?
        }
        if (value != null) {
            sb.append(value);
        } else {
            sb.append(group);
        }
        start = matcher.end();
    }
    sb.append(sql.substring(start));
    System.out.println(sb);

}

From source file:ArrayDictionary.java

/**
 * A kludge for testing ArrayDictionary/*from ww w  .ja  v  a2  s  .c o  m*/
 */
public static void main(String[] args) {
    try {
        PrintStream out = System.out;
        DataInputStream in = new DataInputStream(System.in);

        String line = null;

        out.print("n ? ");
        out.flush();
        line = in.readLine();
        int n = Integer.parseInt(line);
        ArrayDictionary ad = new ArrayDictionary(n);

        String key = null, value = null;
        while (true) {
            out.print("action ? ");
            out.flush();
            line = in.readLine();

            switch (line.charAt(0)) {
            case 'p':
            case 'P':
                out.print("key ? ");
                out.flush();
                key = in.readLine();
                out.print("value ? ");
                out.flush();
                value = in.readLine();
                value = (String) ad.put(key, value);
                out.println("old: " + value);
                break;
            case 'r':
            case 'R':
                out.print("key ? ");
                out.flush();
                key = in.readLine();
                value = (String) ad.remove(key);
                out.println("old: " + value);
                break;
            case 'g':
            case 'G':
                out.print("key ? ");
                out.flush();
                key = in.readLine();
                value = (String) ad.get(key);
                out.println("value: " + value);
                break;
            case 'd':
            case 'D':
                out.println(ad.toString());
                break;
            case 'q':
            case 'Q':
                return;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:de.morbz.osmpoispbf.Scanner.java

public static void main(String[] args) {
    System.out.println("OsmPoisPbf " + VERSION + " started");

    // Get input file
    if (args.length < 1) {
        System.out.println("Error: Please provide an input file");
        System.exit(-1);//from w  ww  .  j  a v a 2  s. c  om
    }
    String inputFile = args[args.length - 1];

    // Get output file
    String outputFile;
    int index = inputFile.indexOf('.');
    if (index != -1) {
        outputFile = inputFile.substring(0, index);
    } else {
        outputFile = inputFile;
    }
    outputFile += ".csv";

    // Setup CLI parameters
    options = new Options();
    options.addOption("ff", "filterFile", true, "The file that is used to filter categories");
    options.addOption("of", "outputFile", true, "The output CSV file to be written");
    options.addOption("rt", "requiredTags", true, "Comma separated list of tags that are required [name]");
    options.addOption("ut", "undesiredTags", true,
            "Comma separated list of tags=value combinations that should be filtered [key=value]");
    options.addOption("ot", "outputTags", true, "Comma separated list of tags that are exported [name]");
    options.addOption("ph", "printHeader", false,
            "If flag is set, the `outputTags` are printed as first line in the output file.");
    options.addOption("r", "relations", false, "Parse relations");
    options.addOption("nw", "noWays", false, "Don't parse ways");
    options.addOption("nn", "noNodes", false, "Don't parse nodes");
    options.addOption("u", "allowUnclosedWays", false, "Allow ways that aren't closed");
    options.addOption("d", "decimals", true, "Number of decimal places of coordinates [7]");
    options.addOption("s", "separator", true, "Separator character for CSV [|]");
    options.addOption("v", "verbose", false, "Print all found POIs");
    options.addOption("h", "help", false, "Print this help");

    // Parse parameters
    CommandLine line = null;
    try {
        line = (new DefaultParser()).parse(options, args);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        printHelp();
        System.exit(-1);
    }

    // Help
    if (line.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    // Get filter file
    String filterFile = null;
    if (line.hasOption("filterFile")) {
        filterFile = line.getOptionValue("filterFile");
    }

    // Get output file
    if (line.hasOption("outputFile")) {
        outputFile = line.getOptionValue("outputFile");
    }

    // Check files
    if (inputFile.equals(outputFile)) {
        System.out.println("Error: Input and output files are the same");
        System.exit(-1);
    }
    File file = new File(inputFile);
    if (!file.exists()) {
        System.out.println("Error: Input file doesn't exist");
        System.exit(-1);
    }

    // Check OSM entity types
    boolean parseNodes = true;
    boolean parseWays = true;
    boolean parseRelations = false;
    if (line.hasOption("noNodes")) {
        parseNodes = false;
    }
    if (line.hasOption("noWays")) {
        parseWays = false;
    }
    if (line.hasOption("relations")) {
        parseRelations = true;
    }

    // Unclosed ways allowed?
    if (line.hasOption("allowUnclosedWays")) {
        onlyClosedWays = false;
    }

    // Get CSV separator
    char separator = '|';
    if (line.hasOption("separator")) {
        String arg = line.getOptionValue("separator");
        if (arg.length() != 1) {
            System.out.println("Error: The CSV separator has to be exactly 1 character");
            System.exit(-1);
        }
        separator = arg.charAt(0);
    }
    Poi.setSeparator(separator);

    // Set decimals
    int decimals = 7; // OSM default
    if (line.hasOption("decimals")) {
        String arg = line.getOptionValue("decimals");
        try {
            int dec = Integer.valueOf(arg);
            if (dec < 0) {
                System.out.println("Error: Decimals must not be less than 0");
                System.exit(-1);
            } else {
                decimals = dec;
            }
        } catch (NumberFormatException ex) {
            System.out.println("Error: Decimals have to be a number");
            System.exit(-1);
        }
    }
    Poi.setDecimals(decimals);

    // Verbose mode?
    if (line.hasOption("verbose")) {
        printPois = true;
    }

    // Required tags
    if (line.hasOption("requiredTags")) {
        String arg = line.getOptionValue("requiredTags");
        requiredTags = arg.split(",");
    }

    // Undesired tags
    if (line.hasOption("undesiredTags")) {
        String arg = line.getOptionValue("undesiredTags");
        undesiredTags = new HashMap<>();
        for (String undesired : arg.split(",")) {
            String[] keyVal = undesired.split("=");
            if (keyVal.length != 2) {
                System.out.println("Error: Undesired Tags have to formated like tag=value");
                System.exit(-1);
            }
            if (!undesiredTags.containsKey(keyVal[0])) {
                undesiredTags.put(keyVal[0], new HashSet<>(1));
            }
            undesiredTags.get(keyVal[0]).add(keyVal[1]);
        }
    }

    // Output tags
    if (line.hasOption("outputTags")) {
        String arg = line.getOptionValue("outputTags");
        outputTags = arg.split(",");
    }

    // Get filter rules
    FilterFileParser parser = new FilterFileParser(filterFile);
    filters = parser.parse();
    if (filters == null) {
        System.exit(-1);
    }

    // Setup CSV output
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8"));
    } catch (IOException e) {
        System.out.println("Error: Output file error");
        System.exit(-1);
    }

    // Print Header
    if (line.hasOption("printHeader")) {
        String header = "category" + separator + "osm_id" + separator + "lat" + separator + "lon";
        for (int i = 0; i < outputTags.length; i++) {
            header += separator + outputTags[i];
        }
        try {
            writer.write(header + "\n");
        } catch (IOException e) {
            System.out.println("Error: Output file write error");
            System.exit(-1);
        }
    }

    // Setup OSMonaut
    EntityFilter filter = new EntityFilter(parseNodes, parseWays, parseRelations);
    Osmonaut naut = new Osmonaut(inputFile, filter, false);

    // Start watch
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // Start OSMonaut
    String finalSeparator = String.valueOf(separator);
    naut.scan(new IOsmonautReceiver() {

        boolean entityNeeded;

        @Override
        public boolean needsEntity(EntityType type, Tags tags) {
            // Are there any tags?
            if (tags.size() == 0) {
                return false;
            }

            // Check required tags
            for (String tag : requiredTags) {
                if (!tags.hasKey(tag)) {
                    return false;
                }
            }

            entityNeeded = getCategory(tags, filters) != null;

            if (undesiredTags != null && entityNeeded) {
                for (String key : undesiredTags.keySet()) {
                    if (tags.hasKey(key)) {
                        for (String val : undesiredTags.get(key)) {
                            if (tags.hasKeyValue(key, val)) {
                                return false;
                            }
                        }
                    }
                }
            }

            return entityNeeded;
        }

        @Override
        public void foundEntity(Entity entity) {
            // Check if way is closed
            if (onlyClosedWays && entity.getEntityType() == EntityType.WAY) {
                if (!((Way) entity).isClosed()) {
                    return;
                }
            }

            // Get category
            Tags tags = entity.getTags();
            String cat = getCategory(tags, filters);
            if (cat == null) {
                return;
            }

            // Get center
            LatLon center = entity.getCenter();
            if (center == null) {
                return;
            }

            // Make OSM-ID
            String type = "";
            switch (entity.getEntityType()) {
            case NODE:
                type = "node";
                break;
            case WAY:
                type = "way";
                break;
            case RELATION:
                type = "relation";
                break;
            }
            String id = String.valueOf(entity.getId());

            // Make output tags
            String[] values = new String[outputTags.length];
            for (int i = 0; i < outputTags.length; i++) {
                String key = outputTags[i];
                if (tags.hasKey(key)) {
                    values[i] = tags.get(key).replaceAll(finalSeparator, "").replaceAll("\"", "");
                }
            }

            // Make POI
            poisFound++;
            Poi poi = new Poi(values, cat, center, type, id);

            // Output
            if (printPois && System.currentTimeMillis() > lastMillis + 40) {
                printPoisFound();
                lastMillis = System.currentTimeMillis();
            }

            // Write to file
            try {
                writer.write(poi.toCsv() + "\n");
            } catch (IOException e) {
                System.out.println("Error: Output file write error");
                System.exit(-1);
            }
        }
    });

    // Close writer
    try {
        writer.close();
    } catch (IOException e) {
        System.out.println("Error: Output file close error");
        System.exit(-1);
    }

    // Output results
    stopWatch.stop();

    printPoisFound();
    System.out.println();
    System.out.println("Elapsed time in milliseconds: " + stopWatch.getElapsedTime());

    // Quit
    System.exit(0);
}

From source file:edu.nyu.tandon.tool.RawHits.java

@SuppressWarnings("unchecked")
public static void main(final String[] arg) throws Exception {

    SimpleJSAP jsap = new SimpleJSAP(RawHits.class.getName(),
            "Loads indices relative to a collection, possibly loads the collection, and answers to queries.",
            new Parameter[] {
                    new FlaggedOption("collection", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'c',
                            "collection", "The collection of documents indexed by the given indices."),
                    new FlaggedOption("objectCollection",
                            new ObjectParser(DocumentCollection.class, MG4JClassParser.PACKAGE),
                            JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "object-collection",
                            "An object specification describing a document collection."),
                    new FlaggedOption("titleList", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 't',
                            "title-list",
                            "A serialized big list of titles (will override collection titles if specified)."),
                    new FlaggedOption("titleFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'T',
                            "title-file",
                            "A file of newline-separated, UTF-8 titles (will override collection titles if specified)."),
                    new FlaggedOption("input", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'I', "input",
                            "A file containing the input."),
                    new Switch("noSizes", 'n', "no-sizes",
                            "Disable loading document sizes (they are necessary for BM25 scoring)."),
                    new Switch("http", 'h', "http", "Starts an HTTP query server."),
                    new Switch("verbose", 'v', "verbose", "Print full exception stack traces."),
                    new FlaggedOption("itemClass", MG4JClassParser.getParser(), JSAP.NO_DEFAULT,
                            JSAP.NOT_REQUIRED, 'i', "item-class",
                            "The class that will handle item display in the HTTP server."),
                    new FlaggedOption("itemMimeType", JSAP.STRING_PARSER, "text/html", JSAP.NOT_REQUIRED, 'm',
                            "item-mime-type",
                            "A MIME type suggested to the class handling item display in the HTTP server."),
                    new FlaggedOption("port", JSAP.INTEGER_PARSER, "4242", JSAP.NOT_REQUIRED, 'p', "port",
                            "The port on localhost where the server will appear."),
                    new UnflaggedOption("basenameWeight", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.GREEDY,
                            "The indices that the servlet will use. Indices are specified using their basename, optionally followed by a colon and a double representing the weight used to score results from that index. Indices without a specified weight are weighted 1."),

                    new Switch("noMplex", 'P', "noMplex", "Starts with multiplex disabled."),
                    new FlaggedOption("results", JSAP.INTEGER_PARSER, "1000", JSAP.NOT_REQUIRED, 'r', "results",
                            "The # of results to display"),
                    new FlaggedOption("mode", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'M',
                            "time", "The results display mode"),
                    new FlaggedOption("divert", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'd',
                            "divert", "output file"),
                    new FlaggedOption("dumpsize", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'D',
                            "dumpsize", "number of queries before dumping")

            });/*from  w ww . j a  v a2  s  . co m*/

    final JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;

    final DocumentCollection documentCollection = (DocumentCollection) (jsapResult.userSpecified("collection")
            ? AbstractDocumentSequence.load(jsapResult.getString("collection"))
            : jsapResult.userSpecified("objectCollection") ? jsapResult.getObject("objectCollection") : null);
    final BigList<? extends CharSequence> titleList = (BigList<? extends CharSequence>) (jsapResult
            .userSpecified("titleList")
                    ? BinIO.loadObject(jsapResult.getString("titleList"))
                    : jsapResult.userSpecified("titleFile")
                            ? new FileLinesBigList(jsapResult.getString("titleFile"), "UTF-8")
                            : null);
    final String[] basenameWeight = jsapResult.getStringArray("basenameWeight");
    final Object2ReferenceLinkedOpenHashMap<String, Index> indexMap = new Object2ReferenceLinkedOpenHashMap<String, Index>(
            Hash.DEFAULT_INITIAL_SIZE, .5f);
    final Reference2DoubleOpenHashMap<Index> index2Weight = new Reference2DoubleOpenHashMap<Index>();
    final boolean verbose = jsapResult.getBoolean("verbose");
    final boolean loadSizes = !jsapResult.getBoolean("noSizes");
    RawHits.loadIndicesFromSpec(basenameWeight, loadSizes, documentCollection, indexMap, index2Weight);

    final long numberOfDocuments = indexMap.values().iterator().next().numberOfDocuments;
    if (titleList != null && titleList.size64() != numberOfDocuments)
        throw new IllegalArgumentException("The number of titles (" + titleList.size64()
                + " and the number of documents (" + numberOfDocuments + ") do not match");

    final Object2ObjectOpenHashMap<String, TermProcessor> termProcessors = new Object2ObjectOpenHashMap<String, TermProcessor>(
            indexMap.size());
    for (String alias : indexMap.keySet())
        termProcessors.put(alias, indexMap.get(alias).termProcessor);

    final SimpleParser simpleParser = new SimpleParser(indexMap.keySet(), indexMap.firstKey(), termProcessors);

    final Reference2ReferenceMap<Index, Object> index2Parser = new Reference2ReferenceOpenHashMap<Index, Object>();
    /*
    // Fetch parsers for payload-based fields.
    for( Index index: indexMap.values() ) if ( index.hasPayloads ) {
     if ( index.payload.getClass() == DatePayload.class ) index2Parser.put( index, DateFormat.getDateInstance( DateFormat.SHORT, Locale.UK ) );
    }
    */

    final HitsQueryEngine queryEngine = new HitsQueryEngine(simpleParser, new DocumentIteratorBuilderVisitor(
            indexMap, index2Parser, indexMap.get(indexMap.firstKey()), MAX_STEMMING), indexMap);
    queryEngine.setWeights(index2Weight);
    queryEngine.score(new Scorer[] { new BM25Scorer(), new VignaScorer() }, new double[] { 1, 1 });

    queryEngine.multiplex = !jsapResult.userSpecified("moPlex") || jsapResult.getBoolean("noMplex");
    queryEngine.intervalSelector = null;
    queryEngine.equalize(1000);

    RawHits query = new RawHits(queryEngine);

    // start docHits with at least 10K results
    query.interpretCommand("$score BM25Scorer");
    //        query.interpretCommand("$mode time");

    if (jsapResult.userSpecified("divert"))
        query.interpretCommand("$divert " + jsapResult.getObject("divert"));

    query.displayMode = OutputType.DOCHHITS;
    query.maxOutput = jsapResult.getInt("results", 1000);

    String q;
    int n = 0;

    String lastQ = "";

    try {
        final BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(jsapResult.getString("input"))));

        final ObjectArrayList<DocumentScoreInfo<ObjectArrayList<Byte>>> results = new ObjectArrayList<DocumentScoreInfo<ObjectArrayList<Byte>>>();

        for (;;) {
            q = br.readLine();
            if (q == null) {
                System.err.println();
                break; // CTRL-D
            }
            if (q.length() == 0)
                continue;
            if (q.charAt(0) == '$') {
                if (!query.interpretCommand(q))
                    break;
                continue;
            }

            queryCount++;
            long time = -System.nanoTime();
            if (q.compareTo(lastQ) != 0) {
                try {
                    n = queryEngine.process(q, 0, query.maxOutput, results);
                } catch (QueryParserException e) {
                    if (verbose)
                        e.getCause().printStackTrace(System.err);
                    else
                        System.err.println(e.getCause());
                    continue;
                } catch (Exception e) {
                    if (verbose)
                        e.printStackTrace(System.err);
                    else
                        System.err.println(e);
                    continue;
                }
                lastQ = q;
            }
            time += System.nanoTime();
            query.output(results, documentCollection, titleList, TextMarker.TEXT_BOLDFACE);
        }
    } finally {
    }
}

From source file:io.alicorn.device.client.DeviceClient.java

public static void main(String[] args) {
    logger.info("Starting Alicorn Client System");

    // Prepare Display Color.
    transform3xWrite(DisplayTools.commandForColor(0, 204, 255));

    // Setup text information.
    //        transform3xWrite(DisplayTools.commandForText("Sup Fam"));

    class StringWrapper {
        public String string = "";
    }// w w w .j a  va 2s.  c o m
    final StringWrapper string = new StringWrapper();

    // Text Handler.
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String latestString = "";
            String outputStringLine1Complete = "";
            long outputStringLine1Cursor = 1;
            int outputStringLine1Mask = 0;
            String outputStringLine2 = "";

            while (true) {
                if (!latestString.equals(string.string)) {
                    latestString = string.string;
                    String[] latestStrings = latestString.split("::");
                    outputStringLine1Complete = latestStrings[0];
                    outputStringLine1Mask = outputStringLine1Complete.length();
                    outputStringLine1Cursor = 0;

                    // Trim second line to a length of sixteen.
                    outputStringLine2 = latestStrings.length > 1 ? latestStrings[1] : "";
                    if (outputStringLine2.length() > 16) {
                        outputStringLine2 = outputStringLine2.substring(0, 16);
                    }
                }

                StringBuilder outputStringLine1 = new StringBuilder();
                if (outputStringLine1Complete.length() > 0) {
                    long cursor = outputStringLine1Cursor;
                    for (int i = 0; i < 16; i++) {
                        outputStringLine1.append(
                                outputStringLine1Complete.charAt((int) (cursor % outputStringLine1Mask)));
                        cursor += 1;
                    }
                    outputStringLine1Cursor += 1;
                } else {
                    outputStringLine1.append("                ");
                }

                try {
                    transform3xWrite(
                            DisplayTools.commandForText(outputStringLine1.toString() + outputStringLine2));
                    Thread.sleep(400);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
    thread.start();

    // Event Handler
    while (true) {
        try {
            String url = "http://169.254.90.174:9789/api/iot/narwhalText";
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            string.string = apacheHttpEntityToString(response.getEntity());

            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}