Skip to content

Instantly share code, notes, and snippets.

@jpbetz
Last active August 29, 2015 13:57
Show Gist options
  • Save jpbetz/9400789 to your computer and use it in GitHub Desktop.
Save jpbetz/9400789 to your computer and use it in GitHub Desktop.
package com.example.fortune.impl;
import com.linkedin.restli.internal.server.model.ResourceModel;
import com.linkedin.restli.server.resources.ResourceFactory;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
* @author jbetz@linkedin.com
*/
public class ProxyResourceFactory implements ResourceFactory
{
private final ResourceFactory _underlying;
public ProxyResourceFactory(ResourceFactory underlying)
{
_underlying = underlying;
}
@Override
public void setRootResources(Map<String, ResourceModel> rootResources)
{
_underlying.setRootResources(rootResources);
}
@Override
@SuppressWarnings("unchecked")
public <R> R create(Class<R> resourceClass)
{
// TODO: Change this for any particular use case. creating proxies for each request like done here will consume all your permgen.
// TODO: Instead, modify this code to cache proxyClasses as appropriate for your use case.
// TODO: If you don't need a new instance of a resource class for each request, simply proxy it once and cache it for subsequent requests.
// TODO: If you do need a new instance of a resource class for each request, see Enhancer.createClass.
R underlyingResourceClass = _underlying.create(resourceClass);
ProxyInvocationHandler handler = new ProxyInvocationHandler(underlyingResourceClass);
return (R) Enhancer.create(resourceClass, handler);
}
public class ProxyInvocationHandler implements MethodInterceptor
{
Object _underlyingResourceClass;
public ProxyInvocationHandler(Object underlyingResourceClass)
{
_underlyingResourceClass = underlyingResourceClass;
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable
{
// intercepted
System.err.println(" method: " + method.getName() + " args: " + Arrays.toString(args));
return method.invoke(_underlyingResourceClass, args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment