Example usage for java.util StringTokenizer nextElement

List of usage examples for java.util StringTokenizer nextElement

Introduction

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

Prototype

public Object nextElement() 

Source Link

Document

Returns the same value as the nextToken method, except that its declared return value is Object rather than String .

Usage

From source file:util.IPChecker.java

private boolean compareIP4(final String ip, final String ip_db) {

    try {//  w  ww . j  ava 2 s.c o m

        String compare = ip_db.substring(ip.indexOf('.', ip.indexOf('.') + 1) + 1);

        final List<String> parts = new ArrayList<String>();
        final StringTokenizer tokenizer = new StringTokenizer(ip, ".");
        while (tokenizer.hasMoreElements()) {
            parts.add(tokenizer.nextElement().toString());
        }

        final String part3 = parts.get(2);
        String part4 = null;
        if (parts.size() == 4) {
            part4 = parts.get(3);
        }

        // Wildcard oder Bereich im dritten Oktett
        if (!compare.contains(".") || part4 == null) {
            // we may have an compare with .
            if (compare.contains(".")) {
                // reset compare to 3th part
                compare = compare.substring(0, compare.indexOf("."));
            }
            if ("*".equals(compare) || "*".equals(part3)) {
                // Wildcard in IP from request or from DB in 3th part
                return true;
            }
            if (compare.contains("-")) { // Bereich
                final int compStart = Integer.valueOf(compare.substring(0, compare.indexOf('-')));
                final int compEnd = Integer.valueOf(compare.substring(compare.indexOf('-') + 1));

                if (part3.contains("-")) {
                    // 3th part contains range
                    final int okt3Start = Integer.valueOf(part3.substring(0, part3.indexOf('-')));
                    final int okt3End = Integer.valueOf(part3.substring(part3.indexOf('-') + 1));
                    if (compStart <= okt3Start && okt3Start <= compEnd
                            || compStart <= okt3End && okt3End <= compEnd
                            || okt3Start <= compStart && compStart <= okt3End) {
                        return true;
                    }
                } else {
                    // 3th part is normal number
                    final int okt3 = Integer.valueOf(part3);
                    if (compStart <= okt3 && okt3 <= compEnd) {
                        return true;
                    }
                }
            } else if (part3.contains("-")) {
                final int part3Start = Integer.valueOf(part3.substring(0, part3.indexOf('-')));
                final int part3End = Integer.valueOf(part3.substring(part3.indexOf('-') + 1));

                // compare is normal number
                final int comp3 = Integer.valueOf(compare);
                if (part3Start <= comp3 && comp3 <= part3End) {
                    return true;
                }

            }

        } else { // Wildcard oder Bereich im vierten Oktett
            final String compare3 = compare.substring(0, compare.indexOf('.'));
            final String compare4 = compare.substring(compare.indexOf('.') + 1);
            if (compare3.equals(part3)) { // 3th part must match
                if ("*".equals(compare4) || "*".equals(part4)) {
                    // Wildcard in IP from request or from DB in 4th part
                    return true;
                }
                if (compare4.contains("-")) { // Bereich
                    final int compStart = Integer.valueOf(compare4.substring(0, compare4.indexOf('-')));
                    final int compEnd = Integer.valueOf(compare4.substring(compare4.indexOf('-') + 1));

                    if (part4.contains("-")) {
                        // 4th part contains range
                        final int okt4Start = Integer.valueOf(part4.substring(0, part4.indexOf('-')));
                        final int okt4End = Integer.valueOf(part4.substring(part4.indexOf('-') + 1));
                        if (compStart <= okt4Start && okt4Start <= compEnd
                                || compStart <= okt4End && okt4End <= compEnd
                                || okt4Start <= compStart && compStart <= okt4End) {
                            return true;
                        }
                    } else {
                        // 4th part is normal number
                        final int okt4 = Integer.valueOf(part4);
                        if (compStart <= okt4 && okt4 <= compEnd) {
                            return true;
                        }
                    }
                }
            }
        }

    } catch (final Exception e) {
        LOG.error("boolean compareIP4(String ip, String ip_db): " + e.toString());
    }

    return false;
}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * Returns a list of the most popular data sets. The title, id and rating of
 * each data set are provided.//from   w w w. j  a  v  a  2  s  .c  om
 * 
 * @param numberOfDatasets
 *            the number of data sets to return.
 * 
 * @return null in case of an error, or a hash map with the latest data sets
 *         including id, rating, title.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static HashMap getMostPopularDatasets(int numberOfDatasets) {
    // check the parameter
    if (numberOfDatasets <= 0) {
        return null;
    }

    // get all the meta data sets
    HashMap hm = CKANGatewayCore.viewDataSets();

    if (hm == null) {
        return null;
    }

    // prepare the variable to return
    HashMap toreturn = new HashMap();

    // help variables for the sorting according to the averaged rating
    HashMap<String, String> relationMap = new HashMap<String, String>();
    ArrayList<String> sList = new ArrayList<String>();

    // iterate over the data sets
    Set<String> keys = (hm.keySet());
    Iterator<String> it = keys.iterator();

    while (it.hasNext()) {
        String key = it.next();

        // get the Map for the next object
        Map m = (Map) hm.get(key);

        // get the JSONArray with the ratings and pass it to the method for
        // calculating the average
        Map eMap = ((Map) m.get("extras"));
        String aRatingStr = "-1";
        if (eMap != null) {
            JSONArray arr = null;
            try {
                if (eMap.get("ratings") instanceof java.lang.String) {
                    JSONParser parser = new JSONParser();
                    arr = (JSONArray) parser.parse((String) eMap.get("ratings"));
                } else
                    arr = (JSONArray) eMap.get("ratings");
            } catch (ParseException e) {
                log.log(Level.SEVERE, "Failed to parse result" + (String) eMap.get("ratings"));
            }

            double averagedRating = calculateAverageRating(arr);
            aRatingStr = new Double(averagedRating).toString();
        }
        // set the data in the help variables
        relationMap.put(aRatingStr + ":" + key, key);
        sList.add(aRatingStr + ":" + key);
    }

    // sort the list with the averaged
    Collections.sort(sList);

    // the variable for counting the added data sets
    int countDataSets = 1;

    // iterate over the sorted list
    for (int i = sList.size() - 1; i >= 0; i--) {

        // check whether the required number of data sets are obtained
        if (countDataSets > numberOfDatasets) {
            break;
        }

        // get the current averaged rating string
        String aRatingStr = sList.get(i);

        // get the corresponding key
        String key = relationMap.get(aRatingStr);

        // get the data set belonging to this key
        Map dSetMap = (Map) hm.get(key);

        // prepare a new hash that represents the map
        Map value = new HashMap();

        value.put("name", dSetMap.get("name"));
        value.put("id", dSetMap.get("id"));
        value.put("title", dSetMap.get("title"));

        StringTokenizer tk = new StringTokenizer(aRatingStr, ":");
        value.put("rating", tk.nextElement());

        // add the data to the to return HashMap
        toreturn.put(key, value);

        // increase the counter for the data sets
        countDataSets++;
    }

    return toreturn;
}

