2 // ========================================================================
3 // Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.util;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
25 * Provide for a Uptime class that is compatible with Android, GAE, and the new Java 8 compact profiles
29 public static final int NOIMPL = -1;
31 public static interface Impl
33 public long getUptime();
36 public static class DefaultImpl implements Impl
39 public Method uptimeMethod;
43 ClassLoader cl = Thread.currentThread().getContextClassLoader();
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)
52 throw new UnsupportedOperationException("method getRuntimeMXBean() not found");
54 mxBean = mxBeanMethod.invoke(mgmtFactory);
57 throw new UnsupportedOperationException("getRuntimeMXBean() method returned null");
59 uptimeMethod = runtimeClass.getMethod("getUptime",noparams);
62 throw new UnsupportedOperationException("method getUptime() not found");
65 catch (ClassNotFoundException |
66 NoClassDefFoundError |
67 NoSuchMethodException |
69 IllegalAccessException |
70 IllegalArgumentException |
71 InvocationTargetException e)
73 throw new UnsupportedOperationException("Implementation not available in this environment",e);
78 public long getUptime()
82 return (long)uptimeMethod.invoke(mxBean);
84 catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
91 private static final Uptime INSTANCE = new Uptime();
93 public static Uptime getInstance()
104 impl = new DefaultImpl();
106 catch (UnsupportedOperationException e)
108 System.err.printf("Defaulting Uptime to NOIMPL due to (%s) %s%n",e.getClass().getName(),e.getMessage());
113 public Impl getImpl()
118 public void setImpl(Impl impl)
123 public static long getUptime()
125 Uptime u = getInstance();
126 if (u == null || u.impl == null)
130 return u.impl.getUptime();