Example usage for java.lang String indexOf

List of usage examples for java.lang String indexOf

Introduction

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

Prototype

public int indexOf(String str) 

Source Link

Document

Returns the index within this string of the first occurrence of the specified substring.

Usage

From source file:Main.java

  public static void main(String[] argv) throws Exception {
  Set result = new HashSet();
  Provider[] providers = Security.getProviders();
  for (int i = 0; i < providers.length; i++) {
    Set keys = providers[i].keySet();
    for (Iterator it = keys.iterator(); it.hasNext();) {
      String key = (String) it.next();
      key = key.split(" ")[0];

      if (key.startsWith("Alg.Alias.")) {
        // Strip the alias
        key = key.substring(10);/*from w  w w  .  jav a2s.c  o  m*/
      }
      int ix = key.indexOf('.');
      result.add(key.substring(0, ix));
    }
  }
  System.out.println(result);
}

From source file:jk.kamoru.test.IMAPMail.java

public static void main(String[] args) {
    /*        if (args.length < 3)
            {//from   www.  j a v a  2s . c  o m
    System.err.println(
        "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
    System.exit(1);
            }
    */
    String server = "imap.handysoft.co.kr";
    String username = "namjk24@handysoft.co.kr";
    String password = "22222";

    String proto = (args.length > 3) ? args[3] : null;

    IMAPClient imap;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        imap = new IMAPSClient(proto, true); // implicit
        // enable the next line to only check if the server certificate has expired (does not check chain):
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        // OR enable the next line if the server uses a self-signed certificate (no checks)
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        imap = new IMAPClient();
    }
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    // We want to timeout if a response takes longer than 60 seconds
    imap.setDefaultTimeout(60000);

    File imap_log_file = new File("IMAMP-UNSEEN");
    try {
        System.out.println(imap_log_file.getAbsolutePath());
        PrintStream ps = new PrintStream(imap_log_file);
        // suppress login details
        imap.addProtocolCommandListener(new PrintCommandListener(ps, true));
    } catch (FileNotFoundException e1) {
        imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));
    }

    try {
        imap.connect(server);
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    try {
        if (!imap.login(username, password)) {
            System.err.println("Could not login to server. Check password.");
            imap.disconnect();
            System.exit(3);
        }

        imap.setSoTimeout(6000);

        //            imap.capability();

        //            imap.select("inbox");

        //            imap.examine("inbox");

        imap.status("inbox", new String[] { "UNSEEN" });

        //            imap.logout();
        imap.disconnect();

        List<String> imap_log = FileUtils.readLines(imap_log_file);
        for (int i = 0; i < imap_log.size(); i++) {
            System.out.println(i + ":" + imap_log.get(i));
        }
        String unseenText = imap_log.get(4);
        unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')'));
        int unseenCount = Integer.parseInt(unseenText.split(" ")[1]);

        System.out.println(unseenCount);
        //imap_log.indexOf("UNSEEN ")
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    }
}

From source file:com.joliciel.jochre.search.JochreSearch.java

/**
 * @param args/*www .  ja  v  a  2s  .com*/
 */
