Example usage for org.apache.commons.lang StringUtils length

List of usage examples for org.apache.commons.lang StringUtils length

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils length.

Prototype

public static int length(String str) 

Source Link

Document

Gets a String's length or 0 if the String is null.

Usage

From source file:org.geoserver.security.iride.util.xml.transform.ErrorHandlerUtils.java

/**
 *
 * @param locator/*from  ww  w  .j  av  a 2  s .  co m*/
 * @return
 */
private static String getLocationMessageText(SourceLocator locator) {
    String locMessage = "";
    String systemId = locator.getSystemId();
    String nodeMessage = null;
    int lineNumber = locator.getLineNumber();

    if (locator instanceof DOMLocator) {
        nodeMessage = "at " + ((DOMLocator) locator).getOriginatingNode().getNodeName() + ' ';
    }
    boolean containsLineNumber = lineNumber != -1;
    if (nodeMessage != null) {
        locMessage += nodeMessage;
    }
    if (containsLineNumber) {
        locMessage += "on line " + lineNumber + ' ';
        if (locator.getColumnNumber() != -1) {
            locMessage += "column " + locator.getColumnNumber() + ' ';
        }
    }
    if (StringUtils.length(systemId) > 0) {
        locMessage += (containsLineNumber ? "of " : "in ") + abbreviatePath(systemId) + ':';
    }

    return locMessage;
}

From source file:org.glimpse.server.news.dom.DomServerNewsChannelBuilder.java

private List<ServerEntry> getAtomEntries(Document doc) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    List<ServerEntry> rssEntries = new LinkedList<ServerEntry>();
    NodeList entries = (NodeList) xpath.evaluate("/feed/entry", doc, XPathConstants.NODESET);
    for (int i = 0; i < entries.getLength(); i++) {
        ServerEntry rssEntry = new ServerEntry();
        Element elmEntry = (Element) entries.item(i);
        String id = (String) xpath.evaluate("id", elmEntry, XPathConstants.STRING);
        String title = (String) xpath.evaluate("title", elmEntry, XPathConstants.STRING);

        String entryUrl = null;/*  w  w  w  . j  a v a  2s. c om*/
        List<Enclosure> enclosures = new LinkedList<Enclosure>();
        NodeList linkList = (NodeList) xpath.evaluate("link", elmEntry, XPathConstants.NODESET);
        if (linkList != null) {
            for (int j = 0; j < linkList.getLength(); j++) {
                Element elmLink = (Element) linkList.item(j);
                String rel = elmLink.getAttribute("rel");
                if (StringUtils.isBlank(rel) || rel.equals("alternate")) {
                    entryUrl = elmLink.getAttribute("href");
                } else if (rel.equals("enclosure")) {
                    Enclosure enclosure = new Enclosure();
                    enclosure.setUrl(elmLink.getAttribute("href"));
                    enclosure.setType(elmLink.getAttribute("type"));
                    enclosures.add(enclosure);
                }
            }
        }
        String updated = (String) xpath.evaluate("updated", elmEntry, XPathConstants.STRING);

        String content = (String) xpath.evaluate("content", elmEntry, XPathConstants.STRING);
        if (StringUtils.isBlank(content)) {
            content = (String) xpath.evaluate("summary", elmEntry, XPathConstants.STRING);
            content += "<p><a href=\"" + entryUrl + "\" target=\"_blank\">Lire la suite</a></p>";
        }

        rssEntry.setId(id);
        rssEntry.setTitle(title);
        rssEntry.setUrl(entryUrl);
        rssEntry.setEnclosures(enclosures);
        rssEntry.setContent(content);

        if (StringUtils.length(updated) > 19) {
            try {
                Date date = null;
                if (updated.endsWith("Z")) {
                    // No timezone
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                    date = formatter.parse(updated.substring(0, 19));
                } else {
                    String timezone = updated.substring(updated.length() - 6);
                    timezone = timezone.substring(0, 3) + timezone.substring(4);
                    updated = updated.substring(0, 19) + timezone;
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                    date = formatter.parse(updated);
                }
                if (date != null) {
                    rssEntry.setDate(date);
                }
            } catch (Exception e) {
                // unparsable date
                logger.warn("Unable to parse date <" + updated + ">", e);
            }
        }

        if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(title) && StringUtils.isNotBlank(entryUrl)) {
            rssEntries.add(rssEntry);
        }
    }

    return rssEntries;
}

