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:com.gargoylesoftware.htmlunit.html.HtmlSerializer.java

private void appendHtmlTextArea(final HtmlTextArea htmlTextArea) {
    if (isVisible(htmlTextArea)) {
        String text = htmlTextArea.getText();

        final BrowserVersion browser = htmlTextArea.getPage().getWebClient().getBrowserVersion();
        if (browser.hasFeature(HTMLTEXTAREA_REMOVE_NEWLINE_FROM_TEXT)) {
            text = TEXT_AREA_PATTERN.matcher(text).replaceAll("");
            text = StringUtils.replace(text, "\r", "");
            text = StringUtils.normalizeSpace(text);
        } else {//from   w  ww.j  ava  2 s. co m
            text = StringUtils.stripEnd(text, null);
            text = TEXT_AREA_PATTERN.matcher(text).replaceAll(AS_TEXT_NEW_LINE);
            text = StringUtils.replace(text, "\r", AS_TEXT_NEW_LINE);
        }
        text = StringUtils.replace(text, " ", AS_TEXT_BLANK);
        doAppend(text);
    }
}

From source file:com.moviejukebox.reader.MovieNFOReader.java

/**
 * Convert the date string to a date and update the movie object
 *
 * @param movie//from  ww w  . j av  a2  s.com
 * @param dateString
 */
public static void movieDate(Movie movie, final String dateString) {
    String parseDate = StringUtils.normalizeSpace(dateString);

    if (StringTools.isNotValidString(parseDate)) {
        // No date, so return
        return;
    }

    Date parsedDate;
    try {
        parsedDate = DateTimeTools.parseStringToDate(parseDate);
    } catch (IllegalArgumentException ex) {
        LOG.warn("Failed parsing NFO file for movie: {}. Please fix or remove it.", movie.getBaseFilename());
        LOG.warn("premiered or releasedate does not contain a valid date: {}", parseDate);
        LOG.warn(SystemTools.getStackTrace(ex));

        if (OverrideTools.checkOverwriteReleaseDate(movie, NFO_PLUGIN_ID)) {
            movie.setReleaseDate(parseDate, NFO_PLUGIN_ID);
        }
        return;
    }

    if (parsedDate != null) {
        try {
            if (OverrideTools.checkOverwriteReleaseDate(movie, NFO_PLUGIN_ID)) {
                movie.setReleaseDate(DateTimeTools.convertDateToString(parsedDate, "yyyy-MM-dd"),
                        NFO_PLUGIN_ID);
            }

            if (OverrideTools.checkOverwriteYear(movie, NFO_PLUGIN_ID)) {
                movie.setYear(DateTimeTools.convertDateToString(parsedDate, "yyyy"), NFO_PLUGIN_ID);
            }
        } catch (Exception ex) {
            LOG.warn("Failed formatting parsed date: {}", parsedDate);
            LOG.warn(SystemTools.getStackTrace(ex));
        }
    }
}

From source file:org.emau.icmvc.ganimed.deduplication.preprocessing.impl.UniversalStringTransformation.java

/**
 * The method normalizes spaces, turns the string to uppercase representation
 * and normalizes hyphens//from  ww w .j a  v  a  2  s .  c  o  m
 * @param input
 * @return
 */
public String normalize(String input) {
    // normalize spaces 
    input = StringUtils.normalizeSpace(input);

    input = StringUtils.replace(input, "-", " - ");
    input = StringUtils.replace(input, " - ", "-");

    input = StringUtils.capitalize(input);

    return input;

}

From source file:org.gbif.drupal.mybatis.EnumDictTypeHandler.java

@VisibleForTesting
protected T lookup(String val) {
    try {//from w  w w  .  j ava  2  s. c  om
        return (T) VocabularyUtils.lookupEnum(val, clazz);

    } catch (IllegalArgumentException e) {
        if (!Strings.isNullOrEmpty(val)) {
            final String normed = StringUtils.normalizeSpace(val.toLowerCase());
            if (dict.containsKey(normed)) {
                return dict.get(normed);
            }
        }
    }
    return defaultValue;
}

From source file:org.gbif.nub.lookup.HigherTaxaLookup.java

/**
 * @return non empty uppercased string with normalized whitespace and all non latin letters replaced. Or null
 */// w w w . j a v  a2s . c  o  m
