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:com.cloud.utils.net.NetUtils.java

private static InetAddress parseIpAddress(final String address) {
    final StringTokenizer st = new StringTokenizer(address, ".");
    final byte[] bytes = new byte[4];

    if (st.countTokens() == 4) {
        try {/*w w  w.  jav a2  s .  co m*/
            for (int i = 0; i < 4; i++) {
                bytes[i] = (byte) Integer.parseInt(st.nextToken());
            }
            return InetAddress.getByAddress(address, bytes);
        } catch (final NumberFormatException nfe) {
            return null;
        } catch (final UnknownHostException uhe) {
            return null;
        }
    }
    return null;
}

From source file:com.ikon.servlet.admin.RepositoryViewServlet.java

/**
 * Save property//from   w w w.  ja v a2 s  .  c  o m
 */
private void save(Session session, String path, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, javax.jcr.PathNotFoundException, RepositoryException {
    log.debug("save({}, {}, {}, {})", new Object[] { session, path, request, response });
    String value = WebUtils.getString(request, "value");
    String property = WebUtils.getString(request, "property");
    Node node = session.getRootNode().getNode(path.substring(1));
    Property prop = node.getProperty(property);
    ValueFactory vf = session.getValueFactory();

    if (prop.getDefinition().isMultiple()) {
        StringTokenizer st = new StringTokenizer(value, "\n");
        Value[] values = new Value[st.countTokens()];

        for (int i = 0; st.hasMoreTokens(); i++) {
            values[i] = vf.createValue(st.nextToken().trim());
        }

        node.setProperty(property, values);
    } else {
        node.setProperty(property, value);
    }

    node.save();

    // Activity log
    UserActivity.log(session.getUserID(), "ADMIN_REPOSITORY_SAVE", node.getUUID(), path,
            property + ", " + value);
    log.debug("save: void");
}

From source file:com.liferay.portal.struts.PortalTilesDefinitionsFactory.java

/**
 * Initialization method./* w w  w. j a  va2  s  .co  m*/
 * Init the factory by reading appropriate configuration file.
 * This method is called exactly once immediately after factory creation in
 * case of internal creation (by DefinitionUtil).
 * @param servletContext Servlet Context passed to newly created factory.
 * @param proposedFilename File names, comma separated, to use as  base file names.
 * @throws DefinitionsFactoryException An error occur during initialization.
 */
protected void initFactory(ServletContext servletContext, String proposedFilename)
        throws DefinitionsFactoryException, FileNotFoundException {

    // Init list of filenames
    StringTokenizer tokenizer = new StringTokenizer(proposedFilename, ",");
    this.filenames = new ArrayList(tokenizer.countTokens());
    while (tokenizer.hasMoreTokens()) {
        this.filenames.add(tokenizer.nextToken().trim());
    }

    loaded = new HashMap();
    defaultFactory = createDefaultFactory(servletContext);
    if (log.isDebugEnabled())
        log.debug("default factory:" + defaultFactory);
}

From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java

protected void validate(HttpServlet servlet, Integer expectedMaxAgeInSeconds, int expectedResponseStatusCode)
        throws Exception {
    // SETUP//from w  w w .  ja  va  2  s  .  co  m
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter("ExpiresDefault", "access plus 1 minute");
    filterConfig.addInitParameter("ExpiresByType text/xml; charset=utf-8", "access plus 3 minutes");
    filterConfig.addInitParameter("ExpiresByType text/xml", "access plus 5 minutes");
    filterConfig.addInitParameter("ExpiresByType text", "access plus 7 minutes");
    filterConfig.addInitParameter("ExpiresExcludedResponseStatusCodes", "304, 503");

    ExpiresFilter expiresFilter = new ExpiresFilter();
    expiresFilter.init(filterConfig);

    context.addFilter(new FilterHolder(expiresFilter), "/*", Handler.REQUEST);

    context.addServlet(new ServletHolder(servlet), "/test");

    server.start();
    try {
        Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        long timeBeforeInMillis = System.currentTimeMillis();

        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();

        // VALIDATE
        Assert.assertEquals(expectedResponseStatusCode, httpURLConnection.getResponseCode());

        for (Entry<String, List<String>> field : httpURLConnection.getHeaderFields().entrySet()) {
            System.out.println(field.getKey() + ": "
                    + StringUtils.arrayToDelimitedString(field.getValue().toArray(), ", "));
        }

        Integer actualMaxAgeInSeconds;

        String cacheControlHeader = httpURLConnection.getHeaderField("Cache-Control");
        if (cacheControlHeader == null) {
            actualMaxAgeInSeconds = null;
        } else {
            actualMaxAgeInSeconds = null;
            // System.out.println("Evaluate Cache-Control:" +
            // cacheControlHeader);
            StringTokenizer cacheControlTokenizer = new StringTokenizer(cacheControlHeader, ",");
            while (cacheControlTokenizer.hasMoreTokens() && actualMaxAgeInSeconds == null) {
                String cacheDirective = cacheControlTokenizer.nextToken();
                // System.out.println("\tEvaluate directive: " +
                // cacheDirective);
                StringTokenizer cacheDirectiveTokenizer = new StringTokenizer(cacheDirective, "=");
                // System.out.println("countTokens=" +
                // cacheDirectiveTokenizer.countTokens());
                if (cacheDirectiveTokenizer.countTokens() == 2) {
                    String key = cacheDirectiveTokenizer.nextToken().trim();
                    String value = cacheDirectiveTokenizer.nextToken().trim();
                    if (key.equalsIgnoreCase("max-age")) {
                        actualMaxAgeInSeconds = Integer.parseInt(value);
                    }
                }
            }
        }

        if (expectedMaxAgeInSeconds == null) {
            Assert.assertNull("actualMaxAgeInSeconds '" + actualMaxAgeInSeconds + "' should be null",
                    actualMaxAgeInSeconds);
            return;
        }

        Assert.assertNotNull(actualMaxAgeInSeconds);

        int deltaInSeconds = Math.abs(actualMaxAgeInSeconds - expectedMaxAgeInSeconds);
        Assert.assertTrue("actualMaxAgeInSeconds: " + actualMaxAgeInSeconds + ", expectedMaxAgeInSeconds: "
                + expectedMaxAgeInSeconds + ", request time: " + timeBeforeInMillis + " for content type "
                + httpURLConnection.getContentType(), deltaInSeconds < 2000);

    } finally {
        server.stop();
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchFormFrame.java

private void copySelectionToInternalClipboardAsBBCodes() {
    try {//from w  w w  . j  a v a 2s . c o  m
        List<AbstractForm> forms = getSelectedForms();
        if (forms.isEmpty()) {
            showInfo("Keine Zeichnungen ausgewhlt");
            return;
        }
        int ignoredForms = 0;
        for (AbstractForm form : forms) {
            if (!form.allowsBBExport()) {
                ignoredForms++;
            }
        }

        boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
                "Nein", "Ja") == JOptionPane.YES_OPTION);

        StringBuilder buffer = new StringBuilder();
        if (extended) {
            buffer.append("[u][size=12]Zeichnungen[/size][/u]\n\n");
        } else {
            buffer.append("[u]Zeichnungen[/u]\n\n");
        }

        buffer.append(new FormListFormatter().formatElements(forms, extended));

        if (extended) {
            buffer.append("\n[size=8]Erstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "[/size]\n");
        } else {
            buffer.append("\nErstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "\n");
        }

        String b = buffer.toString();
        StringTokenizer t = new StringTokenizer(b, "[");
        int cnt = t.countTokens();
        if (cnt > 1000) {
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Die ausgewhlten Zeichnungen bentigen mehr als 1000 BB-Codes\n"
                            + "und knnen daher im Spiel (Forum/IGM/Notizen) nicht auf einmal dargestellt werden.\nTrotzdem exportieren?",
                    "Zu viele BB-Codes", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                return;
            }
        }

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b), null);
        String result = null;
        if (ignoredForms != forms.size()) {
            result = "<html>Daten in Zwischenablage kopiert.";
            if (ignoredForms > 0) {
                result += ((ignoredForms == 1) ? " Eine Zeichnung wurde"
                        : " " + ignoredForms + " Zeichnungen wurden")
                        + " ignoriert, da der BB-Export nur fr Rechtecke, Kreise und Freihandzeichnungen verf&uuml;gbar ist.";
            }
            result += "</html>";
        } else {
            showError(
                    "<html>Keine Zeichnungen exportiert, da der BB-Export nur fr Rechtecke, Kreise und Freihandzeichnungen verf&uuml;gbar ist.</html>");
            return;
        }
        showSuccess(result);
    } catch (Exception e) {
        logger.error("Failed to copy data to clipboard", e);
        String result = "Fehler beim Kopieren in die Zwischenablage.";
        showError(result);
    }
}