From source file:org.glimpse.server.news.sax.ChannelHandler.java

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    if (Type.ATOM.equals(type)) {
        String path = getCurrentPath();
        if (path.equals("/feed/title")) {
            title = buffer.toString();// w ww. ja  v  a2  s  . c o  m
        } else if (path.equals("/feed/entry")) {
            String content = currentContent;
            if (StringUtils.isBlank(content)) {
                content = currentSummary == null ? "" : currentSummary;
                content += "<p><a href=\"" + currentEntry.getUrl()
                        + "\" target=\"_blank\">Lire la suite</a></p>";
            }
            currentEntry.setContent(content);

            if (StringUtils.isNotBlank(currentEntry.getId()) && StringUtils.isNotBlank(currentEntry.getTitle())
                    && StringUtils.isNotBlank(currentEntry.getUrl())) {
                entries.add(currentEntry);
            }

            currentEntry = null;
            currentContent = null;
            currentSummary = null;
        } else if (path.equals("/feed/entry/id")) {
            currentEntry.setId(buffer.toString());
        } else if (path.equals("/feed/entry/title")) {
            currentEntry.setTitle(buffer.toString());
        } else if (path.equals("/feed/entry/updated")) {
            String updated = buffer.toString();
            if (StringUtils.length(updated) > 19) {
                try {
                    Date date = null;
                    if (updated.endsWith("Z")) {
                        // No timezone
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                        date = formatter.parse(updated.substring(0, 19));
                    } else {
                        String timezone = updated.substring(updated.length() - 6);
                        timezone = timezone.substring(0, 3) + timezone.substring(4);
                        updated = updated.substring(0, 19) + timezone;
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                        date = formatter.parse(updated);
                    }
                    if (date != null) {
                        currentEntry.setDate(date);
                    }
                } catch (Exception e) {
                    // unparsable date
                    logger.warn("Unable to parse date <" + updated + ">", e);
                }
            }
        } else if (path.equals("/feed/entry/content")) {
            currentContent = buffer.toString();
        } else if (path.equals("/feed/entry/summary")) {
            currentSummary = buffer.toString();
        }
    } else if (Type.RSS_2_0.equals(type)) {
        String path = getCurrentPath();
        if (path.equals("/rss/channel/title")) {
            title = buffer.toString();
        } else if (path.equals("/rss/channel/link")) {
            url = buffer.toString();
        } else if (path.equals("/rss/channel/item")) {
            String content = currentSummary == null ? "" : currentSummary;
            content += "<p><a href=\"" + currentEntry.getUrl() + "\" target=\"_blank\">Lire la suite</a></p>";
            currentEntry.setContent(content);

            if (StringUtils.isBlank(currentEntry.getId()) && currentEntry.getDate() != null) {
                currentEntry.setId(currentEntry.getDate().toString());
            }

            if (StringUtils.isBlank(currentEntry.getUrl())) {
                currentEntry.setUrl(url);
            }

            if (StringUtils.isNotBlank(currentEntry.getId()) && StringUtils.isNotBlank(currentEntry.getTitle())
                    && StringUtils.isNotBlank(currentEntry.getUrl())) {
                entries.add(currentEntry);
            }

            currentEntry = null;
            currentContent = null;
            currentSummary = null;
        } else if (path.equals("/rss/channel/item/link")) {
            currentEntry.setId(buffer.toString());
            currentEntry.setUrl(buffer.toString());
        } else if (path.equals("/rss/channel/item/title")) {
            currentEntry.setTitle(buffer.toString());
        } else if (path.equals("/rss/channel/item/pubDate")) {
            String pubDate = buffer.toString();
            if (StringUtils.isNotBlank(pubDate)) {
                SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
                formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.ENGLISH));
                try {
                    Date date = formatter.parse(pubDate);
                    currentEntry.setDate(date);
                } catch (Exception e) {
                    // unparsable date
                    logger.debug("Unable to parse date <" + pubDate + ">", e);
                }
            }
        } else if (path.equals("/rss/channel/item/description")) {
            currentSummary = buffer.toString();
        } else if (path.equals("/rss/channel/item/enclosure/url")) {
            currentEnclosure.setUrl(buffer.toString());
        } else if (path.equals("/rss/channel/item/enclosure/type")) {
            currentEnclosure.setType(buffer.toString());
        }
    } else if (Type.RSS_1_0.equals(type)) {
        String path = getCurrentPath();
        if (path.equals("/rdf:RDF/channel/title")) {
            title = buffer.toString();
        } else if (path.equals("/rdf:RDF/channel/link")) {
            url = buffer.toString();
        } else if (path.equals("/rdf:RDF/item")) {
            String content = currentSummary == null ? "" : currentSummary;
            content += "<p><a href=\"" + currentEntry.getUrl() + "\" target=\"_blank\">Lire la suite</a></p>";
            currentEntry.setContent(content);

            if (StringUtils.isBlank(currentEntry.getUrl())) {
                currentEntry.setUrl(url);
            }

            if (StringUtils.isNotBlank(currentEntry.getId()) && StringUtils.isNotBlank(currentEntry.getTitle())
                    && StringUtils.isNotBlank(currentEntry.getUrl())) {
                entries.add(currentEntry);
            }

            currentEntry = null;
            currentContent = null;
            currentSummary = null;
        } else if (path.equals("/rdf:RDF/item/title")) {
            currentEntry.setTitle(buffer.toString());
        } else if (path.equals("/rdf:RDF/item/link")) {
            currentEntry.setId(buffer.toString());
            currentEntry.setUrl(buffer.toString());
        } else if (path.equals("/rdf:RDF/item/description")) {
            currentSummary = buffer.toString();
        } else if (path.equals("/rdf:RDF/item/dc:date")) {
            String updated = buffer.toString();
            if (StringUtils.length(updated) > 19) {
                try {
                    Date date = null;
                    if (updated.endsWith("Z")) {
                        // No timezone
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                        date = formatter.parse(updated.substring(0, 19));
                    } else {
                        String timezone = updated.substring(updated.length() - 6);
                        timezone = timezone.substring(0, 3) + timezone.substring(4);
                        updated = updated.substring(0, 19) + timezone;
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                        date = formatter.parse(updated);
                    }
                    if (date != null) {
                        currentEntry.setDate(date);
                    }
                } catch (Exception e) {
                    // unparsable date
                    logger.warn("Unable to parse date <" + updated + ">", e);
                }
            }
        }
    }

    String s = elementsStack.remove(elementsStack.size() - 1);
    assert s.equals(qName);
}