@VisibleForTesting
protected static String norm(String x) {
    Pattern REMOVE_NON_LETTERS = Pattern.compile("[\\W\\d]+");
    x = Strings.nullToEmpty(x);
    x = REMOVE_NON_LETTERS.matcher(x).replaceAll(" ");
    x = StringUtils.normalizeSpace(x).toUpperCase();
    return StringUtils.trimToNull(x);
}

From source file:org.gbif.registry2.ims.EnumDictTypeHandler.java

@VisibleForTesting
protected T lookup(String val) {
    try {/*from   ww  w . ja va  2 s. c  om*/
        return (T) VocabularyUtils.lookupEnum(val, clazz);

    } catch (IllegalArgumentException e) {
        if (!Strings.isNullOrEmpty(val)) {
            final String normed = StringUtils.normalizeSpace(val.toLowerCase());
            if (DICT.containsKey(normed)) {
                return DICT.get(normed);
            }
        }
    }
    return defaultValue;
}

From source file:org.lanternpowered.server.console.ConsoleCommandCompleter.java

@Override
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
    String buffer = line.line();/* w ww  .j  a  va  2s.  c o  m*/

    // The content with normalized spaces, the spaces are trimmed
    // from the ends and there are never two spaces directly after each other
    String command = StringUtils.normalizeSpace(buffer);

    boolean hasPrefix = command.startsWith("/");
    // Don't include the '/'
    if (hasPrefix) {
        command = command.substring(1);
    }

    // Keep the last space, it must be there!
    if (buffer.endsWith(" ")) {
        command = command + " ";
    }

    final String command0 = command;
    final Future<List<String>> tabComplete = ((LanternScheduler) Sponge.getScheduler()).callSync(
            () -> Sponge.getCommandManager().getSuggestions(LanternConsoleSource.INSTANCE, command0, null));

    try {
        // Get the suggestions
        final List<String> suggestions = tabComplete.get();
        // If the suggestions are for the command and there was a prefix, then append the prefix
        if (hasPrefix && command.split(" ").length == 1 && !command.endsWith(" ")) {
            for (String completion : suggestions) {
                if (!completion.isEmpty()) {
                    candidates.add(new Candidate('/' + completion));
                }
            }
        } else {
            for (String completion : suggestions) {
                if (!completion.isEmpty()) {
                    candidates.add(new Candidate(completion));
                }
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        Lantern.getLogger().error("Failed to tab complete", e);
    }
}

From source file:org.lanternpowered.server.network.vanilla.message.handler.play.HandlerPlayInChatMessage.java

@Override
public void handle(NetworkContext context, MessagePlayInChatMessage message) {
    final NetworkSession session = context.getSession();
    final LanternPlayer player = session.getPlayer();
    player.resetIdleTimeoutCounter();//  w ww.j a  va 2 s.c om
    final String message0 = message.getMessage();

    // Check for a valid click action callback
    final Matcher matcher = LanternClickActionCallbacks.COMMAND_PATTERN.matcher(message0);
    if (matcher.matches()) {
        final UUID uniqueId = UUID.fromString(matcher.group(1));
        final Optional<Consumer<CommandSource>> callback = LanternClickActionCallbacks.get()
                .getCallbackForUUID(uniqueId);
        if (callback.isPresent()) {
            callback.get().accept(player);
        } else {
            player.sendMessage(
                    error(t("The callback you provided was not valid. Keep in mind that callbacks will expire "
                            + "after 10 minutes, so you might want to consider clicking faster next time!")));
        }
        return;
    }

    String message1 = StringUtils.normalizeSpace(message0);
    if (!isAllowedString(message0)) {
        session.disconnect(t("multiplayer.disconnect.illegal_characters"));
        return;
    }
    if (message1.startsWith("/")) {
        Lantern.getSyncExecutorService()
                .submit(() -> Sponge.getCommandManager().process(player, message1.substring(1)));
    } else {
        final Text nameText = player.get(Keys.DISPLAY_NAME).get();
        final Text rawMessageText = Text.of(message0);
        final GlobalConfig.Chat.Urls urls = Lantern.getGame().getGlobalConfig().getChat().getUrls();
        final Text messageText;
        if (urls.isEnabled() && player.hasPermission(Permissions.Chat.FORMAT_URLS)) {
            messageText = newTextWithLinks(message0, urls.getTemplate(), false);
        } else {
            messageText = rawMessageText;
        }
        final MessageChannel channel = player.getMessageChannel();
        final MessageChannelEvent.Chat event = SpongeEventFactory.createMessageChannelEventChat(
                Cause.of(NamedCause.source(player)), channel, Optional.of(channel),
                new MessageEvent.MessageFormatter(nameText, messageText), rawMessageText, false);
        if (!Sponge.getEventManager().post(event) && !event.isMessageCancelled()) {
            event.getChannel().ifPresent(c -> c.send(player, event.getMessage(), ChatTypes.CHAT));
        }
    }
    final Attribute<ChatData> attr = context.getChannel().attr(CHAT_DATA);
    ChatData chatData = attr.get();
    if (chatData == null) {
        chatData = new ChatData();
        final ChatData chatData1 = attr.setIfAbsent(chatData);
        if (chatData1 != null) {
            chatData = chatData1;
        }
    }
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (chatData) {
        final long currentTime = LanternGame.currentTimeTicks();
        if (chatData.lastChatTime != -1L) {
            chatData.chatThrottle = (int) Math.max(0,
                    chatData.chatThrottle - (currentTime - chatData.lastChatTime));
        }
        chatData.lastChatTime = currentTime;
        chatData.chatThrottle += 20;
        if (chatData.chatThrottle > Lantern.getGame().getGlobalConfig().getChatSpamThreshold()) {
            session.disconnect(t("disconnect.spam"));
        }
    }
}

From source file:org.lanternpowered.server.network.vanilla.message.handler.play.HandlerPlayInTabComplete.java

@Override
public void handle(NetworkContext context, MessagePlayInTabComplete message) {
    final String text = message.getText();
    // The content with normalized spaces, the spaces are trimmed
    // from the ends and there are never two spaces directly after eachother
    final String textNormalized = StringUtils.normalizeSpace(text);

    final Player player = context.getSession().getPlayer();
    final Location<World> targetBlock = message.getBlockPosition()
            .map(pos -> new Location<>(player.getWorld(), pos)).orElse(null);

    final boolean hasPrefix = textNormalized.startsWith("/");
    if (hasPrefix || message.getAssumeCommand()) {
        String command = textNormalized;

        // Don't include the '/'
        if (hasPrefix) {
            command = command.substring(1);
        }//www.ja  v a  2 s  .  c om

        // Keep the last space, it must be there!
        if (text.endsWith(" ")) {
            command = command + " ";
        }

        // Get the suggestions
        List<String> suggestions = ((LanternCommandManager) Sponge.getCommandManager()).getSuggestions(player,
                command, targetBlock, message.getAssumeCommand());

        // If the suggestions are for the command and there was a prefix, then append the prefix
        if (hasPrefix && command.split(" ").length == 1 && !command.endsWith(" ")) {
            suggestions = suggestions.stream().map(suggestion -> '/' + suggestion)
                    .collect(ImmutableList.toImmutableList());
        }

        context.getSession().send(new MessagePlayOutTabComplete(suggestions));
    } else {
        // Vanilla mc will complete user names if
        // no command is being completed
        final int index = text.lastIndexOf(' ');
        final String part;
        if (index == -1) {
            part = text;
        } else {
            part = text.substring(index + 1);
        }
        if (part.isEmpty()) {
            return;
        }
        final String part1 = part.toLowerCase();
        final List<String> suggestions = Sponge.getServer().getOnlinePlayers().stream()
                .map(CommandSource::getName).filter(n -> n.toLowerCase().startsWith(part1))
                .collect(Collectors.toList());
        final TabCompleteEvent.Chat event = SpongeEventFactory.createTabCompleteEventChat(
                Cause.source(context.getSession().getPlayer()).build(), ImmutableList.copyOf(suggestions),
                suggestions, text, Optional.ofNullable(targetBlock), false);
        if (!Sponge.getEventManager().post(event)) {
            context.getSession().send(new MessagePlayOutTabComplete(suggestions));
        }
    }
}

From source file:org.starnub.utilities.strings.StringUtilities.java

/**
 * This will remove leading, trailing and double spaces
 *
 * @param s String the string to be cleaned
 * @return String the cleaned string/*from w w w .j ava2s .co m*/
 */
public static String removeDoubleLeadingTrailingSpaces(String s) {
    return StringUtils.normalizeSpace(s);
}