1 package be
.nikiroo
.utils
;
4 import java
.awt
.image
.BufferedImage
;
5 import java
.io
.ByteArrayInputStream
;
6 import java
.io
.ByteArrayOutputStream
;
7 import java
.io
.DataInputStream
;
9 import java
.io
.IOException
;
10 import java
.io
.InputStream
;
11 import java
.security
.MessageDigest
;
12 import java
.security
.NoSuchAlgorithmException
;
13 import java
.text
.Normalizer
;
14 import java
.text
.Normalizer
.Form
;
15 import java
.text
.ParseException
;
16 import java
.text
.SimpleDateFormat
;
17 import java
.util
.Date
;
18 import java
.util
.Scanner
;
19 import java
.util
.regex
.Pattern
;
20 import java
.util
.zip
.ZipInputStream
;
22 import javax
.imageio
.ImageIO
;
24 import org
.unbescape
.html
.HtmlEscape
;
25 import org
.unbescape
.html
.HtmlEscapeLevel
;
26 import org
.unbescape
.html
.HtmlEscapeType
;
29 * This class offer some utilities based around {@link String}s.
33 public class StringUtils
{
35 * This enum type will decide the alignment of a {@link String} when padding
36 * is applied or if there is enough horizontal space for it to be aligned.
38 public enum Alignment
{
39 /** Aligned at left. */
43 /** Aligned at right. */
47 static private Pattern marks
= Pattern
48 .compile("[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+");
51 * Fix the size of the given {@link String} either with space-padding or by
55 * the {@link String} to fix
57 * the size of the resulting {@link String} or -1 for a noop
59 * @return the resulting {@link String} of size <i>size</i>
61 static public String
padString(String text
, int width
) {
62 return padString(text
, width
, true, Alignment
.Beginning
);
66 * Fix the size of the given {@link String} either with space-padding or by
67 * optionally shortening it.
70 * the {@link String} to fix
72 * the size of the resulting {@link String} if the text fits or
73 * if cut is TRUE or -1 for a noop
75 * cut the {@link String} shorter if needed
77 * align the {@link String} in this position if we have enough
80 * @return the resulting {@link String} of size <i>size</i> minimum
82 static public String
padString(String text
, int width
, boolean cut
,
89 int diff
= width
- text
.length();
93 text
= text
.substring(0, width
);
94 } else if (diff
> 0) {
95 if (diff
< 2 && align
!= Alignment
.End
)
96 align
= Alignment
.Beginning
;
100 text
= text
+ new String(new char[diff
]).replace('\0', ' ');
103 text
= new String(new char[diff
]).replace('\0', ' ') + text
;
107 int pad1
= (diff
) / 2;
108 int pad2
= (diff
+ 1) / 2;
109 text
= new String(new char[pad1
]).replace('\0', ' ') + text
110 + new String(new char[pad2
]).replace('\0', ' ');
120 * Sanitise the given input to make it more Terminal-friendly by removing
121 * combining characters.
124 * the input to sanitise
125 * @param allowUnicode
126 * allow Unicode or only allow ASCII Latin characters
128 * @return the sanitised {@link String}
130 static public String
sanitize(String input
, boolean allowUnicode
) {
131 return sanitize(input
, allowUnicode
, !allowUnicode
);
135 * Sanitise the given input to make it more Terminal-friendly by removing
136 * combining characters.
139 * the input to sanitise
140 * @param allowUnicode
141 * allow Unicode or only allow ASCII Latin characters
142 * @param removeAllAccents
143 * TRUE to replace all accentuated characters by their non
144 * accentuated counter-parts
146 * @return the sanitised {@link String}
148 static public String
sanitize(String input
, boolean allowUnicode
,
149 boolean removeAllAccents
) {
151 if (removeAllAccents
) {
152 input
= Normalizer
.normalize(input
, Form
.NFKD
);
153 input
= marks
.matcher(input
).replaceAll("");
156 input
= Normalizer
.normalize(input
, Form
.NFKC
);
159 StringBuilder builder
= new StringBuilder();
160 for (int index
= 0; index
< input
.length(); index
++) {
161 char car
= input
.charAt(index
);
162 // displayable chars in ASCII are in the range 32<->255,
164 if (car
>= 32 && car
<= 255 && car
!= 127) {
168 input
= builder
.toString();
175 * Convert between time in milliseconds to {@link String} in a "static" way
176 * (to exchange data over the wire, for instance).
179 * the time in milliseconds
181 * @return the time as a {@link String}
183 static public String
fromTime(long time
) {
184 SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
185 return sdf
.format(new Date(time
));
189 * Convert between time as a {@link String} to milliseconds in a "static"
190 * way (to exchange data over the wire, for instance).
193 * the time as a {@link String}
195 * @return the time in milliseconds
197 static public long toTime(String displayTime
) {
198 SimpleDateFormat sdf
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
200 return sdf
.parse(displayTime
).getTime();
201 } catch (ParseException e
) {
207 * Convert the given {@link Image} object into a Base64 representation of
208 * the same {@link Image}. object.
211 * the {@link Image} object to convert
213 * @return the Base64 representation
215 * @throws IOException
216 * in case of IO error
218 static public String
fromImage(BufferedImage image
) throws IOException
{
219 String imageString
= null;
220 ByteArrayOutputStream out
= new ByteArrayOutputStream();
222 ImageIO
.write(image
, "jpeg", out
);
223 byte[] imageBytes
= out
.toByteArray();
225 imageString
= new String(Base64
.encodeBytes(imageBytes
));
233 * Convert the given image into a Base64 representation of the same
237 * the image to convert
239 * @return the Base64 representation
241 * @throws IOException
242 * in case of IO error
244 static public String
fromStream(InputStream in
) throws IOException
{
245 String fileString
= null;
246 ByteArrayOutputStream out
= new ByteArrayOutputStream();
248 byte[] buf
= new byte[8192];
251 while ((c
= in
.read(buf
, 0, buf
.length
)) > 0) {
252 out
.write(buf
, 0, c
);
257 fileString
= new String(Base64
.encodeBytes(out
.toByteArray()));
264 * Convert the given Base64 representation of an image into an {@link Image}
268 * the {@link Image} in Base64 format
270 * @return the {@link Image} object
272 * @throws IOException
273 * in case of IO error
275 static public BufferedImage
toImage(String b64data
) throws IOException
{
276 ByteArrayInputStream in
= new ByteArrayInputStream(
277 Base64
.decode(b64data
));
278 return IOUtils
.toImage(in
);
282 * Return a hash of the given {@link String}.
289 static public String
getHash(String input
) {
291 MessageDigest md
= MessageDigest
.getInstance("MD5");
292 md
.update(input
.getBytes());
293 byte byteData
[] = md
.digest();
295 StringBuffer hexString
= new StringBuffer();
296 for (int i
= 0; i
< byteData
.length
; i
++) {
297 String hex
= Integer
.toHexString(0xff & byteData
[i
]);
298 if (hex
.length() == 1)
299 hexString
.append('0');
300 hexString
.append(hex
);
303 return hexString
.toString();
304 } catch (NoSuchAlgorithmException e
) {
310 * Remove the HTML content from the given input, and un-html-ize the rest.
313 * the HTML-encoded content
315 * @return the HTML-free equivalent content
317 public static String
unhtml(String html
) {
318 StringBuilder builder
= new StringBuilder();
321 for (char car
: html
.toCharArray()) {
324 } else if (car
== '>') {
326 } else if (inTag
<= 0) {
331 char nbsp
= ' '; // non-breakable space (a special char)
333 return HtmlEscape
.unescapeHtml(builder
.toString()).replace(nbsp
, space
);
337 * Escape the given {@link String} so it can be used in XML, as content.
340 * the input {@link String}
342 * @return the escaped {@link String}
344 public static String
xmlEscape(String input
) {
349 return HtmlEscape
.escapeHtml(input
,
350 HtmlEscapeType
.HTML4_NAMED_REFERENCES_DEFAULT_TO_HEXA
,
351 HtmlEscapeLevel
.LEVEL_1_ONLY_MARKUP_SIGNIFICANT
);
355 * Escape the given {@link String} so it can be used in XML, as text content
356 * inside double-quotes.
359 * the input {@link String}
361 * @return the escaped {@link String}
363 public static String
xmlEscapeQuote(String input
) {
368 return HtmlEscape
.escapeHtml(input
,
369 HtmlEscapeType
.HTML4_NAMED_REFERENCES_DEFAULT_TO_HEXA
,
370 HtmlEscapeLevel
.LEVEL_1_ONLY_MARKUP_SIGNIFICANT
);
373 public static String
zip64(String data
) {
375 return Base64
.encodeBytes(data
.getBytes(), Base64
.GZIP
);
376 } catch (IOException e
) {
382 public static String
unzip64(String data
) throws IOException
{
383 ByteArrayInputStream in
= new ByteArrayInputStream(Base64
.decode(data
,
386 Scanner scan
= new Scanner(in
);
387 scan
.useDelimiter("\\A");