From source file:org.gravidence.gravifon.resource.bean.ValidateableBean.java

/**
 * Checks that field length satisfies specified range (inclusive).
 * /*ww  w .  j  a v  a  2 s .c  o m*/
 * @param fieldValue field value
 * @param fieldName field name to use in error message
 * @param min minimum number of characters expected
 * @param max maximum number of characters expected
 * @throws ValidationException in case field length is invalid
 */
public static void checkLength(String fieldValue, String fieldName, int min, int max) {
    int fieldLength = StringUtils.length(fieldValue);
    if (fieldLength < min || fieldLength > max) {
        throw new ValidationException(GravifonError.INVALID,
                String.format("Property '%s' value length is out of expected range.", fieldName));
    }
}

From source file:org.jamwiki.db.WikiDatabase.java

/**
  *//from w w  w.j  a  va 2s. com
  */
protected static void setupSpecialPage(Locale locale, String virtualWiki, String topicName, WikiUser user,
        boolean adminOnly) throws DataAccessException, WikiException {
    logger.info("Setting up special page " + virtualWiki + " / " + topicName);
    if (user == null) {
        throw new IllegalArgumentException("Cannot pass null WikiUser object to setupSpecialPage");
    }
    String contents = null;
    try {
        contents = WikiUtil.readSpecialPage(locale, topicName);
    } catch (IOException e) {
        throw new DataAccessException(e);
    }
    Topic topic = new Topic();
    topic.setName(topicName);
    topic.setVirtualWiki(virtualWiki);
    topic.setTopicContent(contents);
    topic.setAdminOnly(adminOnly);
    int charactersChanged = StringUtils.length(contents);
    // FIXME - hard coding
    TopicVersion topicVersion = new TopicVersion(user, user.getLastLoginIpAddress(),
            "Automatically created by system setup", contents, charactersChanged);
    // FIXME - it is not connection-safe to parse for metadata since we are
    // already holding a connection
    // ParserOutput parserOutput =
    // ParserUtil.parserOutput(topic.getTopicContent(), virtualWiki, topicName);
    // WikiBase.getDataHandler().writeTopic(topic, topicVersion,
    // parserOutput.getCategories(), parserOutput.getLinks());
    WikiBase.getDataHandler().writeTopic(topic, topicVersion, null, null);
}

