1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package edu.internet2.middleware.grouperInstaller.util;
20
21 import java.io.BufferedInputStream;
22 import java.io.BufferedOutputStream;
23 import java.io.BufferedReader;
24 import java.io.File;
25 import java.io.FileFilter;
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.io.OutputStream;
33 import java.io.PrintWriter;
34 import java.io.PushbackInputStream;
35 import java.io.Reader;
36 import java.io.StringWriter;
37 import java.io.UnsupportedEncodingException;
38 import java.io.Writer;
39 import java.lang.annotation.Annotation;
40 import java.lang.reflect.Array;
41 import java.lang.reflect.Constructor;
42 import java.lang.reflect.Field;
43 import java.lang.reflect.InvocationTargetException;
44 import java.lang.reflect.Method;
45 import java.lang.reflect.Modifier;
46 import java.math.BigDecimal;
47 import java.net.InetAddress;
48 import java.net.ServerSocket;
49 import java.net.URL;
50 import java.net.URLClassLoader;
51 import java.net.URLDecoder;
52 import java.net.URLEncoder;
53 import java.security.CodeSource;
54 import java.security.MessageDigest;
55 import java.sql.Connection;
56 import java.sql.ResultSet;
57 import java.sql.SQLException;
58 import java.sql.Statement;
59 import java.sql.Timestamp;
60 import java.text.DateFormat;
61 import java.text.DecimalFormat;
62 import java.text.ParseException;
63 import java.text.SimpleDateFormat;
64 import java.util.ArrayList;
65 import java.util.Arrays;
66 import java.util.Calendar;
67 import java.util.Collection;
68 import java.util.Collections;
69 import java.util.Date;
70 import java.util.HashMap;
71 import java.util.HashSet;
72 import java.util.Iterator;
73 import java.util.LinkedHashMap;
74 import java.util.LinkedHashSet;
75 import java.util.List;
76 import java.util.Map;
77 import java.util.Properties;
78 import java.util.Set;
79 import java.util.concurrent.ExecutorService;
80 import java.util.concurrent.Executors;
81 import java.util.jar.Attributes;
82 import java.util.jar.Attributes.Name;
83 import java.util.jar.JarInputStream;
84 import java.util.jar.Manifest;
85 import java.util.logging.ConsoleHandler;
86 import java.util.logging.FileHandler;
87 import java.util.logging.Handler;
88 import java.util.logging.Level;
89 import java.util.logging.Logger;
90 import java.util.logging.SimpleFormatter;
91 import java.util.regex.Matcher;
92 import java.util.regex.Pattern;
93 import java.util.zip.GZIPOutputStream;
94 import java.util.zip.ZipFile;
95
96 import javax.xml.parsers.DocumentBuilder;
97 import javax.xml.parsers.DocumentBuilderFactory;
98 import javax.xml.parsers.ParserConfigurationException;
99 import javax.xml.transform.Transformer;
100 import javax.xml.transform.TransformerFactory;
101 import javax.xml.transform.dom.DOMSource;
102 import javax.xml.transform.stream.StreamResult;
103 import javax.xml.xpath.XPath;
104 import javax.xml.xpath.XPathConstants;
105 import javax.xml.xpath.XPathExpression;
106 import javax.xml.xpath.XPathFactory;
107
108 import org.w3c.dom.Document;
109 import org.w3c.dom.NamedNodeMap;
110 import org.w3c.dom.Node;
111 import org.w3c.dom.NodeList;
112
113 import edu.internet2.middleware.grouperInstaller.GiGrouperVersion;
114 import edu.internet2.middleware.grouperInstallerExt.org.apache.commons.compress.archivers.tar.TarArchiveEntry;
115 import edu.internet2.middleware.grouperInstallerExt.org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
116 import edu.internet2.middleware.grouperInstallerExt.org.apache.commons.httpclient.HttpMethodBase;
117 import edu.internet2.middleware.grouperInstallerExt.org.apache.commons.logging.Log;
118 import edu.internet2.middleware.grouperInstallerExt.org.apache.commons.logging.LogFactory;
119 import edu.internet2.middleware.grouperInstallerExt.org.apache.commons.logging.impl.Jdk14Logger;
120
121
122
123
124
125
126
127
128 @SuppressWarnings({ "serial", "unchecked" })
129 public class GrouperInstallerUtils {
130
131
132
133
134
135 public static void main(String[] args) {
136 tar(new File("C:\\app\\grouperInstallerTarballDir\\grouper_v2_2_1_ui_patch_17"),
137 new File("C:\\app\\grouperInstallerTarballDir\\grouper_v2_2_1_ui_patch_17.tar"));
138
139 }
140
141
142
143
144
145
146 public static boolean fileDelete(File file) {
147 if (!file.exists()) {
148 return false;
149 }
150 if (!file.delete()) {
151 throw new RuntimeException("Couldnt delete file: " + file);
152 }
153 return true;
154 }
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170 public static boolean deleteQuietly(File file) {
171 if (file == null) {
172 return false;
173 }
174
175 try {
176 return file.delete();
177 } catch (Exception e) {
178 return false;
179 }
180 }
181
182
183
184
185
186
187 public static void fileMove(File file, File newFile) {
188 fileMove(file, newFile, true);
189 }
190
191
192
193
194
195
196
197
198 public static boolean fileMove(File file, File newFile, boolean exceptionIfError) {
199 fileDelete(newFile);
200 if (!file.renameTo(newFile)) {
201 copyFile( file, newFile );
202 if (!file.delete()) {
203 if (!exceptionIfError) {
204 return false;
205 }
206 deleteQuietly(newFile);
207 throw new RuntimeException("Could not native Java rename, and failed to delete original file '" + file +
208 "' after copy to '" + newFile + "'");
209 }
210 }
211 return true;
212 }
213
214
215 private static ThreadLocal<Map<String, Map<String, String>>> propertiesThreadLocalOverrideMap = new ThreadLocal<Map<String, Map<String, String>>>();
216
217
218
219
220
221
222
223
224 public static String argAfter(String[] args, String argBefore) {
225 if (length(args) <= 1) {
226 return null;
227 }
228 int argBeforeIndex = -1;
229 for (int i=0;i<args.length;i++) {
230 if (equals(args[i], argBefore)) {
231 argBeforeIndex = i;
232 break;
233 }
234 }
235 if (argBeforeIndex == -1) {
236 throw new RuntimeException("Cant find arg before");
237 }
238 if (argBeforeIndex < args.length - 1) {
239 return args[argBeforeIndex + 1];
240 }
241 return null;
242 }
243
244
245
246
247
248
249
250 public static void append(StringBuilder result,
251 String separatorIfResultNotEmpty, String stringToAppend) {
252 if (result.length() != 0) {
253 result.append(separatorIfResultNotEmpty);
254 }
255 result.append(stringToAppend);
256 }
257
258
259
260
261 public static final String LOG_ERROR = "Error trying to make parent dirs for logger or logging first statement, check to make " +
262 "sure you have proper file permissions, and that your servlet container is giving " +
263 "your app rights to access the log directory (e.g. for tomcat set TOMCAT5_SECURITY=no), g" +
264 "oogle it for more info";
265
266
267
268
269 public static final long ONE_KB = 1024;
270
271
272
273
274 public static final long ONE_MB = ONE_KB * ONE_KB;
275
276
277
278
279 public static final long ONE_GB = ONE_KB * ONE_MB;
280
281
282
283
284
285
286
287
288
289 public static String byteCountToDisplaySize(long size) {
290 String displaySize;
291
292 if (size / ONE_GB > 0) {
293 displaySize = String.valueOf(size / ONE_GB) + " GB";
294 } else if (size / ONE_MB > 0) {
295 displaySize = String.valueOf(size / ONE_MB) + " MB";
296 } else if (size / ONE_KB > 0) {
297 displaySize = String.valueOf(size / ONE_KB) + " KB";
298 } else {
299 displaySize = String.valueOf(size) + " bytes";
300 }
301
302 return displaySize;
303 }
304
305
306
307
308
309
310 public static boolean hasOption(int options, int option) {
311 return (options & option) > 0;
312 }
313
314
315
316
317
318
319 public static String fileCanonicalPath(File file) {
320 try {
321 return file.getCanonicalPath();
322 } catch (IOException ioe) {
323 throw new RuntimeException(ioe);
324 }
325 }
326
327
328
329
330
331
332
333 public static String suffixAfterChar(String input, char theChar) {
334 if (input == null) {
335 return null;
336 }
337
338 int lastIndex = input.lastIndexOf(theChar);
339 if (lastIndex > -1) {
340 input = input.substring(lastIndex + 1, input.length());
341 }
342 return input;
343 }
344
345
346
347
348
349
350
351
352
353 public static String oracleStandardNameFromJava(String javaName) {
354
355 StringBuilder result = new StringBuilder();
356
357 if ((javaName == null) || (0 == "".compareTo(javaName))) {
358 return javaName;
359 }
360
361
362 javaName = suffixAfterChar(javaName, '.');
363
364
365 result.append(javaName.charAt(0));
366
367 char currChar;
368
369 boolean previousCap = false;
370
371
372 for (int i = 1; i < javaName.length(); i++) {
373 currChar = javaName.charAt(i);
374
375
376 if (!previousCap && (currChar >= 'A') && (currChar <= 'Z')) {
377 result.append("_");
378 }
379
380 result.append(currChar);
381 if ((currChar >= 'A') && (currChar <= 'Z')) {
382 previousCap = true;
383 } else {
384 previousCap = false;
385 }
386 }
387
388
389 return result.toString().toUpperCase();
390 }
391
392
393
394
395
396
397
398
399
400
401
402 public static <K,V> boolean mapEquals(Map<K,V> first, Map<K,V> second) {
403 Set<K> keysMismatch = new HashSet<K>();
404 mapDifferences(first, second, keysMismatch, null);
405
406 return keysMismatch.size() == 0;
407
408 }
409
410
411
412
413 private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap());
414
415
416
417
418
419
420
421
422
423
424
425 @SuppressWarnings("unchecked")
426 public static <K,V> void mapDifferences(Map<K,V> first, Map<K,V> second, Set<K> differences, String prefix) {
427 if (first == second) {
428 return;
429 }
430
431 if (first == null) {
432 first = EMPTY_MAP;
433 }
434 if (second == null) {
435 second = EMPTY_MAP;
436 } else {
437
438 second = new LinkedHashMap<K,V>(second);
439 }
440 int firstSize = first == null ? 0 : first.size();
441 int secondSize = second == null ? 0 : second.size();
442
443 if (firstSize == 0 && secondSize == 0) {
444 return;
445 }
446
447 for (K key : first.keySet()) {
448
449 if (second.containsKey(key)) {
450 V firstValue = first.get(key);
451 V secondValue = second.get(key);
452
453 second.remove(key);
454 if (equals(firstValue, secondValue)) {
455 continue;
456 }
457 }
458 differences.add(isNotBlank(prefix) ? (K)(prefix + key) : key);
459 }
460
461 for (K key : second.keySet()) {
462 differences.add(isNotBlank(prefix) ? (K)(prefix + key) : key);
463 }
464 }
465
466
467
468
469
470 public static void sleep(long millis) {
471 try {
472 Thread.sleep(millis);
473 } catch (InterruptedException ie) {
474 throw new RuntimeException(ie);
475 }
476 }
477
478
479
480
481
482
483
484 public static boolean injectInException(Throwable t, String message) {
485
486 String throwableFieldName = "detailMessage";
487
488 try {
489 String currentValue = t.getMessage();
490 if (!isBlank(currentValue)) {
491 currentValue += ",\n" + message;
492 } else {
493 currentValue = message;
494 }
495 assignField(t, throwableFieldName, currentValue);
496 return true;
497 } catch (Throwable t2) {
498
499 return false;
500 }
501
502 }
503
504
505
506
507
508
509
510
511 public static String uniqueId() {
512
513 synchronized (GrouperInstallerUtils.class) {
514 lastId = incrementStringInt(lastId);
515 }
516
517 return String.valueOf(lastId);
518 }
519
520
521
522
523
524
525
526
527
528 public static File fileFromResourceName(String resourceName) {
529
530 URL url = computeUrl(resourceName, true);
531
532 if (url == null) {
533 return null;
534 }
535
536 try {
537 String fileName = URLDecoder.decode(url.getFile(), "UTF-8");
538
539 File configFile = new File(fileName);
540
541 return configFile;
542 } catch (UnsupportedEncodingException uee) {
543 throw new RuntimeException(uee);
544 }
545 }
546
547
548
549
550
551
552
553
554 public static URL computeUrl(String resourceName, boolean canBeNull) {
555
556 ClassLoader cl = classLoader();
557
558 URL url = null;
559
560 try {
561
562 String newResourceName = resourceName.startsWith("/")
563 ? resourceName.substring(1) : resourceName;
564 url = cl.getResource(newResourceName);
565 } catch (NullPointerException npe) {
566 String error = "computeUrl() Could not find resource file: " + resourceName;
567 throw new RuntimeException(error, npe);
568 }
569
570 if (!canBeNull && url == null) {
571 throw new RuntimeException("Cant find resource: " + resourceName);
572 }
573
574 return url;
575 }
576
577
578
579
580
581
582 public static ClassLoader classLoader() {
583 return GrouperInstallerUtils.class.getClassLoader();
584 }
585
586
587
588
589
590
591
592
593
594 @SuppressWarnings("unchecked")
595 public static <T> T[] nonNull(T[] array, Class<?> theClass) {
596 return array == null ? ((T[])Array.newInstance(theClass, 0)) : array;
597 }
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612 public static String prefixOrSuffix(String startString, String separator,
613 boolean isPrefix) {
614 String prefixOrSuffix = null;
615
616
617 if (startString == null) {
618 return startString;
619 }
620
621
622 int separatorIndex = startString.indexOf(separator);
623
624
625 if (separatorIndex == -1) {
626 return startString;
627 }
628
629
630 int separatorLength = separator.length();
631
632 if (isPrefix) {
633 prefixOrSuffix = startString.substring(0, separatorIndex);
634 } else {
635 prefixOrSuffix = startString.substring(separatorIndex + separatorLength,
636 startString.length());
637 }
638
639 return prefixOrSuffix;
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 public static String indent(String string, boolean failIfTypeNotFound) {
684 if (string == null) {
685 return null;
686 }
687 string = trim(string);
688 if (string.startsWith("<")) {
689
690 return new XmlIndenter(string).result();
691 }
692 if (!failIfTypeNotFound) {
693
694 return string;
695 }
696 throw new RuntimeException("Cant find type of string: " + string);
697
698
699 }
700
701
702
703
704
705
706 public static String extensionFromName(String name) {
707 if (isBlank(name)) {
708 return name;
709 }
710 int lastColonIndex = name.lastIndexOf(':');
711 if (lastColonIndex == -1) {
712 return name;
713 }
714 String extension = name.substring(lastColonIndex+1);
715 return extension;
716 }
717
718
719
720
721
722
723 public static Class forName(String origClassName) {
724
725 try {
726 return Class.forName(origClassName);
727 } catch (Throwable t) {
728 throw new RuntimeException("Problem loading class: " + origClassName, t);
729 }
730
731 }
732
733
734
735
736
737
738
739 public static <T> T newInstance(Class<T> theClass) {
740 try {
741 return theClass.newInstance();
742 } catch (Throwable e) {
743 if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) {
744 throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!", e);
745 }
746 throw new RuntimeException("Problem with class: " + theClass, e);
747 }
748 }
749
750
751
752
753
754
755
756
757 public static String parentStemNameFromName(String name) {
758 int lastColonIndex = name.lastIndexOf(':');
759 if (lastColonIndex == -1) {
760 return null;
761 }
762 String parentStemName = name.substring(0,lastColonIndex);
763 return parentStemName;
764
765 }
766
767
768
769
770
771
772
773 public static String defaultIfBlank(String string, String defaultStringIfBlank) {
774 return isBlank(string) ? defaultStringIfBlank : string;
775 }
776
777
778
779
780
781
782
783
784 public static <T> T defaultIfNull(T theValue, T defaultIfTheValueIsNull) {
785 return theValue != null ? theValue : defaultIfTheValueIsNull;
786 }
787
788
789
790
791
792
793
794 public static <T> void addIfNotThere(Collection<T> list, Collection<T> listToAdd) {
795
796 if (listToAdd == null) {
797 return;
798 }
799 for (T t : listToAdd) {
800 if (!list.contains(t)) {
801 list.add(t);
802 }
803 }
804 }
805
806
807
808
809
810
811
812
813
814
815 @SuppressWarnings("unchecked")
816 private static void toStringForLogHelper(Object object, int maxChars, StringBuilder result) {
817
818 try {
819 if (object == null) {
820 result.append("null");
821 } else if (object.getClass().isArray()) {
822
823 int length = Array.getLength(object);
824 if (length == 0) {
825 result.append("Empty array");
826 } else {
827 result.append("Array size: ").append(length).append(": ");
828 for (int i = 0; i < length; i++) {
829 result.append("[").append(i).append("]: ").append(
830 Array.get(object, i)).append("\n");
831 if (maxChars != -1 && result.length() > maxChars) {
832 return;
833 }
834 }
835 }
836 } else if (object instanceof Collection) {
837
838 Collection<Object> collection = (Collection<Object>) object;
839 int collectionSize = collection.size();
840 if (collectionSize == 0) {
841 result.append("Empty ").append(object.getClass().getSimpleName());
842 } else {
843 result.append(object.getClass().getSimpleName()).append(" size: ").append(collectionSize).append(": ");
844 int i=0;
845 for (Object collectionObject : collection) {
846 result.append("[").append(i).append("]: ").append(
847 collectionObject).append("\n");
848 if (maxChars != -1 && result.length() > maxChars) {
849 return;
850 }
851 i++;
852 }
853 }
854 } else {
855 result.append(object.toString());
856 }
857 } catch (Exception e) {
858 result.append("<<exception>> ").append(object.getClass()).append(":\n")
859 .append(getFullStackTrace(e)).append("\n");
860 }
861 }
862
863
864
865
866
867
868 public static String setToString(Set set) {
869 if (set == null) {
870 return "null";
871 }
872 if (set.size() == 0) {
873 return "empty";
874 }
875 StringBuilder result = new StringBuilder();
876 boolean first = true;
877 for (Object object : set) {
878 if (!first) {
879 result.append(", ");
880 }
881 first = false;
882 result.append(object);
883 }
884 return result.toString();
885 }
886
887
888
889
890
891
892
893 @Deprecated
894 public static String MapToString(Map map) {
895 return mapToString(map);
896 }
897
898
899
900
901
902
903 public static String mapToString(Map map) {
904 if (map == null) {
905 return "null";
906 }
907 if (map.size() == 0) {
908 return "empty";
909 }
910 StringBuilder result = new StringBuilder();
911 boolean first = true;
912 for (Object object : map.keySet()) {
913 if (!first) {
914 result.append(", ");
915 }
916 first = false;
917 result.append(object).append(": ").append(map.get(object));
918 }
919 return result.toString();
920 }
921
922
923
924
925
926
927
928 public static String toStringForLog(Object object) {
929 StringBuilder result = new StringBuilder();
930 toStringForLogHelper(object, -1, result);
931 return result.toString();
932 }
933
934
935
936
937
938
939
940
941 public static String toStringForLog(Object object, int maxChars) {
942 StringBuilder result = new StringBuilder();
943 toStringForLogHelper(object, -1, result);
944 String resultString = result.toString();
945 if (maxChars != -1) {
946 return abbreviate(resultString, maxChars);
947 }
948 return resultString;
949 }
950
951
952
953
954
955
956
957 public static int batchNumberOfBatches(int count, int batchSize) {
958 int batches = 1 + ((count - 1) / batchSize);
959 return batches;
960
961 }
962
963
964
965
966
967
968
969 public static int batchNumberOfBatches(Collection<?> collection, int batchSize) {
970 int arrraySize = length(collection);
971 return batchNumberOfBatches(arrraySize, batchSize);
972
973 }
974
975
976
977
978
979
980
981
982
983
984
985
986 @SuppressWarnings("unchecked")
987 public static <T> List<T> batchList(Collection<T> collection, int batchSize,
988 int batchIndex) {
989
990 int numberOfBatches = batchNumberOfBatches(collection, batchSize);
991 int arraySize = length(collection);
992
993
994 if (arraySize == 0) {
995 return new ArrayList<T>();
996 }
997
998 List<T> theBatchObjects = new ArrayList<T>();
999
1000
1001
1002
1003
1004
1005
1006 if (batchIndex == numberOfBatches - 1) {
1007
1008
1009
1010
1011 int collectionIndex = 0;
1012 for (T t : collection) {
1013 if (collectionIndex++ < batchIndex * batchSize) {
1014 continue;
1015 }
1016
1017
1018
1019
1020
1021 theBatchObjects.add(t);
1022 }
1023
1024 } else {
1025
1026
1027 int collectionIndex = 0;
1028 for (T t : collection) {
1029 if (collectionIndex < batchIndex * batchSize) {
1030 collectionIndex++;
1031 continue;
1032 }
1033
1034 if (collectionIndex >= (batchIndex + 1) * batchSize) {
1035 break;
1036 }
1037 theBatchObjects.add(t);
1038 collectionIndex++;
1039 }
1040 }
1041 return theBatchObjects;
1042 }
1043
1044
1045
1046
1047
1048
1049 public static String trimEnd(String text) {
1050 if (text == null) {
1051 return null;
1052 }
1053
1054 return text.replaceFirst("\\s+$", "");
1055 }
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068 public static String[] splitTrim(String input, String separator) {
1069 return splitTrim(input, separator, true);
1070 }
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083 public static List<String> splitTrimToList(String input, String separator) {
1084 if (isBlank(input)) {
1085 return null;
1086 }
1087 String[] array = splitTrim(input, separator);
1088 return toList(array);
1089 }
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102 public static String[] splitTrim(String input, String separator, boolean treatAdjacentSeparatorsAsOne) {
1103 if (isBlank(input)) {
1104 return null;
1105 }
1106
1107
1108 String[] items = treatAdjacentSeparatorsAsOne ? split(input, separator) :
1109 splitPreserveAllTokens(input, separator);
1110
1111
1112 for (int i = 0; (items != null) && (i < items.length); i++) {
1113 items[i] = trim(items[i]);
1114 }
1115
1116
1117 return items;
1118 }
1119
1120
1121
1122
1123
1124
1125 public static String escapeUrlEncode(String string) {
1126 String result = null;
1127 try {
1128 result = URLEncoder.encode(string, "UTF-8");
1129 } catch (UnsupportedEncodingException ex) {
1130 throw new RuntimeException("UTF-8 not supported", ex);
1131 }
1132 return result;
1133 }
1134
1135
1136
1137
1138
1139
1140 public static String escapeUrlDecode(String string) {
1141 String result = null;
1142 try {
1143 result = URLDecoder.decode(string, "UTF-8");
1144 } catch (UnsupportedEncodingException ex) {
1145 throw new RuntimeException("UTF-8 not supported", ex);
1146 }
1147 return result;
1148 }
1149
1150
1151
1152
1153
1154
1155
1156 public static <T> List<T> nonNull(List<T> list) {
1157 return list == null ? new ArrayList<T>() : list;
1158 }
1159
1160
1161
1162
1163
1164
1165
1166 public static <T> Set<T> nonNull(Set<T> set) {
1167 return set == null ? new HashSet<T>() : set;
1168 }
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178 public static <K,V> Map<K,V> nonNull(Map<K,V> map) {
1179 return map == null ? new HashMap<K,V>() : map;
1180 }
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191 @SuppressWarnings("unchecked")
1192 public static <T> List<T> toList(T... objects) {
1193 if (objects == null) {
1194 return null;
1195 }
1196 if (objects.length == 1 && objects[0] instanceof List) {
1197 return (List<T>)objects[0];
1198 }
1199
1200 List<T> result = new ArrayList<T>();
1201 for (T object : objects) {
1202 result.add(object);
1203 }
1204 return result;
1205 }
1206
1207
1208
1209
1210
1211
1212 public static List<Class<?>> toListClasses(Class<?>... classes) {
1213 return toList(classes);
1214 }
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225 public static <T> Set<T> toSet(T... objects) {
1226
1227 Set<T> result = new LinkedHashSet<T>();
1228 for (T object : objects) {
1229 result.add(object);
1230 }
1231 return result;
1232 }
1233
1234
1235
1236
1237 private static final String CACHE_SEPARATOR = "__";
1238
1239
1240
1241
1242 public static final String DATE_FORMAT = "yyyyMMdd";
1243
1244
1245
1246
1247 public static final String DATE_MINUTES_SECONDS_FORMAT = "yyyy/MM/dd HH:mm:ss";
1248
1249
1250
1251
1252 public static final String DATE_MINUTES_SECONDS_NO_SLASH_FORMAT = "yyyyMMdd HH:mm:ss";
1253
1254
1255
1256
1257 public static final String TIMESTAMP_FORMAT = "yyyy/MM/dd HH:mm:ss.SSS";
1258
1259
1260
1261
1262 public static final String TIMESTAMP_NO_SLASH_FORMAT = "yyyyMMdd HH:mm:ss.SSS";
1263
1264
1265
1266
1267 final static SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
1268
1269
1270
1271
1272 public final static SimpleDateFormat dateMinutesSecondsFormat = new SimpleDateFormat(
1273 DATE_MINUTES_SECONDS_FORMAT);
1274
1275
1276
1277
1278 final static SimpleDateFormat dateMinutesSecondsNoSlashFormat = new SimpleDateFormat(
1279 DATE_MINUTES_SECONDS_NO_SLASH_FORMAT);
1280
1281
1282
1283
1284 final static SimpleDateFormat timestampFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);
1285
1286
1287
1288
1289 final static SimpleDateFormat timestampNoSlashFormat = new SimpleDateFormat(
1290 TIMESTAMP_NO_SLASH_FORMAT);
1291
1292
1293
1294
1295
1296
1297
1298 public static void assertion(boolean isTrue, String reason) {
1299 if (!isTrue) {
1300 throw new RuntimeException(reason);
1301 }
1302
1303 }
1304
1305
1306
1307
1308 private static ExpirableCache<String, Set<Field>> fieldSetCache = null;
1309
1310
1311
1312
1313
1314 private static ExpirableCache<String, Set<Field>> fieldSetCache() {
1315 if (fieldSetCache == null) {
1316 fieldSetCache = new ExpirableCache<String, Set<Field>>(60*24);
1317 }
1318 return fieldSetCache;
1319 }
1320
1321
1322
1323
1324
1325 private static ExpirableCache<Class, Method[]> declaredMethodsCache = null;
1326
1327
1328
1329
1330
1331 private static ExpirableCache<Class, Method[]> declaredMethodsCache() {
1332 if (declaredMethodsCache == null) {
1333 declaredMethodsCache = new ExpirableCache<Class, Method[]>(60*24);
1334 }
1335 return declaredMethodsCache;
1336 }
1337
1338
1339
1340
1341
1342
1343 private static ExpirableCache<String, Set<Method>> getterSetCache = null;
1344
1345
1346
1347
1348
1349
1350 private static ExpirableCache<String, Set<Method>> getterSetCache() {
1351 if (getterSetCache == null) {
1352 getterSetCache = new ExpirableCache<String, Set<Method>>(60*24);
1353 }
1354 return getterSetCache;
1355 }
1356
1357
1358
1359
1360
1361
1362 private static ExpirableCache<String, Set<Method>> setterSetCache = null;
1363
1364
1365
1366
1367
1368
1369 private static ExpirableCache<String, Set<Method>> setterSetCache() {
1370 if (setterSetCache == null) {
1371 setterSetCache = new ExpirableCache<String, Set<Method>>(60*24);
1372 }
1373 return setterSetCache;
1374 }
1375
1376
1377
1378
1379
1380 private static char[] lastId = convertLongToStringSmall(new Date().getTime())
1381 .toCharArray();
1382
1383
1384
1385
1386 private static Map<String, Properties> resourcePropertiesCache = new HashMap<String, Properties>();
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408 public static void assignField(Class theClass, Object invokeOn,
1409 String fieldName, Object dataToAssign, boolean callOnSupers,
1410 boolean overrideSecurity, boolean typeCast,
1411 Class<? extends Annotation> annotationWithValueOverride) {
1412 if (theClass == null && invokeOn != null) {
1413 theClass = invokeOn.getClass();
1414 }
1415 Field field = field(theClass, fieldName, callOnSupers, true);
1416 assignField(field, invokeOn, dataToAssign, overrideSecurity, typeCast,
1417 annotationWithValueOverride);
1418 }
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435 public static void assignField(Class theClass, Object invokeOn,
1436 String fieldName, Object dataToAssign,
1437 Class<? extends Annotation> annotationWithValueOverride) {
1438 assignField(theClass, invokeOn, fieldName, dataToAssign, true, true,
1439 true, annotationWithValueOverride);
1440 }
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456 @SuppressWarnings("unchecked")
1457 public static void assignField(Field field, Object invokeOn,
1458 Object dataToAssign, boolean overrideSecurity, boolean typeCast) {
1459
1460 try {
1461 Class fieldType = field.getType();
1462
1463 if (typeCast) {
1464 dataToAssign =
1465 typeCast(dataToAssign, fieldType,
1466 true, true);
1467 }
1468 if (overrideSecurity) {
1469 field.setAccessible(true);
1470 }
1471 field.set(invokeOn, dataToAssign);
1472 } catch (Exception e) {
1473 throw new RuntimeException("Cant assign reflection field: "
1474 + (field == null ? null : field.getName()) + ", on: "
1475 + className(invokeOn) + ", with args: "
1476 + classNameCollection(dataToAssign), e);
1477 }
1478 }
1479
1480
1481
1482
1483
1484
1485
1486 public static Iterator iterator(Object collection) {
1487 if (collection == null) {
1488 return null;
1489 }
1490
1491 if (collection instanceof Collection
1492 && !(collection instanceof ArrayList)) {
1493 return ((Collection) collection).iterator();
1494 }
1495 return null;
1496 }
1497
1498
1499
1500
1501
1502
1503
1504 public static int length(Object arrayOrCollection) {
1505 if (arrayOrCollection == null) {
1506 return 0;
1507 }
1508 if (arrayOrCollection.getClass().isArray()) {
1509 return Array.getLength(arrayOrCollection);
1510 }
1511 if (arrayOrCollection instanceof Collection) {
1512 return ((Collection) arrayOrCollection).size();
1513 }
1514 if (arrayOrCollection instanceof Map) {
1515 return ((Map) arrayOrCollection).size();
1516 }
1517
1518 return 1;
1519 }
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530 public static Object next(Object arrayOrCollection, Iterator iterator,
1531 int index) {
1532 if (arrayOrCollection.getClass().isArray()) {
1533 return Array.get(arrayOrCollection, index);
1534 }
1535 if (arrayOrCollection instanceof ArrayList) {
1536 return ((ArrayList) arrayOrCollection).get(index);
1537 }
1538 if (arrayOrCollection instanceof Collection) {
1539 return iterator.next();
1540 }
1541
1542 if (0 == index) {
1543 return arrayOrCollection;
1544 }
1545 throw new RuntimeException("Invalid class type: "
1546 + arrayOrCollection.getClass().getName());
1547 }
1548
1549
1550
1551
1552
1553
1554
1555
1556 public static Object remove(Object arrayOrCollection,
1557 int index) {
1558 return remove(arrayOrCollection, null, index);
1559 }
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569 public static Object remove(Object arrayOrCollection, Iterator iterator,
1570 int index) {
1571
1572
1573 if (iterator != null) {
1574 iterator.remove();
1575 return arrayOrCollection;
1576 }
1577 if (arrayOrCollection.getClass().isArray()) {
1578 int newLength = Array.getLength(arrayOrCollection) - 1;
1579 Object newArray = Array.newInstance(arrayOrCollection.getClass().getComponentType(), newLength);
1580 if (newLength == 0) {
1581 return newArray;
1582 }
1583 if (index > 0) {
1584 System.arraycopy(arrayOrCollection, 0, newArray, 0, index);
1585 }
1586 if (index < newLength) {
1587 System.arraycopy(arrayOrCollection, index+1, newArray, index, newLength - index);
1588 }
1589 return newArray;
1590 }
1591 if (arrayOrCollection instanceof List) {
1592 ((List)arrayOrCollection).remove(index);
1593 return arrayOrCollection;
1594 } else if (arrayOrCollection instanceof Collection) {
1595
1596 ((Collection)arrayOrCollection).remove(get(arrayOrCollection, index));
1597 return arrayOrCollection;
1598 }
1599 throw new RuntimeException("Invalid class type: "
1600 + arrayOrCollection.getClass().getName());
1601 }
1602
1603
1604
1605
1606
1607
1608 public static String classesString(Object object) {
1609 StringBuilder result = new StringBuilder();
1610 if (object.getClass().isArray()) {
1611 int length = Array.getLength(object);
1612 for (int i=0;i<length;i++) {
1613 result.append(((Class)object).getSimpleName());
1614 if (i < length-1) {
1615 result.append(", ");
1616 }
1617 }
1618 return result.toString();
1619 }
1620
1621 throw new RuntimeException("Not implemented: " + className(object));
1622 }
1623
1624
1625
1626
1627
1628
1629
1630 public static String classNameCollection(Object object) {
1631 if (object == null) {
1632 return null;
1633 }
1634 StringBuffer result = new StringBuffer();
1635
1636 Iterator iterator = iterator(object);
1637 int length = length(object);
1638 for (int i = 0; i < length && i < 20; i++) {
1639 result.append(className(next(object, iterator, i)));
1640 if (i != length - 1) {
1641 result.append(", ");
1642 }
1643 }
1644 return result.toString();
1645 }
1646
1647
1648
1649
1650
1651
1652
1653 public static String className(Object object) {
1654 return object == null ? null : object.getClass().getName();
1655 }
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673 @SuppressWarnings("unchecked")
1674 public static void assignField(Field field, Object invokeOn,
1675 Object dataToAssign, boolean overrideSecurity, boolean typeCast,
1676 Class<? extends Annotation> annotationWithValueOverride) {
1677
1678 if (annotationWithValueOverride != null) {
1679
1680 Annotation annotation = field
1681 .getAnnotation(annotationWithValueOverride);
1682 if (annotation != null) {
1683
1684
1685
1686
1687
1688
1689
1690 throw new RuntimeException("Not supported");
1691 }
1692 }
1693 assignField(field, invokeOn, dataToAssign, overrideSecurity, typeCast);
1694 }
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707 public static void assignField(Object invokeOn, String fieldName,
1708 Object dataToAssign) {
1709 assignField(null, invokeOn, fieldName, dataToAssign, true, true, true,
1710 null);
1711 }
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725 public static Field field(Class theClass, String fieldName,
1726 boolean callOnSupers, boolean throwExceptionIfNotFound) {
1727 try {
1728 Field field = theClass.getDeclaredField(fieldName);
1729
1730 return field;
1731 } catch (NoSuchFieldException e) {
1732
1733
1734 if (callOnSupers && !theClass.equals(Object.class)) {
1735 return field(theClass.getSuperclass(), fieldName, callOnSupers,
1736 throwExceptionIfNotFound);
1737 }
1738 }
1739
1740 if (throwExceptionIfNotFound) {
1741 throw new RuntimeException("Cant find field: " + fieldName
1742 + ", in: " + theClass + ", callOnSupers: " + callOnSupers);
1743 }
1744 return null;
1745 }
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757 @SuppressWarnings("unchecked")
1758 public static Set<String> fieldNames(Class theClass, Class fieldType,
1759 boolean includeStaticFields) {
1760 return fieldNamesHelper(theClass, theClass, fieldType, true, true,
1761 includeStaticFields, null, true);
1762 }
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781 public static Set<String> fieldNames(Class theClass,
1782 Class superclassToStopAt, Class<?> fieldType,
1783 boolean includeSuperclassToStopAt, boolean includeStaticFields,
1784 boolean includeFinalFields) {
1785 return fieldNamesHelper(theClass, superclassToStopAt, fieldType,
1786 includeSuperclassToStopAt, includeStaticFields,
1787 includeFinalFields, null, true);
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 public static Set<String> fieldNames(Class theClass,
1813 Class superclassToStopAt, Class<?> fieldType,
1814 boolean includeSuperclassToStopAt, boolean includeStaticFields,
1815 boolean includeFinalFields,
1816 Class<? extends Annotation> markerAnnotationToIngore) {
1817 return fieldNamesHelper(theClass, superclassToStopAt, fieldType,
1818 includeSuperclassToStopAt, includeStaticFields,
1819 includeFinalFields, markerAnnotationToIngore, false);
1820
1821 }
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837 public static Set<String> fieldNames(Class theClass,
1838 Class superclassToStopAt,
1839 Class<? extends Annotation> markerAnnotationToIngore) {
1840 return fieldNamesHelper(theClass, superclassToStopAt, null, true,
1841 false, false, markerAnnotationToIngore, false);
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 @SuppressWarnings("unchecked")
1868 static Set<String> fieldNamesHelper(Class theClass,
1869 Class superclassToStopAt, Class<?> fieldType,
1870 boolean includeSuperclassToStopAt, boolean includeStaticFields,
1871 boolean includeFinalFields,
1872 Class<? extends Annotation> markerAnnotation,
1873 boolean includeAnnotation) {
1874 Set<Field> fieldSet = fieldsHelper(theClass, superclassToStopAt,
1875 fieldType, includeSuperclassToStopAt, includeStaticFields,
1876 includeFinalFields, markerAnnotation, includeAnnotation);
1877 Set<String> fieldNameSet = new LinkedHashSet<String>();
1878 for (Field field : fieldSet) {
1879 fieldNameSet.add(field.getName());
1880 }
1881 return fieldNameSet;
1882
1883 }
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908 @SuppressWarnings("unchecked")
1909 public static Set<Field> fields(Class theClass, Class superclassToStopAt,
1910 Class fieldType, boolean includeSuperclassToStopAt,
1911 boolean includeStaticFields, boolean includeFinalFields,
1912 Class<? extends Annotation> markerAnnotation,
1913 boolean includeAnnotation) {
1914 return fieldsHelper(theClass, superclassToStopAt, fieldType,
1915 includeSuperclassToStopAt, includeStaticFields,
1916 includeFinalFields, markerAnnotation, includeAnnotation);
1917 }
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937 @SuppressWarnings("unchecked")
1938 public static Set<Field> fields(Class theClass, Class superclassToStopAt,
1939 Class<? extends Annotation> markerAnnotation,
1940 boolean includeAnnotation) {
1941 return fieldsHelper(theClass, superclassToStopAt, null, true, false,
1942 false, markerAnnotation, includeAnnotation);
1943 }
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968 @SuppressWarnings("unchecked")
1969 static Set<Field> fieldsHelper(Class theClass, Class superclassToStopAt,
1970 Class<?> fieldType, boolean includeSuperclassToStopAt,
1971 boolean includeStaticFields, boolean includeFinalFields,
1972 Class<? extends Annotation> markerAnnotation,
1973 boolean includeAnnotation) {
1974
1975
1976 Set<Field> fieldNameSet = null;
1977 String cacheKey = theClass + CACHE_SEPARATOR + superclassToStopAt
1978 + CACHE_SEPARATOR + fieldType + CACHE_SEPARATOR
1979 + includeSuperclassToStopAt + CACHE_SEPARATOR
1980 + includeStaticFields + CACHE_SEPARATOR + includeFinalFields
1981 + CACHE_SEPARATOR + markerAnnotation + CACHE_SEPARATOR
1982 + includeAnnotation;
1983 fieldNameSet = fieldSetCache().get(cacheKey);
1984 if (fieldNameSet != null) {
1985 return fieldNameSet;
1986 }
1987
1988 fieldNameSet = new LinkedHashSet<Field>();
1989 fieldsHelper(theClass, superclassToStopAt, fieldType,
1990 includeSuperclassToStopAt, includeStaticFields,
1991 includeFinalFields, markerAnnotation, fieldNameSet,
1992 includeAnnotation);
1993
1994
1995 fieldSetCache().put(cacheKey, fieldNameSet);
1996
1997 return fieldNameSet;
1998
1999 }
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011 @SuppressWarnings("unchecked")
2012 public static Set<String> compareObjectFields(Object first, Object second,
2013 Set<String> fieldsToCompare, String mapPrefix) {
2014
2015 Set<String> differentFields = new LinkedHashSet<String>();
2016
2017 if (first == second) {
2018 return differentFields;
2019 }
2020
2021
2022 if (first == null || second == null) {
2023 differentFields.addAll(fieldsToCompare);
2024 }
2025
2026 for (String fieldName : fieldsToCompare) {
2027 try {
2028 Object firstValue = fieldValue(first, fieldName);
2029 Object secondValue = fieldValue(second, fieldName);
2030
2031 if (firstValue == secondValue) {
2032 continue;
2033 }
2034 if (firstValue instanceof Map || secondValue instanceof Map) {
2035 mapDifferences((Map)firstValue, (Map)secondValue, differentFields, mapPrefix);
2036 continue;
2037 }
2038
2039
2040 if (firstValue instanceof String || secondValue instanceof String) {
2041 if (!equals(defaultString((String)firstValue),
2042 defaultString((String)secondValue))) {
2043 differentFields.add(fieldName);
2044 }
2045 continue;
2046 }
2047
2048 if (firstValue == null || secondValue == null) {
2049 differentFields.add(fieldName);
2050 continue;
2051 }
2052
2053 if (!firstValue.equals(secondValue)) {
2054 differentFields.add(fieldName);
2055 continue;
2056 }
2057
2058 } catch (RuntimeException re) {
2059 throw new RuntimeException("Problem comparing field " + fieldName
2060 + " on objects: " + className(first) + ", " + className(second));
2061 }
2062
2063
2064 }
2065 return differentFields;
2066 }
2067
2068
2069
2070
2071
2072
2073
2074
2075 @SuppressWarnings("unchecked")
2076 public static <T> T clone(T object, Set<String> fieldsToClone) {
2077
2078
2079 T result = (T)newInstance(object.getClass());
2080
2081 cloneFields(object, result, fieldsToClone);
2082
2083 return result;
2084 }
2085
2086
2087
2088
2089
2090
2091
2092
2093 public static <T> void cloneFields(T object, T result,
2094 Set<String> fieldsToClone) {
2095
2096 if (object == result) {
2097 return;
2098 }
2099
2100
2101 if (object == null || result == null) {
2102 throw new RuntimeException("Cant copy from or to null: " + className(object) + ", " + className(result));
2103 }
2104
2105 Class<?> fieldValueClass = null;
2106
2107 for (String fieldName : nonNull(fieldsToClone)) {
2108 try {
2109
2110 Object fieldValue = fieldValue(object, fieldName);
2111 fieldValueClass = fieldValue == null ? null : fieldValue.getClass();
2112
2113 Object fieldValueToAssign = cloneValue(fieldValue);
2114
2115
2116 assignField(result, fieldName, fieldValueToAssign);
2117
2118 } catch (RuntimeException re) {
2119 throw new RuntimeException("Problem cloning field: " + object.getClass()
2120 + ", " + fieldName + ", " + fieldValueClass, re);
2121 }
2122 }
2123 }
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134 @SuppressWarnings("unchecked")
2135 public static <T> T cloneValue(T value) {
2136
2137 Object clonedValue = value;
2138
2139 if (value == null || value instanceof String
2140 || value.getClass().isPrimitive() || value instanceof Number
2141 || value instanceof Boolean
2142 || value instanceof Date) {
2143
2144
2145
2146 } else if (value instanceof Map) {
2147 clonedValue = new LinkedHashMap();
2148 Map mapValue = (Map)value;
2149 Map clonedMapValue = (Map)clonedValue;
2150 for (Object key : mapValue.keySet()) {
2151 clonedMapValue.put(cloneValue(key), cloneValue(mapValue.get(key)));
2152 }
2153 } else if (value instanceof Set) {
2154 clonedValue = new LinkedHashSet();
2155 Set setValue = (Set)value;
2156 Set clonedSetValue = (Set)clonedValue;
2157 for (Object each : setValue) {
2158 clonedSetValue.add(cloneValue(each));
2159 }
2160 } else if (value instanceof List) {
2161 clonedValue = new ArrayList();
2162 List listValue = (List)value;
2163 List clonedListValue = (List)clonedValue;
2164 for (Object each : listValue) {
2165 clonedListValue.add(cloneValue(each));
2166 }
2167 } else if (value.getClass().isArray()) {
2168 clonedValue = Array.newInstance(value.getClass().getComponentType(), Array.getLength(value));
2169 for (int i=0;i<Array.getLength(value);i++) {
2170 Array.set(clonedValue, i, cloneValue(Array.get(value, i)));
2171 }
2172
2173
2174 } else {
2175
2176
2177 throw new RuntimeException("Unexpected class in clone method: " + value.getClass());
2178
2179 }
2180 return (T)clonedValue;
2181 }
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191 public static Set<String> methodNames(Class<?> theClass, Class<?> superclassToStopAt,
2192 boolean includeSuperclassToStopAt, boolean includeStaticMethods) {
2193
2194 Set<Method> methods = new LinkedHashSet<Method>();
2195 methodsHelper(theClass, superclassToStopAt, includeSuperclassToStopAt, includeStaticMethods,
2196 null, false, methods);
2197 Set<String> methodNames = new HashSet<String>();
2198 for (Method method : methods) {
2199 methodNames.add(method.getName());
2200 }
2201 return methodNames;
2202 }
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214 public static void methodsHelper(Class<?> theClass, Class<?> superclassToStopAt,
2215 boolean includeSuperclassToStopAt,
2216 boolean includeStaticMethods, Class<? extends Annotation> markerAnnotation,
2217 boolean includeAnnotation, Set<Method> methodSet) {
2218 Method[] methods = theClass.getDeclaredMethods();
2219 if (length(methods) != 0) {
2220 for (Method method : methods) {
2221
2222 if (!includeStaticMethods
2223 && Modifier.isStatic(method.getModifiers())) {
2224 continue;
2225 }
2226
2227 if (markerAnnotation != null
2228 && (includeAnnotation != method
2229 .isAnnotationPresent(markerAnnotation))) {
2230 continue;
2231 }
2232
2233 methodSet.add(method);
2234 }
2235 }
2236
2237
2238 if (theClass.equals(superclassToStopAt)
2239 || theClass.equals(Object.class)) {
2240 return;
2241 }
2242 Class superclass = theClass.getSuperclass();
2243 if (!includeSuperclassToStopAt && superclass.equals(superclassToStopAt)) {
2244 return;
2245 }
2246
2247 methodsHelper(superclass, superclassToStopAt,
2248 includeSuperclassToStopAt, includeStaticMethods,
2249 markerAnnotation, includeAnnotation, methodSet);
2250
2251 }
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267 public static Method method(Class<?> theClass,
2268 String methodName, Object paramTypesOrArrayOrList,
2269 Class<?> superclassToStopAt,
2270 boolean includeSuperclassToStopAt,
2271 boolean isStaticOrInstance, Class<? extends Annotation> markerAnnotation,
2272 boolean includeAnnotation) {
2273
2274 Class[] paramTypesArray = (Class[]) toArray(paramTypesOrArrayOrList);
2275
2276 Method method = null;
2277
2278 try {
2279 method = theClass.getDeclaredMethod(methodName, paramTypesArray);
2280 } catch (NoSuchMethodException nsme) {
2281
2282 } catch (Exception e) {
2283 throw new RuntimeException("Problem retrieving method: " + theClass.getSimpleName() + ", " + methodName, e);
2284 }
2285
2286 if (method != null) {
2287
2288
2289 if (!isStaticOrInstance
2290 && Modifier.isStatic(method.getModifiers())) {
2291 return null;
2292 }
2293
2294 if (markerAnnotation == null
2295 || (includeAnnotation == method
2296 .isAnnotationPresent(markerAnnotation))) {
2297 return method;
2298 }
2299 }
2300
2301
2302 if (theClass.equals(superclassToStopAt)
2303 || theClass.equals(Object.class)) {
2304 return null;
2305 }
2306 Class superclass = theClass.getSuperclass();
2307 if (!includeSuperclassToStopAt && superclass.equals(superclassToStopAt)) {
2308 return null;
2309 }
2310
2311 return method(superclass, methodName, paramTypesArray, superclassToStopAt,
2312 includeSuperclassToStopAt, isStaticOrInstance, markerAnnotation, includeAnnotation);
2313 }
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338 @SuppressWarnings("unchecked")
2339 private static void fieldsHelper(Class theClass, Class superclassToStopAt,
2340 Class<?> fieldType, boolean includeSuperclassToStopAt,
2341 boolean includeStaticFields, boolean includeFinalFields,
2342 Class<? extends Annotation> markerAnnotation, Set<Field> fieldSet,
2343 boolean includeAnnotation) {
2344 Field[] fields = theClass.getDeclaredFields();
2345 if (length(fields) != 0) {
2346 for (Field field : fields) {
2347
2348 if (fieldType != null
2349 && !fieldType.isAssignableFrom(field.getType())) {
2350 continue;
2351 }
2352
2353 if (!includeStaticFields
2354 && Modifier.isStatic(field.getModifiers())) {
2355 continue;
2356 }
2357
2358 if (!includeFinalFields
2359 && Modifier.isFinal(field.getModifiers())) {
2360 continue;
2361 }
2362
2363 if (markerAnnotation != null
2364 && (includeAnnotation != field
2365 .isAnnotationPresent(markerAnnotation))) {
2366 continue;
2367 }
2368
2369 fieldSet.add(field);
2370 }
2371 }
2372
2373
2374 if (theClass.equals(superclassToStopAt)
2375 || theClass.equals(Object.class)) {
2376 return;
2377 }
2378 Class superclass = theClass.getSuperclass();
2379 if (!includeSuperclassToStopAt && superclass.equals(superclassToStopAt)) {
2380 return;
2381 }
2382
2383 fieldsHelper(superclass, superclassToStopAt, fieldType,
2384 includeSuperclassToStopAt, includeStaticFields,
2385 includeFinalFields, markerAnnotation, fieldSet,
2386 includeAnnotation);
2387 }
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404 public static Object fieldValue(Class theClass, Object invokeOn,
2405 String fieldName, boolean callOnSupers, boolean overrideSecurity) {
2406 Field field = null;
2407
2408
2409 try {
2410
2411 if (theClass == null) {
2412 theClass = invokeOn.getClass();
2413 }
2414 field = field(theClass, fieldName, callOnSupers, true);
2415 return fieldValue(field, invokeOn, overrideSecurity);
2416 } catch (Exception e) {
2417 throw new RuntimeException("Cant execute reflection field: "
2418 + fieldName + ", on: " + className(invokeOn), e);
2419 }
2420 }
2421
2422
2423
2424
2425
2426
2427
2428
2429 public static Object fieldValue(Field field, Object invokeOn) {
2430 return fieldValue(field, invokeOn, true);
2431 }
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441 public static Object fieldValue(Field field, Object invokeOn,
2442 boolean overrideSecurity) {
2443 if (overrideSecurity) {
2444 field.setAccessible(true);
2445 }
2446 try {
2447 return field.get(invokeOn);
2448 } catch (Exception e) {
2449 throw new RuntimeException("Cant execute reflection field: "
2450 + field.getName() + ", on: " + className(invokeOn), e);
2451
2452 }
2453
2454 }
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465 public static Object fieldValue(Object invokeOn, String fieldName) {
2466 return fieldValue(null, invokeOn, fieldName, true, true);
2467 }
2468
2469
2470
2471
2472
2473
2474
2475 @SuppressWarnings("unused")
2476 private static Method[] retrieveDeclaredMethods(Class theClass) {
2477 Method[] methods = declaredMethodsCache().get(theClass);
2478
2479 if (methods == null) {
2480 methods = theClass.getDeclaredMethods();
2481 declaredMethodsCache().put(theClass, methods);
2482 }
2483 return methods;
2484 }
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498 public static Object callMethod(Class theClass, Object invokeOn,
2499 String methodName) {
2500 return callMethod(theClass, invokeOn, methodName, null, null);
2501 }
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518 public static Object callMethod(Class theClass, Object invokeOn,
2519 String methodName, Object paramTypesOrArrayOrList,
2520 Object paramsOrListOrArray) {
2521 return callMethod(theClass, invokeOn, methodName,
2522 paramTypesOrArrayOrList, paramsOrListOrArray, true);
2523 }
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542 public static Object callMethod(Class theClass, Object invokeOn,
2543 String methodName, Object paramTypesOrArrayOrList,
2544 Object paramsOrListOrArray, boolean callOnSupers) {
2545 return callMethod(theClass, invokeOn, methodName,
2546 paramTypesOrArrayOrList, paramsOrListOrArray, callOnSupers,
2547 false);
2548 }
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558 public static <T> T construct(Class<T> theClass, Class[] types, Object[] args) {
2559 try {
2560 Constructor<T> constructor = theClass.getConstructor(types);
2561
2562 return constructor.newInstance(args);
2563
2564 } catch (Exception e) {
2565 throw new RuntimeException("Having trouble with constructor for class: " + theClass.getSimpleName()
2566 + " and args: " + classesString(types), e);
2567 }
2568 }
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589 public static Object callMethod(Class theClass, Object invokeOn,
2590 String methodName, Object paramTypesOrArrayOrList,
2591 Object paramsOrListOrArray, boolean callOnSupers,
2592 boolean overrideSecurity) {
2593 Method method = null;
2594
2595 Class[] paramTypesArray = (Class[]) toArray(paramTypesOrArrayOrList);
2596
2597 try {
2598 method = theClass.getDeclaredMethod(methodName, paramTypesArray);
2599 if (overrideSecurity) {
2600 method.setAccessible(true);
2601 }
2602 } catch (Exception e) {
2603
2604 if (e instanceof NoSuchMethodException) {
2605
2606
2607
2608 if (callOnSupers
2609 && !theClass.equals(Object.class)) {
2610 return callMethod(theClass.getSuperclass(), invokeOn,
2611 methodName, paramTypesOrArrayOrList,
2612 paramsOrListOrArray, callOnSupers, overrideSecurity);
2613 }
2614 }
2615 throw new RuntimeException("Problem calling method " + methodName
2616 + " on " + theClass.getName(), e);
2617 }
2618
2619 return invokeMethod(method, invokeOn, paramsOrListOrArray);
2620
2621 }
2622
2623
2624 private static final Object NO_PARAMS = new Object();
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635 public static Object invokeMethod(Method method, Object invokeOn) {
2636 return invokeMethod(method, invokeOn, NO_PARAMS);
2637 }
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649 public static Object invokeMethod(Method method, Object invokeOn,
2650 Object paramsOrListOrArray) {
2651
2652 Object[] args = paramsOrListOrArray == NO_PARAMS ? null : (Object[]) toArray(paramsOrListOrArray);
2653
2654
2655 method.setAccessible(true);
2656
2657
2658 Object result = null;
2659 Exception e = null;
2660 try {
2661 result = method.invoke(invokeOn, args);
2662 } catch (IllegalAccessException iae) {
2663 e = iae;
2664 } catch (IllegalArgumentException iae) {
2665 e = iae;
2666 } catch (InvocationTargetException ite) {
2667
2668 if (ite.getCause() instanceof RuntimeException) {
2669 throw (RuntimeException)ite.getCause();
2670 }
2671
2672 e = ite;
2673 }
2674 if (e != null) {
2675 throw new RuntimeException("Cant execute reflection method: "
2676 + method.getName() + ", on: " + className(invokeOn)
2677 + ", with args: " + classNameCollection(args), e);
2678 }
2679 return result;
2680 }
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690 public static Object toArray(Object objectOrArrayOrCollection) {
2691
2692
2693 if (objectOrArrayOrCollection != null
2694 && objectOrArrayOrCollection.getClass().isArray()) {
2695 return objectOrArrayOrCollection;
2696 }
2697 int length = length(objectOrArrayOrCollection);
2698 if (length == 0) {
2699 return null;
2700 }
2701
2702 if (objectOrArrayOrCollection instanceof Collection) {
2703 Collection collection = (Collection) objectOrArrayOrCollection;
2704 Object first = collection.iterator().next();
2705 return toArray(collection, first == null ? Object.class : first
2706 .getClass());
2707 }
2708
2709 Object array = Array.newInstance(objectOrArrayOrCollection.getClass(),
2710 1);
2711 Array.set(array, 0, objectOrArrayOrCollection);
2712 return array;
2713 }
2714
2715
2716
2717
2718
2719
2720
2721
2722 @SuppressWarnings("unchecked")
2723 public static <T> T[] toArray(Collection collection, Class<T> theClass) {
2724 if (collection == null || collection.size() == 0) {
2725 return null;
2726 }
2727
2728 return (T[])collection.toArray((Object[]) Array.newInstance(theClass,
2729 collection.size()));
2730
2731 }
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743 public static Object callMethod(Class theClass, String methodName) {
2744 return callMethod(theClass, null, methodName, null, null);
2745 }
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758 public static Object callMethod(Class theClass, String methodName,
2759 boolean callOnSupers) {
2760 return callMethod(theClass, null, methodName, null, null, callOnSupers);
2761 }
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776 public static Object callMethod(Class theClass, String methodName,
2777 Object paramTypesOrArrayOrList, Object paramsOrListOrArray) {
2778 return callMethod(theClass, null, methodName, paramTypesOrArrayOrList,
2779 paramsOrListOrArray);
2780 }
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792 public static Object callMethod(Object invokeOn, String methodName) {
2793 if (invokeOn == null) {
2794 throw new NullPointerException("invokeOn is null: " + methodName);
2795 }
2796 return callMethod(invokeOn.getClass(), invokeOn, methodName, null,
2797 null, true, true);
2798 }
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812 public static String replace(String text, Object searchFor,
2813 Object replaceWith) {
2814 return replace(null, null, text, searchFor, replaceWith, false, 0,
2815 false);
2816 }
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832 public static String replace(String text, Object searchFor,
2833 Object replaceWith, boolean recurse) {
2834 return replace(null, null, text, searchFor, replaceWith, recurse,
2835 recurse ? length(searchFor) : 0, false);
2836 }
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854 public static String replace(String text, Object searchFor,
2855 Object replaceWith, boolean recurse, boolean removeIfFound) {
2856 return replace(null, null, text, searchFor, replaceWith, recurse,
2857 recurse ? length(searchFor) : 0, removeIfFound);
2858 }
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890 public static String replace(String text, String repl, String with) {
2891 return replace(text, repl, with, -1);
2892 }
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931 public static String replace(String text, String repl, String with, int max) {
2932 if (text == null || isEmpty(repl) || with == null || max == 0) {
2933 return text;
2934 }
2935
2936 StringBuffer buf = new StringBuffer(text.length());
2937 int start = 0, end = 0;
2938 while ((end = text.indexOf(repl, start)) != -1) {
2939 buf.append(text.substring(start, end)).append(with);
2940 start = end + repl.length();
2941
2942 if (--max == 0) {
2943 break;
2944 }
2945 }
2946 buf.append(text.substring(start));
2947 return buf.toString();
2948 }
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972 public static boolean isEmpty(String str) {
2973 return str == null || str.length() == 0;
2974 }
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989 public static void replace(StringBuffer outBuffer, String text,
2990 Object searchFor, Object replaceWith) {
2991 replace(outBuffer, null, text, searchFor, replaceWith, false, 0, false);
2992 }
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009 public static void replace(StringBuffer outBuffer, String text,
3010 Object searchFor, Object replaceWith, boolean recurse) {
3011 replace(outBuffer, null, text, searchFor, replaceWith, recurse,
3012 recurse ? length(searchFor) : 0, false);
3013 }
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044 private static String replace(StringBuffer outBuffer, Writer outWriter,
3045 String text, Object searchFor, Object replaceWith, boolean recurse,
3046 int timeToLive, boolean removeIfFound) {
3047
3048
3049
3050 if (!recurse) {
3051 return replaceHelper(outBuffer, outWriter, text, searchFor,
3052 replaceWith, recurse, timeToLive, removeIfFound);
3053 }
3054
3055 String result = replaceHelper(null, null, text, searchFor, replaceWith,
3056 recurse, timeToLive, removeIfFound);
3057 if (outBuffer != null) {
3058 outBuffer.append(result);
3059 return null;
3060 }
3061
3062 if (outWriter != null) {
3063 try {
3064 outWriter.write(result);
3065 } catch (IOException ioe) {
3066 throw new RuntimeException(ioe);
3067 }
3068 return null;
3069 }
3070
3071 return result;
3072
3073 }
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088 public static void replace(Writer outWriter, String text, Object searchFor,
3089 Object replaceWith) {
3090 replace(null, outWriter, text, searchFor, replaceWith, false, 0, false);
3091 }
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108 public static void replace(Writer outWriter, String text, Object searchFor,
3109 Object replaceWith, boolean recurse) {
3110 replace(null, outWriter, text, searchFor, replaceWith, recurse,
3111 recurse ? length(searchFor) : 0, false);
3112 }
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143 private static String replaceHelper(StringBuffer outBuffer,
3144 Writer outWriter, String text, Object searchFor,
3145 Object replaceWith, boolean recurse, int timeToLive,
3146 boolean removeIfFound) {
3147
3148 try {
3149
3150 if (timeToLive < 0) {
3151 throw new IllegalArgumentException("TimeToLive under 0: "
3152 + timeToLive + ", " + text);
3153 }
3154
3155 int searchForLength = length(searchFor);
3156 boolean done = false;
3157
3158 if (isEmpty(text)) {
3159 return text;
3160 }
3161
3162 if (searchForLength == 0) {
3163 done = true;
3164 }
3165
3166 boolean[] noMoreMatchesForReplIndex = null;
3167 int inputIndex = -1;
3168 int replaceIndex = -1;
3169 long resultPacked = -1;
3170
3171 if (!done) {
3172
3173 if (searchForLength != length(replaceWith)) {
3174 throw new IndexOutOfBoundsException("Lengths dont match: "
3175 + searchForLength + ", " + length(replaceWith));
3176 }
3177
3178
3179 noMoreMatchesForReplIndex = new boolean[searchForLength];
3180
3181
3182
3183
3184
3185 resultPacked = findNextIndexHelper(searchForLength, searchFor,
3186 replaceWith,
3187 noMoreMatchesForReplIndex, text, 0);
3188
3189 inputIndex = unpackInt(resultPacked, true);
3190 replaceIndex = unpackInt(resultPacked, false);
3191 }
3192
3193
3194
3195
3196 boolean writeToWriter = outWriter != null;
3197
3198
3199 if (done || inputIndex == -1) {
3200 if (writeToWriter) {
3201 outWriter.write(text, 0, text.length());
3202 return null;
3203 }
3204 if (outBuffer != null) {
3205 appendSubstring(outBuffer, text, 0, text.length());
3206 return null;
3207 }
3208 return text;
3209 }
3210
3211
3212 StringBuffer bufferToWriteTo = outBuffer != null ? outBuffer
3213 : (writeToWriter ? null : new StringBuffer(text.length()
3214 + replaceStringsBufferIncrease(text, searchFor,
3215 replaceWith)));
3216
3217 String searchString = null;
3218 String replaceString = null;
3219
3220 int start = 0;
3221
3222 while (inputIndex != -1) {
3223
3224 searchString = (String) get(searchFor, replaceIndex);
3225 replaceString = (String) get(replaceWith, replaceIndex);
3226 if (writeToWriter) {
3227 outWriter.write(text, start, inputIndex - start);
3228 outWriter.write(replaceString);
3229 } else {
3230 appendSubstring(bufferToWriteTo, text, start, inputIndex)
3231 .append(replaceString);
3232 }
3233
3234 if (removeIfFound) {
3235
3236 searchFor = remove(searchFor, replaceIndex);
3237 replaceWith = remove(replaceWith, replaceIndex);
3238 noMoreMatchesForReplIndex = (boolean[])remove(noMoreMatchesForReplIndex, replaceIndex);
3239
3240 searchForLength--;
3241 }
3242
3243 start = inputIndex + searchString.length();
3244
3245 resultPacked = findNextIndexHelper(searchForLength, searchFor,
3246 replaceWith,
3247 noMoreMatchesForReplIndex, text, start);
3248 inputIndex = unpackInt(resultPacked, true);
3249 replaceIndex = unpackInt(resultPacked, false);
3250 }
3251 if (writeToWriter) {
3252 outWriter.write(text, start, text.length() - start);
3253
3254 } else {
3255 appendSubstring(bufferToWriteTo, text, start, text.length());
3256 }
3257
3258
3259 if (writeToWriter || outBuffer != null) {
3260 if (recurse) {
3261 throw new IllegalArgumentException(
3262 "Cannot recurse and write to existing buffer or writer!");
3263 }
3264 return null;
3265 }
3266 String resultString = bufferToWriteTo.toString();
3267
3268 if (recurse) {
3269 return replaceHelper(outBuffer, outWriter, resultString,
3270 searchFor, replaceWith, recurse, timeToLive - 1, false);
3271 }
3272
3273 return resultString;
3274 } catch (IOException ioe) {
3275 throw new RuntimeException(ioe);
3276 }
3277 }
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289 static int replaceStringsBufferIncrease(String text, Object repl,
3290 Object with) {
3291
3292 int increase = 0;
3293 Iterator iteratorReplace = iterator(repl);
3294 Iterator iteratorWith = iterator(with);
3295 int replLength = length(repl);
3296 String currentRepl = null;
3297 String currentWith = null;
3298 for (int i = 0; i < replLength; i++) {
3299 currentRepl = (String) next(repl, iteratorReplace, i);
3300 currentWith = (String) next(with, iteratorWith, i);
3301 if (currentRepl == null || currentWith == null) {
3302 throw new NullPointerException("Replace string is null: "
3303 + text + ", " + currentRepl + ", " + currentWith);
3304 }
3305 int greater = currentWith.length() - currentRepl.length();
3306 increase += greater > 0 ? 3 * greater : 0;
3307 }
3308
3309 increase = Math.min(increase, text.length() / 5);
3310 return increase;
3311 }
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325 private static long findNextIndexHelper(int searchForLength,
3326 Object searchFor, Object replaceWith, boolean[] noMoreMatchesForReplIndex,
3327 String input, int start) {
3328
3329 int inputIndex = -1;
3330 int replaceIndex = -1;
3331
3332 Iterator iteratorSearchFor = iterator(searchFor);
3333 Iterator iteratorReplaceWith = iterator(replaceWith);
3334
3335 String currentSearchFor = null;
3336 String currentReplaceWith = null;
3337 int tempIndex = -1;
3338 for (int i = 0; i < searchForLength; i++) {
3339 currentSearchFor = (String) next(searchFor, iteratorSearchFor, i);
3340 currentReplaceWith = (String) next(replaceWith,
3341 iteratorReplaceWith, i);
3342 if (noMoreMatchesForReplIndex[i] || isEmpty(currentSearchFor)
3343 || currentReplaceWith == null) {
3344 continue;
3345 }
3346 tempIndex = input.indexOf(currentSearchFor, start);
3347
3348
3349 noMoreMatchesForReplIndex[i] = tempIndex == -1;
3350
3351 if (tempIndex != -1 && (inputIndex == -1 || tempIndex < inputIndex)) {
3352 inputIndex = tempIndex;
3353 replaceIndex = i;
3354 }
3355
3356 }
3357
3358 long resultPacked = packInts(inputIndex, replaceIndex);
3359 return resultPacked;
3360 }
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372 public static long packInts(int first, int second) {
3373 long result = first;
3374 result <<= 32;
3375 result |= second;
3376 return result;
3377 }
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388 public static int unpackInt(long theLong, boolean isFirst) {
3389
3390 int result = 0;
3391
3392 if (isFirst) {
3393 theLong >>= 32;
3394 }
3395
3396 result = (int) (theLong & 0xffffffff);
3397 return result;
3398 }
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414 private static StringBuffer appendSubstring(StringBuffer buf,
3415 String string, int start, int end) {
3416 for (int i = start; i < end; i++) {
3417 buf.append(string.charAt(i));
3418 }
3419 return buf;
3420 }
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430 public static Object get(Object arrayOrCollection, int index) {
3431
3432 if (arrayOrCollection == null) {
3433 if (index == 0) {
3434 return null;
3435 }
3436 throw new RuntimeException("Trying to access index " + index
3437 + " of null");
3438 }
3439
3440
3441 if (arrayOrCollection instanceof List) {
3442 return ((List) arrayOrCollection).get(index);
3443 }
3444 if (arrayOrCollection instanceof Collection) {
3445 Iterator iterator = iterator(arrayOrCollection);
3446 for (int i = 0; i < index; i++) {
3447 next(arrayOrCollection, iterator, i);
3448 }
3449 return next(arrayOrCollection, iterator, index);
3450 }
3451
3452 if (arrayOrCollection.getClass().isArray()) {
3453 return Array.get(arrayOrCollection, index);
3454 }
3455
3456 if (index == 0) {
3457 return arrayOrCollection;
3458 }
3459
3460 throw new RuntimeException("Trying to access index " + index
3461 + " of and object: " + arrayOrCollection);
3462 }
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472 @SuppressWarnings("unchecked")
3473 public static String toStringSafe(Object object) {
3474 if (object == null) {
3475 return null;
3476 }
3477
3478 try {
3479
3480 if (object instanceof Collection) {
3481 Collection<Object> collection = (Collection<Object>) object;
3482 int collectionSize = collection.size();
3483 if (collectionSize == 0) {
3484 return "Empty " + object.getClass().getSimpleName();
3485 }
3486 Object first = collection.iterator().next();
3487 return object.getClass().getSimpleName() + " of size "
3488 + collectionSize + " with first type: " +
3489 (first == null ? null : first.getClass());
3490 }
3491
3492 return object.toString();
3493 } catch (Exception e) {
3494 return "<<exception>> " + object.getClass() + ":\n" + getFullStackTrace(e) + "\n";
3495 }
3496 }
3497
3498
3499
3500
3501
3502
3503
3504 public static boolean booleanValue(Object object) {
3505
3506 if (nullOrBlank(object)) {
3507 throw new RuntimeException(
3508 "Expecting something which can be converted to boolean, but is null or blank: '"
3509 + object + "'");
3510 }
3511
3512 if (object instanceof Boolean) {
3513 return (Boolean) object;
3514 }
3515 if (object instanceof String) {
3516 String string = (String) object;
3517 if (equalsIgnoreCase(string, "true")
3518 || equalsIgnoreCase(string, "t")
3519 || equalsIgnoreCase(string, "yes")
3520 || equalsIgnoreCase(string, "y")) {
3521 return true;
3522 }
3523 if (equalsIgnoreCase(string, "false")
3524 || equalsIgnoreCase(string, "f")
3525 || equalsIgnoreCase(string, "no")
3526 || equalsIgnoreCase(string, "n")) {
3527 return false;
3528 }
3529 throw new RuntimeException(
3530 "Invalid string to boolean conversion: '" + string
3531 + "' expecting true|false or t|f or yes|no or y|n case insensitive");
3532
3533 }
3534 throw new RuntimeException("Cant convert object to boolean: "
3535 + object.getClass());
3536
3537 }
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547 public static boolean booleanValue(Object object, boolean defaultBoolean) {
3548 if (nullOrBlank(object)) {
3549 return defaultBoolean;
3550 }
3551 return booleanValue(object);
3552 }
3553
3554
3555
3556
3557
3558
3559
3560 public static Boolean booleanObjectValue(Object object) {
3561 if (nullOrBlank(object)) {
3562 return null;
3563 }
3564 return booleanValue(object);
3565 }
3566
3567
3568
3569
3570
3571
3572
3573 public static boolean nullOrBlank(Object object) {
3574
3575 if (object == null) {
3576 return true;
3577 }
3578 if (object instanceof String && isBlank(((String) object))) {
3579 return true;
3580 }
3581 return false;
3582
3583 }
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593 public static Method getter(Class theClass, String fieldName, boolean callOnSupers,
3594 boolean throwExceptionIfNotFound) {
3595 String getterName = getterNameFromPropertyName(fieldName);
3596 return getterHelper(theClass, fieldName, getterName, callOnSupers, throwExceptionIfNotFound);
3597 }
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608 public static Method getterHelper(Class theClass, String fieldName, String getterName,
3609 boolean callOnSupers, boolean throwExceptionIfNotFound) {
3610 Method[] methods = retrieveDeclaredMethods(theClass);
3611 if (methods != null) {
3612 for (Method method : methods) {
3613 if (equals(getterName, method.getName()) && isGetter(method)) {
3614 return method;
3615 }
3616 }
3617 }
3618
3619
3620 if (callOnSupers && !theClass.equals(Object.class)) {
3621 return getterHelper(theClass.getSuperclass(), fieldName, getterName,
3622 callOnSupers, throwExceptionIfNotFound);
3623 }
3624
3625 if (throwExceptionIfNotFound) {
3626 throw new RuntimeException("Cant find getter: "
3627 + getterName + ", in: " + theClass
3628 + ", callOnSupers: " + callOnSupers);
3629 }
3630 return null;
3631 }
3632
3633
3634
3635
3636
3637
3638 public static String getterNameFromPropertyName(String propertyName) {
3639 return "get" + capitalize(propertyName);
3640 }
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653 @SuppressWarnings("unchecked")
3654 public static Set<Method> getters(Class theClass, Class superclassToStopAt,
3655 Class<? extends Annotation> markerAnnotation, Boolean includeAnnotation) {
3656 return gettersHelper(theClass, superclassToStopAt, null, true,
3657 markerAnnotation, includeAnnotation);
3658 }
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671 @SuppressWarnings("unchecked")
3672 static Set<Method> gettersHelper(Class theClass, Class superclassToStopAt, Class<?> fieldType,
3673 boolean includeSuperclassToStopAt,
3674 Class<? extends Annotation> markerAnnotation, Boolean includeAnnotation) {
3675
3676
3677 Set<Method> getterSet = null;
3678 String cacheKey = theClass + CACHE_SEPARATOR + superclassToStopAt + CACHE_SEPARATOR + fieldType + CACHE_SEPARATOR
3679 + includeSuperclassToStopAt + CACHE_SEPARATOR + markerAnnotation + CACHE_SEPARATOR + includeAnnotation;
3680 getterSet = getterSetCache().get(cacheKey);
3681 if (getterSet != null) {
3682 return getterSet;
3683 }
3684
3685 getterSet = new LinkedHashSet<Method>();
3686 gettersHelper(theClass, superclassToStopAt, fieldType, includeSuperclassToStopAt,
3687 markerAnnotation, getterSet, includeAnnotation);
3688
3689
3690 getterSetCache().put(cacheKey, getterSet);
3691
3692 return getterSet;
3693
3694 }
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707 @SuppressWarnings("unchecked")
3708 private static void gettersHelper(Class theClass, Class superclassToStopAt, Class<?> propertyType,
3709 boolean includeSuperclassToStopAt,
3710 Class<? extends Annotation> markerAnnotation, Set<Method> getterSet, Boolean includeAnnotation) {
3711
3712 Method[] methods = retrieveDeclaredMethods(theClass);
3713 if (length(methods) != 0) {
3714 for (Method method: methods) {
3715
3716 if (!isGetter(method)) {
3717 continue;
3718 }
3719
3720 if (markerAnnotation != null
3721 && (includeAnnotation != method.isAnnotationPresent(markerAnnotation))) {
3722 continue;
3723 }
3724
3725 if (propertyType != null && !propertyType.isAssignableFrom(method.getReturnType())) {
3726 continue;
3727 }
3728
3729
3730 getterSet.add(method);
3731 }
3732 }
3733
3734 if (theClass.equals(superclassToStopAt) || theClass.equals(Object.class)) {
3735 return;
3736 }
3737 Class superclass = theClass.getSuperclass();
3738 if (!includeSuperclassToStopAt && superclass.equals(superclassToStopAt)) {
3739 return;
3740 }
3741
3742 gettersHelper(superclass, superclassToStopAt, propertyType,
3743 includeSuperclassToStopAt, markerAnnotation, getterSet,
3744 includeAnnotation);
3745 }
3746
3747
3748
3749
3750
3751
3752
3753 public static boolean isGetter(Method method) {
3754
3755
3756 String methodName = method.getName();
3757 if (!methodName.startsWith("get") && !methodName.startsWith("is")) {
3758 return false;
3759 }
3760
3761
3762 if (method.getReturnType() == Void.TYPE) {
3763 return false;
3764 }
3765
3766
3767 if (length(method.getParameterTypes()) != 0) {
3768 return false;
3769 }
3770
3771
3772 if (Modifier.isStatic(method.getModifiers())) {
3773 return false;
3774 }
3775
3776 return true;
3777 }
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788 public static void assignSetter(Object invokeOn,
3789 String fieldName, Object dataToAssign, boolean typeCast) {
3790 Class invokeOnClass = invokeOn.getClass();
3791 try {
3792 Method setter = setter(invokeOnClass, fieldName, true, true);
3793 setter.setAccessible(true);
3794 if (typeCast) {
3795 dataToAssign = typeCast(dataToAssign, setter.getParameterTypes()[0]);
3796 }
3797 setter.invoke(invokeOn, new Object[]{dataToAssign});
3798 } catch (Exception e) {
3799 throw new RuntimeException("Problem assigning setter: " + fieldName
3800 + " on class: " + invokeOnClass + ", type of data is: " + className(dataToAssign), e);
3801 }
3802 }
3803
3804
3805
3806
3807
3808
3809
3810 public static boolean isSetter(Method method) {
3811
3812
3813 if (!method.getName().startsWith("set")) {
3814 return false;
3815 }
3816
3817
3818 if (method.getReturnType() != Void.TYPE) {
3819 return false;
3820 }
3821
3822
3823 if (length(method.getParameterTypes()) != 1) {
3824 return false;
3825 }
3826
3827
3828 if (Modifier.isStatic(method.getModifiers())) {
3829 return false;
3830 }
3831
3832 return true;
3833 }
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843 public static Method setter(Class theClass, String fieldName, boolean callOnSupers,
3844 boolean throwExceptionIfNotFound) {
3845 String setterName = setterNameFromPropertyName(fieldName);
3846 return setterHelper(theClass, fieldName, setterName, callOnSupers, throwExceptionIfNotFound);
3847 }
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858 public static Method setterHelper(Class theClass, String fieldName, String setterName,
3859 boolean callOnSupers, boolean throwExceptionIfNotFound) {
3860 Method[] methods = retrieveDeclaredMethods(theClass);
3861 if (methods != null) {
3862 for (Method method : methods) {
3863 if (equals(setterName, method.getName()) && isSetter(method)) {
3864 return method;
3865 }
3866 }
3867 }
3868
3869
3870 if (callOnSupers && !theClass.equals(Object.class)) {
3871 return setterHelper(theClass.getSuperclass(), fieldName, setterName,
3872 callOnSupers, throwExceptionIfNotFound);
3873 }
3874
3875 if (throwExceptionIfNotFound) {
3876 throw new RuntimeException("Cant find setter: "
3877 + setterName + ", in: " + theClass
3878 + ", callOnSupers: " + callOnSupers);
3879 }
3880 return null;
3881 }
3882
3883
3884
3885
3886
3887
3888 public static String setterNameFromPropertyName(String propertyName) {
3889 return "set" + capitalize(propertyName);
3890 }
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903 @SuppressWarnings("unchecked")
3904 public static Set<Method> setters(Class theClass, Class superclassToStopAt, Class<?> fieldType,
3905 boolean includeSuperclassToStopAt,
3906 Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) {
3907 return settersHelper(theClass, superclassToStopAt, fieldType,
3908 includeSuperclassToStopAt, markerAnnotation, includeAnnotation);
3909 }
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922 @SuppressWarnings("unchecked")
3923 static Set<Method> settersHelper(Class theClass, Class superclassToStopAt, Class<?> fieldType,
3924 boolean includeSuperclassToStopAt,
3925 Class<? extends Annotation> markerAnnotation, boolean includeAnnotation) {
3926
3927
3928 Set<Method> setterSet = null;
3929 String cacheKey = theClass + CACHE_SEPARATOR + superclassToStopAt + CACHE_SEPARATOR + fieldType + CACHE_SEPARATOR
3930 + includeSuperclassToStopAt + CACHE_SEPARATOR + markerAnnotation + CACHE_SEPARATOR + includeAnnotation;
3931 setterSet = setterSetCache().get(cacheKey);
3932 if (setterSet != null) {
3933 return setterSet;
3934 }
3935
3936 setterSet = new LinkedHashSet<Method>();
3937 settersHelper(theClass, superclassToStopAt, fieldType, includeSuperclassToStopAt,
3938 markerAnnotation, setterSet, includeAnnotation);
3939
3940
3941 setterSetCache().put(cacheKey, setterSet);
3942
3943 return setterSet;
3944
3945 }
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958 @SuppressWarnings("unchecked")
3959 private static void settersHelper(Class theClass, Class superclassToStopAt, Class<?> propertyType,
3960 boolean includeSuperclassToStopAt,
3961 Class<? extends Annotation> markerAnnotation, Set<Method> setterSet, Boolean includeAnnotation) {
3962
3963 Method[] methods = retrieveDeclaredMethods(theClass);
3964 if (length(methods) != 0) {
3965 for (Method method: methods) {
3966
3967 if (!isSetter(method)) {
3968 continue;
3969 }
3970
3971 if (markerAnnotation != null
3972 && (includeAnnotation != method.isAnnotationPresent(markerAnnotation))) {
3973 continue;
3974 }
3975
3976 if (propertyType != null && !propertyType.isAssignableFrom(method.getParameterTypes()[0])) {
3977 continue;
3978 }
3979
3980
3981 setterSet.add(method);
3982 }
3983 }
3984
3985 if (theClass.equals(superclassToStopAt) || theClass.equals(Object.class)) {
3986 return;
3987 }
3988 Class superclass = theClass.getSuperclass();
3989 if (!includeSuperclassToStopAt && superclass.equals(superclassToStopAt)) {
3990 return;
3991 }
3992
3993 settersHelper(superclass, superclassToStopAt, propertyType,
3994 includeSuperclassToStopAt, markerAnnotation, setterSet,
3995 includeAnnotation);
3996 }
3997
3998
3999
4000
4001
4002
4003 public static String propertyName(Method method) {
4004 String methodName = method.getName();
4005 boolean isGetter = methodName.startsWith("get");
4006 boolean isSetter = methodName.startsWith("set");
4007 boolean isIsser = methodName.startsWith("is");
4008 int expectedLength = isIsser ? 2 : 3;
4009 int length = methodName.length();
4010 if ((!(isGetter || isSetter || isIsser)) || (length <= expectedLength)) {
4011 throw new RuntimeException("Not a getter or setter: " + methodName);
4012 }
4013 char fourthCharLower = Character.toLowerCase(methodName.charAt(expectedLength));
4014
4015 if (length == expectedLength +1) {
4016 return Character.toString(fourthCharLower);
4017 }
4018
4019 return fourthCharLower + methodName.substring(expectedLength+1, length);
4020 }
4021
4022
4023
4024
4025
4026
4027
4028 public static Class propertyType(Class theClass, String propertyName) {
4029 Method method = getter(theClass, propertyName, true, false);
4030 if (method != null) {
4031 return method.getReturnType();
4032 }
4033
4034 method = setter(theClass, propertyName, true, false);
4035 if (method != null) {
4036 return method.getParameterTypes()[0];
4037 }
4038
4039 Field field = field(theClass, propertyName, true, true);
4040 return field.getType();
4041 }
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051 public static <T> T typeCast(Object value, Class<T> theClass) {
4052
4053 return typeCast(value, theClass, false, false);
4054 }
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072 public static File newFileUniqueName(String parentDirName, String namePrefix, String nameSuffix, boolean createFile) {
4073 DateFormat fileNameFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss_SSS");
4074 if (!isBlank(parentDirName)) {
4075
4076 if (!parentDirName.endsWith("/") && !parentDirName.endsWith("\\")) {
4077 parentDirName += File.separator;
4078 }
4079
4080
4081 File parentDir = new File(parentDirName);
4082 if (!parentDir.exists()) {
4083 if (!parentDir.mkdirs()) {
4084 throw new RuntimeException("Cant make dir: " + parentDir.getAbsolutePath());
4085 }
4086 } else {
4087 if (!parentDir.isDirectory()) {
4088 throw new RuntimeException("Parent dir is not a directory: " + parentDir.getAbsolutePath());
4089 }
4090 }
4091
4092 } else {
4093
4094 parentDirName = "";
4095 }
4096
4097 if (!nameSuffix.contains(".")) {
4098 nameSuffix = "." + nameSuffix;
4099 }
4100
4101 String fileName = parentDirName + namePrefix + "_" + fileNameFormat.format(new Date()) + nameSuffix;
4102 int dotLocation = fileName.lastIndexOf('.');
4103 String fileNamePre = fileName.substring(0,dotLocation);
4104 String fileNamePost = fileName.substring(dotLocation);
4105 File theFile = new File(fileName);
4106
4107 int i;
4108
4109 for (i=0;i<1000;i++) {
4110
4111 if (!theFile.exists()) {
4112 break;
4113 }
4114
4115 fileName = fileNamePre + "_" + i + fileNamePost;
4116 theFile = new File(fileName);
4117
4118 }
4119
4120 if (i>=1000) {
4121 throw new RuntimeException("Cant find filename to create: " + fileName);
4122 }
4123
4124 if (createFile) {
4125 try {
4126 if (!theFile.createNewFile()) {
4127 throw new RuntimeException("Cant create file, it returned false");
4128 }
4129 } catch (Exception e) {
4130 throw new RuntimeException("Cant create file: " + fileName + ", make sure " +
4131 "permissions and such are ok, or change file location in grouper.properties if applicable", e);
4132 }
4133 }
4134 return theFile;
4135 }
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148 public static Date dateValue(Object inputObject) {
4149 if (inputObject == null) {
4150 return null;
4151 }
4152
4153 if (inputObject instanceof java.util.Date) {
4154 return (Date)inputObject;
4155 }
4156
4157 if (inputObject instanceof String) {
4158 String input = (String)inputObject;
4159
4160 if (isBlank(input)) {
4161 return null;
4162 }
4163
4164 try {
4165 if (input.length() == 8) {
4166
4167 return dateFormat().parse(input);
4168 }
4169 if (!contains(input, '.')) {
4170 if (contains(input, '/')) {
4171 return dateMinutesSecondsFormat.parse(input);
4172 }
4173
4174 return dateMinutesSecondsNoSlashFormat.parse(input);
4175 }
4176 if (contains(input, '/')) {
4177
4178 int lastDotIndex = input.lastIndexOf('.');
4179 if (lastDotIndex == input.length() - 7) {
4180 String nonNanoInput = input.substring(0,input.length()-3);
4181 Date date = timestampFormat.parse(nonNanoInput);
4182
4183 String lastThree = input.substring(input.length()-3,input.length());
4184 int lastThreeInt = Integer.parseInt(lastThree);
4185 Timestamp timestamp = new Timestamp(date.getTime());
4186 timestamp.setNanos(timestamp.getNanos() + (lastThreeInt * 1000));
4187 return timestamp;
4188 }
4189 return timestampFormat.parse(input);
4190 }
4191
4192 return timestampNoSlashFormat.parse(input);
4193 } catch (ParseException pe) {
4194 throw new RuntimeException(errorStart + toStringForLog(input));
4195 }
4196 }
4197
4198 throw new RuntimeException("Cannot convert Object to date : " + toStringForLog(inputObject));
4199 }
4200
4201
4202
4203
4204
4205
4206 public static boolean isBlank(Object input) {
4207 if (null == input) {
4208 return true;
4209 }
4210 return (input instanceof String && isBlank((String)input));
4211 }
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224 @SuppressWarnings({ "unchecked", "cast" })
4225 public static <T> T typeCast(Object value, Class<T> theClass,
4226 boolean convertNullToDefaultPrimitive, boolean useNewInstanceHooks) {
4227
4228 if (Object.class.equals(theClass)) {
4229 return (T)value;
4230 }
4231
4232 if (value==null) {
4233 if (convertNullToDefaultPrimitive && theClass.isPrimitive()) {
4234 if ( theClass == boolean.class ) {
4235 return (T)Boolean.FALSE;
4236 }
4237 if ( theClass == char.class ) {
4238 return (T)(Object)0;
4239 }
4240
4241 return typeCast(0, theClass, false, false);
4242 }
4243 return null;
4244 }
4245
4246 if (theClass.isInstance(value)) {
4247 return (T)value;
4248 }
4249
4250
4251 if (theClass.isArray() && theClass.getComponentType() != null) {
4252 theClass = (Class<T>)theClass.getComponentType();
4253 }
4254 Object resultValue = null;
4255
4256 if (theClass.equals(Date.class)) {
4257 resultValue = dateValue(value);
4258 } else if (theClass.equals(String.class)) {
4259 resultValue = stringValue(value);
4260 } else if (theClass.equals(Timestamp.class)) {
4261 resultValue = toTimestamp(value);
4262 } else if (theClass.equals(Boolean.class) || theClass.equals(boolean.class)) {
4263 resultValue = booleanObjectValue(value);
4264 } else if (theClass.equals(Integer.class) || theClass.equals(int.class)) {
4265 resultValue = intObjectValue(value, true);
4266 } else if (theClass.equals(Double.class) || theClass.equals(double.class)) {
4267 resultValue = doubleObjectValue(value, true);
4268 } else if (theClass.equals(Float.class) || theClass.equals(float.class)) {
4269 resultValue = floatObjectValue(value, true);
4270 } else if (theClass.equals(Long.class) || theClass.equals(long.class)) {
4271 resultValue = longObjectValue(value, true);
4272 } else if (theClass.equals(Byte.class) || theClass.equals(byte.class)) {
4273 resultValue = byteObjectValue(value);
4274 } else if (theClass.equals(Character.class) || theClass.equals(char.class)) {
4275 resultValue = charObjectValue(value);
4276 } else if (theClass.equals(Short.class) || theClass.equals(short.class)) {
4277 resultValue = shortObjectValue(value);
4278 } else if ( theClass.isEnum() && (value instanceof String) ) {
4279 resultValue = Enum.valueOf((Class)theClass, (String) value);
4280 } else if ( theClass.equals(Class.class) && (value instanceof String) ) {
4281 resultValue = forName((String)value);
4282 } else if (useNewInstanceHooks && value instanceof String) {
4283 String stringValue = (String)value;
4284 if ( equals("null", stringValue)) {
4285 resultValue = null;
4286 } else if (equals("newInstance", stringValue)) {
4287 resultValue = newInstance(theClass);
4288 } else {
4289
4290 try {
4291 Constructor constructor = theClass.getConstructor(new Class[] {String.class} );
4292 resultValue = constructor.newInstance(new Object[] {stringValue} );
4293 } catch (Exception e) {
4294 throw new RuntimeException("Cant find constructor with string for class: " + theClass);
4295 }
4296 }
4297 } else {
4298 throw new RuntimeException("Cannot convert from type: " + value.getClass() + " to type: " + theClass);
4299 }
4300
4301 return (T)resultValue;
4302 }
4303
4304
4305
4306
4307
4308
4309 public static boolean isScalar(Class<?> type) {
4310
4311 if (type.isArray()) {
4312 return false;
4313 }
4314
4315
4316 if (type.isPrimitive()) {
4317 return true;
4318 }
4319
4320 if (Number.class.isAssignableFrom(type)) {
4321 return true;
4322 }
4323
4324 if (Date.class.isAssignableFrom(type)) {
4325 return true;
4326 }
4327 if (Character.class.equals(type)) {
4328 return true;
4329 }
4330
4331 if (CharSequence.class.equals(type) || CharSequence.class.isAssignableFrom(type)) {
4332 return true;
4333 }
4334 if (Class.class == type || Boolean.class == type || type.isEnum()) {
4335 return true;
4336 }
4337
4338 return false;
4339 }
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359 public static Timestamp toTimestamp(Object input) {
4360
4361 if (null == input) {
4362 return null;
4363 } else if (input instanceof java.sql.Timestamp) {
4364 return (Timestamp) input;
4365 } else if (input instanceof String) {
4366 return stringToTimestamp((String) input);
4367 } else if (input instanceof Date) {
4368 return new Timestamp(((Date)input).getTime());
4369 } else if (input instanceof java.sql.Date) {
4370 return new Timestamp(((java.sql.Date)input).getTime());
4371 } else {
4372 throw new RuntimeException("Cannot convert Object to timestamp : " + input);
4373 }
4374
4375 }
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385 public static String stringValue(Object input) {
4386
4387 if (input == null) {
4388 return (String) input;
4389 }
4390
4391 if (input instanceof Timestamp) {
4392
4393 return timestampToString((Timestamp) input);
4394 }
4395
4396 if (input instanceof Date) {
4397
4398 return stringValue((Date) input);
4399 }
4400
4401 if (input instanceof Number) {
4402 DecimalFormat decimalFormat = new DecimalFormat(
4403 "###################.###############");
4404 return decimalFormat.format(((Number) input).doubleValue());
4405
4406 }
4407
4408 return input.toString();
4409 }
4410
4411
4412
4413
4414
4415
4416 public synchronized static String timestampToString(Date timestamp) {
4417 if (timestamp == null) {
4418 return null;
4419 }
4420 return timestampFormat.format(timestamp);
4421 }
4422
4423
4424
4425
4426
4427
4428 synchronized static SimpleDateFormat dateFormat() {
4429 return dateFormat;
4430 }
4431
4432
4433
4434
4435
4436
4437 public static String stringValue(java.util.Date date) {
4438 synchronized (GrouperInstallerUtils.class) {
4439 if (date == null) {
4440 return null;
4441 }
4442
4443 String theString = dateFormat().format(date);
4444
4445 return theString;
4446 }
4447 }
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459 public static Timestamp stringToTimestamp(String input) {
4460 Date date = stringToTimestampHelper(input);
4461 if (date == null) {
4462 return null;
4463 }
4464
4465 if (date instanceof Timestamp) {
4466 return (Timestamp)date;
4467 }
4468 return new Timestamp(date.getTime());
4469 }
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482 synchronized static Date stringToTimestampHelper(String input) {
4483
4484 if (isBlank(input)) {
4485 return null;
4486 }
4487
4488 try {
4489
4490 if (equals("99999999", input)
4491 || equals("999999", input)) {
4492 input = "20991231";
4493 }
4494 if (input.length() == 8) {
4495
4496 return dateFormat().parse(input);
4497 }
4498 if (!contains(input, '.')) {
4499 if (contains(input, '/')) {
4500 return dateMinutesSecondsFormat.parse(input);
4501 }
4502
4503 return dateMinutesSecondsNoSlashFormat.parse(input);
4504 }
4505 if (contains(input, '/')) {
4506
4507 int lastDotIndex = input.lastIndexOf('.');
4508 if (lastDotIndex == input.length() - 7) {
4509 String nonNanoInput = input.substring(0,input.length()-3);
4510 Date date = timestampFormat.parse(nonNanoInput);
4511
4512 String lastThree = input.substring(input.length()-3,input.length());
4513 int lastThreeInt = Integer.parseInt(lastThree);
4514 Timestamp timestamp = new Timestamp(date.getTime());
4515 timestamp.setNanos(timestamp.getNanos() + (lastThreeInt * 1000));
4516 return timestamp;
4517 }
4518 return timestampFormat.parse(input);
4519 }
4520
4521 return timestampNoSlashFormat.parse(input);
4522 } catch (ParseException pe) {
4523 throw new RuntimeException(errorStart + input);
4524 }
4525 }
4526
4527
4528
4529
4530 private static final String errorStart = "Invalid timestamp, please use any of the formats: "
4531 + DATE_FORMAT + ", " + TIMESTAMP_FORMAT
4532 + ", " + DATE_MINUTES_SECONDS_FORMAT + ": ";
4533
4534
4535
4536
4537
4538
4539 public static BigDecimal bigDecimalObjectValue(Object input) {
4540 if (input instanceof BigDecimal) {
4541 return (BigDecimal)input;
4542 }
4543 if (isBlank(input)) {
4544 return null;
4545 }
4546 return BigDecimal.valueOf(doubleValue(input));
4547 }
4548
4549
4550
4551
4552
4553
4554 public static Byte byteObjectValue(Object input) {
4555 if (input instanceof Byte) {
4556 return (Byte)input;
4557 }
4558 if (isBlank(input)) {
4559 return null;
4560 }
4561 return Byte.valueOf(byteValue(input));
4562 }
4563
4564
4565
4566
4567
4568
4569 public static byte byteValue(Object input) {
4570 if (input instanceof String) {
4571 String string = (String)input;
4572 return Byte.parseByte(string);
4573 }
4574 if (input instanceof Number) {
4575 return ((Number)input).byteValue();
4576 }
4577 throw new RuntimeException("Cannot convert to byte: " + className(input));
4578 }
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589 public static Double doubleObjectValue(Object input, boolean allowNullBlank) {
4590
4591 if (input instanceof Double) {
4592 return (Double) input;
4593 }
4594
4595 if (allowNullBlank && isBlank(input)) {
4596 return null;
4597 }
4598
4599 return Double.valueOf(doubleValue(input));
4600 }
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610 public static double doubleValue(Object input) {
4611 if (input instanceof String) {
4612 String string = (String)input;
4613 return Double.parseDouble(string);
4614 }
4615 if (input instanceof Number) {
4616 return ((Number)input).doubleValue();
4617 }
4618 throw new RuntimeException("Cannot convert to double: " + className(input));
4619 }
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631 public static double doubleValueNoError(Object input) {
4632 if (input == null || (input instanceof String
4633 && isBlank((String)input))) {
4634 return NOT_FOUND;
4635 }
4636
4637 try {
4638 return doubleValue(input);
4639 } catch (Exception e) {
4640
4641 }
4642
4643 return NOT_FOUND;
4644 }
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655 public static Float floatObjectValue(Object input, boolean allowNullBlank) {
4656
4657 if (input instanceof Float) {
4658 return (Float) input;
4659 }
4660
4661 if (allowNullBlank && isBlank(input)) {
4662 return null;
4663 }
4664 return Float.valueOf(floatValue(input));
4665 }
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675 public static float floatValue(Object input) {
4676 if (input instanceof String) {
4677 String string = (String)input;
4678 return Float.parseFloat(string);
4679 }
4680 if (input instanceof Number) {
4681 return ((Number)input).floatValue();
4682 }
4683 throw new RuntimeException("Cannot convert to float: " + className(input));
4684 }
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695 public static float floatValueNoError(Object input) {
4696 if (input == null || (input instanceof String
4697 && isBlank((String)input))) {
4698 return NOT_FOUND;
4699 }
4700 try {
4701 return floatValue(input);
4702 } catch (Exception e) {
4703 e.printStackTrace();
4704 }
4705
4706 return NOT_FOUND;
4707 }
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718 public static Integer intObjectValue(Object input, boolean allowNullBlank) {
4719
4720 if (input instanceof Integer) {
4721 return (Integer) input;
4722 }
4723
4724 if (allowNullBlank && isBlank(input)) {
4725 return null;
4726 }
4727
4728 return Integer.valueOf(intValue(input));
4729 }
4730
4731
4732
4733
4734
4735
4736 public static int intValue(Object input) {
4737 if (input instanceof String) {
4738 String string = (String)input;
4739 return Integer.parseInt(string);
4740 }
4741 if (input instanceof Number) {
4742 return ((Number)input).intValue();
4743 }
4744 if (false) {
4745 if (input == null) {
4746 return 0;
4747 }
4748 if (input instanceof String || isBlank((String)input)) {
4749 return 0;
4750 }
4751 }
4752
4753 throw new RuntimeException("Cannot convert to int: " + className(input));
4754 }
4755
4756
4757
4758
4759
4760
4761
4762 public static int intValue(Object input, int valueIfNull) {
4763 if (input == null || "".equals(input)) {
4764 return valueIfNull;
4765 }
4766 return intObjectValue(input, false);
4767 }
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778 public static int intValueNoError(Object input) {
4779 if (input == null || (input instanceof String
4780 && isBlank((String)input))) {
4781 return NOT_FOUND;
4782 }
4783 try {
4784 return intValue(input);
4785 } catch (Exception e) {
4786
4787 }
4788
4789 return NOT_FOUND;
4790 }
4791
4792
4793 public static final int NOT_FOUND = -999999999;
4794
4795
4796
4797
4798 public static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809 public static Long longObjectValue(Object input, boolean allowNullBlank) {
4810
4811 if (input instanceof Long) {
4812 return (Long) input;
4813 }
4814
4815 if (allowNullBlank && isBlank(input)) {
4816 return null;
4817 }
4818
4819 return Long.valueOf(longValue(input));
4820 }
4821
4822
4823
4824
4825
4826
4827 public static long longValue(Object input) {
4828 if (input instanceof String) {
4829 String string = (String)input;
4830 return Long.parseLong(string);
4831 }
4832 if (input instanceof Number) {
4833 return ((Number)input).longValue();
4834 }
4835 throw new RuntimeException("Cannot convert to long: " + className(input));
4836 }
4837
4838
4839
4840
4841
4842
4843
4844 public static long longValue(Object input, long valueIfNull) {
4845 if (input == null || "".equals(input)) {
4846 return valueIfNull;
4847 }
4848 return longObjectValue(input, false);
4849 }
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860 public static long longValueNoError(Object input) {
4861 if (input == null || (input instanceof String
4862 && isBlank((String)input))) {
4863 return NOT_FOUND;
4864 }
4865 try {
4866 return longValue(input);
4867 } catch (Exception e) {
4868
4869 }
4870
4871 return NOT_FOUND;
4872 }
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882 public static Short shortObjectValue(Object input) {
4883
4884 if (input instanceof Short) {
4885 return (Short) input;
4886 }
4887
4888 if (isBlank(input)) {
4889 return null;
4890 }
4891
4892 return Short.valueOf(shortValue(input));
4893 }
4894
4895
4896
4897
4898
4899
4900 public static short shortValue(Object input) {
4901 if (input instanceof String) {
4902 String string = (String)input;
4903 return Short.parseShort(string);
4904 }
4905 if (input instanceof Number) {
4906 return ((Number)input).shortValue();
4907 }
4908 throw new RuntimeException("Cannot convert to short: " + className(input));
4909 }
4910
4911
4912
4913
4914
4915
4916 public static Character charObjectValue(Object input) {
4917 if (input instanceof Character) {
4918 return (Character) input;
4919 }
4920 if (isBlank(input)) {
4921 return null;
4922 }
4923 return new Character(charValue(input));
4924 }
4925
4926
4927
4928
4929
4930
4931 public static char charValue(Object input) {
4932 if (input instanceof Character) {
4933 return ((Character) input).charValue();
4934 }
4935
4936 if (input instanceof String) {
4937 String inputString = (String) input;
4938 if (inputString.length() == 1) {
4939 return inputString.charAt(0);
4940 }
4941 }
4942 throw new RuntimeException("Cannot convert to char: "
4943 + (input == null ? null : (input.getClass() + ", " + input)));
4944 }
4945
4946
4947
4948
4949
4950 public static void createParentDirectories(File file) {
4951 if (!file.getParentFile().exists()) {
4952 if (!file.getParentFile().mkdirs()) {
4953 throw new RuntimeException("Could not create directory : " + file.getParentFile());
4954 }
4955 }
4956 }
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966 public static void saveStringIntoFile(File file, String contents) {
4967 try {
4968 writeStringToFile(file, contents, "UTF-8");
4969 } catch (IOException ioe) {
4970 throw new RuntimeException(ioe);
4971 }
4972 }
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985 public static boolean saveStringIntoFile(File file, String contents,
4986 boolean onlyIfDifferentContents, boolean ignoreWhitespace) {
4987 if (onlyIfDifferentContents && file.exists()) {
4988 String fileContents = readFileIntoString(file);
4989 String compressedContents = contents;
4990 if (ignoreWhitespace) {
4991 compressedContents = replaceWhitespaceWithSpace(compressedContents);
4992 fileContents = replaceWhitespaceWithSpace(fileContents);
4993 }
4994
4995
4996 if (equals(fileContents, compressedContents)) {
4997 return false;
4998 }
4999
5000 }
5001 saveStringIntoFile(file, contents);
5002 return true;
5003 }
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022 public static void writeStringToFile(File file, String data, String encoding)
5023 throws IOException {
5024 OutputStream out = new java.io.FileOutputStream(file);
5025 try {
5026 out.write(data.getBytes(encoding));
5027 } finally {
5028 closeQuietly(out);
5029 }
5030 }
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045 public static void writeStringToFile(File file, String data) {
5046 try {
5047 writeStringToFile(file, data, "UTF-8");
5048 } catch (IOException ioe) {
5049 throw new RuntimeException(ioe);
5050 }
5051 }
5052
5053
5054
5055
5056
5057
5058
5059
5060 public static String readFileIntoString(File file) {
5061
5062 if (file == null) {
5063 return null;
5064 }
5065 try {
5066 return readFileToString(file, "UTF-8");
5067 } catch (IOException ioe) {
5068 throw new RuntimeException(ioe);
5069 }
5070 }
5071
5072
5073
5074
5075
5076
5077
5078 public static String readResourceIntoString(String resourceName, boolean allowNull) {
5079 if (isBlank(resourceName)) {
5080 if (allowNull) {
5081 return null;
5082 }
5083 throw new RuntimeException("Resource name is blank");
5084 }
5085 URL url = computeUrl(resourceName, allowNull);
5086
5087
5088 if (url == null && allowNull) {
5089 return null;
5090 }
5091
5092 InputStream inputStream = null;
5093 StringWriter stringWriter = new StringWriter();
5094 try {
5095 inputStream = url.openStream();
5096 copy(inputStream, stringWriter, "UTF-8");
5097 } catch (IOException ioe) {
5098 throw new RuntimeException("Error reading resource: '" + resourceName + "'", ioe);
5099 } finally {
5100 closeQuietly(inputStream);
5101 closeQuietly(stringWriter);
5102 }
5103 return stringWriter.toString();
5104 }
5105
5106
5107
5108
5109
5110
5111
5112 public static String readResourceIntoString(String resourceName, Class<?> classInJar) {
5113
5114 try {
5115 return readResourceIntoString(resourceName, false);
5116 } catch (Exception e) {
5117
5118 }
5119
5120
5121 File jarFile = classInJar == null ? null : jarFile(classInJar);
5122 File parentDir = jarFile == null ? null : jarFile.getParentFile();
5123 String fileName = parentDir == null ? null
5124 : (stripLastSlashIfExists(fileCanonicalPath(parentDir)) + File.separator + resourceName);
5125 File configFile = fileName == null ? null
5126 : new File(fileName);
5127
5128 return readFileIntoString(configFile);
5129 }
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146 public static String readFileToString(File file, String encoding) throws IOException {
5147 InputStream in = new java.io.FileInputStream(file);
5148 try {
5149 return toString(in, encoding);
5150 } finally {
5151 closeQuietly(in);
5152 }
5153 }
5154
5155
5156
5157
5158
5159
5160 public static String replaceWhitespaceWithSpace(String input) {
5161 if (input == null) {
5162 return input;
5163 }
5164 return input.replaceAll("\\s+", " ");
5165 }
5166
5167
5168
5169
5170
5171
5172 public static void closeQuietly(InputStream input) {
5173 if (input == null) {
5174 return;
5175 }
5176
5177 try {
5178 input.close();
5179 } catch (IOException ioe) {
5180 }
5181 }
5182
5183
5184
5185
5186
5187
5188 public static void closeQuietly(ZipFile input) {
5189 if (input == null) {
5190 return;
5191 }
5192
5193 try {
5194 input.close();
5195 } catch (IOException ioe) {
5196 }
5197 }
5198
5199
5200
5201
5202
5203
5204 public static void closeQuietly(OutputStream output) {
5205 if (output == null) {
5206 return;
5207 }
5208
5209 try {
5210 output.close();
5211 } catch (IOException ioe) {
5212 }
5213 }
5214
5215
5216
5217
5218
5219
5220
5221 public static void closeQuietly(Reader input) {
5222 if (input == null) {
5223 return;
5224 }
5225
5226 try {
5227 input.close();
5228 } catch (IOException ioe) {
5229 }
5230 }
5231
5232
5233
5234
5235
5236 public static void closeQuietly(Writer writer) {
5237 if (writer != null) {
5238 try {
5239 writer.close();
5240 } catch (IOException e) {
5241
5242 }
5243 }
5244 }
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255 public static String toString(InputStream input, String encoding) throws IOException {
5256 StringWriter sw = new StringWriter();
5257 copy(input, sw, encoding);
5258 return sw.toString();
5259 }
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271 public static void copy(InputStream input, Writer output, String encoding)
5272 throws IOException {
5273 InputStreamReader in = new InputStreamReader(input, encoding);
5274 copy(in, output);
5275 }
5276
5277
5278
5279
5280
5281
5282
5283
5284 public static int copy(Reader input, Writer output) throws IOException {
5285 char[] buffer = new char[DEFAULT_BUFFER_SIZE];
5286 int count = 0;
5287 int n = 0;
5288 while (-1 != (n = input.read(buffer))) {
5289 output.write(buffer, 0, n);
5290 count += n;
5291 }
5292 return count;
5293 }
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304 public static String convertLongToChar(long theLong) {
5305 if ((theLong < 0) || (theLong >= 62)) {
5306 throw new RuntimeException("convertLongToChar() "
5307 + " invalid input (not >=0 && <62: " + theLong);
5308 } else if (theLong < 26) {
5309 return "" + (char) ('a' + theLong);
5310 } else if (theLong < 52) {
5311 return "" + (char) ('A' + (theLong - 26));
5312 } else {
5313 return "" + (char) ('0' + (theLong - 52));
5314 }
5315 }
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326 public static String convertLongToCharSmall(long theLong) {
5327 if ((theLong < 0) || (theLong >= 36)) {
5328 throw new RuntimeException("convertLongToCharSmall() "
5329 + " invalid input (not >=0 && <36: " + theLong);
5330 } else if (theLong < 26) {
5331 return "" + (char) ('A' + theLong);
5332 } else {
5333 return "" + (char) ('0' + (theLong - 26));
5334 }
5335 }
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346 public static String convertLongToString(long theLong) {
5347 long quotient = theLong / 62;
5348 long remainder = theLong % 62;
5349
5350 if (quotient == 0) {
5351 return convertLongToChar(remainder);
5352 }
5353 StringBuffer result = new StringBuffer();
5354 result.append(convertLongToString(quotient));
5355 result.append(convertLongToChar(remainder));
5356
5357 return result.toString();
5358 }
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369 public static String convertLongToStringSmall(long theLong) {
5370 long quotient = theLong / 36;
5371 long remainder = theLong % 36;
5372
5373 if (quotient == 0) {
5374 return convertLongToCharSmall(remainder);
5375 }
5376 StringBuffer result = new StringBuffer();
5377 result.append(convertLongToStringSmall(quotient));
5378 result.append(convertLongToCharSmall(remainder));
5379
5380 return result.toString();
5381 }
5382
5383
5384
5385
5386
5387
5388
5389
5390 public static char incrementChar(char theChar) {
5391 if (theChar == 'Z') {
5392 return '0';
5393 }
5394
5395 if (theChar == '9') {
5396 return 'A';
5397 }
5398
5399 return ++theChar;
5400 }
5401
5402
5403
5404
5405
5406 public static boolean isWindows() {
5407 String osname = defaultString(System.getProperty("os.name"));
5408
5409 if (contains(osname.toLowerCase(), "windows")) {
5410 return true;
5411 }
5412 return false;
5413 }
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423 public static char[] incrementStringInt(char[] string) {
5424 if (string == null) {
5425 return string;
5426 }
5427
5428
5429 int i = 0;
5430
5431 for (i = string.length - 1; i >= 0; i--) {
5432 char inc = string[i];
5433 inc = incrementChar(inc);
5434 string[i] = inc;
5435
5436 if (inc != 'A') {
5437 break;
5438 }
5439 }
5440
5441
5442 if (i < 0) {
5443 return ("A" + new String(string)).toCharArray();
5444 }
5445
5446 return string;
5447 }
5448
5449
5450
5451
5452
5453
5454 public synchronized static Properties propertiesFromResourceName(String resourceName) {
5455 return propertiesFromResourceName(resourceName, true, true, null, null);
5456 }
5457
5458
5459
5460
5461 private static Log LOG = GrouperInstallerUtils.retrieveLog(GrouperInstallerUtils.class);
5462
5463
5464
5465
5466 public static void propertiesCacheClear() {
5467 resourcePropertiesCache.clear();
5468 }
5469
5470
5471
5472
5473
5474
5475 public static Properties propertiesFromFile(File propertiesFile) {
5476 Properties properties = new Properties();
5477 FileInputStream fileInputStream = null;
5478 try {
5479 fileInputStream = new FileInputStream(propertiesFile);
5480 properties.load(fileInputStream);
5481 return properties;
5482 } catch (IOException ioe) {
5483 throw new RuntimeException("Probably reading properties from file: "
5484 + (propertiesFile == null ? null : propertiesFile.getAbsolutePath()), ioe);
5485 } finally {
5486 closeQuietly(fileInputStream);
5487 }
5488 }
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499 public synchronized static Properties propertiesFromResourceName(String resourceName, boolean useCache,
5500 boolean exceptionIfNotExist, Class<?> classInJar, StringBuilder callingLog) {
5501
5502 Properties properties = resourcePropertiesCache.get(resourceName);
5503
5504 if (!useCache || !resourcePropertiesCache.containsKey(resourceName)) {
5505
5506 properties = new Properties();
5507
5508 boolean success = false;
5509
5510 URL url = computeUrl(resourceName, true);
5511 InputStream inputStream = null;
5512 try {
5513 inputStream = url.openStream();
5514 properties.load(inputStream);
5515 success = true;
5516 String theLog = "Reading resource: " + resourceName + ", from: " + url.toURI();
5517 if (LOG != null) {
5518 LOG.debug(theLog);
5519 }
5520 if (callingLog != null) {
5521 callingLog.append(theLog);
5522 }
5523 } catch (Exception e) {
5524
5525
5526 properties.clear();
5527
5528
5529 File jarFile = classInJar == null ? null : jarFile(classInJar);
5530 File parentDir = jarFile == null ? null : jarFile.getParentFile();
5531 String fileName = parentDir == null ? null
5532 : (stripLastSlashIfExists(fileCanonicalPath(parentDir)) + File.separator + resourceName);
5533 File configFile = fileName == null ? null
5534 : new File(fileName);
5535
5536 try {
5537
5538 if (configFile != null && configFile.exists() && configFile.isFile()) {
5539 inputStream = new FileInputStream(configFile);
5540 properties.load(inputStream);
5541 success = true;
5542 String theLog = "Reading resource: " + resourceName + ", from: " + fileCanonicalPath(configFile);
5543 if (LOG != null) {
5544 LOG.debug(theLog);
5545 }
5546 if (callingLog != null) {
5547 callingLog.append(theLog);
5548 }
5549 }
5550
5551 } catch (Exception e2) {
5552 if (LOG != null) {
5553 LOG.debug("Error reading from file for resource: " + resourceName + ", file: " + fileName, e2);
5554 }
5555 }
5556 if (!success) {
5557 properties = null;
5558 if (exceptionIfNotExist) {
5559 throw new RuntimeException("Problem with resource: '" + resourceName + "'", e);
5560 }
5561 }
5562 } finally {
5563 closeQuietly(inputStream);
5564
5565 if (useCache && properties != null && properties.size() > 0) {
5566 resourcePropertiesCache.put(resourceName, properties);
5567 }
5568 }
5569 }
5570
5571 return properties;
5572 }
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584 public static <E extends Enum<?>> E enumValueOfIgnoreCase(Class<E> theEnumClass, String string,
5585 boolean exceptionOnNotFound) throws RuntimeException {
5586
5587 return enumValueOfIgnoreCase(theEnumClass, string, exceptionOnNotFound, true);
5588
5589 }
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602 public static <E extends Enum<?>> E enumValueOfIgnoreCase(Class<E> theEnumClass, String string,
5603 boolean exceptionOnNotFound, boolean exceptionIfInvalid) throws RuntimeException {
5604
5605 if (!exceptionOnNotFound && isBlank(string)) {
5606 return null;
5607 }
5608 for (E e : theEnumClass.getEnumConstants()) {
5609 if (equalsIgnoreCase(string, e.name())) {
5610 return e;
5611 }
5612 }
5613 if (!exceptionIfInvalid) {
5614 return null;
5615 }
5616 StringBuilder error = new StringBuilder(
5617 "Cant find " + theEnumClass.getSimpleName() + " from string: '").append(string);
5618 error.append("', expecting one of: ");
5619 for (E e : theEnumClass.getEnumConstants()) {
5620 error.append(e.name()).append(", ");
5621 }
5622 throw new RuntimeException(error.toString());
5623
5624 }
5625
5626
5627
5628
5629
5630
5631
5632 public static Object propertyValue(Object object, String property) {
5633 Method getter = getter(object.getClass(), property, true, true);
5634 Object result = invokeMethod(getter, object);
5635 return result;
5636 }
5637
5638
5639
5640
5641
5642
5643
5644 public static String propertiesValue(Properties properties, String key) {
5645 return propertiesValue(properties, null, key);
5646 }
5647
5648
5649
5650
5651
5652
5653
5654
5655 public static String propertiesValue(Properties properties, Map<String, String> overrideMap, String key) {
5656 return propertiesValue(properties, overrideMap, null, key);
5657 }
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667 public static String propertiesValue(Properties properties, Map<String, String> overrideMap, Map<String, String> overrideMap2, String key) {
5668 String value = overrideMap == null ? null : overrideMap.get(key);
5669 if (isBlank(value)) {
5670 value = overrideMap2 == null ? null : overrideMap2.get(key);
5671 }
5672 if (isBlank(value)) {
5673 value = properties.getProperty(key);
5674 }
5675 value = trim(value);
5676 value = substituteCommonVars(value);
5677 return value;
5678 }
5679
5680
5681
5682
5683
5684
5685 public static String substituteCommonVars(String string) {
5686 if (string == null) {
5687 return string;
5688 }
5689
5690 if (string.indexOf('$') < 0) {
5691 return string;
5692 }
5693
5694 string = GrouperInstallerUtils.replace(string, "$space$", " ");
5695
5696
5697 string = GrouperInstallerUtils.replace(string, "$newline$", "\n");
5698 return string;
5699 }
5700
5701
5702
5703
5704
5705
5706
5707
5708 public static boolean propertiesValueBoolean(Properties properties,
5709 String propertyName, boolean defaultValue) {
5710 return propertiesValueBoolean(properties, null, propertyName, defaultValue);
5711 }
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723 public static boolean propertiesValueBoolean(String resourceName, Properties properties,
5724 Map<String, String> overrideMap, String propertyName, boolean defaultValue, boolean required) {
5725 propertyValidateValueBoolean(resourceName, properties, overrideMap, propertyName, required, true);
5726
5727 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
5728
5729 return propertiesValueBoolean(properties, threadLocalMap, overrideMap, propertyName, defaultValue);
5730 }
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742 public static int propertiesValueInt(String resourceName, Properties properties,
5743 Map<String, String> overrideMap, String propertyName, int defaultValue, boolean required) {
5744
5745 propertyValidateValueInt(resourceName, properties, overrideMap, propertyName, required, true);
5746
5747 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
5748
5749 return propertiesValueInt(properties, threadLocalMap, overrideMap, propertyName, defaultValue);
5750 }
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761 public static String propertiesValue(String resourceName, Properties properties,
5762 Map<String, String> overrideMap, String propertyName, boolean required) {
5763
5764 if (required) {
5765 propertyValidateValueRequired(resourceName, properties, overrideMap, propertyName, true);
5766 }
5767 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
5768
5769 return propertiesValue(properties, threadLocalMap, overrideMap, propertyName);
5770 }
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780 public static int propertiesValueInt(Properties properties,
5781 Map<String, String> overrideMap, String propertyName, int defaultValue) {
5782 return propertiesValueInt(properties, overrideMap, null, propertyName, defaultValue);
5783 }
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795 public static int propertiesValueInt(Properties properties,
5796 Map<String, String> overrideMap, Map<String, String> overrideMap2, String propertyName, int defaultValue) {
5797
5798 String value = propertiesValue(properties, overrideMap, overrideMap2, propertyName);
5799 if (isBlank(value)) {
5800 return defaultValue;
5801 }
5802
5803 try {
5804 return intValue(value);
5805 } catch (Exception e) {}
5806
5807 throw new RuntimeException("Invalid int value: '" + value + "' for property: " + propertyName + " in grouper.properties");
5808
5809 }
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819 public static boolean propertiesValueBoolean(Properties properties,
5820 Map<String, String> overrideMap, String propertyName, boolean defaultValue) {
5821 return propertiesValueBoolean(properties, overrideMap, null, propertyName, defaultValue);
5822 }
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833 public static boolean propertiesValueBoolean(Properties properties,
5834 Map<String, String> overrideMap, Map<String, String> overrideMap2, String propertyName, boolean defaultValue) {
5835
5836
5837 String value = propertiesValue(properties, overrideMap, overrideMap2, propertyName);
5838 if (isBlank(value)) {
5839 return defaultValue;
5840 }
5841
5842 if ("true".equalsIgnoreCase(value)) {
5843 return true;
5844 }
5845 if ("false".equalsIgnoreCase(value)) {
5846 return false;
5847 }
5848 if ("t".equalsIgnoreCase(value)) {
5849 return true;
5850 }
5851 if ("f".equalsIgnoreCase(value)) {
5852 return false;
5853 }
5854 throw new RuntimeException("Invalid boolean value: '" + value + "' for property: " + propertyName + " in properties file");
5855
5856 }
5857
5858
5859
5860
5861
5862 public static void closeQuietly(Connection connection) {
5863 if (connection != null) {
5864 try {
5865 connection.close();
5866 } catch (Exception e) {
5867
5868 }
5869 }
5870 }
5871
5872
5873
5874
5875
5876 public static void closeQuietly(Statement statement) {
5877 if (statement != null) {
5878 try {
5879 statement.close();
5880 } catch (Exception e) {
5881
5882 }
5883 }
5884 }
5885
5886
5887
5888
5889
5890 public static void closeQuietly(ResultSet resultSet) {
5891 if (resultSet != null) {
5892 try {
5893 resultSet.close();
5894 } catch (Exception e) {
5895
5896 }
5897 }
5898 }
5899
5900
5901 private static String hostname = null;
5902
5903
5904
5905
5906
5907 public static String hostname() {
5908
5909 if (isBlank(hostname)) {
5910
5911
5912 hostname = "unknown";
5913 try {
5914 InetAddress addr = InetAddress.getLocalHost();
5915
5916
5917 hostname = addr.getHostName();
5918 } catch (Exception e) {
5919 System.err.println("Cant find servers hostname: ");
5920 e.printStackTrace();
5921 }
5922 }
5923
5924 return hostname;
5925 }
5926
5927
5928
5929
5930
5931
5932 public static boolean isAscii(char input) {
5933 return input < 128;
5934 }
5935
5936
5937
5938
5939
5940
5941 public static int lengthAscii(String input) {
5942 if (input == null) {
5943 return 0;
5944 }
5945
5946 int utfLength = input.length();
5947
5948 int extras = 0;
5949 for (int i=0;i<utfLength;i++) {
5950
5951 if (!isAscii(input.charAt(i))) {
5952 extras++;
5953 }
5954 }
5955 return utfLength + extras;
5956 }
5957
5958
5959
5960
5961
5962 public static void rollbackQuietly(Connection connection) {
5963 if (connection != null) {
5964 try {
5965 connection.rollback();
5966 } catch (Exception e) {
5967
5968 }
5969 }
5970 }
5971
5972
5973
5974
5975
5976
5977
5978 public static String truncateAscii(String input, int requiredLength) {
5979 if (input == null) {
5980 return input;
5981 }
5982
5983 int utfLength = input.length();
5984
5985
5986 if (utfLength * 2 < requiredLength) {
5987 return input;
5988 }
5989
5990
5991 int asciiLength = 0;
5992 for (int i=0;i<utfLength;i++) {
5993
5994 asciiLength++;
5995
5996
5997 if (!isAscii(input.charAt(i))) {
5998 asciiLength++;
5999 }
6000
6001
6002 if (asciiLength > requiredLength) {
6003
6004 return input.substring(0,i);
6005 }
6006 }
6007
6008 return input;
6009 }
6010
6011
6012
6013
6014
6015
6016
6017 public static String readFromFileIfFile(String in, boolean disableExternalFileLookup) {
6018
6019 String theIn = in;
6020
6021 if (File.separatorChar == '/') {
6022 theIn = replace(theIn, "\\", "/");
6023 } else {
6024 theIn = replace(theIn, "/", "\\");
6025 }
6026
6027
6028 if (theIn.indexOf(File.separatorChar) != -1 && !disableExternalFileLookup) {
6029
6030 theIn = readFileIntoString(new File(theIn));
6031 return theIn;
6032 }
6033 return in;
6034
6035 }
6036
6037
6038
6039
6040
6041
6042 public static void mkdirs(File dir) {
6043 if (!dir.exists()) {
6044 if (!dir.mkdirs()) {
6045 throw new RuntimeException("Could not create directory : " + dir.getParentFile());
6046 }
6047 return;
6048 }
6049 if (!dir.isDirectory()) {
6050 throw new RuntimeException("Should be a directory but is not: " + dir);
6051 }
6052 }
6053
6054
6055
6056
6057
6058
6059
6060
6061 public static boolean equals(String first, String second) {
6062 if (first == second) {
6063 return true;
6064 }
6065 if (first == null || second == null) {
6066 return false;
6067 }
6068 return first.equals(second);
6069 }
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086 public static boolean isBlank(String str) {
6087 int strLen;
6088 if (str == null || (strLen = str.length()) == 0) {
6089 return true;
6090 }
6091 for (int i = 0; i < strLen; i++) {
6092 if ((Character.isWhitespace(str.charAt(i)) == false)) {
6093 return false;
6094 }
6095 }
6096 return true;
6097 }
6098
6099
6100
6101
6102
6103
6104 public static boolean isNotBlank(String str) {
6105 return !isBlank(str);
6106 }
6107
6108
6109
6110
6111
6112
6113 public static String trim(String str) {
6114 return str == null ? null : str.trim();
6115 }
6116
6117
6118
6119
6120
6121
6122
6123 public static boolean equalsIgnoreCase(String str1, String str2) {
6124 return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
6125 }
6126
6127
6128
6129
6130
6131
6132 public static String trimToEmpty(String str) {
6133 return str == null ? "" : str.trim();
6134 }
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168 public static String abbreviate(String str, int maxWidth) {
6169 return abbreviate(str, 0, maxWidth);
6170 }
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207 public static String abbreviate(String str, int offset, int maxWidth) {
6208 if (str == null) {
6209 return null;
6210 }
6211 if (maxWidth < 4) {
6212 throw new IllegalArgumentException("Minimum abbreviation width is 4");
6213 }
6214 if (str.length() <= maxWidth) {
6215 return str;
6216 }
6217 if (offset > str.length()) {
6218 offset = str.length();
6219 }
6220 if ((str.length() - offset) < (maxWidth - 3)) {
6221 offset = str.length() - (maxWidth - 3);
6222 }
6223 if (offset <= 4) {
6224 return str.substring(0, maxWidth - 3) + "...";
6225 }
6226 if (maxWidth < 7) {
6227 throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
6228 }
6229 if ((offset + (maxWidth - 3)) < str.length()) {
6230 return "..." + abbreviate(str.substring(offset), maxWidth - 3);
6231 }
6232 return "..." + str.substring(str.length() - (maxWidth - 3));
6233 }
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259 public static String[] split(String str) {
6260 return split(str, null, -1);
6261 }
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289 public static String[] split(String str, char separatorChar) {
6290 return splitWorker(str, separatorChar, false);
6291 }
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318 public static String[] split(String str, String separatorChars) {
6319 return splitWorker(str, separatorChars, -1, false);
6320 }
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352 public static String[] split(String str, String separatorChars, int max) {
6353 return splitWorker(str, separatorChars, max, false);
6354 }
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380 public static String[] splitByWholeSeparator(String str, String separator) {
6381 return splitByWholeSeparator(str, separator, -1);
6382 }
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411 @SuppressWarnings("unchecked")
6412 public static String[] splitByWholeSeparator(String str, String separator, int max) {
6413 if (str == null) {
6414 return null;
6415 }
6416
6417 int len = str.length();
6418
6419 if (len == 0) {
6420 return EMPTY_STRING_ARRAY;
6421 }
6422
6423 if ((separator == null) || ("".equals(separator))) {
6424
6425 return split(str, null, max);
6426 }
6427
6428 int separatorLength = separator.length();
6429
6430 ArrayList substrings = new ArrayList();
6431 int numberOfSubstrings = 0;
6432 int beg = 0;
6433 int end = 0;
6434 while (end < len) {
6435 end = str.indexOf(separator, beg);
6436
6437 if (end > -1) {
6438 if (end > beg) {
6439 numberOfSubstrings += 1;
6440
6441 if (numberOfSubstrings == max) {
6442 end = len;
6443 substrings.add(str.substring(beg));
6444 } else {
6445
6446
6447 substrings.add(str.substring(beg, end));
6448
6449
6450
6451
6452 beg = end + separatorLength;
6453 }
6454 } else {
6455
6456 beg = end + separatorLength;
6457 }
6458 } else {
6459
6460 substrings.add(str.substring(beg));
6461 end = len;
6462 }
6463 }
6464
6465 return (String[]) substrings.toArray(new String[substrings.size()]);
6466 }
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493 public static String[] splitPreserveAllTokens(String str) {
6494 return splitWorker(str, null, -1, true);
6495 }
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529 public static String[] splitPreserveAllTokens(String str, char separatorChar) {
6530 return splitWorker(str, separatorChar, true);
6531 }
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545 @SuppressWarnings("unchecked")
6546 private static String[] splitWorker(String str, char separatorChar,
6547 boolean preserveAllTokens) {
6548
6549
6550 if (str == null) {
6551 return null;
6552 }
6553 int len = str.length();
6554 if (len == 0) {
6555 return EMPTY_STRING_ARRAY;
6556 }
6557 List list = new ArrayList();
6558 int i = 0, start = 0;
6559 boolean match = false;
6560 boolean lastMatch = false;
6561 while (i < len) {
6562 if (str.charAt(i) == separatorChar) {
6563 if (match || preserveAllTokens) {
6564 list.add(str.substring(start, i));
6565 match = false;
6566 lastMatch = true;
6567 }
6568 start = ++i;
6569 continue;
6570 }
6571 lastMatch = false;
6572 match = true;
6573 i++;
6574 }
6575 if (match || (preserveAllTokens && lastMatch)) {
6576 list.add(str.substring(start, i));
6577 }
6578 return (String[]) list.toArray(new String[list.size()]);
6579 }
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614 public static String[] splitPreserveAllTokens(String str, String separatorChars) {
6615 return splitWorker(str, separatorChars, -1, true);
6616 }
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654 public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) {
6655 return splitWorker(str, separatorChars, max, true);
6656 }
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672 @SuppressWarnings("unchecked")
6673 private static String[] splitWorker(String str, String separatorChars, int max,
6674 boolean preserveAllTokens) {
6675
6676
6677
6678
6679 if (str == null) {
6680 return null;
6681 }
6682 int len = str.length();
6683 if (len == 0) {
6684 return EMPTY_STRING_ARRAY;
6685 }
6686 List list = new ArrayList();
6687 int sizePlus1 = 1;
6688 int i = 0, start = 0;
6689 boolean match = false;
6690 boolean lastMatch = false;
6691 if (separatorChars == null) {
6692
6693 while (i < len) {
6694 if (Character.isWhitespace(str.charAt(i))) {
6695 if (match || preserveAllTokens) {
6696 lastMatch = true;
6697 if (sizePlus1++ == max) {
6698 i = len;
6699 lastMatch = false;
6700 }
6701 list.add(str.substring(start, i));
6702 match = false;
6703 }
6704 start = ++i;
6705 continue;
6706 }
6707 lastMatch = false;
6708 match = true;
6709 i++;
6710 }
6711 } else if (separatorChars.length() == 1) {
6712
6713 char sep = separatorChars.charAt(0);
6714 while (i < len) {
6715 if (str.charAt(i) == sep) {
6716 if (match || preserveAllTokens) {
6717 lastMatch = true;
6718 if (sizePlus1++ == max) {
6719 i = len;
6720 lastMatch = false;
6721 }
6722 list.add(str.substring(start, i));
6723 match = false;
6724 }
6725 start = ++i;
6726 continue;
6727 }
6728 lastMatch = false;
6729 match = true;
6730 i++;
6731 }
6732 } else {
6733
6734 while (i < len) {
6735 if (separatorChars.indexOf(str.charAt(i)) >= 0) {
6736 if (match || preserveAllTokens) {
6737 lastMatch = true;
6738 if (sizePlus1++ == max) {
6739 i = len;
6740 lastMatch = false;
6741 }
6742 list.add(str.substring(start, i));
6743 match = false;
6744 }
6745 start = ++i;
6746 continue;
6747 }
6748 lastMatch = false;
6749 match = true;
6750 i++;
6751 }
6752 }
6753 if (match || (preserveAllTokens && lastMatch)) {
6754 list.add(str.substring(start, i));
6755 }
6756 return (String[]) list.toArray(new String[list.size()]);
6757 }
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782 public static String join(Object[] array) {
6783 return join(array, null);
6784 }
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808 public static String join(Object[] array, char separator) {
6809 if (array == null) {
6810 return null;
6811 }
6812 int arraySize = array.length;
6813 int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString()
6814 .length()) + 1)
6815 * arraySize);
6816 StringBuffer buf = new StringBuffer(bufSize);
6817
6818 for (int i = 0; i < arraySize; i++) {
6819 if (i > 0) {
6820 buf.append(separator);
6821 }
6822 if (array[i] != null) {
6823 buf.append(array[i]);
6824 }
6825 }
6826 return buf.toString();
6827 }
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852 public static String join(Object[] array, String separator) {
6853 if (array == null) {
6854 return null;
6855 }
6856 if (separator == null) {
6857 separator = "";
6858 }
6859 int arraySize = array.length;
6860
6861
6862
6863
6864 int bufSize = ((arraySize == 0) ? 0 : arraySize
6865 * ((array[0] == null ? 16 : array[0].toString().length()) + separator.length()));
6866
6867 StringBuffer buf = new StringBuffer(bufSize);
6868
6869 for (int i = 0; i < arraySize; i++) {
6870 if (i > 0) {
6871 buf.append(separator);
6872 }
6873 if (array[i] != null) {
6874 buf.append(array[i]);
6875 }
6876 }
6877 return buf.toString();
6878 }
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894 public static String join(Iterator iterator, char separator) {
6895 if (iterator == null) {
6896 return null;
6897 }
6898 StringBuffer buf = new StringBuffer(256);
6899 while (iterator.hasNext()) {
6900 Object obj = iterator.next();
6901 if (obj != null) {
6902 buf.append(obj);
6903 }
6904 if (iterator.hasNext()) {
6905 buf.append(separator);
6906 }
6907 }
6908 return buf.toString();
6909 }
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924 public static String join(Iterator iterator, String separator) {
6925 if (iterator == null) {
6926 return null;
6927 }
6928 StringBuffer buf = new StringBuffer(256);
6929 while (iterator.hasNext()) {
6930 Object obj = iterator.next();
6931 if (obj != null) {
6932 buf.append(obj);
6933 }
6934 if ((separator != null) && iterator.hasNext()) {
6935 buf.append(separator);
6936 }
6937 }
6938 return buf.toString();
6939 }
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956 public static String defaultString(String str) {
6957 return str == null ? "" : str;
6958 }
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976 public static String defaultString(String str, String defaultStr) {
6977 return str == null ? defaultStr : str;
6978 }
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995 public static String defaultIfEmpty(String str, String defaultStr) {
6996 return isEmpty(str) ? defaultStr : str;
6997 }
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016 public static String capitalize(String str) {
7017 int strLen;
7018 if (str == null || (strLen = str.length()) == 0) {
7019 return str;
7020 }
7021 return new StringBuffer(strLen).append(Character.toTitleCase(str.charAt(0))).append(
7022 str.substring(1)).toString();
7023 }
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044 public static boolean contains(String str, char searchChar) {
7045 if (isEmpty(str)) {
7046 return false;
7047 }
7048 return str.indexOf(searchChar) >= 0;
7049 }
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072 public static boolean contains(String str, String searchStr) {
7073 if (str == null || searchStr == null) {
7074 return false;
7075 }
7076 return str.indexOf(searchStr) >= 0;
7077 }
7078
7079
7080
7081
7082 public static final String[] EMPTY_STRING_ARRAY = new String[0];
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103 public static boolean equals(Object object1, Object object2) {
7104 if (object1 == object2) {
7105 return true;
7106 }
7107 if ((object1 == null) || (object2 == null)) {
7108 return false;
7109 }
7110 return object1.equals(object2);
7111 }
7112
7113
7114
7115
7116
7117
7118
7119
7120 public static String getFullStackTrace(Throwable throwable) {
7121 StringWriter sw = new StringWriter();
7122 PrintWriter pw = new PrintWriter(sw, true);
7123 Throwable[] ts = getThrowables(throwable);
7124 for (int i = 0; i < ts.length; i++) {
7125 ts[i].printStackTrace(pw);
7126 if (isNestedThrowable(ts[i])) {
7127 break;
7128 }
7129 }
7130 return sw.getBuffer().toString();
7131 }
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145 @SuppressWarnings("unchecked")
7146 public static Throwable[] getThrowables(Throwable throwable) {
7147 List list = new ArrayList();
7148 while (throwable != null) {
7149 list.add(throwable);
7150 throwable = getCause(throwable);
7151 }
7152 return (Throwable[]) list.toArray(new Throwable[list.size()]);
7153 }
7154
7155
7156
7157
7158 private static String[] CAUSE_METHOD_NAMES = {
7159 "getCause",
7160 "getNextException",
7161 "getTargetException",
7162 "getException",
7163 "getSourceException",
7164 "getRootCause",
7165 "getCausedByException",
7166 "getNested",
7167 "getLinkedException",
7168 "getNestedException",
7169 "getLinkedCause",
7170 "getThrowable",
7171 };
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182 public static boolean isNestedThrowable(Throwable throwable) {
7183 if (throwable == null) {
7184 return false;
7185 }
7186
7187 if (throwable instanceof SQLException) {
7188 return true;
7189 } else if (throwable instanceof InvocationTargetException) {
7190 return true;
7191 } else if (isThrowableNested()) {
7192 return true;
7193 }
7194
7195 Class cls = throwable.getClass();
7196 for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
7197 try {
7198 Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], (Class[])null);
7199 if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
7200 return true;
7201 }
7202 } catch (NoSuchMethodException ignored) {
7203 } catch (SecurityException ignored) {
7204 }
7205 }
7206
7207 try {
7208 Field field = cls.getField("detail");
7209 if (field != null) {
7210 return true;
7211 }
7212 } catch (NoSuchFieldException ignored) {
7213 } catch (SecurityException ignored) {
7214 }
7215
7216 return false;
7217 }
7218
7219
7220
7221
7222 private static final Method THROWABLE_CAUSE_METHOD;
7223 static {
7224 Method getCauseMethod;
7225 try {
7226 getCauseMethod = Throwable.class.getMethod("getCause", (Class[])null);
7227 } catch (Exception e) {
7228 getCauseMethod = null;
7229 }
7230 THROWABLE_CAUSE_METHOD = getCauseMethod;
7231 }
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241 public static boolean isThrowableNested() {
7242 return THROWABLE_CAUSE_METHOD != null;
7243 }
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274 public static Throwable getCause(Throwable throwable) {
7275 return getCause(throwable, CAUSE_METHOD_NAMES);
7276 }
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296 public static Throwable getCause(Throwable throwable, String[] methodNames) {
7297 if (throwable == null) {
7298 return null;
7299 }
7300 Throwable cause = getCauseUsingWellKnownTypes(throwable);
7301 if (cause == null) {
7302 if (methodNames == null) {
7303 methodNames = CAUSE_METHOD_NAMES;
7304 }
7305 for (int i = 0; i < methodNames.length; i++) {
7306 String methodName = methodNames[i];
7307 if (methodName != null) {
7308 cause = getCauseUsingMethodName(throwable, methodName);
7309 if (cause != null) {
7310 break;
7311 }
7312 }
7313 }
7314
7315 if (cause == null) {
7316 cause = getCauseUsingFieldName(throwable, "detail");
7317 }
7318 }
7319 return cause;
7320 }
7321
7322
7323
7324
7325
7326
7327
7328
7329 private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) {
7330 Method method = null;
7331 try {
7332 method = throwable.getClass().getMethod(methodName, (Class[])null);
7333 } catch (NoSuchMethodException ignored) {
7334 } catch (SecurityException ignored) {
7335 }
7336
7337 if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
7338 try {
7339 return (Throwable) method.invoke(throwable, EMPTY_OBJECT_ARRAY);
7340 } catch (IllegalAccessException ignored) {
7341 } catch (IllegalArgumentException ignored) {
7342 } catch (InvocationTargetException ignored) {
7343 }
7344 }
7345 return null;
7346 }
7347
7348
7349
7350
7351
7352
7353
7354
7355 private static Throwable getCauseUsingFieldName(Throwable throwable, String fieldName) {
7356 Field field = null;
7357 try {
7358 field = throwable.getClass().getField(fieldName);
7359 } catch (NoSuchFieldException ignored) {
7360 } catch (SecurityException ignored) {
7361 }
7362
7363 if (field != null && Throwable.class.isAssignableFrom(field.getType())) {
7364 try {
7365 return (Throwable) field.get(throwable);
7366 } catch (IllegalAccessException ignored) {
7367 } catch (IllegalArgumentException ignored) {
7368 }
7369 }
7370 return null;
7371 }
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383 private static Throwable getCauseUsingWellKnownTypes(Throwable throwable) {
7384 if (throwable instanceof SQLException) {
7385 return ((SQLException) throwable).getNextException();
7386 } else if (throwable instanceof InvocationTargetException) {
7387 return ((InvocationTargetException) throwable).getTargetException();
7388 } else {
7389 return null;
7390 }
7391 }
7392
7393
7394
7395
7396 public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
7397
7398
7399
7400
7401
7402
7403 public static String argKey(String option) {
7404 int equalsIndex = option.indexOf("=");
7405 if (equalsIndex == -1) {
7406 throw new RuntimeException("Invalid option: " + option + ", it should look like: --someOption=someValue");
7407 }
7408 String key = option.substring(0,equalsIndex);
7409 if (!key.startsWith("--")) {
7410 throw new RuntimeException("Invalid option: " + option + ", it should look like: --someOption=someValue");
7411 }
7412 key = key.substring(2);
7413 return key;
7414 }
7415
7416
7417
7418
7419
7420
7421
7422 public static String argValue(String option) {
7423 int equalsIndex = option.indexOf("=");
7424 if (equalsIndex == -1) {
7425 throw new RuntimeException("Invalid option: " + option + ", it should look like: --someOption=someValue");
7426 }
7427 String value = option.substring(equalsIndex+1, option.length());
7428 return value;
7429 }
7430
7431
7432
7433
7434
7435 public static Map<String, String> argMap(String[] args) {
7436
7437 Map<String, String> result = new LinkedHashMap<String, String>();
7438
7439 for (String arg : nonNull(args,String.class)) {
7440 String key = argKey(arg);
7441 String value = argValue(arg);
7442 if (result.containsKey(key)) {
7443 throw new RuntimeException("Passing key twice: " + key);
7444 }
7445 result.put(key, value);
7446 }
7447
7448 return result;
7449 }
7450
7451
7452
7453
7454
7455
7456 public static boolean fileCreate(File fileToCreate) {
7457
7458 if (fileToCreate.exists() && fileToCreate.isFile()) {
7459 return false;
7460 }
7461
7462 if (fileToCreate.exists() && !fileToCreate.isFile()) {
7463 throw new RuntimeException("Trying to create file and it doesnt exist: " + fileToCreate.getAbsolutePath());
7464 }
7465
7466 try {
7467 if (!fileToCreate.createNewFile()) {
7468 throw new RuntimeException("Cant create file: " + fileToCreate);
7469 }
7470 } catch (IOException ioe) {
7471 throw new RuntimeException("Cant create file: " + fileToCreate.getAbsolutePath(), ioe);
7472 }
7473
7474 return true;
7475
7476 }
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486 public static String argMapString(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7487 String key, boolean required) {
7488
7489 if (argMap.containsKey(key)) {
7490
7491
7492 argMapNotUsed.remove(key);
7493
7494 return argMap.get(key);
7495 }
7496 if (required) {
7497 throw new RuntimeException("Argument '--" + key + "' is required, but not specified. e.g. --" + key + "=value");
7498 }
7499 return null;
7500
7501 }
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522 public static void copyDirectoryToDirectory(File srcDir, File destDir)
7523 throws IOException {
7524 if (srcDir == null) {
7525 throw new NullPointerException("Source must not be null");
7526 }
7527 if (srcDir.exists() && srcDir.isDirectory() == false) {
7528 throw new IllegalArgumentException("Source '" + destDir + "' is not a directory");
7529 }
7530 if (destDir == null) {
7531 throw new NullPointerException("Destination must not be null");
7532 }
7533 if (destDir.exists() && destDir.isDirectory() == false) {
7534 throw new IllegalArgumentException("Destination '" + destDir
7535 + "' is not a directory");
7536 }
7537 copyDirectory(srcDir, new File(destDir, srcDir.getName()), true);
7538 }
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557 public static void copyDirectory(File srcDir, File destDir) {
7558 try {
7559 copyDirectory(srcDir, destDir, true);
7560 } catch (IOException ioe) {
7561 throw new RuntimeException("Problem with sourceDir: " + srcDir + ", destDir: " + destDir, ioe);
7562 }
7563 }
7564
7565
7566
7567
7568
7569
7570
7571 public static List<File> jarFindJar(List<File> allJars, String fileName) {
7572 Set<File> result = new HashSet<File>();
7573
7574
7575 Set<String> baseFileNames = jarFileBaseNames(fileName);
7576
7577 if (GrouperInstallerUtils.length(baseFileNames) == 0) {
7578 throw new RuntimeException("Why is base file name null? " + fileName);
7579 }
7580
7581
7582 for (File file : allJars) {
7583
7584 if (!file.getName().endsWith(".jar")) {
7585 continue;
7586 }
7587
7588 Set<String> fileBaseFileNames = jarFileBaseNames(file.getName());
7589
7590 for (String fileBaseFileName : GrouperInstallerUtils.nonNull(fileBaseFileNames)) {
7591 if (baseFileNames.contains(fileBaseFileName)) {
7592 result.add(file);
7593 }
7594 }
7595 }
7596
7597 return new ArrayList<File>(result);
7598
7599 }
7600
7601
7602
7603
7604
7605
7606
7607 public static List<File> jarFindJar(File dir, String fileName) {
7608 if (dir.getName().equals("grouper") || dir.getName().equals("custom") || dir.getName().equals("jdbcSamples")) {
7609 return jarFindJar(dir.getParentFile(), fileName);
7610 }
7611 return jarFindJar(GrouperInstallerUtils.fileListRecursive(dir), fileName);
7612 }
7613
7614
7615
7616
7617
7618
7619 public static Set<String> jarFileBaseNames(String fileName) {
7620
7621 Set<String> result = new HashSet<String>();
7622
7623 Pattern pattern = Pattern.compile("^(.*?)-[0-9].*.jar$");
7624 Matcher matcher = pattern.matcher(fileName);
7625 String baseName = null;
7626 if (matcher.matches()) {
7627 baseName = matcher.group(1);
7628 } else if (fileName.endsWith(".jar")) {
7629 baseName = fileName.substring(0, fileName.length() - ".jar".length());
7630 } else {
7631 return result;
7632 }
7633
7634 result.add(baseName.toLowerCase());
7635
7636 if (baseName.endsWith("-core")) {
7637 baseName = baseName.substring(0, baseName.length() - "-core".length());
7638 result.add(baseName.toLowerCase());
7639 }
7640
7641 if (baseName.toLowerCase().equals("mysql-connector-java") || baseName.toLowerCase().equals("mysql-connector-java-bin")) {
7642 result.add("mysql-connector-java");
7643 result.add("mysql-connector-java-bin");
7644 }
7645
7646 if (baseName.toLowerCase().equals("mail") || baseName.toLowerCase().equals("mailapi")) {
7647 result.add("mail");
7648 result.add("mailapi");
7649 }
7650
7651 return result;
7652 }
7653
7654
7655
7656
7657
7658
7659
7660
7661 public static <T> boolean containsAny(Collection<T> a, Collection<T> b) {
7662 if (a == null || b == null) {
7663 return false;
7664 }
7665 for (T t : a) {
7666 if (b.contains(t)) {
7667 return true;
7668 }
7669 }
7670 return false;
7671 }
7672
7673
7674
7675
7676
7677
7678 public static String jarFileBaseName(String fileName) {
7679
7680 Pattern pattern = Pattern.compile("^(.*?)-[0-9].*.jar$");
7681 Matcher matcher = pattern.matcher(fileName);
7682 String baseName = null;
7683 if (matcher.matches()) {
7684 baseName = matcher.group(1);
7685 } else if (fileName.endsWith(".jar")) {
7686 baseName = fileName.substring(0, fileName.length() - ".jar".length());
7687 } else {
7688 return null;
7689 }
7690
7691 if (baseName.endsWith("-core")) {
7692 baseName = baseName.substring(0, baseName.length() - "-core".length());
7693 }
7694 return baseName;
7695 }
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717 public static void copyDirectory(File srcDir, File destDir,
7718 boolean preserveFileDate) throws IOException {
7719 copyDirectory(srcDir, destDir, null, preserveFileDate);
7720 }
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761 public static void copyDirectory(File srcDir, File destDir,
7762 FileFilter filter) throws IOException {
7763 copyDirectory(srcDir, destDir, filter, true);
7764 }
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806 public static void copyDirectory(File srcDir, File destDir,
7807 FileFilter filter, boolean preserveFileDate) throws IOException {
7808 if (srcDir == null) {
7809 throw new NullPointerException("Source must not be null");
7810 }
7811 if (destDir == null) {
7812 throw new NullPointerException("Destination must not be null");
7813 }
7814 if (srcDir.exists() == false) {
7815 throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
7816 }
7817 if (srcDir.isDirectory() == false) {
7818 throw new IOException("Source '" + srcDir + "' exists but is not a directory");
7819 }
7820 if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
7821 throw new IOException("Source '" + srcDir + "' and destination '" + destDir
7822 + "' are the same");
7823 }
7824
7825
7826 List exclusionList = null;
7827 if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
7828 File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
7829 if (srcFiles != null && srcFiles.length > 0) {
7830 exclusionList = new ArrayList(srcFiles.length);
7831 for (int i = 0; i < srcFiles.length; i++) {
7832 File copiedFile = new File(destDir, srcFiles[i].getName());
7833 exclusionList.add(copiedFile.getCanonicalPath());
7834 }
7835 }
7836 }
7837 doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);
7838 }
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851 private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,
7852 boolean preserveFileDate, List exclusionList) throws IOException {
7853 if (destDir.exists()) {
7854 if (destDir.isDirectory() == false) {
7855 throw new IOException("Destination '" + destDir
7856 + "' exists but is not a directory");
7857 }
7858 } else {
7859 if (destDir.mkdirs() == false) {
7860 throw new IOException("Destination '" + destDir + "' directory cannot be created");
7861 }
7862 if (preserveFileDate) {
7863 destDir.setLastModified(srcDir.lastModified());
7864 }
7865 }
7866 if (destDir.canWrite() == false) {
7867 throw new IOException("Destination '" + destDir + "' cannot be written to");
7868 }
7869
7870 File[] files = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
7871 if (files == null) {
7872 throw new IOException("Failed to list contents of " + srcDir);
7873 }
7874 for (int i = 0; i < files.length; i++) {
7875 File copiedFile = new File(destDir, files[i].getName());
7876 if (exclusionList == null || !exclusionList.contains(files[i].getCanonicalPath())) {
7877 if (files[i].isDirectory()) {
7878 doCopyDirectory(files[i], copiedFile, filter, preserveFileDate, exclusionList);
7879 } else {
7880 doCopyFile(files[i], copiedFile, preserveFileDate);
7881 }
7882 }
7883 }
7884 }
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895 public static boolean argMapBoolean(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7896 String key, boolean required, boolean defaultValue) {
7897 String argString = argMapString(argMap, argMapNotUsed, key, required);
7898
7899 if (isBlank(argString) && required) {
7900 throw new RuntimeException("Argument '--" + key + "' is required, but not specified. e.g. --" + key + "=true");
7901 }
7902 return booleanValue(argString, defaultValue);
7903 }
7904
7905
7906
7907
7908
7909
7910
7911
7912 public static Timestamp argMapTimestamp(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7913 String key) {
7914 String argString = argMapString(argMap, argMapNotUsed, key, false);
7915 if (isBlank(argString)) {
7916 return null;
7917 }
7918 Date date = stringToDate2(argString);
7919 return new Timestamp(date.getTime());
7920 }
7921
7922
7923
7924
7925
7926
7927
7928
7929 public static Boolean argMapBoolean(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7930 String key) {
7931 String argString = argMapString(argMap, argMapNotUsed, key, false);
7932
7933 return booleanObjectValue(argString);
7934 }
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944 public static Set<String> argMapSet(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7945 String key, boolean required) {
7946 List<String> list = argMapList(argMap, argMapNotUsed, key, required);
7947 return list == null ? null : new LinkedHashSet(list);
7948 }
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958 public static List<String> argMapList(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7959 String key, boolean required) {
7960 String argString = argMapString(argMap, argMapNotUsed, key, required);
7961 if (isBlank(argString)) {
7962 return null;
7963 }
7964 return splitTrimToList(argString, ",");
7965 }
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975 public static List<String> argMapFileList(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7976 String key, boolean required) {
7977 String argString = argMapString(argMap, argMapNotUsed, key, required);
7978 if (isBlank(argString)) {
7979 return null;
7980 }
7981
7982 File file = new File(argString);
7983 try {
7984
7985 String listString = GrouperInstallerUtils.readFileIntoString(file);
7986 String[] array = listString.split("\\s+");
7987 List<String> list = new ArrayList<String>();
7988 for (String string : array) {
7989
7990 if (!GrouperInstallerUtils.isBlank(string)) {
7991
7992 list.add(trim(string));
7993 }
7994 }
7995 return list;
7996 } catch (Exception e) {
7997 throw new RuntimeException("Error reading file: '"
7998 + GrouperInstallerUtils.fileCanonicalPath(file) + "' from command line arg: " + key, e );
7999 }
8000 }
8001
8002
8003
8004
8005
8006
8007 public static String responseBodyAsString(HttpMethodBase method) {
8008 InputStream inputStream = null;
8009 try {
8010
8011 StringWriter writer = new StringWriter();
8012 inputStream = method.getResponseBodyAsStream();
8013 copy(inputStream, writer);
8014 return writer.toString();
8015 } catch (Exception e) {
8016 throw new RuntimeException(e);
8017 } finally {
8018 closeQuietly(inputStream);
8019 }
8020
8021 }
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038 public static void copy(InputStream input, Writer output)
8039 throws IOException {
8040 String charsetName = "UTF-8";
8041 InputStreamReader in = new InputStreamReader(input, charsetName);
8042 copy(in, output);
8043 }
8044
8045
8046
8047
8048
8049
8050 public static File jarFile(Class sampleClass) {
8051 try {
8052 CodeSource codeSource = sampleClass.getProtectionDomain().getCodeSource();
8053 if (codeSource != null && codeSource.getLocation() != null) {
8054 String fileName = URLDecoder.decode(codeSource.getLocation().getFile(), "UTF-8");
8055 return new File(fileName);
8056 }
8057 String resourcePath = sampleClass.getName();
8058 resourcePath = resourcePath.replace('.', '/') + ".class";
8059 URL url = computeUrl(resourcePath, true);
8060 String urlPath = url.toString();
8061
8062 if (urlPath.startsWith("jar:")) {
8063 urlPath = urlPath.substring(4);
8064 }
8065 if (urlPath.startsWith("file:")) {
8066 urlPath = urlPath.substring(5);
8067 }
8068 urlPath = prefixOrSuffix(urlPath, "!", true);
8069
8070 urlPath = URLDecoder.decode(urlPath, "UTF-8");
8071
8072 File file = new File(urlPath);
8073 if (urlPath.endsWith(".jar") && file.exists() && file.isFile()) {
8074 return file;
8075 }
8076 } catch (Exception e) {
8077 LOG.warn("Cant find jar for class: " + sampleClass + ", " + e.getMessage(), e);
8078 }
8079 return null;
8080 }
8081
8082
8083
8084
8085
8086
8087
8088
8089 public static String stripLastSlashIfExists(String input) {
8090 if ((input == null) || (input.length() == 0)) {
8091 return null;
8092 }
8093
8094 char lastChar = input.charAt(input.length() - 1);
8095
8096 if ((lastChar == '\\') || (lastChar == '/')) {
8097 return input.substring(0, input.length() - 1);
8098 }
8099
8100 return input;
8101 }
8102
8103
8104
8105
8106
8107
8108
8109 public static String retrievePasswordFromStdin(boolean dontMask, String prompt) {
8110 String passwordString = null;
8111
8112 if (dontMask) {
8113
8114 System.out.print(prompt);
8115
8116 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8117
8118
8119
8120 try {
8121 passwordString = br.readLine();
8122 } catch (IOException ioe) {
8123 System.out.println("IO error! " + getFullStackTrace(ioe));
8124 System.exit(1);
8125 }
8126
8127 } else {
8128 char password[] = null;
8129 try {
8130 password = retrievePasswordFromStdin(System.in, prompt);
8131 } catch (IOException ioe) {
8132 ioe.printStackTrace();
8133 }
8134 passwordString = String.valueOf(password);
8135 }
8136 return passwordString;
8137
8138 }
8139
8140
8141
8142
8143
8144
8145
8146 public static final char[] retrievePasswordFromStdin(InputStream in, String prompt) throws IOException {
8147 MaskingThread maskingthread = new MaskingThread(prompt);
8148
8149 Thread thread = new Thread(maskingthread);
8150 thread.start();
8151
8152 char[] lineBuffer;
8153 char[] buf;
8154
8155 buf = lineBuffer = new char[128];
8156
8157 int room = buf.length;
8158 int offset = 0;
8159 int c;
8160
8161 loop: while (true) {
8162 switch (c = in.read()) {
8163 case -1:
8164 case '\n':
8165 break loop;
8166
8167 case '\r':
8168 int c2 = in.read();
8169 if ((c2 != '\n') && (c2 != -1)) {
8170 if (!(in instanceof PushbackInputStream)) {
8171 in = new PushbackInputStream(in);
8172 }
8173 ((PushbackInputStream) in).unread(c2);
8174 } else {
8175 break loop;
8176 }
8177
8178 default:
8179 if (--room < 0) {
8180 buf = new char[offset + 128];
8181 room = buf.length - offset - 1;
8182 System.arraycopy(lineBuffer, 0, buf, 0, offset);
8183 Arrays.fill(lineBuffer, ' ');
8184 lineBuffer = buf;
8185 }
8186 buf[offset++] = (char) c;
8187 break;
8188 }
8189 }
8190 maskingthread.stopMasking();
8191 if (offset == 0) {
8192 return null;
8193 }
8194 char[] ret = new char[offset];
8195 System.arraycopy(buf, 0, ret, 0, offset);
8196 Arrays.fill(buf, ' ');
8197 return ret;
8198 }
8199
8200
8201
8202
8203 static class MaskingThread extends Thread {
8204
8205
8206 private volatile boolean stop;
8207
8208
8209
8210 private char echochar = ' ';
8211
8212
8213
8214
8215 public MaskingThread(String prompt) {
8216 System.out.print(prompt);
8217 }
8218
8219
8220
8221
8222 @Override
8223 public void run() {
8224
8225 int priority = Thread.currentThread().getPriority();
8226 Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
8227
8228 try {
8229 this.stop = true;
8230 while (this.stop) {
8231 System.out.print("\010" + this.echochar);
8232 try {
8233
8234 Thread.sleep(1);
8235 } catch (InterruptedException iex) {
8236 Thread.currentThread().interrupt();
8237 return;
8238 }
8239 }
8240 } finally {
8241 Thread.currentThread().setPriority(priority);
8242 }
8243 }
8244
8245
8246
8247
8248 public void stopMasking() {
8249 this.stop = false;
8250 }
8251 }
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262 public static boolean propertyValidateValueRequired(String resourceName, Properties properties,
8263 Map<String, String> overrideMap, String key, boolean exceptionOnError) {
8264
8265 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
8266
8267 String value = propertiesValue(properties, threadLocalMap, overrideMap, key);
8268
8269 if (!GrouperInstallerUtils.isBlank(value)) {
8270 return true;
8271 }
8272 String error = "Cant find property " + key + " in resource: " + resourceName + ", it is required";
8273
8274 if (exceptionOnError) {
8275 throw new RuntimeException(error);
8276 }
8277
8278 System.err.println("Grouper error: " + error);
8279 LOG.error(error);
8280 return false;
8281 }
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293 public static boolean propertyValidateValueBoolean(String resourceName, Properties properties,
8294 Map<String, String> overrideMap, String key,
8295 boolean required, boolean exceptionOnError) {
8296
8297 if (required && !propertyValidateValueRequired(resourceName, properties,
8298 overrideMap, key, exceptionOnError)) {
8299 return false;
8300 }
8301
8302 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
8303
8304 String value = propertiesValue(properties, threadLocalMap, overrideMap, key);
8305
8306 if (!required && GrouperInstallerUtils.isBlank(value)) {
8307 return true;
8308 }
8309 try {
8310 booleanValue(value);
8311 return true;
8312 } catch (Exception e) {
8313
8314 }
8315 String error = "Expecting true or false property " + key + " in resource: " + resourceName + ", but is '" + value + "'";
8316 if (exceptionOnError) {
8317 throw new RuntimeException(error);
8318 }
8319 System.err.println("Grouper error: " + error);
8320 LOG.error(error);
8321 return false;
8322 }
8323
8324
8325
8326
8327
8328
8329 public static void threadRunWithStatusDots(final Runnable runnable, boolean printProgress) {
8330 threadRunWithStatusDots(runnable, printProgress, true);
8331 }
8332
8333
8334
8335
8336
8337
8338
8339 public static void threadRunWithStatusDots(final Runnable runnable, boolean printProgress, boolean injectStackInException) {
8340
8341 if (!printProgress) {
8342 runnable.run();
8343 return;
8344 }
8345
8346 try {
8347 final Exception[] theException = new Exception[1];
8348
8349 Runnable wrappedRunnable = new Runnable() {
8350
8351 public void run() {
8352 try {
8353
8354 runnable.run();
8355
8356 } catch (Exception e) {
8357 theException[0] = e;
8358 }
8359 }
8360
8361 };
8362
8363 Thread thread = new Thread(wrappedRunnable);
8364
8365 thread.start();
8366
8367 long start = System.currentTimeMillis();
8368
8369 boolean wroteProgress = false;
8370
8371 int dotCount = 0;
8372
8373 while (true) {
8374
8375 if (thread.isAlive()) {
8376 if (System.currentTimeMillis() - start > 5000) {
8377
8378 wroteProgress = true;
8379 System.out.print(".");
8380 dotCount++;
8381 start = System.currentTimeMillis();
8382
8383 if (dotCount % 40 == 0) {
8384 System.out.println("");
8385 }
8386
8387 } else {
8388
8389 GrouperInstallerUtils.sleep(500);
8390
8391 }
8392 } else {
8393 if (wroteProgress) {
8394
8395 System.out.println("");
8396 }
8397 break;
8398 }
8399 }
8400
8401
8402 thread.join();
8403
8404 if (theException[0] != null) {
8405
8406 if (injectStackInException) {
8407
8408 injectInException(theException[0], getFullStackTrace(new RuntimeException("caller stack")));
8409 }
8410 throw theException[0];
8411 }
8412
8413 } catch (Exception exception) {
8414 if (exception instanceof RuntimeException) {
8415 throw (RuntimeException)exception;
8416 }
8417 throw new RuntimeException(exception);
8418 }
8419
8420 }
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432 public static boolean propertyValidateValueInt(String resourceName, Properties properties,
8433 Map<String, String> overrideMap, String key,
8434 boolean required, boolean exceptionOnError) {
8435
8436 if (required && !propertyValidateValueRequired(resourceName, properties,
8437 overrideMap, key, exceptionOnError)) {
8438 return false;
8439 }
8440
8441 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
8442
8443 String value = propertiesValue(properties, threadLocalMap, overrideMap, key);
8444
8445 if (!required && GrouperInstallerUtils.isBlank(value)) {
8446 return true;
8447 }
8448 try {
8449 intValue(value);
8450 return true;
8451 } catch (Exception e) {
8452
8453 }
8454 String error = "Expecting integer property " + key + " in resource: " + resourceName + ", but is '" + value + "'";
8455 if (exceptionOnError) {
8456 throw new RuntimeException(error);
8457 }
8458 System.err.println("Grouper error: " + error);
8459 LOG.error(error);
8460 return false;
8461 }
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474 public static boolean propertyValidateValueClass(String resourceName, Properties properties,
8475 Map<String, String> overrideMap, String key, Class<?> classType, boolean required, boolean exceptionOnError) {
8476
8477 if (required && !propertyValidateValueRequired(resourceName, properties,
8478 overrideMap, key, exceptionOnError)) {
8479 return false;
8480 }
8481 String value = propertiesValue(properties, overrideMap, key);
8482
8483
8484 if (!required && GrouperInstallerUtils.isBlank(value)) {
8485 return true;
8486 }
8487
8488 String extraError = "";
8489 try {
8490
8491
8492 Class<?> theClass = forName(value);
8493 if (classType.isAssignableFrom(theClass)) {
8494 return true;
8495 }
8496 extraError = " does not derive from class: " + classType.getSimpleName();
8497
8498 } catch (Exception e) {
8499 extraError = ", " + getFullStackTrace(e);
8500 }
8501 String error = "Cant process property " + key + " in resource: " + resourceName + ", the current" +
8502 " value is '" + value + "', which should be of type: "
8503 + classType.getName() + extraError;
8504 if (exceptionOnError) {
8505 throw new RuntimeException(error);
8506 }
8507 System.err.println("Grouper error: " + error);
8508 LOG.error(error);
8509 return false;
8510
8511 }
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537 public static String stripStart(String str, String stripChars) {
8538 int strLen;
8539 if (str == null || (strLen = str.length()) == 0) {
8540 return str;
8541 }
8542 int start = 0;
8543 if (stripChars == null) {
8544 while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
8545 start++;
8546 }
8547 } else if (stripChars.length() == 0) {
8548 return str;
8549 } else {
8550 while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) {
8551 start++;
8552 }
8553 }
8554 return str.substring(start);
8555 }
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581 public static String stripEnd(String str, String stripChars) {
8582 int end;
8583 if (str == null || (end = str.length()) == 0) {
8584 return str;
8585 }
8586
8587 if (stripChars == null) {
8588 while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
8589 end--;
8590 }
8591 } else if (stripChars.length() == 0) {
8592 return str;
8593 } else {
8594 while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
8595 end--;
8596 }
8597 }
8598 return str.substring(0, end);
8599 }
8600
8601
8602
8603
8604
8605 public static final String EMPTY = "";
8606
8607
8608
8609
8610
8611 public static final int INDEX_NOT_FOUND = -1;
8612
8613
8614
8615
8616 private static final int PAD_LIMIT = 8192;
8617
8618
8619
8620
8621
8622
8623 private static final String[] PADDING = new String[Character.MAX_VALUE];
8624
8625 static {
8626
8627 PADDING[32] = " ";
8628 }
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648 public static String repeat(String str, int repeat) {
8649
8650
8651 if (str == null) {
8652 return null;
8653 }
8654 if (repeat <= 0) {
8655 return EMPTY;
8656 }
8657 int inputLength = str.length();
8658 if (repeat == 1 || inputLength == 0) {
8659 return str;
8660 }
8661 if (inputLength == 1 && repeat <= PAD_LIMIT) {
8662 return padding(repeat, str.charAt(0));
8663 }
8664
8665 int outputLength = inputLength * repeat;
8666 switch (inputLength) {
8667 case 1:
8668 char ch = str.charAt(0);
8669 char[] output1 = new char[outputLength];
8670 for (int i = repeat - 1; i >= 0; i--) {
8671 output1[i] = ch;
8672 }
8673 return new String(output1);
8674 case 2:
8675 char ch0 = str.charAt(0);
8676 char ch1 = str.charAt(1);
8677 char[] output2 = new char[outputLength];
8678 for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
8679 output2[i] = ch0;
8680 output2[i + 1] = ch1;
8681 }
8682 return new String(output2);
8683 default:
8684 StringBuffer buf = new StringBuffer(outputLength);
8685 for (int i = 0; i < repeat; i++) {
8686 buf.append(str);
8687 }
8688 return buf.toString();
8689 }
8690 }
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707 private static String padding(int repeat, char padChar) {
8708
8709
8710 String pad = PADDING[padChar];
8711 if (pad == null) {
8712 pad = String.valueOf(padChar);
8713 }
8714 while (pad.length() < repeat) {
8715 pad = pad.concat(pad);
8716 }
8717 PADDING[padChar] = pad;
8718 return pad.substring(0, repeat);
8719 }
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740 public static String rightPad(String str, int size) {
8741 return rightPad(str, size, ' ');
8742 }
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765 public static String rightPad(String str, int size, char padChar) {
8766 if (str == null) {
8767 return null;
8768 }
8769 int pads = size - str.length();
8770 if (pads <= 0) {
8771 return str;
8772 }
8773 if (pads > PAD_LIMIT) {
8774 return rightPad(str, size, String.valueOf(padChar));
8775 }
8776 return str.concat(padding(pads, padChar));
8777 }
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802 public static String rightPad(String str, int size, String padStr) {
8803 if (str == null) {
8804 return null;
8805 }
8806 if (isEmpty(padStr)) {
8807 padStr = " ";
8808 }
8809 int padLen = padStr.length();
8810 int strLen = str.length();
8811 int pads = size - strLen;
8812 if (pads <= 0) {
8813 return str;
8814 }
8815 if (padLen == 1 && pads <= PAD_LIMIT) {
8816 return rightPad(str, size, padStr.charAt(0));
8817 }
8818
8819 if (pads == padLen) {
8820 return str.concat(padStr);
8821 } else if (pads < padLen) {
8822 return str.concat(padStr.substring(0, pads));
8823 } else {
8824 char[] padding = new char[pads];
8825 char[] padChars = padStr.toCharArray();
8826 for (int i = 0; i < pads; i++) {
8827 padding[i] = padChars[i % padLen];
8828 }
8829 return str.concat(new String(padding));
8830 }
8831 }
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852 public static String leftPad(String str, int size) {
8853 return leftPad(str, size, ' ');
8854 }
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877 public static String leftPad(String str, int size, char padChar) {
8878 if (str == null) {
8879 return null;
8880 }
8881 int pads = size - str.length();
8882 if (pads <= 0) {
8883 return str;
8884 }
8885 if (pads > PAD_LIMIT) {
8886 return leftPad(str, size, String.valueOf(padChar));
8887 }
8888 return padding(pads, padChar).concat(str);
8889 }
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914 public static String leftPad(String str, int size, String padStr) {
8915 if (str == null) {
8916 return null;
8917 }
8918 if (isEmpty(padStr)) {
8919 padStr = " ";
8920 }
8921 int padLen = padStr.length();
8922 int strLen = str.length();
8923 int pads = size - strLen;
8924 if (pads <= 0) {
8925 return str;
8926 }
8927 if (padLen == 1 && pads <= PAD_LIMIT) {
8928 return leftPad(str, size, padStr.charAt(0));
8929 }
8930
8931 if (pads == padLen) {
8932 return padStr.concat(str);
8933 } else if (pads < padLen) {
8934 return padStr.substring(0, pads).concat(str);
8935 } else {
8936 char[] padding = new char[pads];
8937 char[] padChars = padStr.toCharArray();
8938 for (int i = 0; i < pads; i++) {
8939 padding[i] = padChars[i % padLen];
8940 }
8941 return new String(padding).concat(str);
8942 }
8943 }
8944
8945
8946
8947
8948
8949 public static void convertToRuntimeException(Exception e) {
8950 if (e instanceof RuntimeException) {
8951 throw (RuntimeException)e;
8952 }
8953 throw new RuntimeException(e.getMessage(), e);
8954 }
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981 public static String substringBefore(String str, String separator) {
8982 if (isEmpty(str) || separator == null) {
8983 return str;
8984 }
8985 if (separator.length() == 0) {
8986 return EMPTY;
8987 }
8988 int pos = str.indexOf(separator);
8989 if (pos == -1) {
8990 return str;
8991 }
8992 return str.substring(0, pos);
8993 }
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021 public static String substringAfter(String str, String separator) {
9022 if (isEmpty(str)) {
9023 return str;
9024 }
9025 if (separator == null) {
9026 return EMPTY;
9027 }
9028 int pos = str.indexOf(separator);
9029 if (pos == -1) {
9030 return EMPTY;
9031 }
9032 return str.substring(pos + separator.length());
9033 }
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060 public static String substringBeforeLast(String str, String separator) {
9061 if (isEmpty(str) || isEmpty(separator)) {
9062 return str;
9063 }
9064 int pos = str.lastIndexOf(separator);
9065 if (pos == -1) {
9066 return str;
9067 }
9068 return str.substring(0, pos);
9069 }
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098 public static String substringAfterLast(String str, String separator) {
9099 if (isEmpty(str)) {
9100 return str;
9101 }
9102 if (isEmpty(separator)) {
9103 return EMPTY;
9104 }
9105 int pos = str.lastIndexOf(separator);
9106 if (pos == -1 || pos == (str.length() - separator.length())) {
9107 return EMPTY;
9108 }
9109 return str.substring(pos + separator.length());
9110 }
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121 public static Integer argMapInteger(Map<String, String> argMap, Map<String, String> argMapNotUsed,
9122 String key, boolean required, Integer defaultValue) {
9123 String argString = argMapString(argMap, argMapNotUsed, key, required);
9124
9125 if (isBlank(argString) && required) {
9126 throw new RuntimeException("Argument '--" + key + "' is required, but not specified. e.g. --" + key + "=5");
9127 }
9128 if (isBlank(argString)) {
9129 if (defaultValue != null) {
9130 return defaultValue;
9131 }
9132 return null;
9133 }
9134 return intValue(argString);
9135 }
9136
9137
9138
9139
9140
9141
9142 public static java.sql.Date toSqlDate(Date date) {
9143 if (date == null) {
9144 return null;
9145 }
9146 return new java.sql.Date(date.getTime());
9147 }
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159 public static int indexOf(Object[] array, Object objectToFind) {
9160 return indexOf(array, objectToFind, 0);
9161 }
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172 public static boolean contains(Object[] array, Object objectToFind) {
9173 return indexOf(array, objectToFind) != -1;
9174 }
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190 public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
9191 if (array == null) {
9192 return -1;
9193 }
9194 if (startIndex < 0) {
9195 startIndex = 0;
9196 }
9197 if (objectToFind == null) {
9198 for (int i = startIndex; i < array.length; i++) {
9199 if (array[i] == null) {
9200 return i;
9201 }
9202 }
9203 } else {
9204 for (int i = startIndex; i < array.length; i++) {
9205 if (objectToFind.equals(array[i])) {
9206 return i;
9207 }
9208 }
9209 }
9210 return -1;
9211 }
9212
9213
9214
9215
9216
9217 private static final String WS_DATE_FORMAT = "yyyy/MM/dd HH:mm:ss.SSS";
9218
9219
9220
9221
9222
9223 private static final String WS_DATE_FORMAT2 = "yyyy/MM/dd_HH:mm:ss.SSS";
9224
9225
9226
9227
9228
9229
9230
9231
9232 public static String dateToString(Date date) {
9233 if (date == null) {
9234 return null;
9235 }
9236 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WS_DATE_FORMAT);
9237 return simpleDateFormat.format(date);
9238 }
9239
9240
9241
9242
9243
9244
9245
9246
9247 public static Date stringToDate(String dateString) {
9248 if (isBlank(dateString)) {
9249 return null;
9250 }
9251 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WS_DATE_FORMAT);
9252 try {
9253 return simpleDateFormat.parse(dateString);
9254 } catch (ParseException e) {
9255 SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat(WS_DATE_FORMAT2);
9256 try {
9257 return simpleDateFormat2.parse(dateString);
9258 } catch (ParseException e2) {
9259 throw new RuntimeException("Cannot convert '" + dateString
9260 + "' to a date based on format: " + WS_DATE_FORMAT, e);
9261 }
9262 }
9263 }
9264
9265
9266
9267
9268 private static Pattern datePattern_yyyy_mm_dd = Pattern.compile("^(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})$");
9269
9270
9271
9272
9273 private static Pattern datePattern_dd_mon_yyyy = Pattern.compile("^(\\d{1,2})[^\\d]+([a-zA-Z]{3,15})[^\\d]+(\\d{4})$");
9274
9275
9276
9277
9278 private static Pattern datePattern_yyyy_mm_dd_hhmmss = Pattern.compile("^(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})$");
9279
9280
9281
9282
9283 private static Pattern datePattern_dd_mon_yyyy_hhmmss = Pattern.compile("^(\\d{1,2})[^\\d]+([a-zA-Z]{3,15})[^\\d]+(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})$");
9284
9285
9286
9287
9288 private static Pattern datePattern_yyyy_mm_dd_hhmmss_SSS = Pattern.compile("^(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,3})$");
9289
9290
9291
9292
9293 private static Pattern datePattern_dd_mon_yyyy_hhmmss_SSS = Pattern.compile("^(\\d{1,2})[^\\d]+([a-zA-Z]{3,15})[^\\d]+(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,3})$");
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307 public static Date stringToDate2(String input) {
9308
9309 if (isBlank(input)) {
9310 return null;
9311 }
9312 input = input.trim();
9313 Matcher matcher = null;
9314
9315 int month = 0;
9316 int day = 0;
9317 int year = 0;
9318 int hour = 0;
9319 int minute = 0;
9320 int second = 0;
9321 int milli = 0;
9322
9323 boolean foundMatch = false;
9324
9325
9326 if (!foundMatch) {
9327 matcher = datePattern_yyyy_mm_dd.matcher(input);
9328 if (matcher.matches()) {
9329 year = intValue(matcher.group(1));
9330 month = intValue(matcher.group(2));
9331 day = intValue(matcher.group(3));
9332 foundMatch = true;
9333 }
9334 }
9335
9336
9337 if (!foundMatch) {
9338 matcher = datePattern_dd_mon_yyyy.matcher(input);
9339 if (matcher.matches()) {
9340 day = intValue(matcher.group(1));
9341 month = monthInt(matcher.group(2));
9342 year = intValue(matcher.group(3));
9343 foundMatch = true;
9344 }
9345 }
9346
9347
9348 if (!foundMatch) {
9349 matcher = datePattern_yyyy_mm_dd_hhmmss.matcher(input);
9350 if (matcher.matches()) {
9351 year = intValue(matcher.group(1));
9352 month = intValue(matcher.group(2));
9353 day = intValue(matcher.group(3));
9354 hour = intValue(matcher.group(4));
9355 minute = intValue(matcher.group(5));
9356 second = intValue(matcher.group(6));
9357 foundMatch = true;
9358 }
9359 }
9360
9361
9362 if (!foundMatch) {
9363 matcher = datePattern_dd_mon_yyyy_hhmmss.matcher(input);
9364 if (matcher.matches()) {
9365 day = intValue(matcher.group(1));
9366 month = monthInt(matcher.group(2));
9367 year = intValue(matcher.group(3));
9368 hour = intValue(matcher.group(4));
9369 minute = intValue(matcher.group(5));
9370 second = intValue(matcher.group(6));
9371 foundMatch = true;
9372 }
9373 }
9374
9375
9376 if (!foundMatch) {
9377 matcher = datePattern_yyyy_mm_dd_hhmmss_SSS.matcher(input);
9378 if (matcher.matches()) {
9379 year = intValue(matcher.group(1));
9380 month = intValue(matcher.group(2));
9381 day = intValue(matcher.group(3));
9382 hour = intValue(matcher.group(4));
9383 minute = intValue(matcher.group(5));
9384 second = intValue(matcher.group(6));
9385 milli = intValue(matcher.group(7));
9386 foundMatch = true;
9387 }
9388 }
9389
9390
9391 if (!foundMatch) {
9392 matcher = datePattern_dd_mon_yyyy_hhmmss_SSS.matcher(input);
9393 if (matcher.matches()) {
9394 day = intValue(matcher.group(1));
9395 month = monthInt(matcher.group(2));
9396 year = intValue(matcher.group(3));
9397 hour = intValue(matcher.group(4));
9398 minute = intValue(matcher.group(5));
9399 second = intValue(matcher.group(6));
9400 milli = intValue(matcher.group(7));
9401 foundMatch = true;
9402 }
9403 }
9404
9405 Calendar calendar = Calendar.getInstance();
9406 calendar.set(Calendar.YEAR, year);
9407 calendar.set(Calendar.MONTH, month-1);
9408 calendar.set(Calendar.DAY_OF_MONTH, day);
9409 calendar.set(Calendar.HOUR_OF_DAY, hour);
9410 calendar.set(Calendar.MINUTE, minute);
9411 calendar.set(Calendar.SECOND, second);
9412 calendar.set(Calendar.MILLISECOND, milli);
9413 return calendar.getTime();
9414 }
9415
9416
9417
9418
9419
9420
9421
9422 public static int monthInt(String mon) {
9423
9424 if (!isBlank(mon)) {
9425 mon = mon.toLowerCase();
9426
9427 if (equals(mon, "jan") || equals(mon, "january")) {
9428 return 1;
9429 }
9430
9431 if (equals(mon, "feb") || equals(mon, "february")) {
9432 return 2;
9433 }
9434
9435 if (equals(mon, "mar") || equals(mon, "march")) {
9436 return 3;
9437 }
9438
9439 if (equals(mon, "apr") || equals(mon, "april")) {
9440 return 4;
9441 }
9442
9443 if (equals(mon, "may")) {
9444 return 5;
9445 }
9446
9447 if (equals(mon, "jun") || equals(mon, "june")) {
9448 return 6;
9449 }
9450
9451 if (equals(mon, "jul") || equals(mon, "july")) {
9452 return 7;
9453 }
9454
9455 if (equals(mon, "aug") || equals(mon, "august")) {
9456 return 8;
9457 }
9458
9459 if (equals(mon, "sep") || equals(mon, "september")) {
9460 return 9;
9461 }
9462
9463 if (equals(mon, "oct") || equals(mon, "october")) {
9464 return 10;
9465 }
9466
9467 if (equals(mon, "nov") || equals(mon, "november")) {
9468 return 11;
9469 }
9470
9471 if (equals(mon, "dec") || equals(mon, "december")) {
9472 return 12;
9473 }
9474
9475 }
9476
9477 throw new RuntimeException("Invalid month: " + mon);
9478 }
9479
9480
9481
9482
9483
9484
9485 public static Map<String, String> propertiesThreadLocalOverrideMap(String propertiesFileName) {
9486 Map<String, Map<String, String>> overrideMap = propertiesThreadLocalOverrideMap.get();
9487 if (overrideMap == null) {
9488 overrideMap = new HashMap<String, Map<String, String>>();
9489 propertiesThreadLocalOverrideMap.set(overrideMap);
9490 }
9491 Map<String, String> propertiesOverrideMap = overrideMap.get(propertiesFileName);
9492 if (propertiesOverrideMap == null) {
9493 propertiesOverrideMap = new HashMap<String, String>();
9494 overrideMap.put(propertiesFileName, propertiesOverrideMap);
9495 }
9496 return propertiesOverrideMap;
9497 }
9498
9499
9500
9501
9502 private static boolean configuredLogs = false;
9503
9504
9505 public static String theLogLevel = "WARNING";
9506
9507
9508
9509
9510
9511
9512 public static String fileAddLastSlashIfNotExists(String filePath) {
9513 filePath = filePath.replace(File.separatorChar == '/' ? '\\' : '/', File.separatorChar);
9514 if (!filePath.endsWith(File.separator)) {
9515 filePath = filePath + File.separatorChar;
9516 }
9517 return filePath;
9518 }
9519
9520
9521
9522
9523
9524 public static Log retrieveLog(Class<?> theClass) {
9525
9526 Log theLog = LogFactory.getLog(theClass);
9527
9528 if (!configuredLogs) {
9529 String logLevel = theLogLevel;
9530 String logFile = null;
9531
9532 boolean hasLogLevel = !isBlank(logLevel);
9533 boolean hasLogFile = !isBlank(logFile);
9534
9535 if (hasLogLevel || hasLogFile) {
9536 if (theLog instanceof Jdk14Logger) {
9537 Jdk14Logger jdkLogger = (Jdk14Logger) theLog;
9538 Logger logger = jdkLogger.getLogger();
9539
9540 long timeToLive = 60;
9541 while (logger.getParent() != null && timeToLive-- > 0) {
9542
9543 logger = logger.getParent();
9544 }
9545
9546 if (length(logger.getHandlers()) == 1) {
9547
9548
9549 if (logger.getHandlers()[0].getClass() == ConsoleHandler.class) {
9550 logger.removeHandler(logger.getHandlers()[0]);
9551 }
9552 }
9553
9554 if (length(logger.getHandlers()) == 0) {
9555 Handler handler = null;
9556 if (hasLogFile) {
9557 try {
9558 handler = new FileHandler(logFile, true);
9559 } catch (IOException ioe) {
9560 throw new RuntimeException(ioe);
9561 }
9562 } else {
9563 handler = new ConsoleHandler();
9564 }
9565 handler.setFormatter(new SimpleFormatter());
9566 handler.setLevel(Level.ALL);
9567 logger.addHandler(handler);
9568
9569 logger.setUseParentHandlers(false);
9570 }
9571
9572 if (hasLogLevel) {
9573 Level level = Level.parse(logLevel);
9574
9575 logger.setLevel(level);
9576
9577 }
9578 }
9579 }
9580
9581 configuredLogs = true;
9582 }
9583
9584 return new GrouperInstallerLog(theLog);
9585
9586 }
9587
9588
9589
9590
9591
9592 public static void tar(File directory, File tarFile) {
9593 tar(directory, tarFile, true);
9594 }
9595
9596
9597
9598
9599
9600
9601
9602 public static void tar(File directory, File tarFile, boolean includeDirectoryInTarPath) {
9603
9604 try {
9605 tarFile.createNewFile();
9606 TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(new FileOutputStream(tarFile));
9607
9608
9609 tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
9610
9611 for (File file : fileListRecursive(directory)) {
9612 if (file.isFile()) {
9613 String relativePath = (includeDirectoryInTarPath ? (directory.getName() + File.separator) : "") + fileRelativePath(directory, file);
9614
9615 relativePath = replace(relativePath, "\\", "/");
9616 TarArchiveEntry entry = new TarArchiveEntry(file, relativePath);
9617 tarArchiveOutputStream.putArchiveEntry(entry);
9618 copy(new FileInputStream(file), tarArchiveOutputStream);
9619 tarArchiveOutputStream.closeArchiveEntry();
9620 }
9621 }
9622
9623 tarArchiveOutputStream.close();
9624 } catch (Exception e) {
9625 throw new RuntimeException("Error creating tar: " + tarFile.getAbsolutePath() + ", from dir: " + directory.getAbsolutePath(), e);
9626 }
9627 }
9628
9629
9630
9631
9632
9633
9634 public static void gzip(File inputFile, File outputFile) {
9635 GZIPOutputStream gzipOutputStream = null;
9636
9637 try {
9638
9639 outputFile.createNewFile();
9640
9641 gzipOutputStream = new GZIPOutputStream(
9642 new BufferedOutputStream(new FileOutputStream(outputFile)));
9643
9644 copy(new FileInputStream(inputFile), gzipOutputStream);
9645 } catch (Exception e) {
9646 throw new RuntimeException("Error creating gzip from " + inputFile.getAbsolutePath() + " to " + outputFile.getAbsolutePath());
9647 } finally {
9648 closeQuietly(gzipOutputStream);
9649 }
9650
9651 }
9652
9653
9654
9655
9656
9657
9658 public static String fileSha1(File file) {
9659
9660 FileInputStream fis = null;
9661
9662 try {
9663 MessageDigest md = MessageDigest.getInstance("SHA1");
9664 fis = new FileInputStream(file);
9665 byte[] dataBytes = new byte[1024];
9666
9667 int nread = 0;
9668
9669 while ((nread = fis.read(dataBytes)) != -1) {
9670 md.update(dataBytes, 0, nread);
9671 };
9672
9673 byte[] mdbytes = md.digest();
9674
9675
9676 StringBuffer sb = new StringBuffer("");
9677 for (int i = 0; i < mdbytes.length; i++) {
9678 sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
9679 }
9680 return sb.toString();
9681 } catch (Exception e) {
9682 throw new RuntimeException("Problem getting checksum of file: " + file.getAbsolutePath(), e);
9683 } finally {
9684 closeQuietly(fis);
9685 }
9686 }
9687
9688
9689 private static Map<String, String> grouperInstallerOverrideMap = new LinkedHashMap<String, String>();
9690
9691
9692
9693
9694
9695 public static Map<String, String> grouperInstallerOverrideMap() {
9696 return grouperInstallerOverrideMap;
9697 }
9698
9699
9700
9701
9702
9703 public static Properties grouperInstallerProperties() {
9704 Properties properties = null;
9705 try {
9706 properties = propertiesFromResourceName(
9707 "grouper.installer.properties", true, true, GrouperInstallerUtils.class, null);
9708 } catch (Exception e) {
9709 throw new RuntimeException("Error accessing file: grouper.installer.properties " +
9710 "This properties file needs to be in the same directory as grouperInstaller.jar, or on your Java classpath", e);
9711 }
9712 return properties;
9713 }
9714
9715
9716
9717
9718
9719
9720 public static boolean propertiesContainsKey(String key) {
9721 return grouperInstallerProperties().containsKey(key);
9722 }
9723
9724
9725
9726
9727
9728
9729
9730 public static String propertiesValue(String key, boolean required) {
9731 return GrouperInstallerUtils.propertiesValue("grouper.installer.properties",
9732 grouperInstallerProperties(),
9733 GrouperInstallerUtils.grouperInstallerOverrideMap(), key, required);
9734 }
9735
9736
9737
9738
9739
9740
9741
9742
9743 public static boolean propertiesValueBoolean(String key, boolean defaultValue, boolean required ) {
9744 return GrouperInstallerUtils.propertiesValueBoolean(
9745 "grouper.installer.properties", grouperInstallerProperties(),
9746 GrouperInstallerUtils.grouperInstallerOverrideMap(),
9747 key, defaultValue, required);
9748 }
9749
9750
9751
9752
9753
9754
9755
9756
9757 public static int propertiesValueInt(String key, int defaultValue, boolean required ) {
9758 return GrouperInstallerUtils.propertiesValueInt(
9759 "grouper.installer.properties", grouperInstallerProperties(),
9760 GrouperInstallerUtils.grouperInstallerOverrideMap(),
9761 key, defaultValue, required);
9762 }
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784 public static int copy(InputStream input, OutputStream output) throws IOException {
9785 long count = copyLarge(input, output);
9786 if (count > Integer.MAX_VALUE) {
9787 return -1;
9788 }
9789 return (int) count;
9790 }
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806 public static long copyLarge(InputStream input, OutputStream output)
9807 throws IOException {
9808 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
9809 long count = 0;
9810 int n = 0;
9811 while (-1 != (n = input.read(buffer))) {
9812 output.write(buffer, 0, n);
9813 count += n;
9814 }
9815 return count;
9816 }
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826 public static void deleteRecursiveDirectory(String dirName) {
9827
9828 File dir = new File(dirName);
9829
9830
9831 if (!dir.exists()) {
9832 return;
9833 }
9834
9835
9836 if (!dir.isDirectory()) {
9837 throw new RuntimeException("The directory: " + dirName + " is not a directory");
9838 }
9839
9840
9841 File[] allFiles = dir.listFiles();
9842
9843
9844 for (int i = 0; i < allFiles.length; i++) {
9845 if (-1 < allFiles[i].getName().indexOf("..")) {
9846 continue;
9847 }
9848
9849 if (allFiles[i].isFile()) {
9850
9851 if (!allFiles[i].delete()) {
9852 throw new RuntimeException("Could not delete file: " + allFiles[i].getPath());
9853 }
9854 } else {
9855
9856 deleteRecursiveDirectory(allFiles[i].getPath());
9857 }
9858 }
9859
9860
9861 if (!dir.delete()) {
9862 throw new RuntimeException("Could not delete directory: " + dir.getPath());
9863 }
9864 }
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874 public static CommandResult execCommand(String command, boolean printProgress) {
9875 String[] args = splitTrim(command, " ");
9876 return execCommand(args, printProgress);
9877 }
9878
9879
9880
9881
9882
9883 private static class StreamGobbler implements Runnable {
9884
9885
9886 private InputStream inputStream;
9887
9888
9889 private String resultString;
9890
9891
9892 private String type;
9893
9894
9895 private String command;
9896
9897
9898 private File printToFile;
9899
9900
9901 private boolean outOrErr;
9902
9903
9904
9905
9906 private boolean printOutputErrorAsReceived;
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917 private StreamGobbler(InputStream is, String theType, String theCommand, File thePrintToFile,
9918 boolean thePrintOutputErrorAsReceived, boolean theOutOrErr) {
9919 this.inputStream = is;
9920 this.type = theType;
9921 this.command = theCommand;
9922 this.printToFile = thePrintToFile;
9923 this.printOutputErrorAsReceived = thePrintOutputErrorAsReceived;
9924 this.outOrErr = theOutOrErr;
9925 }
9926
9927
9928
9929
9930
9931 public String getResultString() {
9932 return this.resultString;
9933 }
9934
9935
9936
9937
9938
9939 @Override
9940 public void run() {
9941
9942
9943 FileOutputStream fileOutputStream = null;
9944
9945 try {
9946 fileOutputStream = this.printToFile == null ? null : new FileOutputStream(this.printToFile);
9947 } catch (IOException ioe) {
9948 throw new RuntimeException(ioe);
9949 }
9950
9951 try {
9952
9953 if (this.printOutputErrorAsReceived) {
9954 if (this.outOrErr) {
9955 copy(this.inputStream, System.out);
9956 } else {
9957 copy(this.inputStream, System.err);
9958 }
9959 } else if (this.printToFile != null) {
9960 copy(this.inputStream, fileOutputStream);
9961
9962 } else {
9963 StringWriter stringWriter = new StringWriter();
9964 copy(this.inputStream, stringWriter);
9965 this.resultString = stringWriter.toString();
9966 }
9967 } catch (Exception e) {
9968
9969 LOG.warn("Error saving output of executable: " + (this.resultString)
9970 + ", " + this.type + ", " + this.command, e);
9971 throw new RuntimeException(e);
9972
9973 } finally {
9974 closeQuietly(fileOutputStream);
9975 }
9976 }
9977 }
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988 public static CommandResult execCommand(String[] arguments, boolean printProgress) {
9989 return execCommand(arguments, true, printProgress);
9990 }
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002 public static CommandResult execCommand(String command, String[] arguments, boolean printProgress) {
10003
10004 List<String> args = new ArrayList<String>();
10005 args.add(command);
10006 for (String argument : nonNull(arguments, String.class)) {
10007 args.add(argument);
10008 }
10009
10010 return execCommand(toArray(args, String.class), true, printProgress);
10011 }
10012
10013
10014
10015
10016 private static ExecutorService executorService = Executors.newCachedThreadPool();
10017
10018
10019
10020
10021
10022 public static ExecutorService retrieveExecutorService() {
10023 return executorService;
10024 }
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039 public static CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero, boolean printProgress) {
10040 return execCommand(arguments, exceptionOnExitValueNeZero, true, printProgress);
10041 }
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057 public static CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero, boolean waitFor, boolean printProgress) {
10058 return execCommand(arguments, exceptionOnExitValueNeZero, waitFor, null, null, null, printProgress);
10059 }
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078 public static CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero, boolean waitFor,
10079 String[] envVariables, File workingDirectory, String outputFilePrefix, boolean printProgress) {
10080 return execCommand(arguments, exceptionOnExitValueNeZero, waitFor, envVariables, workingDirectory, outputFilePrefix, false, printProgress);
10081 }
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101 public static CommandResult execCommand(final String[] arguments, final boolean exceptionOnExitValueNeZero, final boolean waitFor,
10102 final String[] envVariables, final File workingDirectory, final String outputFilePrefix,
10103 final boolean printOutputErrorAsReceived, boolean printProgress) {
10104 return execCommand(arguments, exceptionOnExitValueNeZero, waitFor, envVariables,
10105 workingDirectory, outputFilePrefix, printOutputErrorAsReceived, printProgress, true);
10106 }
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127 public static CommandResult execCommand(final String[] arguments, final boolean exceptionOnExitValueNeZero, final boolean waitFor,
10128 final String[] envVariables, final File workingDirectory, final String outputFilePrefix,
10129 final boolean printOutputErrorAsReceived, boolean printProgress, final boolean logError) {
10130
10131 final CommandResult[] result = new CommandResult[1];
10132
10133 Runnable runnable = new Runnable() {
10134
10135 public void run() {
10136 result[0] = execCommandHelper(arguments, exceptionOnExitValueNeZero, waitFor,
10137 envVariables, workingDirectory, outputFilePrefix, printOutputErrorAsReceived, logError);
10138 }
10139 };
10140
10141 GrouperInstallerUtils.threadRunWithStatusDots(runnable, printProgress, logError);
10142
10143 return result[0];
10144
10145
10146 }
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166 private static CommandResult execCommandHelper(String[] arguments, boolean exceptionOnExitValueNeZero, boolean waitFor,
10167 String[] envVariables, File workingDirectory, String outputFilePrefix, boolean printOutputErrorAsReceived, boolean logError) {
10168
10169 if (printOutputErrorAsReceived && !isBlank(outputFilePrefix)) {
10170 throw new RuntimeException("Cant print as received and have output file prefix");
10171 }
10172
10173 Process process = null;
10174
10175 StringBuilder commandBuilder = new StringBuilder();
10176 for (int i = 0; i < arguments.length; i++) {
10177 commandBuilder.append(arguments[i]).append(" ");
10178 }
10179 String command = commandBuilder.toString();
10180 if (LOG.isDebugEnabled()) {
10181 LOG.debug("Running command: " + command);
10182 }
10183 StreamGobbler outputGobbler = null;
10184 StreamGobbler errorGobbler = null;
10185 try {
10186 process = Runtime.getRuntime().exec(arguments, envVariables, workingDirectory);
10187
10188 if (!waitFor) {
10189 return new CommandResult(null, null, -1);
10190 }
10191 outputGobbler = new StreamGobbler(process.getInputStream(), ".out", command, outputFilePrefix == null ? null : new File(outputFilePrefix + "Out.log"), printOutputErrorAsReceived, true);
10192 errorGobbler = new StreamGobbler(process.getErrorStream(), ".err", command, outputFilePrefix == null ? null : new File(outputFilePrefix + "Err.log"), printOutputErrorAsReceived, false);
10193
10194 Thread outputThread = new Thread(outputGobbler);
10195 outputThread.setDaemon(true);
10196 outputThread.start();
10197
10198 Thread errorThread = new Thread(errorGobbler);
10199 errorThread.setDaemon(true);
10200 errorThread.start();
10201
10202 try {
10203 process.waitFor();
10204 } finally {
10205
10206
10207 try {
10208 outputThread.join();
10209 } catch (Exception e) {
10210
10211 }
10212 try {
10213 errorThread.join();
10214 } catch (Exception e) {
10215
10216 }
10217 }
10218 } catch (Exception e) {
10219 if (logError) {
10220 LOG.error("Error running command: " + command, e);
10221 }
10222 throw new RuntimeException("Error running command: " + command + ", " + e.getMessage(), e);
10223 } finally {
10224 try {
10225 process.destroy();
10226 } catch (Exception e) {
10227 }
10228 }
10229
10230
10231 if (process.exitValue() != 0 && exceptionOnExitValueNeZero) {
10232 String message = "Process exit status=" + process.exitValue() + ": out: " +
10233 (outputGobbler == null ? null : outputGobbler.getResultString())
10234 + ", err: " + (errorGobbler == null ? null : errorGobbler.getResultString());
10235 if (logError) {
10236 LOG.error(message + ", on command: " + command + (workingDirectory == null ? "" : (", workingDir: " + workingDirectory.getAbsolutePath())));
10237 }
10238 throw new RuntimeException(message);
10239 }
10240
10241 int exitValue = process.exitValue();
10242 return new CommandResult(errorGobbler.getResultString(), outputGobbler.getResultString(), exitValue);
10243 }
10244
10245
10246
10247
10248
10249 public static class CommandResult{
10250
10251
10252
10253 private String errorText;
10254
10255
10256
10257
10258 private String outputText;
10259
10260
10261
10262
10263 private int exitCode;
10264
10265
10266
10267
10268
10269
10270
10271
10272 public CommandResult(String _errorText, String _outputText, int _exitCode){
10273 this.errorText = _errorText;
10274 this.outputText = _outputText;
10275 this.exitCode = _exitCode;
10276 }
10277
10278
10279
10280
10281
10282
10283
10284 public String getErrorText() {
10285 return this.errorText;
10286 }
10287
10288
10289
10290
10291
10292
10293
10294 public String getOutputText() {
10295 return this.outputText;
10296 }
10297
10298
10299
10300
10301
10302
10303
10304 public int getExitCode() {
10305 return this.exitCode;
10306 }
10307
10308
10309
10310 }
10311
10312
10313
10314
10315
10316 public static String javaCommand() {
10317 return javaHome() + File.separator + "bin" + File.separator + "java";
10318 }
10319
10320
10321 private static String JAVA_HOME = null;
10322
10323
10324
10325
10326
10327 public static String javaHome() {
10328 if (isBlank(JAVA_HOME)) {
10329
10330
10331 JAVA_HOME = System.getProperty("java.home");
10332
10333 if (JAVA_HOME.endsWith("jre")) {
10334 String newJavaHome = JAVA_HOME.substring(0,JAVA_HOME.length()-4);
10335 File javac = new File(newJavaHome + File.separator + "bin" + File.separator + "javac");
10336 if (javac.exists()) {
10337 JAVA_HOME = newJavaHome;
10338 }
10339 javac = new File(newJavaHome + File.separator + "bin" + File.separator + "javac.exe");
10340 if (javac.exists()) {
10341 JAVA_HOME = newJavaHome;
10342 }
10343 }
10344 }
10345 return JAVA_HOME;
10346 }
10347
10348
10349
10350
10351
10352
10353
10354 public static boolean portAvailable(int port) {
10355 return portAvailable(port, null);
10356 }
10357
10358
10359
10360
10361
10362
10363
10364
10365 public static boolean portAvailable(int port, String ipAddress) {
10366
10367 ServerSocket ss = null;
10368 try {
10369
10370 if (isBlank(ipAddress) || "0.0.0.0".equals(ipAddress)) {
10371 ss = new ServerSocket(port);
10372 } else {
10373
10374 Pattern pattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)");
10375
10376 Matcher matcher = pattern.matcher(ipAddress);
10377
10378 if (!matcher.matches()) {
10379 throw new RuntimeException("IP address not valid! '" + ipAddress + "'");
10380 }
10381
10382 byte[] b = new byte[4];
10383 for (int i=0;i<4;i++) {
10384 int theInt = intValue(matcher.group(i+1));
10385 if (theInt > 255 || theInt < 0) {
10386 System.out.println("IP address part must be between 0 and 255: '" + theInt + "'");
10387 }
10388 b[i] = (byte)theInt;
10389 }
10390
10391
10392 InetAddress inetAddress = InetAddress.getByAddress(b);
10393
10394 ss = new ServerSocket(port, 50, inetAddress);
10395 }
10396 ss.setReuseAddress(true);
10397 return true;
10398 } catch (IOException e) {
10399 } finally {
10400 if (ss != null) {
10401 try {
10402 ss.close();
10403 } catch (IOException e) {
10404
10405 }
10406 }
10407 }
10408
10409 return false;
10410 }
10411
10412
10413
10414
10415
10416
10417 public static void classpathAddFile(File file) {
10418 try {
10419 classpathAddUrl(file.toURI().toURL());
10420 } catch (IOException ioe) {
10421 throw new RuntimeException("Problem adding file to classpath: " + (file == null ? null : file.getAbsolutePath()));
10422 }
10423 }
10424
10425
10426
10427
10428 private static Set<String> urlsAddedToClasspath = new HashSet<String>();
10429
10430
10431
10432
10433
10434 public static void classpathAddUrl(URL url) {
10435
10436 String urlString = url.toString();
10437 if (urlsAddedToClasspath.contains(urlString)) {
10438 return;
10439 }
10440
10441 URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
10442 Class sysclass = URLClassLoader.class;
10443
10444 try {
10445 Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
10446 method.setAccessible(true);
10447 method.invoke(sysloader, new Object[] { url });
10448 } catch (Throwable t) {
10449 throw new RuntimeException("Error, could not add URL to system classloader: " + urlString, t);
10450 }
10451
10452 urlsAddedToClasspath.add(urlString);
10453 }
10454
10455
10456
10457
10458
10459
10460
10461
10462 public static <T> T listPopOne(List<T> list) {
10463 int size = length(list);
10464 if (size == 1) {
10465 return list.get(0);
10466 } else if (size == 0) {
10467 return null;
10468 }
10469 throw new RuntimeException("More than one object of type " + className(list.get(0))
10470 + " was returned when only one was expected. (size:" + size +")" );
10471 }
10472
10473
10474
10475
10476
10477
10478
10479 public static void copyFile(File sourceFile, File destinationFile) {
10480
10481 copyFile(sourceFile, destinationFile, true);
10482 }
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493 public static boolean copyFile(File sourceFile, File destinationFile, boolean onlyIfDifferentContents,
10494 boolean ignoreWhitespace) {
10495 if (onlyIfDifferentContents) {
10496 String sourceContents = readFileIntoString(sourceFile);
10497 return saveStringIntoFile(destinationFile, sourceContents,
10498 onlyIfDifferentContents, ignoreWhitespace);
10499 }
10500 copyFile(sourceFile, destinationFile);
10501 return true;
10502 }
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519 public static void copyFile(File srcFile, File destFile,
10520 boolean preserveFileDate) {
10521
10522 try {
10523 if (srcFile == null) {
10524 throw new NullPointerException("Source must not be null");
10525 }
10526 if (destFile == null) {
10527 throw new NullPointerException("Destination must not be null");
10528 }
10529 if (srcFile.exists() == false) {
10530 throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
10531 }
10532 if (srcFile.isDirectory()) {
10533 throw new IOException("Source '" + srcFile + "' exists but is a directory");
10534 }
10535 if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
10536 throw new IOException("Source '" + srcFile + "' and destination '" + destFile
10537 + "' are the same");
10538 }
10539 if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) {
10540 if (destFile.getParentFile().mkdirs() == false) {
10541 throw new IOException("Destination '" + destFile
10542 + "' directory cannot be created");
10543 }
10544 }
10545 if (destFile.exists() && destFile.canWrite() == false) {
10546 throw new IOException("Destination '" + destFile + "' exists but is read-only");
10547 }
10548 doCopyFile(srcFile, destFile, preserveFileDate);
10549 } catch (IOException ioe) {
10550 throw new RuntimeException(ioe);
10551 }
10552 }
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562 private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
10563 throws IOException {
10564 if (destFile.exists() && destFile.isDirectory()) {
10565 throw new IOException("Destination '" + destFile + "' exists but is a directory");
10566 }
10567
10568 FileInputStream input = new FileInputStream(srcFile);
10569 try {
10570 FileOutputStream output = new FileOutputStream(destFile);
10571 try {
10572 copy(input, output);
10573 } finally {
10574 closeQuietly(output);
10575 }
10576 } finally {
10577 closeQuietly(input);
10578 }
10579
10580 if (srcFile.length() != destFile.length()) {
10581 throw new IOException("Failed to copy full contents from '" +
10582 srcFile + "' to '" + destFile + "'");
10583 }
10584 if (preserveFileDate) {
10585 destFile.setLastModified(srcFile.lastModified());
10586 }
10587 }
10588
10589
10590
10591
10592
10593
10594
10595 public static NodeList xpathEvaluate(File xmlFile, String xpathExpression) {
10596 InputStream inputStream = null;
10597 try {
10598 inputStream = new FileInputStream(xmlFile);
10599 return xpathEvaluate(inputStream, xpathExpression);
10600 } catch (Exception e) {
10601 String errorMessage = "Problem with file: " + xmlFile == null ? null : xmlFile.getAbsolutePath();
10602 if (e instanceof RuntimeException) {
10603 GrouperInstallerUtils.injectInException(e, errorMessage);
10604 throw (RuntimeException)e;
10605 }
10606 throw new RuntimeException(errorMessage, e);
10607 } finally {
10608 GrouperInstallerUtils.closeQuietly(inputStream);
10609 }
10610 }
10611
10612
10613
10614
10615
10616
10617 public static NodeList xpathEvaluate(URL url, String xpathExpression) {
10618 InputStream inputStream = null;
10619 try {
10620 inputStream = url.openStream();
10621 return xpathEvaluate(inputStream, xpathExpression);
10622 } catch (Exception e) {
10623 String errorMessage = "Problem with url: " + url == null ? null : url.toExternalForm();
10624 if (e instanceof RuntimeException) {
10625 GrouperInstallerUtils.injectInException(e, errorMessage);
10626 throw (RuntimeException)e;
10627 }
10628 throw new RuntimeException(errorMessage, e);
10629 } finally {
10630 GrouperInstallerUtils.closeQuietly(inputStream);
10631 }
10632 }
10633
10634
10635
10636
10637
10638
10639 public static NodeList xpathEvaluate(InputStream inputStream, String xpathExpression) {
10640
10641 try {
10642 DocumentBuilderFactory domFactory = xmlDocumentBuilderFactory();
10643 DocumentBuilder builder = domFactory.newDocumentBuilder();
10644 Document doc = builder.parse(inputStream);
10645 XPath xpath = XPathFactory.newInstance().newXPath();
10646
10647 XPathExpression expr = xpath.compile(xpathExpression);
10648
10649 Object result = expr.evaluate(doc, XPathConstants.NODESET);
10650 NodeList nodes = (NodeList) result;
10651 return nodes;
10652 } catch (Exception e) {
10653 throw new RuntimeException("Problem evaluating xpath: " + ", expression: '" + xpathExpression + "'", e);
10654 }
10655
10656 }
10657
10658
10659
10660
10661
10662 public static DocumentBuilderFactory xmlDocumentBuilderFactory() {
10663 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
10664 domFactory.setNamespaceAware(true);
10665 domFactory.setValidating(false);
10666 try {
10667 domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
10668 } catch (ParserConfigurationException pce) {
10669 throw new RuntimeException(pce);
10670 }
10671 return domFactory;
10672 }
10673
10674
10675 private static final String[] XML_SEARCH_NO_SINGLE = new String[]{"&","<",">","\""};
10676
10677
10678 private static final String[] XML_REPLACE_NO_SINGLE = new String[]{"&","<",">","""};
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689 public static String xmlEscape(String input) {
10690 return xmlEscape(input, true);
10691 }
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702 public static String xmlEscape(String input, boolean isEscape) {
10703 if (isEscape) {
10704 return replace(input, XML_SEARCH_NO_SINGLE, XML_REPLACE_NO_SINGLE);
10705 }
10706 return replace(input, XML_REPLACE_NO_SINGLE, XML_SEARCH_NO_SINGLE);
10707 }
10708
10709
10710
10711
10712
10713
10714
10715
10716 public static String xpathEvaluateAttribute(File xmlFile, String xpathExpression, String attributeName) {
10717 NodeList nodes = GrouperInstallerUtils.xpathEvaluate(xmlFile, xpathExpression);
10718 if (nodes == null || nodes.getLength() == 0) {
10719 return null;
10720 }
10721 if (nodes.getLength() != 1) {
10722 throw new RuntimeException("There is more than 1 xpath expression: '" + xpathExpression + "' element in server.xml: " + xmlFile.getAbsolutePath());
10723 }
10724
10725
10726 NamedNodeMap attributes = nodes.item(0).getAttributes();
10727 if (attributes == null || attributes.getLength() == 0 ) {
10728 return null;
10729 }
10730 Node attribute = attributes.getNamedItem(attributeName);
10731 if (attribute == null) {
10732 return null;
10733 }
10734
10735 String nodeValue = attribute.getNodeValue();
10736 return nodeValue;
10737 }
10738
10739
10740
10741
10742
10743
10744
10745
10746 public static String xmlElementToXml(String elementName,
10747 String extraAttributes, Map<String, String> attributes) {
10748
10749 StringBuilder result = new StringBuilder();
10750
10751 result.append("<").append(elementName).append(" ");
10752
10753 if (!isBlank(extraAttributes)) {
10754 result.append(extraAttributes);
10755 }
10756
10757 for (String attributeName : attributes.keySet()) {
10758 result.append(" ").append(attributeName).append("=\"");
10759 String attributeValue = GrouperInstallerUtils.trimToEmpty(attributes.get(attributeName));
10760 result.append(GrouperInstallerUtils.xmlEscape(attributeValue)).append("\"");
10761 }
10762
10763 result.append(" />");
10764
10765 return result.toString();
10766 }
10767
10768
10769
10770
10771
10772
10773
10774 public static String xmlToString(Node document) {
10775 try {
10776 DOMSource domSource = new DOMSource(document);
10777 StringWriter writer = new StringWriter();
10778 StreamResult result = new StreamResult(writer);
10779 TransformerFactory tf = TransformerFactory.newInstance();
10780 Transformer transformer = tf.newTransformer();
10781 transformer.transform(domSource, result);
10782 return writer.toString();
10783 } catch (Exception exception) {
10784 throw new RuntimeException(exception);
10785 }
10786 }
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796 public static Integer xpathEvaluateAttributeInt(File xmlFile, String xpathExpression, String attributeName, Integer defaultValue) {
10797 String nodeValue = xpathEvaluateAttribute(xmlFile, xpathExpression, attributeName);
10798 Integer intValue = GrouperInstallerUtils.intValue(nodeValue, defaultValue);
10799 return intValue;
10800 }
10801
10802
10803
10804
10805
10806
10807 public static String jarVersion(File jarFile) {
10808 return jarVersion(jarFile, false);
10809 }
10810
10811
10812
10813
10814
10815
10816
10817 public static File jarNewerVersion(File jar1, File jar2) {
10818
10819 String version1 = jarVersion(jar1, false);
10820 String version2 = jarVersion(jar2, false);
10821
10822 if (version1 == null && version2 == null) {
10823 return null;
10824 }
10825
10826 if (version1 == null) {
10827 return jar2;
10828 }
10829
10830 if (version2 == null) {
10831 return jar1;
10832 }
10833
10834 GiGrouperVersion giGrouperVersion1 = GiGrouperVersion.valueOfIgnoreCase(version1, false);
10835 GiGrouperVersion giGrouperVersion2 = GiGrouperVersion.valueOfIgnoreCase(version2, false);
10836
10837 if (giGrouperVersion1 == null && giGrouperVersion2 == null) {
10838 return null;
10839 }
10840
10841 if (giGrouperVersion1 == null) {
10842 return jar2;
10843 }
10844
10845 if (giGrouperVersion2 == null) {
10846 return jar1;
10847 }
10848
10849 if (giGrouperVersion1.lessThanArg(giGrouperVersion2)) {
10850 return jar2;
10851 }
10852
10853 return jar1;
10854 }
10855
10856
10857
10858
10859
10860
10861
10862 public static String jarVersion(File jarFile, boolean exceptionIfProblem) {
10863 try {
10864 String version = jarVersion0(jarFile);
10865
10866 if (isBlank(version)) {
10867 version = jarVersion1(jarFile);
10868 }
10869
10870 if (isBlank(version)) {
10871
10872
10873 if (tempFilePathForJars != null) {
10874
10875 String jarFilePath = jarFile.getAbsolutePath();
10876 jarFilePath = replace(jarFilePath, ":", "_");
10877 if (jarFilePath.startsWith("/") || jarFilePath.startsWith("\\")) {
10878 jarFilePath = jarFilePath.substring(1);
10879 }
10880 jarFilePath = tempFilePathForJars + jarFilePath;
10881 File bakJarFile = new File(jarFilePath);
10882 mkdirs(bakJarFile.getParentFile());
10883 copyFile(jarFile, bakJarFile);
10884 version = jarVersion2(bakJarFile);
10885 } else {
10886 throw new RuntimeException("You need to set tempFileForJars");
10887 }
10888
10889 }
10890 return version;
10891 } catch (RuntimeException e) {
10892 injectInException(e, "Problem with jar: " + jarFile.getAbsolutePath());
10893 if (exceptionIfProblem) {
10894 throw e;
10895 }
10896 System.out.println("Non-fatal issue with " + jarFile.getAbsolutePath() + ", " + e.getMessage() + ", assuming cant find version");
10897 }
10898 return null;
10899 }
10900
10901 private static Pattern versionPattern = Pattern.compile("^.*(\\d+)\\.(\\d+)\\.(\\d+)\\.jar*$");
10902
10903
10904
10905
10906
10907
10908 public static String jarVersion0(File jarFile) {
10909 String fileName = jarFile.getName();
10910 Matcher matcher = versionPattern.matcher(fileName);
10911 if (matcher.matches()) {
10912 return matcher.group(1) + "." + matcher.group(2) + "." + matcher.group(3);
10913 }
10914 return null;
10915 }
10916
10917
10918
10919
10920 public static String tempFilePathForJars = null;
10921
10922
10923
10924
10925
10926
10927 public static String jarVersion2(File jarFile) {
10928
10929 InputStream manifestStream = null;
10930 try {
10931 URL manifestUrl = new URL("jar:file:" + jarFile.getCanonicalPath() + "!/META-INF/MANIFEST.MF");
10932 manifestStream = manifestUrl.openStream();
10933 Manifest manifest = new Manifest(manifestStream);
10934 return manifest == null ? null : manifestVersion(jarFile, manifest);
10935 } catch (Exception e) {
10936 if (e instanceof RuntimeException) {
10937 throw (RuntimeException)e;
10938 }
10939 throw new RuntimeException(jarFile.getAbsolutePath() + ", " + e.getMessage(), e);
10940 } finally {
10941 closeQuietly(manifestStream);
10942 }
10943 }
10944
10945
10946
10947
10948
10949
10950 public static String[] splitLines(String string) {
10951 String newline = newlineFromFile(string);
10952 String[] lines = null;
10953 if ("\n".equals(newline)) {
10954 lines = string.split("[\\n]");
10955 } else if ("\r".equals(newline)) {
10956 lines = string.split("[\\r]");
10957 } else if ("\r\n".equals(newline)) {
10958 lines = string.split("[\\r\\n]");
10959 } else {
10960 lines = string.split("[\\r\\n]+");
10961 }
10962 return lines;
10963 }
10964
10965
10966
10967
10968
10969
10970 public static String replaceNewlinesWithSpace(String input) {
10971
10972 if (input == null) {
10973 return null;
10974 }
10975
10976 input = GrouperInstallerUtils.replace(input, "\r\n", " ");
10977 input = GrouperInstallerUtils.replace(input, "\r", " ");
10978 input = GrouperInstallerUtils.replace(input, "\n", " ");
10979
10980 return input;
10981
10982 }
10983
10984
10985
10986
10987 private static Set<String> printedCantFindVersionJarName = new HashSet<String>();
10988
10989 static {
10990
10991
10992
10993 printedCantFindVersionJarName.add("sqljdbc4.jar");
10994 }
10995
10996
10997
10998
10999
11000
11001 public static String manifestVersion(File jarFile, Manifest manifest) {
11002
11003 boolean printJarVersionProblemsV1 = propertiesValueBoolean("grouperInstaller.printJarVersionIssuesV1", false, false);
11004
11005 String[] propertyNames = new String[]{
11006 "Implementation-Version","Version"};
11007
11008 Map<String, Attributes> attributeMap = manifest.getEntries();
11009 String value = null;
11010 for (String propertyName : propertyNames) {
11011 value = manifest.getMainAttributes().getValue(propertyName);
11012 if (!isBlank(value)) {
11013 break;
11014 }
11015 }
11016 if (value == null) {
11017 OUTER:
11018 for (Attributes attributes: attributeMap.values()) {
11019 for (String propertyName : propertyNames) {
11020 value = attributes.getValue(propertyName);
11021 if (!isBlank(value)) {
11022 break OUTER;
11023 }
11024 }
11025 }
11026 }
11027 if (value == null) {
11028 if (!printedCantFindVersionJarName.contains(jarFile.getName())) {
11029 printedCantFindVersionJarName.add(jarFile.getName());
11030 if (printJarVersionProblemsV1) {
11031 System.out.println("Error: cant find version for jar: " + jarFile.getName());
11032 }
11033 if (printJarVersionProblemsV1) {
11034 for (Attributes attributes: attributeMap.values()) {
11035 for (Object key : attributes.keySet()) {
11036 System.out.println(jarFile.getName() + ", " + key + ": " + attributes.getValue((Name)key));
11037 }
11038 }
11039 Attributes attributes = manifest.getMainAttributes();
11040 for (Object key : attributes.keySet()) {
11041 System.out.println(jarFile.getName() + ", main " + key + ": " + attributes.getValue((Name)key));
11042 }
11043 }
11044 }
11045 }
11046 return value;
11047 }
11048
11049
11050
11051
11052
11053
11054 public static String newlineFromFile(String fileContents) {
11055 String newline = "\n";
11056 if (fileContents.contains("\r\n")) {
11057 newline = "\r\n";
11058 }
11059 if (fileContents.contains("\n\r")) {
11060 newline = "\n\r";
11061 }
11062 if (fileContents.contains("\r")) {
11063 newline = "\r";
11064 }
11065 return newline;
11066 }
11067
11068
11069
11070
11071
11072
11073
11074 public static List<File> fileListRecursive(File parent, String fileName) {
11075 List<File> allFiles = GrouperInstallerUtils.fileListRecursive(parent);
11076 List<File> result = new ArrayList<File>();
11077 for (File file : allFiles) {
11078 if (equals(file.getName(), fileName)) {
11079 result.add(file);
11080 }
11081 }
11082 return result;
11083 }
11084
11085
11086
11087
11088
11089
11090 public static List<File> fileListRecursive(File parent) {
11091 List<File> results = new ArrayList<File>();
11092 fileListRecursiveHelper(parent, results);
11093 return results;
11094 }
11095
11096
11097
11098
11099
11100
11101 private static void fileListRecursiveHelper(File parent, List<File> fileList) {
11102 if (parent == null || !parent.exists() || !parent.isDirectory()) {
11103 return;
11104 }
11105 List<File> subFiles = nonNull(toList(parent.listFiles()));
11106 for (File subFile : subFiles) {
11107 if (subFile.isFile()) {
11108 fileList.add(subFile);
11109 }
11110 if (subFile.isDirectory()) {
11111 fileListRecursiveHelper(subFile, fileList);
11112 }
11113 }
11114 }
11115
11116
11117
11118
11119
11120 public static String fileMassagePathsNoLeadingOrTrailing(String path) {
11121 path = path.replace(File.separatorChar == '/' ? '\\' : '/', File.separatorChar);
11122 if (path.startsWith(File.separator)) {
11123 path = path.substring(1);
11124 }
11125 if (path.endsWith(File.separator)) {
11126 path = path.substring(0, path.length()-1);
11127 }
11128 return path;
11129 }
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145 public static boolean contentEquals(File file1, File file2) {
11146 try {
11147 boolean file1Exists = file1 != null && file1.exists();
11148 boolean file2Exists = file2 != null && file2.exists();
11149 if (file1Exists != file2Exists) {
11150 return false;
11151 }
11152
11153 if (!file1Exists) {
11154
11155 return true;
11156 }
11157
11158 if (file1.isDirectory() || file2.isDirectory()) {
11159
11160 throw new IOException("Can't compare directories, only files: " + file1.getAbsolutePath() + ", " + file2.getAbsolutePath());
11161 }
11162
11163 if (file1.length() != file2.length()) {
11164
11165 return false;
11166 }
11167
11168 if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
11169
11170 return true;
11171 }
11172
11173 InputStream input1 = null;
11174 InputStream input2 = null;
11175 try {
11176 input1 = new FileInputStream(file1);
11177 input2 = new FileInputStream(file2);
11178 return contentEquals(input1, input2);
11179
11180 } finally {
11181 closeQuietly(input1);
11182 closeQuietly(input2);
11183 }
11184 } catch (IOException ioe) {
11185 throw new RuntimeException(ioe);
11186 }
11187 }
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203 public static boolean contentEquals(InputStream input1, InputStream input2)
11204 throws IOException {
11205 if (!(input1 instanceof BufferedInputStream)) {
11206 input1 = new BufferedInputStream(input1);
11207 }
11208 if (!(input2 instanceof BufferedInputStream)) {
11209 input2 = new BufferedInputStream(input2);
11210 }
11211
11212 int ch = input1.read();
11213 while (-1 != ch) {
11214 int ch2 = input2.read();
11215 if (ch != ch2) {
11216 return false;
11217 }
11218 ch = input1.read();
11219 }
11220
11221 int ch2 = input2.read();
11222 return (ch2 == -1);
11223 }
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240 public static boolean contentEquals(Reader input1, Reader input2)
11241 throws IOException {
11242 if (!(input1 instanceof BufferedReader)) {
11243 input1 = new BufferedReader(input1);
11244 }
11245 if (!(input2 instanceof BufferedReader)) {
11246 input2 = new BufferedReader(input2);
11247 }
11248
11249 int ch = input1.read();
11250 while (-1 != ch) {
11251 int ch2 = input2.read();
11252 if (ch != ch2) {
11253 return false;
11254 }
11255 ch = input1.read();
11256 }
11257
11258 int ch2 = input2.read();
11259 return (ch2 == -1);
11260 }
11261
11262
11263
11264
11265
11266
11267 public static Set<String> fileDescendantRelativePaths(File parentDir) {
11268 Set<String> result = new LinkedHashSet<String>();
11269 List<File> descendants = fileListRecursive(parentDir);
11270 for (File file : GrouperInstallerUtils.nonNull(descendants)) {
11271 String descendantPath = file.getAbsolutePath();
11272 String parentPath = parentDir.getAbsolutePath();
11273 if (!descendantPath.startsWith(parentPath)) {
11274 throw new RuntimeException("Why doesnt descendantPath '" + descendantPath + "' start with parent path '" + parentPath + "'?");
11275 }
11276 descendantPath = descendantPath.substring(parentPath.length());
11277 if (descendantPath.startsWith("/") || descendantPath.startsWith("\\")) {
11278 descendantPath = descendantPath.substring(1);
11279 }
11280 result.add(descendantPath);
11281 }
11282 return result;
11283 }
11284
11285
11286
11287
11288
11289
11290
11291 public static String fileRelativePath(File parentDir, File file) {
11292
11293 String descendantPath = file.getAbsolutePath();
11294 String parentPath = parentDir.getAbsolutePath();
11295 if (!descendantPath.startsWith(parentPath)) {
11296 throw new RuntimeException("Why doesnt descendantPath '" + descendantPath + "' start with parent path '" + parentPath + "'?");
11297 }
11298 descendantPath = descendantPath.substring(parentPath.length());
11299 if (descendantPath.startsWith("/") || descendantPath.startsWith("\\")) {
11300 descendantPath = descendantPath.substring(1);
11301 }
11302 return descendantPath;
11303 }
11304
11305
11306
11307
11308
11309
11310
11311 public static boolean filePathStartsWith(String bigPath, String prefixPath) {
11312
11313 bigPath = replace(bigPath, "\\\\", "\\");
11314 bigPath = replace(bigPath, "\\", "/");
11315
11316 prefixPath = replace(prefixPath, "\\\\", "\\");
11317 prefixPath = replace(prefixPath, "\\", "/");
11318
11319 return bigPath.startsWith(prefixPath);
11320
11321 }
11322
11323
11324
11325
11326
11327
11328 public static String jarVersion1(File jarFile) {
11329 FileInputStream fileInputStream = null;
11330 try {
11331 fileInputStream = new FileInputStream(jarFile);
11332 JarInputStream jarInputStream = new JarInputStream(fileInputStream);
11333
11334 Manifest manifest = jarInputStream.getManifest();
11335
11336 return manifest == null ? null : manifestVersion(jarFile, manifest);
11337
11338 } catch (Exception e) {
11339 if (e instanceof RuntimeException) {
11340 throw (RuntimeException)e;
11341 }
11342 throw new RuntimeException(e.getMessage(), e);
11343 } finally {
11344 closeQuietly(fileInputStream);
11345 }
11346
11347 }
11348
11349 }