Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

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

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:com.jaspersoft.jasperserver.war.action.repositoryExplorer.ResourceAction.java

public Event getUriDisplayLabelList(RequestContext context) {

    try {/*from  ww w.  j a  v  a2s .  c o  m*/
        String uriList = URLDecoder.decode((String) context.getRequestParameters().get("uriList"), "UTF-8");
        String type = (String) context.getRequestParameters().get("type");

        StringTokenizer str = new StringTokenizer(uriList, ",");
        StringBuffer sb = new StringBuffer();
        sb.append('{');
        int counter = 0;
        int fromIndex = 1;
        Resource rootFolder = repositoryService.getFolder(null, "/");
        while (str.hasMoreElements()) {
            String currentString = (String) str.nextElement();
            StringBuffer currentDisplayLabel = new StringBuffer("");
            if (currentString.equals("/")) {
                sb.append(
                        "\"" + counter + "\":\"" + "/" + rootFolder.getLabel().replaceAll("<", "&lt;") + "\"");
                counter++;
                continue;
            } else {
                currentDisplayLabel.append("/" + rootFolder.getLabel().replaceAll("<", "&lt;"));
            }
            if (currentString.length() > 1) {
                int lastIndex = currentString.lastIndexOf("/");
                while ((fromIndex = currentString.indexOf('/', fromIndex)) != -1) {
                    String currentUri = currentString.substring(0, currentString.indexOf('/', fromIndex));

                    try {
                        currentDisplayLabel.append("/").append(repositoryService
                                .getFolder(exContext(context), currentUri).getLabel().replaceAll("<", "&lt;"));
                    } catch (Exception e) {
                        currentDisplayLabel.append("/")
                                .append(repositoryService.getResource(exContext(context), currentUri).getLabel()
                                        .replaceAll("<", "&lt;"));
                    }

                    if (lastIndex == fromIndex) {
                        break;
                    }
                    fromIndex++;
                }
                if ((type.equals("resource")) && (counter > 0)) {
                    currentDisplayLabel.append("/").append(repositoryService
                            .getResource(exContext(context), currentString).getLabel().replaceAll("<", "&lt;"));
                } else if (type.equals("folder") || ((type.equals("resource")) && (counter == 0))) {
                    currentDisplayLabel.append("/").append(repositoryService
                            .getFolder(exContext(context), currentString).getLabel().replaceAll("<", "&lt;"));
                }
                // put each full display label into json
                if (counter == 0) {
                    sb.append("\"" + counter + "\":\"" + currentDisplayLabel.toString() + "\"");
                } else {
                    sb.append(",\"" + counter + "\":\"" + currentDisplayLabel.toString() + "\"");
                }
            }
            counter++;
            fromIndex = 1;
        }

        sb.append('}');
        context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString());
    } catch (UnsupportedEncodingException e) {
    }

    return success();
}

From source file:com.metaparadigm.jsonrpc.JSONRPCBridge.java