From source file:de.suse.swamp.core.workflow.WorkflowTemplate.java

/** Get the DatabitTemplate in the given path
 * Notation: datasetname.[datasetname.[databitname]]
 *
 * @param path//from   w w  w. java  2 s .  c  o m
 * @return requested Databit if found, null if not.
 */
public DatabitTemplate getDatabitTemplate(String path) {
    DatabitTemplate dbit = null;
    if (path.startsWith("System.")) {
        path = path.substring(7);
        dbit = DataToWfPropertyMapper.getValueForWorkflow(this, path);
    } else {
        StringTokenizer st = new StringTokenizer(path, ".");
        if (st.countTokens() < 1) {
            Logger.BUG("Empty pathname for getting Databittemplate");
        } else if (st.countTokens() > 1) {
            // assuming that the first item is the datasetname
            String datasetName = st.nextToken();
            DatasetTemplate dataset = (DatasetTemplate) datasetTemplates.get(datasetName);
            if (dataset == null && WorkflowManager.isInstantiated()) {
                WorkflowManager wfman = WorkflowManager.getInstance();
                if (wfman.templateExists(parentWfName, parentWfVersion)) {
                    WorkflowTemplate parent = WorkflowManager.getInstance().getWorkflowTemplate(parentWfName,
                            parentWfVersion);
                    dbit = parent.getDatabitTemplate(path);
                }
            } else if (dataset != null) {
                String newField = path.substring(datasetName.length() + 1);
                dbit = dataset.getDatabitTemplate(newField);
            }
        }
    }
    return dbit;
}

