001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     matic
016 */
017package org.nuxeo.runtime.management.stopwatchs;
018
019import java.io.Serializable;
020import java.lang.reflect.Field;
021import java.util.HashMap;
022import java.util.Map;
023
024import org.javasimon.Stopwatch;
025import org.javasimon.StopwatchSample;
026
027/**
028 * @author matic
029 */
030public class StopwatchMXBeanImpl extends org.javasimon.jmx.StopwatchMXBeanImpl implements StopwatchMXBean {
031
032    public StopwatchMXBeanImpl(Stopwatch stopwatch) {
033        super(stopwatch);
034    }
035
036    @Override
037    public String sampleAsString() {
038        return sample().toString();
039    }
040
041    protected void doFillMap(StopwatchSample sample, Map<String, Serializable> map, Class<?> clazz) {
042        if (clazz == null) {
043            return;
044        }
045        if (Object.class.equals(clazz)) {
046            return;
047        }
048        for (Field f : clazz.getDeclaredFields()) {
049            try {
050                f.setAccessible(true);
051                map.put(f.getName(), (Serializable) f.get(sample));
052            } catch (ReflectiveOperationException e) {
053                throw new RuntimeException(e);
054            }
055        }
056        doFillMap(sample, map, clazz.getSuperclass());
057    }
058
059    @Override
060    public Map<String, Serializable> sampleAsMap() {
061        Map<String, Serializable> map = new HashMap<String, Serializable>();
062        StopwatchSample sample = sample();
063        doFillMap(sample, map, sample.getClass());
064        return map;
065    }
066
067}