001package arcommon;
002
003import java.awt.Desktop;
004import java.awt.EventQueue;
005import java.awt.Toolkit;
006import java.io.File;
007import java.io.IOException;
008import java.text.Collator;
009import java.util.ArrayList;
010import java.util.Arrays;
011import java.util.Collection;
012import java.util.Collections;
013import java.util.Date;
014import java.util.Iterator;
015import java.util.List;
016import java.util.Properties;
017
018import arcommon.exception.ExceptionUtil;
019
020public class Util {
021    /**
022     * Sorts the collection c parameter and returns it.
023     * <br>
024     * Note: Objects in the Collection must implemented Comparable!!
025     */
026    public static <T extends Comparable<T>> List<T> sortCollection(Collection<T> c) {
027        ArrayList<T> result = new ArrayList<T>(c);
028        Collections.sort(result);
029        return result;
030    }
031    
032    public static void sortStringListWithLocale(List<String> c) {
033        Collator collator = Collator.getInstance();
034        collator.setStrength(Collator.PRIMARY);
035        Collections.sort(c, collator);
036    }
037    
038    public static void sortStringListCaseInsensitiveOrder(List<String> list) {
039        Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
040    }
041    
042    public static void printMessageWithSourceLine(double number) {
043        printMessageWithSourceLineLocale("" + number);
044    }
045    
046    public static void printMessageWithSourceLine(long number) {
047        printMessageWithSourceLineLocale("" + number);
048    }
049    
050    public static void printMessageWithSourceLine(boolean b) {
051        printMessageWithSourceLineLocale("" + b);
052    }
053    
054    public static void printMessageWithSourceLine(boolean[] texts) {
055        printMessageWithSourceLineLocale(Arrays.toString(texts));
056    }
057    
058    public static void printMessageWithSourceLine(byte[] bytes) {
059        printMessageWithSourceLineLocale(Arrays.toString(bytes));
060    }
061    
062    public static void printMessageWithSourceLine(int[] ints) {
063        printMessageWithSourceLineLocale(Arrays.toString(ints));
064    }
065    
066    public static void printMessageWithSourceLine(long[] longs) {
067        printMessageWithSourceLineLocale(Arrays.toString(longs));
068    }
069    
070    public static void printMessageWithSourceLine(float[] floats) {
071        printMessageWithSourceLineLocale(Arrays.toString(floats));
072    }
073    
074    public static void printMessageWithSourceLine(double[] doubles) {
075        printMessageWithSourceLineLocale(Arrays.toString(doubles));
076    }
077    
078    public static void printMessageWithSourceLine(Object[] objects) {
079        printMessageWithSourceLineLocale(Arrays.toString(objects));
080    }
081    
082    public static void printMessageWithSourceLine(String text) {
083        printMessageWithSourceLineLocale(text);
084    }
085
086    public static void printMessageWithSourceLine(Date date) {
087        printMessageWithSourceLineLocale(DateUtil.dateToDateAndTimeString(date));
088    }
089    
090    public static void printMessageWithSourceLine(Object object) {
091        if (object == null) {
092            printMessageWithSourceLineLocale("null");
093        } else {
094            printMessageWithSourceLineLocale(object.toString());
095        }
096    }
097    
098    public static void printMessageWithSourceLine() {
099        printMessageWithSourceLineLocale("");
100    }
101    
102    private static void printMessageWithSourceLineLocale(String text) {
103        StackTraceElement[] stackTraceElement = ExceptionUtil.stackToStackTraceElements();
104        if (stackTraceElement != null && stackTraceElement.length >= 4) {
105            text = stackTraceElement[3].toString() + " (" + DateUtil.dateToDateAndTimeString(new Date()) + "):\n    " + text;
106        }
107        System.out.println(text);
108    }
109    
110    public static void printCurrentSourceLine() {
111        printCurrentSourceLine(1, false);
112    }
113    
114    public static void printCurrentSourceLine(int callByOffset, boolean err) {
115        StackTraceElement[] stackToStackTraceElements = ExceptionUtil.stackToStackTraceElements();
116        if (err) {
117            System.err.println(stackToStackTraceElements[2 + callByOffset]);
118        } else {
119            System.out.println(stackToStackTraceElements[2 + callByOffset]);
120        }
121    }
122    
123    public static String sourcePathLocationToString(String sourcePath, String fileName, int lineNumber) {
124        String clazz = fileName.replace(sourcePath, "");
125        clazz = clazz.replace("\\", ".");
126        clazz = clazz.replace(".java", "");
127        return sourceClassLocationToString(clazz, fileName, lineNumber);
128    }
129    
130    public static String sourceClassLocationToString(String clazz, String fileName, int lineNumber) {
131        return "\tat " + clazz + ".dummyMethod(" + FileUtil.calculateFileName(fileName) + ":" + lineNumber + ")";
132    }
133    
134    public static void printSourcePathLocation(String sourcePath, String fileName, int lineNumber) {
135        String sourceLocationToString = sourcePathLocationToString(sourcePath, fileName, lineNumber);
136        System.out.println(sourceLocationToString);
137    }
138    
139    public static void printClassLocation(String clazz, String fileName, int lineNumber) {
140        String sourceLocationToString = sourceClassLocationToString(clazz, fileName, lineNumber);
141        System.out.println(sourceLocationToString);
142        
143    }
144    public static List<Object> getEventQueue() {
145        List<Object> queue = new ArrayList<Object>();
146        try {
147            Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
148            EventQueue systemEventQueue = defaultToolkit.getSystemEventQueue();
149            
150            Object fieldValue = ReflectionUtil.getFieldValue(systemEventQueue, "queues");
151            Object[] queues = (Object[])fieldValue;
152            
153            Object head = ReflectionUtil.getFieldValue(queues[1], "head");
154            
155            while (head != null) {
156                Object eventObject = ReflectionUtil.getFieldValue(head, "event");
157                queue.add(eventObject);
158                head = ReflectionUtil.getFieldValue(head, "next");
159            }
160        } catch (Exception e) {
161            e.printStackTrace();
162        }
163        return queue;
164    }
165    
166    public static void sleep(int ms) {
167        try {
168            Thread.sleep(ms);
169        } catch (InterruptedException e) {
170            ;
171        }
172    }
173    
174    public static void printProperties() {
175        Properties properties = System.getProperties();
176        Iterator<Object> i = properties.keySet().iterator();
177        while (i.hasNext()) {
178            String propertyString = (String)i.next();
179            Object property = properties.get(propertyString);
180            System.out.println(propertyString + ": " + property);
181        }
182    }
183
184    /**
185     * Opens the file in a desktop specific way.
186     * @see arcommon.net.NetUtil#openBrowser(String)
187     * @see arcommon.net.NetUtil#openBrowserWithDialog(String)
188     */
189    public static void openFile(String fileName) {
190        String[] commands;
191        switch (Util.getOSType()) {
192            case WINDOWS :
193                commands = new String[] {"cmd.exe", "/c", "start", "\"\"", "\"" + fileName + "\""};
194            break;
195            case LINUX :
196                commands = new String[] {"xdg-open", fileName};
197            break;
198            case MAC :
199                commands = new String[] {"open", fileName};
200            break;
201            default :
202                throw new RuntimeException("Unknown OS type: " + Util.getOSType());
203        }
204        try {
205            Runtime.getRuntime().exec(commands);
206        } catch (IOException e2) {
207            e2.printStackTrace();
208        }
209    }
210    
211    public static void openDirectory(String path) {
212        String windowsExplorer = "C:\\WINDOWS\\explorer.exe";
213        path = FileUtil.calculateAbsolutePath(path);
214        if (isWindowsOS() && FileUtil.exists(windowsExplorer)) {
215            ProcessUtil.startCommand(windowsExplorer, "/n,/e,", "\"" + FileUtil.calculatePath(path) + "\"");
216        } else {
217            try {
218                Desktop d = Desktop.getDesktop();
219                if (!path.endsWith(File.separator) && FileUtil.exists(path)) {
220                    path += File.separator;
221                }
222                path = FileUtil.calculatePath(path);
223                if (path == null || path.length() == 0) {
224                    path = ".";
225                }
226                d.open(new File(path));
227            } catch (IOException e1) {
228                throw new RuntimeException(e1);
229            }
230        }
231    }
232    
233    public static void openContainedDirectoryAndSelectFile(String fileName) {
234        String windowsExplorer = "C:\\WINDOWS\\explorer.exe";
235        fileName = FileUtil.calculateAbsoluteFileName(fileName);
236        if (isWindowsOS() && FileUtil.exists(windowsExplorer) && FileUtil.exists(fileName)) {
237            fileName = fileName.replace('/', '\\');
238            ProcessUtil.startCommand(windowsExplorer, "/n,/e,/select,", "\"" + fileName + "\"");
239        } else {
240            String linuxNautilus = "/usr/bin/nautilus";
241            if (isLinuxOS() && FileUtil.exists(linuxNautilus) && FileUtil.exists(fileName)) {
242                ProcessUtil.startCommand(linuxNautilus, "--new-window", "--select", fileName);
243            } else {
244                String path = FileUtil.calculatePath(fileName);
245                openDirectory(path);
246            }
247        }
248    }
249
250    public static int readNumberFromStdIn(String message) {
251        System.out.print(message);
252        String line = "";
253        try {
254            while (true) {
255                int read = System.in.read();
256                if (read == 13) {
257                    continue;
258                }
259                if (read == 10) {
260                    if (StringUtil.isStringAnInt(line)) {
261                        return StringUtil.stringToInt(line);
262                    }
263                    System.out.println("\"" + line + "\" is not a number");
264                    System.out.print(message);
265                    line = "";
266                    continue;
267                }
268                line += (char)read;
269            }
270        } catch (IOException e) {
271            throw new RuntimeException(e);
272        }
273    }
274
275    public static String readLineFromStdIn() {
276        String line = "";
277        try {
278            while (true) {
279                int read = System.in.read();
280                if (read == -1) {
281                    if (line.length() == 0) {
282                        return null;
283                    }
284                    return line;
285                }
286                if (isWindowsOS()) {
287                    if (read == 10) {
288                        break;
289                    }
290                    if (read == 13) {
291                        continue;
292                    }
293                } else {
294                    if (read == 10) {
295                        break;
296                    }
297                }
298                line += (char)read;
299            }
300            return line;
301        } catch (IOException e) {
302            throw new RuntimeException(e);
303        }
304    }
305    
306    public static enum WindowsType {WINDOWS_XP, WINDOWS_10};
307
308    public static WindowsType getWindowsType() {
309        if (!isWindowsOS()) {
310            throw new RuntimeException("!isWindowsOS()");
311        }
312        if (isWindowsXp()) {
313            return WindowsType.WINDOWS_XP;
314        }
315        if (isWindows10()) {
316            return WindowsType.WINDOWS_10;
317        }
318        throw new RuntimeException("Unknown Windows type: " + OS_NAME);
319    }
320    
321    public static boolean isWindowsXp() {
322        return OS_NAME.startsWith("Windows XP");
323    }
324    
325    public static boolean isWindows10() {
326        return OS_NAME.startsWith("Windows 10");
327    }
328    
329    public static enum OsType {WINDOWS, LINUX, MAC};
330    
331    public static OsType getOSType() {
332        if (isWindowsOS()) {
333            return OsType.WINDOWS;
334        }
335        if (isLinuxOS()) {
336            return OsType.LINUX;
337        }
338        if (isMacOS()) {
339            return OsType.MAC;
340        }
341        throw new RuntimeException("Unknown OS type: " + OS_NAME);
342    }
343    
344    public static boolean isWindowsOS() {
345        return OS_NAME.startsWith("Windows");
346    }
347    
348    public static boolean isLinuxOS() {
349        return OS_NAME.startsWith("Linux");
350    }
351    
352    public static boolean isMacOS() {
353        return OS_NAME.startsWith("Mac");
354    }
355    
356    public static boolean isJava_1_4() {
357        String javaVersionProperty = System.getProperty("java.version");
358        if (javaVersionProperty.startsWith("1.4")) {
359            return true;
360        }
361        return false;
362    }
363
364    // Code copied from org.apache.commons.lang.SystemUtils.java begin...
365    public static float getJavaVersion() {
366        int indexOf = JAVA_VERSION.indexOf('.');
367        String string;
368        if (indexOf != -1) {
369            indexOf = JAVA_VERSION.indexOf('.', indexOf + 1);
370            if (indexOf != -1) {
371                string = JAVA_VERSION.substring(0, indexOf);
372            } else {
373                string = JAVA_VERSION.substring(0, 3);
374            }
375        } else {
376            string = JAVA_VERSION.substring(0, 3);
377        }
378        return Float.parseFloat(string);
379    }
380    
381    public static boolean isJavaVersionAtLeast(float requiredVersion) {
382        return getJavaVersion() >= requiredVersion;
383    }
384    
385    public static final String JAVA_VERSION = System.getProperty("java.version");
386    public static final int JAVA_MODULE_SYSTEM_VERSION = 9;
387    public static final int JAVA_MODULE_SYSTEM_STRICT_VERSION = 16;
388    public static final int JAVA_MODULE_SYSTEM_VERY_STRICT_VERSION = 17;
389    public static final String OS_NAME = System.getProperty("os.name");
390    // ...code copied from org.apache.commons.lang.SystemUtils.java end
391}