Example usage for java.util StringTokenizer countTokens

List of usage examples for java.util StringTokenizer countTokens

Introduction

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

Prototype

public int countTokens() 

Source Link

Document

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Usage

From source file:fr.openwide.talendalfresco.rest.server.ContentImportCommandServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  www . j a  va  2 s  .  c om*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled())
        logger.debug(
                "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));

    AuthenticationStatus status = servletAuthenticate(req, res);
    if (status == AuthenticationStatus.Failure) {
        return;
    }

    setNoCacheHeaders(res);

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    if (tokenCount < 3) {
        throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
    }

    t.nextToken(); // skip servlet name

    // get the command processor to execute the command e.g. "workflow"
    String procName = t.nextToken();

    // get the command to perform
    String command = t.nextToken();

    // get any remaining uri elements to pass to the processor
    String[] urlElements = new String[tokenCount - 3];
    for (int i = 0; i < tokenCount - 3; i++) {
        urlElements[i] = t.nextToken();
    }

    // retrieve the URL arguments to pass to the processor
    Map<String, String> args = new HashMap<String, String>(8, 1.0f);
    Enumeration names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        args.put(name, req.getParameter(name));
    }

    try {
        // get configured command processor by name from Config Service
        CommandProcessor processor = createCommandProcessor(procName);

        // validate that the processor has everything it needs to run the command
        if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
            redirectToLoginPage(req, res, getServletContext());
            return;
        }

        ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
        UserTransaction txn = null;
        try {
            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                txn = serviceRegistry.getTransactionService().getUserTransaction();
                txn.begin();
            }

            // inform the processor to execute the specified command
            if (processor instanceof ExtCommandProcessor) {
                ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
            } else {
                processor.process(serviceRegistry, req, command);
            }

            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                // commit the transaction
                txn.commit();
            }
        } catch (Throwable txnErr) {
            if (!(processor instanceof RestCommandProcessor)
                    || ((RestCommandProcessor) processor).isTransactional()) {
                // [talendalfresco] disable tx for ImportCommand
                try {
                    if (txn != null) {
                        txn.rollback();
                    }
                } catch (Exception tex) {
                }
            }
            throw txnErr;
        }

        String returnPage = req.getParameter(ARG_RETURNPAGE);
        if (returnPage != null && returnPage.length() != 0) {
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to specified return page: " + returnPage);

            res.sendRedirect(returnPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("No return page specified, displaying status output.");

            if (res.getContentType() == null) {
                res.setContentType("text/html");
            }

            // request that the processor output a useful status message
            PrintWriter out = res.getWriter();
            processor.outputStatus(out);
            out.close();
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
    }
}

From source file:org.alfresco.web.app.servlet.CommandServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*ww w  .  j ava 2 s  .c o  m*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled())
        logger.debug(
                "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));

    AuthenticationStatus status = servletAuthenticate(req, res);
    if (status == AuthenticationStatus.Failure) {
        return;
    }

    setNoCacheHeaders(res);

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    if (tokenCount < 3) {
        throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
    }

    t.nextToken(); // skip servlet name

    // get the command processor to execute the command e.g. "workflow"
    String procName = t.nextToken();

    // get the command to perform
    String command = t.nextToken();

    // get any remaining uri elements to pass to the processor
    String[] urlElements = new String[tokenCount - 3];
    for (int i = 0; i < tokenCount - 3; i++) {
        urlElements[i] = t.nextToken();
    }

    // retrieve the URL arguments to pass to the processor
    Map<String, String> args = new HashMap<String, String>(8, 1.0f);
    Enumeration names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        args.put(name, req.getParameter(name));
    }

    try {
        // get configured command processor by name from Config Service
        CommandProcessor processor = createCommandProcessor(procName);

        // validate that the processor has everything it needs to run the command
        if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
            redirectToLoginPage(req, res, getServletContext());
            return;
        }

        ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
        UserTransaction txn = null;
        try {
            txn = serviceRegistry.getTransactionService().getUserTransaction();
            txn.begin();

            // inform the processor to execute the specified command
            if (processor instanceof ExtCommandProcessor) {
                ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
            } else {
                processor.process(serviceRegistry, req, command);
            }

            // commit the transaction
            txn.commit();
        } catch (Throwable txnErr) {
            try {
                if (txn != null) {
                    txn.rollback();
                }
            } catch (Exception tex) {
            }
            throw txnErr;
        }

        String returnPage = req.getParameter(ARG_RETURNPAGE);
        if (returnPage != null && returnPage.length() != 0) {
            validateReturnPage(returnPage, req);
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to specified return page: " + returnPage);

            res.sendRedirect(returnPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("No return page specified, displaying status output.");

            if (res.getContentType() == null && !res.isCommitted()) {
                res.setContentType("text/html");

                // request that the processor output a useful status message
                PrintWriter out = res.getWriter();
                processor.outputStatus(out);
                out.close();
            }
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
    }
}

