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

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

Introduction

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

Prototype

public static String strip(String str) 

Source Link

Document

Strips whitespace from the start and end of a String.

Usage

From source file:org.apache.storm.st.wrapper.LogData.java

public LogData(String logLine) {
    DateTime tempDate;//from w ww  . jav a2  s  .com
    final String[] pair = StringDecorator.split2(StringUtils.strip(logLine));
    final List<String> pairList = Arrays.asList(pair);
    AssertUtil.assertTwoElements(pairList);
    tempDate = dateFormat.parseDateTime(pairList.get(0).substring(0, dateLen));
    this.logDate = tempDate;
    this.data = pairList.get(1);
}

From source file:org.apache.wookie.w3c.util.UnicodeUtils.java

/**
 * Normalizes all space characters (and whitespace if includeWhitespace is set to true) in the given string to 
 * U+0020, then collapses multiple adjacent spaces to a single space, and
 * removes any leading and trailing spaces. If the input string is null,
 * the method returns an empty string ("")
 * @param in the string to normalize//ww  w .j  av  a  2 s. c o m
 * @param includeWhitespace set to true to normalize whitespace as well as space characters
 * @return the normalized string
 */
private static String normalize(String in, boolean includeWhitespace) {
    if (in == null)
        return "";
    // Create a buffer for the string
    StringBuffer buf = new StringBuffer();
    // Iterate over characters in the string and append them to buffer, replacing matching characters with standard spaces
    for (int x = 0; x < in.length(); x++) {
        char ch = in.charAt(x);
        if (Character.isSpaceChar(ch) || (Character.isWhitespace(ch) && includeWhitespace)) {
            ch = ' ';
        }
        buf.append(ch);
    }
    String str = buf.toString();
    // Squeeze out extra spaces
    str = CharSetUtils.squeeze(str, " ");
    // Strip off trailing and leading spaces
    str = StringUtils.strip(str);
    return str;
}

From source file:org.b3log.symphony.processor.advice.validate.ArticleAddValidation.java

/**
 * Validates article fields./*from w  w w.  j  a va 2s . c  o m*/
 *
 * @param request the specified HTTP servlet request
 * @param requestJSONObject the specified request object
 * @throws RequestProcessAdviceException if validate failed
 */