public static void main(String[] args) {
    try {
        Map<String, String> argMap = new HashMap<String, String>();

        for (String arg : args) {
            int equalsPos = arg.indexOf('=');
            String argName = arg.substring(0, equalsPos);
            String argValue = arg.substring(equalsPos + 1);
            argMap.put(argName, argValue);
        }

        String command = argMap.get("command");
        argMap.remove("command");

        String logConfigPath = argMap.get("logConfigFile");
        if (logConfigPath != null) {
            argMap.remove("logConfigFile");
            Properties props = new Properties();
            props.load(new FileInputStream(logConfigPath));
            PropertyConfigurator.configure(props);
        }

        LOG.debug("##### Arguments:");
        for (Entry<String, String> arg : argMap.entrySet()) {
            LOG.debug(arg.getKey() + ": " + arg.getValue());
        }

        SearchServiceLocator locator = SearchServiceLocator.getInstance();
        SearchService searchService = locator.getSearchService();

        if (command.equals("buildIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateDocument(documentDir);
        } else if (command.equals("updateIndex")) {
            String indexDirPath = argMap.get("indexDir");
            String documentDirPath = argMap.get("documentDir");
            boolean forceUpdate = false;
            if (argMap.containsKey("forceUpdate")) {
                forceUpdate = argMap.get("forceUpdate").equals("true");
            }
            File indexDir = new File(indexDirPath);
            indexDir.mkdirs();
            File documentDir = new File(documentDirPath);

            JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir);
            builder.updateIndex(documentDir, forceUpdate);
        } else if (command.equals("search")) {
            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator.getInstance(locator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();

            String indexDirPath = argMap.get("indexDir");
            File indexDir = new File(indexDirPath);
            JochreQuery query = searchService.getJochreQuery(argMap);

            JochreIndexSearcher searcher = searchService.getJochreIndexSearcher(indexDir);
            TopDocs topDocs = searcher.search(query);

            Set<Integer> docIds = new LinkedHashSet<Integer>();
            for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
                docIds.add(scoreDoc.doc);
            }
            Set<String> fields = new HashSet<String>();
            fields.add("text");

            Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher());
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            highlightManager.setDecimalPlaces(query.getDecimalPlaces());
            highlightManager.setMinWeight(0.0);
            highlightManager.setIncludeText(true);
            highlightManager.setIncludeGraphics(true);

            Writer out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
            if (command.equals("highlight")) {
                highlightManager.highlight(highlighter, docIds, fields, out);
            } else {
                highlightManager.findSnippets(highlighter, docIds, fields, out);
            }
        } else {
            throw new RuntimeException("Unknown command: " + command);
        }
    } catch (RuntimeException e) {
        LogUtils.logError(LOG, e);
        throw e;
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static void main(String args[]) {
    JTextArea area = new JTextArea(5, 20);
    area.setText("this is a test.");
    String charsToHighlight = "aeiouAEIOU";
    Highlighter h = area.getHighlighter();
    h.removeAllHighlights();/*www .jav  a 2s.c o m*/
    String text = area.getText().toUpperCase();
    for (int i = 0; i < text.length(); i += 1) {
        char ch = text.charAt(i);
        if (charsToHighlight.indexOf(ch) >= 0)
            try {
                h.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
            } catch (Exception ble) {
            }
    }
}

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }//  ww  w  .ja  va  2 s .c om
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame("MultiHighlight");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextArea comp = new JTextArea(5, 20);
    comp.setText("this is a test");
    frame.getContentPane().add(new JScrollPane(comp), BorderLayout.CENTER);

    String charsToHighlight = "a";
    Highlighter h = comp.getHighlighter();
    h.removeAllHighlights();/*  ww  w .ja  v  a 2  s  .  c om*/
    String text = comp.getText().toUpperCase();

    for (int j = 0; j < text.length(); j += 1) {
        char ch = text.charAt(j);
        if (charsToHighlight.indexOf(ch) >= 0)
            h.addHighlight(j, j + 1, DefaultHighlighter.DefaultPainter);
    }
    frame.pack();
    frame.setVisible(true);
}

From source file:TextAroundBox.java

public static void main(String[] args) {
    final Display display = new Display();
    final Color RED = display.getSystemColor(SWT.COLOR_RED);
    Shell shell = new Shell(display);
    shell.setBounds(10, 10, 250, 250);// w  w w.  ja  v  a2s .c om
    final StyledText text = new StyledText(shell, SWT.NONE);
    text.setBounds(10, 10, 200, 200);
    text.addListener(SWT.Paint, new Listener() {
        public void handleEvent(Event event) {
            String contents = text.getText();
            int stringWidth = event.gc.stringExtent(SEARCH_STRING).x;
            int lineHeight = text.getLineHeight();
            event.gc.setForeground(RED);
            int index = contents.indexOf(SEARCH_STRING);
            while (index != -1) {
                Point topLeft = text.getLocationAtOffset(index);
                event.gc.drawRectangle(topLeft.x - 1, topLeft.y, stringWidth + 1, lineHeight - 1);
                index = contents.indexOf(SEARCH_STRING, index + 1);
            }
        }
    });
    text.setText("This demonstrates drawing a box\naround every occurrence of the word\nbox in the StyledText");
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.trendmicro.hdfs.webdav.Main.java

public static void main(String[] args) {

    HDFSWebDAVServlet servlet = HDFSWebDAVServlet.getServlet();
    Configuration conf = servlet.getConfiguration();

    // Process command line 

    Options options = new Options();
    options.addOption("d", "debug", false, "Enable debug logging");
    options.addOption("p", "port", true, "Port to bind to [default: 8080]");
    options.addOption("b", "bind-address", true, "Address or hostname to bind to [default: 0.0.0.0]");
    options.addOption("g", "ganglia", true, "Send Ganglia metrics to host:port [default: none]");

    CommandLine cmd = null;// ww  w .  j  av a 2s.  c om
    try {
        cmd = new PosixParser().parse(options, args);
    } catch (ParseException e) {
        printUsageAndExit(options, -1);
    }

    if (cmd.hasOption('d')) {
        Logger rootLogger = Logger.getLogger("com.trendmicro");
        rootLogger.setLevel(Level.DEBUG);
    }

    if (cmd.hasOption('b')) {
        conf.set("hadoop.webdav.bind.address", cmd.getOptionValue('b'));
    }

    if (cmd.hasOption('p')) {
        conf.setInt("hadoop.webdav.port", Integer.valueOf(cmd.getOptionValue('p')));
    }

    String gangliaHost = null;
    int gangliaPort = 8649;
    if (cmd.hasOption('g')) {
        String val = cmd.getOptionValue('g');
        if (val.indexOf(':') != -1) {
            String[] split = val.split(":");
            gangliaHost = split[0];
            gangliaPort = Integer.valueOf(split[1]);
        } else {
            gangliaHost = val;
        }
    }

    InetSocketAddress addr = getAddress(conf);

    // Log in the server principal from keytab

    UserGroupInformation.setConfiguration(conf);
    if (UserGroupInformation.isSecurityEnabled())
        try {
            SecurityUtil.login(conf, "hadoop.webdav.server.kerberos.keytab",
                    "hadoop.webdav.server.kerberos.principal", addr.getHostName());
        } catch (IOException e) {
            LOG.fatal("Could not log in", e);
            System.err.println("Could not log in");
            System.exit(-1);
        }

    // Set up embedded Jetty

    Server server = new Server();

    server.setSendServerVersion(false);
    server.setSendDateHeader(false);
    server.setStopAtShutdown(true);

    // Set up connector
    Connector connector = new SelectChannelConnector();
    connector.setPort(addr.getPort());
    connector.setHost(addr.getHostName());
    server.addConnector(connector);
    LOG.info("Listening on " + addr);

    // Set up context
    Context context = new Context(server, "/", Context.SESSIONS);
    // WebDAV servlet
    ServletHolder servletHolder = new ServletHolder(servlet);
    servletHolder.setInitParameter("authenticate-header", "Basic realm=\"Hadoop WebDAV Server\"");
    context.addServlet(servletHolder, "/*");
    // metrics instrumentation filter
    context.addFilter(new FilterHolder(new DefaultWebappMetricsFilter()), "/*", 0);
    // auth filter
    context.addFilter(new FilterHolder(new AuthFilter(conf)), "/*", 0);
    server.setHandler(context);

    // Set up Ganglia metrics reporting
    if (gangliaHost != null) {
        GangliaReporter.enable(1, TimeUnit.MINUTES, gangliaHost, gangliaPort);
    }

    // Start and join the server thread    
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        LOG.fatal("Failed to start Jetty", e);
        System.err.println("Failed to start Jetty");
        System.exit(-1);
    }
}

From source file:net.iridiant.hdfs.webdav.Main.java

