Example usage for java.util StringTokenizer nextToken

List of usage examples for java.util StringTokenizer nextToken

Introduction

In this page you can find the example usage for java.util StringTokenizer nextToken.

Prototype

public String nextToken() 

Source Link

Document

Returns the next token from this string tokenizer.

Usage

From source file:mitm.common.tools.SendMail.java

private static Address[] getRecipients(String recipients) throws AddressException {
    if (StringUtils.isBlank(recipients)) {
        return null;
    }/* w w w  . j a va2 s . c o  m*/

    List<Address> addresses = new LinkedList<Address>();

    StringTokenizer tokenizer = new StringTokenizer(recipients, ",");

    while (tokenizer.hasMoreTokens()) {
        String recipient = tokenizer.nextToken();

        addresses.add(new InternetAddress(recipient));
    }

    return (Address[]) addresses.toArray(new Address[0]);
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPProxyConfigurator.java

/**
 * Check if the specified host is in the list of non proxy hosts.
 *
 * @param host/*from   w ww.java2 s . c om*/
 *            host name
 * @param nonProxyHosts
 *            string containing the list of non proxy hosts
 * @return true/false
 */
public static boolean isHostInNonProxyList(String host, String nonProxyHosts) {
    if ((nonProxyHosts == null) || (host == null)) {
        return false;
    }

    /*
     * The http.nonProxyHosts system property is a list enclosed in double
     * quotes with items separated by a vertical bar.
     */
    StringTokenizer tokenizer = new StringTokenizer(nonProxyHosts, "|\"");

    while (tokenizer.hasMoreTokens()) {
        String pattern = tokenizer.nextToken();
        if (match(pattern, host, false)) {
            return true;
        }
    }
    return false;
}

From source file:io.jari.geenstijl.API.API.java

/**
 * Get article and comments (note that getArticles doesn't get the comments)
 *
 * @param url The direct url to the geenstijl article
 * @return Artikel The fetched article/*from w  w w .j  ava  2s  .  co m*/
 * @throws IOException
 * @throws ParseException
 */
public static Artikel getArticle(String url, Context context) throws IOException, ParseException {
    ensureCookies();
    domain = context.getSharedPreferences("geenstijl", 0).getString("gsdomain", "www.geenstijl.nl");
    Artikel artikel;
    Log.i(TAG, "GETARTICLE STEP 1/2: Getting/parsing article page & images... " + url);
    Document document = Jsoup.connect(url).get();
    Element artikel_el = document.select("#content>article").first();
    artikel = parseArtikel(artikel_el, context);

    Log.i(TAG, "GETARTICLE STEP 2/2: Parsing comments...");
    ArrayList<Comment> comments = new ArrayList<Comment>();
    int i = 0;
    Elements comments_el = document.select("#comments article");
    for (Element comment_el : comments_el) {
        i++;
        Comment comment = new Comment();
        comment.id = Integer.parseInt(comment_el.attr("id").substring(1));
        Element footer = comment_el.select("footer").first();
        StringTokenizer footer_items = new StringTokenizer(footer.text(), "|");
        comment.auteur = footer_items.nextToken().trim();

        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyHH:mm", Locale.US);
            comment.datum = simpleDateFormat
                    .parse(footer_items.nextToken().trim() + footer_items.nextToken().trim());
        } catch (ParseException parseEx) {
            //fuck gebruikers met pipe chars in hun naam, pech, gehad.
            continue;
        }

        comment.inhoud = comment_el.select("p").first().html();

        Log.d(TAG + ".perf", "CommentParser: Parsed " + comment.id + ": " + i + "/" + comments_el.size());

        comments.add(comment);
    }

    Comment[] comm = new Comment[comments.size()];
    comments.toArray(comm);
    artikel.comments = comm;

    Log.i(TAG, "GETARTICLE: DONE");

    return artikel;
}

From source file:com.netscape.cmsutil.util.Utils.java

public static String normalizeString(String string, Boolean keepSpace) {

    if (string == null) {
        return string;
    }//from   ww w .  j a va2 s.  c om

    StringBuffer sb = new StringBuffer();
    StringTokenizer st = null;
    if (keepSpace)
        st = new StringTokenizer(string, "\r\n");
    else
        st = new StringTokenizer(string, "\r\n ");

    while (st.hasMoreTokens()) {
        String nextLine = st.nextToken();
        nextLine = nextLine.trim();
        sb.append(nextLine);
    }
    return sb.toString();
}

From source file:DateParser.java

