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