
com.github.gkutiel.flip.web.MethodInvokerFinder Maven / Gradle / Ivy
package com.github.gkutiel.flip.web;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.github.gkutiel.flip.utils.Utils;
interface MethodInvokerFinder {
static class CatchAllFinder implements MethodInvokerFinder {
private final Map> catchAll;
CatchAllFinder(final Map> catchAll) {
this.catchAll = catchAll;
}
private String[] argsFromPath(final String path, final String prefix) {
if (path.length() == 1) return new String[0];
return path.substring(prefix.length() + 1).split("/");
}
@Override
public MethodInvoker find(final HttpServletRequest req, final HttpServletResponse res) {
final String path = req.getPathInfo();
final Entry> catchAll = findCatchAll(path);
if (catchAll == null) return null;
final String prefix = catchAll.getKey();
final String[] args = argsFromPath(path, prefix);
final Class> clazz = catchAll.getValue();
final Method method = findMethod(clazz, args);
if (method == null) return null;
return new MethodInvokerCatchAll(clazz, method, args);
}
private Entry> findCatchAll(final String path) {
for (final Entry> catchAll : this.catchAll.entrySet()) {
final String prefix = catchAll.getKey();
if (path.startsWith(prefix)) return catchAll;
}
return null;
}
private Method findMethod(final Class> clazz, final String[] args) {
final Method[] methods = clazz.getDeclaredMethods();
AccessibleObject.setAccessible(methods, true);
for (final Method method : methods)
if (method.getParameterTypes().length == args.length) return method;
return null;
}
}
static class DefaultFinder implements MethodInvokerFinder {
@Override
public MethodInvoker find(final HttpServletRequest req, final HttpServletResponse res) {
try {
final String[] args = req.getPathInfo().substring(1).split("/");
if (args.length < 2) return null;
final Class> clazz = Class.forName("web." + args[0]);
final Method method = Utils.Reflection.findFirstMethod(clazz, args[1]);
if (method == null) return null;
return new MethodInvokerDefault(clazz, method);
} catch (final ClassNotFoundException e) {
// TODO (gilad) log
return null;
}
}
}
MethodInvoker find(final HttpServletRequest req, final HttpServletResponse res);
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy