72 lines
1.8 KiB
Java
72 lines
1.8 KiB
Java
package dev.peerat.framework;
|
|
|
|
import java.lang.reflect.Method;
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
public class RouteState {
|
|
|
|
private Object instance;
|
|
private Method method;
|
|
private Route route;
|
|
private Pattern pattern;
|
|
private int[] bindMethod;
|
|
|
|
public RouteState(Object instance, Method method, Route route){
|
|
this.instance = instance;
|
|
this.method = method;
|
|
this.route = route;
|
|
this.pattern = Pattern.compile(route.path());
|
|
|
|
Class<?>[] parameters = method.getParameterTypes();
|
|
this.bindMethod = new int[4];
|
|
this.bindMethod[0] = findIndex(parameters, Matcher.class);
|
|
this.bindMethod[1] = findIndex(parameters, Context.class);
|
|
this.bindMethod[2] = findIndex(parameters, HttpReader.class);
|
|
this.bindMethod[3] = findIndex(parameters, HttpWriter.class);
|
|
}
|
|
|
|
public Matcher match(String path){
|
|
Matcher matcher = pattern.matcher(path);
|
|
return matcher.matches() ? matcher : null;
|
|
}
|
|
|
|
public boolean isWebSocket(){
|
|
return route.websocket();
|
|
}
|
|
|
|
public boolean needLogin(){
|
|
return route.needLogin();
|
|
}
|
|
|
|
public Method getMethod(){
|
|
return this.method;
|
|
}
|
|
|
|
public Object getInstance(){
|
|
return this.instance;
|
|
}
|
|
|
|
public Object[] bindMethod(Matcher matcher, Context context, HttpReader reader, HttpWriter writer){
|
|
Object[] result = new Object[method.getParameterCount()];
|
|
setElement(result, bindMethod[0], matcher);
|
|
setElement(result, bindMethod[1], context);
|
|
setElement(result, bindMethod[2], reader);
|
|
setElement(result, bindMethod[3], writer);
|
|
return result;
|
|
}
|
|
|
|
private void setElement(Object[] array, int position, Object element){
|
|
if(position < 0) return;
|
|
array[position] = element;
|
|
}
|
|
|
|
private int findIndex(Class<?>[] array, Class<?> type){
|
|
for(int i = 0; i < array.length; i++){
|
|
Class<?> clazz = array[i];
|
|
if(type.isAssignableFrom(clazz)) return i;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
}
|