From source file:org.openremote.controller.protocol.telnet.TelnetCommand.java

public void send(boolean readResponse) {
    TelnetClient tc = null;/*w  w w . j  av  a2  s .c o  m*/
    if (readResponse) {
        setResponse("");
    }
    try {
        tc = new TelnetClient();
        tc.connect(getIp(), Integer.parseInt(getPort()));
        StringTokenizer st = new StringTokenizer(getCommand(), "|");
        int count = 0;
        if (getCommand().startsWith("|")) {
            count++;
        }
        String waitFor = "";
        while (st.hasMoreElements()) {
            String cmd = (String) st.nextElement();
            if (count % 2 == 0) {
                waitFor = cmd;
                if (!"null".equals(cmd)) {
                    waitForString(cmd, tc);
                }
            } else {
                sendString(cmd, tc);
                if (readResponse) {
                    readString(waitFor, tc);
                }
            }
            count++;
        }
    } catch (Exception e) {
        logger.error("could not perform telnetEvent", e);
    } finally {
        if (tc != null) {
            try {
                tc.disconnect();
            } catch (IOException e) {
                logger.error("could not disconnect from telnet", e);
            }
        }
    }
}

From source file:ro.cs.cm.common.TextTable.java

public void addRow(String theRow, byte aRowAlign) {
    // dk am speficat ca nu avem nici o linie (doar headerul)
    // nu face nimic
    // adaug inca o linie la matricea tabel
    // log.debug("addRow() -> CurrentRowNo begin = " + currentRowNo);
    if (currentRowNo > MAX_NO_OF_ROWS_ALLOWED) {
        logger.info("No of allowed cols ".concat(String.valueOf(MAX_NO_OF_ROWS_ALLOWED)));
    }/* w  ww  .  j a va2s  .c o  m*/
    ArrayList<String> row = new ArrayList<String>();
    StringTokenizer st = new StringTokenizer(theRow, ELEMENT_SEPARATOR);
    rowAlign.add(new Byte(aRowAlign));
    int j = 0;
    boolean amAvutCaracterEndLine = false;
    StringBuffer sb = new StringBuffer();
    while (st.hasMoreElements()) {
        // punem un spatiu in stanga si in dreapta continutului
        sb.delete(0, sb.length()); // resetez StringBufferul
        sb.append(" ");
        String s = (String) st.nextElement();
        if (s.indexOf('\n') != -1) {
            s = s.replace('\n', '?');
            amAvutCaracterEndLine = true;
        }
        sb.append(s);
        sb.append(" ");
        row.add(sb.toString());
    }
    // in cazul in care o linie nu este completa (ca numar de coloane),
    // completez
    if (j < header.length) {
        for (int i = j; i < header.length; row.add(" "), i++) {
            ;
        }
    }
    if (amAvutCaracterEndLine) {
        row.add(" (? = \\n)");
    }
    table.add(row);
    // incrementez variabila statica currentRow pentru
    // a stii nr. de ordine al urmatoarei linii adaugate
    currentRowNo++;
    // log.debug("addRow() -> CurrentRowNo end = " + currentRowNo);
}

