1 //
2 // ========================================================================
3 // Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.websocket.common.util;
20
21 /**
22 * Collection of utility methods for Text content
23 */
24 public final class TextUtil
25 {
26 /**
27 * Create a hint of what the text is like.
28 * <p>
29 * Used by logging and error messages to get a hint of what the text is like.
30 *
31 * @param text
32 * the text to abbreviate, quote, and generally give you a hint of what the value is.
33 * @return the abbreviated text
34 */
35 public static String hint(String text)
36 {
37 if (text == null)
38 {
39 return "<null>";
40 }
41 return '"' + maxStringLength(30,text) + '"';
42 }
43
44 /**
45 * Smash a long string to fit within the max string length, by taking the middle section of the string and replacing them with an ellipsis "..."
46 * <p>
47 *
48 * <pre>
49 * Examples:
50 * .maxStringLength( 9, "Eatagramovabits") == "Eat...its"
51 * .maxStringLength(10, "Eatagramovabits") == "Eat...bits"
52 * .maxStringLength(11, "Eatagramovabits") == "Eata...bits"
53 * </pre>
54 *
55 * @param max
56 * the maximum size of the string (minimum size supported is 9)
57 * @param raw
58 * the raw string to smash
59 * @return the ellipsis'd version of the string.
60 */
61 public static String maxStringLength(int max, String raw)
62 {
63 int length = raw.length();
64 if (length <= max)
65 {
66 // already short enough
67 return raw;
68 }
69
70 if (max < 9)
71 {
72 // minimum supported
73 return raw.substring(0,max);
74 }
75
76 StringBuilder ret = new StringBuilder();
77 int startLen = (int)Math.round((double)max / (double)3);
78 ret.append(raw.substring(0,startLen));
79 ret.append("...");
80 ret.append(raw.substring(length - (max - startLen - 3)));
81
82 return ret.toString();
83 }
84 }