From source file:com.comtop.cap.bm.metadata.common.dwr.CapMapConverter.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object convertInbound(Class<?> paramType, InboundVariable data) throws ConversionException {
    if (data.isNull()) {
        return null;
    }/*ww  w .j  a  v  a 2 s. co  m*/

    String value = data.getValue();

    // If the text is null then the whole bean is null
    if (value.trim().equals(ProtocolConstants.INBOUND_NULL)) {
        return null;
    }

    if (!value.startsWith(ProtocolConstants.INBOUND_MAP_START)
            || !value.endsWith(ProtocolConstants.INBOUND_MAP_END)) {
        log.warn("Expected object while converting data for " + paramType.getName() + " in "
                + data.getContext().getCurrentProperty() + ". Passed: " + value);
        throw new ConversionException(paramType, "Data conversion error. See logs for more details.");
    }

    value = value.substring(1, value.length() - 1);

    try {
        // Maybe we ought to check that the paramType isn't expecting a more
        // distinct type of Map and attempt to create that?
        Map<Object, Object> map;

        // If paramType is concrete then just use whatever we've got.
        if (!paramType.isInterface() && !Modifier.isAbstract(paramType.getModifiers())) {
            // If there is a problem creating the type then we have no way
            // of completing this - they asked for a specific type and we
            // can't create that type. I don't know of a way of finding
            // subclasses that might be instaniable so we accept failure.
            map = (Map<Object, Object>) paramType.newInstance();
        } else {
            map = new HashMap<Object, Object>();
        }

        // Get the extra type info
        Property parent = data.getContext().getCurrentProperty();

        Property keyProp = parent.createChild(0);
        keyProp = converterManager.checkOverride(keyProp);

        Property valProp = parent.createChild(1);
        valProp = converterManager.checkOverride(valProp);

        // We should put the new object into the working map in case it
        // is referenced later nested down in the conversion process.
        data.getContext().addConverted(data, paramType, map);
        InboundContext incx = data.getContext();

        // Loop through the property declarations
        StringTokenizer st = new StringTokenizer(value, ",");
        int size = st.countTokens();
        for (int i = 0; i < size; i++) {
            String token = st.nextToken();
            if (token.trim().length() == 0) {
                continue;
            }

            int colonpos = token.indexOf(ProtocolConstants.INBOUND_MAP_ENTRY);
            if (colonpos == -1) {
                throw new ConversionException(paramType, "Missing " + ProtocolConstants.INBOUND_MAP_ENTRY
                        + " in object description: {1}" + token);
            }

            String valStr = token.substring(colonpos + 1).trim();
            String[] splitIv = ConvertUtil.splitInbound(valStr);
            String splitIvValue = splitIv[ConvertUtil.INBOUND_INDEX_VALUE];
            String splitIvType = splitIv[ConvertUtil.INBOUND_INDEX_TYPE];
            InboundVariable valIv = new InboundVariable(incx, null, splitIvType, splitIvValue);
            valIv.dereference();

            Class valTyClass = String.class;

            if ("boolean".equals(valIv.getType())) {
                valTyClass = Boolean.class;
            } else if ("array".equals(valIv.getType())) {
                valTyClass = ArrayList.class;
            } else if ("number".equals(valIv.getType())) {
                String strValue = valIv.getValue();
                if (strValue.indexOf(".") != -1) {
                    valTyClass = Double.class;
                } else {
                    valTyClass = Integer.class;
                }
            } else if ("date".equals(valIv.getType())) {
                valTyClass = Date.class;
            }

            Object val = converterManager.convertInbound(valTyClass, valIv, valProp);
            String keyStr = token.substring(0, colonpos).trim();
            map.put(keyStr, val);
        }

        return map;
    } catch (ConversionException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ConversionException(paramType, ex);
    }
}

