
le-annen.javaserver.0.1.source-code.Router Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of javaserver Show documentation
Show all versions of javaserver Show documentation
A minimal java http server which fulfills small portions of the
http specifications. This is not a full fledged or secure server. It should only be used
for learning purposes and contains no guarantees of any king.
The newest version!
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
class Router implements RouterInterface {
private HashMap router = new HashMap<>();
void addRoute(
String httpMethod,
String route,
ControllerInterface controller) {
Boolean methodRouteExists = router.keySet().contains(httpMethod);
Routes routes;
if(methodRouteExists) { routes = router.get(httpMethod);} else { routes = new Routes();}
Boolean pathRouteExists = routes.getRoutePaths().contains(route);
if(!pathRouteExists) { routes.add(route, controller); }
router.put(httpMethod, routes);
}
Routes getRoutes(String httpMethod) {
return router.get(httpMethod);
}
@Override
public ResponseParameters route(RequestParameters requestParameters) throws IOException {
String httpMethod = requestParameters.getHttpVerb();
File file = new File(requestParameters.getDirectoryPath() +
requestParameters.getRequestPath());
Boolean isDirectory = file.isDirectory();
Boolean isFile = file.exists() && !isDirectory;
Boolean methodExists = router.keySet().contains(httpMethod);
Boolean routeExists = router
.get(httpMethod)
.getRoutePaths()
.contains(requestParameters.getRequestPath());
if(methodExists && routeExists) {
Routes routes = router.get(httpMethod);
return routes.getResponse(requestParameters);
} else if(isDirectory) {
ControllerDirectory controllerDirectory = new ControllerDirectory();
return dynamicRoute(requestParameters, controllerDirectory);
} else if(isFile) {
ControllerFile controllerFile = new ControllerFile();
return dynamicRoute(requestParameters, controllerFile);
} else {
return new ControllerFourOhFour().getResponse(requestParameters);
}
}
private ResponseParameters dynamicRoute(
RequestParameters requestParameters,
ControllerInterface controllerInterface) throws IOException {
Routes dynamicRoutes = new Routes();
String route = requestParameters.getRequestPath();
dynamicRoutes.add(route, controllerInterface);
return dynamicRoutes.getResponse(requestParameters);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy