1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.util;
20
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23
24
25
26
27 public class Uptime
28 {
29 public static final int NOIMPL = -1;
30
31 public static interface Impl
32 {
33 public long getUptime();
34 }
35
36 public static class DefaultImpl implements Impl
37 {
38 public Object mxBean;
39 public Method uptimeMethod;
40
41 public DefaultImpl()
42 {
43 ClassLoader cl = Thread.currentThread().getContextClassLoader();
44 try
45 {
46 Class<?> mgmtFactory = Class.forName("java.lang.management.ManagementFactory",true,cl);
47 Class<?> runtimeClass = Class.forName("java.lang.management.RuntimeMXBean",true,cl);
48 Class<?> noparams[] = new Class<?>[0];
49 Method mxBeanMethod = mgmtFactory.getMethod("getRuntimeMXBean",noparams);
50 if (mxBeanMethod == null)
51 {
52 throw new UnsupportedOperationException("method getRuntimeMXBean() not found");
53 }
54 mxBean = mxBeanMethod.invoke(mgmtFactory);
55 if (mxBean == null)
56 {
57 throw new UnsupportedOperationException("getRuntimeMXBean() method returned null");
58 }
59 uptimeMethod = runtimeClass.getMethod("getUptime",noparams);
60 if (mxBean == null)
61 {
62 throw new UnsupportedOperationException("method getUptime() not found");
63 }
64 }
65 catch (ClassNotFoundException |
66 NoClassDefFoundError |
67 NoSuchMethodException |
68 SecurityException |
69 IllegalAccessException |
70 IllegalArgumentException |
71 InvocationTargetException e)
72 {
73 throw new UnsupportedOperationException("Implementation not available in this environment",e);
74 }
75 }
76
77 @Override
78 public long getUptime()
79 {
80 try
81 {
82 return (long)uptimeMethod.invoke(mxBean);
83 }
84 catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
85 {
86 return NOIMPL;
87 }
88 }
89 }
90
91 private static final Uptime INSTANCE = new Uptime();
92
93 public static Uptime getInstance()
94 {
95 return INSTANCE;
96 }
97
98 private Impl impl;
99
100 private Uptime()
101 {
102 try
103 {
104 impl = new DefaultImpl();
105 }
106 catch (UnsupportedOperationException e)
107 {
108 System.err.printf("Defaulting Uptime to NOIMPL due to (%s) %s%n",e.getClass().getName(),e.getMessage());
109 impl = null;
110 }
111 }
112
113 public Impl getImpl()
114 {
115 return impl;
116 }
117
118 public void setImpl(Impl impl)
119 {
120 this.impl = impl;
121 }
122
123 public static long getUptime()
124 {
125 Uptime u = getInstance();
126 if (u == null || u.impl == null)
127 {
128 return NOIMPL;
129 }
130 return u.impl.getUptime();
131 }
132 }