Example usage for java.util StringTokenizer hasMoreTokens

List of usage examples for java.util StringTokenizer hasMoreTokens

Introduction

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

Prototype

public boolean hasMoreTokens() 

Source Link

Document

Tests if there are more tokens available from this tokenizer's string.

Usage

From source file:ca.uhn.fhir.rest.server.RestfulServerUtils.java

public static PreferReturnEnum parsePreferHeader(String theValue) {
    if (isBlank(theValue)) {
        return null;
    }/* w w w .ja  v a  2  s. c  o  m*/

    StringTokenizer tok = new StringTokenizer(theValue, ",");
    while (tok.hasMoreTokens()) {
        String next = tok.nextToken();
        int eqIndex = next.indexOf('=');
        if (eqIndex == -1 || eqIndex >= next.length() - 2) {
            continue;
        }

        String key = next.substring(0, eqIndex).trim();
        if (key.equals(Constants.HEADER_PREFER_RETURN) == false) {
            continue;
        }

        String value = next.substring(eqIndex + 1).trim();
        if (value.length() < 2) {
            continue;
        }
        if ('"' == value.charAt(0) && '"' == value.charAt(value.length() - 1)) {
            value = value.substring(1, value.length() - 1);
        }

        return PreferReturnEnum.fromHeaderValue(value);
    }

    return null;
}

From source file:it.greenvulcano.util.txt.TextUtils.java

/**
 * Replaces SQL invalid chars within <tt>input</tt> String with the
 * corresponding entities.//  w  ww . j  a  v  a 2 s .  com
 * 
 * @param input
 *        the input <tt>String</tt>.
 * @return the input string, with SQL invalid chars replaced by the
 *         corresponding entities.
 */
public static String replaceSQLInvalidChars(String input) {
    // Shortcuts for efficiency
    final int len;
    if ((input == null) || ((len = input.length()) == 0)) {
        return input;
    }

    StringBuffer result = new StringBuffer((int) (len * 1.5));
    StringTokenizer tokenizer = new StringTokenizer(input, sqlInvalid, true);
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        Object repl = sqlReplacements.get(token);
        if (repl == null) {
            repl = token;
        }
        result.append((String) repl);
    }
    return result.toString();
}

From source file:luceneindexdemo.LuceneIndexDemo.java