public static void validateArticleFields(final HttpServletRequest request, final JSONObject requestJSONObject)
        throws RequestProcessAdviceException {
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final LangPropsService langPropsService = beanManager.getReference(LangPropsServiceImpl.class);
    final TagQueryService tagQueryService = beanManager.getReference(TagQueryService.class);

    final String articleTitle = requestJSONObject.optString(Article.ARTICLE_TITLE);
    if (Strings.isEmptyOrNull(articleTitle) || articleTitle.length() > MAX_ARTICLE_TITLE_LENGTH) {
        throw new RequestProcessAdviceException(
                new JSONObject().put(Keys.MSG, langPropsService.get("articleTitleErrorLabel")));
    }

    final int articleType = requestJSONObject.optInt(Article.ARTICLE_TYPE);
    if (Article.isInvalidArticleType(articleType)) {
        throw new RequestProcessAdviceException(
                new JSONObject().put(Keys.MSG, langPropsService.get("articleTypeErrorLabel")));
    }

    String articleTags = requestJSONObject.optString(Article.ARTICLE_TAGS);
    if (Strings.isEmptyOrNull(articleTags)) {
        throw new RequestProcessAdviceException(
                new JSONObject().put(Keys.MSG, langPropsService.get("tagsErrorLabel")));
    }

    final ArticleMgmtService articleMgmtService = beanManager.getReference(ArticleMgmtService.class);

    articleTags = articleTags.replaceAll("\\s+", ",");
    articleTags = articleMgmtService.formatArticleTags(articleTags);

    String[] tagTitles = articleTags.split(",");
    if (null == tagTitles || 0 == tagTitles.length) {
        throw new RequestProcessAdviceException(
                new JSONObject().put(Keys.MSG, langPropsService.get("tagsErrorLabel")));
    }

    tagTitles = new LinkedHashSet<String>(Arrays.asList(tagTitles)).toArray(new String[0]);
    final List<String> invalidTags = tagQueryService.getInvalidTags();

    final StringBuilder tagBuilder = new StringBuilder();
    for (int i = 0; i < tagTitles.length; i++) {
        final String tagTitle = tagTitles[i].trim();

        if (Strings.isEmptyOrNull(tagTitle)) {
            throw new RequestProcessAdviceException(
                    new JSONObject().put(Keys.MSG, langPropsService.get("tagsErrorLabel")));
        }

        if (!Tag.TAG_TITLE_PATTERN.matcher(tagTitle).matches()) {
            throw new RequestProcessAdviceException(
                    new JSONObject().put(Keys.MSG, langPropsService.get("tagsErrorLabel")));
        }

        if (Strings.isEmptyOrNull(tagTitle) || tagTitle.length() > Tag.MAX_TAG_TITLE_LENGTH
                || tagTitle.length() < 1) {
            throw new RequestProcessAdviceException(
                    new JSONObject().put(Keys.MSG, langPropsService.get("tagsErrorLabel")));
        }

        final JSONObject currentUser = (JSONObject) request.getAttribute(User.USER);
        if (!Role.ADMIN_ROLE.equals(currentUser.optString(User.USER_ROLE))
                && ArrayUtils.contains(Symphonys.RESERVED_TAGS, tagTitle)) {
            throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG,
                    langPropsService.get("articleTagReservedLabel") + " [" + tagTitle + "]"));
        }

        if (invalidTags.contains(tagTitle)) {
            throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG,
                    langPropsService.get("articleTagInvalidLabel") + " [" + tagTitle + "]"));
        }

        tagBuilder.append(tagTitle).append(",");
    }
    if (tagBuilder.length() > 0) {
        tagBuilder.deleteCharAt(tagBuilder.length() - 1);
    }
    requestJSONObject.put(Article.ARTICLE_TAGS, tagBuilder.toString());

    String articleContent = requestJSONObject.optString(Article.ARTICLE_CONTENT);
    articleContent = StringUtils.strip(articleContent);
    if (Strings.isEmptyOrNull(articleContent) || articleContent.length() > MAX_ARTICLE_CONTENT_LENGTH
            || articleContent.length() < MIN_ARTICLE_CONTENT_LENGTH) {
        throw new RequestProcessAdviceException(
                new JSONObject().put(Keys.MSG, langPropsService.get("articleContentErrorLabel")));
    }

    final int rewardPoint = requestJSONObject.optInt(Article.ARTICLE_REWARD_POINT, 0);
    if (rewardPoint < 0) {
        throw new RequestProcessAdviceException(new JSONObject().put(Keys.MSG, "invalidRewardPointLabel"));
    }

    if (rewardPoint > 0) {
        final String articleRewardContnt = requestJSONObject.optString(Article.ARTICLE_REWARD_CONTENT);
        if (Strings.isEmptyOrNull(articleRewardContnt)
                || articleRewardContnt.length() > MAX_ARTICLE_CONTENT_LENGTH
                || articleRewardContnt.length() < MIN_ARTICLE_CONTENT_LENGTH) {
            throw new RequestProcessAdviceException(
                    new JSONObject().put(Keys.MSG, langPropsService.get("articleRewardContentErrorLabel")));
        }
    }
}

From source file:org.codehaus.mojo.taglist.FileAnalyser.java

/**
 * Scans a file to look for task tags.//from  www .j a  v  a2 s  . c  o  m
 * 
 * @param file the file to scan.
 */
