From 996df57b87a1d50d52ad8e4ee88a6f66b09529aa Mon Sep 17 00:00:00 2001 From: Sven Kubiak Date: Mon, 24 Sep 2018 13:51:45 +0200 Subject: [PATCH] #391 First draft for programatical route configuration --- .../java/io/mangoo/admin/AdminController.java | 18 +- .../java/io/mangoo/admin/AdminFilter.java | 81 ---- .../main/java/io/mangoo/core/Application.java | 183 ++++----- .../main/java/io/mangoo/core/Shutdown.java | 4 +- .../java/io/mangoo/core/yaml/YamlRoute.java | 81 ---- .../java/io/mangoo/core/yaml/YamlRouter.java | 21 - .../main/java/io/mangoo/crypto/Crypto.java | 4 +- .../main/java/io/mangoo/enums/Default.java | 2 +- .../src/main/java/io/mangoo/enums/Http.java | 33 ++ .../main/java/io/mangoo/enums/Required.java | 4 +- .../main/java/io/mangoo/enums/RouteType.java | 15 - .../main/java/io/mangoo/enums/SecureType.java | 13 + ...gooLifecycle.java => MangooBootstrap.java} | 10 +- .../io/mangoo/interfaces/MangooRoute.java | 5 + .../src/main/java/io/mangoo/routing/Bind.java | 29 ++ .../src/main/java/io/mangoo/routing/On.java | 44 ++ .../main/java/io/mangoo/routing/Route.java | 139 ------- .../main/java/io/mangoo/routing/Router.java | 24 +- .../main/java/io/mangoo/routing/Secure.java | 88 ++++ .../routing/routes/ControllerRoute.java | 42 ++ .../io/mangoo/routing/routes/FileRoute.java | 22 + .../io/mangoo/routing/routes/PathRoute.java | 22 + .../mangoo/routing/routes/RequestRoute.java | 119 ++++++ .../routing/routes/ServerSentEventRoute.java | 21 + .../mangoo/routing/routes/WebSocketRoute.java | 36 ++ .../templating/methods/RouteMethod.java | 8 +- .../java/io/mangoo/utils/BootstrapUtils.java | 33 -- .../src/main/java/app/Bootstrap.java | 187 +++++++++ .../src/main/java/{conf => app}/Module.java | 6 +- .../src/main/java/conf/Lifecycle.java | 34 -- .../src/main/java/main/Main.java | 2 +- .../src/main/resources/routes.yaml | 382 ------------------ .../mangoo/configuration/LifecycleTest.java | 29 -- .../io/mangoo/configuration/ModuleTest.java | 7 +- .../io/mangoo/filters/AdminFilterTest.java | 87 ---- .../java/io/mangoo/routing/RouterTest.java | 6 +- .../routing/bindings/InjectionTest.java | 6 +- .../io/mangoo/utils/BootstrapUtilsTest.java | 31 -- pom.xml | 6 +- 39 files changed, 792 insertions(+), 1092 deletions(-) delete mode 100644 mangooio-core/src/main/java/io/mangoo/admin/AdminFilter.java delete mode 100644 mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRoute.java delete mode 100644 mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRouter.java create mode 100644 mangooio-core/src/main/java/io/mangoo/enums/Http.java delete mode 100644 mangooio-core/src/main/java/io/mangoo/enums/RouteType.java create mode 100644 mangooio-core/src/main/java/io/mangoo/enums/SecureType.java rename mangooio-core/src/main/java/io/mangoo/interfaces/{MangooLifecycle.java => MangooBootstrap.java} (73%) create mode 100644 mangooio-core/src/main/java/io/mangoo/interfaces/MangooRoute.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/Bind.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/On.java delete mode 100644 mangooio-core/src/main/java/io/mangoo/routing/Route.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/Secure.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/routes/ControllerRoute.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/routes/FileRoute.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/routes/PathRoute.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/routes/RequestRoute.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/routes/ServerSentEventRoute.java create mode 100644 mangooio-core/src/main/java/io/mangoo/routing/routes/WebSocketRoute.java create mode 100644 mangooio-integration-test/src/main/java/app/Bootstrap.java rename mangooio-integration-test/src/main/java/{conf => app}/Module.java (71%) delete mode 100644 mangooio-integration-test/src/main/java/conf/Lifecycle.java delete mode 100644 mangooio-integration-test/src/main/resources/routes.yaml delete mode 100644 mangooio-integration-test/src/test/java/io/mangoo/configuration/LifecycleTest.java delete mode 100644 mangooio-integration-test/src/test/java/io/mangoo/filters/AdminFilterTest.java diff --git a/mangooio-core/src/main/java/io/mangoo/admin/AdminController.java b/mangooio-core/src/main/java/io/mangoo/admin/AdminController.java index 9c04666e50..e769d2923d 100644 --- a/mangooio-core/src/main/java/io/mangoo/admin/AdminController.java +++ b/mangooio-core/src/main/java/io/mangoo/admin/AdminController.java @@ -13,9 +13,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Objects; -import java.util.Set; import java.util.concurrent.atomic.LongAdder; -import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; @@ -26,7 +24,6 @@ import com.google.inject.Inject; -import io.mangoo.annotations.FilterWith; import io.mangoo.cache.Cache; import io.mangoo.configuration.Config; import io.mangoo.core.Application; @@ -40,8 +37,6 @@ import io.mangoo.models.Metrics; import io.mangoo.providers.CacheProvider; import io.mangoo.routing.Response; -import io.mangoo.routing.Route; -import io.mangoo.routing.Router; import io.mangoo.routing.bindings.Request; import io.mangoo.scheduler.Scheduler; import io.mangoo.utils.BootstrapUtils; @@ -53,7 +48,6 @@ * @author svenkubiak * */ -@FilterWith(AdminFilter.class) public class AdminController { private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger(AdminController.class); private static final String JOBS = "jobs"; @@ -176,15 +170,15 @@ public Response metrics() { } public Response routes() { - Set routes = Router.getRoutes() - .stream() - .filter((Route route) -> !route.getUrl().contains("@admin")) - .collect(Collectors.toSet()); - +// Set routes = Router.getRoutes() +// .stream() +// .filter((Route route) -> !route.getUrl().contains("@admin")) +// .collect(Collectors.toSet()); +// return Response.withOk() .andContent(SPACE, ROUTES) .andContent(VERSION, VERSION_TAG) - .andContent(ROUTES, routes) + //.andContent(ROUTES, routes) .andTemplate(Template.DEFAULT.routesPath()); } diff --git a/mangooio-core/src/main/java/io/mangoo/admin/AdminFilter.java b/mangooio-core/src/main/java/io/mangoo/admin/AdminFilter.java deleted file mode 100644 index 4affaa5280..0000000000 --- a/mangooio-core/src/main/java/io/mangoo/admin/AdminFilter.java +++ /dev/null @@ -1,81 +0,0 @@ -package io.mangoo.admin; - -import java.util.Base64; -import java.util.Objects; - -import org.apache.commons.lang3.StringUtils; - -import com.google.common.base.Charsets; -import com.google.inject.Inject; - -import io.mangoo.configuration.Config; -import io.mangoo.enums.Default; -import io.mangoo.enums.Header; -import io.mangoo.enums.Required; -import io.mangoo.enums.Template; -import io.mangoo.interfaces.MangooFilter; -import io.mangoo.routing.Response; -import io.mangoo.routing.bindings.Request; - -/** - * Authentication filter for administrative area - * - * @author svenkubiak - * - */ -public class AdminFilter implements MangooFilter { - private static final Base64.Decoder decoder = Base64.getDecoder(); - private Config config; - - @Inject - public AdminFilter (Config config) { - this.config = Objects.requireNonNull(config, Required.CONFIG.toString()); - } - - @Override - public Response execute(Request request, Response response) { - if (!this.config.isApplicationAdminEnable()) { - return Response.withNotFound() - .andBody(Template.DEFAULT.notFound()) - .end(); - } - - if (!isAuthenticated(request)) { - return Response.withUnauthorized() - .andHeader(Header.WWW_AUTHENTICATE.toHttpString(), "Basic realm=Administration authentication") - .andEmptyBody() - .end(); - } - - return response; - } - - /** - * Checks via a basic HTTP authentication if user is authenticated - * - * @param request The current HTTP request - * @return True if credentials are valid, false otherwise - */ - private boolean isAuthenticated(Request request) { - String username = null; - String password = null; - String authInfo = request.getHeader(Header.AUTHORIZATION.toHttpString()); - if (StringUtils.isNotBlank(authInfo)) { - authInfo = StringUtils.replace(authInfo, "Basic", ""); - authInfo = authInfo.trim(); - authInfo = new String(decoder.decode(authInfo), Charsets.UTF_8); - - final String [] credentials = authInfo.split(":"); - if (credentials != null && credentials.length == Default.BASICAUTH_CREDENTIALS_LENGTH.toInt()) { - username = credentials[0]; - password = credentials[1]; - } - } - - return StringUtils.isNotBlank(username) && - StringUtils.isNotBlank(password) && - StringUtils.isNotBlank(this.config.getApplicationAdminUsername()) && - StringUtils.isNotBlank(this.config.getApplicationAdminPassword()) && - this.config.getApplicationAdminUsername().equals(username); - } -} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/core/Application.java b/mangooio-core/src/main/java/io/mangoo/core/Application.java index ed3e772aaf..8933e37308 100644 --- a/mangooio-core/src/main/java/io/mangoo/core/Application.java +++ b/mangooio-core/src/main/java/io/mangoo/core/Application.java @@ -1,6 +1,5 @@ package io.mangoo.core; -import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.time.Duration; import java.time.LocalDateTime; @@ -19,9 +18,6 @@ import org.quartz.JobDetail; import org.quartz.Trigger; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.google.common.io.Resources; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Module; @@ -33,19 +29,17 @@ import io.mangoo.admin.AdminController; import io.mangoo.annotations.Schedule; import io.mangoo.configuration.Config; -import io.mangoo.core.yaml.YamlRoute; -import io.mangoo.core.yaml.YamlRouter; import io.mangoo.email.MailEventListener; import io.mangoo.enums.CacheName; import io.mangoo.enums.Default; import io.mangoo.enums.Key; import io.mangoo.enums.Mode; import io.mangoo.enums.Required; -import io.mangoo.enums.RouteType; import io.mangoo.exceptions.MangooSchedulerException; -import io.mangoo.interfaces.MangooLifecycle; +import io.mangoo.interfaces.MangooBootstrap; import io.mangoo.providers.CacheProvider; -import io.mangoo.routing.Route; +import io.mangoo.routing.Bind; +import io.mangoo.routing.On; import io.mangoo.routing.Router; import io.mangoo.routing.handlers.DispatcherHandler; import io.mangoo.routing.handlers.ExceptionHandler; @@ -53,6 +47,11 @@ import io.mangoo.routing.handlers.MetricsHandler; import io.mangoo.routing.handlers.ServerSentEventHandler; import io.mangoo.routing.handlers.WebSocketHandler; +import io.mangoo.routing.routes.FileRoute; +import io.mangoo.routing.routes.PathRoute; +import io.mangoo.routing.routes.RequestRoute; +import io.mangoo.routing.routes.ServerSentEventRoute; +import io.mangoo.routing.routes.WebSocketRoute; import io.mangoo.scheduler.Scheduler; import io.mangoo.services.EventBusService; import io.mangoo.utils.BootstrapUtils; @@ -67,7 +66,6 @@ import io.undertow.server.handlers.PathHandler; import io.undertow.server.handlers.resource.ClassPathResourceManager; import io.undertow.server.handlers.resource.ResourceHandler; -import io.undertow.util.HttpString; import io.undertow.util.Methods; /** @@ -127,7 +125,7 @@ public static void start(Mode mode) { * Registers Listeners at the event bus */ private static void prepareEventBus() { - injector.getInstance(EventBusService.class).register(injector.getInstance(MailEventListener.class)); + getInstance(EventBusService.class).register(getInstance(MailEventListener.class)); } /** @@ -200,7 +198,7 @@ public static Duration getUptime() { /** * Short form for getting an Goolge Guice injected class by - * calling injector.getInstance(...) + * calling getInstance(...) * * @param clazz The class to retrieve from the injector * @param JavaDoc requires this (just ignore it) @@ -252,7 +250,7 @@ private static void prepareInjector() { .createInjector(); try { - injector.getInstance(LifecycleManager.class).start(); + getInstance(LifecycleManager.class).start(); } catch (Exception e) { LOG.error("Failed to start Governator LifecycleManager", e); failsafe(); @@ -263,14 +261,14 @@ private static void prepareInjector() { * Callback to MangooLifecycle applicationInitialized */ private static void applicationInitialized() { - injector.getInstance(MangooLifecycle.class).applicationInitialized(); + getInstance(MangooBootstrap.class).applicationInitialized(); } /** * Checks for config failures that pervent the application from starting */ private static void prepareConfig() { - Config config = injector.getInstance(Config.class); + Config config = getInstance(Config.class); int bitLength = getBitLength(config.getApplicationSecret()); if (bitLength < KEY_MIN_BIT_LENGTH) { @@ -324,7 +322,7 @@ private static void prepareConfig() { * Do sanity checks on the configuration an warn about it in the log */ private static void sanityChecks() { - Config config = injector.getInstance(Config.class); + Config config = getInstance(Config.class); List warnings = new ArrayList<>(); if (!config.isAuthenticationCookieSecure()) { @@ -393,62 +391,25 @@ private static void sanityChecks() { LOG.warn(warning); } - injector.getInstance(CacheProvider.class).getCache(CacheName.APPLICATION).put(Key.MANGOOIO_WARNINGS.toString(), warnings); + getInstance(CacheProvider.class).getCache(CacheName.APPLICATION).put(Key.MANGOOIO_WARNINGS.toString(), warnings); } /** - * Parse routes from routes.yaml file and set up dispatcher + * Validate if the routes that are defined in the router are valid */ private static void prepareRoutes() { - Config config = injector.getInstance(Config.class); - ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); - YamlRouter yamlRouter = null; - try { - yamlRouter = objectMapper.readValue(Resources.getResource(Default.ROUTES_FILE.toString()).openStream(), YamlRouter.class); - } catch (IOException e) { - LOG.error("Failed to load routes.yaml Please make sure that your routes.yaml exists in your application src/main/resources folder", e); - failsafe(); - } + injector.getInstance(MangooBootstrap.class).initializeRoutes(); - if (yamlRouter != null) { - for (final YamlRoute yamlRoute : yamlRouter.getRoutes()) { - RouteType routeType = BootstrapUtils.getRouteType(yamlRoute.getMethod()); - final Route route = new Route(routeType) - .toUrl(yamlRoute.getUrl().trim()) - .withRequest(HttpString.tryFromString(yamlRoute.getMethod())) - .withUsername(yamlRoute.getUsername()) - .withPassword(yamlRoute.getPassword()) - .withAuthentication(yamlRoute.isAuthentication()) - .withLimit(yamlRoute.getLimit()) - .allowBlocking(yamlRoute.isBlocking()); - - try { - String mapping = yamlRoute.getMapping(); - if (StringUtils.isNotBlank(mapping)) { - if (routeType == RouteType.REQUEST) { - int lastIndexOf = mapping.trim().lastIndexOf('.'); - String controllerClass = BootstrapUtils.getPackageName(config.getApplicationController()) + mapping.substring(0, lastIndexOf); - route.withClass(Class.forName(controllerClass)); - - String methodName = mapping.substring(lastIndexOf + 1); - if (BootstrapUtils.methodExists(methodName, route.getControllerClass())) { - route.withMethod(methodName); - } else { - LOG.error("Method '{}' does not exists in controller class '{}'", methodName, route.getControllerClass()); - failsafe(); - } - } else { - route.withClass(Class.forName(BootstrapUtils.getPackageName(config.getApplicationController()) + mapping)); - } - } - Router.addRoute(route); - } catch (final ClassNotFoundException e) { - LOG.error("Failed to create routes from routes.yaml"); - LOG.error("Please verify that your routes.yaml mapping is correct", e); + Router.getRoutes().forEach((mangooRoute) -> { + if (mangooRoute instanceof RequestRoute) { + RequestRoute requestRoute = (RequestRoute) mangooRoute; + + if (!BootstrapUtils.methodExists(requestRoute.getControllerMethod(), requestRoute.getControllerClass())) { + LOG.error("Method '{}' does not exists in controller class '{}'", requestRoute.getControllerMethod(), requestRoute.getControllerClass()); failsafe(); } } - } + }); } /** @@ -456,57 +417,64 @@ private static void prepareRoutes() { */ private static void createRoutes() { pathHandler = new PathHandler(getRoutingHandler()); - for (final Route route : Router.getRoutes()) { - if (RouteType.WEBSOCKET == route.getRouteType()) { - pathHandler.addExactPath(route.getUrl(), - Handlers.websocket(injector.getInstance(WebSocketHandler.class) - .withControllerClass(route.getControllerClass()) - .withAuthentication(route.isAuthenticationRequired()))); - } else if (RouteType.SERVER_SENT_EVENT == route.getRouteType()) { - pathHandler.addExactPath(route.getUrl(), - Handlers.serverSentEvents(injector.getInstance(ServerSentEventHandler.class) - .withAuthentication(route.isAuthenticationRequired()))); - } else if (RouteType.RESOURCE_PATH == route.getRouteType()) { - pathHandler.addPrefixPath(route.getUrl(), - new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + route.getUrl()))); + Router.getRoutes().forEach((mangooRoute) -> { + if (mangooRoute instanceof WebSocketRoute) { + WebSocketRoute webSocketRoute = (WebSocketRoute) mangooRoute; + + pathHandler.addExactPath(webSocketRoute.getUrl(), + Handlers.websocket(getInstance(WebSocketHandler.class) + .withControllerClass(webSocketRoute.getControllerClass()))); + } else if (mangooRoute instanceof ServerSentEventRoute) { + ServerSentEventRoute serverSentEventRoute = (ServerSentEventRoute) mangooRoute; + + pathHandler.addExactPath(serverSentEventRoute.getUrl(), + Handlers.serverSentEvents(getInstance(ServerSentEventHandler.class))); + } else if (mangooRoute instanceof PathRoute) { + PathRoute pathRoute = (PathRoute) mangooRoute; + + pathHandler.addPrefixPath(pathRoute.getUrl(), + new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + pathRoute.getUrl()))); } else { // Ignoring anything else except WebSocket ServerSentEvent or Resource Path for PathHandler } - } + }); } private static RoutingHandler getRoutingHandler() { final RoutingHandler routingHandler = Handlers.routing(); routingHandler.setFallbackHandler(Application.getInstance(FallbackHandler.class)); - Config config = injector.getInstance(Config.class); + Config config = getInstance(Config.class); if (config.isApplicationAdminEnable()) { - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin").withRequest(Methods.GET).withClass(AdminController.class).withMethod("index").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/health").withRequest(Methods.GET).withClass(AdminController.class).withMethod("health").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/scheduler").withRequest(Methods.GET).withClass(AdminController.class).withMethod("scheduler").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/logger").withRequest(Methods.GET).withClass(AdminController.class).withMethod("logger").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/logger/ajax").withRequest(Methods.POST).withClass(AdminController.class).withMethod("loggerajax").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/routes").withRequest(Methods.GET).withClass(AdminController.class).withMethod("routes").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/metrics").withRequest(Methods.GET).withClass(AdminController.class).withMethod("metrics").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/metrics/reset").withRequest(Methods.GET).withClass(AdminController.class).withMethod("resetMetrics").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/tools").withRequest(Methods.GET).withClass(AdminController.class).withMethod("tools").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/tools/ajax").withRequest(Methods.POST).withClass(AdminController.class).withMethod("toolsajax").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/scheduler/execute/{name}").withRequest(Methods.GET).withClass(AdminController.class).withMethod("execute").useInternalTemplateEngine()); - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/@admin/scheduler/state/{name}").withRequest(Methods.GET).withClass(AdminController.class).withMethod("state").useInternalTemplateEngine()); - } - - Router.getRoutes().parallelStream().forEach((Route route) -> { - if (RouteType.REQUEST == route.getRouteType()) { + Bind.controller(AdminController.class).with( + On.get().to("/@admin").respondeWith("index"), + On.get().to("/@admin/health").respondeWith("health"), + On.get().to("/@admin/scheduler").respondeWith("scheduler"), + On.get().to("/@admin/logger").respondeWith("logger"), + On.post().to("/@admin/logger/ajax").respondeWith("loggerajax"), + On.get().to("/@admin/routes").respondeWith("routes"), + On.get().to("/@admin/metrics").respondeWith("metrics"), + On.get().to("/@admin/metrics/reset").respondeWith("resetMetrics"), + On.get().to("/@admin/metrics/reset").respondeWith("resetMetrics"), + On.get().to("/@admin/tools").respondeWith("tools"), + On.post().to("/@admin/tools/ajax").respondeWith("toolsajax"), + On.get().to("/@admin/scheduler/execute/{name}").respondeWith("execute"), + On.get().to("/@admin/scheduler/state/{name}").respondeWith("state") + ); + } + + Router.getRoutes().forEach((mangooRoute) -> { + if (mangooRoute instanceof RequestRoute) { + RequestRoute requestRoute = (RequestRoute) mangooRoute; DispatcherHandler dispatcherHandler = Application.getInstance(DispatcherHandler.class) - .dispatch(route.getControllerClass(), route.getControllerMethod()) - .isBlocking(route.isBlockingAllowed()) - .withUsername(route.getUsername()) - .withPassword(route.getPassword()) - .withLimit(route.getLimit()); + .dispatch(requestRoute.getControllerClass(), requestRoute.getControllerMethod()) + .isBlocking(requestRoute.isBlocking()) + .withLimit(requestRoute.getLimit()); - routingHandler.add(route.getRequestMethod(),route.getUrl(), dispatcherHandler); - } else if (RouteType.RESOURCE_FILE == route.getRouteType()) { - routingHandler.add(Methods.GET, route.getUrl(), resourceHandler); + routingHandler.add(requestRoute.getMethod().toString(), requestRoute.getUrl(), dispatcherHandler); + } else if (mangooRoute instanceof FileRoute) { + FileRoute fileRoute = (FileRoute) mangooRoute; + routingHandler.add(Methods.GET, fileRoute.getUrl(), resourceHandler); } else { // Ignoring anything else except Request and RequestFile for DispatcherHandler } @@ -516,7 +484,7 @@ private static RoutingHandler getRoutingHandler() { } private static void prepareUndertow() { - Config config = injector.getInstance(Config.class); + Config config = getInstance(Config.class); HttpHandler httpHandler; if (config.isMetricsEnable()) { @@ -585,9 +553,8 @@ private static int getBitLength(String secret) { private static List getModules() { final List modules = new ArrayList<>(); try { - final Class applicationModule = Class.forName(Default.MODULE_CLASS.toString()); modules.add(new io.mangoo.core.Module()); - modules.add((AbstractModule) applicationModule.getConstructor().newInstance()); + modules.add((AbstractModule) Class.forName(Default.MODULE_CLASS.toString()).getConstructor().newInstance()); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) { LOG.error("Failed to load modules. Check that conf/Module.java exists in your application", e); @@ -598,11 +565,11 @@ private static List getModules() { } private static void applicationStarted() { - injector.getInstance(MangooLifecycle.class).applicationStarted(); + getInstance(MangooBootstrap.class).applicationStarted(); } private static void prepareScheduler() { - Config config = injector.getInstance(Config.class); + Config config = getInstance(Config.class); List> jobs = new ArrayList<>(); try (ScanResult scanResult = @@ -615,7 +582,7 @@ private static void prepareScheduler() { } if (!jobs.isEmpty() && config.isSchedulerAutostart()) { - final Scheduler mangooScheduler = injector.getInstance(Scheduler.class); + final Scheduler mangooScheduler = getInstance(Scheduler.class); mangooScheduler.initialize(); for (Class clazz : jobs) { diff --git a/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java b/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java index 260526afe7..12c153ae57 100644 --- a/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java +++ b/mangooio-core/src/main/java/io/mangoo/core/Shutdown.java @@ -7,7 +7,7 @@ import com.netflix.governator.lifecycle.LifecycleManager; import io.mangoo.exceptions.MangooSchedulerException; -import io.mangoo.interfaces.MangooLifecycle; +import io.mangoo.interfaces.MangooBootstrap; import io.mangoo.providers.CacheProvider; import io.mangoo.scheduler.Scheduler; import io.mangoo.services.ConcurrentService; @@ -36,7 +36,7 @@ public void run() { } private static void invokeLifecycle() { - Application.getInstance(MangooLifecycle.class).applicationStopped(); + Application.getInstance(MangooBootstrap.class).applicationStopped(); } private static void stopExecutionManager() { diff --git a/mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRoute.java b/mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRoute.java deleted file mode 100644 index 58289e3078..0000000000 --- a/mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRoute.java +++ /dev/null @@ -1,81 +0,0 @@ -package io.mangoo.core.yaml; - -/** - * - * @author svenkubiak - * - */ -public class YamlRoute { - private String method; - private String url; - private String mapping; - private String username; - private String password; - private int limit; - private boolean blocking; - private boolean authentication; - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public void setLimit(int limit) { - this.limit = limit; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getMapping() { - return mapping; - } - - public int getLimit() { - return limit; - } - - public void setMapping(String mapping) { - this.mapping = mapping; - } - - public boolean isBlocking() { - return blocking; - } - - public void setBlocking(boolean blocking) { - this.blocking = blocking; - } - - public boolean isAuthentication() { - return authentication; - } - - public void setAuthentication(boolean authentication) { - this.authentication = authentication; - } -} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRouter.java b/mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRouter.java deleted file mode 100644 index 861646ecc5..0000000000 --- a/mangooio-core/src/main/java/io/mangoo/core/yaml/YamlRouter.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.mangoo.core.yaml; - -import java.util.ArrayList; -import java.util.List; - -/** - * - * @author svenkubiak - * - */ -public class YamlRouter { - private List routes; - - public List getRoutes() { - return new ArrayList<>(routes); - } - - public void setRoutes(List routes) { - this.routes = new ArrayList<>(routes); - } -} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/crypto/Crypto.java b/mangooio-core/src/main/java/io/mangoo/crypto/Crypto.java index 34a9c2a670..ed2a99afcb 100644 --- a/mangooio-core/src/main/java/io/mangoo/crypto/Crypto.java +++ b/mangooio-core/src/main/java/io/mangoo/crypto/Crypto.java @@ -46,7 +46,7 @@ public class Crypto { private static final Base64.Encoder base64Encoder = Base64.getEncoder(); private static final Base64.Decoder base64Decoder = Base64.getDecoder(); private static final String ENCODING = "UTF8"; - private static final String CIPHER = "RSA/NONE/OAEPWithSHA512AndMGF1Padding"; + private static final String CIPHER = "RSA/ECB/OAEPWithSHA512AndMGF1Padding"; private static final String ALGORITHM = "RSA"; private static final int KEYLENGTH = 2048; private static final int KEYINDEX_START = 0; @@ -297,7 +297,7 @@ private String encodeBase64(byte[] bytes) { * @return Bytes array * @throws IOException */ - private byte[] decodeBase64(String text) throws IOException { + private byte[] decodeBase64(String text) { Objects.requireNonNull(text, Required.PLAIN_TEXT.toString()); return org.apache.commons.codec.binary.Base64.decodeBase64(text); diff --git a/mangooio-core/src/main/java/io/mangoo/enums/Default.java b/mangooio-core/src/main/java/io/mangoo/enums/Default.java index 30d74e64f6..f9769a693a 100644 --- a/mangooio-core/src/main/java/io/mangoo/enums/Default.java +++ b/mangooio-core/src/main/java/io/mangoo/enums/Default.java @@ -54,7 +54,7 @@ public enum Default { LIFECYCLE_CLASS("conf.Lifecycle"), LOGO_FILE("logo.txt"), METRICS_ENABLE(Constants.FALSE), - MODULE_CLASS("conf.Module"), + MODULE_CLASS("app.Module"), NUMBER_FORMAT("0.######"), OAUTH_REQUEST_PARAMETER("oauth"), ROUTES_FILE("routes.yaml"), diff --git a/mangooio-core/src/main/java/io/mangoo/enums/Http.java b/mangooio-core/src/main/java/io/mangoo/enums/Http.java new file mode 100644 index 0000000000..46b453b074 --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/enums/Http.java @@ -0,0 +1,33 @@ +package io.mangoo.enums; + +import io.undertow.util.HttpString; + +/** + * + * @author svenkubiak + * + */ +public enum Http { + DELETE("delete"), + GET("get"), + HEAD("head"), + OPTIONS("options"), + PATCH("patch"), + POST("post"), + PUT("put"); + + private final String value; + + Http (String value) { + this.value = value; + } + + public HttpString toHttpString() { + return new HttpString(this.value); + } + + @Override + public String toString() { + return this.value; + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/enums/Required.java b/mangooio-core/src/main/java/io/mangoo/enums/Required.java index 24edd667ec..3e369c3632 100644 --- a/mangooio-core/src/main/java/io/mangoo/enums/Required.java +++ b/mangooio-core/src/main/java/io/mangoo/enums/Required.java @@ -102,7 +102,9 @@ public enum Required { VALUE("value can not be null"), VALUES("values can not be null"), PUBLIC_KEY("public key can not be null"), - PRIVATE_KEY("private key can not be null"); + PRIVATE_KEY("private key can not be null"), + HTTP_METHOD("HTTP method can not be null"), + MAPPING("mapping can not be null"); private final String value; diff --git a/mangooio-core/src/main/java/io/mangoo/enums/RouteType.java b/mangooio-core/src/main/java/io/mangoo/enums/RouteType.java deleted file mode 100644 index de04da26fc..0000000000 --- a/mangooio-core/src/main/java/io/mangoo/enums/RouteType.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.mangoo.enums; - -/** - * Route types for easy routing configuration - * - * @author svenkubiak - * - */ -public enum RouteType { - REQUEST, - RESOURCE_FILE, - RESOURCE_PATH, - SERVER_SENT_EVENT, - WEBSOCKET -} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/enums/SecureType.java b/mangooio-core/src/main/java/io/mangoo/enums/SecureType.java new file mode 100644 index 0000000000..38898d5c9c --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/enums/SecureType.java @@ -0,0 +1,13 @@ +package io.mangoo.enums; + +/** + * + * @author svenkubiak + * + */ +public enum SecureType { + CONTROLLER, + METHOD, + URL, + URLS; +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/interfaces/MangooLifecycle.java b/mangooio-core/src/main/java/io/mangoo/interfaces/MangooBootstrap.java similarity index 73% rename from mangooio-core/src/main/java/io/mangoo/interfaces/MangooLifecycle.java rename to mangooio-core/src/main/java/io/mangoo/interfaces/MangooBootstrap.java index 7a8e5df596..1d9da98917 100644 --- a/mangooio-core/src/main/java/io/mangoo/interfaces/MangooLifecycle.java +++ b/mangooio-core/src/main/java/io/mangoo/interfaces/MangooBootstrap.java @@ -1,11 +1,17 @@ package io.mangoo.interfaces; /** - * + * * @author svenkubiak * */ -public interface MangooLifecycle { +public interface MangooBootstrap { + + /** + * Place all routes for your application in this method + */ + void initializeRoutes(); + /** * Executed after config is loaded and Google Guice injector is initialized */ diff --git a/mangooio-core/src/main/java/io/mangoo/interfaces/MangooRoute.java b/mangooio-core/src/main/java/io/mangoo/interfaces/MangooRoute.java new file mode 100644 index 0000000000..879d017d32 --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/interfaces/MangooRoute.java @@ -0,0 +1,5 @@ +package io.mangoo.interfaces; + +public interface MangooRoute { + +} diff --git a/mangooio-core/src/main/java/io/mangoo/routing/Bind.java b/mangooio-core/src/main/java/io/mangoo/routing/Bind.java new file mode 100644 index 0000000000..1d027d986a --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/Bind.java @@ -0,0 +1,29 @@ +package io.mangoo.routing; + +import io.mangoo.routing.routes.ControllerRoute; +import io.mangoo.routing.routes.FileRoute; +import io.mangoo.routing.routes.PathRoute; +import io.mangoo.routing.routes.ServerSentEventRoute; +import io.mangoo.routing.routes.WebSocketRoute; + +public class Bind { + public static ServerSentEventRoute serverSentEvent() { + return new ServerSentEventRoute(); + } + + public static WebSocketRoute webSocket() { + return new WebSocketRoute(); + } + + public static PathRoute pathResource() { + return new PathRoute(); + } + + public static FileRoute fileResource() { + return new FileRoute(); + } + + public static ControllerRoute controller(Class clazz) { + return new ControllerRoute(clazz); + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/On.java b/mangooio-core/src/main/java/io/mangoo/routing/On.java new file mode 100644 index 0000000000..aa71908447 --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/On.java @@ -0,0 +1,44 @@ +package io.mangoo.routing; + +import io.mangoo.enums.Http; +import io.mangoo.routing.routes.RequestRoute; + +/** + * + * @author svenkubiak + * + */ +public class On { + + public static RequestRoute get() { + return new RequestRoute(Http.GET); + } + + public static RequestRoute post() { + return new RequestRoute(Http.POST); + } + + public static RequestRoute put() { + return new RequestRoute(Http.PUT); + } + + public static RequestRoute patch() { + return new RequestRoute(Http.PATCH); + } + + public static RequestRoute delete() { + return new RequestRoute(Http.DELETE); + } + + public static RequestRoute options() { + return new RequestRoute(Http.OPTIONS); + } + + public static RequestRoute head() { + return new RequestRoute(Http.HEAD); + } + + public static RequestRoute anyOf(Http... methods) { + return new RequestRoute(methods); + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/Route.java b/mangooio-core/src/main/java/io/mangoo/routing/Route.java deleted file mode 100644 index aa1eb3dc6e..0000000000 --- a/mangooio-core/src/main/java/io/mangoo/routing/Route.java +++ /dev/null @@ -1,139 +0,0 @@ -package io.mangoo.routing; - -import java.util.Objects; - -import io.mangoo.enums.Required; -import io.mangoo.enums.RouteType; -import io.undertow.util.HttpString; - -/** - * - * @author svenkubiak - * - */ -public class Route { - private final RouteType routeType; - private Class controllerClass; - private String controllerMethod; - private HttpString requestMethod; - private String url; - private String username; - private String password; - private int limit; - private boolean authentication; - private boolean blocking; - private boolean internalTemplateEngine; - - public Route(RouteType routeType) { - this.routeType = Objects.requireNonNull(routeType, Required.ROUTE_TYPE.toString()); - } - - public Route toUrl(String url) { - this.url = Objects.requireNonNull(url, Required.URL.toString()); - - if (RouteType.RESOURCE_PATH == this.routeType) { - if ('/' != this.url.charAt(0)) { - this.url = "/" + this.url; - } - - if (!this.url.endsWith("/")) { - this.url = this.url + "/"; - } - } else { - if ('/' != this.url.charAt(0)) { - this.url = "/" + this.url; - } - } - - return this; - } - - public Route withClass(Class controllerClass) { - this.controllerClass = controllerClass; - return this; - } - - public Route withMethod(String controllerMethod) { - this.controllerMethod = controllerMethod; - return this; - } - - public Route withRequest(HttpString requestMethod) { - this.requestMethod = requestMethod; - return this; - } - - public Route withAuthentication(boolean authentication) { - this.authentication = authentication; - return this; - } - - public Route withUsername(String username) { - this.username = username; - return this; - } - - public Route withPassword(String password) { - this.password = password; - return this; - } - - public Route allowBlocking(boolean blocking) { - this.blocking = blocking; - return this; - } - - public Route useInternalTemplateEngine() { - this.internalTemplateEngine = true; - return this; - } - - public Route withLimit(int limit) { - this.limit = limit; - return this; - } - - public String getUrl() { - return this.url; - } - - public int getLimit() { - return this.limit; - } - - public String getUsername() { - return this.username; - } - - public String getPassword() { - return this.password; - } - - public RouteType getRouteType() { - return this.routeType; - } - - public Class getControllerClass() { - return this.controllerClass; - } - - public String getControllerMethod() { - return this.controllerMethod; - } - - public HttpString getRequestMethod() { - return this.requestMethod; - } - - public boolean isAuthenticationRequired() { - return this.authentication; - } - - public boolean isInternalTemplateEngine() { - return this.internalTemplateEngine; - } - - public boolean isBlockingAllowed() { - return this.blocking; - } -} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/Router.java b/mangooio-core/src/main/java/io/mangoo/routing/Router.java index b3da29837e..ab103b19e6 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/Router.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/Router.java @@ -8,9 +8,11 @@ import java.util.concurrent.ConcurrentHashMap; import com.google.common.base.Preconditions; +import com.tc.text.StringUtils; import io.mangoo.enums.Required; -import io.mangoo.enums.RouteType; +import io.mangoo.interfaces.MangooRoute; +import io.mangoo.routing.routes.RequestRoute; /** * @@ -18,8 +20,8 @@ * */ public final class Router { - private static Set routes = ConcurrentHashMap.newKeySet(); - private static Map reverseRoutes = new ConcurrentHashMap<>(); + private static Set routes = ConcurrentHashMap.newKeySet(); + private static Map reverseRoutes = new ConcurrentHashMap<>(); private static final int MAX_ROUTES = 100000; private Router(){ @@ -30,20 +32,24 @@ private Router(){ * * @param route The route to add */ - public static void addRoute(Route route) { + public static void addRoute(MangooRoute route) { Objects.requireNonNull(route, Required.ROUTE.toString()); Preconditions.checkArgument(routes.size() <= MAX_ROUTES, "Maximum of " + MAX_ROUTES + " routes reached"); routes.add(route); - if (route.getRouteType() == RouteType.REQUEST) { - reverseRoutes.put((route.getControllerClass().getSimpleName() + ":" + route.getControllerMethod()).toLowerCase(Locale.ENGLISH), route); + + if (route instanceof RequestRoute) { + RequestRoute requestRoute = (RequestRoute) route; + if (requestRoute.getControllerClass() != null && StringUtils.isNotBlank(requestRoute.getControllerMethod())) { + reverseRoutes.put((requestRoute.getControllerClass().getSimpleName() + ":" + requestRoute.getControllerMethod()).toLowerCase(Locale.ENGLISH), requestRoute); + } } } /** * @return An unmodifiable set of all configured routes */ - public static Set getRoutes() { + public static Set getRoutes() { return Collections.unmodifiableSet(routes); } @@ -53,8 +59,8 @@ public static Set getRoutes() { * @param key The controller class and method in the form ControllerClass:ControllerMethod * @return A route object based on the given controller and method or null if none found */ - public static Route getReverseRoute(String key) { + public static RequestRoute getReverseRoute(String key) { Objects.requireNonNull(key, Required.KEY.toString()); - return reverseRoutes.get(key.toLowerCase(Locale.ENGLISH)); + return (RequestRoute) reverseRoutes.get(key.toLowerCase(Locale.ENGLISH)); } } \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/Secure.java b/mangooio-core/src/main/java/io/mangoo/routing/Secure.java new file mode 100644 index 0000000000..7849ebdedc --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/Secure.java @@ -0,0 +1,88 @@ +package io.mangoo.routing; + +import java.util.Objects; + +import io.mangoo.enums.Required; +import io.mangoo.enums.SecureType; + +/** + * + * @author svenkubiak + * + */ +public class Secure { + private Class controllerClass; + private SecureType secureType; + private String url; + private String controllerMethod; + private String[] urls; + + public static Secure url(String url) { + Objects.requireNonNull(url, Required.URL.toString()); + + Secure secure = new Secure(); + secure.secureType = SecureType.URL; + secure.url = url; + + return secure; + } + + public static Secure controller(Class clazz) { + Objects.requireNonNull(clazz, Required.CONTROLLER_CLASS.toString()); + + Secure secure = new Secure(); + secure.secureType = SecureType.CONTROLLER; + secure.controllerClass = clazz; + + return secure; + } + + public static Secure method(Class clazz, String method) { + Objects.requireNonNull(clazz, Required.CONTROLLER_CLASS.toString()); + Objects.requireNonNull(clazz, Required.CONTROLLER_METHOD.toString()); + + Secure secure = new Secure(); + secure.secureType = SecureType.METHOD; + secure.controllerClass = clazz; + secure.controllerMethod = method; + + return secure; + } + + public static Secure urls(String... urls) { + Objects.requireNonNull(urls, Required.URL.toString()); + + Secure secure = new Secure(); + secure.secureType = SecureType.URLS; + secure.urls = urls; + + return secure; + } + + public void withBasicAuthentication(String username, String password) { + Objects.requireNonNull(username, Required.USERNAME.toString()); + Objects.requireNonNull(password, Required.PASSWORD.toString()); + + if (SecureType.URL == this.secureType) { + + } else if (SecureType.CONTROLLER == this.secureType) { + Router.getRoutes().forEach(route -> { + + }); + } else if (SecureType.METHOD == this.secureType) { + + } else if (SecureType.URLS == this.secureType) { + + } else { + // Ignore anything else + } + } + + public void withAuthentication() { + // TODO Auto-generated method stub + } + + public void withAuthorization(String role) { + // TODO Auto-generated method stub + } +} diff --git a/mangooio-core/src/main/java/io/mangoo/routing/routes/ControllerRoute.java b/mangooio-core/src/main/java/io/mangoo/routing/routes/ControllerRoute.java new file mode 100644 index 0000000000..3e8ec8e39f --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/ControllerRoute.java @@ -0,0 +1,42 @@ +package io.mangoo.routing.routes; + +import java.util.Objects; + +import io.mangoo.enums.Http; +import io.mangoo.enums.Required; +import io.mangoo.interfaces.MangooRoute; +import io.mangoo.routing.Router; + +/** + * + * @author svenkubiak + * + */ + +public class ControllerRoute { + private Class controllerClass; + + public ControllerRoute(Class clazz) { + Objects.requireNonNull(clazz, Required.CONTROLLER_CLASS.toString()); + + this.controllerClass = clazz; + } + + public void with(MangooRoute... routes) { + Objects.requireNonNull(routes, Required.ROUTE.toString()); + + for (MangooRoute route : routes) { + RequestRoute requestRoute = (RequestRoute) route; + requestRoute.withControllerClass(this.controllerClass); + + if (requestRoute.hasMultipleMethods()) { + for (Http method : requestRoute.getMethods()) { + requestRoute.withHttpMethod(method); + Router.addRoute(requestRoute); + } + } else { + Router.addRoute(requestRoute); + } + } + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/routes/FileRoute.java b/mangooio-core/src/main/java/io/mangoo/routing/routes/FileRoute.java new file mode 100644 index 0000000000..74d4207d4d --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/FileRoute.java @@ -0,0 +1,22 @@ +package io.mangoo.routing.routes; + +import java.util.Objects; + +import io.mangoo.enums.Required; +import io.mangoo.interfaces.MangooRoute; +import io.mangoo.routing.Router; + +public class FileRoute implements MangooRoute { + private String url; + + public String getUrl() { + return this.url; + } + + public void to(String url) { + Objects.requireNonNull(url, Required.URL.toString()); + this.url = url; + + Router.addRoute(this); + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/routes/PathRoute.java b/mangooio-core/src/main/java/io/mangoo/routing/routes/PathRoute.java new file mode 100644 index 0000000000..b71052b843 --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/PathRoute.java @@ -0,0 +1,22 @@ +package io.mangoo.routing.routes; + +import java.util.Objects; + +import io.mangoo.enums.Required; +import io.mangoo.interfaces.MangooRoute; +import io.mangoo.routing.Router; + +public class PathRoute implements MangooRoute { + private String url; + + public String getUrl() { + return this.url; + } + + public void to(String url) { + Objects.requireNonNull(url, Required.URL.toString()); + this.url = url; + + Router.addRoute(this); + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/routes/RequestRoute.java b/mangooio-core/src/main/java/io/mangoo/routing/routes/RequestRoute.java new file mode 100644 index 0000000000..dbb9fe77dd --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/RequestRoute.java @@ -0,0 +1,119 @@ +package io.mangoo.routing.routes; + +import java.util.Objects; + +import io.mangoo.enums.Http; +import io.mangoo.enums.Required; +import io.mangoo.interfaces.MangooRoute; +import io.mangoo.routing.Response; + +/** + * + * @author svenkubiak + * + */ +public class RequestRoute implements MangooRoute { + private Http[] methods; + private String url; + private Class controllerClass; + private String controllerMethod; + private int limit; + private Http method; + private boolean blocking; + private Response response; + + public RequestRoute(Http method) { + Objects.requireNonNull(method, Required.HTTP_METHOD.toString()); + + this.method = method; + } + + public RequestRoute(Http... methods) { + Objects.requireNonNull(method, Required.HTTP_METHOD.toString()); + + this.methods = methods; + } + + public RequestRoute to(String url) { + Objects.requireNonNull(url, Required.URL.toString()); + this.url = url; + + return this; + } + + public RequestRoute respondeWith(Response response) { + Objects.requireNonNull(response, Required.RESPONSE.toString()); + + this.response = response; + + return this; + } + + public RequestRoute respondeWith(String method) { + Objects.requireNonNull(method, Required.CONTROLLER_METHOD.toString()); + + this.controllerMethod = method; + + return this; + } + + public RequestRoute maxRequestsPerSecond(int requestsPerSecond) { + this.limit = requestsPerSecond; + + return this; + } + + public RequestRoute canBlock() { + this.blocking = true; + + return this; + } + + public void withControllerClass(Class clazz) { + Objects.requireNonNull(clazz, Required.CONTROLLER_CLASS.toString()); + + this.controllerClass = clazz; + } + + public void withHttpMethod(Http method) { + Objects.requireNonNull(method, Required.METHOD.toString()); + + this.method = method; + } + + public boolean hasMultipleMethods() { + return methods != null && methods.length > 0; + } + + public Http[] getMethods() { + return methods; + } + + public String getUrl() { + return url; + } + + public Class getControllerClass() { + return controllerClass; + } + + public String getControllerMethod() { + return controllerMethod; + } + + public int getLimit() { + return limit; + } + + public Http getMethod() { + return method; + } + + public boolean isBlocking() { + return blocking; + } + + public Response getResponse() { + return response; + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/routes/ServerSentEventRoute.java b/mangooio-core/src/main/java/io/mangoo/routing/routes/ServerSentEventRoute.java new file mode 100644 index 0000000000..8106df1ec0 --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/ServerSentEventRoute.java @@ -0,0 +1,21 @@ +package io.mangoo.routing.routes; + +import java.util.Objects; + +import io.mangoo.enums.Required; +import io.mangoo.interfaces.MangooRoute; +import io.mangoo.routing.Router; + +public class ServerSentEventRoute implements MangooRoute { + private String url; + + public String getUrl() { + return this.url; + } + + public void to(String url) { + Objects.requireNonNull(url, Required.URL.toString()); + this.url = url; + Router.addRoute(this); + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/routing/routes/WebSocketRoute.java b/mangooio-core/src/main/java/io/mangoo/routing/routes/WebSocketRoute.java new file mode 100644 index 0000000000..71664141b7 --- /dev/null +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/WebSocketRoute.java @@ -0,0 +1,36 @@ +package io.mangoo.routing.routes; + +import java.util.Objects; + +import io.mangoo.enums.Required; +import io.mangoo.interfaces.MangooRoute; +import io.mangoo.routing.Router; + +public class WebSocketRoute implements MangooRoute { + private String url; + private Class controller; + + public String getUrl() { + return url; + } + + public Class getControllerClass() { + return controller; + } + + public WebSocketRoute to(String url) { + Objects.requireNonNull(url, Required.URL.toString()); + this.url = url; + + Router.addRoute(this); + + return this; + } + + public WebSocketRoute onController(Class clazz) { + Objects.requireNonNull(clazz, Required.URL.toString()); + + this.controller = clazz; + return this; + } +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/templating/methods/RouteMethod.java b/mangooio-core/src/main/java/io/mangoo/templating/methods/RouteMethod.java index fa7b8583cc..85fa842a95 100644 --- a/mangooio-core/src/main/java/io/mangoo/templating/methods/RouteMethod.java +++ b/mangooio-core/src/main/java/io/mangoo/templating/methods/RouteMethod.java @@ -10,8 +10,8 @@ import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; -import io.mangoo.routing.Route; import io.mangoo.routing.Router; +import io.mangoo.routing.routes.RequestRoute; /** * @@ -28,9 +28,9 @@ public TemplateModel exec(List arguments) throws TemplateModelException { String url; if (arguments.size() >= MIN_ARGUMENTS) { String controller = ((SimpleScalar) arguments.get(0)).getAsString(); - Route route = Router.getReverseRoute(controller); - if (route != null) { - url = route.getUrl(); + RequestRoute requestRoute = Router.getReverseRoute(controller); + if (requestRoute != null) { + url = requestRoute.getUrl(); Matcher matcher = PARAMETER_PATTERN.matcher(url); int i = 1; while (matcher.find()) { diff --git a/mangooio-core/src/main/java/io/mangoo/utils/BootstrapUtils.java b/mangooio-core/src/main/java/io/mangoo/utils/BootstrapUtils.java index 58a71da0e4..f5c0c74cec 100644 --- a/mangooio-core/src/main/java/io/mangoo/utils/BootstrapUtils.java +++ b/mangooio-core/src/main/java/io/mangoo/utils/BootstrapUtils.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; -import java.util.Locale; import java.util.Objects; import java.util.Properties; @@ -16,7 +15,6 @@ import io.mangoo.enums.Default; import io.mangoo.enums.Required; -import io.mangoo.enums.RouteType; /** * @@ -29,37 +27,6 @@ public final class BootstrapUtils { private BootstrapUtils() { } - /** - * Retrieves a RouteType enum based on a given method string - * - * @param method The method to check - * @return The RouteType enum or null if given method is undefined - */ - public static RouteType getRouteType(String method) { - Objects.requireNonNull(method, Required.METHOD.toString()); - - switch (method.toUpperCase(Locale.ENGLISH)) { - case "GET": - case "POST": - case "PUT": - case "DELETE": - case "PATCH": - case "OPTIONS": - case "HEAD": - return RouteType.REQUEST; - case "WSS": - return RouteType.WEBSOCKET; - case "SSE": - return RouteType.SERVER_SENT_EVENT; - case "FILE": - return RouteType.RESOURCE_FILE; - case "PATH": - return RouteType.RESOURCE_PATH; - default: - return null; - } - } - /** * Retrieves the current version of the framework from the version.properties file * diff --git a/mangooio-integration-test/src/main/java/app/Bootstrap.java b/mangooio-integration-test/src/main/java/app/Bootstrap.java new file mode 100644 index 0000000000..36b1bf1063 --- /dev/null +++ b/mangooio-integration-test/src/main/java/app/Bootstrap.java @@ -0,0 +1,187 @@ +package app; + +import controllers.ApplicationController; +import controllers.AuthenticationController; +import controllers.AuthenticityController; +import controllers.BasicAuthenticationController; +import controllers.FilterController; +import controllers.FlashController; +import controllers.FormController; +import controllers.I18nController; +import controllers.JsonController; +import controllers.ParameterController; +import controllers.SessionController; +import controllers.WebSocketController; +import controllers.subcontrollers.SubController; +import io.mangoo.interfaces.MangooBootstrap; +import io.mangoo.routing.Bind; +import io.mangoo.routing.On; +import io.mangoo.routing.Secure; + +public class Bootstrap implements MangooBootstrap { + + @Override + public void initializeRoutes() { + // SessionController + Bind.controller(SessionController.class).with( + On.get().to("/session").respondeWith("session"), + On.get().to("/session/valued/{uuid}").respondeWith("valued") + ); + + // AuthenticityController + Bind.controller(AuthenticityController.class).with( + On.get().to("/authenticityform").respondeWith("form"), + On.get().to("/authenticitytoken").respondeWith("token"), + On.get().to("/valid").respondeWith("valid"), + On.get().to("/invalid").respondeWith("invalid") + ); + + // FilterController + Bind.controller(FilterController.class).with( + On.get().to("/filter").respondeWith("filter"), + On.get().to("/headerfilter").respondeWith("headerfilter"), + On.get().to("/filters").respondeWith("filters") + ); + + // I18nController + Bind.controller(I18nController.class).with( + On.get().to("/translation").respondeWith("translation"), + On.get().to("/messages").respondeWith("messages"), + On.get().to("/special").respondeWith("special"), + On.get().to("/umlaute").respondeWith("umlaute"), + On.get().to("/localize").respondeWith("localize") + ); + + // FlashController + Bind.controller(FlashController.class).with( + On.get().to("/flash").respondeWith("flash"), + On.get().to("/flashed").respondeWith("flashed") + ); + + // JsonController + Bind.controller(JsonController.class).with( + On.get().to("/render").respondeWith("render"), + On.post().to("/parse").respondeWith("parse"), + On.put().to("/parse").respondeWith("parse"), + On.patch().to("/parse").respondeWith("parse"), + On.post().to("/body").respondeWith("body"), + On.post().to("/requestAndJson").respondeWith("requestAndJson") + ); + + // FormController + Bind.controller(FormController.class).with( + On.post().to("/form").respondeWith("form"), + On.post().to("/multivalued").respondeWith("multivalued"), + On.post().to("/submit").respondeWith("submit"), + On.get().to("/flashify").respondeWith("flashify"), + On.post().to("/singlefile").respondeWith("singlefile"), + On.post().to("/multifile").respondeWith("multifile"), + On.post().to("/validateform").respondeWith("validateform") + ); + + // AuthenticationController + Bind.controller(AuthenticationController.class).with( + On.post().to("/dologin").respondeWith("doLogin"), + On.post().to("/login").respondeWith("login"), + On.get().to("/login").respondeWith("login"), + On.get().to("/subject").respondeWith("subject"), + On.get().to("/authenticationrequired").respondeWith("notauthenticated"), + On.get().to("/authenticate").respondeWith("authenticate"), + On.get().to("/logout").respondeWith("logout") + ); + + // ParameterController + Bind.controller(ParameterController.class).with( + On.get().to("/string/{foo}").respondeWith("stringParam"), + On.get().to("/optional/{foo}").respondeWith("optionalParam"), + On.get().to("/string").respondeWith("stringParam"), + On.get().to("/int/{foo}").respondeWith("intParam"), + On.get().to("/integer/{foo}").respondeWith("integerParam"), + On.get().to("/doublePrimitive/{foo}").respondeWith("doublePrimitiveParam"), + On.get().to("/double/{foo}").respondeWith("doubleParam"), + On.get().to("/float/{foo}").respondeWith("floatParam"), + On.get().to("/floatPrimitive/{foo}").respondeWith("floatPrimitiveParam"), + On.get().to("/longPrimitive/{foo}").respondeWith("longPrimitiveParam"), + On.get().to("/long/{foo}").respondeWith("longParam"), + On.get().to("/multiple/{foo}/{bar}").respondeWith("multipleParam"), + On.get().to("/path").respondeWith("pathParam"), + On.get().to("/localdate/{localDate}").respondeWith("localdate"), + On.get().to("/localdatetime/{localDateTime}").respondeWith("localdatetime") + ); + + // ApplicationController + Bind.controller(ApplicationController.class).with( + On.get().to("/").respondeWith("index").canBlock(), + On.get().to("/route").respondeWith("route"), + On.post().to("/").respondeWith("index"), + On.put().to("/").respondeWith("index"), + On.patch().to("/").respondeWith("index"), + On.head().to("/").respondeWith("index"), + On.delete().to("/").respondeWith("index"), + On.options().to("/").respondeWith("index"), + On.get().to("/reverse").respondeWith("reverse"), + On.get().to("/location").respondeWith("location"), + On.get().to("/prettytime").respondeWith("prettytime"), + On.get().to("/location/{myloca}").respondeWith("location"), + On.get().to("/redirect").respondeWith("redirect"), + On.get().to("/limit").respondeWith("limit").maxRequestsPerSecond(10), + On.get().to("/text").respondeWith("text"), + On.get().to("/forbidden").respondeWith("forbidden"), + On.get().to("/badrequest").respondeWith("badrequest"), + On.get().to("/unauthorized").respondeWith("unauthorized"), + On.get().to("/binary").respondeWith("binary"), + On.get().to("/header").respondeWith("header").canBlock(), + On.get().to("/etag").respondeWith("etag"), + On.get().to("/request").respondeWith("request"), + On.post().to("/post").respondeWith("post"), + On.put().to("/post").respondeWith("put"), + On.post().to("/jsonpathpost").respondeWith("jsonPathPost"), + On.put().to("/jsonpathput").respondeWith("jsonPathPut"), + On.post().to("/jsonboonpost").respondeWith("jsonBoonPost"), + On.put().to("/jsonboonpost").respondeWith("jsonBoonPut"), + On.get().to("/freemarker").respondeWith("freemarker") + ); + + // SubController + Bind.controller(SubController.class).with( + On.get().to("/subcontroller").respondeWith("check") + ); + + // BasicAuthenticationController + Bind.controller(BasicAuthenticationController.class).with( + On.get().to("/basicauth").respondeWith("basicauth") + ); + + Bind.serverSentEvent().to("/sse"); + Bind.serverSentEvent().to("/sseauth"); + + Bind.webSocket().onController(WebSocketController.class).to("/websocket"); + Bind.webSocket().onController(WebSocketController.class).to("/websocketauth"); + + Bind.pathResource().to("/assets/"); + Bind.fileResource().to("/robots.txt"); + + Secure.controller(BasicAuthenticationController.class).withBasicAuthentication("username", "password"); + Secure.method(BasicAuthenticationController.class, "foo").withBasicAuthentication("username", "password"); + + Secure.url("/protected").withBasicAuthentication("username", "password"); + Secure.url("/dashboard").withAuthentication(); + Secure.urls("/dashboard", "bla", "bar", "foo").withAuthentication(); + Secure.url("/auth/*").withAuthorization("rolename"); + } + + @Override + public void applicationInitialized() { + // TODO Auto-generated method stub + } + + @Override + public void applicationStarted() { + // TODO Auto-generated method stub + } + + @Override + public void applicationStopped() { + // TODO Auto-generated method stub + } +} \ No newline at end of file diff --git a/mangooio-integration-test/src/main/java/conf/Module.java b/mangooio-integration-test/src/main/java/app/Module.java similarity index 71% rename from mangooio-integration-test/src/main/java/conf/Module.java rename to mangooio-integration-test/src/main/java/app/Module.java index 752002834a..b4c77586da 100644 --- a/mangooio-integration-test/src/main/java/conf/Module.java +++ b/mangooio-integration-test/src/main/java/app/Module.java @@ -1,15 +1,15 @@ -package conf; +package app; import com.google.inject.AbstractModule; import filters.MyGlobalFilter; -import io.mangoo.interfaces.MangooLifecycle; +import io.mangoo.interfaces.MangooBootstrap; import io.mangoo.interfaces.MangooRequestFilter; public class Module extends AbstractModule { @Override protected void configure() { + bind(MangooBootstrap.class).to(Bootstrap.class); bind(MangooRequestFilter.class).to(MyGlobalFilter.class); - bind(MangooLifecycle.class).to(Lifecycle.class); } } \ No newline at end of file diff --git a/mangooio-integration-test/src/main/java/conf/Lifecycle.java b/mangooio-integration-test/src/main/java/conf/Lifecycle.java deleted file mode 100644 index c6949a88a4..0000000000 --- a/mangooio-integration-test/src/main/java/conf/Lifecycle.java +++ /dev/null @@ -1,34 +0,0 @@ -package conf; - -import com.google.inject.Singleton; - -import io.mangoo.interfaces.MangooLifecycle; - -@Singleton -public class Lifecycle implements MangooLifecycle { - private int initialize; - private int started; - - @Override - public void applicationInitialized() { - this.initialize++; - } - - @Override - public void applicationStarted() { - this.started++; - } - - @Override - public void applicationStopped() { - // do nothing for now - } - - public int getInitialize() { - return initialize; - } - - public int getStarted() { - return started; - } -} \ No newline at end of file diff --git a/mangooio-integration-test/src/main/java/main/Main.java b/mangooio-integration-test/src/main/java/main/Main.java index 5492157791..2db9cbce08 100644 --- a/mangooio-integration-test/src/main/java/main/Main.java +++ b/mangooio-integration-test/src/main/java/main/Main.java @@ -13,7 +13,7 @@ public final class Main { private Main(){ } - public static void main(String... args) throws Exception { + public static void main(String... args) { Application.start(Mode.DEV); } } \ No newline at end of file diff --git a/mangooio-integration-test/src/main/resources/routes.yaml b/mangooio-integration-test/src/main/resources/routes.yaml deleted file mode 100644 index 44133ebf39..0000000000 --- a/mangooio-integration-test/src/main/resources/routes.yaml +++ /dev/null @@ -1,382 +0,0 @@ -routes: -# Routes configuration -# -# This file defines all application routes. -# All routes start with an identifier of the method, followed by the -# url, followed by a mapping to the controller class and method. For -# some types a controller and method is not required. -# -# You can find a detailed explation of the routing file in the documentation -# https://mangoo.io/documentation#_routes -# -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -# BasicAuthenticationController -- method: GET - url: /basicauth - mapping: BasicAuthenticationController.basicauth - username: foo - password: $2a$12$Po56ZgZQgDEoK6nws6gaAuZriIwcFT1thEHq.N2T9wLdUnhmlLKxG - -# FilterController -- method: GET - url: /filter - mapping: FilterController.filter - -- method: GET - url: /headerfilter - mapping: FilterController.headerfilter - -- method: GET - url: /filters - mapping: FilterController.filters - -# I18nController -- method: GET - url: /translation - mapping: I18nController.translation - -- method: GET - url: /messages - mapping: I18nController.messages - -- method: GET - url: /special - mapping: I18nController.special - -- method: GET - url: /umlaute - mapping: I18nController.umlaute - -- method: GET - url: /localize - mapping: I18nController.localize - -# FlashController -- method: GET - url: /flash - mapping: FlashController.flash - -- method: GET - url: /flashed - mapping: FlashController.flashed - -# AuthenticationController -- method: POST - url: /dologin - mapping: AuthenticationController.doLogin - -- method: POST - url: /login - mapping: AuthenticationController.login - -- method: GET - url: /login - mapping: AuthenticationController.login - -- method: GET - url: /subject - mapping: AuthenticationController.subject - -- method: GET - url: /authenticationrequired - mapping: AuthenticationController.notauthenticated - -- method: GET - url: /authenticate - mapping: AuthenticationController.authenticate - -- method: GET - url: /logout - mapping: AuthenticationController.logout - -# SessionController -- method: GET - url: /session - mapping: SessionController.session - -- method: GET - url: /session/valued/{uuid} - mapping: SessionController.valued - -# ParameterController -- method: GET - url: /string/{foo} - mapping: ParameterController.stringParam - -- method: GET - url: /optional/{foo} - mapping: ParameterController.optionalParam - -- method: GET - url: /string - mapping: ParameterController.stringParam - -- method: GET - url: /int/{foo} - mapping: ParameterController.intParam - -- method: GET - url: /integer/{foo} - mapping: ParameterController.integerParam - -- method: GET - url: /doublePrimitive/{foo} - mapping: ParameterController.doublePrimitiveParam - -- method: GET - url: /double/{foo} - mapping: ParameterController.doubleParam - -- method: GET - url: /float/{foo} - mapping: ParameterController.floatParam - -- method: GET - url: /floatPrimitive/{foo} - mapping: ParameterController.floatPrimitiveParam - -- method: GET - url: /longPrimitive/{foo} - mapping: ParameterController.longPrimitiveParam - -- method: GET - url: /long/{foo} - mapping: ParameterController.longParam - -- method: GET - url: /multiple/{foo}/{bar} - mapping: ParameterController.multipleParam - -- method: GET - url: /path - mapping: ParameterController.pathParam - -- method: GET - url: /localdate/{localDate} - mapping: ParameterController.localdate - -- method: GET - url: /localdatetime/{localDateTime} - mapping: ParameterController.localdatetime - -# AuthenticityController -- method: GET - url: /authenticityform - mapping: AuthenticityController.form - -- method: GET - url: /authenticitytoken - mapping: AuthenticityController.token - -- method: GET - url: /valid - mapping: AuthenticityController.valid - -- method: GET - url: /invalid - mapping: AuthenticityController.invalid - -#JsonController -- method: GET - url: /render - mapping: JsonController.render - -- method: POST - url: /parse - mapping: JsonController.parse - -- method: PUT - url: /parse - mapping: JsonController.parse - -- method: PATCH - url: /parse - mapping: JsonController.parse - -- method: POST - url: /body - mapping: JsonController.body - -- method: POST - url: /requestAndJson - mapping: JsonController.requestAndJson - -# FormController -- method: POST - url: /form - mapping: FormController.form - -- method: POST - url: /multivalued - mapping: FormController.multivalued - -- method: POST - url: /submit - mapping: FormController.submit - -- method: GET - url: /flashify - mapping: FormController.flashify - -- method: POST - url: /singlefile - mapping: FormController.singlefile - -- method: POST - url: /multifile - mapping: FormController.multifile - -- method: POST - url: /validateform - mapping: FormController.validateform - -# ApplicationController -- method: GET - url: / - mapping: ApplicationController.index - blocking: true - -- method: GET - url: /route - mapping: ApplicationController.route - -- method: POST - url: / - mapping: ApplicationController.index - -- method: PUT - url: / - mapping: ApplicationController.index - -- method: PATCH - url: / - mapping: ApplicationController.index - -- method: HEAD - url: / - mapping: ApplicationController.index - -- method: DELETE - url: / - mapping: ApplicationController.index - -- method: OPTIONS - url: / - mapping: ApplicationController.index - -- method: GET - url: /reverse - mapping: ApplicationController.reverse - -- method: GET - url: /location - mapping: ApplicationController.location - -- method: GET - url: /prettytime - mapping: ApplicationController.prettytime - -- method: GET - url: /location/{myloca} - mapping: ApplicationController.location - -- method: GET - url: /redirect - mapping: ApplicationController.redirect - -- method: GET - url: /limit - mapping: ApplicationController.limit - limit: 10 - -- method: GET - url: /text - mapping: ApplicationController.text - -- method: GET - url: /forbidden - mapping: ApplicationController.forbidden - -- method: GET - url: /badrequest - mapping: ApplicationController.badrequest - -- method: GET - url: /unauthorized - mapping: ApplicationController.unauthorized - -- method: GET - url: /binary - mapping: ApplicationController.binary - -- method: GET - url: /header - mapping: ApplicationController.header - blocking: true - -- method: GET - url: /etag - mapping: ApplicationController.etag - -- method: GET - url: /request - mapping: ApplicationController.request - -- method: POST - url: /post - mapping: ApplicationController.post - -- method: PUT - url: /put - mapping: ApplicationController.put - -- method: POST - url: /jsonpathpost - mapping: ApplicationController.jsonPathPost - -- method: PUT - url: /jsonpathput - mapping: ApplicationController.jsonPathPut - -- method: POST - url: /jsonboonpost - mapping: ApplicationController.jsonBoonPost - -- method: PUT - url: /jsonboonput - mapping: ApplicationController.jsonBoonPut - -- method: GET - url: /freemarker - mapping: ApplicationController.freemarker - -# Controllers in Sub Packages -- method: GET - url: /subcontroller - mapping: subcontrollers.SubController.check - -# WebSocketController -- method: WSS - url: /websocket - mapping: WebSocketController - -- method: WSS - url: /websocketauth - mapping: WebSocketController - authentication: true - -# ServerSentEvent -- method: SSE - url: /sse - -- method: SSE - url: /sseauth - authentication: true - -# Resource path and resource files -- method: PATH - url: /assets/ - -- method: FILE - url: /robots.txt diff --git a/mangooio-integration-test/src/test/java/io/mangoo/configuration/LifecycleTest.java b/mangooio-integration-test/src/test/java/io/mangoo/configuration/LifecycleTest.java deleted file mode 100644 index b1a1d1245a..0000000000 --- a/mangooio-integration-test/src/test/java/io/mangoo/configuration/LifecycleTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.mangoo.configuration; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; - -import conf.Lifecycle; -import io.mangoo.TestExtension; -import io.mangoo.core.Application; - -/** - * - * @author svenkubiak - * - */ -@ExtendWith({TestExtension.class}) -public class LifecycleTest { - @Test - public void testLifecycleInvocation() { - //given - final Lifecycle lifecycle = Application.getInstance(Lifecycle.class); - - //then - assertThat(lifecycle.getInitialize(), equalTo(1)); - assertThat(lifecycle.getStarted(), equalTo(1)); - } -} \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/configuration/ModuleTest.java b/mangooio-integration-test/src/test/java/io/mangoo/configuration/ModuleTest.java index 33acd8d4eb..550ab1b172 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/configuration/ModuleTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/configuration/ModuleTest.java @@ -16,7 +16,7 @@ import io.mangoo.TestExtension; import io.mangoo.cache.Cache; import io.mangoo.core.Application; -import io.mangoo.interfaces.MangooLifecycle; +import io.mangoo.interfaces.MangooBootstrap; import io.mangoo.interfaces.MangooRequestFilter; import io.mangoo.templating.TemplateEngine; @@ -41,7 +41,7 @@ public void testBindings() { Binding cache = guice.getBinding(Cache.class); Binding templateEngine = guice.getBinding(TemplateEngine.class); Binding mangooRequestFilter = guice.getBinding(MangooRequestFilter.class); - Binding mangooLifecycle = guice.getBinding(MangooLifecycle.class); + Binding mangooBootstrap = guice.getBinding(MangooBootstrap.class); //then assertThat(stage.getKey().getTypeLiteral().getType().getTypeName(), equalTo("com.google.inject.Stage")); @@ -52,7 +52,6 @@ public void testBindings() { assertThat(cache.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.cache.Cache")); assertThat(templateEngine.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.templating.TemplateEngine")); assertThat(mangooRequestFilter.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.interfaces.MangooRequestFilter")); - assertThat(mangooLifecycle.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.interfaces.MangooLifecycle")); - + assertThat(mangooBootstrap.getKey().getTypeLiteral().getType().getTypeName(), equalTo("io.mangoo.interfaces.MangooBootstrap")); } } \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/filters/AdminFilterTest.java b/mangooio-integration-test/src/test/java/io/mangoo/filters/AdminFilterTest.java deleted file mode 100644 index 486b4274dd..0000000000 --- a/mangooio-integration-test/src/test/java/io/mangoo/filters/AdminFilterTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package io.mangoo.filters; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.mockito.Mockito.when; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; - -import io.mangoo.TestExtension; -import io.mangoo.admin.AdminFilter; -import io.mangoo.configuration.Config; -import io.mangoo.core.Application; -import io.mangoo.enums.Header; -import io.mangoo.enums.Template; -import io.mangoo.routing.Response; -import io.mangoo.routing.bindings.Request; -import io.undertow.util.StatusCodes; - -/** - * - * @author svenkubiak - * - */ -@ExtendWith({TestExtension.class}) -public class AdminFilterTest { - - @Test - public void testAdminNotEnabled() { - //given - Config mockedConfig = Mockito.mock(Config.class); - Request mockedRequest = Mockito.mock(Request.class); - Response mockedResponse = Mockito.mock(Response.class); - AdminFilter filter = new AdminFilter(mockedConfig); - - //when - when(mockedConfig.isApplicationAdminEnable()).thenReturn(false); - Response response = filter.execute(mockedRequest, mockedResponse); - - //then - assertThat(response, not(nullValue())); - assertThat(response.getStatusCode(), equalTo(StatusCodes.NOT_FOUND)); - assertThat(response.getBody(), equalTo(Template.DEFAULT.notFound())); - assertThat(response.isEndResponse(), equalTo(true)); - } - - @Test - public void testAdminEnabledNotAuthorized() { - //given - Config mockedConfig = Mockito.mock(Config.class); - Request mockedRequest = Mockito.mock(Request.class); - Response mockedResponse = Mockito.mock(Response.class); - AdminFilter filter = new AdminFilter(mockedConfig); - - //when - when(mockedConfig.isApplicationAdminEnable()).thenReturn(true); - when(mockedRequest.getHeader(Header.AUTHORIZATION.toHttpString())).thenReturn(""); - Response response = filter.execute(mockedRequest, mockedResponse); - - //then - assertThat(response, not(nullValue())); - assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getHeader(Header.WWW_AUTHENTICATE.toHttpString()), equalTo("Basic realm=Administration authentication")); - assertThat(response.getBody(), equalTo("")); - assertThat(response.isEndResponse(), equalTo(true)); - } - - @Test - public void testAdminEnabledAuthorized() { - //given - Config config = Application.getInstance(Config.class); - Request mockedRequest = Mockito.mock(Request.class); - Response mockedResponse = Mockito.mock(Response.class); - AdminFilter filter = new AdminFilter(config); - - //when - when(mockedRequest.getHeader(Header.AUTHORIZATION.toHttpString())).thenReturn("Basic YWRtaW46YWRtaW4="); - Response response = filter.execute(mockedRequest, mockedResponse); - - //then - assertThat(response, not(nullValue())); - assertThat(response, equalTo(mockedResponse)); - } -} \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/RouterTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/RouterTest.java index e23f14dce7..43b84c46f6 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/routing/RouterTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/RouterTest.java @@ -9,9 +9,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import controllers.ApplicationController; import io.mangoo.TestExtension; -import io.mangoo.enums.RouteType; /** * @@ -24,7 +22,7 @@ public class RouterTest { @Test public void testAddRoute() { //given - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/foo").withMethod("bar").withClass(ApplicationController.class)); + On.get().to("/foo").respondeWith("index"); //then assertThat(Router.getRoutes(), not(nullValue())); @@ -35,7 +33,7 @@ public void testAddRoute() { public void testMaxRoutes() { Assertions.assertThrows(IllegalArgumentException.class, () -> { for (int i=0; i <= 100000; i++) { - Router.addRoute(new Route(RouteType.REQUEST).toUrl("/foo").withMethod("bar").withClass(ApplicationController.class)); + On.get().to("/foo").respondeWith("index"); } }); } diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/bindings/InjectionTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/bindings/InjectionTest.java index 2d469b874f..d6e1c93992 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/routing/bindings/InjectionTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/bindings/InjectionTest.java @@ -14,7 +14,7 @@ import io.mangoo.core.Shutdown; import io.mangoo.crypto.Crypto; import io.mangoo.i18n.Messages; -import io.mangoo.interfaces.MangooLifecycle; +import io.mangoo.interfaces.MangooBootstrap; import io.mangoo.interfaces.MangooRequestFilter; import io.mangoo.models.Metrics; import io.mangoo.providers.CacheProvider; @@ -207,9 +207,9 @@ public void testExceptionHandler() { } @Test - public void testMangooLifecycle() { + public void testMangooBootstrap() { //given - MangooLifecycle mangooLifecycle = Application.getInstance(MangooLifecycle.class); + MangooBootstrap mangooLifecycle = Application.getInstance(MangooBootstrap.class); //then assertThat(mangooLifecycle, not(nullValue())); diff --git a/mangooio-integration-test/src/test/java/io/mangoo/utils/BootstrapUtilsTest.java b/mangooio-integration-test/src/test/java/io/mangoo/utils/BootstrapUtilsTest.java index 66fc40ef26..deeaab65bc 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/utils/BootstrapUtilsTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/utils/BootstrapUtilsTest.java @@ -7,8 +7,6 @@ import org.junit.jupiter.api.Test; -import io.mangoo.enums.RouteType; - /** * * @author svenkubiak @@ -16,35 +14,6 @@ */ public class BootstrapUtilsTest { - @Test - public void testGetRouteType() { - //given - String get = "get"; - String patch = "patch"; - String options = "options"; - String post = "post"; - String put = "put"; - String delete = "delete"; - String head = "head"; - String wss = "wss"; - String sse = "sse"; - String file = "file"; - String path = "path"; - - //then - assertThat(BootstrapUtils.getRouteType(options), equalTo(RouteType.REQUEST)); - assertThat(BootstrapUtils.getRouteType(patch), equalTo(RouteType.REQUEST)); - assertThat(BootstrapUtils.getRouteType(get), equalTo(RouteType.REQUEST)); - assertThat(BootstrapUtils.getRouteType(post), equalTo(RouteType.REQUEST)); - assertThat(BootstrapUtils.getRouteType(put), equalTo(RouteType.REQUEST)); - assertThat(BootstrapUtils.getRouteType(delete), equalTo(RouteType.REQUEST)); - assertThat(BootstrapUtils.getRouteType(head), equalTo(RouteType.REQUEST)); - assertThat(BootstrapUtils.getRouteType(wss), equalTo(RouteType.WEBSOCKET)); - assertThat(BootstrapUtils.getRouteType(sse), equalTo(RouteType.SERVER_SENT_EVENT)); - assertThat(BootstrapUtils.getRouteType(file), equalTo(RouteType.RESOURCE_FILE)); - assertThat(BootstrapUtils.getRouteType(path), equalTo(RouteType.RESOURCE_PATH)); - } - @Test public void testGetPackageName() { //given diff --git a/pom.xml b/pom.xml index 63f36ad8ce..4f79ab0235 100644 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ 3.5.4 4.5.6 5.6.0 - 2.9.6 + 2.9.7 3.7.0 2.27 5.3.1 @@ -198,7 +198,7 @@ com.google.inject guice - 4.2.0 + 4.2.1 org.ocpsoft.prettytime @@ -560,7 +560,7 @@ it.unimi.dsi dsiutils - 2.5.1 + 2.5.2 com.google.zxing