From source file:org.jamwiki.servlets.EditServlet.java

/**
 * Functionality to handle the "Save" button being clicked.
 *//*from w w w.  jav  a2s  .c  o  m*/
private void save(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    String topicName = WikiUtil.getTopicFromRequest(request);
    String virtualWiki = pageInfo.getVirtualWikiName();
    Topic topic = loadTopic(virtualWiki, topicName);
    Topic lastTopic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
    if (lastTopic != null
            && !lastTopic.getCurrentVersionId().equals(retrieveLastTopicVersionId(request, topic))) {
        // someone else has edited the topic more recently
        resolve(request, next, pageInfo);
        return;
    }
    String contents = request.getParameter("contents");
    String sectionName = "";
    if (!StringUtils.isBlank(request.getParameter("section"))) {
        // load section of topic
        int section = Integer.valueOf(request.getParameter("section"));
        ParserOutput parserOutput = new ParserOutput();
        String[] spliceResult = ParserUtil.parseSplice(parserOutput, request.getContextPath(),
                request.getLocale(), virtualWiki, topicName, section, contents);
        contents = spliceResult[1];
        sectionName = parserOutput.getSectionName();
    }
    if (contents == null) {
        logger.warning("The topic " + topicName + " has no content");
        throw new WikiException(new WikiMessage("edit.exception.nocontent", topicName));
    }
    // strip line feeds
    contents = StringUtils.remove(contents, '\r');
    String lastTopicContent = (lastTopic != null) ? StringUtils.remove(lastTopic.getTopicContent(), '\r') : "";
    if (lastTopic != null && StringUtils.equals(lastTopicContent, contents)) {
        // topic hasn't changed. redirect to prevent user from refreshing and
        // re-submitting
        ServletUtil.redirect(next, virtualWiki, topic.getName());
        return;
    }
    if (handleSpam(request, next, topicName, contents)) {
        this.loadEdit(request, next, pageInfo, contents, virtualWiki, topicName, false);
        return;
    }
    // parse for signatures and other syntax that should not be saved in raw
    // form
    WikiUser user = ServletUtil.currentWikiUser();
    ParserInput parserInput = new ParserInput();
    parserInput.setContext(request.getContextPath());
    parserInput.setLocale(request.getLocale());
    parserInput.setWikiUser(user);
    parserInput.setTopicName(topicName);
    parserInput.setUserDisplay(ServletUtil.getIpAddress(request));
    parserInput.setVirtualWiki(virtualWiki);
    ParserOutput parserOutput = ParserUtil.parseMetadata(parserInput, contents);
    // parse signatures and other values that need to be updated prior to saving
    contents = ParserUtil.parseMinimal(parserInput, contents);
    topic.setTopicContent(contents);
    // if (!StringUtils.isBlank(parserOutput.getRedirect())) {
    // // set up a redirect
    // topic.setRedirectTo(parserOutput.getRedirect());
    // topic.setTopicType(Topic.TYPE_REDIRECT);
    // } else if (topic.getTopicType() == Topic.TYPE_REDIRECT) {
    // // no longer a redirect
    // topic.setRedirectTo(null);
    // topic.setTopicType(Topic.TYPE_ARTICLE);
    // }
    int charactersChanged = StringUtils.length(contents) - StringUtils.length(lastTopicContent);
    TopicVersion topicVersion = new TopicVersion(user, ServletUtil.getIpAddress(request),
            request.getParameter("editComment"), contents, charactersChanged);
    if (request.getParameter("minorEdit") != null) {
        topicVersion.setEditType(TopicVersion.EDIT_MINOR);
    }
    WikiBase.getDataHandler().writeTopic(topic, topicVersion, parserOutput.getCategories(),
            parserOutput.getLinks());
    // // update watchlist
    WikiUserDetails userDetails = ServletUtil.currentUserDetails();
    if (!userDetails.hasRole(RoleImpl.ROLE_ANONYMOUS)) {
        // Watchlist watchlist = ServletUtil.currentWatchlist(request,
        // virtualWiki);
        // boolean watchTopic = (request.getParameter("watchTopic") != null);
        // if (watchlist.containsTopic(topicName) != watchTopic) {
        // WikiBase.getDataHandler().writeWatchlistEntry(watchlist, virtualWiki,
        // topicName, user.getUserId());
        // }
    }
    // redirect to prevent user from refreshing and re-submitting
    String target = topic.getName();
    if (!StringUtils.isBlank(sectionName)) {
        target += "#" + sectionName;
    }
    ServletUtil.redirect(next, virtualWiki, target);
}