From source file:lineage2.gameserver.Announcements.java

/**
 * Method loadAnnouncements./*from  www.  ja  v a 2 s.  c o  m*/
 */
public void loadAnnouncements() {
    _announcements.clear();
    try {
        List<String> lines = Arrays
                .asList(FileUtils.readFileToString(new File("config/announcements.txt"), "UTF-8").split("\n"));
        for (String line : lines) {
            StringTokenizer token = new StringTokenizer(line, "\t");
            if (token.countTokens() > 1) {
                addAnnouncement(Integer.parseInt(token.nextToken()), token.nextToken(), false);
            } else {
                addAnnouncement(0, line, false);
            }
        }
    } catch (Exception e) {
        _log.error("Error while loading config/announcements.txt!");
    }
}

From source file:org.apache.cocoon.util.log.XMLCocoonLogFormatter.java

/**
 * Set the types from a whitespace separated string
 *//*from ww w  . j av  a  2  s.c o  m*/
public void setTypes(String typeString) {
    if (typeString == null) {
        this.types = new int[0];
    } else {
        // this is not the best implementation, but it works...
        StringTokenizer st = new StringTokenizer(typeString);
        this.types = new int[st.countTokens()];
        for (int i = 0; i < this.types.length; i++) {
            this.types[i] = this.getTypeIdFor(st.nextToken());
        }
    }
}

From source file:ca.phon.app.session.editor.TranscriberSelectionDialog.java

public String getUsername() {
    if (newTranscriptButton.isSelected()) {
        return usernameField.getText();
    } else {/*from   w w w  .  j a va  2s . c o m*/
        String userListName = existingUserList.getSelectedValue().toString();
        StringTokenizer st = new StringTokenizer(userListName, "-");

        if (st.countTokens() == 2) {
            st.nextToken();

            return StringUtils.strip(st.nextToken());
        } else {
            return new String();
        }
    }
}

From source file:org.jmxtrans.embedded.config.EtcdKVStore.java

private URL[] makeEtcdBaseUris(String etcdURI) throws EmbeddedJmxTransException {
    String serverList = null;/*from  w  ww.  j a  v a2  s  .  c o  m*/
    try {
        if (etcdURI.indexOf("[") > 0) {
            serverList = etcdURI.substring(etcdURI.indexOf("[") + 1, etcdURI.indexOf("]"));
        } else {
            serverList = etcdURI.substring(7, etcdURI.indexOf("/", 7));
        }

        StringTokenizer st = new StringTokenizer(serverList, ",");
        URL[] result = new URL[st.countTokens()];
        int k = 0;
        while (st.hasMoreTokens()) {
            result[k] = new URL("http://" + st.nextToken().trim());
            k++;
        }

        return result;

    } catch (Exception e) {
        throw new EmbeddedJmxTransException(
                "Exception buildind etcd server list from: '" + etcdURI + "': " + e.getMessage(), e);
    }

}

From source file:com.clustercontrol.sql.util.JdbcDriverProperties.java

/**
 * properties(param1=xxx&param2=yyy&param3=zzz...)????Properties??
 * @param props properties???/*  w w  w  . ja  va2s .  co m*/
 * @return
 */
private Properties parseProperties(String props) {
    Properties ret = new Properties();

    StringTokenizer separeteToken = new StringTokenizer(props, _propertiesSepareteToken);
    StringTokenizer defineToken = null;

    while (separeteToken.hasMoreTokens()) {
        String property = separeteToken.nextToken();
        log.debug(this.classname + " : parsing property. (" + property + ")");
        defineToken = new StringTokenizer(property, _propertiesDefineToken);
        if (defineToken.countTokens() == 2) {
            String key = defineToken.nextToken();
            String value = defineToken.nextToken();
            ret.setProperty(key, value);
            log.debug(this.classname + " : setting property. (key = " + key + ", value = " + value + ")");
        } else {
            log.info(this.classname + " : skipped, because of invalid jdbc parameter. (" + property + ")");
        }
    }

    return ret;
}