public void scanFile(File file) {
    LineNumberReader reader = null;

    try {
        reader = new LineNumberReader(getReader(file));

        String currentLine = reader.readLine();
        while (currentLine != null) {
            int index = -1;
            Iterator iter = tagClasses.iterator();
            // look for a tag on this line
            while (iter.hasNext()) {
                TagClass tagClass = (TagClass) iter.next();
                index = tagClass.tagMatchContains(currentLine, locale);
                if (index != TagClass.NO_MATCH) {
                    // there's a tag on this line
                    String commentType = null;
                    commentType = extractCommentType(currentLine, index);

                    if (commentType == null) {
                        // this is not a valid comment tag: skip other tag classes and
                        // go to the next line
                        break;
                    }

                    int tagLength = tagClass.getLastTagMatchStringLength();
                    int commentStartIndex = reader.getLineNumber();
                    StringBuffer comment = new StringBuffer();

                    String firstLine = StringUtils.strip(currentLine.substring(index + tagLength));
                    firstLine = StringUtils.removeEnd(firstLine, "*/"); //MTAGLIST-35
                    if (firstLine.length() == 0 || ":".equals(firstLine)) {
                        // this is not a valid comment tag: nothing is written there
                        if (emptyCommentsOn) {
                            comment.append("--");
                            comment.append(noCommentString);
                            comment.append("--");
                        } else {
                            continue;
                        }
                    } else {
                        // this tag has a comment
                        if (firstLine.charAt(0) == ':') {
                            comment.append(firstLine.substring(1).trim());
                        } else {
                            comment.append(firstLine);
                        }

                        if (multipleLineCommentsOn) {
                            // Mark the current position, set the read forward limit to
                            // a large number that should not be met.
                            reader.mark(MAX_COMMENT_CHARACTERS);

                            // next line
                            String futureLine = reader.readLine();

                            // we're looking for multiple line comments
                            while (futureLine != null && futureLine.trim().startsWith(commentType)
                                    && futureLine.indexOf(tagClass.getLastTagMatchString()) < 0) {
                                String currentComment = futureLine
                                        .substring(futureLine.indexOf(commentType) + commentType.length())
                                        .trim();
                                if (currentComment.startsWith("@") || "".equals(currentComment)
                                        || "/".equals(currentComment)) {
                                    // the comment is finished
                                    break;
                                }
                                // try to look if the next line is not a new tag
                                boolean newTagFound = false;
                                Iterator moreTCiter = tagClasses.iterator();
                                while (moreTCiter.hasNext()) {
                                    TagClass tc = (TagClass) moreTCiter.next();
                                    if (tc.tagMatchStartsWith(currentComment, locale)) {
                                        newTagFound = true;
                                        break;
                                    }
                                }
                                if (newTagFound) {
                                    // this is a new comment: stop here the current comment
                                    break;
                                }
                                // nothing was found: this means the comment is going on this line
                                comment.append(" ");
                                comment.append(currentComment);
                                futureLine = reader.readLine();
                            }

                            // Reset the reader to the marked position before the multi
                            // line check was performed.
                            reader.reset();
                        }
                    }
                    TagReport tagReport = tagClass.getTagReport();
                    FileReport fileReport = tagReport.getFileReport(file, encoding);
                    fileReport.addComment(comment.toString(), commentStartIndex);
                }
            }
            currentLine = reader.readLine();
        }
    } catch (IOException e) {
        log.error("Error while scanning the file " + file.getPath(), e);
    } finally {
        IOUtil.close(reader);
    }
}

From source file:org.codice.ddf.catalog.ui.config.ConfigurationApplication.java

public void setTypeNameMapping(String[] mappings) {
    if (mappings != null) {
        typeNameMapping = MapUtils.lazyMap(new TreeMap(), NEW_SET_FACTORY);

        for (String mappingValue : mappings) {
            // workaround for KARAF-1701
            for (String mapping : StringUtils.split(mappingValue, ",")) {
                String[] nameAndType = StringUtils.split(mapping, "=");
                if (nameAndType.length == 2) {
                    String displayName = StringUtils.strip(nameAndType[0]);
                    String type = StringUtils.strip(nameAndType[1]);
                    if (StringUtils.isNotBlank(displayName) && StringUtils.isNotBlank(type)) {
                        typeNameMapping.get(displayName).add(type);
                    }//from  w ww .  j  av  a 2s  . co m
                } else {
                    LOGGER.info("Invalid type display name mapping format {}", mapping);
                }
            }
        }
    }
}

