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 | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
66 | InvocationTargetException e)
67 {
68 throw new UnsupportedOperationException("Implementation not available",e);
69 }
70 }
71
72 @Override
73 public long getUptime()
74 {
75 try
76 {
77 return (long)uptimeMethod.invoke(mxBean);
78 }
79 catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
80 {
81 return NOIMPL;
82 }
83 }
84 }
85
86 private static final Uptime INSTANCE = new Uptime();
87
88 public static Uptime getInstance()
89 {
90 return INSTANCE;
91 }
92
93 private Impl impl;
94
95 private Uptime()
96 {
97 try
98 {
99 impl = new DefaultImpl();
100 }
101 catch (UnsupportedOperationException e)
102 {
103 System.err.printf("Defaulting Uptime to NOIMPL due to (%s) %s%n",e.getClass().getName(),e.getMessage());
104 impl = null;
105 }
106 }
107
108 public Impl getImpl()
109 {
110 return impl;
111 }
112
113 public void setImpl(Impl impl)
114 {
115 this.impl = impl;
116 }
117
118 public static long getUptime()
119 {
120 Uptime u = getInstance();
121 if (u == null || u.impl == null)
122 {
123 return NOIMPL;
124 }
125 return u.impl.getUptime();
126 }
127 }