public JSONRPCResult call(Object context[], JSONObject jsonReq) {
    JSONRPCResult result = null;//from www. j a  v  a2 s.co  m
    String encodedMethod = null;
    Object requestId = null;
    JSONArray arguments = null;

    try {
        // Get method name, arguments and request id
        encodedMethod = jsonReq.getString("method");
        arguments = jsonReq.getJSONArray("params");
        requestId = jsonReq.opt("id");
    } catch (NoSuchElementException e) {
        log.severe("no method or parameters in request");
        return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (isDebug())
        log.fine("call " + encodedMethod + "(" + arguments + ")" + ", requestId=" + requestId);

    String className = null;
    String methodName = null;
    int objectID = 0;

    // Parse the class and methodName
    StringTokenizer t = new StringTokenizer(encodedMethod, ".");
    if (t.hasMoreElements())
        className = t.nextToken();
    if (t.hasMoreElements())
        methodName = t.nextToken();

    // See if we have an object method in the format ".obj#<objectID>"
    if (encodedMethod.startsWith(".obj#")) {
        t = new StringTokenizer(className, "#");
        t.nextToken();
        objectID = Integer.parseInt(t.nextToken());
    }

    ObjectInstance oi = null;
    ClassData cd = null;
    HashMap methodMap = null;
    Method method = null;
    Object itsThis = null;

    if (objectID == 0) {
        // Handle "system.listMethods"
        if (encodedMethod.equals("system.listMethods")) {
            HashSet m = new HashSet();
            globalBridge.allInstanceMethods(m);
            if (globalBridge != this) {
                globalBridge.allStaticMethods(m);
                globalBridge.allInstanceMethods(m);
            }
            allStaticMethods(m);
            allInstanceMethods(m);
            JSONArray methods = new JSONArray();
            Iterator i = m.iterator();
            while (i.hasNext())
                methods.put(i.next());
            return new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, methods);
        }
        // Look up the class, object instance and method objects
        if (className == null || methodName == null
                || ((oi = resolveObject(className)) == null && (cd = resolveClass(className)) == null))
            return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId,
                    JSONRPCResult.MSG_ERR_NOMETHOD);
        if (oi != null) {
            itsThis = oi.o;
            methodMap = oi.classData().methodMap;
        } else {
            methodMap = cd.staticMethodMap;
        }
    } else {
        if ((oi = resolveObject(new Integer(objectID))) == null)
            return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId,
                    JSONRPCResult.MSG_ERR_NOMETHOD);
        itsThis = oi.o;
        methodMap = oi.classData().methodMap;
        // Handle "system.listMethods"
        if (methodName.equals("listMethods")) {
            HashSet m = new HashSet();
            uniqueMethods(m, "", oi.classData().staticMethodMap);
            uniqueMethods(m, "", oi.classData().methodMap);
            JSONArray methods = new JSONArray();
            Iterator i = m.iterator();
            while (i.hasNext())
                methods.put(i.next());
            return new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, methods);
        }
    }

    if ((method = resolveMethod(methodMap, methodName, arguments)) == null)
        return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId, JSONRPCResult.MSG_ERR_NOMETHOD);
    // Call the method
    try {
        if (debug)
            log.fine("invoking " + method.getReturnType().getName() + " " + method.getName() + "("
                    + argSignature(method) + ")");
        Object javaArgs[] = unmarshallArgs(context, method, arguments);
        for (int i = 0; i < context.length; i++)
            preInvokeCallback(context[i], itsThis, method, javaArgs);
        Object o = method.invoke(itsThis, javaArgs);
        for (int i = 0; i < context.length; i++)
            postInvokeCallback(context[i], itsThis, method, o);
        SerializerState state = new SerializerState();
        result = new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, ser.marshall(state, o));
    } catch (UnmarshallException e) {
        for (int i = 0; i < context.length; i++)
            errorCallback(context[i], itsThis, method, e);
        result = new JSONRPCResult(JSONRPCResult.CODE_ERR_UNMARSHALL, requestId, e.getMessage());
    } catch (MarshallException e) {
        for (int i = 0; i < context.length; i++)
            errorCallback(context[i], itsThis, method, e);
        result = new JSONRPCResult(JSONRPCResult.CODE_ERR_MARSHALL, requestId, e.getMessage());
    } catch (Throwable e) {
        if (e instanceof InvocationTargetException)
            e = ((InvocationTargetException) e).getTargetException();
        for (int i = 0; i < context.length; i++)
            errorCallback(context[i], itsThis, method, e);
        result = new JSONRPCResult(JSONRPCResult.CODE_REMOTE_EXCEPTION, requestId, e);
    }

    // Return the results
    return result;
}

From source file:padl.creator.classfile.relationship.RelationshipAnalyzer.java