From source file:edu.ucla.stat.SOCR.chart.demo.BoxAndWhiskerChartDemo2.java

public void setDataTable(String input) {
    hasExample = true;/*  w w w. j  a v  a 2 s. co  m*/
    StringTokenizer lnTkns = new StringTokenizer(input, "#");
    String line;
    int lineCt = lnTkns.countTokens();

    int r = 0;
    while (lnTkns.hasMoreTokens()) {
        line = lnTkns.nextToken();

        //   String tb[] =line.split("\t");
        StringTokenizer cellTkns = new StringTokenizer(line, ",");// IE use "space" Mac use tab as cell separator
        int cellCnt = cellTkns.countTokens();
        String tb[] = new String[cellCnt];
        int r1 = 0;
        while (cellTkns.hasMoreTokens()) {
            tb[r1] = cellTkns.nextToken();
            r1++;
        }
        //System.out.println("tb.length="+tb.length);
        int colCt = tb.length;
        //vertical
        resetTableRows(colCt);
        resetTableColumns(lineCt);

        for (int i = 0; i < tb.length; i++) {
            //System.out.println(tb[i]);
            if (tb[i].length() == 0)
                tb[i] = "0";
            dataTable.setValueAt(tb[i], i, r); //vertical
        }
        r++;
    }

    // this will update the mapping panel     
    resetTableColumns(dataTable.getColumnCount());
}

From source file:OverwriteProperties.java

/**
 *  Reads in the properties from the specified file
 *
 * @param  propFile                   Description of the Parameter
 * @param  index                      Description of the Parameter
 * @exception  FileNotFoundException  Description of the Exception
 * @exception  IOException            Description of the Exception
 *//* w  ww.  j av  a  2s . c o m*/
public void readProperties(File propFile, int index) throws FileNotFoundException, IOException {
    BufferedReader reader = new BufferedReader(new FileReader(propFile));
    String key = null;
    String line = null;

    while ((line = reader.readLine()) != null) {
        StringTokenizer tokenizer = new StringTokenizer(line, "=");

        int count = tokenizer.countTokens();
        if (count == 2 && line.startsWith("include")) {
            key = tokenizer.nextToken().trim();
            File includeFile = new File(includeRoot + tokenizer.nextToken().trim());
            if (verbose) {
                System.out.println("include File = " + includeFile);
            }
            readProperties(includeFile, index);
            continue;
        }
        if (count >= 1 && line.startsWith("module.packages")) {
            baseArray.add(index, line);
            if (verbose) {
                System.out.println("Adding module.package to baseArray[" + index + "] = " + line);
            }
            index++;

            key = line.trim();
            if (baseMap.containsKey(key)) {
                int ix = ((Integer) baseMap.get(key)).intValue();
                baseArray.set(ix, line);
                if (verbose) {
                    System.out.println("Resetting baseArray[" + ix + "] = " + line);
                }
            }

            continue;
        }
        if (count >= 1 && line.startsWith("-")) {
            // remove from base

            String prefix = line.trim().substring(1);
            removeArray.add(prefix);
            if (verbose) {
                System.out.println("Flagging for removal = " + line);
            }
            continue;
        }
        if (count >= 1 && !line.startsWith("#")) {
            key = tokenizer.nextToken().trim();
            if (key != null && key.length() > 0) {
                if (baseMap.containsKey(key)) {
                    int ix = ((Integer) baseMap.get(key)).intValue();
                    baseArray.set(ix, line);
                    if (verbose) {
                        System.out.println("Resetting baseArray[" + ix + "] = " + line);
                    }
                } else {
                    baseArray.add(index, line);
                    if (verbose) {
                        System.out.println("Adding new entry to baseArray[" + index + "] = " + line);
                    }
                    baseMap.put(key, new Integer(index));
                    if (verbose) {
                        System.out.println("baseMap[" + key + "," + index + "]");
                    }
                    index++;
                }
            }
        }

    }
    reader.close();

}