diff options
Diffstat (limited to 'src/main/java/com/juick/util/formatters')
-rw-r--r-- | src/main/java/com/juick/util/formatters/PlainTextFormatter.java | 25 |
1 files changed, 24 insertions, 1 deletions
diff --git a/src/main/java/com/juick/util/formatters/PlainTextFormatter.java b/src/main/java/com/juick/util/formatters/PlainTextFormatter.java index 9a885bca..2e7722e7 100644 --- a/src/main/java/com/juick/util/formatters/PlainTextFormatter.java +++ b/src/main/java/com/juick/util/formatters/PlainTextFormatter.java @@ -22,6 +22,7 @@ import com.juick.util.MessageUtils; import org.apache.commons.lang3.StringUtils; import org.ocpsoft.prettytime.PrettyTime; +import java.text.BreakIterator; import java.util.Date; import java.util.Locale; @@ -62,7 +63,7 @@ public class PlainTextFormatter { sb.append(attachmentUrl).append("\n"); } if (txt.length() >= cropLength) { - sb.append(StringUtils.substring(txt, 0, cropLength)).append(" [...]"); + sb.append(PlainTextFormatter.truncateText(txt, cropLength)).append(" [...]"); } else { sb.append(txt); } @@ -97,4 +98,26 @@ public class PlainTextFormatter { public static String formatTwitterCard(Message jmsg) { return MessageUtils.getMessageHashTags(jmsg) + StringUtils.defaultString(jmsg.getText()); } + /** + * Truncate text to the nearest word, up to a maximum length specified. + * + * @param text + * @param maxLength + * @return + */ + public static String truncateText(String text, int maxLength) { + if(text != null && text.length() > maxLength) { + BreakIterator bi = BreakIterator.getWordInstance(); + bi.setText(text); + + if(bi.isBoundary(maxLength-1)) { + return text.substring(0, maxLength-2); + } else { + int preceding = bi.preceding(maxLength-1); + return text.substring(0, preceding-1); + } + } else { + return text; + } + } } |