From source file:org.jamwiki.servlets.ManageServlet.java

/**
 *
 *//*ww w  .  j  ava2  s .  co m*/
private void deletePage(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo, String topicName)
        throws Exception {
    String virtualWiki = pageInfo.getVirtualWikiName();
    Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, true, null);
    if (topic.getDeleted()) {
        logger.warning("Attempt to delete a topic that is already deleted: " + virtualWiki + " / " + topicName);
        return;
    }
    int charactersChanged = 0 - StringUtils.length(topic.getTopicContent());
    String contents = "";
    topic.setTopicContent(contents);
    WikiUser user = ServletUtil.currentWikiUser();
    TopicVersion topicVersion = new TopicVersion(user, ServletUtil.getIpAddress(request),
            request.getParameter("deleteComment"), contents, charactersChanged);
    topicVersion.setEditType(TopicVersion.EDIT_DELETE);
    WikiBase.getDataHandler().deleteTopic(topic, topicVersion);
}

From source file:org.jamwiki.servlets.ManageServlet.java

/**
 *
 *///from w  w  w .ja  v  a2  s.co m
private void undeletePage(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo,
        String topicName) throws Exception {
    String virtualWiki = pageInfo.getVirtualWikiName();
    Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, true, null);
    if (!topic.getDeleted()) {
        logger.warning("Attempt to undelete a topic that is not deleted: " + virtualWiki + " / " + topicName);
        return;
    }
    TopicVersion previousVersion = WikiBase.getDataHandler().lookupTopicVersion(topic.getCurrentVersionId());
    while (previousVersion != null && previousVersion.getPreviousTopicVersionId() != null
            && previousVersion.getEditType() == TopicVersion.EDIT_DELETE) {
        // loop back to find the last non-delete edit
        previousVersion = WikiBase.getDataHandler()
                .lookupTopicVersion(previousVersion.getPreviousTopicVersionId());
    }
    String contents = previousVersion.getVersionContent();
    topic.setTopicContent(contents);
    WikiUser user = ServletUtil.currentWikiUser();
    int charactersChanged = StringUtils.length(contents);
    TopicVersion topicVersion = new TopicVersion(user, ServletUtil.getIpAddress(request),
            request.getParameter("undeleteComment"), contents, charactersChanged);
    topicVersion.setEditType(TopicVersion.EDIT_UNDELETE);
    WikiBase.getDataHandler().undeleteTopic(topic, topicVersion);
}

From source file:org.jamwiki.servlets.TranslationServlet.java

/**
 *
 */// ww w  .  j av a 2s  . co m
private void writeTopic(HttpServletRequest request, WikiPageInfo pageInfo) throws Exception {
    String virtualWiki = pageInfo.getVirtualWikiName();
    String language = request.getParameter("language");
    String topicName = NamespaceHandler.NAMESPACE_JAMWIKI + NamespaceHandler.NAMESPACE_SEPARATOR
            + Utilities.decodeTopicName(filename(language), true);
    String contents = "<pre><nowiki>\n" + Utilities.readFile(filename(language)) + "\n</nowiki></pre>";
    Topic topic = WikiBase.getDataHandler().lookupTopic(virtualWiki, topicName, false, null);
    if (topic == null) {
        topic = new Topic();
        topic.setVirtualWiki(virtualWiki);
        topic.setName(topicName);
    }
    int charactersChanged = StringUtils.length(contents) - StringUtils.length(topic.getTopicContent());
    topic.setTopicContent(contents);
    topic.setReadOnly(true);
    topic.setTopicType(Topic.TYPE_SYSTEM_FILE);
    WikiUser user = ServletUtil.currentWikiUser();
    TopicVersion topicVersion = new TopicVersion(user, ServletUtil.getIpAddress(request), null, contents,
            charactersChanged);
    WikiBase.getDataHandler().writeTopic(topic, topicVersion, null, null);
}

From source file:org.jdto.util.expression.Expression.java

private boolean isOperator(String previousToken) {
    if (StringUtils.length(previousToken) != 1) {
        return false;
    }/*from  ww  w  .  java2 s .co m*/

    char character = previousToken.charAt(0);

    //look if it is on the list of supported operators.
    return isOperator(character);
}