Example usage for org.apache.commons.lang3 StringUtils normalizeSpace

List of usage examples for org.apache.commons.lang3 StringUtils normalizeSpace

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils normalizeSpace.

Prototype

public static String normalizeSpace(final String str) 

Source Link

Document

<p> Similar to <a href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize -space</a> </p> <p> The function returns the argument string with whitespace normalized by using <code> #trim(String) </code> to remove leading and trailing whitespace and then replacing sequences of whitespace characters by a single space.

Usage

From source file:gov.nyc.doitt.gis.geoclient.parser.token.TextUtils.java

public static String sanitize(String s) {
    if (s == null || s.isEmpty()) {
        return s;
    }//w  w  w .  j  av  a2s. co m
    // Remove leading and trailing spaces or punctuation (except for trailing 
    //period characters (eg, N.Y.)
    String clean = StringUtils.removePattern(s, "^(?:\\s|\\p{Punct})+|(?:\\s|[\\p{Punct}&&[^.]])+$");
    // Make sure ampersand is surrounded by spaces but allow double ampersand
    clean = clean.replaceAll("([^\\s&])\\&", "$1 &");
    clean = clean.replaceAll("\\&([^\\s&])", "& $1");
    // Normalize whitespace
    clean = StringUtils.normalizeSpace(clean);
    return clean;
}

From source file:com.mgmtp.jfunk.common.util.JFunkUtils.java

/**
 * Removes leading and trailing whitespace and replaces sequences of whitespace characters by a single space. As opposed to
 * {@link Character#isWhitespace(char)} or {@link StringUtils#isWhitespace(CharSequence)}, this funtion also considers
 * non-breaking spaces (ASCII 160) as whitespace.
 * /*from  w w w .j a  v a  2  s.c om*/
 * @param value
 *            the string to normalize whitespaces from, may be null
 * @return the modified string with whitespace normalized, or {@code null} if null was passed in
 */
public static String normalizeSpace(final String value) {
    if (value == null) {
        return null;
    }
    String result = NBSP_PATTERN.matcher(value).replaceAll(" ");
    return StringUtils.normalizeSpace(result);
}

From source file:net.ontopia.topicmaps.classify.JunkNormalizer.java

@Override
public String normalize(String term) {
    // strip out repeated whitespace characters
    term = StringUtils.normalizeSpace(term);
    // drop 's endings
    if (term.length() >= 2 && term.endsWith("'s")) {
        term = term.substring(0, term.length() - 2);
    }//from w w w  . j  a va2s.  c om
    return term;
}

From source file:alfio.manager.EventNameManager.java

/**
 * Generates and returns a short name based on the given display name.<br>
 * The generated short name will be returned only if it was not already used.<br>
 * The input parameter will be clean from "evil" characters such as punctuation and accents
 *
 * 1) if the {@code displayName} is a one-word name, then no further calculation will be done and it will be returned as it is, to lower case
 * 2) the {@code displayName} will be split by word and transformed to lower case. If the total length is less than 15, then it will be joined using "-" and returned
 * 3) the first letter of each word will be taken, excluding numbers
 * 4) a random code will be returned//from w w w .  j  a va2s  .c om
 *
 * @param displayName
 * @return
 */
public String generateShortName(String displayName) {
    Validate.isTrue(StringUtils.isNotBlank(displayName));
    String cleanDisplayName = StringUtils.stripAccents(StringUtils.normalizeSpace(displayName))
            .toLowerCase(Locale.ENGLISH).replaceAll(FIND_EVIL_CHARACTERS, "-");
    if (!StringUtils.containsWhitespace(cleanDisplayName) && isUnique(cleanDisplayName)) {
        return cleanDisplayName;
    }
    Optional<String> dashedName = getDashedName(cleanDisplayName);
    if (dashedName.isPresent()) {
        return dashedName.get();
    }
    Optional<String> croppedName = getCroppedName(cleanDisplayName);
    if (croppedName.isPresent()) {
        return croppedName.get();
    }
    return generateRandomName();
}

From source file:net.ontopia.topicmaps.cmdlineutils.Consistify.java