From source file:org.cytobank.acs.core.Association.java

/**
 * Sets the relationship to the <code>FileResourceIdentifier</code> that this association points to.
 * //www.  j a va 2  s  .c o  m
 * @param relationship A <code>String</code> describing the relationship.  A constant out of <code>RelationshipTypes</code>, which represent the known association types
 * from the ACS specification, should be considered before using a custom type.  An <code>InvalidAssociationException</code> will be thrown if this parameter is empty or null.
 */
public void setRelationship(String relationship) throws InvalidAssociationException {
    if (StringUtils.isBlank(relationship))
        throw new InvalidAssociationException(BLANK_RELATIONSHIP_ERROR);

    relationship = StringUtils.strip(relationship.toLowerCase());

    setAttributeValue(Constants.RELATIONSHIP_ATTRIBUTE, relationship);
}

From source file:org.cytobank.acs.core.FileResourceIdentifier.java

/**
 * Sets the MIME type of the file that this <code>FileResourceIdentifier</code> refers to.
 * <p>/*from   ww  w  .j  a  v a  2s .c om*/
 * NOTE: "application/vnd.isac.fcs" is the expected MIME type to be used in the case of FCS files. (Available in <code>Constants.FCS_FILE_MIME_TYPE</code>.)
 *
 * @param mimeType a <code>String</code> representing the MIME type of the file that this <code>FileResourceIdentifier</code> refers to,
 * or <code>null</code> if there is none
 * @see Constants#FCS_FILE_MIME_TYPE
 */
public void setMimeType(String mimeType) {
    // If the mimeType is a null or an empty String then delete the attribute to keep things tidy
    if (StringUtils.isBlank(mimeType))
        removeAttribute(Constants.MIME_TYPE_ATTRIBUTE);

    // Strip white spaces off the ends of the mime type
    mimeType = StringUtils.strip(mimeType);

    setAttributeValue(Constants.MIME_TYPE_ATTRIBUTE, mimeType);
}

From source file:org.cytobank.acs.core.RelationshipTypes.java

/** 
 * Returns <code>true</code> if one <code>String</code> matches another after dropping case and stripping off surrounding white spaces.
 * @param relationshipTypeConstant a <code>String</code> representing an <code>RelationshipType</code> constant 
 * @param relationshipType a <code>String</code> to test if it the same as the <code>RelationshipType</code> constant
 * @return <code>true</code> if they match, <code>false</code> otherwise
 *///from ww  w  .  ja  v a 2  s  .c o m
public static boolean testAssociationType(String relationshipTypeConstant, String relationshipType) {
    relationshipType = StringUtils.strip(relationshipType);

    return relationshipTypeConstant.equalsIgnoreCase(relationshipType);
}

From source file:org.dspace.importer.external.metadatamapping.processor.AuthorMetadataProcessorService.java

@Override
public String processMetadataValue(String value) {
    String ret = value;/* www  .  j a v  a 2s .co  m*/
    ret = StringUtils.strip(ret);
    ret = StringUtils.stripEnd(ret, ".");

    return ret;
}

From source file:org.dspace.importer.external.metadatamapping.transform.AuthorMetadataProcessorService.java

/**
 * Strip a given value of its last dot (.)
 * @param value the value to run the processing over
 * @return The initial param with its ending dot stripped
 *//* w ww  .j  ava2  s . co m*/
@Override
public String processMetadataValue(String value) {
    String ret = value;
    ret = StringUtils.strip(ret);
    ret = StringUtils.stripEnd(ret, ".");

    return ret;
}