From source file:org.acmsl.commons.utils.http.HttpServletUtils.java

/**
 * Removes the trailing servlet info from given servlet path.
 * @param servletPath the servlet path./*  ww w .ja  v a  2 s  .c  o  m*/
 * @return the actual relative path of the servlet, without the
 * information about the servlet itself.
 */
@NotNull
protected String removeServletInfo(@NotNull final String servletPath) {
    @NotNull
    final StringBuilder result = new StringBuilder();

    @NotNull
    final StringTokenizer tokenizer = new StringTokenizer(servletPath, "/");

    final int totalTokens = tokenizer.countTokens();

    int tokenIndex = 1;

    while (tokenizer.hasMoreTokens()) {
        if (tokenIndex < totalTokens) {
            result.append("/");
            result.append(tokenizer.nextToken());
            tokenIndex++;
        } else {
            break;
        }
    }

    return result.toString();
}

From source file:com.sun.faban.harness.webclient.ResultAction.java

@SuppressWarnings("empty-statement")
private void prepareUpload(HttpServletRequest request, RunResult result, HashSet<String> uploadedRuns,
        HashSet<File> uploadSet) throws IOException, ClassNotFoundException {
    String runId = result.runId.toString();
    StringBuilder formattedTags = new StringBuilder();
    File runTagFile = new File(Config.OUT_DIR + runId + "/META-INF/tags");
    String tags = request.getParameter(runId + "_tags").trim();
    TagEngine te = TagEngine.getInstance();
    if (tags != null && !"".equals(tags)) {
        StringTokenizer t = new StringTokenizer(tags, " \n,");
        ArrayList<String> tagList = new ArrayList<String>(t.countTokens());
        while (t.hasMoreTokens()) {
            String nextT = t.nextToken().trim();
            if (nextT != null && !"".equals(nextT)) {
                formattedTags.append(nextT + "\n");
                tagList.add(nextT);/*w w w .  ja va  2s. c om*/
            }
        }
        FileHelper.writeContentToFile(formattedTags.toString(), runTagFile);
        result.tags = tagList.toArray(new String[tagList.size()]);

        boolean tagsChanged = true;
        if (result.tags == null && result.tags.length == 0) {
            if (tags == null || "".equals(tags)) {
                tagsChanged = false;
            }
        }

        if (tagsChanged) {
            te.add(runId, result.tags);
            te.save();
        }
    } else {
        runTagFile.delete();
        result.tags = new String[1];
        result.tags[0] = "&nbsp;";
        te.add(runId, new String[0]);
        te.save();
    }
    result.description = request.getParameter(runId + "_description");
    editXML(result);
    uploadedRuns.add(runId);
    uploadSet.add(jarUpRun(runId));
}