From source file:org.chiba.xml.xforms.connector.SchemaValidator.java

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 */// ww w  .j a v a  2  s.c  o  m
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

From source file:org.wso2.carbon.identity.openidconnect.SAMLAssertionClaimsCallback.java

/**
 * Set claims from a Users claims Map object to a JWTClaimsSet object
 * @param claims Users claims//ww w.  j  av a2s  . c om
 * @param jwtClaimsSet JWTClaimsSet object
 */
private void setClaimsToJwtClaimSet(Map<String, Object> claims, JWTClaimsSet jwtClaimsSet) {
    JSONArray values;
    Object claimSeparator = claims.get(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
    if (claimSeparator != null) {
        String claimSeparatorString = (String) claimSeparator;
        if (StringUtils.isNotBlank(claimSeparatorString)) {
            userAttributeSeparator = (String) claimSeparator;
        }
        claims.remove(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR);
    }

    for (Map.Entry<String, Object> entry : claims.entrySet()) {
        String value = entry.getValue().toString();
        values = new JSONArray();
        if (userAttributeSeparator != null && value.contains(userAttributeSeparator)) {
            StringTokenizer st = new StringTokenizer(value, userAttributeSeparator);
            while (st.hasMoreElements()) {
                String attributeValue = st.nextElement().toString();
                if (StringUtils.isNotBlank(attributeValue)) {
                    values.add(attributeValue);
                }
            }
            jwtClaimsSet.setClaim(entry.getKey(), values);
        } else {
            jwtClaimsSet.setClaim(entry.getKey(), value);
        }
    }
}

From source file:org.apache.torque.map.TableMap.java

/**
 * Removes the PREFIX, removes the underscores and makes
 * first letter caps./*from   ww  w. ja  va 2  s.c  o m*/
 *
 * SCARAB_FOO_BAR becomes FooBar.
 *
 * @param data A String.
 * @return A String with data processed.
 */
public final String removeUnderScores(String data) {
    String tmp = null;
    StringBuffer out = new StringBuffer();
    if (hasPrefix(data)) {
        tmp = removePrefix(data);
    } else {
        tmp = data;
    }

    StringTokenizer st = new StringTokenizer(tmp, "_");
    while (st.hasMoreTokens()) {
        String element = ((String) st.nextElement()).toLowerCase();
        out.append(StringUtils.capitalize(element));
    }
    return out.toString();
}

From source file:eu.aniketos.scpm.userinterface.views.ScpmUI.java

/**
 * @see loadBPMN//from w ww  . j a va 2 s  .co  m
 * @see getExtensions() When generates a *.activiti file from *.bpmn20.xml
 *      file, The Activiti designer only copes with the original
 *      tags/elements. Any security extensions that embedded in the
 *      composition plan by SCF have to be abstracted manually. This method
 *      saves security extensions into the activiti file.
 * 
 * @param id
 *            The ID of element to be saved.
 * @param attributes
 *            Value of the extended attributes.
 * @param bpmn2Element
 *            The element to be parsed.
 */

private static void setExtensions(String id, List<String> attributes, List<org.w3c.dom.Element> bpmn2Element) {

    for (int index = 0; index < bpmn2Element.size(); index++) {
        // System.out.println(getAttValue("id", bpmn2Element.get(index)));
        if (getAttValue("id", bpmn2Element.get(index)).equals(id)) {
            String fieldPosition = getAttValue("fieldExtensions", bpmn2Element.get(index));
            StringTokenizer str = new StringTokenizer(fieldPosition);

            int attNumber = 0;

            while (str.hasMoreElements()) {
                String pString = (String) str.nextElement();
                int pInt = Integer.parseInt(pString.substring(1));
                // System.out.println(pInt);
                bpmn2Element.get(pInt - 1).setAttribute("expression", attributes.get(attNumber));
                attNumber++;
            }
        }
    }
}

From source file:org.hfoss.posit.android.sync.Communicator.java

/**
 * The data has the form: [attr=value, ...] or 'null'
 * @param cv//from   ww w  .ja  va2 s. c  o  m
 * @param data
 */
static private void addExtraDataToContentValues(ContentValues cv, String data) {
    Log.i(TAG, "data = " + data + " " + data.length());
    if (data.equals("null"))
        return;
    data = data.trim();
    data = data.substring(1, data.length() - 1);
    StringTokenizer st = new StringTokenizer(data, ",");
    while (st.hasMoreElements()) {
        String attrvalpair = (String) st.nextElement();
        String attr = attrvalpair.substring(0, attrvalpair.indexOf("="));
        attr = attr.trim();
        String val = attrvalpair.substring(attrvalpair.indexOf("=") + 1);
        val = val.trim();
        Log.i(TAG, "Putting " + attr + "=" + val + " into CV");
        if (Integer.getInteger(val) != null)
            cv.put(attr, Integer.parseInt(val));
        //         else if (Boolean.getBoolean(val) != null)
        //            cv.put(attr, Boolean.parseBoolean(val))
        //         else if (Double.getDouble(val) != null))
        //            cv.put(attr, Double.parseDouble(val))
        else
            cv.put(attr, val);
    }

}

From source file:com.impetus.client.neo4j.GraphEntityMapper.java

/**
 * Prepares Embedded ID field from value prepared via
 * serializeIdAttributeValue method./* w w w .  j  a v a  2s.c om*/
 */
private Object deserializeIdAttributeValue(final EntityMetadata m, String idValue) {
    if (idValue == null) {
        return null;
    }
    Class<?> embeddableClass = m.getIdAttribute().getBindableJavaType();
    Object embeddedObject = embeddedObject = KunderaCoreUtils.createNewInstance(embeddableClass);
    List<String> tokens = new ArrayList<String>();
    StringTokenizer st = new StringTokenizer((String) idValue, COMPOSITE_KEY_SEPARATOR);
    while (st.hasMoreTokens()) {
        tokens.add((String) st.nextElement());
    }

    int count = 0;
    for (Field embeddedField : embeddableClass.getDeclaredFields()) {
        if (!ReflectUtils.isTransientOrStatic(embeddedField)) {
            if (count < tokens.size()) {
                String value = tokens.get(count++);
                PropertyAccessorHelper.set(embeddedObject, embeddedField, value);
            }
        }
    }
    return embeddedObject;
}