001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Stephane Lacoin
018 */
019package org.nuxeo.runtime.javaagent;
020
021import java.lang.reflect.InvocationHandler;
022import java.lang.reflect.Method;
023import java.lang.reflect.Proxy;
024import java.util.HashMap;
025import java.util.Map;
026
027public class AgentHandler implements InvocationHandler {
028
029    public static <I> I newHandler(Class<I> type, Object agent) {
030        return type.cast(Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
031                new Class<?>[] { type }, new AgentHandler(agent)));
032    }
033
034    protected AgentHandler(Object agent) {
035        this.agent = agent;
036        type = agent.getClass();
037    }
038
039    protected final Class<?> type;
040
041    protected final Object agent;
042
043    @Override
044    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
045        if ("humanReadable".equals(method.getName())) {
046            return humanReadable((long) args[0]);
047        }
048        return agentMethod(method).invoke(agent, args);
049    }
050
051    protected static String[] units = { "b", "Kb", "Mb" };
052
053    protected String humanReadable(long size) {
054        String unit = "b";
055        double dSize = size;
056        for (String eachUnit : units) {
057            unit = eachUnit;
058            if (dSize < 1024) {
059                break;
060            }
061            dSize /= 1024;
062        }
063
064        return dSize + unit;
065    }
066
067    protected final Map<Method, Method> agentMethods = new HashMap<>();
068
069    protected Method agentMethod(Method bridgeMethod) throws NoSuchMethodException, SecurityException {
070        Method agentMethod = agentMethods.get(bridgeMethod);
071        if (agentMethod == null) {
072            agentMethod = type.getDeclaredMethod(bridgeMethod.getName(), bridgeMethod.getParameterTypes());
073            agentMethods.put(bridgeMethod, agentMethod);
074        }
075        return agentMethod;
076    }
077
078}