Utilities

Allgemeine Java Utilities:

Diese Klasse beinhaltet allgemeine Utilities die nicht in den anderen Utilities zusammengefasst werden konnten

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
package de.soderer.utilities;

import java.awt.Desktop;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.swt.program.Program;

/**
 * Global Utilities
 *
 * This class does no Logging via Log4J, because it is often used before its initialisation
 */

public class Utilities {
  public static final String STANDARD_XML = "<?xml version=\"1.0\" encoding=\"<encoding>\" standalone=\"yes\"?>\n<root>\n</root>\n";
  public static final String STANDARD_HTML = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\t<head>\n\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=<encoding>\" />\n\t\t<title>HtmlTitle</title>\n\t\t<meta name=\"Title\" content=\"HtmlTitle\" />\n\t</head>\n\t<body>\n\t</body>\n</html>\n";
  public static final String STANDARD_BASHSCRIPTSTART = "#!/bin/bash\n";

  public static final byte[] UTF_16_LE_BOM = new byte[] { (byte)0xFF, (byte)0xFE };
  public static final byte[] UTF_16_BE_BOM = new byte[] { (byte)0xFE, (byte)0xFF };
  public static final byte[] UTF_8_BOM = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };

  /**
   * Generate a unique ID
   *
   * @return
   */

  public static String generateUUID() {
    return UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
  }

  /**
   * Get a UUID from a string
   *
   * @param value
   * @return
   */

  public static UUID getUUIDFromString(String value) {
    StringBuilder uuidString = new StringBuilder(value);
    uuidString.insert(20, '-');
    uuidString.insert(16, '-');
    uuidString.insert(12, '-');
    uuidString.insert(8, '-');
    return UUID.fromString(uuidString.toString());
  }

  /**
   * Find a file using the ClassLoader
   *
   * @param resourceName
   * @return
   */

  public static URI getResource(String resourceName) {
    try {
      URL url = Utilities.class.getResource("/" + resourceName);
      if (url != null) {
        return url.toURI();
      } else {
        return null;
      }
    } catch (Exception e) {
      System.out.println("Looking for Resource '" + resourceName + "' on the classpath root");
      System.out.println(e.getClass().getName() + ": " + e.getMessage());
      System.err.println(e.getClass().getName() + ": " + e.getMessage());
      return null;
    }
  }

  /**
   * Get the data of a file included in a jar file
   *
   * @param resourceName
   * @return
   */

  public static InputStream getResourceAsStream(String resourceName) {
    return Utilities.class.getResourceAsStream("/" + resourceName);
  }

  /**
   * Decode a URL encoded string
   *
   * @param decode
   * @return
   * @throws Exception
   */

  public static String decodeURL(String decode) throws Exception {
    try {
      return URLDecoder.decode(decode, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
      throw new Exception("Fehler in der URL-Decodierung", e);
    }
  }

  /**
   * Encode data in a zipped base64 string data
   *
   * @param clearArrayToEncode
   * @return
   */

  public static byte[] encodeToZippedBase64(byte[] clearArrayToEncode) {
    try {
      ByteArrayOutputStream encoded = new ByteArrayOutputStream();

      GZIPOutputStream gzipCompresser = new GZIPOutputStream(encoded);
      gzipCompresser.write(clearArrayToEncode);
      gzipCompresser.close();

      return Base64.encodeBase64(encoded.toByteArray());
    } catch (IOException e) {
      return null;
    }
  }

  /**
   * Decode data from a zipped base64 string data
   *
   * @param zipedArrayToDecode
   * @return
   * @throws Exception
   */

  public static byte[] decodeFromZippedBase64(byte[] zipedArrayToDecode) throws Exception {
    return unzipByteArray(Base64.decodeBase64(zipedArrayToDecode));
  }

  /**
   * Unzip byteArray by GZIP-Algorithm
   *
   * @param zippedData
   * @return unzippedData
   * @throws Exception
   */

  public static byte[] unzipByteArray(byte[] zippedData) throws Exception {
    try {
      ByteArrayOutputStream decoded = new ByteArrayOutputStream();
      ByteArrayInputStream encoded = new ByteArrayInputStream(zippedData);
      IOUtils.copy(new GZIPInputStream(encoded), decoded);
      return decoded.toByteArray();
    } catch (IOException e) {
      throw new Exception("Komprimierte Daten konnten nicht entpackt werden", e);
    }
  }

  /**
   * Get the duration between two timestamps as a string
   *
   * @param startTime
   * @param endTime
   * @return
   */

  public static String getDuration(Calendar startTime, Calendar endTime) {
    int durationInMilliSeconds = (int)(endTime.getTimeInMillis() - startTime.getTimeInMillis());
    int milliSecondsPart = durationInMilliSeconds % 1000;
    int secondsPart = durationInMilliSeconds / 1000 % 60;
    int minutesPart = durationInMilliSeconds / 1000 / 60 % 60;
    int hoursPart = durationInMilliSeconds / 1000 / 60 / 60 % 24;
    int days = durationInMilliSeconds / 1000 / 60 / 60 % 24;

    String returnString = milliSecondsPart + "ms";
    if (secondsPart > 0) {
      returnString = secondsPart + "s " + returnString;
    }
    if (minutesPart > 0) {
      returnString = minutesPart + "m " + returnString;
    }
    if (hoursPart > 0) {
      returnString = hoursPart + "h " + returnString;
    }
    if (days > 0) {
      returnString = days + "d " + returnString;
    }
    return returnString;
  }

  /**
   * Read a directory and return all files starting with a basename form a list of basenames
   *
   * @param basenameList
   * @return
   */

  public static ArrayList<File> getArrayOfFilesByStammname(String basenameList) {
    return getArrayOfFilesByStammname(Arrays.asList(basenameList.split(";")));
  }

  /**
   * Read a directory and return all files starting with a basename form a list of basenames
   *
   * @param stammNamenListe
   * @return
   */

  public static ArrayList<File> getArrayOfFilesByStammname(List<String> stammNamenListe) {
    ArrayList<File> ergebnisListe = new ArrayList<File>();

    for (String stammName : stammNamenListe) {
      // Suchverzeichnis und Dateistammname ermitteln
      // Achtung: stammName kann auch wildcards wie '*' enthalten daher
      // NICHT mit File-Class arbeiten
      int unixLastIndexOfSeparator = stammName.lastIndexOf("/");
      int dosLastIndexOfSeparator = stammName.lastIndexOf("\\");
      int lastIndexOfSeparator = Math.max(unixLastIndexOfSeparator, dosLastIndexOfSeparator);
      String suchVerzeichnis = stammName.substring(0, lastIndexOfSeparator + 1);
      String stammFileName = stammName.substring(lastIndexOfSeparator + 1);

      // Dateiliste erstellen
      File searchPath = new File(suchVerzeichnis);
      if (searchPath.isDirectory()) {
        File[] partList = searchPath.listFiles();
        for (int i = 0; i < partList.length; i++) {
          if (partList[i].isFile()
              && (stammFileName.endsWith("*") && partList[i].getName().startsWith(stammFileName.substring(0, stammFileName.length() - 1)) || !stammFileName.endsWith("*")
                  && partList[i].getName().equals(stammFileName))) {
            // Datei gefunden: partList[i].getName());
            if (!ergebnisListe.contains(partList[i])) {
              ergebnisListe.add(partList[i]);
            }
          }
        }
      }
    }

    return ergebnisListe;
  }

  /**
   * Read a directory and return all files fitting to a regex pattern
   *
   * @param startDirectory
   * @param patternString
   * @param traverseCompletely
   * @return
   */

  public static List<File> getFilesByPattern(File startDirectory, String patternString, boolean traverseCompletely) {
    return getFilesByPattern(startDirectory, Pattern.compile(patternString), traverseCompletely);
  }

  /**
   * Read a directory and return all files fitting to a regex pattern
   *
   * @param startDirectory
   * @param pattern
   * @param traverseCompletely
   * @return
   */

  public static List<File> getFilesByPattern(File startDirectory, Pattern pattern, boolean traverseCompletely) {
    List<File> files = new ArrayList<File>();
    if (startDirectory.isDirectory()) {
      for (File file : startDirectory.listFiles()) {
        if (file.isDirectory() && traverseCompletely) {
          files.addAll(getFilesByPattern(file, pattern, traverseCompletely));
        } else if (file.isFile() && pattern.matcher(file.getName()).matches()) {
          files.add(file);
        }
      }
    }
    return files;
  }

  /**
   * Read a directory and return all files fitting to a wildcard pattern
   *
   * @param startDirectory
   * @param fileFilterWithWildcards
   * @param traverseCompletely
   * @return
   */

  public static List<File> getFilesWithWildcards(File startDirectory, String fileFilterWithWildcards, boolean traverseCompletely) {
    List<File> files = new ArrayList<File>();
    if (startDirectory.isDirectory()) {
      FileFilter fileFilter = new WildcardFileFilter(fileFilterWithWildcards);
      for (File file : startDirectory.listFiles(fileFilter)) {
        if (file.isFile()) {
          files.add(file);
        }
      }

      if (traverseCompletely) {
        for (File file : startDirectory.listFiles()) {
          if (file.isDirectory()) {
            files.addAll(getFilesWithWildcards(file, fileFilterWithWildcards, traverseCompletely));
          }
        }
      }
    }
    return files;
  }

  /**
   * Check a simple name string
   *
   * @param value
   * @return
   */

  public static boolean checkForValidUserName(String value) {
    return value != null && value.matches("[A-Za-z0-9_-]*");
  }

  /**
   * Convert an ArrayList of Strings to a StringArray
   *
   * @param pArrayListOfStrings
   * @return
   */

  public static String[] convertArrayListOfStringsToStringArray(ArrayList<String> pArrayListOfStrings) {
    String[] arrayofStrings = new String[0];
    return pArrayListOfStrings.toArray(arrayofStrings);
  }

  /**
   * Get index of an Integer within an Array of Integers
   *
   * @param searchInt
   * @param intArray
   * @return
   */

  public static int getIndex(int searchInt, int[] intArray) {
    for (int i = 0; i < intArray.length; i++) {
      if (intArray[i] == searchInt) {
        return i;
      }
    }
    return -1;
  }

  /**
   * Read a stream into a string
   */

  public static String inputStreamToString(InputStream in, String encoding) throws IOException {
    BufferedReader bufferedReader = null;
    try {
      bufferedReader = new BufferedReader(new InputStreamReader(in, encoding));
      StringBuffer stringBuilder = new StringBuffer();
      String line = null;

      while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line + "\n");
      }

      return stringBuilder.toString();
    } finally {
      if (bufferedReader != null) {
        bufferedReader.close();
        bufferedReader = null;
      }
    }
  }

  /**
   * Use a string as inputStream
   *
   * @throws UnsupportedEncodingException
   */

  public static InputStream stringToInputStream(String valueString) throws UnsupportedEncodingException {
    return new ByteArrayInputStream(valueString.getBytes("UTF-8"));
  }

  /**
   * Read all stream data in byteArray
   *
   * @param inputStream
   * @return
   * @throws Exception
   */

  public static byte[] readStreamInArray(InputStream inputStream) throws Exception {
    // Wenn keine Daten aus dem Stream gelesen werden konnten
    // Wird mehrfach diese Thread-Wartezeit eingeräumt
    final int WAIT_TIME = 50;

    // Maximale Anzahl von Wartezyklen mit WAIT_TIME
    // Danach wird eine Exception geworfen
    final int MAX_WAIT_COUNT = 2000;

    ByteArrayOutputStream returnArrayBuffer = null;
    byte[] Buff = new byte[4096];
    int readBlockCount = 0;
    int waitCycleCount = 0;

    try {
      // Anlegen des Writers mit der Groesse des Streams
      returnArrayBuffer = new ByteArrayOutputStream();

      // In pContentLen sollte eigentlich immer die max. Laenge des
      // Streams stehen
      // Ende des Lesens ist, wenn genau diese Anzahl Bytes aus dem Stream
      // ausgelesen werden konnte
      // Das Lesen erfolgt in Bloecken zu max. 4096 Byte Laenge
      while (readBlockCount > -1) {
        try {
          readBlockCount = inputStream.read(Buff);

          if (readBlockCount > -1) {
            // Übergabe der Daten an den Writer
            for (int i = 0; i < readBlockCount; i++) {
              returnArrayBuffer.write((char)Buff[i]);
            }
            waitCycleCount = 0;
          } else if (readBlockCount < 0) {
            // Es wurden alle Daten gelesen
            continue;
          }
        } catch (SocketTimeoutException ex) {
          Thread.sleep(WAIT_TIME);
          waitCycleCount++;
        }

        // Prüfen ob max. Wartzeit ueberschritten?
        if (waitCycleCount > MAX_WAIT_COUNT) {
          throw new Exception("Fehler in readStreamInArray WaitExceed");
        }
      }
    } catch (InterruptedException ex) {
      // Wird von der Methode "Sleep" geworfen
      throw new Exception("Interrupted-Fehler in readStreamInArray: " + ex.getMessage(), ex);
    } catch (IOException ex) {
      throw new Exception("IO-Fehler in readStreamInArray: " + ex.getMessage(), ex);
    } catch (Exception ex) {
      throw new Exception("Fehler in readStreamInArray: " + ex.getMessage(), ex);
    } finally {
      IOUtils.closeQuietly(returnArrayBuffer);
    }

    return returnArrayBuffer.toByteArray();
  }

  /**
   * Read available stream data in byteArray
   *
   * @param inputStream
   * @return
   * @throws Exception
   */

  public static byte[] readAvailableDataFromStreamInArray(InputStream inputStream) throws Exception {
    byte[] returnData = new byte[inputStream.available()];
    @SuppressWarnings("unused")
    int bytesRead = inputStream.read(returnData);
    return returnData;
  }

  /**
   * Read stream data in byteArray until next linefeed or stream end
   *
   * @param inStream
   * @return
   * @throws IOException
   */

  public static byte[] readStreamUntilEndOrLinefeed(InputStream inStream) throws IOException {
    ByteArrayOutputStream returnData = new ByteArrayOutputStream();
    int nextByte;
    while (true) {
      nextByte = inStream.read();
      if (nextByte < 0) {
        break;
      } else if (nextByte == '\n') {
        returnData.write(nextByte);
        break;
      } else {
        returnData.write(nextByte);
      }
    }
    return returnData.toByteArray();
  }

  /**
   * Compare 2 VersionStrings (e.g.: 4.1.03 > 4.1.2)
   *
   * @param version1
   * @param version2
   * @return -1 if Version1 < Version2<br>
   *         0 if Version1 = Version2<br>
   *         +1 if Version1 > Version2<br>
   */

  public static int compareVersion(String version1, String version2) {
    String[] versionparts1 = version1.split("\\.");
    String[] versionparts2 = version2.split("\\.");
    for (int i = 0; i < Math.min(versionparts1.length, versionparts1.length); i++) {
      int value1 = 0;
      if (versionparts1.length > i) {
        value1 = Integer.parseInt(versionparts1[i]);
      }
      int value2 = 0;
      if (versionparts2.length > i) {
        value2 = Integer.parseInt(versionparts2[i]);
      }
      if (value1 < value2) {
        return -1;
      } else if (value1 > value2) {
        return 1;
      }
    }
    return 0;
  }

  /**
   * Get email from X509Certificate
   *
   * @param cert
   * @return
   */

  public static String getEmailFromCertificate(X509Certificate cert) {
    String[] nameParts = cert.getSubjectX500Principal().toString().split(",");
    for (String namePart : nameParts) {
      if (namePart.matches("^[ \\t]*EMAILADDRESS=.*")) {
        return namePart.substring(namePart.indexOf("=") + 1).trim();
      }
    }

    return null;
  }

  /**
   * Get cn from X509Certificate
   *
   * @param cert
   * @return
   */

  public static String getCnFromCertificate(X509Certificate cert) {
    String[] nameParts = cert.getSubjectX500Principal().toString().split(",");
    for (String namePart : nameParts) {
      if (namePart.matches("^[ \\t]*CN=.*")) {
        return namePart.substring(namePart.indexOf("=") + 1).trim();
      }
    }

    return null;
  }

  /**
   * Check if a day is included in a list of days
   *
   * @param listOfDays
   * @param day
   * @return
   */

  public static boolean dayListIncludes(List<GregorianCalendar> listOfDays, GregorianCalendar day) {
    for (GregorianCalendar listDay : listOfDays) {
      if (listDay.get(Calendar.DAY_OF_YEAR) == day.get(Calendar.DAY_OF_YEAR)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Ermitteln des nächsten geplanten Startzeitpunktes Der Timingparameter kann Wochentage, Zeiten, Monats-, Quartalsplanungen und Feiertage enthalten
   *
   * Mögliche Ausprägungen: "ONCE" => nur einmalig (returns null) "0600;0800" => täglich um 06:00 und um 08:00 "MoMi:1700" => Montags und Mittwochs um 17:00 "M05:1600" => jeden 05.ten im Monat um
   * 16:00 "Q:1600" => Jeden ersten Tag im Quartal um 16:00 "QW:1600" => Jeden ersten Werktag im Quartal um 16:00 "MoDiMiDoFr:1700;!23012011" => Mo bis Fr um 17:00 aber nicht am 23.01.2011
   * (Feiertagsregelung durch '!'-Zeichen)
   *
   * Alle Ausprägungen können beliebig kombiniert werden, werden dann durch Semikolons getrennt aufgelistet
   *
   * @param timingString
   * @return
   * @throws Exception
   */

  public static Timestamp calculateNextJobStart(String timingString) {
    GregorianCalendar now = new GregorianCalendar();
    GregorianCalendar returnStart = new GregorianCalendar();
    returnStart.add(GregorianCalendar.YEAR, 1);

    // Feiertage die explizit ausgeschlossen werden
    List<GregorianCalendar> excludedDays = new ArrayList<GregorianCalendar>();

    if (timingString.equalsIgnoreCase("once")) {
      return null;
    }

    String[] timingParameterList = timingString.split(";");
    for (String timingParameter : timingParameterList) {
      if (timingParameter.startsWith("!")) {
        try {
          GregorianCalendar exclusionDate = new GregorianCalendar();
          exclusionDate.setTime(DateUtils.DDMMYYYY.parse(timingParameter.substring(1)));
          excludedDays.add(exclusionDate);
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }
    }

    for (String timingParameter : timingParameterList) {
      GregorianCalendar nextStartByThisParameter = new GregorianCalendar();
      nextStartByThisParameter.setTime(now.getTime());

      if (timingParameter.startsWith("!")) {
        // Exclusionen wurden bereits verarbeitet
        continue;
      } else if (!timingParameter.contains(":")) {
        if (isNumber(timingParameter)) {
          // tägliche Verarbeitung zur gegebenen Uhrzeit
          nextStartByThisParameter.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(timingParameter.substring(0, 2)));
          nextStartByThisParameter.set(GregorianCalendar.MINUTE, Integer.parseInt(timingParameter.substring(2)));
          nextStartByThisParameter.set(GregorianCalendar.SECOND, 0);
          nextStartByThisParameter.set(GregorianCalendar.MILLISECOND, 0);

          // nächsten Start solange in die Zukunft verschieben (+1Tag)
          // bis
          // Parameter-Bedingung erfüllt ist
          // Bei treffender Feiertagseintragung auch um einen Tag
          // weiterschieben
          while (nextStartByThisParameter.before(now) && nextStartByThisParameter.before(returnStart) || dayListIncludes(excludedDays, nextStartByThisParameter)) {
            nextStartByThisParameter.add(GregorianCalendar.DAY_OF_MONTH, 1);
          }
        } else {
          // wochentägliche Verarbeitung um 00:00 Uhr
          List<Integer> weekdayIndexes = new ArrayList<Integer>();
          for (String weekDay : TextUtilities.chopToChunks(timingParameter, 2)) {
            weekdayIndexes.add(DateUtils.getWeekdayIndex(weekDay));
          }
          nextStartByThisParameter.set(GregorianCalendar.HOUR_OF_DAY, 0);
          nextStartByThisParameter.set(GregorianCalendar.MINUTE, 0);
          nextStartByThisParameter.set(GregorianCalendar.SECOND, 0);
          nextStartByThisParameter.set(GregorianCalendar.MILLISECOND, 0);

          // nächsten Start solange in die Zukunft verschieben (+1Tag)
          // bis
          // Parameter-Bedingung erfüllt ist
          // Bei treffender Feiertagseintragung auch um einen Tag
          // weiterschieben
          while ((nextStartByThisParameter.before(now) || !weekdayIndexes.contains(nextStartByThisParameter.get(Calendar.DAY_OF_WEEK))) && nextStartByThisParameter.before(returnStart)
              || dayListIncludes(excludedDays, nextStartByThisParameter)) {
            nextStartByThisParameter.add(GregorianCalendar.DAY_OF_MONTH, 1);
          }
        }
      } else if (timingParameter.length() == 8) {
        // Monatssteuerung "M01:1700"
        String tag = timingParameter.substring(1, timingParameter.indexOf(":"));
        String zeit = timingParameter.substring(timingParameter.indexOf(":") + 1);
        nextStartByThisParameter.set(GregorianCalendar.DAY_OF_MONTH, Integer.parseInt(tag));
        nextStartByThisParameter.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(zeit.substring(0, 2)));
        nextStartByThisParameter.set(GregorianCalendar.MINUTE, Integer.parseInt(zeit.substring(2)));
        nextStartByThisParameter.set(GregorianCalendar.SECOND, 0);
        nextStartByThisParameter.set(GregorianCalendar.MILLISECOND, 0);

        // Den nächsten passenden Monat finden
        while (nextStartByThisParameter.before(now) && nextStartByThisParameter.before(returnStart)) {
          nextStartByThisParameter.add(GregorianCalendar.MONTH, 1);
        }

        // Bei treffender Feiertagseintragung um einen Tag
        // weiterschieben
        while (dayListIncludes(excludedDays, nextStartByThisParameter)) {
          nextStartByThisParameter.add(GregorianCalendar.DAY_OF_YEAR, 1);
        }
      } else if (timingParameter.startsWith("Q:")) {
        // Quartalsweise Planung (Q:1200): Start am ersten Kalendertag
        // im Quartal
        if (nextStartByThisParameter.get(GregorianCalendar.MONTH) < GregorianCalendar.APRIL) {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.APRIL);
        } else if (nextStartByThisParameter.get(GregorianCalendar.MONTH) < GregorianCalendar.JULY) {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.JULY);
        } else if (nextStartByThisParameter.get(GregorianCalendar.MONTH) < GregorianCalendar.OCTOBER) {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.OCTOBER);
        } else {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.JANUARY);
          nextStartByThisParameter.add(GregorianCalendar.YEAR, 1);
        }

        nextStartByThisParameter.set(GregorianCalendar.DAY_OF_MONTH, 1);
        String zeit = timingParameter.substring(timingParameter.indexOf(":") + 1);
        nextStartByThisParameter.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(zeit.substring(0, 2)));
        nextStartByThisParameter.set(GregorianCalendar.MINUTE, Integer.parseInt(zeit.substring(2)));
        nextStartByThisParameter.set(GregorianCalendar.SECOND, 0);
        nextStartByThisParameter.set(GregorianCalendar.MILLISECOND, 0);

        // Bei treffender Feiertagseintragung um einen Tag
        // weiterschieben
        while (dayListIncludes(excludedDays, nextStartByThisParameter)) {
          nextStartByThisParameter.add(GregorianCalendar.DAY_OF_YEAR, 1);
        }
      } else if (timingParameter.startsWith("QW:")) {
        // Quartalsweise Planung (QW:1200): Start am ersten Werktag im
        // Quartal
        if (nextStartByThisParameter.get(GregorianCalendar.MONTH) < GregorianCalendar.APRIL) {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.APRIL);
        } else if (nextStartByThisParameter.get(GregorianCalendar.MONTH) < GregorianCalendar.JULY) {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.JULY);
        } else if (nextStartByThisParameter.get(GregorianCalendar.MONTH) < GregorianCalendar.OCTOBER) {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.OCTOBER);
        } else {
          nextStartByThisParameter.set(GregorianCalendar.MONTH, GregorianCalendar.JANUARY);
          nextStartByThisParameter.add(GregorianCalendar.YEAR, 1);
        }

        nextStartByThisParameter.set(GregorianCalendar.DAY_OF_MONTH, 1);

        // Bei treffender Feiertagseintragung oder Wochentagsregelung um
        // einen Tag weiterschieben
        while (nextStartByThisParameter.get(GregorianCalendar.DAY_OF_WEEK) == java.util.Calendar.SATURDAY
            || nextStartByThisParameter.get(GregorianCalendar.DAY_OF_WEEK) == java.util.Calendar.SUNDAY || dayListIncludes(excludedDays, nextStartByThisParameter)) {
          nextStartByThisParameter.add(GregorianCalendar.DAY_OF_MONTH, 1);
        }

        String zeit = timingParameter.substring(timingParameter.indexOf(":") + 1);
        nextStartByThisParameter.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(zeit.substring(0, 2)));
        nextStartByThisParameter.set(GregorianCalendar.MINUTE, Integer.parseInt(zeit.substring(2)));
        nextStartByThisParameter.set(GregorianCalendar.SECOND, 0);
        nextStartByThisParameter.set(GregorianCalendar.MILLISECOND, 0);
      } else {
        // WochenTagessteuerung (ermöglicht auch Werktagssteuerung)
        String wochenTage = timingParameter.substring(0, timingParameter.indexOf(":"));
        String zeit = timingParameter.substring(timingParameter.indexOf(":") + 1);
        List<Integer> weekdayIndexes = new ArrayList<Integer>();
        for (String weekDay : TextUtilities.chopToChunks(wochenTage, 2)) {
          weekdayIndexes.add(DateUtils.getWeekdayIndex(weekDay));
        }
        nextStartByThisParameter.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(zeit.substring(0, 2)));
        nextStartByThisParameter.set(GregorianCalendar.MINUTE, Integer.parseInt(zeit.substring(2)));
        nextStartByThisParameter.set(GregorianCalendar.SECOND, 0);
        nextStartByThisParameter.set(GregorianCalendar.MILLISECOND, 0);

        // nächsten Start solange in die Zukunft verschieben (+1Tag) bis
        // Parameter-Bedingung erfüllt ist
        // Bei treffender Feiertagseintragung auch um einen Tag
        // weiterschieben
        while ((nextStartByThisParameter.before(now) || !weekdayIndexes.contains(nextStartByThisParameter.get(Calendar.DAY_OF_WEEK))) && nextStartByThisParameter.before(returnStart)
            || dayListIncludes(excludedDays, nextStartByThisParameter)) {
          nextStartByThisParameter.add(GregorianCalendar.DAY_OF_MONTH, 1);
        }
      }

      if (nextStartByThisParameter.before(returnStart)) {
        returnStart = nextStartByThisParameter;
      }
    }

    return new Timestamp(returnStart.getTimeInMillis());
  }

  /**
   * Parse a version string like 4.3.2
   *
   * @param versionString
   * @return
   */

  public static int[] parseVersionNumber(String versionString) {
    try {
      Pattern versionPattern = Pattern.compile("^(\\d+)(?:\\.(\\d+)){0,1}(?:\\.(\\d+)){0,1}$");
      Matcher matcher = versionPattern.matcher(versionString);
      if (!matcher.find() || matcher.groupCount() < 1 || matcher.groupCount() > 3) {
        throw new IllegalArgumentException("Version must be in form <major>[.<minor>[.<micro>]]");
      }

      int major = new Integer(matcher.group(1));
      int minor = 0;
      if (matcher.groupCount() >= 2 && matcher.group(2) != null) {
        minor = new Integer(matcher.group(2));
      }
      int micro = 0;
      if (matcher.groupCount() == 3 && matcher.group(3) != null) {
        micro = new Integer(matcher.group(3));
      }

      return new int[] { major, minor, micro };
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("Version must contain integervalues only");
    }
  }

  /**
   * Check for a number
   *
   * @param value
   * @return
   */

  public static boolean isNumber(String value) {
    try {
      Integer.parseInt(value);
      return true;
    } catch (NumberFormatException e) {
      return false;
    }
  }

  /**
   * Remove the time part of a GregorianCalendar
   *
   * @param value
   * @return
   */

  public static GregorianCalendar getDayWithoutTime(GregorianCalendar value) {
    return new GregorianCalendar(value.get(GregorianCalendar.YEAR), value.get(GregorianCalendar.MONTH), value.get(GregorianCalendar.DAY_OF_MONTH));
  }

  /***
   * Split a list into smaller lists to a maximum chunkSize
   *
   * @param originalList
   * @param chunkSize
   * @return
   */

  public static <E> List<List<E>> chopListToChunks(List<E> originalList, int chunkSize) {
    if (originalList == null || originalList.size() <= 0 || chunkSize <= 0) {
      return null;
    }

    List<List<E>> returnList = new ArrayList<List<E>>();
    int endIndex = 0;

    while (endIndex < originalList.size()) {
      int startIndex = endIndex;
      if (chunkSize < originalList.size() - endIndex) {
        endIndex += chunkSize;
      } else {
        endIndex = originalList.size();
      }

      returnList.add(originalList.subList(startIndex, endIndex));
    }

    return returnList;
  }

  /**
   * List of characters for randomization
   */

  private static final char[] randomCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöüß".toCharArray();

  /**
   * List of numbers and strings for randomization
   */

  private static final char[] randomAlphaNumericCharacters = (new String(randomCharacters) + "0123456789").toCharArray();

  /**
   * Random generator
   */

  private static final Random random = new SecureRandom();

  /**
   * Generate a random number up to maximum value
   *
   * @param excludedMaximum
   * @return
   */

  public static int getRandomNumber(int excludedMaximum) {
    return random.nextInt(excludedMaximum);
  }

  /**
   * Generate a random string of given size
   *
   * @param length
   * @return
   */

  public static String getRandomString(int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      sb.append(randomCharacters[random.nextInt(randomCharacters.length)]);
    }
    return sb.toString();
  }

  /**
   * Generate a random string of numbers and characters of given size
   *
   * @param length
   * @return
   */

  public static String getRandomAlphanumericString(int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      sb.append(randomAlphaNumericCharacters[random.nextInt(randomAlphaNumericCharacters.length)]);
    }
    return sb.toString();
  }

  /**
   * Generate a random number of given size
   *
   * @param length
   * @return
   */

  public static String getRandomNumberString(int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++) {
      sb.append(random.nextInt(10));
    }
    return sb.toString();
  }

  /**
   * Generate a random byte
   *
   * @return
   */

  public static byte getRandomByte() {
    byte[] result = new byte[1];
    random.nextBytes(result);
    return result[0];
  }

  /**
   * Generate a random byteArray
   *
   * @param arrayToFill
   * @return
   */

  public static byte[] getRandomByteArray(byte[] arrayToFill) {
    random.nextBytes(arrayToFill);
    return arrayToFill;
  }

  /**
   * Get hostname of this machine
   *
   * @return
   */

  public static String getHostName() {
    try {
      return InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      return "unbekannter Rechnername";
    }
  }

  /**
   * Convert a collection to a string like Stringutils.join, but keep null values as "<null>" string
   *
   * @param collection
   * @param separator
   * @return
   */

  public static String convertCollectionToString(Collection<?> collection, String separator) {
    StringBuilder builder = new StringBuilder();

    for (Object object : collection) {
      if (builder.length() > 0) {
        builder.append(separator);
      }
      if (object == null) {
        builder.append("<null>");
      } else {
        builder.append(object.toString());
      }
    }

    return builder.toString();
  }

  /**
   * Check if a Integer is contained by an interval definition
   * Interval definitions like -1;2-5;8+
   *
   * @param intervals
   * @param item
   * @return
   */

  public static boolean checkForIntervalContainment(String intervals, int item) {
    if (intervals != null && intervals.length() > 0) {
      String[] blockStrings = intervals.split(";");
      for (int i = 0; i < blockStrings.length; i++) {
        if (blockStrings[i].endsWith("+")) {
          if (Integer.parseInt(blockStrings[i].substring(0, blockStrings[i].length() - 1)) <= item) {
            return true;
          }
        } else if (blockStrings[i].matches("\\d+-\\d+")) {
          int plusIndex = blockStrings[i].indexOf("-");
          int startVersion = Integer.parseInt(blockStrings[i].substring(0, plusIndex));
          int endeVersion = Integer.parseInt(blockStrings[i].substring(plusIndex + 1));
          if (startVersion <= item && endeVersion >= item) {
            return true;
          }
        } else if (blockStrings[i].matches("-\\d+")) {
          int endeVersion = Integer.parseInt(blockStrings[i].substring(1));
          if (endeVersion >= item) {
            return true;
          }
        } else {
          if (Integer.parseInt(blockStrings[i]) == item) {
            return true;
          }
        }
      }
    }

    return false;
  }

  /**
   * Read a directory and return all files fitting namestart and extension
   *
   * @param directory
   * @param nameStart
   * @param extension
   * @return
   */

  public static File[] getSubfilesByNameAndExtension(File directory, String nameStart, String extension) {
    List<File> files = new LinkedList<File>();
    for (File file : directory.listFiles()) {
      if (file.getName().startsWith(nameStart) && file.getName().endsWith("." + extension)) {
        files.add(file);
      }
    }
    return files.toArray(new File[0]);
  }

  /**
   * Get all recursive subfiles of a directory
   *
   * @param directory
   * @return
   * @throws Exception
   */

  public static List<File> getAllSubfiles(File directory) throws Exception {
    try {
      List<File> files = new LinkedList<File>();
      File[] subFiles = directory.listFiles();
      if (subFiles != null) {
        for (File file : subFiles) {
          if (file.isDirectory()) {
            files.addAll(getAllSubfiles(file));
          } else {
            files.add(file);
          }
        }
      }
      return files;
    } catch (DoNotWrapException e) {
      throw e;
    } catch (Exception e) {
      throw new DoNotWrapException("Error reading subfiles of: " + directory.getAbsolutePath(), e);
    }
  }

  /**
   * Get number of all recursive subfiles of a directory
   *
   * @param directory
   * @return
   * @throws Exception
   */

  public static int getAllSubfilesNumber(File directory) throws Exception {
    try {
      int fileCount = 0;
      File[] subFiles = directory.listFiles();
      if (subFiles != null) {
        for (File file : subFiles) {
          if (file.isDirectory()) {
            fileCount += getAllSubfilesNumber(file);
          } else {
            fileCount++;
          }
        }
      }
      return fileCount;
    } catch (DoNotWrapException e) {
      throw e;
    } catch (Exception e) {
      throw new DoNotWrapException("Error reading subfilenumber of: " + directory.getAbsolutePath(), e);
    }
  }

  /**
   * Get size in bytes of all recursive subfiles of a directory
   *
   * @param directory
   * @return
   * @throws Exception
   */

  public static long getAllSubfilesSize(File directory) throws Exception {
    try {
      long fileSizeSum = 0;
      File[] subFiles = directory.listFiles();
      if (subFiles != null) {
        for (File file : subFiles) {
          if (file.isDirectory()) {
            fileSizeSum += getAllSubfilesSize(file);
          } else {
            fileSizeSum += file.length();
          }
        }
      }
      return fileSizeSum;
    } catch (DoNotWrapException e) {
      throw e;
    } catch (Exception e) {
      throw new DoNotWrapException("Error reading subfilesize of: " + directory.getAbsolutePath(), e);
    }
  }

  /**
   * Delete all subfiles fitting namestart and extension
   *
   * @param directory
   * @param nameStart
   * @param extension
   */

  public static void deleteSubfilesByNameAndExtension(File directory, String nameStart, String extension) {
    for (File file : getSubfilesByNameAndExtension(directory, nameStart, extension)) {
      FileUtils.deleteQuietly(file);
    }
  }

  /**
   * Get the minimum of a value list down to a valid minimum
   *
   * @param allowedValueMinimum
   * @param values
   * @return
   */

  public static int getMinimumOfAllowedValues(int allowedValueMinimum, int... values) {
    int returnValue = Integer.MAX_VALUE;
    if (values != null) {
      for (int value : values) {
        if (value >= allowedValueMinimum) {
          returnValue = Math.min(returnValue, value);
        }
      }
    }
    return returnValue;
  }

  /**
   * Convert a string to boolean
   *
   * @param value
   * @return
   */

  public static boolean interpretAsBool(String value) {
    if (StringUtils.isNotEmpty(value)) {
      value = value.trim();
      return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("+") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("ja") || value.equalsIgnoreCase("ok") || value.equalsIgnoreCase("on") || value.equalsIgnoreCase("an");
    } else {
      return false;
    }
  }

  /**
   * Check if any characters in a list are equal
   *
   * @param values
   * @return
   */

  public static boolean anyCharsAreEqual(char... values) {
    for (int i = 0; i < values.length; i++) {
      for (int j = i + 1; j < values.length; j++) {
        if (values[i] == values[j]) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Math.square
   *
   * @param value
   * @return
   */

  public static int square(int value) {
    return value * value;
  }

  /**
   * Math power
   *
   * @param base
   * @param exp
   * @return
   */

  public static int pow(int base, int exp) {
    if (exp < 0) {
      throw new IllegalArgumentException("Invalid negative exponent");
    } else if (exp == 0) {
      return 1;
    } else {
      return square(pow(base, exp / 2)) * (exp % 2 == 1 ? base : 1);
    }
  }
  
  /**
   * Get number of lines of a textfile
   *
   * @param file
   * @return
   * @throws IOException
   */

  public static int getLineCount(File file) throws IOException {
    LineNumberReader lineNumberReader = null;
    try {
      lineNumberReader = new LineNumberReader(new InputStreamReader(new FileInputStream(file)));
      while (lineNumberReader.readLine() != null) {
        // do nothing
      }

      return lineNumberReader.getLineNumber();
    } finally {
      IOUtils.closeQuietly(lineNumberReader);
    }
  }

  /**
   * Get a collection like a set as a ordered list
   * @param c
   * @return
   */

  public static <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
    List<T> list = new ArrayList<T>(c);
    java.util.Collections.sort(list);
    return list;
  }

  /**
   * Search textfile for string
   *
   * @param searchFile
   * @param searchText
   * @param searchCaseSensitive
   * @param searchTextIsRegularExpression
   * @param defaultEncoding
   * @return
   * @throws Exception
   */

  public static boolean fileSearchText(File searchFile, String searchText, boolean searchCaseSensitive, boolean searchTextIsRegularExpression, String defaultEncoding) throws Exception {
    List<String> searchTexts = new ArrayList<String>();
    searchTexts.add(searchText);
    return fileSearchText(searchFile, searchTexts, searchCaseSensitive, searchTextIsRegularExpression, defaultEncoding);
  }

  /**
   * Search textfile for string
   *
   * @param searchFile
   * @param searchTexts
   * @param searchCaseSensitive
   * @param searchTextIsRegularExpression
   * @param defaultEncoding
   * @return
   * @throws Exception
   */

  public static boolean fileSearchText(File searchFile, List<String> searchTexts, boolean searchCaseSensitive, boolean searchTextIsRegularExpression, String defaultEncoding) throws Exception {
    FileInputStream fileInputStream = null;
    try {
      if (searchFile.length() > 0 && searchTexts != null && searchTexts.size() > 0) {
        byte[] encodingBuffer = Utilities.readFirstFileData(searchFile, 100);
        Tuple<String, Boolean> encodingData = TextUtilities.detectEncoding(encodingBuffer);
        if (encodingData == null) {
          encodingData = TextFilePropertiesReader.getEncodingData(defaultEncoding);
        }

        fileInputStream = new FileInputStream(searchFile);
        String dataString = IOUtils.toString(fileInputStream, encodingData.getFirst());

        for (int i = 0; i < searchTexts.size(); i++) {
          Pattern searchPattern;
          if (searchTextIsRegularExpression) {
            if (searchCaseSensitive) {
              searchPattern = Pattern.compile(searchTexts.get(i));
            } else {
              searchPattern = Pattern.compile(searchTexts.get(i), Pattern.CASE_INSENSITIVE);
            }
          } else {
            if (searchCaseSensitive) {
              searchPattern = Pattern.compile(searchTexts.get(i), Pattern.LITERAL);
            } else {
              searchPattern = Pattern.compile(searchTexts.get(i), Pattern.CASE_INSENSITIVE | Pattern.LITERAL);
            }
          }
          Matcher matcher = searchPattern.matcher(dataString);
          if (matcher.find()) {
            return true;
          }
        }
      }
      return false;
    } finally {
      IOUtils.closeQuietly(fileInputStream);
    }
  }

  /**
   * Replace string in textfile
   *
   * @param searchFile
   * @param searchText
   * @param replacementText
   * @param searchCaseSensitive
   * @param searchTextIsRegularExpression
   * @param defaultEncoding
   * @return
   * @throws Exception
   */

  public static boolean fileReplaceText(File searchFile, String searchText, String replacementText, boolean searchCaseSensitive, boolean searchTextIsRegularExpression, String defaultEncoding) throws Exception {
    List<String> searchTexts = new ArrayList<String>();
    searchTexts.add(searchText);
    List<String> replacementTexts = new ArrayList<String>();
    replacementTexts.add(replacementText);
    return fileReplaceText(searchFile, searchTexts, replacementTexts, searchCaseSensitive, searchTextIsRegularExpression, defaultEncoding);
  }

  /**
   * Replace strings in textfile
   *
   * @param searchFile
   * @param searchTexts
   * @param replacementTexts
   * @param searchCaseSensitive
   * @param searchTextIsRegularExpression
   * @param defaultEncoding
   * @return
   * @throws Exception
   */

  public static boolean fileReplaceText(File searchFile, List<String> searchTexts, List<String> replacementTexts, boolean searchCaseSensitive, boolean searchTextIsRegularExpression, String defaultEncoding) throws Exception {
    FileInputStream fileInputStream = null;
    try {
      boolean foundAndReplaced = false;
      if (searchFile.length() > 0 && searchTexts != null && searchTexts.size() > 0 && replacementTexts != null && replacementTexts.size() > 0) {
        byte[] encodingBuffer = Utilities.readFirstFileData(searchFile, 100);
        Tuple<String, Boolean> encodingData = TextUtilities.detectEncoding(encodingBuffer);
        if (encodingData == null) {
          encodingData = TextFilePropertiesReader.getEncodingData(defaultEncoding);
        }

        fileInputStream = new FileInputStream(searchFile);
        String dataString = IOUtils.toString(fileInputStream, encodingData.getFirst());

        for (int i = 0; i < searchTexts.size(); i++) {
          Pattern searchPattern;
          if (searchTextIsRegularExpression) {
            if (searchCaseSensitive) {
              searchPattern = Pattern.compile(searchTexts.get(i), Pattern.MULTILINE);
            } else {
              searchPattern = Pattern.compile(searchTexts.get(i), Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
            }
          } else {
            if (searchCaseSensitive) {
              searchPattern = Pattern.compile(searchTexts.get(i), Pattern.MULTILINE | Pattern.LITERAL);
            } else {
              searchPattern = Pattern.compile(searchTexts.get(i), Pattern.MULTILINE | Pattern.CASE_INSENSITIVE | Pattern.LITERAL);
            }
          }
          Matcher matcher = searchPattern.matcher(dataString);
          if (matcher.find()) {
            dataString = matcher.replaceAll(replacementTexts.get(i));
            foundAndReplaced = true;
          }
        }

        if (foundAndReplaced) {
          FileUtils.writeStringToFile(searchFile, dataString, encodingData.getFirst());
        }
      }
      return foundAndReplaced;
    } finally {
      IOUtils.closeQuietly(fileInputStream);
    }
  }

  /**
   * Get files of classpath
   *
   * @return
   */

  public static String getClassPath() {
    ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();

    StringBuilder classpath = new StringBuilder();
    for (int i = 0; i < urls.length; i++) {
      classpath.append(urls[i].getFile() + "\n");
    }
    return classpath.toString();
  }

  /**
   * Check bytearrays equality
   *
   * @param byteArray1
   * @param byteArray2
   * @return
   */

  public static boolean compare(byte[] byteArray1, byte[] byteArray2) {
    if (byteArray1 == byteArray2) {
      return true;
    } else if (byteArray1 == null || byteArray2 == null || byteArray1.length != byteArray2.length) {
      return false;
    } else {
      for (int i = 0; i < byteArray1.length; i++) {
        if (byteArray1[i] != byteArray2[i]) {
          return false;
        }
      }
      return true;
    }
  }

  /**
   * Read first n bytes of binary file
   *
   * @param dataFile
   * @param maxAmountToRead
   * @return
   * @throws Exception
   */

  public static byte[] readFirstFileData(File dataFile, int maxAmountToRead) throws Exception {
    FileInputStream input = null;
    try {
      input = new FileInputStream(dataFile);
      byte[] encodingBufferInterim = new byte[maxAmountToRead];
      int bytesRead = input.read(encodingBufferInterim);
      byte[] encodingBuffer = ArrayUtils.subarray(encodingBufferInterim, 0, bytesRead);
      return encodingBuffer;
    } catch (Exception e) {
      throw e;
    } finally {
      IOUtils.closeQuietly(input);
    }
  }

  /**
   * Get all system properties
   *
   * @return
   */

  public static Map<String, String> getSystemPropertiesMap() {
    Map<String, String> propertiesMap = new HashMap<String, String>();
    for (Object key : System.getProperties().keySet()) {
      propertiesMap.put((String)key, System.getProperties().getProperty((String)key));
    }
    return propertiesMap;
  }

  /**
   * Convert Map to String
   *
   * @param map
   * @param entrySeparator
   * @param keySeparator
   * @param sort
   * @return
   */

  public static String getStringFromMap(Map<String, ? extends Object> map, String entrySeparator, String keySeparator, boolean sort) {
    List<String> keyList = new ArrayList<String>(map.keySet());
    if (sort) {
      Collections.sort(keyList);
    }

    StringBuilder builder = new StringBuilder();
    for (Object key : keyList) {
      if (builder.length() > 0) {
        builder.append(entrySeparator);
      }
      builder.append(key == null ? "" : key);
      builder.append(keySeparator);
      Object value = map.get(key);
      builder.append(value == null ? "" : value.toString());
    }
    return builder.toString();
  }

  /**
   * Make a number human readable
   *
   * @param value
   * @return
   */

  public static String getHumanReadableNumber(Number value) {
    return getHumanReadableNumber(value, null, true);
  }

  /**
   * Make a number with unitsign human readable
   *
   * @param value
   * @param unitTypeSign
   * @return
   */

  public static String getHumanReadableNumber(Number value, String unitTypeSign) {
    return getHumanReadableNumber(value, unitTypeSign, true);
  }

  /**
   * Make a number with unitsign human readable
   *
   * @param value
   * @param unitTypeSign
   * @param siUnits
   * @return
   */

  public static String getHumanReadableNumber(Number value, String unitTypeSign, boolean siUnits) {
    int unit = siUnits ? 1000 : 1024;
    double interimValue = value.doubleValue();
    String unitExtension = "";
    if (interimValue < unit) {
      if (StringUtils.isNotBlank(unitTypeSign)) {
        unitExtension = " " + unitTypeSign;
      }

      if (value instanceof Integer || value instanceof Long) {
        return value + unitExtension;
      }
    } else {
      int exp = (int)(Math.log(interimValue) / Math.log(unit));
      unitExtension = " " + (siUnits ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (siUnits ? "" : "i");
      if (StringUtils.isNotBlank(unitTypeSign)) {
        unitExtension += unitTypeSign;
      }
      interimValue = interimValue / Math.pow(unit, exp);
    }

    String valueString;
    if (interimValue >= 1000) {
      valueString = String.format("%.1f", interimValue);
    } else if (interimValue >= 100) {
      valueString = String.format("%.2f", interimValue);
    } else if (interimValue >= 10) {
      valueString = String.format("%.3f", interimValue);
    } else if (interimValue >= 1) {
      valueString = String.format("%.4f", interimValue);
    } else {
      valueString = String.format("%.5f", interimValue);
    }

    return valueString + unitExtension;
  }

  /**
   * Generate MD5 from string data
   *
   * @param data
   * @return
   * @throws Exception
   */

  public static byte[] getMD5Hash(String data) throws Exception {
    try {
      return MessageDigest.getInstance("MD5").digest(data.getBytes("UTF-8"));
    } catch (Exception e) {
      throw new Exception("Error while MD5 hashing", e);
    }
  }

  /**
   * Generate SHA-1 from string data
   *
   * @param data
   * @return
   * @throws Exception
   */

  public static byte[] getSHA1Hash(String data) throws Exception {
    try {
      return MessageDigest.getInstance("SHA-1").digest(data.getBytes("UTF-8"));
    } catch (Exception e) {
      throw new Exception("Error while SHA-1 hashing", e);
    }
  }

  /**
   * Generate SHA-512 from string data
   *
   * @param data
   * @return
   * @throws Exception
   */

  public static byte[] getSHA512Hash(String data) throws Exception {
    try {
      return MessageDigest.getInstance("SHA-512").digest(data.getBytes("UTF-8"));
    } catch (Exception e) {
      throw new Exception("Error while SHA-512 hashing", e);
    }
  }

  /**
   * Get bytearray for list of bytes
   *
   * @param data
   * @return
   */

  public static byte[] getByteArray(List<Byte> data) {
    byte[] returnArray = new byte[data.size()];
    for (int i = 0; i < data.size(); i++) {
      returnArray[i] = data.get(i);
    }
    return returnArray;
  }

  /**
   * Get stacktrace as string
   *
   * @param stackTrace
   * @return
   */

  public static String stacktraceToString(StackTraceElement[] stackTrace) {
    StringBuilder returnBuilder = new StringBuilder();
    if (stackTrace != null) {
      for (StackTraceElement stackTraceElement : stackTrace) {
        returnBuilder.append(stackTraceElement.toString());
        returnBuilder.append("\n");
      }
    }
    return returnBuilder.toString();
  }

  /**
   * Send an email
   *
   * @param senderAdress
   * @param toAdressList
   * @param ccAdressList
   * @param subject
   * @param bodyText
   * @param bodyHtml
   * @param mailtype
   * @param charset
   * @return
   */

  public static boolean sendEmail(String senderAdress, String toAdressList, String ccAdressList, String subject, String bodyText, String bodyHtml, int mailtype, String charset) {
    try {
      // create some properties and get the default Session
      Properties props = new Properties();
      props.put("system.mail.host", "localhost");
      Session session = Session.getDefaultInstance(props, null);
      // session.setDebug(debug);

      // create a message
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(senderAdress));
      msg.setSubject(subject, charset);
      msg.setSentDate(new Date());

      // Set to-recipient email addresses
      InternetAddress[] toAddresses = getEmailAddressesFromList(toAdressList);
      if (toAddresses != null && toAddresses.length > 0) {
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
      }

      // Set cc-recipient email addresses
      InternetAddress[] ccAddresses = getEmailAddressesFromList(ccAdressList);
      if (ccAddresses != null && ccAddresses.length > 0) {
        msg.setRecipients(Message.RecipientType.CC, ccAddresses);
      }

      switch (mailtype) {
        case 0:
          msg.setText(bodyText, charset);
          break;
        case 1:
          Multipart mp = new MimeMultipart("alternative");
          MimeBodyPart mbp = new MimeBodyPart();
          mbp.setText(bodyText, charset);
          mp.addBodyPart(mbp);
          mbp = new MimeBodyPart();
          mbp.setContent(bodyHtml, "text/html; charset=" + charset);
          mp.addBodyPart(mbp);
          msg.setContent(mp);
          break;
        default:
          msg.setText(bodyText, charset);
          break;
      }

      Transport.send(msg);
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }

  /**
   * Get emails from string list
   *
   * @param listString
   * @return
   */

  public static InternetAddress[] getEmailAddressesFromList(String listString) {
    if (StringUtils.isNotBlank(listString)) {
      List<InternetAddress> emailAddresses = new ArrayList<InternetAddress>();
      for (String singleAdr : listString.split(";|,| ")) {
        singleAdr = singleAdr.trim();
        if (StringUtils.isNotBlank(singleAdr)) {
          try {
            InternetAddress nextAddress = new InternetAddress(singleAdr.trim());
            nextAddress.validate();
            emailAddresses.add(nextAddress);
          } catch (AddressException e) {
            e.printStackTrace();
          }
        }
      }

      return emailAddresses.toArray(new InternetAddress[emailAddresses.size()]);
    } else {
      return new InternetAddress[0];
    }
  }

  /**
   * Try to open en email in the standard email client
   *
   * @param toAdress
   * @param subject
   * @param body
   * @return
   */

  public static boolean openMailInStandardClient(String toAdress, String subject, String body) {
    return openMailInStandardClient(toAdress, null, subject, body);
  }

  /**
   * Try to open en email in the standard email client
   *
   * @param toAdress
   * @param ccAdress
   * @param subject
   * @param body
   * @return
   */

  public static boolean openMailInStandardClient(String toAdress, String ccAdress, String subject, String body) {
    try {
      File attachmentFile = null;
      String mailtoString = "mailto:" + URLEncoder.encode(toAdress, "UTF-8") + "?" + (StringUtils.isNotBlank(ccAdress) ? "cc=" + URLEncoder.encode(ccAdress, "UTF-8") + "&" : "") + "subject="
          + URLEncoder.encode(subject, "UTF-8").replace("+", "%20") + "&body=" + URLEncoder.encode(body, "UTF-8").replace("+", "%20")
          + (attachmentFile != null ? "&attachment=" + attachmentFile.getAbsolutePath() : ""); // maybe it is "&attach="
      boolean success;
      try {
        success = Program.launch(mailtoString);
      } catch (Exception e) {
        throw new Exception("Open mail by swt.Program failed");
      }

      if (!success) {
        if (SystemUtilities.isWindowsSystem()) {
          if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.MAIL)) {
              desktop.mail(new URI(mailtoString));
              return true;
            } else {
              return false;
            }
          } else {
            return false;
          }
        } else {
          try {
            // For using the parameters check the following description
            // http://kb.mozillazine.org/Command_line_arguments_%28Thunderbird%29
            Runtime.getRuntime().exec("thunderbird -compose");
            success = Program.launch(mailtoString);
          } catch (Exception e) {
            throw new Exception("Open mail by thunderbird failed");
          }
        }
        return true;
      } else {
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * Download a file from url
   *
   * @param url
   * @param localeDestionationPath
   * @throws Exception
   */

  public static void downloadFile(String url, String localeDestionationPath) throws Exception {
    BufferedInputStream bufferedInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
      bufferedInputStream = new BufferedInputStream(new URL(url).openStream());
      fileOutputStream = new FileOutputStream(localeDestionationPath);
      IOUtils.copy(bufferedInputStream, fileOutputStream);
    } catch (Exception e) {
      throw new Exception("Cannot download file", e);
    } finally {
      IOUtils.closeQuietly(fileOutputStream);
      IOUtils.closeQuietly(bufferedInputStream);
    }
  }

  /**
   * Check array for duplicate strings
   *
   * @param inputArray
   * @param ignoreNullValues
   * @return
   */

  public static boolean checkForDuplicates(String[] inputArray, boolean ignoreNullValues) {
    Set<String> tempSet = new HashSet<String>();
    for (String stringItem : inputArray) {
      if (!ignoreNullValues || stringItem != null) {
        if (!tempSet.add(stringItem)) {
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Filter all Objects of given class
   *
   * @param collection
   * @param classToSelect
   * @return
   */

  @SuppressWarnings("unchecked")
  public static <T> List<T> selectItems(Collection<?> collection, Class<T> classToSelect) {
    List<T> list = new ArrayList<T>();
    for (Object item : collection) {
      if (classToSelect.isInstance(item)) {
        list.add((T)item);
      }
    }
    return list;
  }

  /**
   * Filter all Objects of given class
   *
   * @param array
   * @param classToSelect
   * @return
   */

  @SuppressWarnings("unchecked")
  public static <T> List<T> selectItems(Object[] array, Class<T> classToSelect) {
    List<T> list = new ArrayList<T>();
    for (Object item : array) {
      if (classToSelect.isInstance(item)) {
        list.add((T)item);
      }
    }
    return list;
  }
}