From source file:net.swas.explorer.httpprofile.DOProfile.java

/**
 * This function is responsible for inserting parent and leaf nodes
 * @param urls//  w  w w  . j  av a  2s.  c o m
 * @throws SQLException
 */
public void insertPairs(ArrayList<String> urls) throws SQLException {
    int max = 0;
    for (String string : urls) {
        if (max == 0) {
            max = getMaxIdPairs(max);
        } else {
            max = max + 1;
        }
        System.out.println("url size : " + urls.size());
        System.out.println("url : " + string);
        StringTokenizer urlTokenizer = new StringTokenizer(string, "/");
        System.out.println("total tokens are= " + urlTokenizer.countTokens());
        urlTokenizer.nextToken();
        int value = 0;
        int x = 0;
        String parent = "";
        while (urlTokenizer.hasMoreTokens()) {
            ResultSet rs = null;
            String name = urlTokenizer.nextToken();
            System.out.println("Name :" + name);
            if (x == 0) {
                String sql_qry = "select name from pairs where name= ?";
                PreparedStatement stmt = (PreparedStatement) cdb.prepareQuery(sql_qry);
                stmt.setString(1, name);
                rs = cdb.executeQuery(stmt);
                rs.next();
            } else {
                String sql_qry = "select name, parentid from pairs where name=?";
                PreparedStatement stmt = (PreparedStatement) cdb.prepareQuery(sql_qry);
                stmt.setString(1, name);
                rs = cdb.executeQuery(stmt);
                rs.next();

                String sqlQry = "select  id from pairs where name=?";
                PreparedStatement pstmt = (PreparedStatement) cdb.prepareQuery(sqlQry);
                pstmt.setString(1, parent);
                ResultSet rss = cdb.executeQuery(pstmt);
                rss.next();
                value = rss.getInt(1);
            }

            String sql_qry = "select name, parentid from pairs where name=?";
            PreparedStatement stmt = (PreparedStatement) cdb.prepareQuery(sql_qry);
            stmt.setString(1, name);
            rs = cdb.executeQuery(stmt);
            rs.next();
            if (!rs.first()) {
                if (x == 0)
                    value = 0;
                else
                    max = max + 1;

                String sqlInsertPairQry = "INSERT INTO pairs (id, name, parentid) VALUES (?,?,?)";
                PreparedStatement pstmt = (PreparedStatement) cdb.prepareQuery(sqlInsertPairQry);
                pstmt.setLong(1, max);
                pstmt.setString(2, name);
                pstmt.setLong(3, value);
                cdb.updateQuery(pstmt);
                System.out.println("inserted is " + name);

            } else {

            }
            parent = name;
            // value=max;
            x++;
        }
    }

}

From source file:org.alfresco.po.share.GroupsPage.java

/**
 * Get list of group members for any group in groups page
 * //  w  w  w  . jav  a  2  s .co  m
 * @return List of Users
 */
public List<UserProfile> getMembersList() {
    try {
        List<UserProfile> listOfUsers = new ArrayList<UserProfile>();
        List<WebElement> groupMembers = findAndWaitForElements(By.cssSelector(USER_NAMES));
        for (WebElement webElement : groupMembers) {
            UserProfile profile = new UserProfile();
            String text = webElement.getText();
            StringTokenizer userInfo = new StringTokenizer(text);

            int userDispalySize = 0;
            int userInfoSize = userInfo.countTokens();

            while (userInfo.hasMoreElements()) {

                if (userDispalySize == 0) {
                    profile.setfName((String) userInfo.nextElement());
                } else if (userDispalySize == 1 && userInfoSize > 2) {
                    profile.setlName((String) userInfo.nextElement());
                } else if (userDispalySize == 2 || (userDispalySize == 1 && userInfoSize == 2)) {
                    profile.setUsername((String) userInfo.nextElement());
                }
                userDispalySize++;
            }
            listOfUsers.add(profile);
        }
        return listOfUsers;

    } catch (TimeoutException e) {
        logger.error("Unable to get the list of members : ", e);
    }

    throw new PageOperationException("Unable to get the list of members  : ");
}