private Vector createFieldsFromFieldInfos(final String fieldInfos) {
    final Vector callingFields = new Vector();
    final StringTokenizer st = new StringTokenizer(fieldInfos, "#");
    IFirstClassEntity entityDeclaringField = null;
    IField aCallingField = null;/*from  www  . ja  v  a  2s . c o  m*/
    while (st.hasMoreElements()) {

        final String oneFieldInfo = st.nextToken();
        //Extracts the field name
        final String usedFieldName = RelationshipAnalyzer.extractFieldName(oneFieldInfo);

        try {
            //Extracts the entity name that declares the field
            final String entityNameDeclaringField = oneFieldInfo.substring(0, oneFieldInfo.indexOf(" "));

            // Gets from the abstract level model the entity within its name
            entityDeclaringField = Utils.getEntityOrCreateGhost(this.codeLevelModel,
                    entityNameDeclaringField.toCharArray(), RelationshipAnalyzer.MapOfIDsEntities);
            // Yann 2006/02/08: Members!
            // The getConstituentFromID() method takes care of members and ghosts...
            //   // Tests if the entity exists. Otherwise, I create a ghost. 
            //   if (entityDeclaringField == null) {
            //      try {
            //         // Extracts the field type
            //         String fieldType =
            //            RelationshipAnalyzer.extractFieldType(
            //               oneFieldInfo);
            //         final int cardinality =
            //            padl.util.Util.isArrayOrCollection(fieldType)
            //               ? Constants.CARDINALITY_MANY
            //               : Constants.CARDINALITY_ONE;
            //
            //         // Creates a new Ghost and a field by the Factory
            //         entityDeclaringField =
            //            aFactory.createGhost(entityNameDeclaringField);
            //         aCallingField =
            //            aFactory.createField(
            //               usedFieldName,
            //               fieldType,
            //               cardinality);
            //
            //         // The field is added to the new ghost
            //         entityDeclaringField.addConstituent(aCallingField);
            //         anAbstractLevelModel.addConstituent(entityDeclaringField);
            //
            //      }
            //      catch (final ModelDeclarationException e) {
            //         e.printStackTrace(
            //            OutputManager
            //               .getCurrentOutputManager()
            //               .getErrorOutput());
            //      }
            //   }
            //   else {
            aCallingField = (IField) entityDeclaringField.getConstituentFromID(usedFieldName);
            // Yann 2007/01/24: Unneeded test
            // The test of the usedFieldName being empty
            // is only needed because of the bug documented
            // in method extractFieldName()!
            if (aCallingField == null && !usedFieldName.equals("")) {
                final String fieldType = RelationshipAnalyzer.extractFieldType(oneFieldInfo);
                final int cardinality = padl.util.Util.isArrayOrCollection(fieldType.toCharArray())
                        ? Constants.CARDINALITY_MANY
                        : Constants.CARDINALITY_ONE;

                aCallingField = this.codeLevelModel.getFactory().createField(usedFieldName.toCharArray(),
                        usedFieldName.toCharArray(), fieldType.toCharArray(), cardinality);
                aCallingField.setVisibility(Modifier.PUBLIC);
                entityDeclaringField.addConstituent(aCallingField);
            }
            callingFields.add(aCallingField);
        } catch (final Exception e) {
            e.printStackTrace(ProxyConsole.getInstance().errorOutput());
        }
    }
    return callingFields;
}

From source file:com.pureinfo.ark.auth2.domain.impl.Auth2MgrImplBase.java

/**
 * Reloads the configuration./*ww  w .j  av  a2s.  co  m*/
 * 
 * @throws PureException
 *             if failed.
 */
