1. Project Clover database Wed Jan 17 2024 23:40:18 CST
  2. Package org.europa.together.utils

File StringUtils.java

 

Coverage histogram

../../../../img/srcFileCovDistChart10.png
0% of files have more coverage

Code metrics

22
86
15
1
324
193
29
0.34
5.73
15
1.93

Classes

Class Line # Actions
StringUtils 21 86 0% 29 0
1.0100%
 

Contributing tests

This file is covered by 201 tests. .

Source view

1    package org.europa.together.utils;
2   
3    import java.nio.charset.Charset;
4    import java.nio.charset.StandardCharsets;
5    import java.text.DateFormat;
6    import java.text.ParseException;
7    import java.text.SimpleDateFormat;
8    import java.util.ArrayList;
9    import java.util.Base64;
10    import java.util.Date;
11    import java.util.List;
12    import java.util.UUID;
13    import org.europa.together.application.LogbackLogger;
14    import org.europa.together.business.Logger;
15    import org.europa.together.domain.ByteOrderMark;
16    import org.europa.together.domain.LogLevel;
17   
18    /**
19    * Some useful Methods for String manipulation, Hash and UUID generation.
20    */
 
21    public final class StringUtils {
22   
23    private static final Logger LOGGER = new LogbackLogger(StringUtils.class);
24    private static final Charset CHARSET = Charset.forName("UTF-8");
25    private static final int LIMES = 9;
26    private static final int LIMIT = 2100;
27   
28    /**
29    * Constructor.
30    */
 
31  1 toggle private StringUtils() {
32  1 throw new UnsupportedOperationException();
33    }
34   
35    /**
36    * Test a String if is empty or NULL. Return TRUE when the String is empty
37    * or NULL. The test don't figure out when a Sting contains only non
38    * printable or whitespace characters.
39    *
40    * @param string as String
41    * @return true on success
42    */
 
43  3146 toggle public static boolean isEmpty(final String string) {
44  3146 boolean test = false;
45  3146 if (string == null || string.equals("")) {
46  355 test = true;
47    }
48  3146 return test;
49    }
50   
51    /**
52    * Convert a Hash String to an Integer. Takes each character of the hash
53    * string, convert them to his ASCII number as int and add the result to a
54    * sum.
55    *
56    * @param hash as String
57    * @return hash as integer
58    */
 
59  16 toggle public static int hashToInt(final String hash) {
60  16 int hashNumber = 0;
61  1072 for (int i = 0; i < hash.length(); i++) {
62  1056 char character = hash.charAt(i);
63  1056 int ascii = (int) character;
64  1056 hashNumber += ascii;
65    }
66  16 LOGGER.log("hashToInt() " + hash + " -> " + hashNumber, LogLevel.DEBUG);
67  16 return hashNumber;
68    }
69   
70    /**
71    * Creates a List with Strings entries in a short way. Sample:
72    * List&lt;String&gt; list = new arrayList(); list.add("foo");
73    * list.add("more");
74    * <br> is reduced to stringListBuilder("foo", "more");
75    *
76    * @param strings as String
77    * @return a List of Strings
78    */
 
79  3 toggle public static List<String> stringListBuilder(final String... strings) {
80  3 List<String> list = new ArrayList<>();
81  3 for (String s : strings) {
82  5 if (s != null) {
83  4 list.add(s);
84    }
85    }
86  3 return list;
87    }
88   
89    /**
90    * Create a String from a given ByteArray. Each character get converted to
91    * his UTF-8 hexadecimal expression. e.g. '#' -> "23"
92    *
93    * @param bytes as byteArray
94    * @return bytes as String
95    */
 
96  365 toggle public static String byteToString(final byte[] bytes) {
97  365 StringBuilder sb = new StringBuilder(bytes.length * 2);
98  10434 for (int i = 0; i < bytes.length; ++i) {
99  10069 sb.append(Integer.toHexString(
100    (bytes[i] & Constraints.HEX_255) | Constraints.HEX_256).substring(1, 1 + 2));
101    }
102  365 return sb.toString();
103    }
104   
105    /**
106    * Concatenate a list of Strings using StringBuilder.
107    *
108    * @param strings as String
109    * @return string as String
110    */
 
111  1 toggle public static String concatString(final String... strings) {
112  1 StringBuilder result = new StringBuilder();
113  1 for (String s : strings) {
114  4 result.append(s);
115    }
116  1 return result.toString();
117    }
118   
119    /**
120    * Decode a given URL to a Base64 String.
121    *
122    * @param url as String
123    * @return decodedUrl as String
124    */
 
125  1 toggle public static String base64UrlEncoding(final String url) {
126  1 return Base64.getUrlEncoder().encodeToString(url.getBytes());
127    }
128   
129    /**
130    * Encode from a Base64 back to a readable URL.
131    *
132    * @param base64Url as byte[]
133    * @return encodedUrl as String
134    */
 
135  2 toggle public static String base64UrlDecoding(final String base64Url) {
136  2 String encoded = "";
137  2 try {
138  2 byte[] decodedBytes = Base64.getUrlDecoder().decode(base64Url);
139  1 encoded = new String(decodedBytes, StandardCharsets.UTF_8.toString());
140    } catch (Exception ex) {
141  1 LOGGER.catchException(ex);
142    }
143  2 return encoded;
144    }
145   
146    /**
147    * Escape (decode) in a String all special Characters for XML to thir
148    * equivalent representation. Characters: <, >, &, ', "<br>
149    * This replacement extend the security of a web Application against XSS and
150    * SQL Injections for user modified content.
151    *
152    * @param content as String
153    * @return escapedXml as String
154    */
 
155  1 toggle public static String escapeXmlCharacters(final String content) {
156    //do not change ordering!
157  1 String replace = content.replaceAll("&", "&#0038;");
158  1 replace = replace.replaceAll("<", "&#0060;");
159  1 replace = replace.replaceAll(">", "&#0062;");
160  1 replace = replace.replaceAll("'", "&#0039;");
161  1 replace = replace.replaceAll("\"", "&#0034;");
162  1 return replace;
163    }
164   
165    /**
166    * Produce a lorem ipsum text with 4 paragraphs and 2100 characters. The
167    * parameter chars reduce the output to the given count of characters. To
168    * get the whole text set chars to 0.
169    *
170    * @param chars as int
171    * @return out as String
172    */
 
173  5 toggle public static String generateLoremIpsum(final int chars) {
174  5 String out
175    = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy "
176    + "eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam "
177    + "voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet "
178    + "clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit "
179    + "amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
180    + "nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed "
181    + "diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. "
182    + "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor "
183    + "sitView Generated Project Site amet. Lorem ipsum dolor sit amet, consetetur "
184    + "sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore "
185    + "magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo "
186    + "dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus "
187    + "est Lorem ipsum dolor sit amet.\n"
188    + "\n"
189    + "Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie "
190    + "consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan"
191    + " et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis"
192    + " dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer "
193    + "adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore "
194    + "magna aliquam erat volutpat.\n"
195    + "\n"
196    + "Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit "
197    + "lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure "
198    + "dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore"
199    + " eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim "
200    + "qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla "
201    + "facilisi.\n"
202    + "\n"
203    + "Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet "
204    + "doming id quod mazim placera facer possim assum. Lorem ipsum dolor sit amet, "
205    + "consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut "
206    + "laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis "
207    + "nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea "
208    + "commodo consequat.";
209  5 if (chars > 0 && chars <= LIMIT) {
210  1 out = out.substring(0, chars);
211    }
212  5 return out;
213    }
214   
215    /**
216    * Creates a String of specified length with the content of numbers.
217    * generateStringOfLength(13) = [0123456789012]
218    *
219    * @param length as int
220    * @return string as String
221    */
 
222  2 toggle public static String generateStringOfLength(final int length) {
223  2 StringBuilder sb = new StringBuilder(length);
224  2 int counter = 0;
225  25 for (int i = 0; i < length; ++i) {
226  23 sb.append(counter);
227  23 counter++;
228  23 if (counter > LIMES) {
229  1 counter = 0;
230    }
231    }
232  2 return sb.toString();
233    }
234   
235    /**
236    * Generates an universally unique identifier (UUID). The UUID is a type 4
237    * (pseudo randomly generated) UUID. The UUID is generated using a
238    * cryptographically strong pseudo random number generator.
239    *
240    * @return UUID as String
241    */
 
242  2208 toggle public static String generateUUID() {
243  2208 UUID uuid = UUID.randomUUID();
244  2208 LOGGER.log("generateUUID() " + uuid, LogLevel.DEBUG);
245  2208 return uuid.toString();
246    }
247   
248    /**
249    * Shrink XML, JS and CSS Files to reduce the payload for network traffic.
250    * The shrinker removes comments and unnecessary whitespace and line breaks.
251    *
252    * @param content as String
253    * @return shrinked content as String
254    */
 
255  4 toggle public static String shrink(final String content) {
256    //Comments
257  4 String shrink = content
258    .replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)", "");
259  4 shrink = shrink.replaceAll("(?s)<!--.*?-->", "");
260    //whitespace
261  4 shrink = shrink.replaceAll("\\s+", " ");
262  4 shrink = shrink.replaceAll(" ", " ");
263  4 shrink = shrink.replaceAll(">.*?<", "><");
264  4 return shrink;
265    }
266   
267    /**
268    * Detect and remove the (BOM) Byte Order Mark from a string.
269    *
270    * @param content as String
271    * @return utf-8 String
272    */
 