public static void main(String[] args) {

    HDFSWebDAVServlet servlet = HDFSWebDAVServlet.getServlet();
    Configuration conf = servlet.getConfiguration();

    // Process command line 

    Options options = new Options();
    options.addOption("d", "debug", false, "Enable debug logging");
    options.addOption("p", "port", true, "Port to bind to [default: 8080]");
    options.addOption("b", "bind-address", true, "Address or hostname to bind to [default: 0.0.0.0]");
    options.addOption("g", "ganglia", true, "Send Ganglia metrics to host:port [default: none]");

    CommandLine cmd = null;/*from w  ww  . ja  va 2s.  c om*/
    try {
        cmd = new PosixParser().parse(options, args);
    } catch (ParseException e) {
        printUsageAndExit(options, -1);
    }

    if (cmd.hasOption('d')) {
        Logger rootLogger = Logger.getLogger("net.iridiant");
        rootLogger.setLevel(Level.DEBUG);
    }

    if (cmd.hasOption('b')) {
        conf.set("hadoop.webdav.bind.address", cmd.getOptionValue('b'));
    }

    if (cmd.hasOption('p')) {
        conf.setInt("hadoop.webdav.port", Integer.valueOf(cmd.getOptionValue('p')));
    }

    String gangliaHost = null;
    int gangliaPort = 8649;
    if (cmd.hasOption('g')) {
        String val = cmd.getOptionValue('g');
        if (val.indexOf(':') != -1) {
            String[] split = val.split(":");
            gangliaHost = split[0];
            gangliaPort = Integer.valueOf(split[1]);
        } else {
            gangliaHost = val;
        }
    }

    InetSocketAddress addr = getAddress(conf);

    // Log in the server principal from keytab

    UserGroupInformation.setConfiguration(conf);
    if (UserGroupInformation.isSecurityEnabled())
        try {
            SecurityUtil.login(conf, "hadoop.webdav.server.kerberos.keytab",
                    "hadoop.webdav.server.kerberos.principal", addr.getHostName());
        } catch (IOException e) {
            LOG.fatal("Could not log in", e);
            System.err.println("Could not log in");
            System.exit(-1);
        }

    // Set up embedded Jetty

    Server server = new Server();

    server.setSendServerVersion(false);
    server.setSendDateHeader(false);
    server.setStopAtShutdown(true);

    // Set up connector
    Connector connector = new SelectChannelConnector();
    connector.setPort(addr.getPort());
    connector.setHost(addr.getHostName());
    server.addConnector(connector);
    LOG.info("Listening on " + addr);

    // Set up context
    Context context = new Context(server, "/", Context.SESSIONS);
    // WebDAV servlet
    ServletHolder servletHolder = new ServletHolder(servlet);
    servletHolder.setInitParameter("authenticate-header", "Basic realm=\"Hadoop WebDAV Server\"");
    context.addServlet(servletHolder, "/*");
    // metrics instrumentation filter
    context.addFilter(new FilterHolder(new DefaultWebappMetricsFilter()), "/*", 0);
    // auth filter
    context.addFilter(new FilterHolder(new AuthFilter(conf)), "/*", 0);
    server.setHandler(context);

    // Set up Ganglia metrics reporting
    if (gangliaHost != null) {
        GangliaReporter.enable(1, TimeUnit.MINUTES, gangliaHost, gangliaPort);
    }

    // Start and join the server thread    
    try {
        server.start();
        server.join();
    } catch (Exception e) {
        LOG.fatal("Failed to start Jetty", e);
        System.err.println("Failed to start Jetty");
        System.exit(-1);
    }
}

From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?"));
    opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription(
            "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, UimaStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)")
            .create("p"));
    opts.addOption(OptionBuilder.withLongOpt("cardinality").withArgName("ngram-order").hasArg().withDescription(
            "Specify the cardinality of the ngrams (min. 1). Specify a range using 'from-to'. (Examples: 5 = extract 5grams; 1-5 = extract 1grams, 2grams, ..., 5grams; default: 1-5).")
            .create("n"));
    opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg()
            .withDescription(/* w w  w  .j a  va 2  s .  c  o m*/
                    "specify the directory that contains '.txt' files that are used as source for generating ngrams.")
            .create("d"));
    opts.addOption(OptionBuilder.withLongOpt("overwrite").withDescription("Overwrite existing ngram file.")
            .create("w"));

    CommandLine cli = null;
    try {
        cli = new GnuParser().parse(opts, args);
    } catch (Exception e) {
        print_usage(opts, e.getMessage());
    }
    if (cli.hasOption("?"))
        print_usage(opts, null);

    AbstractStringProvider prvdr = null;
    try {
        prvdr = StartLM
                .getStringProviderInstance(cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()));
    } catch (Exception e) {
        print_usage(opts, String.format("Could not instantiate LmProvider '%s': %s",
                cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()), e.getMessage()));
    }

    String n_ = cli.getOptionValue("cardinality", "1-5");
    int dash_index = n_.indexOf('-');
    int n_e = Integer.parseInt(n_.substring(dash_index + 1, n_.length()).trim());
    int n_b = n_e;
    if (dash_index == 0)
        n_b = 1;
    if (dash_index > 0)
        n_b = Math.max(1, Integer.parseInt(n_.substring(0, dash_index).trim()));

    final File src_dir = new File(cli.getOptionValue("dir"));
    boolean overwrite = Boolean.parseBoolean(cli.getOptionValue("overwrite", "false"));

    generateNgrams(src_dir, prvdr, n_b, n_e, overwrite);

}