public synchronized void reloadConfig() throws PureException {
    // 1. init or clear
    if (m_hRightDefs == null) {
        m_hBaseDefs = new HashMap();
        m_hRightDefs = new HashMap();
        m_actionDictionary = new ActionDictionary();
    } else if (m_hRightDefs.size() > 0) {
        m_hBaseDefs.clear();
        m_hRightDefs.clear();
        m_actionDictionary.clear();
    }

    //2. to load configuration from file
    String sPath = ClassResourceUtil.mapFullPath(m_sConfigFile, true);
    logger.debug("to load rights config from " + sPath);

    RightsConfig config = new RightsConfig();
    config.fromXML(XMLUtil.fileToElement(sPath));

    //3. to cache base actions
    ActionDef[] actions = config.getActions();
    if (actions != null) {
        for (int i = 0; i < actions.length; i++) {
            m_actionDictionary.put(actions[i]);
        }
    }

    //4. to cache right definitions
    ResourceDef[] resources = config.getResources();
    ResourceDef resource;
    RightDef[] rights;
    BaseDef base;
    RightDef right;
    StringTokenizer stRoles;
    Object oKey;
    for (int i = 0; i < resources.length; i++) {
        resource = resources[i];
        // to cache base def
        base = resource.getBase();
        if (base != null) {
            // to parse right value
            base.parseRight(m_actionDictionary);
            // to cache base
            oKey = new Integer(resource.getTypeId());
            m_hBaseDefs.put(oKey, base);
        }

        //to cache right def
        rights = resource.getRights();
        if (rights == null || rights.length == 0)
            continue; //skip
        for (int j = 0; j < rights.length; j++) {
            right = rights[j];
            right.parseRight(m_actionDictionary);
            stRoles = new StringTokenizer(right.getRoles(), ",");
            while (stRoles.hasMoreElements()) {
                oKey = makeKey(resource.getTypeId(), (String) stRoles.nextElement());
                //logger.debug("RightDef cached: "+oKey);
                m_hRightDefs.put(oKey, right);
            } //endwhile
        }
    } //endfor
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

public static final QueryExpression createFilterInQuery(final String query, final String order,
        final QueryExpression queryExpression, final String crmFieldsSeparator,
        final String orderFieldsSeparator) throws Exception {

    if (query != null) {
        /* Tokenize the where clause */
        final StringTokenizer stringTokenizer = new StringTokenizer(query,
                HTTPConstants.andClause + HTTPConstants.orClause, true);

        /* Create filter expression */
        final FilterExpression filterExpression = queryExpression.addNewCriteria();

        /* Create array of condition expression object */
        final ArrayOfConditionExpression arrayOfConditionExpression = filterExpression.addNewConditions();

        /* Iterate over tokenizer */
        while (stringTokenizer.hasMoreElements()) {
            String tempElement = stringTokenizer.nextToken();

            if (logger.isDebugEnabled()) {
                logger.debug("----Inside createFilterExpression: tempElement: " + tempElement);
            }/*from www. j a  va  2  s . co m*/

            /* Replace 'like' operator case */
            tempElement = replaceLikeOpCase(tempElement);

            /* Check for '!=' operator */
            if (tempElement.contains(notEqualOperator)) {

                /* Validate the element */
                if (tempElement.split(notEqualOperator).length < 2) {
                    throw new ScribeException(
                            ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'");
                }

                /* Create condition expression */
                final ConditionExpression conditionExpression = arrayOfConditionExpression.addNewCondition();

                /* Set attribute name */
                conditionExpression.setAttributeName(tempElement.split(notEqualOperator)[0].trim());

                /* Check for 'NULL' values */
                if (tempElement.split(notEqualOperator)[1].trim().toUpperCase()
                        .equalsIgnoreCase(nullConstant)) {

                    /* Set Nill value */
                    conditionExpression.setOperator(ConditionOperator.NOT_NULL);
                } else {

                    /* Set operator as 'NOT_EQUAL' */
                    conditionExpression.setOperator(ConditionOperator.NOT_EQUAL);

                    /* Set value */
                    final ArrayOfAnyType arrayOfAnyType = ArrayOfAnyType.Factory.newInstance();
                    arrayOfAnyType.addNewValue();
                    arrayOfAnyType.setValueArray(0,
                            XmlString.Factory.newValue(tempElement.split(notEqualOperator)[1].trim()));
                    conditionExpression.setValues(arrayOfAnyType);
                }
            } else /* Check for '=' operator */
            if (tempElement.contains(equalOperator)) {

                /* Validate the element */
                if (tempElement.split(equalOperator).length < 2) {
                    throw new ScribeException(
                            ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'");
                }

                /* Create condition expression */
                final ConditionExpression conditionExpression = arrayOfConditionExpression.addNewCondition();

                /* Set attribute name */
                conditionExpression.setAttributeName(tempElement.split(equalOperator)[0].trim());

                /* Check for 'NULL' values */
                if (tempElement.split(equalOperator)[1].trim().toUpperCase().equalsIgnoreCase(nullConstant)) {

                    /* Set Nill value */
                    conditionExpression.setOperator(ConditionOperator.NULL);
                } else {

                    /* Set operator as 'EQUAL' */
                    conditionExpression.setOperator(ConditionOperator.EQUAL);

                    /* Set value */
                    final ArrayOfAnyType arrayOfAnyType = ArrayOfAnyType.Factory.newInstance();
                    arrayOfAnyType.addNewValue();
                    arrayOfAnyType.setValueArray(0,
                            XmlString.Factory.newValue(tempElement.split(equalOperator)[1].trim()));
                    conditionExpression.setValues(arrayOfAnyType);
                }
            } else /* Check for 'LIKE' operator */
            if (tempElement.contains(likeOperator)) {

                /* Validate the element */
                if (tempElement.split(likeOperator).length < 2) {
                    throw new ScribeException(
                            ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'");
                }

                /* Create condition expression */
                final ConditionExpression conditionExpression = arrayOfConditionExpression.addNewCondition();

                /* Set attribute name */
                conditionExpression.setAttributeName(tempElement.split(likeOperator)[0].trim());

                /* Check for 'NULL' values */
                if (tempElement.split(likeOperator)[1].trim().toUpperCase().equalsIgnoreCase(nullConstant)) {

                    /* Set Nill value */
                    conditionExpression.setOperator(ConditionOperator.NULL);
                } else {

                    /* Set operator as 'EQUAL' */
                    conditionExpression.setOperator(ConditionOperator.LIKE);

                    /* Set value */
                    final ArrayOfAnyType arrayOfAnyType = ArrayOfAnyType.Factory.newInstance();
                    arrayOfAnyType.addNewValue();
                    arrayOfAnyType.setValueArray(0,
                            XmlString.Factory.newValue(tempElement.split(likeOperator)[1].trim()));
                    conditionExpression.setValues(arrayOfAnyType);
                }
            } else {
                throw new ScribeException(
                        ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'");
            }
        }
    }

    /* If a valid order */
    if (order != null && !"".equals(order)) {

        /* Create order expression */
        final ArrayOfOrderExpression arrayOfOrderExpression = queryExpression.addNewOrders();

        /* Tokenize the order clause */
        final StringTokenizer stringTokenizer = new StringTokenizer(order, crmFieldsSeparator);

        /* Iterate over tokenizer */
        while (stringTokenizer.hasMoreElements()) {

            /* Create new order expression */
            final OrderExpression orderExpression = arrayOfOrderExpression.addNewOrder();

            /* Validate order clause */
            final String[] updatedOrderArray = parseAndValidateOrderClauseForMSCRM(stringTokenizer.nextToken(),
                    orderFieldsSeparator);

            /* Set attribute name */
            orderExpression.setAttributeName(updatedOrderArray[0]);

            /* Set order type */
            if ("ASC".equalsIgnoreCase(updatedOrderArray[1])) {

                orderExpression.setOrderType(OrderType.ASCENDING);
            } else if ("DESC".equalsIgnoreCase(updatedOrderArray[1])) {

                orderExpression.setOrderType(OrderType.DESCENDING);
            }
        }
    }
    return queryExpression;
}

From source file:com.ebay.jetstream.messaging.transport.zookeeper.ZooKeeperTransport.java

private List<String> pathForNettyContexts(String path) {
    List<String> nettyContextpaths = new ArrayList<String>();
    for (String nettyContextpath : m_nettyContexts) {
        StringTokenizer tokens = new StringTokenizer(nettyContextpath, "/");
        StringBuffer tokenpath = new StringBuffer();
        while (tokens.hasMoreElements()) {
            if (tokenpath.length() != 0)
                tokenpath.append('/');

            tokenpath.append(tokens.nextToken());
            nettyContextpaths.add(path + "/" + tokenpath);
        }//from  w  ww. ja  v  a2 s.com

    }
    return nettyContextpaths;
}

From source file:net.rim.ejde.internal.util.ImportUtils.java

/**
 * Returns a <code>List</code> of [UserData] sources
 *
 * @param proj//from  w w  w.j  a  v a2  s  .  c om
 * @return
 */
static public List<String> getSources(Project proj) {
    List<String> sources = new ArrayList<String>();
    String udata = proj.getUserData();

    StringTokenizer st = new StringTokenizer(udata, "|");
    String token;

    while (st.hasMoreElements()) {
        token = st.nextToken();
        if (StringUtils.isNotBlank(token)) {
            sources.add(token);
        }
    }

    return sources;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Extracts the colors from the parameter String.<p>
 * /*from  w w  w. ja  va  2  s .co  m*/
 * @param colors list of color names and values
 * @return HashMap with color names and values
 */
private HashMap extractColors(String colors) {

    HashMap colorStorage = new HashMap();

    if (colors != null) {
        StringTokenizer tok = new StringTokenizer(colors, ",");
        // loop through the tokens
        // all tokens have the format "extension=type"    
        while (tok.hasMoreElements()) {
            String token = tok.nextToken();
            // now extract the file extension and the type
            String colorName = token.substring(0, token.indexOf("="));
            String colorValue = token.substring(token.indexOf("=") + 1);
            colorStorage.put(colorName, colorValue);
        }
    }
    return colorStorage;
}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasico.CatBasicoControllerImpl.java

public boolean sonValidosExportar(ActionMapping mapping, SonValidosExportarForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    Collection mensajes = new ArrayList();

    ValidaVO datos = form.getValida();/*  ww  w .ja  v  a 2s .  c om*/

    if (datos != null) {
        // leemos los errores de validacion
        String mens = datos.getResultadoValidacion().toString();
        StringTokenizer token = new StringTokenizer(mens, ";");
        while (token.hasMoreElements()) {
            mensajes.add(token.nextElement().toString());
            // token.nextElement();

        }
        form.setMensajesError(mensajes);

    } else {
        datos.setEsValidoManifest(new Boolean(false));//Devuelve false para la validacin
    }
    return datos.getEsValidoManifest().booleanValue();//Devuelve el resultado de la validacin, true o false

}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasico.CatBasicoControllerImpl.java

public boolean sonValidosMDBO(ActionMapping mapping, SonValidosMDBOForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // despues de validar metadatos viene aqui donde comprobaremos si el
    // resultado es true o false
    Collection mensajes = new ArrayList();

    ValidaVO datos = form.getValida();//from  www  .  j a  va2 s. c o m

    if (datos != null) {
        // leemos los resultados de la validacion
        String mens = datos.getResultadoValidacion().toString();
        StringTokenizer token = new StringTokenizer(mens, ";");
        while (token.hasMoreElements()) {
            mensajes.add(token.nextElement().toString());
            // token.nextElement();

        }
        form.setMensajesError(mensajes);

    } else {
        datos.setEsValidoManifest(new Boolean(false));//Devuelve false para la validacin
    }
    return datos.getEsValidoManifest().booleanValue();//Devuelve el resultado de la validacin, true o false

}