public static void searchIndex(String s) throws IOException, ParseException, SQLException,
        FileNotFoundException, org.json.simple.parser.ParseException {

    Directory directory = FSDirectory.getDirectory(INDEX_DIRECTORY);
    IndexReader reader = IndexReader.open(directory);
    IndexSearcher search = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    QueryParser queryparser = new QueryParser(FIELD_CONTENTS, analyzer);
    Query query = queryparser.parse(s);
    Hits hits = search.search(query);//w w w  .j  av  a2s.c  o  m
    Iterator<Hit> it = hits.iterator();
    //System.out.println("hits:"+hits.length());
    float f_score;
    List<String> names = new ArrayList<>();
    while (it.hasNext()) {
        Hit hit = it.next();
        f_score = hit.getScore();

        //System.out.println(f_score);
        Document document = hit.getDocument();
        Field f = document.getField(FIELD_PATH);

        //System.out.println(f.readerValue());
        //System.out.println(document.getValues(FIELD_PATH));
        String path = document.get(FIELD_PATH);
        System.out.println(document.getValues(path));
        Field con = document.getField(FIELD_PATH);
        //System.out.println("hit:"+path+" "+hit.getId()+" "+con);
        names.add(new File(path).getName());
    }

    //ProcessBuilder pb=new ProcessBuilder();
    FileReader fReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/inntell.json");
    JSONParser jsParser = new JSONParser();
    //System.out.println("This is an assumption that you belong to US");
    FileReader freReader = new FileReader("/home/rishav12/NetBeansProjects/LuceneIndexDemo/location.json");
    Connection con = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
    System.out.println(names);
    if (names.get(0).equals("miss")) {

        System.out.println(s);
        StringTokenizer stringTokenizer = new StringTokenizer(s);
        Connection con1 = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
        String querySearch = "match ()-[r:KNOWS]-() where has(r.relType) return distinct r.relType";
        ResultSet rSet = con.createStatement().executeQuery(querySearch);
        List<String> allRels = new ArrayList<>();
        while (rSet.next()) {
            System.out.println();
            allRels.add(rSet.getString("r.relType"));
        }
        //System.out.println(rSet);

        while (stringTokenizer.hasMoreTokens()) {
            String next = stringTokenizer.nextToken();
            if (allRels.contains(next)) {
                missOperation(next);
            }
            //System.out.println(resSet.getString("r.relType"));

        }
        System.out.println(names.get(1));
        //missOperation(names.get(1));
    } else {
        try {
            JSONObject jsonObj = (JSONObject) jsParser.parse(fReader);
            System.out.println(names.get(0));

            JSONObject jsObj = (JSONObject) jsonObj.get(names.get(0));
            JSONObject results = new JSONObject();
            System.out.println(jsObj.get("explaination"));
            results.put("explaination", jsObj.get("explaination"));
            JSONArray reqmts = (JSONArray) jsObj.get("true");
            System.out.println("Let me look out for the places that contains ");
            List<String> lis = new ArrayList<>();
            JSONObject locObj = (JSONObject) jsParser.parse(freReader);
            JSONArray jsArray = (JSONArray) locObj.get("CHENNAI");
            Iterator<JSONArray> ite = reqmts.iterator();
            int k = 0;
            String resQuery = "START n=node:restaurant('withinDistance:[" + jsArray.get(0) + ","
                    + jsArray.get(1) + ",7.5]') where";
            Iterator<JSONArray> ite1 = reqmts.iterator();
            while (ite1.hasNext())
                System.out.println(ite1.next());

            while (ite.hasNext()) {
                lis.add("n.type=" + "'" + ite.next() + "'");
                if (k == 0)
                    resQuery += " " + lis.get(k);
                else
                    resQuery += " or " + lis.get(k);
                //System.out.println(attrib);
                k++;

            }
            resQuery += " return n.name,n.place,n.type";
            File writeTo = new File(
                    "/home/rishav12/NetBeansProjects/LuceneIndexDemo/filestoIndex1/" + names.get(0));
            FileOutputStream fop = new FileOutputStream(writeTo, true);
            String writeTOFile = s + "\n";
            fop.write(writeTOFile.getBytes());
            //System.out.println(resQuery);
            ResultSet res = con.createStatement().executeQuery(resQuery);
            JSONArray resSet = new JSONArray();

            while (res.next()) {
                System.out.println(" name:" + res.getString("n.name") + " located:" + res.getString("n.place")
                        + " type:" + res.getString("n.type"));
                JSONObject jsPart = new JSONObject();
                jsPart.put("name", res.getString("n.name"));
                jsPart.put("located", res.getString("n.place"));
                jsPart.put("type", res.getString("n.type"));
                resSet.add(jsPart);
            }
            results.put("results", resSet);
            File resultFile = new File("result.json");
            FileOutputStream fop1 = new FileOutputStream(resultFile);
            System.out.println(results);
            fop1.write(results.toJSONString().getBytes());
            //String resQuery="START n=node:restaurant('withinDistance:[40.7305991, -73.9865812,10.0]') where n.coffee=true return n.name,n.address;";
            //System.out.println("Sir these results are for some coffee shops nearby NEW YORK");
            //ResultSet res=con.createStatement().executeQuery(resQuery);
            //while(res.next())
            //System.out.println("name: "+res.getString("n.name")+" address: "+res.getString("n.address"));
        } catch (org.json.simple.parser.ParseException ex) {
            Logger.getLogger(LuceneIndexDemo.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

From source file:com.wegas.core.Helper.java

/**
 * Encode a String to look like a JavaScript variable.
 *
 * @param name String to encode/*from   ww w  . ja v a  2s  .  c om*/
 * @return a String which will be understandable by JavaScript as a var
 */
public static String camelCasify(String name) {
    if (name.isEmpty()) {
        throw new NullPointerException("Name is empty");
    }
    StringBuilder sb = new StringBuilder();
    StringTokenizer st = new StringTokenizer(name);
    String tmp;
    Boolean first = true;
    while (st.hasMoreTokens()) { //CamelCase the name except first word (instance like)
        tmp = st.nextToken();
        if (first) {
            sb.append(tmp.substring(0, 1).toLowerCase());
            first = false;
        } else {
            sb.append(tmp.substring(0, 1).toUpperCase());
        }
        sb.append(tmp.substring(1));
        //sb.append(tmp.substring(1).toLowerCase());
    }
    return sb.toString();
}

From source file:it.univpm.deit.semedia.musicuri.core.Toolset.java

/**
 * Removes the first occurence of an integer within a String. It is used to 
 * remove the integer test case identifier from filenames that are used for 
 * testing and evaluation purposes in this project
 * @param filename the filename to remove the identifier from
 * @return a string containing the filename without an identifier
 */// w  w w.j  a  v a2  s . c o  m
public static String removeTestCaseIdentifier(String filename) {
    String filenameWithoutIdentifier;
    StringTokenizer tok = new StringTokenizer(filename, " `~!@#$%^&*()_-+={}[]|\\:;\"'<>,.?/\t\n\r");
    int numOfTokensInString = tok.countTokens();
    String[] tokens = new String[numOfTokensInString];
    int i = 0;
    while (tok.hasMoreTokens()) {
        String token = tok.nextToken();
        tokens[i] = token;
        i++;
    }

    try {
        Integer tmp = new Integer(tokens[0]);
        int testCaseId = tmp.intValue();
        String identifier = "";
        if (testCaseId >= 1) {
            // add zero padding
            if (testCaseId >= 0 && testCaseId < 10)
                identifier = "000" + testCaseId + " ";
            if (testCaseId >= 10 && testCaseId < 100)
                identifier = "00" + testCaseId + " ";
            if (testCaseId >= 100 && testCaseId < 1000)
                identifier = "0" + testCaseId + " ";
            if (testCaseId > 1000)
                identifier = testCaseId + " ";
        }
        filenameWithoutIdentifier = filename.replaceFirst(identifier, "");
    } catch (NumberFormatException e) {
        // if the first token was not an integer identifier, return what you got as input
        filenameWithoutIdentifier = filename;
    }
    return filenameWithoutIdentifier;
}

From source file:com.free.exception.ExceptionHelper.java

/**
 * <p>/* www.  j  av a 2s  .c o m*/
 * Functionality shared between the <code>getStackFrames(Throwable)</code>
 * methods of this and the
 * {@link org.apache.commons.lang.exception.NestableDelegate} classes.
 * </p>
 */
static String[] getStackFrames(String stackTrace) {
    String linebreak = LINE_SEPARATOR;
    StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
    List<String> list = new LinkedList<String>();
    while (frames.hasMoreTokens()) {
        list.add(frames.nextToken());
    }
    return (String[]) list.toArray(new String[list.size()]);
}

From source file:com.salesmanager.core.util.ShippingUtil.java

/**
 * returns a map index - List 0 --- ShippingPriceRegion -------------String
 * -------------String 1 --- ShippingPriceRegion -------------String
 * -------------String/*from   w  w  w.j  a  v  a 2  s  .  c  o m*/
 */

public static Map buildShippingPriceRegionMap(String countryIsoCode, String zonesConfigurationLine,
        String estimateConfigurationLine) throws Exception {

    Map returnmap = new TreeMap();
    StringTokenizer cvtk = null;
    String countryline = null;
    int i = 1;

    if (!StringUtils.isBlank(zonesConfigurationLine)) {

        cvtk = new StringTokenizer(zonesConfigurationLine, "|");

        while (cvtk.hasMoreTokens()) {
            ShippingPriceRegion spr = null;
            if (returnmap.containsKey(i)) {
                spr = (ShippingPriceRegion) returnmap.get(i);
            } else {
                spr = new ShippingPriceRegion();
            }
            countryline = cvtk.nextToken();// maxpound:price,maxpound:price...|
            if (!countryline.equals("*")) {
                StringTokenizer countrystk = new StringTokenizer(countryline, ";");
                String country = null;
                StringBuffer countrline = new StringBuffer();
                while (countrystk.hasMoreTokens()) {
                    country = countrystk.nextToken();
                    if (countryIsoCode != null && country.equals(countryIsoCode)) {

                    }
                    // now get maxpound and price
                    spr.addCountry(country);
                    countrline.append(country).append(";");
                }
                String line = countrline.toString();
                spr.setCountryline(line.substring(0, line.length() - 1));
            }
            returnmap.put(i, spr);
            i++;
        }

    }

    // estimate

    if (!StringUtils.isBlank(estimateConfigurationLine)) {

        cvtk = new StringTokenizer(estimateConfigurationLine, "|");// index:<MINCOST>;<MAXCOST>|
        countryline = null;
        i = 1;
        while (cvtk.hasMoreTokens()) {

            countryline = cvtk.nextToken();// index:<MINCOST>;<MAXCOST>

            StringTokenizer indextk = new StringTokenizer(countryline, ":");// index
            String configLine = null;
            int indexCount = 1;
            ShippingPriceRegion spr = null;
            while (indextk != null && indextk.hasMoreTokens()) {
                configLine = indextk.nextToken();

                if (indexCount == 1) {// countries
                    try {
                        int index = Integer.parseInt(configLine);
                        spr = (ShippingPriceRegion) returnmap.get(index);
                        if (spr != null) {
                            spr.setEstimatedTimeEnabled(true);
                        }
                    } catch (Exception e) {
                        // log.error("Cannot parse to an integer " +
                        // configLine);
                    }
                }
                if (indexCount == 2) {// days
                    // parse dates <mindate>;<maxdate>
                    StringTokenizer datetk = new StringTokenizer(configLine, ";");// date
                    int dateCount = 1;
                    while (datetk != null && datetk.hasMoreTokens()) {
                        String date = (String) datetk.nextToken();

                        try {

                            if (spr != null) {
                                if (dateCount == 1) {
                                    spr.setMinDays(Integer.parseInt(date));
                                }
                                if (dateCount == 2) {
                                    spr.setMaxDays(Integer.parseInt(date));
                                }
                            }

                        } catch (Exception e) {
                            // log.error("Cannot parse integer " + date);
                        }

                        dateCount++;
                    }
                }
                indexCount++;
            }
            i++;
        }

    }

    return returnmap;

}

From source file:edu.psu.iam.cpr.core.util.Utility.java

/**
 * Return a List of name tokens//from   w  ww.  j  a  v  a  2  s  .  c  o m
 *
 * @param names is a comma separated String
 * @return will a List of Strings
 */
public static List<String> getNameTokens(final String names) {
    List<String> listNames = new ArrayList<String>();
    if (fieldIsPresent(names)) {
        StringTokenizer stkn = new StringTokenizer(names, " ,");
        while (stkn.hasMoreTokens()) {
            String aName = stkn.nextToken();
            if (aName.trim().length() > 0) {
                listNames.add(aName);
            }
        }
    }

    return listNames;
}

From source file:fr.paris.lutece.portal.service.mail.MailUtil.java

/**
 * Extract The list of String Address content in the string strRecipients
 * @return The list of String Address content in the string strRecipients
 * @param strRecipients The list of recipient separated by the mail
 *            separator defined in config.properties
 *
 *//*from w w w  . ja v a  2 s. c  o m*/
public static List<String> getAllStringAdressOfRecipients(String strRecipients) {
    StringTokenizer st = new StringTokenizer(strRecipients,
            AppPropertiesService.getProperty(PROPERTY_MAIL_LIST_SEPARATOR, ";"));
    List<String> listRecipients = new ArrayList<String>();

    while (st.hasMoreTokens()) {
        listRecipients.add(st.nextToken());
    }

    return listRecipients;
}

From source file:marytts.util.string.StringUtils.java

/**
 * Divides the example text of a voice into
 * sentences in a vector/*  w w  w  .j  a v a2  s .c  o  m*/
 * @param text the example text
 * @return vector of example sentences
 */
public static Vector<String> processVoiceExampleText(String text) {
    StringTokenizer st = new StringTokenizer(text, "#");
    Vector<String> sentences = null;

    while (st.hasMoreTokens()) {
        if (sentences == null)
            sentences = new Vector<String>();

        sentences.add(st.nextToken());
    }

    return sentences;
}