private static Calendar getCalendar(String isodate) {
    // YYYY-MM-DDThh:mm:ss.sTZD
    StringTokenizer st = new StringTokenizer(isodate, "-T:.+Z", true);

    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.clear();/* www. java  2  s .c  o  m*/
    try {
        // Year
        if (st.hasMoreTokens()) {
            int year = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.YEAR, year);
        } else {
            return calendar;
        }
        // Month
        if (check(st, "-") && (st.hasMoreTokens())) {
            int month = Integer.parseInt(st.nextToken()) - 1;
            calendar.set(Calendar.MONTH, month);
        } else {
            return calendar;
        }
        // Day
        if (check(st, "-") && (st.hasMoreTokens())) {
            int day = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.DAY_OF_MONTH, day);
        } else {
            return calendar;
        }
        // Hour
        if (check(st, "T") && (st.hasMoreTokens())) {
            int hour = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.HOUR_OF_DAY, hour);
        } else {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar;
        }
        // Minutes
        if (check(st, ":") && (st.hasMoreTokens())) {
            int minutes = Integer.parseInt(st.nextToken());
            calendar.set(Calendar.MINUTE, minutes);
        } else {
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar;
        }

        //
        // Not mandatory now
        //

        // Secondes
        if (!st.hasMoreTokens()) {
            return calendar;
        }
        String tok = st.nextToken();
        if (tok.equals(":")) { // secondes
            if (st.hasMoreTokens()) {
                int secondes = Integer.parseInt(st.nextToken());
                calendar.set(Calendar.SECOND, secondes);
                if (!st.hasMoreTokens()) {
                    return calendar;
                }
                // frac sec
                tok = st.nextToken();
                if (tok.equals(".")) {
                    // bug fixed, thx to Martin Bottcher
                    String nt = st.nextToken();
                    while (nt.length() < 3) {
                        nt += "0";
                    }
                    nt = nt.substring(0, 3); // Cut trailing chars..
                    int millisec = Integer.parseInt(nt);
                    // int millisec = Integer.parseInt(st.nextToken()) * 10;
                    calendar.set(Calendar.MILLISECOND, millisec);
                    if (!st.hasMoreTokens()) {
                        return calendar;
                    }
                    tok = st.nextToken();
                } else {
                    calendar.set(Calendar.MILLISECOND, 0);
                }
            } else {
                throw new RuntimeException("No secondes specified");
            }
        } else {
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        // Timezone
        if (!tok.equals("Z")) { // UTC
            if (!(tok.equals("+") || tok.equals("-"))) {
                throw new RuntimeException("only Z, + or - allowed");
            }
            boolean plus = tok.equals("+");
            if (!st.hasMoreTokens()) {
                throw new RuntimeException("Missing hour field");
            }
            int tzhour = Integer.parseInt(st.nextToken());
            int tzmin = 0;
            if (check(st, ":") && (st.hasMoreTokens())) {
                tzmin = Integer.parseInt(st.nextToken());
            } else {
                throw new RuntimeException("Missing minute field");
            }
            if (plus) {
                calendar.add(Calendar.HOUR, -tzhour);
                calendar.add(Calendar.MINUTE, -tzmin);
            } else {
                calendar.add(Calendar.HOUR, tzhour);
                calendar.add(Calendar.MINUTE, tzmin);
            }
        }
    } catch (NumberFormatException ex) {
        throw new RuntimeException("[" + ex.getMessage() + "] is not an integer");
    }
    return calendar;
}

From source file:es.eucm.eadandroid.homeapp.repository.resourceHandler.RepoResourceHandler.java

/**
 * Uncompresses any zip file//  www  .j a  v a 2 s . c  om
 */
public static void unzip(String path_from, String path_to, String name, boolean deleteZip) {

    StringTokenizer separator = new StringTokenizer(name, ".", true);
    String file_name = separator.nextToken();

    File f = new File(path_to + file_name);

    if (f.exists())
        removeDirectory(f);

    separator = new StringTokenizer(path_to + file_name, "/", true);

    String partial_path = null;
    String total_path = separator.nextToken();

    while (separator.hasMoreElements()) {

        partial_path = separator.nextToken();
        total_path = total_path + partial_path;
        if (!new File(total_path).exists()) {

            if (separator.hasMoreElements())
                total_path = total_path + separator.nextToken();
            else
                (new File(total_path)).mkdir();

        } else
            total_path = total_path + separator.nextToken();

    }

    Enumeration<? extends ZipEntry> entries = null;
    ZipFile zipFile = null;

    try {
        String location_ead = path_from + name;
        zipFile = new ZipFile(location_ead);

        entries = zipFile.entries();

        BufferedOutputStream file;

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            separator = new StringTokenizer(entry.getName(), "/", true);
            partial_path = null;
            total_path = "";

            while (separator.hasMoreElements()) {

                partial_path = separator.nextToken();
                total_path = total_path + partial_path;
                if (!new File(entry.getName()).exists()) {

                    if (separator.hasMoreElements()) {
                        total_path = total_path + separator.nextToken();
                        (new File(path_to + file_name + "/" + total_path)).mkdir();
                    } else {

                        file = new BufferedOutputStream(
                                new FileOutputStream(path_to + file_name + "/" + total_path));

                        System.err.println("Extracting file: " + entry.getName());
                        copyInputStream(zipFile.getInputStream(entry), file);
                    }
                } else {
                    total_path = total_path + separator.nextToken();
                }
            }

        }

        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return;
    }

    if (deleteZip)
        (new File(path_from + name)).delete();

}

