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 if (fileName.toLowerCase().startsWith("okhttp-2")) {
7638 result.add("okhttp-2");
7639 } else if (fileName.toLowerCase().startsWith("okhttp-3")) {
7640 result.add("okhttp-3");
7641 } else {
7642
7643 result.add(baseName.toLowerCase());
7644 }
7645 if (baseName.endsWith("-core") && !baseName.toLowerCase().contains("aws")) {
7646 baseName = baseName.substring(0, baseName.length() - "-core".length());
7647 result.add(baseName.toLowerCase());
7648 }
7649
7650 if (baseName.toLowerCase().equals("mysql-connector-java") || baseName.toLowerCase().equals("mysql-connector-java-bin")) {
7651 result.add("mysql-connector-java");
7652 result.add("mysql-connector-java-bin");
7653 }
7654
7655 if (baseName.toLowerCase().equals("mail") || baseName.toLowerCase().equals("mailapi")) {
7656 result.add("mail");
7657 result.add("mailapi");
7658 }
7659
7660 return result;
7661 }
7662
7663
7664
7665
7666
7667
7668
7669
7670 public static <T> boolean containsAny(Collection<T> a, Collection<T> b) {
7671 if (a == null || b == null) {
7672 return false;
7673 }
7674 for (T t : a) {
7675 if (b.contains(t)) {
7676 return true;
7677 }
7678 }
7679 return false;
7680 }
7681
7682
7683
7684
7685
7686
7687 public static String jarFileBaseName(String fileName) {
7688
7689 Pattern pattern = Pattern.compile("^(.*?)-[0-9].*.jar$");
7690 Matcher matcher = pattern.matcher(fileName);
7691 String baseName = null;
7692 if (matcher.matches()) {
7693 baseName = matcher.group(1);
7694 } else if (fileName.endsWith(".jar")) {
7695 baseName = fileName.substring(0, fileName.length() - ".jar".length());
7696 } else {
7697 return null;
7698 }
7699
7700 if (baseName.endsWith("-core")) {
7701 baseName = baseName.substring(0, baseName.length() - "-core".length());
7702 }
7703 return baseName;
7704 }
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726 public static void copyDirectory(File srcDir, File destDir,
7727 boolean preserveFileDate) throws IOException {
7728 copyDirectory(srcDir, destDir, null, preserveFileDate);
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
7765
7766
7767
7768
7769
7770 public static void copyDirectory(File srcDir, File destDir,
7771 FileFilter filter) throws IOException {
7772 copyDirectory(srcDir, destDir, filter, true);
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
7810
7811
7812
7813
7814
7815 public static void copyDirectory(File srcDir, File destDir,
7816 FileFilter filter, boolean preserveFileDate) throws IOException {
7817 if (srcDir == null) {
7818 throw new NullPointerException("Source must not be null");
7819 }
7820 if (destDir == null) {
7821 throw new NullPointerException("Destination must not be null");
7822 }
7823 if (srcDir.exists() == false) {
7824 throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
7825 }
7826 if (srcDir.isDirectory() == false) {
7827 throw new IOException("Source '" + srcDir + "' exists but is not a directory");
7828 }
7829 if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
7830 throw new IOException("Source '" + srcDir + "' and destination '" + destDir
7831 + "' are the same");
7832 }
7833
7834
7835 List exclusionList = null;
7836 if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
7837 File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
7838 if (srcFiles != null && srcFiles.length > 0) {
7839 exclusionList = new ArrayList(srcFiles.length);
7840 for (int i = 0; i < srcFiles.length; i++) {
7841 File copiedFile = new File(destDir, srcFiles[i].getName());
7842 exclusionList.add(copiedFile.getCanonicalPath());
7843 }
7844 }
7845 }
7846 doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);
7847 }
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860 private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,
7861 boolean preserveFileDate, List exclusionList) throws IOException {
7862 if (destDir.exists()) {
7863 if (destDir.isDirectory() == false) {
7864 throw new IOException("Destination '" + destDir
7865 + "' exists but is not a directory");
7866 }
7867 } else {
7868 if (destDir.mkdirs() == false) {
7869 throw new IOException("Destination '" + destDir + "' directory cannot be created");
7870 }
7871 if (preserveFileDate) {
7872 destDir.setLastModified(srcDir.lastModified());
7873 }
7874 }
7875 if (destDir.canWrite() == false) {
7876 throw new IOException("Destination '" + destDir + "' cannot be written to");
7877 }
7878
7879 File[] files = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
7880 if (files == null) {
7881 throw new IOException("Failed to list contents of " + srcDir);
7882 }
7883 for (int i = 0; i < files.length; i++) {
7884 File copiedFile = new File(destDir, files[i].getName());
7885 if (exclusionList == null || !exclusionList.contains(files[i].getCanonicalPath())) {
7886 if (files[i].isDirectory()) {
7887 doCopyDirectory(files[i], copiedFile, filter, preserveFileDate, exclusionList);
7888 } else {
7889 doCopyFile(files[i], copiedFile, preserveFileDate);
7890 }
7891 }
7892 }
7893 }
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904 public static boolean argMapBoolean(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7905 String key, boolean required, boolean defaultValue) {
7906 String argString = argMapString(argMap, argMapNotUsed, key, required);
7907
7908 if (isBlank(argString) && required) {
7909 throw new RuntimeException("Argument '--" + key + "' is required, but not specified. e.g. --" + key + "=true");
7910 }
7911 return booleanValue(argString, defaultValue);
7912 }
7913
7914
7915
7916
7917
7918
7919
7920
7921 public static Timestamp argMapTimestamp(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7922 String key) {
7923 String argString = argMapString(argMap, argMapNotUsed, key, false);
7924 if (isBlank(argString)) {
7925 return null;
7926 }
7927 Date date = stringToDate2(argString);
7928 return new Timestamp(date.getTime());
7929 }
7930
7931
7932
7933
7934
7935
7936
7937
7938 public static Boolean argMapBoolean(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7939 String key) {
7940 String argString = argMapString(argMap, argMapNotUsed, key, false);
7941
7942 return booleanObjectValue(argString);
7943 }
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953 public static Set<String> argMapSet(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7954 String key, boolean required) {
7955 List<String> list = argMapList(argMap, argMapNotUsed, key, required);
7956 return list == null ? null : new LinkedHashSet(list);
7957 }
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967 public static List<String> argMapList(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7968 String key, boolean required) {
7969 String argString = argMapString(argMap, argMapNotUsed, key, required);
7970 if (isBlank(argString)) {
7971 return null;
7972 }
7973 return splitTrimToList(argString, ",");
7974 }
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984 public static List<String> argMapFileList(Map<String, String> argMap, Map<String, String> argMapNotUsed,
7985 String key, boolean required) {
7986 String argString = argMapString(argMap, argMapNotUsed, key, required);
7987 if (isBlank(argString)) {
7988 return null;
7989 }
7990
7991 File file = new File(argString);
7992 try {
7993
7994 String listString = GrouperInstallerUtils.readFileIntoString(file);
7995 String[] array = listString.split("\\s+");
7996 List<String> list = new ArrayList<String>();
7997 for (String string : array) {
7998
7999 if (!GrouperInstallerUtils.isBlank(string)) {
8000
8001 list.add(trim(string));
8002 }
8003 }
8004 return list;
8005 } catch (Exception e) {
8006 throw new RuntimeException("Error reading file: '"
8007 + GrouperInstallerUtils.fileCanonicalPath(file) + "' from command line arg: " + key, e );
8008 }
8009 }
8010
8011
8012
8013
8014
8015
8016 public static String responseBodyAsString(HttpMethodBase method) {
8017 InputStream inputStream = null;
8018 try {
8019
8020 StringWriter writer = new StringWriter();
8021 inputStream = method.getResponseBodyAsStream();
8022 copy(inputStream, writer);
8023 return writer.toString();
8024 } catch (Exception e) {
8025 throw new RuntimeException(e);
8026 } finally {
8027 closeQuietly(inputStream);
8028 }
8029
8030 }
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047 public static void copy(InputStream input, Writer output)
8048 throws IOException {
8049 String charsetName = "UTF-8";
8050 InputStreamReader in = new InputStreamReader(input, charsetName);
8051 copy(in, output);
8052 }
8053
8054
8055
8056
8057
8058
8059 public static File jarFile(Class sampleClass) {
8060 try {
8061 CodeSource codeSource = sampleClass.getProtectionDomain().getCodeSource();
8062 if (codeSource != null && codeSource.getLocation() != null) {
8063 String fileName = URLDecoder.decode(codeSource.getLocation().getFile(), "UTF-8");
8064 return new File(fileName);
8065 }
8066 String resourcePath = sampleClass.getName();
8067 resourcePath = resourcePath.replace('.', '/') + ".class";
8068 URL url = computeUrl(resourcePath, true);
8069 String urlPath = url.toString();
8070
8071 if (urlPath.startsWith("jar:")) {
8072 urlPath = urlPath.substring(4);
8073 }
8074 if (urlPath.startsWith("file:")) {
8075 urlPath = urlPath.substring(5);
8076 }
8077 urlPath = prefixOrSuffix(urlPath, "!", true);
8078
8079 urlPath = URLDecoder.decode(urlPath, "UTF-8");
8080
8081 File file = new File(urlPath);
8082 if (urlPath.endsWith(".jar") && file.exists() && file.isFile()) {
8083 return file;
8084 }
8085 } catch (Exception e) {
8086 LOG.warn("Cant find jar for class: " + sampleClass + ", " + e.getMessage(), e);
8087 }
8088 return null;
8089 }
8090
8091
8092
8093
8094
8095
8096
8097
8098 public static String stripLastSlashIfExists(String input) {
8099 if ((input == null) || (input.length() == 0)) {
8100 return null;
8101 }
8102
8103 char lastChar = input.charAt(input.length() - 1);
8104
8105 if ((lastChar == '\\') || (lastChar == '/')) {
8106 return input.substring(0, input.length() - 1);
8107 }
8108
8109 return input;
8110 }
8111
8112
8113
8114
8115
8116
8117
8118 public static String retrievePasswordFromStdin(boolean dontMask, String prompt) {
8119 String passwordString = null;
8120
8121 if (dontMask) {
8122
8123 System.out.print(prompt);
8124
8125 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8126
8127
8128
8129 try {
8130 passwordString = br.readLine();
8131 } catch (IOException ioe) {
8132 System.out.println("IO error! " + getFullStackTrace(ioe));
8133 System.exit(1);
8134 }
8135
8136 } else {
8137 char password[] = null;
8138 try {
8139 password = retrievePasswordFromStdin(System.in, prompt);
8140 } catch (IOException ioe) {
8141 ioe.printStackTrace();
8142 }
8143 passwordString = String.valueOf(password);
8144 }
8145 return passwordString;
8146
8147 }
8148
8149
8150
8151
8152
8153
8154
8155 public static final char[] retrievePasswordFromStdin(InputStream in, String prompt) throws IOException {
8156 MaskingThread maskingthread = new MaskingThread(prompt);
8157
8158 Thread thread = new Thread(maskingthread);
8159 thread.start();
8160
8161 char[] lineBuffer;
8162 char[] buf;
8163
8164 buf = lineBuffer = new char[128];
8165
8166 int room = buf.length;
8167 int offset = 0;
8168 int c;
8169
8170 loop: while (true) {
8171 switch (c = in.read()) {
8172 case -1:
8173 case '\n':
8174 break loop;
8175
8176 case '\r':
8177 int c2 = in.read();
8178 if ((c2 != '\n') && (c2 != -1)) {
8179 if (!(in instanceof PushbackInputStream)) {
8180 in = new PushbackInputStream(in);
8181 }
8182 ((PushbackInputStream) in).unread(c2);
8183 } else {
8184 break loop;
8185 }
8186
8187 default:
8188 if (--room < 0) {
8189 buf = new char[offset + 128];
8190 room = buf.length - offset - 1;
8191 System.arraycopy(lineBuffer, 0, buf, 0, offset);
8192 Arrays.fill(lineBuffer, ' ');
8193 lineBuffer = buf;
8194 }
8195 buf[offset++] = (char) c;
8196 break;
8197 }
8198 }
8199 maskingthread.stopMasking();
8200 if (offset == 0) {
8201 return null;
8202 }
8203 char[] ret = new char[offset];
8204 System.arraycopy(buf, 0, ret, 0, offset);
8205 Arrays.fill(buf, ' ');
8206 return ret;
8207 }
8208
8209
8210
8211
8212 static class MaskingThread extends Thread {
8213
8214
8215 private volatile boolean stop;
8216
8217
8218
8219 private char echochar = ' ';
8220
8221
8222
8223
8224 public MaskingThread(String prompt) {
8225 System.out.print(prompt);
8226 }
8227
8228
8229
8230
8231 @Override
8232 public void run() {
8233
8234 int priority = Thread.currentThread().getPriority();
8235 Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
8236
8237 try {
8238 this.stop = true;
8239 while (this.stop) {
8240 System.out.print("\010" + this.echochar);
8241 try {
8242
8243 Thread.sleep(1);
8244 } catch (InterruptedException iex) {
8245 Thread.currentThread().interrupt();
8246 return;
8247 }
8248 }
8249 } finally {
8250 Thread.currentThread().setPriority(priority);
8251 }
8252 }
8253
8254
8255
8256
8257 public void stopMasking() {
8258 this.stop = false;
8259 }
8260 }
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271 public static boolean propertyValidateValueRequired(String resourceName, Properties properties,
8272 Map<String, String> overrideMap, String key, boolean exceptionOnError) {
8273
8274 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
8275
8276 String value = propertiesValue(properties, threadLocalMap, overrideMap, key);
8277
8278 if (!GrouperInstallerUtils.isBlank(value)) {
8279 return true;
8280 }
8281 String error = "Cant find property " + key + " in resource: " + resourceName + ", it is required";
8282
8283 if (exceptionOnError) {
8284 throw new RuntimeException(error);
8285 }
8286
8287 System.err.println("Grouper error: " + error);
8288 LOG.error(error);
8289 return false;
8290 }
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302 public static boolean propertyValidateValueBoolean(String resourceName, Properties properties,
8303 Map<String, String> overrideMap, String key,
8304 boolean required, boolean exceptionOnError) {
8305
8306 if (required && !propertyValidateValueRequired(resourceName, properties,
8307 overrideMap, key, exceptionOnError)) {
8308 return false;
8309 }
8310
8311 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
8312
8313 String value = propertiesValue(properties, threadLocalMap, overrideMap, key);
8314
8315 if (!required && GrouperInstallerUtils.isBlank(value)) {
8316 return true;
8317 }
8318 try {
8319 booleanValue(value);
8320 return true;
8321 } catch (Exception e) {
8322
8323 }
8324 String error = "Expecting true or false property " + key + " in resource: " + resourceName + ", but is '" + value + "'";
8325 if (exceptionOnError) {
8326 throw new RuntimeException(error);
8327 }
8328 System.err.println("Grouper error: " + error);
8329 LOG.error(error);
8330 return false;
8331 }
8332
8333
8334
8335
8336
8337
8338 public static void threadRunWithStatusDots(final Runnable runnable, boolean printProgress) {
8339 threadRunWithStatusDots(runnable, printProgress, true);
8340 }
8341
8342
8343
8344
8345
8346
8347
8348 public static void threadRunWithStatusDots(final Runnable runnable, boolean printProgress, boolean injectStackInException) {
8349
8350 if (!printProgress) {
8351 runnable.run();
8352 return;
8353 }
8354
8355 try {
8356 final Exception[] theException = new Exception[1];
8357
8358 Runnable wrappedRunnable = new Runnable() {
8359
8360 public void run() {
8361 try {
8362
8363 runnable.run();
8364
8365 } catch (Exception e) {
8366 theException[0] = e;
8367 }
8368 }
8369
8370 };
8371
8372 Thread thread = new Thread(wrappedRunnable);
8373
8374 thread.start();
8375
8376 long start = System.currentTimeMillis();
8377
8378 boolean wroteProgress = false;
8379
8380 int dotCount = 0;
8381
8382 while (true) {
8383
8384 if (thread.isAlive()) {
8385 if (System.currentTimeMillis() - start > 5000) {
8386
8387 wroteProgress = true;
8388 System.out.print(".");
8389 dotCount++;
8390 start = System.currentTimeMillis();
8391
8392 if (dotCount % 40 == 0) {
8393 System.out.println("");
8394 }
8395
8396 } else {
8397
8398 GrouperInstallerUtils.sleep(500);
8399
8400 }
8401 } else {
8402 if (wroteProgress) {
8403
8404 System.out.println("");
8405 }
8406 break;
8407 }
8408 }
8409
8410
8411 thread.join();
8412
8413 if (theException[0] != null) {
8414
8415 if (injectStackInException) {
8416
8417 injectInException(theException[0], getFullStackTrace(new RuntimeException("caller stack")));
8418 }
8419 throw theException[0];
8420 }
8421
8422 } catch (Exception exception) {
8423 if (exception instanceof RuntimeException) {
8424 throw (RuntimeException)exception;
8425 }
8426 throw new RuntimeException(exception);
8427 }
8428
8429 }
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441 public static boolean propertyValidateValueInt(String resourceName, Properties properties,
8442 Map<String, String> overrideMap, String key,
8443 boolean required, boolean exceptionOnError) {
8444
8445 if (required && !propertyValidateValueRequired(resourceName, properties,
8446 overrideMap, key, exceptionOnError)) {
8447 return false;
8448 }
8449
8450 Map<String, String> threadLocalMap = propertiesThreadLocalOverrideMap(resourceName);
8451
8452 String value = propertiesValue(properties, threadLocalMap, overrideMap, key);
8453
8454 if (!required && GrouperInstallerUtils.isBlank(value)) {
8455 return true;
8456 }
8457 try {
8458 intValue(value);
8459 return true;
8460 } catch (Exception e) {
8461
8462 }
8463 String error = "Expecting integer property " + key + " in resource: " + resourceName + ", but is '" + value + "'";
8464 if (exceptionOnError) {
8465 throw new RuntimeException(error);
8466 }
8467 System.err.println("Grouper error: " + error);
8468 LOG.error(error);
8469 return false;
8470 }
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483 public static boolean propertyValidateValueClass(String resourceName, Properties properties,
8484 Map<String, String> overrideMap, String key, Class<?> classType, boolean required, boolean exceptionOnError) {
8485
8486 if (required && !propertyValidateValueRequired(resourceName, properties,
8487 overrideMap, key, exceptionOnError)) {
8488 return false;
8489 }
8490 String value = propertiesValue(properties, overrideMap, key);
8491
8492
8493 if (!required && GrouperInstallerUtils.isBlank(value)) {
8494 return true;
8495 }
8496
8497 String extraError = "";
8498 try {
8499
8500
8501 Class<?> theClass = forName(value);
8502 if (classType.isAssignableFrom(theClass)) {
8503 return true;
8504 }
8505 extraError = " does not derive from class: " + classType.getSimpleName();
8506
8507 } catch (Exception e) {
8508 extraError = ", " + getFullStackTrace(e);
8509 }
8510 String error = "Cant process property " + key + " in resource: " + resourceName + ", the current" +
8511 " value is '" + value + "', which should be of type: "
8512 + classType.getName() + extraError;
8513 if (exceptionOnError) {
8514 throw new RuntimeException(error);
8515 }
8516 System.err.println("Grouper error: " + error);
8517 LOG.error(error);
8518 return false;
8519
8520 }
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546 public static String stripStart(String str, String stripChars) {
8547 int strLen;
8548 if (str == null || (strLen = str.length()) == 0) {
8549 return str;
8550 }
8551 int start = 0;
8552 if (stripChars == null) {
8553 while ((start != strLen) && Character.isWhitespace(str.charAt(start))) {
8554 start++;
8555 }
8556 } else if (stripChars.length() == 0) {
8557 return str;
8558 } else {
8559 while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) {
8560 start++;
8561 }
8562 }
8563 return str.substring(start);
8564 }
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590 public static String stripEnd(String str, String stripChars) {
8591 int end;
8592 if (str == null || (end = str.length()) == 0) {
8593 return str;
8594 }
8595
8596 if (stripChars == null) {
8597 while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) {
8598 end--;
8599 }
8600 } else if (stripChars.length() == 0) {
8601 return str;
8602 } else {
8603 while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
8604 end--;
8605 }
8606 }
8607 return str.substring(0, end);
8608 }
8609
8610
8611
8612
8613
8614 public static final String EMPTY = "";
8615
8616
8617
8618
8619
8620 public static final int INDEX_NOT_FOUND = -1;
8621
8622
8623
8624
8625 private static final int PAD_LIMIT = 8192;
8626
8627
8628
8629
8630
8631
8632 private static final String[] PADDING = new String[Character.MAX_VALUE];
8633
8634 static {
8635
8636 PADDING[32] = " ";
8637 }
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657 public static String repeat(String str, int repeat) {
8658
8659
8660 if (str == null) {
8661 return null;
8662 }
8663 if (repeat <= 0) {
8664 return EMPTY;
8665 }
8666 int inputLength = str.length();
8667 if (repeat == 1 || inputLength == 0) {
8668 return str;
8669 }
8670 if (inputLength == 1 && repeat <= PAD_LIMIT) {
8671 return padding(repeat, str.charAt(0));
8672 }
8673
8674 int outputLength = inputLength * repeat;
8675 switch (inputLength) {
8676 case 1:
8677 char ch = str.charAt(0);
8678 char[] output1 = new char[outputLength];
8679 for (int i = repeat - 1; i >= 0; i--) {
8680 output1[i] = ch;
8681 }
8682 return new String(output1);
8683 case 2:
8684 char ch0 = str.charAt(0);
8685 char ch1 = str.charAt(1);
8686 char[] output2 = new char[outputLength];
8687 for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
8688 output2[i] = ch0;
8689 output2[i + 1] = ch1;
8690 }
8691 return new String(output2);
8692 default:
8693 StringBuffer buf = new StringBuffer(outputLength);
8694 for (int i = 0; i < repeat; i++) {
8695 buf.append(str);
8696 }
8697 return buf.toString();
8698 }
8699 }
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716 private static String padding(int repeat, char padChar) {
8717
8718
8719 String pad = PADDING[padChar];
8720 if (pad == null) {
8721 pad = String.valueOf(padChar);
8722 }
8723 while (pad.length() < repeat) {
8724 pad = pad.concat(pad);
8725 }
8726 PADDING[padChar] = pad;
8727 return pad.substring(0, repeat);
8728 }
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749 public static String rightPad(String str, int size) {
8750 return rightPad(str, size, ' ');
8751 }
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774 public static String rightPad(String str, int size, char padChar) {
8775 if (str == null) {
8776 return null;
8777 }
8778 int pads = size - str.length();
8779 if (pads <= 0) {
8780 return str;
8781 }
8782 if (pads > PAD_LIMIT) {
8783 return rightPad(str, size, String.valueOf(padChar));
8784 }
8785 return str.concat(padding(pads, padChar));
8786 }
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811 public static String rightPad(String str, int size, String padStr) {
8812 if (str == null) {
8813 return null;
8814 }
8815 if (isEmpty(padStr)) {
8816 padStr = " ";
8817 }
8818 int padLen = padStr.length();
8819 int strLen = str.length();
8820 int pads = size - strLen;
8821 if (pads <= 0) {
8822 return str;
8823 }
8824 if (padLen == 1 && pads <= PAD_LIMIT) {
8825 return rightPad(str, size, padStr.charAt(0));
8826 }
8827
8828 if (pads == padLen) {
8829 return str.concat(padStr);
8830 } else if (pads < padLen) {
8831 return str.concat(padStr.substring(0, pads));
8832 } else {
8833 char[] padding = new char[pads];
8834 char[] padChars = padStr.toCharArray();
8835 for (int i = 0; i < pads; i++) {
8836 padding[i] = padChars[i % padLen];
8837 }
8838 return str.concat(new String(padding));
8839 }
8840 }
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861 public static String leftPad(String str, int size) {
8862 return leftPad(str, size, ' ');
8863 }
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886 public static String leftPad(String str, int size, char padChar) {
8887 if (str == null) {
8888 return null;
8889 }
8890 int pads = size - str.length();
8891 if (pads <= 0) {
8892 return str;
8893 }
8894 if (pads > PAD_LIMIT) {
8895 return leftPad(str, size, String.valueOf(padChar));
8896 }
8897 return padding(pads, padChar).concat(str);
8898 }
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923 public static String leftPad(String str, int size, String padStr) {
8924 if (str == null) {
8925 return null;
8926 }
8927 if (isEmpty(padStr)) {
8928 padStr = " ";
8929 }
8930 int padLen = padStr.length();
8931 int strLen = str.length();
8932 int pads = size - strLen;
8933 if (pads <= 0) {
8934 return str;
8935 }
8936 if (padLen == 1 && pads <= PAD_LIMIT) {
8937 return leftPad(str, size, padStr.charAt(0));
8938 }
8939
8940 if (pads == padLen) {
8941 return padStr.concat(str);
8942 } else if (pads < padLen) {
8943 return padStr.substring(0, pads).concat(str);
8944 } else {
8945 char[] padding = new char[pads];
8946 char[] padChars = padStr.toCharArray();
8947 for (int i = 0; i < pads; i++) {
8948 padding[i] = padChars[i % padLen];
8949 }
8950 return new String(padding).concat(str);
8951 }
8952 }
8953
8954
8955
8956
8957
8958 public static void convertToRuntimeException(Exception e) {
8959 if (e instanceof RuntimeException) {
8960 throw (RuntimeException)e;
8961 }
8962 throw new RuntimeException(e.getMessage(), e);
8963 }
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990 public static String substringBefore(String str, String separator) {
8991 if (isEmpty(str) || separator == null) {
8992 return str;
8993 }
8994 if (separator.length() == 0) {
8995 return EMPTY;
8996 }
8997 int pos = str.indexOf(separator);
8998 if (pos == -1) {
8999 return str;
9000 }
9001 return str.substring(0, pos);
9002 }
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030 public static String substringAfter(String str, String separator) {
9031 if (isEmpty(str)) {
9032 return str;
9033 }
9034 if (separator == null) {
9035 return EMPTY;
9036 }
9037 int pos = str.indexOf(separator);
9038 if (pos == -1) {
9039 return EMPTY;
9040 }
9041 return str.substring(pos + separator.length());
9042 }
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069 public static String substringBeforeLast(String str, String separator) {
9070 if (isEmpty(str) || isEmpty(separator)) {
9071 return str;
9072 }
9073 int pos = str.lastIndexOf(separator);
9074 if (pos == -1) {
9075 return str;
9076 }
9077 return str.substring(0, pos);
9078 }
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107 public static String substringAfterLast(String str, String separator) {
9108 if (isEmpty(str)) {
9109 return str;
9110 }
9111 if (isEmpty(separator)) {
9112 return EMPTY;
9113 }
9114 int pos = str.lastIndexOf(separator);
9115 if (pos == -1 || pos == (str.length() - separator.length())) {
9116 return EMPTY;
9117 }
9118 return str.substring(pos + separator.length());
9119 }
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130 public static Integer argMapInteger(Map<String, String> argMap, Map<String, String> argMapNotUsed,
9131 String key, boolean required, Integer defaultValue) {
9132 String argString = argMapString(argMap, argMapNotUsed, key, required);
9133
9134 if (isBlank(argString) && required) {
9135 throw new RuntimeException("Argument '--" + key + "' is required, but not specified. e.g. --" + key + "=5");
9136 }
9137 if (isBlank(argString)) {
9138 if (defaultValue != null) {
9139 return defaultValue;
9140 }
9141 return null;
9142 }
9143 return intValue(argString);
9144 }
9145
9146
9147
9148
9149
9150
9151 public static java.sql.Date toSqlDate(Date date) {
9152 if (date == null) {
9153 return null;
9154 }
9155 return new java.sql.Date(date.getTime());
9156 }
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168 public static int indexOf(Object[] array, Object objectToFind) {
9169 return indexOf(array, objectToFind, 0);
9170 }
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181 public static boolean contains(Object[] array, Object objectToFind) {
9182 return indexOf(array, objectToFind) != -1;
9183 }
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199 public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
9200 if (array == null) {
9201 return -1;
9202 }
9203 if (startIndex < 0) {
9204 startIndex = 0;
9205 }
9206 if (objectToFind == null) {
9207 for (int i = startIndex; i < array.length; i++) {
9208 if (array[i] == null) {
9209 return i;
9210 }
9211 }
9212 } else {
9213 for (int i = startIndex; i < array.length; i++) {
9214 if (objectToFind.equals(array[i])) {
9215 return i;
9216 }
9217 }
9218 }
9219 return -1;
9220 }
9221
9222
9223
9224
9225
9226 private static final String WS_DATE_FORMAT = "yyyy/MM/dd HH:mm:ss.SSS";
9227
9228
9229
9230
9231
9232 private static final String WS_DATE_FORMAT2 = "yyyy/MM/dd_HH:mm:ss.SSS";
9233
9234
9235
9236
9237
9238
9239
9240
9241 public static String dateToString(Date date) {
9242 if (date == null) {
9243 return null;
9244 }
9245 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WS_DATE_FORMAT);
9246 return simpleDateFormat.format(date);
9247 }
9248
9249
9250
9251
9252
9253
9254
9255
9256 public static Date stringToDate(String dateString) {
9257 if (isBlank(dateString)) {
9258 return null;
9259 }
9260 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(WS_DATE_FORMAT);
9261 try {
9262 return simpleDateFormat.parse(dateString);
9263 } catch (ParseException e) {
9264 SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat(WS_DATE_FORMAT2);
9265 try {
9266 return simpleDateFormat2.parse(dateString);
9267 } catch (ParseException e2) {
9268 throw new RuntimeException("Cannot convert '" + dateString
9269 + "' to a date based on format: " + WS_DATE_FORMAT, e);
9270 }
9271 }
9272 }
9273
9274
9275
9276
9277 private static Pattern datePattern_yyyy_mm_dd = Pattern.compile("^(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})$");
9278
9279
9280
9281
9282 private static Pattern datePattern_dd_mon_yyyy = Pattern.compile("^(\\d{1,2})[^\\d]+([a-zA-Z]{3,15})[^\\d]+(\\d{4})$");
9283
9284
9285
9286
9287 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})$");
9288
9289
9290
9291
9292 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})$");
9293
9294
9295
9296
9297 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})$");
9298
9299
9300
9301
9302 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})$");
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316 public static Date stringToDate2(String input) {
9317
9318 if (isBlank(input)) {
9319 return null;
9320 }
9321 input = input.trim();
9322 Matcher matcher = null;
9323
9324 int month = 0;
9325 int day = 0;
9326 int year = 0;
9327 int hour = 0;
9328 int minute = 0;
9329 int second = 0;
9330 int milli = 0;
9331
9332 boolean foundMatch = false;
9333
9334
9335 if (!foundMatch) {
9336 matcher = datePattern_yyyy_mm_dd.matcher(input);
9337 if (matcher.matches()) {
9338 year = intValue(matcher.group(1));
9339 month = intValue(matcher.group(2));
9340 day = intValue(matcher.group(3));
9341 foundMatch = true;
9342 }
9343 }
9344
9345
9346 if (!foundMatch) {
9347 matcher = datePattern_dd_mon_yyyy.matcher(input);
9348 if (matcher.matches()) {
9349 day = intValue(matcher.group(1));
9350 month = monthInt(matcher.group(2));
9351 year = intValue(matcher.group(3));
9352 foundMatch = true;
9353 }
9354 }
9355
9356
9357 if (!foundMatch) {
9358 matcher = datePattern_yyyy_mm_dd_hhmmss.matcher(input);
9359 if (matcher.matches()) {
9360 year = intValue(matcher.group(1));
9361 month = intValue(matcher.group(2));
9362 day = intValue(matcher.group(3));
9363 hour = intValue(matcher.group(4));
9364 minute = intValue(matcher.group(5));
9365 second = intValue(matcher.group(6));
9366 foundMatch = true;
9367 }
9368 }
9369
9370
9371 if (!foundMatch) {
9372 matcher = datePattern_dd_mon_yyyy_hhmmss.matcher(input);
9373 if (matcher.matches()) {
9374 day = intValue(matcher.group(1));
9375 month = monthInt(matcher.group(2));
9376 year = intValue(matcher.group(3));
9377 hour = intValue(matcher.group(4));
9378 minute = intValue(matcher.group(5));
9379 second = intValue(matcher.group(6));
9380 foundMatch = true;
9381 }
9382 }
9383
9384
9385 if (!foundMatch) {
9386 matcher = datePattern_yyyy_mm_dd_hhmmss_SSS.matcher(input);
9387 if (matcher.matches()) {
9388 year = intValue(matcher.group(1));
9389 month = intValue(matcher.group(2));
9390 day = intValue(matcher.group(3));
9391 hour = intValue(matcher.group(4));
9392 minute = intValue(matcher.group(5));
9393 second = intValue(matcher.group(6));
9394 milli = intValue(matcher.group(7));
9395 foundMatch = true;
9396 }
9397 }
9398
9399
9400 if (!foundMatch) {
9401 matcher = datePattern_dd_mon_yyyy_hhmmss_SSS.matcher(input);
9402 if (matcher.matches()) {
9403 day = intValue(matcher.group(1));
9404 month = monthInt(matcher.group(2));
9405 year = intValue(matcher.group(3));
9406 hour = intValue(matcher.group(4));
9407 minute = intValue(matcher.group(5));
9408 second = intValue(matcher.group(6));
9409 milli = intValue(matcher.group(7));
9410 foundMatch = true;
9411 }
9412 }
9413
9414 Calendar calendar = Calendar.getInstance();
9415 calendar.set(Calendar.YEAR, year);
9416 calendar.set(Calendar.MONTH, month-1);
9417 calendar.set(Calendar.DAY_OF_MONTH, day);
9418 calendar.set(Calendar.HOUR_OF_DAY, hour);
9419 calendar.set(Calendar.MINUTE, minute);
9420 calendar.set(Calendar.SECOND, second);
9421 calendar.set(Calendar.MILLISECOND, milli);
9422 return calendar.getTime();
9423 }
9424
9425
9426
9427
9428
9429
9430
9431 public static int monthInt(String mon) {
9432
9433 if (!isBlank(mon)) {
9434 mon = mon.toLowerCase();
9435
9436 if (equals(mon, "jan") || equals(mon, "january")) {
9437 return 1;
9438 }
9439
9440 if (equals(mon, "feb") || equals(mon, "february")) {
9441 return 2;
9442 }
9443
9444 if (equals(mon, "mar") || equals(mon, "march")) {
9445 return 3;
9446 }
9447
9448 if (equals(mon, "apr") || equals(mon, "april")) {
9449 return 4;
9450 }
9451
9452 if (equals(mon, "may")) {
9453 return 5;
9454 }
9455
9456 if (equals(mon, "jun") || equals(mon, "june")) {
9457 return 6;
9458 }
9459
9460 if (equals(mon, "jul") || equals(mon, "july")) {
9461 return 7;
9462 }
9463
9464 if (equals(mon, "aug") || equals(mon, "august")) {
9465 return 8;
9466 }
9467
9468 if (equals(mon, "sep") || equals(mon, "september")) {
9469 return 9;
9470 }
9471
9472 if (equals(mon, "oct") || equals(mon, "october")) {
9473 return 10;
9474 }
9475
9476 if (equals(mon, "nov") || equals(mon, "november")) {
9477 return 11;
9478 }
9479
9480 if (equals(mon, "dec") || equals(mon, "december")) {
9481 return 12;
9482 }
9483
9484 }
9485
9486 throw new RuntimeException("Invalid month: " + mon);
9487 }
9488
9489
9490
9491
9492
9493
9494 public static Map<String, String> propertiesThreadLocalOverrideMap(String propertiesFileName) {
9495 Map<String, Map<String, String>> overrideMap = propertiesThreadLocalOverrideMap.get();
9496 if (overrideMap == null) {
9497 overrideMap = new HashMap<String, Map<String, String>>();
9498 propertiesThreadLocalOverrideMap.set(overrideMap);
9499 }
9500 Map<String, String> propertiesOverrideMap = overrideMap.get(propertiesFileName);
9501 if (propertiesOverrideMap == null) {
9502 propertiesOverrideMap = new HashMap<String, String>();
9503 overrideMap.put(propertiesFileName, propertiesOverrideMap);
9504 }
9505 return propertiesOverrideMap;
9506 }
9507
9508
9509
9510
9511 private static boolean configuredLogs = false;
9512
9513
9514 public static String theLogLevel = "WARNING";
9515
9516
9517
9518
9519
9520
9521 public static String fileAddLastSlashIfNotExists(String filePath) {
9522 filePath = filePath.replace(File.separatorChar == '/' ? '\\' : '/', File.separatorChar);
9523 if (!filePath.endsWith(File.separator)) {
9524 filePath = filePath + File.separatorChar;
9525 }
9526 return filePath;
9527 }
9528
9529
9530
9531
9532
9533 public static Log retrieveLog(Class<?> theClass) {
9534
9535 Log theLog = LogFactory.getLog(theClass);
9536
9537 if (!configuredLogs) {
9538 String logLevel = theLogLevel;
9539 String logFile = null;
9540
9541 boolean hasLogLevel = !isBlank(logLevel);
9542 boolean hasLogFile = !isBlank(logFile);
9543
9544 if (hasLogLevel || hasLogFile) {
9545 if (theLog instanceof Jdk14Logger) {
9546 Jdk14Logger jdkLogger = (Jdk14Logger) theLog;
9547 Logger logger = jdkLogger.getLogger();
9548
9549 long timeToLive = 60;
9550 while (logger.getParent() != null && timeToLive-- > 0) {
9551
9552 logger = logger.getParent();
9553 }
9554
9555 if (length(logger.getHandlers()) == 1) {
9556
9557
9558 if (logger.getHandlers()[0].getClass() == ConsoleHandler.class) {
9559 logger.removeHandler(logger.getHandlers()[0]);
9560 }
9561 }
9562
9563 if (length(logger.getHandlers()) == 0) {
9564 Handler handler = null;
9565 if (hasLogFile) {
9566 try {
9567 handler = new FileHandler(logFile, true);
9568 } catch (IOException ioe) {
9569 throw new RuntimeException(ioe);
9570 }
9571 } else {
9572 handler = new ConsoleHandler();
9573 }
9574 handler.setFormatter(new SimpleFormatter());
9575 handler.setLevel(Level.ALL);
9576 logger.addHandler(handler);
9577
9578 logger.setUseParentHandlers(false);
9579 }
9580
9581 if (hasLogLevel) {
9582 Level level = Level.parse(logLevel);
9583
9584 logger.setLevel(level);
9585
9586 }
9587 }
9588 }
9589
9590 configuredLogs = true;
9591 }
9592
9593 return new GrouperInstallerLog(theLog);
9594
9595 }
9596
9597
9598
9599
9600
9601 public static void tar(File directory, File tarFile) {
9602 tar(directory, tarFile, true);
9603 }
9604
9605
9606
9607
9608
9609
9610
9611 public static void tar(File directory, File tarFile, boolean includeDirectoryInTarPath) {
9612
9613 try {
9614 tarFile.createNewFile();
9615 TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(new FileOutputStream(tarFile));
9616
9617
9618 tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
9619
9620 for (File file : fileListRecursive(directory)) {
9621 if (file.isFile()) {
9622 String relativePath = (includeDirectoryInTarPath ? (directory.getName() + File.separator) : "") + fileRelativePath(directory, file);
9623
9624 relativePath = replace(relativePath, "\\", "/");
9625 TarArchiveEntry entry = new TarArchiveEntry(file, relativePath);
9626 tarArchiveOutputStream.putArchiveEntry(entry);
9627 copy(new FileInputStream(file), tarArchiveOutputStream);
9628 tarArchiveOutputStream.closeArchiveEntry();
9629 }
9630 }
9631
9632 tarArchiveOutputStream.close();
9633 } catch (Exception e) {
9634 throw new RuntimeException("Error creating tar: " + tarFile.getAbsolutePath() + ", from dir: " + directory.getAbsolutePath(), e);
9635 }
9636 }
9637
9638
9639
9640
9641
9642
9643 public static void gzip(File inputFile, File outputFile) {
9644 GZIPOutputStream gzipOutputStream = null;
9645
9646 try {
9647
9648 outputFile.createNewFile();
9649
9650 gzipOutputStream = new GZIPOutputStream(
9651 new BufferedOutputStream(new FileOutputStream(outputFile)));
9652
9653 copy(new FileInputStream(inputFile), gzipOutputStream);
9654 } catch (Exception e) {
9655 throw new RuntimeException("Error creating gzip from " + inputFile.getAbsolutePath() + " to " + outputFile.getAbsolutePath());
9656 } finally {
9657 closeQuietly(gzipOutputStream);
9658 }
9659
9660 }
9661
9662
9663
9664
9665
9666
9667 public static String fileSha1(File file) {
9668
9669 FileInputStream fis = null;
9670
9671 try {
9672 MessageDigest md = MessageDigest.getInstance("SHA1");
9673 fis = new FileInputStream(file);
9674 byte[] dataBytes = new byte[1024];
9675
9676 int nread = 0;
9677
9678 while ((nread = fis.read(dataBytes)) != -1) {
9679 md.update(dataBytes, 0, nread);
9680 };
9681
9682 byte[] mdbytes = md.digest();
9683
9684
9685 StringBuffer sb = new StringBuffer("");
9686 for (int i = 0; i < mdbytes.length; i++) {
9687 sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
9688 }
9689 return sb.toString();
9690 } catch (Exception e) {
9691 throw new RuntimeException("Problem getting checksum of file: " + file.getAbsolutePath(), e);
9692 } finally {
9693 closeQuietly(fis);
9694 }
9695 }
9696
9697
9698 private static Map<String, String> grouperInstallerOverrideMap = new LinkedHashMap<String, String>();
9699
9700
9701
9702
9703
9704 public static Map<String, String> grouperInstallerOverrideMap() {
9705 return grouperInstallerOverrideMap;
9706 }
9707
9708
9709
9710
9711
9712 public static Properties grouperInstallerProperties() {
9713 Properties properties = null;
9714 try {
9715 properties = propertiesFromResourceName(
9716 "grouper.installer.properties", true, false, GrouperInstallerUtils.class, null);
9717 if (properties == null) {
9718 properties = new Properties();
9719 }
9720 } catch (Exception e) {
9721 throw new RuntimeException("Error accessing file: grouper.installer.properties " +
9722 "This properties file needs to be in the same directory as grouperInstaller.jar, or on your Java classpath", e);
9723 }
9724 return properties;
9725 }
9726
9727
9728
9729
9730
9731
9732 public static boolean propertiesContainsKey(String key) {
9733 return grouperInstallerProperties().containsKey(key);
9734 }
9735
9736
9737
9738
9739
9740
9741
9742 public static String propertiesValue(String key, boolean required) {
9743 return GrouperInstallerUtils.propertiesValue("grouper.installer.properties",
9744 grouperInstallerProperties(),
9745 GrouperInstallerUtils.grouperInstallerOverrideMap(), key, required);
9746 }
9747
9748
9749
9750
9751
9752
9753
9754
9755 public static boolean propertiesValueBoolean(String key, boolean defaultValue, boolean required ) {
9756 return GrouperInstallerUtils.propertiesValueBoolean(
9757 "grouper.installer.properties", grouperInstallerProperties(),
9758 GrouperInstallerUtils.grouperInstallerOverrideMap(),
9759 key, defaultValue, required);
9760 }
9761
9762
9763
9764
9765
9766
9767
9768
9769 public static int propertiesValueInt(String key, int defaultValue, boolean required ) {
9770 return GrouperInstallerUtils.propertiesValueInt(
9771 "grouper.installer.properties", grouperInstallerProperties(),
9772 GrouperInstallerUtils.grouperInstallerOverrideMap(),
9773 key, defaultValue, required);
9774 }
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796 public static int copy(InputStream input, OutputStream output) throws IOException {
9797 long count = copyLarge(input, output);
9798 if (count > Integer.MAX_VALUE) {
9799 return -1;
9800 }
9801 return (int) count;
9802 }
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818 public static long copyLarge(InputStream input, OutputStream output)
9819 throws IOException {
9820 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
9821 long count = 0;
9822 int n = 0;
9823 while (-1 != (n = input.read(buffer))) {
9824 output.write(buffer, 0, n);
9825 count += n;
9826 }
9827 return count;
9828 }
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838 public static void deleteRecursiveDirectory(String dirName) {
9839
9840 File dir = new File(dirName);
9841
9842
9843 if (!dir.exists()) {
9844 return;
9845 }
9846
9847
9848 if (!dir.isDirectory()) {
9849 throw new RuntimeException("The directory: " + dirName + " is not a directory");
9850 }
9851
9852
9853 File[] allFiles = dir.listFiles();
9854
9855
9856 for (int i = 0; i < allFiles.length; i++) {
9857 if (-1 < allFiles[i].getName().indexOf("..")) {
9858 continue;
9859 }
9860
9861 if (allFiles[i].isFile()) {
9862
9863 if (!allFiles[i].delete()) {
9864 throw new RuntimeException("Could not delete file: " + allFiles[i].getPath());
9865 }
9866 } else {
9867
9868 deleteRecursiveDirectory(allFiles[i].getPath());
9869 }
9870 }
9871
9872
9873 if (!dir.delete()) {
9874 throw new RuntimeException("Could not delete directory: " + dir.getPath());
9875 }
9876 }
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886 public static CommandResult execCommand(String command, boolean printProgress) {
9887 String[] args = splitTrim(command, " ");
9888 return execCommand(args, printProgress);
9889 }
9890
9891
9892
9893
9894
9895 private static class StreamGobbler implements Runnable {
9896
9897
9898 private InputStream inputStream;
9899
9900
9901 private String resultString;
9902
9903
9904 private String type;
9905
9906
9907 private String command;
9908
9909
9910 private File printToFile;
9911
9912
9913 private boolean outOrErr;
9914
9915
9916
9917
9918 private boolean printOutputErrorAsReceived;
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929 private StreamGobbler(InputStream is, String theType, String theCommand, File thePrintToFile,
9930 boolean thePrintOutputErrorAsReceived, boolean theOutOrErr) {
9931 this.inputStream = is;
9932 this.type = theType;
9933 this.command = theCommand;
9934 this.printToFile = thePrintToFile;
9935 this.printOutputErrorAsReceived = thePrintOutputErrorAsReceived;
9936 this.outOrErr = theOutOrErr;
9937 }
9938
9939
9940
9941
9942
9943 public String getResultString() {
9944 return this.resultString;
9945 }
9946
9947
9948
9949
9950
9951 @Override
9952 public void run() {
9953
9954
9955 FileOutputStream fileOutputStream = null;
9956
9957 try {
9958 fileOutputStream = this.printToFile == null ? null : new FileOutputStream(this.printToFile);
9959 } catch (IOException ioe) {
9960 throw new RuntimeException(ioe);
9961 }
9962
9963 try {
9964
9965 if (this.printOutputErrorAsReceived) {
9966 if (this.outOrErr) {
9967 copy(this.inputStream, System.out);
9968 } else {
9969 copy(this.inputStream, System.err);
9970 }
9971 } else if (this.printToFile != null) {
9972 copy(this.inputStream, fileOutputStream);
9973
9974 } else {
9975 StringWriter stringWriter = new StringWriter();
9976 copy(this.inputStream, stringWriter);
9977 this.resultString = stringWriter.toString();
9978 }
9979 } catch (Exception e) {
9980
9981 LOG.warn("Error saving output of executable: " + (this.resultString)
9982 + ", " + this.type + ", " + this.command, e);
9983 throw new RuntimeException(e);
9984
9985 } finally {
9986 closeQuietly(fileOutputStream);
9987 }
9988 }
9989 }
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000 public static CommandResult execCommand(String[] arguments, boolean printProgress) {
10001 return execCommand(arguments, true, printProgress);
10002 }
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014 public static CommandResult execCommand(String command, String[] arguments, boolean printProgress) {
10015
10016 List<String> args = new ArrayList<String>();
10017 args.add(command);
10018 for (String argument : nonNull(arguments, String.class)) {
10019 args.add(argument);
10020 }
10021
10022 return execCommand(toArray(args, String.class), true, printProgress);
10023 }
10024
10025
10026
10027
10028 private static ExecutorService executorService = Executors.newCachedThreadPool();
10029
10030
10031
10032
10033
10034 public static ExecutorService retrieveExecutorService() {
10035 return executorService;
10036 }
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051 public static CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero, boolean printProgress) {
10052 return execCommand(arguments, exceptionOnExitValueNeZero, true, printProgress);
10053 }
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069 public static CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero, boolean waitFor, boolean printProgress) {
10070 return execCommand(arguments, exceptionOnExitValueNeZero, waitFor, null, null, null, printProgress);
10071 }
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090 public static CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero, boolean waitFor,
10091 String[] envVariables, File workingDirectory, String outputFilePrefix, boolean printProgress) {
10092 return execCommand(arguments, exceptionOnExitValueNeZero, waitFor, envVariables, workingDirectory, outputFilePrefix, false, printProgress);
10093 }
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113 public static CommandResult execCommand(final String[] arguments, final boolean exceptionOnExitValueNeZero, final boolean waitFor,
10114 final String[] envVariables, final File workingDirectory, final String outputFilePrefix,
10115 final boolean printOutputErrorAsReceived, boolean printProgress) {
10116 return execCommand(arguments, exceptionOnExitValueNeZero, waitFor, envVariables,
10117 workingDirectory, outputFilePrefix, printOutputErrorAsReceived, printProgress, true);
10118 }
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139 public static CommandResult execCommand(final String[] arguments, final boolean exceptionOnExitValueNeZero, final boolean waitFor,
10140 final String[] envVariables, final File workingDirectory, final String outputFilePrefix,
10141 final boolean printOutputErrorAsReceived, boolean printProgress, final boolean logError) {
10142
10143 final CommandResult[] result = new CommandResult[1];
10144
10145 Runnable runnable = new Runnable() {
10146
10147 public void run() {
10148 result[0] = execCommandHelper(arguments, exceptionOnExitValueNeZero, waitFor,
10149 envVariables, workingDirectory, outputFilePrefix, printOutputErrorAsReceived, logError);
10150 }
10151 };
10152
10153 GrouperInstallerUtils.threadRunWithStatusDots(runnable, printProgress, logError);
10154
10155 return result[0];
10156
10157
10158 }
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178 private static CommandResult execCommandHelper(String[] arguments, boolean exceptionOnExitValueNeZero, boolean waitFor,
10179 String[] envVariables, File workingDirectory, String outputFilePrefix, boolean printOutputErrorAsReceived, boolean logError) {
10180
10181 if (printOutputErrorAsReceived && !isBlank(outputFilePrefix)) {
10182 throw new RuntimeException("Cant print as received and have output file prefix");
10183 }
10184
10185 Process process = null;
10186
10187 StringBuilder commandBuilder = new StringBuilder();
10188 for (int i = 0; i < arguments.length; i++) {
10189 commandBuilder.append(arguments[i]).append(" ");
10190 }
10191 String command = commandBuilder.toString();
10192 if (LOG.isDebugEnabled()) {
10193 LOG.debug("Running command: " + command);
10194 }
10195 StreamGobbler outputGobbler = null;
10196 StreamGobbler errorGobbler = null;
10197 try {
10198 process = Runtime.getRuntime().exec(arguments, envVariables, workingDirectory);
10199
10200 if (!waitFor) {
10201 return new CommandResult(null, null, -1);
10202 }
10203 outputGobbler = new StreamGobbler(process.getInputStream(), ".out", command, outputFilePrefix == null ? null : new File(outputFilePrefix + "Out.log"), printOutputErrorAsReceived, true);
10204 errorGobbler = new StreamGobbler(process.getErrorStream(), ".err", command, outputFilePrefix == null ? null : new File(outputFilePrefix + "Err.log"), printOutputErrorAsReceived, false);
10205
10206 Thread outputThread = new Thread(outputGobbler);
10207 outputThread.setDaemon(true);
10208 outputThread.start();
10209
10210 Thread errorThread = new Thread(errorGobbler);
10211 errorThread.setDaemon(true);
10212 errorThread.start();
10213
10214 try {
10215 process.waitFor();
10216 } finally {
10217
10218
10219 try {
10220 outputThread.join();
10221 } catch (Exception e) {
10222
10223 }
10224 try {
10225 errorThread.join();
10226 } catch (Exception e) {
10227
10228 }
10229 }
10230 } catch (Exception e) {
10231 if (logError) {
10232 LOG.error("Error running command: " + command, e);
10233 }
10234 throw new RuntimeException("Error running command: " + command + ", " + e.getMessage(), e);
10235 } finally {
10236 try {
10237 process.destroy();
10238 } catch (Exception e) {
10239 }
10240 }
10241
10242
10243 if (process.exitValue() != 0 && exceptionOnExitValueNeZero) {
10244 String message = "Process exit status=" + process.exitValue() + ": out: " +
10245 (outputGobbler == null ? null : outputGobbler.getResultString())
10246 + ", err: " + (errorGobbler == null ? null : errorGobbler.getResultString());
10247 if (logError) {
10248 LOG.error(message + ", on command: " + command + (workingDirectory == null ? "" : (", workingDir: " + workingDirectory.getAbsolutePath())));
10249 }
10250 throw new RuntimeException(message);
10251 }
10252
10253 int exitValue = process.exitValue();
10254 return new CommandResult(errorGobbler.getResultString(), outputGobbler.getResultString(), exitValue);
10255 }
10256
10257
10258
10259
10260
10261 public static class CommandResult{
10262
10263
10264
10265 private String errorText;
10266
10267
10268
10269
10270 private String outputText;
10271
10272
10273
10274
10275 private int exitCode;
10276
10277
10278
10279
10280
10281
10282
10283
10284 public CommandResult(String _errorText, String _outputText, int _exitCode){
10285 this.errorText = _errorText;
10286 this.outputText = _outputText;
10287 this.exitCode = _exitCode;
10288 }
10289
10290
10291
10292
10293
10294
10295
10296 public String getErrorText() {
10297 return this.errorText;
10298 }
10299
10300
10301
10302
10303
10304
10305
10306 public String getOutputText() {
10307 return this.outputText;
10308 }
10309
10310
10311
10312
10313
10314
10315
10316 public int getExitCode() {
10317 return this.exitCode;
10318 }
10319
10320
10321
10322 }
10323
10324
10325
10326
10327
10328 @Deprecated
10329 public static String javaCommand() {
10330 return javaHome() + File.separator + "bin" + File.separator + "java";
10331 }
10332
10333
10334 private static String JAVA_HOME = null;
10335
10336
10337
10338
10339
10340
10341
10342
10343 @Deprecated
10344 public static String javaHome() {
10345 if (isBlank(JAVA_HOME)) {
10346
10347
10348 JAVA_HOME = System.getProperty("java.home");
10349
10350 if (JAVA_HOME.endsWith("jre")) {
10351 String newJavaHome = JAVA_HOME.substring(0,JAVA_HOME.length()-4);
10352 File javac = new File(newJavaHome + File.separator + "bin" + File.separator + "javac");
10353 if (javac.exists()) {
10354 JAVA_HOME = newJavaHome;
10355 }
10356 javac = new File(newJavaHome + File.separator + "bin" + File.separator + "javac.exe");
10357 if (javac.exists()) {
10358 JAVA_HOME = newJavaHome;
10359 }
10360 }
10361 }
10362 return JAVA_HOME;
10363 }
10364
10365
10366
10367
10368
10369
10370
10371 public static boolean portAvailable(int port) {
10372 return portAvailable(port, null);
10373 }
10374
10375
10376
10377
10378
10379
10380
10381
10382 public static boolean portAvailable(int port, String ipAddress) {
10383
10384 ServerSocket ss = null;
10385 try {
10386
10387 if (isBlank(ipAddress) || "0.0.0.0".equals(ipAddress)) {
10388 ss = new ServerSocket(port);
10389 } else {
10390
10391 Pattern pattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)");
10392
10393 Matcher matcher = pattern.matcher(ipAddress);
10394
10395 if (!matcher.matches()) {
10396 throw new RuntimeException("IP address not valid! '" + ipAddress + "'");
10397 }
10398
10399 byte[] b = new byte[4];
10400 for (int i=0;i<4;i++) {
10401 int theInt = intValue(matcher.group(i+1));
10402 if (theInt > 255 || theInt < 0) {
10403 System.out.println("IP address part must be between 0 and 255: '" + theInt + "'");
10404 }
10405 b[i] = (byte)theInt;
10406 }
10407
10408
10409 InetAddress inetAddress = InetAddress.getByAddress(b);
10410
10411 ss = new ServerSocket(port, 50, inetAddress);
10412 }
10413 ss.setReuseAddress(true);
10414 return true;
10415 } catch (IOException e) {
10416 } finally {
10417 if (ss != null) {
10418 try {
10419 ss.close();
10420 } catch (IOException e) {
10421
10422 }
10423 }
10424 }
10425
10426 return false;
10427 }
10428
10429
10430
10431
10432
10433
10434 public static void classpathAddFile(File file) {
10435 try {
10436 classpathAddUrl(file.toURI().toURL());
10437 } catch (IOException ioe) {
10438 throw new RuntimeException("Problem adding file to classpath: " + (file == null ? null : file.getAbsolutePath()));
10439 }
10440 }
10441
10442
10443
10444
10445 private static Set<String> urlsAddedToClasspath = new HashSet<String>();
10446
10447
10448
10449
10450
10451 public static void classpathAddUrl(URL url) {
10452
10453 String urlString = url.toString();
10454 if (urlsAddedToClasspath.contains(urlString)) {
10455 return;
10456 }
10457
10458 URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
10459 Class sysclass = URLClassLoader.class;
10460
10461 try {
10462 Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
10463 method.setAccessible(true);
10464 method.invoke(sysloader, new Object[] { url });
10465 } catch (Throwable t) {
10466 throw new RuntimeException("Error, could not add URL to system classloader: " + urlString, t);
10467 }
10468
10469 urlsAddedToClasspath.add(urlString);
10470 }
10471
10472
10473
10474
10475
10476
10477
10478
10479 public static <T> T listPopOne(List<T> list) {
10480 int size = length(list);
10481 if (size == 1) {
10482 return list.get(0);
10483 } else if (size == 0) {
10484 return null;
10485 }
10486 throw new RuntimeException("More than one object of type " + className(list.get(0))
10487 + " was returned when only one was expected. (size:" + size +")" );
10488 }
10489
10490
10491
10492
10493
10494
10495
10496 public static void copyFile(File sourceFile, File destinationFile) {
10497
10498 copyFile(sourceFile, destinationFile, true);
10499 }
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510 public static boolean copyFile(File sourceFile, File destinationFile, boolean onlyIfDifferentContents,
10511 boolean ignoreWhitespace) {
10512 if (onlyIfDifferentContents) {
10513 String sourceContents = readFileIntoString(sourceFile);
10514 return saveStringIntoFile(destinationFile, sourceContents,
10515 onlyIfDifferentContents, ignoreWhitespace);
10516 }
10517 copyFile(sourceFile, destinationFile);
10518 return true;
10519 }
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536 public static void copyFile(File srcFile, File destFile,
10537 boolean preserveFileDate) {
10538
10539 try {
10540 if (srcFile == null) {
10541 throw new NullPointerException("Source must not be null");
10542 }
10543 if (destFile == null) {
10544 throw new NullPointerException("Destination must not be null");
10545 }
10546 if (srcFile.exists() == false) {
10547 throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
10548 }
10549 if (srcFile.isDirectory()) {
10550 throw new IOException("Source '" + srcFile + "' exists but is a directory");
10551 }
10552 if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
10553 throw new IOException("Source '" + srcFile + "' and destination '" + destFile
10554 + "' are the same");
10555 }
10556 if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) {
10557 if (destFile.getParentFile().mkdirs() == false) {
10558 throw new IOException("Destination '" + destFile
10559 + "' directory cannot be created");
10560 }
10561 }
10562 if (destFile.exists() && destFile.canWrite() == false) {
10563 throw new IOException("Destination '" + destFile + "' exists but is read-only");
10564 }
10565 doCopyFile(srcFile, destFile, preserveFileDate);
10566 } catch (IOException ioe) {
10567 throw new RuntimeException(ioe);
10568 }
10569 }
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579 private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
10580 throws IOException {
10581 if (destFile.exists() && destFile.isDirectory()) {
10582 throw new IOException("Destination '" + destFile + "' exists but is a directory");
10583 }
10584
10585 FileInputStream input = new FileInputStream(srcFile);
10586 try {
10587 FileOutputStream output = new FileOutputStream(destFile);
10588 try {
10589 copy(input, output);
10590 } finally {
10591 closeQuietly(output);
10592 }
10593 } finally {
10594 closeQuietly(input);
10595 }
10596
10597 if (srcFile.length() != destFile.length()) {
10598 throw new IOException("Failed to copy full contents from '" +
10599 srcFile + "' to '" + destFile + "'");
10600 }
10601 if (preserveFileDate) {
10602 destFile.setLastModified(srcFile.lastModified());
10603 }
10604 }
10605
10606
10607
10608
10609
10610
10611
10612 public static NodeList xpathEvaluate(File xmlFile, String xpathExpression) {
10613 InputStream inputStream = null;
10614 try {
10615 inputStream = new FileInputStream(xmlFile);
10616 return xpathEvaluate(inputStream, xpathExpression);
10617 } catch (Exception e) {
10618 String errorMessage = "Problem with file: " + xmlFile == null ? null : xmlFile.getAbsolutePath();
10619 if (e instanceof RuntimeException) {
10620 GrouperInstallerUtils.injectInException(e, errorMessage);
10621 throw (RuntimeException)e;
10622 }
10623 throw new RuntimeException(errorMessage, e);
10624 } finally {
10625 GrouperInstallerUtils.closeQuietly(inputStream);
10626 }
10627 }
10628
10629
10630
10631
10632
10633
10634 public static NodeList xpathEvaluate(URL url, String xpathExpression) {
10635 InputStream inputStream = null;
10636 try {
10637 inputStream = url.openStream();
10638 return xpathEvaluate(inputStream, xpathExpression);
10639 } catch (Exception e) {
10640 String errorMessage = "Problem with url: " + url == null ? null : url.toExternalForm();
10641 if (e instanceof RuntimeException) {
10642 GrouperInstallerUtils.injectInException(e, errorMessage);
10643 throw (RuntimeException)e;
10644 }
10645 throw new RuntimeException(errorMessage, e);
10646 } finally {
10647 GrouperInstallerUtils.closeQuietly(inputStream);
10648 }
10649 }
10650
10651
10652
10653
10654
10655
10656 public static NodeList xpathEvaluate(InputStream inputStream, String xpathExpression) {
10657
10658 try {
10659 DocumentBuilderFactory domFactory = xmlDocumentBuilderFactory();
10660 DocumentBuilder builder = domFactory.newDocumentBuilder();
10661 Document doc = builder.parse(inputStream);
10662 XPath xpath = XPathFactory.newInstance().newXPath();
10663
10664 XPathExpression expr = xpath.compile(xpathExpression);
10665
10666 Object result = expr.evaluate(doc, XPathConstants.NODESET);
10667 NodeList nodes = (NodeList) result;
10668 return nodes;
10669 } catch (Exception e) {
10670 throw new RuntimeException("Problem evaluating xpath: " + ", expression: '" + xpathExpression + "'", e);
10671 }
10672
10673 }
10674
10675
10676
10677
10678
10679 public static DocumentBuilderFactory xmlDocumentBuilderFactory() {
10680 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
10681 domFactory.setNamespaceAware(true);
10682 domFactory.setValidating(false);
10683 try {
10684 domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
10685 } catch (ParserConfigurationException pce) {
10686 throw new RuntimeException(pce);
10687 }
10688 return domFactory;
10689 }
10690
10691
10692 private static final String[] XML_SEARCH_NO_SINGLE = new String[]{"&","<",">","\""};
10693
10694
10695 private static final String[] XML_REPLACE_NO_SINGLE = new String[]{"&","<",">","""};
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706 public static String xmlEscape(String input) {
10707 return xmlEscape(input, true);
10708 }
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719 public static String xmlEscape(String input, boolean isEscape) {
10720 if (isEscape) {
10721 return replace(input, XML_SEARCH_NO_SINGLE, XML_REPLACE_NO_SINGLE);
10722 }
10723 return replace(input, XML_REPLACE_NO_SINGLE, XML_SEARCH_NO_SINGLE);
10724 }
10725
10726
10727
10728
10729
10730
10731
10732
10733 public static String xpathEvaluateAttribute(File xmlFile, String xpathExpression, String attributeName) {
10734 NodeList nodes = GrouperInstallerUtils.xpathEvaluate(xmlFile, xpathExpression);
10735 if (nodes == null || nodes.getLength() == 0) {
10736 return null;
10737 }
10738 if (nodes.getLength() != 1) {
10739 throw new RuntimeException("There is more than 1 xpath expression: '" + xpathExpression + "' element in server.xml: " + xmlFile.getAbsolutePath());
10740 }
10741
10742
10743 NamedNodeMap attributes = nodes.item(0).getAttributes();
10744 if (attributes == null || attributes.getLength() == 0 ) {
10745 return null;
10746 }
10747 Node attribute = attributes.getNamedItem(attributeName);
10748 if (attribute == null) {
10749 return null;
10750 }
10751
10752 String nodeValue = attribute.getNodeValue();
10753 return nodeValue;
10754 }
10755
10756
10757
10758
10759
10760
10761
10762
10763 public static String xmlElementToXml(String elementName,
10764 String extraAttributes, Map<String, String> attributes) {
10765
10766 StringBuilder result = new StringBuilder();
10767
10768 result.append("<").append(elementName).append(" ");
10769
10770 if (!isBlank(extraAttributes)) {
10771 result.append(extraAttributes);
10772 }
10773
10774 for (String attributeName : attributes.keySet()) {
10775 result.append(" ").append(attributeName).append("=\"");
10776 String attributeValue = GrouperInstallerUtils.trimToEmpty(attributes.get(attributeName));
10777 result.append(GrouperInstallerUtils.xmlEscape(attributeValue)).append("\"");
10778 }
10779
10780 result.append(" />");
10781
10782 return result.toString();
10783 }
10784
10785
10786
10787
10788
10789
10790
10791 public static String xmlToString(Node document) {
10792 try {
10793 DOMSource domSource = new DOMSource(document);
10794 StringWriter writer = new StringWriter();
10795 StreamResult result = new StreamResult(writer);
10796 TransformerFactory tf = TransformerFactory.newInstance();
10797 Transformer transformer = tf.newTransformer();
10798 transformer.transform(domSource, result);
10799 return writer.toString();
10800 } catch (Exception exception) {
10801 throw new RuntimeException(exception);
10802 }
10803 }
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813 public static Integer xpathEvaluateAttributeInt(File xmlFile, String xpathExpression, String attributeName, Integer defaultValue) {
10814 String nodeValue = xpathEvaluateAttribute(xmlFile, xpathExpression, attributeName);
10815 Integer intValue = GrouperInstallerUtils.intValue(nodeValue, defaultValue);
10816 return intValue;
10817 }
10818
10819
10820
10821
10822
10823
10824 public static String jarVersion(File jarFile) {
10825 return jarVersion(jarFile, false);
10826 }
10827
10828
10829
10830
10831
10832
10833
10834 public static File jarNewerVersion(File jar1, File jar2) {
10835
10836 String version1 = jarVersion(jar1, false);
10837 String version2 = jarVersion(jar2, false);
10838
10839 if (version1 == null && version2 == null) {
10840 return null;
10841 }
10842
10843 if (version1 == null) {
10844 return jar2;
10845 }
10846
10847 if (version2 == null) {
10848 return jar1;
10849 }
10850
10851 int compare = compareVersions(version1, version2);
10852 return (compare >= 0 ? jar1 : jar2);
10853 }
10854
10855
10856 private static final String[] versionProperties = new String[]{
10857 "Implementation-Version","Version"};
10858
10859
10860
10861
10862
10863
10864
10865 public static String jarVersion(Class sampleClass) throws Exception {
10866 return manifestProperty(sampleClass, versionProperties);
10867 }
10868
10869
10870 private static String grouperVersionString = null;
10871
10872
10873
10874
10875
10876 public static String grouperInstallerVersion() {
10877 if (grouperVersionString == null) {
10878
10879 try {
10880 grouperVersionString = GrouperInstallerUtils.jarVersion(GiGrouperVersion.class);
10881 } catch (Exception e) {
10882 if (LOG.isDebugEnabled()) {
10883 LOG.debug("Can't find version of grouper jar, using 2.5.0", e);
10884 } else {
10885 LOG.warn("Can't find version of grouper jar, using 2.5.0");
10886 }
10887 }
10888 if (grouperVersionString == null) {
10889 grouperVersionString = "2.5.0";
10890 }
10891 }
10892 return grouperVersionString;
10893 }
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903 public static String manifestProperty(Class sampleClass, String[] propertyNames) throws Exception {
10904 File jarFile = jarFile(sampleClass);
10905 URL manifestUrl = new URL("jar:file:" + jarFile.getCanonicalPath() + "!/META-INF/MANIFEST.MF");
10906 Manifest manifest = new Manifest(manifestUrl.openStream());
10907 Map<String, Attributes> attributeMap = manifest.getEntries();
10908 String value = null;
10909 for (String propertyName : propertyNames) {
10910 value = manifest.getMainAttributes().getValue(propertyName);
10911 if (!isBlank(value)) {
10912 break;
10913 }
10914 }
10915 if (value == null) {
10916 OUTER:
10917 for (Attributes attributes: attributeMap.values()) {
10918 for (String propertyName : propertyNames) {
10919 value = attributes.getValue(propertyName);
10920 if (!isBlank(value)) {
10921 break OUTER;
10922 }
10923 }
10924 }
10925 }
10926 if (value == null) {
10927
10928 for (Attributes attributes: attributeMap.values()) {
10929 for (Object key : attributes.keySet()) {
10930 LOG.info(jarFile.getName() + ", " + key + ": " + attributes.getValue((Name)key));
10931 }
10932 }
10933 Attributes attributes = manifest.getMainAttributes();
10934 for (Object key : attributes.keySet()) {
10935 LOG.info(jarFile.getName() + ", " + key + ": " + attributes.getValue((Name)key));
10936 }
10937 }
10938 return value;
10939 }
10940
10941
10942
10943
10944
10945
10946
10947
10948 public static String jarVersion(File jarFile, boolean exceptionIfProblem) {
10949 try {
10950 String version = jarVersion0(jarFile);
10951
10952 if (isBlank(version)) {
10953 version = jarVersion1(jarFile);
10954 }
10955
10956 if (isBlank(version)) {
10957
10958
10959 if (tempFilePathForJars != null) {
10960
10961 String jarFilePath = jarFile.getAbsolutePath();
10962 jarFilePath = replace(jarFilePath, ":", "_");
10963 if (jarFilePath.startsWith("/") || jarFilePath.startsWith("\\")) {
10964 jarFilePath = jarFilePath.substring(1);
10965 }
10966 jarFilePath = tempFilePathForJars + jarFilePath;
10967 File bakJarFile = new File(jarFilePath);
10968 mkdirs(bakJarFile.getParentFile());
10969 copyFile(jarFile, bakJarFile);
10970 version = jarVersion2(bakJarFile);
10971 } else {
10972 throw new RuntimeException("You need to set tempFileForJars");
10973 }
10974
10975 }
10976 return version;
10977 } catch (RuntimeException e) {
10978 injectInException(e, "Problem with jar: " + jarFile.getAbsolutePath());
10979 if (exceptionIfProblem) {
10980 throw e;
10981 }
10982 System.out.println("Non-fatal issue with " + jarFile.getAbsolutePath() + ", " + e.getMessage() + ", assuming cant find version");
10983 }
10984 return null;
10985 }
10986
10987
10988
10989
10990
10991
10992 public static String jarVersion0(File jarFile) {
10993 Pattern versionPattern = Pattern.compile("^.*-((\\d+)\\.(\\d+)(\\.(\\d+))*)\\.jar*$");
10994 String fileName = jarFile.getName();
10995 Matcher matcher = versionPattern.matcher(fileName);
10996 if (matcher.matches()) {
10997 return matcher.group(1);
10998 }
10999 return null;
11000 }
11001
11002
11003
11004
11005 public static String tempFilePathForJars = null;
11006
11007
11008
11009
11010
11011
11012 public static String jarVersion2(File jarFile) {
11013
11014 InputStream manifestStream = null;
11015 try {
11016 URL manifestUrl = new URL("jar:file:" + jarFile.getCanonicalPath() + "!/META-INF/MANIFEST.MF");
11017 manifestStream = manifestUrl.openStream();
11018 Manifest manifest = new Manifest(manifestStream);
11019 return manifest == null ? null : manifestVersion(jarFile, manifest);
11020 } catch (Exception e) {
11021 if (e instanceof RuntimeException) {
11022 throw (RuntimeException)e;
11023 }
11024 throw new RuntimeException(jarFile.getAbsolutePath() + ", " + e.getMessage(), e);
11025 } finally {
11026 closeQuietly(manifestStream);
11027 }
11028 }
11029
11030
11031
11032
11033
11034
11035 public static String[] splitLines(String string) {
11036 String newline = newlineFromFile(string);
11037 String[] lines = null;
11038 if ("\n".equals(newline)) {
11039 lines = string.split("[\\n]");
11040 } else if ("\r".equals(newline)) {
11041 lines = string.split("[\\r]");
11042 } else if ("\r\n".equals(newline)) {
11043 lines = string.split("[\\r\\n]");
11044 } else {
11045 lines = string.split("[\\r\\n]+");
11046 }
11047 return lines;
11048 }
11049
11050
11051
11052
11053
11054
11055 public static String replaceNewlinesWithSpace(String input) {
11056
11057 if (input == null) {
11058 return null;
11059 }
11060
11061 input = GrouperInstallerUtils.replace(input, "\r\n", " ");
11062 input = GrouperInstallerUtils.replace(input, "\r", " ");
11063 input = GrouperInstallerUtils.replace(input, "\n", " ");
11064
11065 return input;
11066
11067 }
11068
11069
11070
11071
11072 private static Set<String> printedCantFindVersionJarName = new HashSet<String>();
11073
11074 static {
11075
11076
11077
11078 printedCantFindVersionJarName.add("sqljdbc4.jar");
11079 }
11080
11081
11082
11083
11084
11085
11086 public static String manifestVersion(File jarFile, Manifest manifest) {
11087
11088 boolean printJarVersionProblemsV1 = propertiesValueBoolean("grouperInstaller.printJarVersionIssuesV1", false, false);
11089
11090 String[] propertyNames = new String[]{
11091 "Implementation-Version","Version"};
11092
11093 Map<String, Attributes> attributeMap = manifest.getEntries();
11094 String value = null;
11095 for (String propertyName : propertyNames) {
11096 value = manifest.getMainAttributes().getValue(propertyName);
11097 if (!isBlank(value)) {
11098 break;
11099 }
11100 }
11101 if (value == null) {
11102 OUTER:
11103 for (Attributes attributes: attributeMap.values()) {
11104 for (String propertyName : propertyNames) {
11105 value = attributes.getValue(propertyName);
11106 if (!isBlank(value)) {
11107 break OUTER;
11108 }
11109 }
11110 }
11111 }
11112 if (value == null) {
11113 if (!printedCantFindVersionJarName.contains(jarFile.getName())) {
11114 printedCantFindVersionJarName.add(jarFile.getName());
11115 if (printJarVersionProblemsV1) {
11116 System.out.println("Error: cant find version for jar: " + jarFile.getName());
11117 }
11118 if (printJarVersionProblemsV1) {
11119 for (Attributes attributes: attributeMap.values()) {
11120 for (Object key : attributes.keySet()) {
11121 System.out.println(jarFile.getName() + ", " + key + ": " + attributes.getValue((Name)key));
11122 }
11123 }
11124 Attributes attributes = manifest.getMainAttributes();
11125 for (Object key : attributes.keySet()) {
11126 System.out.println(jarFile.getName() + ", main " + key + ": " + attributes.getValue((Name)key));
11127 }
11128 }
11129 }
11130 }
11131 return value;
11132 }
11133
11134
11135
11136
11137
11138
11139 public static String newlineFromFile(String fileContents) {
11140 String newline = "\n";
11141 if (fileContents.contains("\r\n")) {
11142 newline = "\r\n";
11143 }
11144 if (fileContents.contains("\n\r")) {
11145 newline = "\n\r";
11146 }
11147 if (fileContents.contains("\r")) {
11148 newline = "\r";
11149 }
11150 return newline;
11151 }
11152
11153
11154
11155
11156
11157
11158
11159 public static List<File> fileListRecursive(File parent, String fileName) {
11160 List<File> allFiles = GrouperInstallerUtils.fileListRecursive(parent);
11161 List<File> result = new ArrayList<File>();
11162 for (File file : allFiles) {
11163 if (equals(file.getName(), fileName)) {
11164 result.add(file);
11165 }
11166 }
11167 return result;
11168 }
11169
11170
11171
11172
11173
11174
11175 public static List<File> fileListRecursive(File parent) {
11176 List<File> results = new ArrayList<File>();
11177 fileListRecursiveHelper(parent, results);
11178 return results;
11179 }
11180
11181
11182
11183
11184
11185
11186 private static void fileListRecursiveHelper(File parent, List<File> fileList) {
11187 if (parent == null || !parent.exists() || !parent.isDirectory()) {
11188 return;
11189 }
11190 List<File> subFiles = nonNull(toList(parent.listFiles()));
11191 for (File subFile : subFiles) {
11192 if (subFile.isFile()) {
11193 fileList.add(subFile);
11194 }
11195 if (subFile.isDirectory()) {
11196 fileListRecursiveHelper(subFile, fileList);
11197 }
11198 }
11199 }
11200
11201
11202
11203
11204
11205 public static String fileMassagePathsNoLeadingOrTrailing(String path) {
11206 path = path.replace(File.separatorChar == '/' ? '\\' : '/', File.separatorChar);
11207 if (path.startsWith(File.separator)) {
11208 path = path.substring(1);
11209 }
11210 if (path.endsWith(File.separator)) {
11211 path = path.substring(0, path.length()-1);
11212 }
11213 return path;
11214 }
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230 public static boolean contentEquals(File file1, File file2) {
11231 try {
11232 boolean file1Exists = file1 != null && file1.exists();
11233 boolean file2Exists = file2 != null && file2.exists();
11234 if (file1Exists != file2Exists) {
11235 return false;
11236 }
11237
11238 if (!file1Exists) {
11239
11240 return true;
11241 }
11242
11243 if (file1.isDirectory() || file2.isDirectory()) {
11244
11245 throw new IOException("Can't compare directories, only files: " + file1.getAbsolutePath() + ", " + file2.getAbsolutePath());
11246 }
11247
11248 if (file1.length() != file2.length()) {
11249
11250 return false;
11251 }
11252
11253 if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
11254
11255 return true;
11256 }
11257
11258 InputStream input1 = null;
11259 InputStream input2 = null;
11260 try {
11261 input1 = new FileInputStream(file1);
11262 input2 = new FileInputStream(file2);
11263 return contentEquals(input1, input2);
11264
11265 } finally {
11266 closeQuietly(input1);
11267 closeQuietly(input2);
11268 }
11269 } catch (IOException ioe) {
11270 throw new RuntimeException(ioe);
11271 }
11272 }
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288 public static boolean contentEquals(InputStream input1, InputStream input2)
11289 throws IOException {
11290 if (!(input1 instanceof BufferedInputStream)) {
11291 input1 = new BufferedInputStream(input1);
11292 }
11293 if (!(input2 instanceof BufferedInputStream)) {
11294 input2 = new BufferedInputStream(input2);
11295 }
11296
11297 int ch = input1.read();
11298 while (-1 != ch) {
11299 int ch2 = input2.read();
11300 if (ch != ch2) {
11301 return false;
11302 }
11303 ch = input1.read();
11304 }
11305
11306 int ch2 = input2.read();
11307 return (ch2 == -1);
11308 }
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325 public static boolean contentEquals(Reader input1, Reader input2)
11326 throws IOException {
11327 if (!(input1 instanceof BufferedReader)) {
11328 input1 = new BufferedReader(input1);
11329 }
11330 if (!(input2 instanceof BufferedReader)) {
11331 input2 = new BufferedReader(input2);
11332 }
11333
11334 int ch = input1.read();
11335 while (-1 != ch) {
11336 int ch2 = input2.read();
11337 if (ch != ch2) {
11338 return false;
11339 }
11340 ch = input1.read();
11341 }
11342
11343 int ch2 = input2.read();
11344 return (ch2 == -1);
11345 }
11346
11347
11348
11349
11350
11351
11352 public static Set<String> fileDescendantRelativePaths(File parentDir) {
11353 Set<String> result = new LinkedHashSet<String>();
11354 List<File> descendants = fileListRecursive(parentDir);
11355 for (File file : GrouperInstallerUtils.nonNull(descendants)) {
11356 String descendantPath = file.getAbsolutePath();
11357 String parentPath = parentDir.getAbsolutePath();
11358 if (!descendantPath.startsWith(parentPath)) {
11359 throw new RuntimeException("Why doesnt descendantPath '" + descendantPath + "' start with parent path '" + parentPath + "'?");
11360 }
11361 descendantPath = descendantPath.substring(parentPath.length());
11362 if (descendantPath.startsWith("/") || descendantPath.startsWith("\\")) {
11363 descendantPath = descendantPath.substring(1);
11364 }
11365 result.add(descendantPath);
11366 }
11367 return result;
11368 }
11369
11370
11371
11372
11373
11374
11375
11376 public static String fileRelativePath(File parentDir, File file) {
11377
11378 String descendantPath = file.getAbsolutePath();
11379 String parentPath = parentDir.getAbsolutePath();
11380 if (!descendantPath.startsWith(parentPath)) {
11381 throw new RuntimeException("Why doesnt descendantPath '" + descendantPath + "' start with parent path '" + parentPath + "'?");
11382 }
11383 descendantPath = descendantPath.substring(parentPath.length());
11384 if (descendantPath.startsWith("/") || descendantPath.startsWith("\\")) {
11385 descendantPath = descendantPath.substring(1);
11386 }
11387 return descendantPath;
11388 }
11389
11390
11391
11392
11393
11394
11395
11396 public static boolean filePathStartsWith(String bigPath, String prefixPath) {
11397
11398 bigPath = replace(bigPath, "\\\\", "\\");
11399 bigPath = replace(bigPath, "\\", "/");
11400
11401 prefixPath = replace(prefixPath, "\\\\", "\\");
11402 prefixPath = replace(prefixPath, "\\", "/");
11403
11404 return bigPath.startsWith(prefixPath);
11405
11406 }
11407
11408
11409
11410
11411
11412
11413 public static String jarVersion1(File jarFile) {
11414 FileInputStream fileInputStream = null;
11415 try {
11416 fileInputStream = new FileInputStream(jarFile);
11417 JarInputStream jarInputStream = new JarInputStream(fileInputStream);
11418
11419 Manifest manifest = jarInputStream.getManifest();
11420
11421 return manifest == null ? null : manifestVersion(jarFile, manifest);
11422
11423 } catch (Exception e) {
11424 if (e instanceof RuntimeException) {
11425 throw (RuntimeException)e;
11426 }
11427 throw new RuntimeException(e.getMessage(), e);
11428 } finally {
11429 closeQuietly(fileInputStream);
11430 }
11431
11432 }
11433
11434
11435
11436
11437
11438
11439
11440 public static int compareVersions(String s1String, String s2String) {
11441 if (s1String.equals(s2String)) {
11442 return 0;
11443 }
11444
11445 String[] s1Tokens = s1String.split("\\.");
11446 String[] s2Tokens = s2String.split("\\.");
11447
11448 int i = 0;
11449 while( i < s1Tokens.length && i < s2Tokens.length && s1Tokens[i].equals(s2Tokens[i]) ) {
11450 i++;
11451 }
11452
11453 while (i < s1Tokens.length || i < s2Tokens.length) {
11454 Integer s1Value = 0;
11455 Integer s2Value = 0;
11456
11457 if (i < s1Tokens.length) {
11458 String s1Token = s1Tokens[i];
11459 try {
11460 s1Value = Integer.parseInt(s1Token);
11461 } catch (NumberFormatException e) {
11462 System.out.println("WARNING: Could not parse number from '" + s1Token + "' in version string '" + s1String + "'");
11463 return -1;
11464 }
11465 }
11466
11467 if (i < s2Tokens.length) {
11468 String s2Token = s2Tokens[i];
11469 try {
11470 s2Value = Integer.parseInt(s2Token);
11471 } catch (NumberFormatException e) {
11472 System.out.println("WARNING: Could not parse number from '" + s2Token + "' in version string '" + s2String + "' -- assuming -1");
11473 return 1;
11474 }
11475 }
11476
11477 int cmp = s1Value.compareTo(s2Value);
11478 if (cmp != 0) {
11479 return cmp;
11480 }
11481
11482 ++i;
11483 }
11484
11485
11486 return 0;
11487 }
11488 }