1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util.internal;
17
18 import java.security.AccessController;
19 import java.security.PrivilegedActionException;
20 import java.security.PrivilegedExceptionAction;
21 import java.util.concurrent.atomic.AtomicInteger;
22 import java.util.zip.Deflater;
23
24
25
26
27
28
29
30
31
32
33
34
35 public final class DetectionUtil {
36
37 private static final int JAVA_VERSION = javaVersion0();
38 private static final boolean HAS_UNSAFE = hasUnsafe(AtomicInteger.class.getClassLoader());
39 private static final boolean IS_WINDOWS;
40 static {
41 String os = System.getProperty("os.name").toLowerCase();
42
43 IS_WINDOWS = os.indexOf("win") >= 0;
44 }
45
46
47
48
49
50 public static boolean isWindows() {
51 return IS_WINDOWS;
52 }
53
54 public static boolean hasUnsafe() {
55 return HAS_UNSAFE;
56 }
57
58 public static int javaVersion() {
59 return JAVA_VERSION;
60 }
61
62 private static boolean hasUnsafe(ClassLoader loader) {
63 boolean useUnsafe = Boolean.valueOf(SystemPropertyUtil.get("org.jboss.netty.tryUnsafe", "true"));
64 if (!useUnsafe) {
65 return false;
66 }
67
68 try {
69 Class<?> unsafeClazz = Class.forName("sun.misc.Unsafe", true, loader);
70 return hasUnsafeField(unsafeClazz);
71 } catch (Exception e) {
72
73 }
74 return false;
75 }
76
77 private static boolean hasUnsafeField(final Class<?> unsafeClass) throws PrivilegedActionException {
78 return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
79 public Boolean run() throws Exception {
80 unsafeClass.getDeclaredField("theUnsafe");
81 return true;
82 }
83 });
84 }
85
86 private static int javaVersion0() {
87 try {
88
89
90
91 Class.forName("android.app.Application");
92 return 6;
93 } catch (ClassNotFoundException e) {
94
95 }
96
97 try {
98 Deflater.class.getDeclaredField("SYNC_FLUSH");
99 return 7;
100 } catch (Exception e) {
101
102 }
103
104 try {
105 Double.class.getDeclaredField("MIN_NORMAL");
106 return 6;
107 } catch (Exception e) {
108
109 }
110
111 return 5;
112 }
113
114 private DetectionUtil() {
115
116 }
117 }