273  8 toggle public static String skipBom(final String content) {
274  7 if (content.isEmpty()) {
275  1 throw new NullPointerException("The String in StringUtils.skipBom() is null.");
276    }
277  6 List<ByteOrderMark> bomList = new ArrayList<>();
278  6 bomList.add(ByteOrderMark.UTF_8);
279  6 bomList.add(ByteOrderMark.UTF_16LE);
280  6 bomList.add(ByteOrderMark.UTF_16BE);
281  6 bomList.add(ByteOrderMark.UTF_32LE);
282  6 bomList.add(ByteOrderMark.UTF_32BE);
283  6 String clean = content;
284  6 byte[] array = content.getBytes(CHARSET);
285  6 for (ByteOrderMark entry : bomList) {
286  18 boolean hasBOM = true;
287  29 for (int i = 0; i < entry.getBytes().length; i++) {
288  26 byte[] s = {array[i]};
289  26 byte[] d = {entry.getBytes()[i]};
290  26 LOGGER.log(i + "> " + byteToString(s) + " : " + byteToString(d),
291    LogLevel.TRACE);
292   
293  26 if (array[i] != entry.getBytes()[i]) {
294  15 hasBOM = false;
295  15 break;
296    }
297    }
298   
299  18 if (hasBOM) {
300  3 clean = content.substring(1);
301  3 LOGGER.log("BOM: " + entry.toString() + " detected and removed.",
302    LogLevel.DEBUG);
303  3 break;
304    } else {
305  15 LOGGER.log("No BOM detected for: " + entry.toString(), LogLevel.DEBUG);
306    }
307    }
308  6 return clean;
309    }
310   
311    /**
312    * Create from a given String for UTC in the format of yyyy-mm-dd HH:mm:ss a
313    * java.util.Date class.
314    *
315    * @param timestamp as Sting
316    * @return timestamp as Date
317    * @throws java.text.ParseException
318    */
 
319  2 toggle public static Date createDateFromString(final String timestamp)
320    throws ParseException {
321  2 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
322  2 return dateFormat.parse(timestamp);
323    }
324    }