protected static void normalizeTopicNames(TopicMapIF tm) {
    Iterator it = tm.getTopics().iterator();
    while (it.hasNext()) {
        TopicIF topic = (TopicIF) it.next();

        Iterator it2 = topic.getTopicNames().iterator();
        while (it2.hasNext()) {
            TopicNameIF bn = (TopicNameIF) it2.next();
            bn.setValue(StringUtils.normalizeSpace(bn.getValue()));
        }/*from  w w w .j  a  va2  s . co m*/
    }
}

From source file:eu.openanalytics.rsb.EmailDepositITCase.java

private void verifyValidResult(final MimeMessage rsbResponseMessage, final String exceptedResponseBody)
        throws IOException, MessagingException {
    final Multipart parts = (Multipart) rsbResponseMessage.getContent();
    assertThat(StringUtils.normalizeSpace(
            ((MimeMultipart) getMailBodyPart(parts, "multipart/related").getContent()).getBodyPart(0)
                    .getContent().toString()),
            is(StringUtils.normalizeSpace(exceptedResponseBody)));

    assertThat(getMailBodyPart(parts, "application/pdf").getFileName(), is("rnorm.pdf"));
}

From source file:eu.openanalytics.rsb.EmailDepositITCase.java

private void verifyErrorResult(final MimeMessage rsbResponseMessage) throws IOException, MessagingException {
    final Multipart parts = (Multipart) rsbResponseMessage.getContent();

    final String responseBody = StringUtils
            .normalizeSpace(((MimeMultipart) getMailBodyPart(parts, "multipart/related").getContent())
                    .getBodyPart(0).getContent().toString());
    assertThat(StringUtils.containsIgnoreCase(responseBody, "error"), is(true));
}

From source file:controllers.modules.CorpusModule.java

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;// w w  w .j  a  va2  s  . c o m
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}

From source file:com.moviejukebox.model.Filmography.java

public final void setCharacter(final String character) {
    // Remove duplicate spaces and trim
    String newCharacter = StringUtils.normalizeSpace(character);

    if (isValidString(newCharacter) && !this.character.equalsIgnoreCase(newCharacter)) {
        this.character = newCharacter;
        setDirty();//from  ww  w.  j a  va2  s  .c  o m
    }
}

From source file:it.webappcommon.lib.dao.AbstractBaseDAO.java

/**
 * //from  w ww  .  j a  v a2 s.co m
 * @param conn
 * @return un nuovo ArrayList anche se non ci sono risultati dall query
 * @throws Exception
 */
public List<T> getAll(F filtro) throws Exception {
    List<T> returnValue = new ArrayList<T>();

    PreparedStatement prpStmt = null;
    StringBuilder sqlQuery = null;
    ResultSet rs = null;

    try {

        sqlQuery = new StringBuilder();

        sqlQuery.append("SELECT * FROM ");
        sqlQuery.append(" " + getNomeTabella() + " ");
        sqlQuery.append("WHERE ");
        // Verifico se e' specificato un filtro
        if (filtro != null) {
            sqlQuery.append(filtro.getSQLWhere());
        } else {
            sqlQuery.append(QueryBuilder.ALWAYS_TRUE); // TODO: se il
            // filtro e' null
            // non
            // posso accodare il resto delle
            // conzioni di base se non faccio
            // questo.
        }
        // Verifico se e' specificato un campo cancellazione
        if (getCampoDataCancellazione() != null
                && ((filtro == null) || (filtro != null && !filtro.isIncludeDeleted()))) {
            sqlQuery.append(" AND " + getCampoDataCancellazione() + " IS NULL");
        }
        // Verifico se e' specificato un ordinamento
        if (filtro != null) {
            sqlQuery.append(filtro.getSQLSort());
        }
        // Verifico se e' specificato un limit per le paginazioni
        if (filtro != null) {
            sqlQuery.append(filtro.getSQLLimit());
        }

        // prpStmt = getConnection().prepareStatement(sqlQuery.toString());
        String sqlString = sqlQuery.toString();
        logger.debug(sqlString);
        prpStmt = getConnection().prepareStatement(StringUtils.normalizeSpace(sqlString));
        logger.debug(prpStmt);
        rs = prpStmt.executeQuery();

        while (rs.next()) {
            returnValue.add(this.filler(rs));
        }

        // commit();
    } catch (Exception ex) {
        // rollback();
        logger.error(prpStmt, ex);
        throw ex;
    } finally {
        DAOUtils.close(getConnection(), prpStmt, rs, connApertaQui);
    }

    return returnValue;
}