From source file:net.sf.jasperreports.charts.util.ChartUtil.java

private static int[] getCoordinates(ChartEntity entity) {
    int[] coordinates = null;
    String shapeCoords = entity.getShapeCoords();
    if (shapeCoords != null && shapeCoords.length() > 0) {
        StringTokenizer tokens = new StringTokenizer(shapeCoords, ",");
        coordinates = new int[tokens.countTokens()];
        int idx = 0;
        while (tokens.hasMoreTokens()) {
            String coord = tokens.nextToken();
            coordinates[idx] = Integer.parseInt(coord);
            ++idx;/*w  w  w.j a v  a2 s.  c  o  m*/
        }
    }
    return coordinates;
}

From source file:Main.java

/**
 * Return current IP address as byte array, for V4 that will be 4 bytes for
 * V6 16./*from ww  w  .  jav  a2s .c om*/
 * 
 * @param address
 *            String representation of IP address. Both V4 and V6 type
 *            addresses are accepted.
 * @return IP Byte array representation of the address. Check Array.length
 *         to get the size of the array.
 */
public static byte[] parseByteArray(String address) throws IllegalArgumentException {

    StringTokenizer st;
    byte[] v;

    if (address.indexOf('.') != -1) {
        st = new StringTokenizer(address, ".");
        v = new byte[4];
    } else if (address.indexOf(':') != -1) {
        st = new StringTokenizer(address, ":");
        v = new byte[16];
    } else {
        throw new IllegalArgumentException(
                "Illegal IP address format. Expected a string in either '.' or ':' notation");
    }

    for (int i = 0; i < v.length; i++) {
        String t = st.nextToken();

        if (t == null && i != v.length) {
            throw new IllegalArgumentException("Illegal IP address format. String has too few byte elements.");
        }

        v[i] = (byte) Integer.parseInt(t);
    }

    return (v);
}

From source file:correospingtelnet.Telnet.java

/***
 * Main for the TelnetClientExample.//from  ww  w  .  j  ava  2  s.c  o m
 * @param args input params
 * @throws Exception on error
 ***/

public static void doTelnet(String ip) throws Exception {
    FileOutputStream fout = null;

    String remoteip = ip;

    int remoteport = 23;

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new Telnet());
            tc.registerNotifHandler(new Telnet());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");
            System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        final String line = new String(buff, 0, ret_read); // deliberate use of default charset
                        if (line.startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if (line.startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if (line.startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if (line.startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if (line.startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if (line.startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else if (line.matches("^\\^[A-Z^]\\r?\\n?$")) {
                            byte toSend = buff[1];
                            if (toSend == '^') {
                                outstr.write(toSend);
                            } else {
                                outstr.write(toSend - 'A' + 1);
                            }
                            outstr.flush();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.izforge.izpack.util.IoHelper.java

/**
 * Loads all environment variables via an exec.
 *///from   w w w  . j av a2  s  . co  m
private static void loadEnv() {
    String[] output = new String[2];
    String[] params;
    if (OsVersion.IS_WINDOWS) {
        String command = "cmd.exe";
        if (System.getProperty("os.name").toLowerCase().contains("windows 9")) {
            command = "command.com";
        }
        params = new String[] { command, "/C", "set" };
    } else {
        params = new String[] { "env" };
    }
    FileExecutor fe = new FileExecutor();
    fe.executeCommand(params, output);
    if (output[0].length() <= 0) {
        return;
    }
    String lineSep = System.getProperty("line.separator");
    StringTokenizer tokenizer = new StringTokenizer(output[0], lineSep);
    envVars = new Properties();
    String var = null;
    while (tokenizer.hasMoreTokens()) {
        String line = tokenizer.nextToken();
        if (line.indexOf('=') == -1) { // May be a env var with a new line in it.
            if (var == null) {
                var = lineSep + line;
            } else {
                var += lineSep + line;
            }
        } else { // New var, perform the previous one.
            setEnvVar(var);
            var = line;
        }
    }
    setEnvVar(var);
}