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 e769d2923d..6dc0e964fb 100644 --- a/mangooio-core/src/main/java/io/mangoo/admin/AdminController.java +++ b/mangooio-core/src/main/java/io/mangoo/admin/AdminController.java @@ -170,15 +170,13 @@ public Response metrics() { } public Response routes() { -// Set routes = Router.getRoutes() -// .stream() -// .filter((Route route) -> !route.getUrl().contains("@admin")) -// .collect(Collectors.toSet()); -// + //FIX ME + //Set routes = Router.getRoutes(); + return Response.withOk() .andContent(SPACE, ROUTES) .andContent(VERSION, VERSION_TAG) - //.andContent(ROUTES, routes) + .andContent(ROUTES, new ArrayList<>()) .andTemplate(Template.DEFAULT.routesPath()); } 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 8933e37308..604a8b8976 100644 --- a/mangooio-core/src/main/java/io/mangoo/core/Application.java +++ b/mangooio-core/src/main/java/io/mangoo/core/Application.java @@ -423,12 +423,15 @@ private static void createRoutes() { pathHandler.addExactPath(webSocketRoute.getUrl(), Handlers.websocket(getInstance(WebSocketHandler.class) - .withControllerClass(webSocketRoute.getControllerClass()))); + .withControllerClass(webSocketRoute.getControllerClass()) + .withAuthentication(webSocketRoute.hasAuthentication()))); + } else if (mangooRoute instanceof ServerSentEventRoute) { ServerSentEventRoute serverSentEventRoute = (ServerSentEventRoute) mangooRoute; pathHandler.addExactPath(serverSentEventRoute.getUrl(), - Handlers.serverSentEvents(getInstance(ServerSentEventHandler.class))); + Handlers.serverSentEvents(getInstance(ServerSentEventHandler.class) + .withAuthentication(serverSentEventRoute.hasAuthentication()))); } else if (mangooRoute instanceof PathRoute) { PathRoute pathRoute = (PathRoute) mangooRoute; @@ -446,7 +449,8 @@ private static RoutingHandler getRoutingHandler() { Config config = getInstance(Config.class); if (config.isApplicationAdminEnable()) { - Bind.controller(AdminController.class).with( + Bind.controller(AdminController.class).withBasicAuthentication(config.getApplicationAdminUsername(), config.getApplicationAdminPassword()) + .withRoutes( On.get().to("/@admin").respondeWith("index"), On.get().to("/@admin/health").respondeWith("health"), On.get().to("/@admin/scheduler").respondeWith("scheduler"), @@ -469,6 +473,9 @@ private static RoutingHandler getRoutingHandler() { DispatcherHandler dispatcherHandler = Application.getInstance(DispatcherHandler.class) .dispatch(requestRoute.getControllerClass(), requestRoute.getControllerMethod()) .isBlocking(requestRoute.isBlocking()) + .withBasicAuthentication(requestRoute.getUsername(), requestRoute.getPassword()) + .withAuthentication(requestRoute.hasAuthentication()) + .withAuthorization(requestRoute.hasAuthorization()) .withLimit(requestRoute.getLimit()); routingHandler.add(requestRoute.getMethod().toString(), requestRoute.getUrl(), dispatcherHandler); @@ -557,7 +564,7 @@ private static List getModules() { 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); + LOG.error("Failed to load modules. Check that app/Module.java exists in your application", e); failsafe(); } diff --git a/mangooio-core/src/main/java/io/mangoo/enums/SecureType.java b/mangooio-core/src/main/java/io/mangoo/enums/SecureType.java deleted file mode 100644 index 38898d5c9c..0000000000 --- a/mangooio-core/src/main/java/io/mangoo/enums/SecureType.java +++ /dev/null @@ -1,13 +0,0 @@ -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/MangooRoute.java b/mangooio-core/src/main/java/io/mangoo/interfaces/MangooRoute.java index 879d017d32..7b39b16482 100644 --- a/mangooio-core/src/main/java/io/mangoo/interfaces/MangooRoute.java +++ b/mangooio-core/src/main/java/io/mangoo/interfaces/MangooRoute.java @@ -1,5 +1,13 @@ package io.mangoo.interfaces; +/** + * + * @author svenkubiak + * + */ public interface MangooRoute { - -} + /** + * @return The configured URL for this route + */ + String getUrl(); +} \ No newline at end of file diff --git a/mangooio-core/src/main/java/io/mangoo/models/Identity.java b/mangooio-core/src/main/java/io/mangoo/models/Identity.java index 7ec31a39cb..cdba63084f 100644 --- a/mangooio-core/src/main/java/io/mangoo/models/Identity.java +++ b/mangooio-core/src/main/java/io/mangoo/models/Identity.java @@ -6,7 +6,6 @@ import java.util.Set; import io.mangoo.enums.Required; -import io.mangoo.utils.CodecUtils; import io.undertow.security.idm.Account; import io.undertow.security.idm.Credential; import io.undertow.security.idm.IdentityManager; @@ -73,9 +72,7 @@ public Set getRoles() { private boolean verifyCredential(Credential credential) { if (credential instanceof PasswordCredential) { - return CodecUtils.checkJBCrypt( - new String (((PasswordCredential) credential).getPassword()), - this.password); + return new String (((PasswordCredential) credential).getPassword()).equals(this.password); } return false; diff --git a/mangooio-core/src/main/java/io/mangoo/routing/Attachment.java b/mangooio-core/src/main/java/io/mangoo/routing/Attachment.java index 5ed8f228c0..4cd983ac76 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/Attachment.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/Attachment.java @@ -44,6 +44,7 @@ public class Attachment { private String password; private Request request; private boolean requestFilter; + private boolean authorization; private Map requestParameter; private Response response; private Session session; @@ -159,6 +160,10 @@ public String getUsername() { public boolean hasAuthentication() { return StringUtils.isNotBlank(this.username) && StringUtils.isNotBlank(this.password); } + + public boolean hasAuthorization() { + return this.authorization; + } public boolean hasLimit() { return this.limit > 0; @@ -256,8 +261,10 @@ public Attachment withMethodParameters(Map> methodParameters) { return this; } - public Attachment withPassword(String password) { + public Attachment withBasicAuthentication(String username, String password) { + this.username = username; this.password = password; + return this; } @@ -276,8 +283,13 @@ public Attachment withTemplateEngine(TemplateEngine templateEngine) { return this; } - public Attachment withUsername(String username) { - this.username = username; + public Attachment withAuthorization(boolean authroization) { + this.authorization = authroization; + return this; + } + + public Attachment withAuthentication(boolean authentication) { + //this.authentication = authentication; return this; } } \ 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 ab103b19e6..7b0dc76394 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/Router.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/Router.java @@ -41,7 +41,7 @@ public static void addRoute(MangooRoute 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); + reverseRoutes.put((requestRoute.getControllerClass().getSimpleName().toLowerCase(Locale.ENGLISH) + ":" + requestRoute.getControllerMethod()).toLowerCase(Locale.ENGLISH), requestRoute); } } } @@ -63,4 +63,12 @@ public static RequestRoute getReverseRoute(String key) { Objects.requireNonNull(key, Required.KEY.toString()); return (RequestRoute) reverseRoutes.get(key.toLowerCase(Locale.ENGLISH)); } + + /** + * Removes all routes from the router + */ + public static void reset() { + routes = ConcurrentHashMap.newKeySet(); + reverseRoutes = new ConcurrentHashMap<>(); + } } \ 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 deleted file mode 100644 index 7849ebdedc..0000000000 --- a/mangooio-core/src/main/java/io/mangoo/routing/Secure.java +++ /dev/null @@ -1,88 +0,0 @@ -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/handlers/DispatcherHandler.java b/mangooio-core/src/main/java/io/mangoo/routing/handlers/DispatcherHandler.java index ec9f14306f..ad185151e9 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/handlers/DispatcherHandler.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/handlers/DispatcherHandler.java @@ -56,6 +56,8 @@ public class DispatcherHandler implements HttpHandler { private int methodParametersCount; private boolean hasRequestFilter; private boolean blocking; + private boolean authentication; + private boolean authroization; public DispatcherHandler dispatch(Class controllerClass, String controllerMethodName) { Objects.requireNonNull(controllerClass, Required.CONTROLLER_CLASS.toString()); @@ -98,13 +100,24 @@ public DispatcherHandler isBlocking(boolean blocking) { return this; } - public DispatcherHandler withUsername(String username) { + public DispatcherHandler withBasicAuthentication(String username, String password) { this.username = username; + this.password = password; + + return this; + } + + public DispatcherHandler withAuthentication(boolean hasAuthentication) { + this.authentication = true; return this; } - public DispatcherHandler withPassword(String password) { - this.password = password; + public DispatcherHandler withAuthorization(boolean authorization) { +// if (authorization) { +// this.authentication = true; +// this.authroization = true; +// } +// return this; } @@ -134,8 +147,9 @@ public void handleRequest(HttpServerExchange exchange) throws Exception { .withRequestParameter(RequestUtils.getRequestParameters(exchange)) .withMessages(this.messages) .withLimit(this.limit) - .withUsername(this.username) - .withPassword(this.password) + .withAuthorization(this.authroization) + .withAuthentication(this.authentication) + .withBasicAuthentication(this.username, this.password) .withTemplateEngine(this.templateEngine); exchange.putAttachment(RequestUtils.getAttachmentKey(), attachment); 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 index 3e8ec8e39f..80712ff450 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/routes/ControllerRoute.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/ControllerRoute.java @@ -2,6 +2,8 @@ import java.util.Objects; +import org.apache.commons.lang3.StringUtils; + import io.mangoo.enums.Http; import io.mangoo.enums.Required; import io.mangoo.interfaces.MangooRoute; @@ -12,22 +14,38 @@ * @author svenkubiak * */ - public class ControllerRoute { private Class controllerClass; + private boolean authentication; + private String username; + private String password; + /** + * Creates a new set of route to a given controller class + * + * @param clazz The controller class to bind to + */ public ControllerRoute(Class clazz) { Objects.requireNonNull(clazz, Required.CONTROLLER_CLASS.toString()); this.controllerClass = clazz; } - public void with(MangooRoute... routes) { + /** + * Sets the given routes to the defined controller class + * + * @param routes The routes to be configured for the controller + */ + public void withRoutes(MangooRoute... routes) { Objects.requireNonNull(routes, Required.ROUTE.toString()); for (MangooRoute route : routes) { RequestRoute requestRoute = (RequestRoute) route; requestRoute.withControllerClass(this.controllerClass); + + if (hasBasicAuthentication()) { + requestRoute.withBasicAuthentication(this.username, this.password); + } if (requestRoute.hasMultipleMethods()) { for (Http method : requestRoute.getMethods()) { @@ -39,4 +57,66 @@ public void with(MangooRoute... routes) { } } } + + /** + * Sets Basic HTTP authentication to all method on the defined controller class + * + * @param username The username for basic authentication in clear text + * @param password The password for basic authentication in clear text + * + * @return controller route instance + */ + public ControllerRoute withBasicAuthentication(String username, String password) { + Objects.requireNonNull(username, Required.USERNAME.toString()); + Objects.requireNonNull(password, Required.PASSWORD.toString()); + + this.username = username; + this.password = password; + + return this; + } + + /** + * Sets authentication to true, default is false + * + * @return controller route instance + */ + public ControllerRoute requireAuthentication() { + this.authentication = true; + + return this; + } + + /** + * Sets required authorization role to this route + * Authorization implicitly set authentication to true + * + * @param role The require role + * @return controller route instance + */ + public ControllerRoute requireAuthorization(String role) { + // TODO Implementation needed + + return this; + } + + public boolean hasAuthentication() { + return this.authentication; + } + + public boolean hasBasicAuthentication() { + return StringUtils.isNotBlank(this.username) && StringUtils.isNotBlank(this.password); + } + + public Class getControllerClass() { + return controllerClass; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } } \ 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 index 74d4207d4d..f3e9be3154 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/routes/FileRoute.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/FileRoute.java @@ -6,17 +6,33 @@ import io.mangoo.interfaces.MangooRoute; import io.mangoo.routing.Router; +/** + * + * @author svenkubiak + * + */ public class FileRoute implements MangooRoute { private String url; - public String getUrl() { - return this.url; - } - + /** + * Sets the URL for this route + * + * @param url The URL for this route + */ public void to(String url) { Objects.requireNonNull(url, Required.URL.toString()); + + if ('/' != url.charAt(0)) { + url = "/" + url; + } + this.url = url; - + Router.addRoute(this); } + + @Override + public String getUrl() { + return this.url; + } } \ 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 index b71052b843..0192cb1deb 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/routes/PathRoute.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/PathRoute.java @@ -6,17 +6,37 @@ import io.mangoo.interfaces.MangooRoute; import io.mangoo.routing.Router; +/** + * + * @author svenkubiak + * + */ public class PathRoute implements MangooRoute { private String url; - public String getUrl() { - return this.url; - } - + /** + * Sets the URL for this route + * + * @param url The URL for this route + */ public void to(String url) { Objects.requireNonNull(url, Required.URL.toString()); + + if ('/' != url.charAt(0)) { + url = "/" + url; + } + + if (!url.endsWith("/")) { + url = url + "/"; + } + this.url = url; Router.addRoute(this); } + + @Override + public String getUrl() { + return this.url; + } } \ 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 index dbb9fe77dd..16660019a9 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/routes/RequestRoute.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/RequestRoute.java @@ -2,6 +2,8 @@ import java.util.Objects; +import org.apache.commons.lang3.StringUtils; + import io.mangoo.enums.Http; import io.mangoo.enums.Required; import io.mangoo.interfaces.MangooRoute; @@ -13,74 +15,172 @@ * */ public class RequestRoute implements MangooRoute { + private Class controllerClass; private Http[] methods; + private Http method; + private Response response; private String url; - private Class controllerClass; private String controllerMethod; + private String username; + private String password; private int limit; - private Http method; private boolean blocking; - private Response response; + private boolean authentication; + private boolean authorization; 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; } + /** + * Sets the URL for this route + * + * @param url The URL for this route + * + * @return RequestRoute instance + */ public RequestRoute to(String url) { Objects.requireNonNull(url, Required.URL.toString()); + + if ('/' != url.charAt(0)) { + url = "/" + url; + } + this.url = url; return this; } + /** + * Sets a defined response to the request route that will be returned directly + * on this request + * + * @param response The response to return + * + * @return RequestRoute instance + */ public RequestRoute respondeWith(Response response) { Objects.requireNonNull(response, Required.RESPONSE.toString()); - this.response = response; return this; } + /** + * Sets the controller method to response with on the request + * + * @param method The controller method + * @return RequestRoute instance + */ public RequestRoute respondeWith(String method) { Objects.requireNonNull(method, Required.CONTROLLER_METHOD.toString()); - this.controllerMethod = method; - return this; } - public RequestRoute maxRequestsPerSecond(int requestsPerSecond) { + /** + * Sets a request limit to the request + * + * @param requestsPerSecond Number of request per second + * @return RequestRoute instance + */ + public RequestRoute withRequestLimit(int requestsPerSecond) { this.limit = requestsPerSecond; - - return this; - } - - public RequestRoute canBlock() { - this.blocking = true; - return this; } + /** + * Sets the controller class of this request + * + * @param clazz The controller class + */ public void withControllerClass(Class clazz) { Objects.requireNonNull(clazz, Required.CONTROLLER_CLASS.toString()); - this.controllerClass = clazz; } + /** + * Sets the controller method of this request + * @param method The controller method + */ public void withHttpMethod(Http method) { Objects.requireNonNull(method, Required.METHOD.toString()); - this.method = method; } + /** + * Sets Basic HTTP authentication to all method on the defined controller class + * + * @param username The username for basic authentication in cleartext + * @param password The password for basic authentication in cleartext + * + * @return RequestRoute instance + */ + public RequestRoute withBasicAuthentication(String username, String password) { + Objects.requireNonNull(username, Required.USERNAME.toString()); + Objects.requireNonNull(password, Required.PASSWORD.toString()); + + this.username = username; + this.password = password; + + return this; + } + + /** + * Sets authentication to true, default is false + * + * @return RequestRoute instance + */ + public RequestRoute requireAuthentication() { + this.authentication = true; + return this; + } + + public RequestRoute requiresAuthrozation(String role) { + return this; + } + + /** + * Configures this request as long running request that does not block other request + * + * @return RequestRoute instance + */ + public RequestRoute canBlock() { + this.blocking = true; + return this; + } + + public boolean hasAuthentication() { + return this.authentication; + } + + public boolean hasAuthorization() { + return authorization; + } + + public boolean hasBasicAuthentication() { + return StringUtils.isNotBlank(this.username) && StringUtils.isNotBlank(this.password); + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public RequestRoute requireAuthorization(String role) { + //TODO needs implementation + return this; + } + public boolean hasMultipleMethods() { return methods != null && methods.length > 0; } @@ -89,6 +189,7 @@ public Http[] getMethods() { return methods; } + @Override public String getUrl() { return url; } 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 index 8106df1ec0..72fc00b76d 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/routes/ServerSentEventRoute.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/ServerSentEventRoute.java @@ -6,16 +6,47 @@ import io.mangoo.interfaces.MangooRoute; import io.mangoo.routing.Router; +/** + * + * @author svenkubiak + * + */ public class ServerSentEventRoute implements MangooRoute { private String url; - - public String getUrl() { - return this.url; - } + private boolean authentication; - public void to(String url) { + /** + * Sets the URL for this route + * + * @param url The URL for this route + * @return ServerSentEventRoute instance + */ + public ServerSentEventRoute to(String url) { Objects.requireNonNull(url, Required.URL.toString()); + + if ('/' != url.charAt(0)) { + url = "/" + url; + } this.url = url; + Router.addRoute(this); + + return this; + } + + /** + * Sets authentication to true, default is false + */ + public void requireAuthentication() { + this.authentication = true; + } + + @Override + public String getUrl() { + return this.url; + } + + public boolean hasAuthentication() { + return this.authentication; } } \ 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 index 71664141b7..07003d5cf0 100644 --- a/mangooio-core/src/main/java/io/mangoo/routing/routes/WebSocketRoute.java +++ b/mangooio-core/src/main/java/io/mangoo/routing/routes/WebSocketRoute.java @@ -6,20 +6,29 @@ import io.mangoo.interfaces.MangooRoute; import io.mangoo.routing.Router; +/** + * + * @author svenkubiak + * + */ public class WebSocketRoute implements MangooRoute { private String url; - private Class controller; + private Class controllerClass; + private boolean authentication; - public String getUrl() { - return url; - } - - public Class getControllerClass() { - return controller; - } - + /** + * Sets the URL for this route + * + * @param url The URL for this WebSocket route + * @return WebSocketRoute instance + */ public WebSocketRoute to(String url) { Objects.requireNonNull(url, Required.URL.toString()); + + if ('/' != url.charAt(0)) { + url = "/" + url; + } + this.url = url; Router.addRoute(this); @@ -27,10 +36,36 @@ public WebSocketRoute to(String url) { return this; } + /** + * Sets the controller class for this WebSocket route + * + * @param clazz The controller class + * @return WebSocketRoute instance + */ public WebSocketRoute onController(Class clazz) { Objects.requireNonNull(clazz, Required.URL.toString()); - this.controller = clazz; + this.controllerClass = clazz; return this; } + + /** + * Sets authentication to true, default is false + */ + public void requireAuthentication() { + this.authentication = true; + } + + @Override + public String getUrl() { + return this.url; + } + + public boolean hasAuthentication() { + return this.authentication; + } + + public Class getControllerClass() { + return this.controllerClass; + } } \ 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 85fa842a95..59f87481af 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 @@ -29,6 +29,7 @@ public TemplateModel exec(List arguments) throws TemplateModelException { if (arguments.size() >= MIN_ARGUMENTS) { String controller = ((SimpleScalar) arguments.get(0)).getAsString(); RequestRoute requestRoute = Router.getReverseRoute(controller); + if (requestRoute != null) { url = requestRoute.getUrl(); Matcher matcher = PARAMETER_PATTERN.matcher(url); diff --git a/mangooio-core/src/main/resources/templates/admin/routes.ftl b/mangooio-core/src/main/resources/templates/admin/routes.ftl index 5ba7abdf5a..5589b13c21 100644 --- a/mangooio-core/src/main/resources/templates/admin/routes.ftl +++ b/mangooio-core/src/main/resources/templates/admin/routes.ftl @@ -7,7 +7,7 @@

Routes

- +
diff --git a/mangooio-integration-test/src/main/java/app/Bootstrap.java b/mangooio-integration-test/src/main/java/app/Bootstrap.java index 36b1bf1063..2152054855 100644 --- a/mangooio-integration-test/src/main/java/app/Bootstrap.java +++ b/mangooio-integration-test/src/main/java/app/Bootstrap.java @@ -16,20 +16,19 @@ 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( + Bind.controller(SessionController.class).withRoutes( On.get().to("/session").respondeWith("session"), On.get().to("/session/valued/{uuid}").respondeWith("valued") ); // AuthenticityController - Bind.controller(AuthenticityController.class).with( + Bind.controller(AuthenticityController.class).withRoutes( On.get().to("/authenticityform").respondeWith("form"), On.get().to("/authenticitytoken").respondeWith("token"), On.get().to("/valid").respondeWith("valid"), @@ -37,14 +36,14 @@ public void initializeRoutes() { ); // FilterController - Bind.controller(FilterController.class).with( + Bind.controller(FilterController.class).withRoutes( On.get().to("/filter").respondeWith("filter"), On.get().to("/headerfilter").respondeWith("headerfilter"), On.get().to("/filters").respondeWith("filters") ); // I18nController - Bind.controller(I18nController.class).with( + Bind.controller(I18nController.class).withRoutes( On.get().to("/translation").respondeWith("translation"), On.get().to("/messages").respondeWith("messages"), On.get().to("/special").respondeWith("special"), @@ -53,13 +52,13 @@ public void initializeRoutes() { ); // FlashController - Bind.controller(FlashController.class).with( + Bind.controller(FlashController.class).withRoutes( On.get().to("/flash").respondeWith("flash"), On.get().to("/flashed").respondeWith("flashed") ); // JsonController - Bind.controller(JsonController.class).with( + Bind.controller(JsonController.class).withRoutes( On.get().to("/render").respondeWith("render"), On.post().to("/parse").respondeWith("parse"), On.put().to("/parse").respondeWith("parse"), @@ -69,7 +68,7 @@ public void initializeRoutes() { ); // FormController - Bind.controller(FormController.class).with( + Bind.controller(FormController.class).withRoutes( On.post().to("/form").respondeWith("form"), On.post().to("/multivalued").respondeWith("multivalued"), On.post().to("/submit").respondeWith("submit"), @@ -80,7 +79,8 @@ public void initializeRoutes() { ); // AuthenticationController - Bind.controller(AuthenticationController.class).with( + Bind.controller(AuthenticationController.class).requireAuthentication() + .withRoutes( On.post().to("/dologin").respondeWith("doLogin"), On.post().to("/login").respondeWith("login"), On.get().to("/login").respondeWith("login"), @@ -91,7 +91,8 @@ public void initializeRoutes() { ); // ParameterController - Bind.controller(ParameterController.class).with( + Bind.controller(ParameterController.class).requireAuthorization("role") + .withRoutes( On.get().to("/string/{foo}").respondeWith("stringParam"), On.get().to("/optional/{foo}").respondeWith("optionalParam"), On.get().to("/string").respondeWith("stringParam"), @@ -110,11 +111,11 @@ public void initializeRoutes() { ); // ApplicationController - Bind.controller(ApplicationController.class).with( + Bind.controller(ApplicationController.class).withRoutes( On.get().to("/").respondeWith("index").canBlock(), On.get().to("/route").respondeWith("route"), On.post().to("/").respondeWith("index"), - On.put().to("/").respondeWith("index"), + On.put().to("/put").respondeWith("put"), On.patch().to("/").respondeWith("index"), On.head().to("/").respondeWith("index"), On.delete().to("/").respondeWith("index"), @@ -124,7 +125,7 @@ public void initializeRoutes() { 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("/limit").respondeWith("limit").withRequestLimit(10), On.get().to("/text").respondeWith("text"), On.get().to("/forbidden").respondeWith("forbidden"), On.get().to("/badrequest").respondeWith("badrequest"), @@ -138,36 +139,28 @@ public void initializeRoutes() { 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.put().to("/jsonboonput").respondeWith("jsonBoonPut"), On.get().to("/freemarker").respondeWith("freemarker") ); // SubController - Bind.controller(SubController.class).with( + Bind.controller(SubController.class).withRoutes( On.get().to("/subcontroller").respondeWith("check") ); // BasicAuthenticationController - Bind.controller(BasicAuthenticationController.class).with( - On.get().to("/basicauth").respondeWith("basicauth") + Bind.controller(BasicAuthenticationController.class).withRoutes( + On.get().to("/basicauth").respondeWith("basicauth").withBasicAuthentication("foo", "bar") ); Bind.serverSentEvent().to("/sse"); - Bind.serverSentEvent().to("/sseauth"); + Bind.serverSentEvent().to("/sseauth").requireAuthentication(); Bind.webSocket().onController(WebSocketController.class).to("/websocket"); - Bind.webSocket().onController(WebSocketController.class).to("/websocketauth"); + Bind.webSocket().onController(WebSocketController.class).to("/websocketauth").requireAuthentication(); 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 diff --git a/mangooio-integration-test/src/test/java/io/mangoo/controllers/AdminControllerTest.java b/mangooio-integration-test/src/test/java/io/mangoo/controllers/AdminControllerTest.java index e2f14cbbac..abca6b7c17 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/controllers/AdminControllerTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/controllers/AdminControllerTest.java @@ -24,7 +24,6 @@ @ExtendWith({TestExtension.class}) public class AdminControllerTest { private static final String TEXT_HTML = "text/html; charset=UTF-8"; - private static final String TEXT_PLAIN = "text/plain; charset=UTF-8"; private static final String LOGGER = "logger"; private static final String SCHEDULER = "scheduler"; private static final String METRICS = "metrics"; @@ -33,11 +32,22 @@ public class AdminControllerTest { private static final String ADMIN = "admin"; private static final String CONTROL_PANEL = "Dashboard"; + @Test + public void testDashboardUnAuthorized() { + //given + WebResponse response = WebRequest.get("/@admin").execute(); + + //then + assertThat(response, not(nullValue())); + assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); + assertThat(response.getContent(), not(containsString(CONTROL_PANEL))); + } + @Test public void testDashboardAuthorized() { //given WebResponse response = WebRequest.get("/@admin") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -55,7 +65,6 @@ public void testLoggerUnAuthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo(TEXT_PLAIN)); assertThat(response.getContent(), not(containsString(LOGGER))); } @@ -63,7 +72,7 @@ public void testLoggerUnAuthorized() { public void testLoggerAuthorized() { //given WebResponse response = WebRequest.get("/@admin/logger") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -72,24 +81,12 @@ public void testLoggerAuthorized() { assertThat(response.getContentType(), equalTo(TEXT_HTML)); assertThat(response.getContent(), containsString(LOGGER)); } - - @Test - public void testDashboardUnAuthorized() { - //given - WebResponse response = WebRequest.get("/@admin").execute(); - - //then - assertThat(response, not(nullValue())); - assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo(TEXT_PLAIN)); - assertThat(response.getContent(), not(containsString(CONTROL_PANEL))); - } @Test public void testRoutedAuthorized() { //given WebResponse response = WebRequest.get("/@admin/routes") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -107,7 +104,6 @@ public void testRoutedUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo(TEXT_PLAIN)); assertThat(response.getContent(), not(containsString(ROUTES))); } @@ -115,7 +111,7 @@ public void testRoutedUnauthorized() { public void testMetricsAuthorized() { //given WebResponse response = WebRequest.get("/@admin/metrics") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -129,7 +125,7 @@ public void testMetricsAuthorized() { public void testResetMetricsAuthorized() { //given WebResponse response = WebRequest.get("/@admin/metrics/reset") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -162,7 +158,6 @@ public void testResetMetricsUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo(TEXT_PLAIN)); assertThat(response.getContent(), not(containsString(ROUTES))); } @@ -174,7 +169,6 @@ public void testMetricsUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo(TEXT_PLAIN)); assertThat(response.getContent(), not(containsString(METRICS))); } @@ -182,7 +176,7 @@ public void testMetricsUnauthorized() { public void testSchedulerAuthorized() { //given WebResponse response = WebRequest.get("/@admin/scheduler") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -200,7 +194,6 @@ public void testSchedulerUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo(TEXT_PLAIN)); assertThat(response.getContent(), not(containsString(SCHEDULER))); } @@ -208,7 +201,7 @@ public void testSchedulerUnauthorized() { public void testToolsAuthorized() { //given WebResponse response = WebRequest.get("/@admin/tools") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -226,7 +219,6 @@ public void testToolsUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo(TEXT_PLAIN)); assertThat(response.getContent(), not(containsString(TOOLS))); } @@ -234,7 +226,7 @@ public void testToolsUnauthorized() { public void testToolsAjaxAuthorized() { //given WebResponse response = WebRequest.post("/@admin/tools/ajax") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -251,7 +243,6 @@ public void testToolsAjaxUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo("text/plain; charset=UTF-8")); assertThat(response.getContent(), not(containsString(SCHEDULER))); } @@ -259,7 +250,7 @@ public void testToolsAjaxUnauthorized() { public void testLoggerAjaxAuthorized() { //given WebResponse response = WebRequest.post("/@admin/logger/ajax") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -276,7 +267,6 @@ public void testLoggerAjaxUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo("text/plain; charset=UTF-8")); assertThat(response.getContent(), not(containsString(SCHEDULER))); } @@ -284,7 +274,7 @@ public void testLoggerAjaxUnauthorized() { public void testHealthAuthorized() { //given WebResponse response = WebRequest.get("/@admin/health") - .withBasicauthentication(ADMIN, ADMIN) + .withBasicAuthentication(ADMIN, ADMIN) .execute(); //then @@ -302,7 +292,6 @@ public void testHealthUnauthorized() { //then assertThat(response, not(nullValue())); assertThat(response.getStatusCode(), equalTo(StatusCodes.UNAUTHORIZED)); - assertThat(response.getContentType(), equalTo("text/plain; charset=UTF-8")); assertThat(response.getContent(), not(containsString("uptime"))); } } \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/controllers/ApplicationControllerTest.java b/mangooio-integration-test/src/test/java/io/mangoo/controllers/ApplicationControllerTest.java index 927752c149..29d35814c7 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/controllers/ApplicationControllerTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/controllers/ApplicationControllerTest.java @@ -73,9 +73,9 @@ public void testRoute() { //then assertThat(response, not(nullValue())); - assertThat(response.getContentType(), equalTo(TEXT_HTML)); assertThat(response.getStatusCode(), equalTo(StatusCodes.OK)); assertThat(response.getContent(), equalTo("/route")); + assertThat(response.getContentType(), equalTo(TEXT_HTML)); } @Test @@ -85,9 +85,9 @@ public void testReverse() { //then assertThat(response, not(nullValue())); - assertThat(response.getContentType(), equalTo(TEXT_HTML)); assertThat(response.getStatusCode(), equalTo(StatusCodes.OK)); assertThat(response.getContent(), equalTo("/string\n/int/23\n/multiple/11/42")); + assertThat(response.getContentType(), equalTo(TEXT_HTML)); } @Test diff --git a/mangooio-integration-test/src/test/java/io/mangoo/controllers/BasicAuthenticationControllerTest.java b/mangooio-integration-test/src/test/java/io/mangoo/controllers/BasicAuthenticationControllerTest.java index 92ee875c90..4a2c32925b 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/controllers/BasicAuthenticationControllerTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/controllers/BasicAuthenticationControllerTest.java @@ -29,11 +29,11 @@ public void testBasicAuthenticationFail() { @Test public void testBasicAuthenticationSuccess() { //given - final WebResponse response = WebRequest.get("/basicauth").withBasicauthentication("foo", "bar").execute(); + final WebResponse response = WebRequest.get("/basicauth").withBasicAuthentication("foo", "bar").execute(); //then assertThat(response, not(nullValue())); - assertThat(response.getContent(), equalTo("authenticated")); assertThat(response.getStatusCode(), equalTo(StatusCodes.OK)); + assertThat(response.getContent(), equalTo("authenticated")); } } \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/controllers/HttpMethodsTest.java b/mangooio-integration-test/src/test/java/io/mangoo/controllers/HttpMethodsTest.java index 609a5dc207..a2b7c1f277 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/controllers/HttpMethodsTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/controllers/HttpMethodsTest.java @@ -44,7 +44,7 @@ public void testPost() { @Test public void testPut() { //given - final WebResponse response = WebRequest.put("/").execute(); + final WebResponse response = WebRequest.put("/put").execute(); //then assertThat(response, not(nullValue())); diff --git a/mangooio-integration-test/src/test/java/io/mangoo/models/IdentityTest.java b/mangooio-integration-test/src/test/java/io/mangoo/models/IdentityTest.java index df20aef34f..56b9359c6f 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/models/IdentityTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/models/IdentityTest.java @@ -9,7 +9,6 @@ import org.junit.jupiter.api.extension.ExtendWith; import io.mangoo.TestExtension; -import io.mangoo.utils.CodecUtils; import io.undertow.security.idm.Account; import io.undertow.security.idm.PasswordCredential; @@ -25,7 +24,7 @@ public class IdentityTest { @Test public void testValidVerify() { //given - Identity identity = new Identity("foo", CodecUtils.hexJBcrypt("bar")); + Identity identity = new Identity("foo", "bar"); PasswordCredential credential = new PasswordCredential(password); //when @@ -39,7 +38,7 @@ public void testValidVerify() { @Test public void testNonValidVerify() { //given - Identity identity = new Identity("foo", CodecUtils.hexJBcrypt("abar")); + Identity identity = new Identity("foo", "abar"); PasswordCredential credential = new PasswordCredential(password); //when diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/AttachmentTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/AttachmentTest.java index 751cee2800..3c4683980c 100644 --- a/mangooio-integration-test/src/test/java/io/mangoo/routing/AttachmentTest.java +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/AttachmentTest.java @@ -41,11 +41,10 @@ public void testCreateAttachment() { attachment.withMethodAnnotations(new ArrayList()); attachment.withMethodParameterCount(42); attachment.withMethodParameters(new HashMap<>()); - attachment.withPassword("foobar"); + attachment.withBasicAuthentication("peter", "foobar"); attachment.withRequestFilter(true); attachment.withRequestParameter(new HashMap<>()); attachment.withTemplateEngine(Application.getInstance(TemplateEngine.class)); - attachment.withUsername("peter"); //then assertThat(attachment.getClassAnnotations(), instanceOf(ArrayList.class)); 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 43b84c46f6..6b30562856 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,7 +9,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import controllers.ApplicationController; import io.mangoo.TestExtension; +import io.mangoo.core.Application; +import io.mangoo.interfaces.MangooBootstrap; /** * @@ -33,8 +36,13 @@ public void testAddRoute() { public void testMaxRoutes() { Assertions.assertThrows(IllegalArgumentException.class, () -> { for (int i=0; i <= 100000; i++) { - On.get().to("/foo").respondeWith("index"); + Bind.controller(ApplicationController.class).withRoutes( + On.get().to("/foo").respondeWith("index") + ); } }); + + Router.reset(); + Application.getInstance(MangooBootstrap.class).initializeRoutes(); } } \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/ControllerRouteTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/ControllerRouteTest.java new file mode 100644 index 0000000000..d4bfbd9530 --- /dev/null +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/ControllerRouteTest.java @@ -0,0 +1,85 @@ +package io.mangoo.routing.routes; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import controllers.ApplicationController; +import io.mangoo.TestExtension; +import io.mangoo.routing.On; +import io.mangoo.routing.Router; + +@ExtendWith({TestExtension.class}) +public class ControllerRouteTest { + + @Test + public void testCreation() { + //given + Class clazz = ApplicationController.class; + + //when + ControllerRoute route = new ControllerRoute(clazz); + + //then + assertThat(route.getControllerClass(), equalTo(clazz)); + } + + @Test + public void testWithMethods() { + //given + String route1 = UUID.randomUUID().toString(); + String route2 = UUID.randomUUID().toString(); + + //when + ControllerRoute route = new ControllerRoute(ApplicationController.class); + route.withRoutes( + On.get().to("/route1").respondeWith(route1), + On.post().to("/route2").respondeWith(route2) + ); + + //then + Set requestRoutes = Router.getRoutes().stream() + .filter(RequestRoute.class::isInstance) + .map(RequestRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = requestRoutes.stream() + .filter(r -> r.getControllerMethod().equals(route1) || r.getControllerMethod().equals(route2)) + .collect(Collectors.toSet()); + + assertThat(collectedRoutes.size(), equalTo(2)); + } + + @Test + public void testWithBasicAuthentication() { + //given + String route1 = UUID.randomUUID().toString(); + + //when + ControllerRoute route = new ControllerRoute(ApplicationController.class); + route.withBasicAuthentication("foo", "bar").withRoutes( + On.get().to("/route1").respondeWith(route1) + ); + + //then + Set requestRoutes = Router.getRoutes().stream() + .filter(RequestRoute.class::isInstance) + .map(RequestRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = requestRoutes.stream() + .filter(r -> r.getControllerMethod().equals(route1)) + .collect(Collectors.toSet()); + + RequestRoute requestRoute = collectedRoutes.iterator().next(); + + assertThat(requestRoute.getUsername(), equalTo("foo")); + assertThat(requestRoute.getPassword(), equalTo("bar")); + } +} \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/FileRouteTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/FileRouteTest.java new file mode 100644 index 0000000000..88175a348e --- /dev/null +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/FileRouteTest.java @@ -0,0 +1,58 @@ +package io.mangoo.routing.routes; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import io.mangoo.TestExtension; +import io.mangoo.routing.Router; + +@ExtendWith({TestExtension.class}) +public class FileRouteTest { + + @Test + public void testTo() { + //given + FileRoute fileRoute = new FileRoute(); + + //when + fileRoute.to("foo"); + + //then + assertThat(fileRoute.getUrl(), equalTo("/foo")); + + //when + fileRoute.to("/bar"); + + //then + assertThat(fileRoute.getUrl(), equalTo("/bar")); + } + + @Test + public void testAddingRoute() { + //given + String url = "/" + UUID.randomUUID().toString(); + FileRoute fileRoute = new FileRoute(); + + //when + fileRoute.to(url); + + //then + Set fileRoutes = Router.getRoutes().stream() + .filter(FileRoute.class::isInstance) + .map(FileRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = fileRoutes.stream() + .filter(r -> r.getUrl().equals(url)) + .collect(Collectors.toSet()); + + assertThat(collectedRoutes.size(), equalTo(1)); + } +} diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/PathRouteTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/PathRouteTest.java new file mode 100644 index 0000000000..32bc00ff68 --- /dev/null +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/PathRouteTest.java @@ -0,0 +1,58 @@ +package io.mangoo.routing.routes; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import io.mangoo.TestExtension; +import io.mangoo.routing.Router; + +@ExtendWith({TestExtension.class}) +public class PathRouteTest { + + @Test + public void testTo() { + //given + PathRoute pathRoute = new PathRoute(); + + //when + pathRoute.to("foo"); + + //then + assertThat(pathRoute.getUrl(), equalTo("/foo/")); + + //when + pathRoute.to("/bar/"); + + //then + assertThat(pathRoute.getUrl(), equalTo("/bar/")); + } + + @Test + public void testAddingRoute() { + //given + String url = "/" + UUID.randomUUID().toString() + "/"; + PathRoute pathRoute = new PathRoute(); + + //when + pathRoute.to(url); + + //then + Set pathRoutes = Router.getRoutes().stream() + .filter(PathRoute.class::isInstance) + .map(PathRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = pathRoutes.stream() + .filter(r -> r.getUrl().equals(url)) + .collect(Collectors.toSet()); + + assertThat(collectedRoutes.size(), equalTo(1)); + } +} \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/RequestRouteTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/RequestRouteTest.java new file mode 100644 index 0000000000..7165138686 --- /dev/null +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/RequestRouteTest.java @@ -0,0 +1,33 @@ +package io.mangoo.routing.routes; + +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 io.mangoo.TestExtension; +import io.mangoo.enums.Http; + +@ExtendWith({TestExtension.class}) +public class RequestRouteTest { + + @Test + public void testTo() { + //given + RequestRoute requestRoute = new RequestRoute(Http.GET); + + //when + requestRoute.to("foo"); + + //then + assertThat(requestRoute.getUrl(), equalTo("/foo")); + assertThat(requestRoute.getMethod(), equalTo(Http.GET)); + + //when + requestRoute.to("/bar"); + + //then + assertThat(requestRoute.getUrl(), equalTo("/bar")); + } +} \ No newline at end of file diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/ServerSentEventRouteTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/ServerSentEventRouteTest.java new file mode 100644 index 0000000000..624ce81a67 --- /dev/null +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/ServerSentEventRouteTest.java @@ -0,0 +1,81 @@ +package io.mangoo.routing.routes; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import io.mangoo.TestExtension; +import io.mangoo.routing.Router; + +@ExtendWith({TestExtension.class}) +public class ServerSentEventRouteTest { + + @Test + public void testTo() { + //given + ServerSentEventRoute serverSentEventRoute = new ServerSentEventRoute(); + + //when + serverSentEventRoute.to("foo"); + + //then + assertThat(serverSentEventRoute.getUrl(), equalTo("/foo")); + + //when + serverSentEventRoute.to("/bar"); + + //then + assertThat(serverSentEventRoute.getUrl(), equalTo("/bar")); + } + + @Test + public void testAddingRoute() { + //given + String url = "/" + UUID.randomUUID().toString(); + ServerSentEventRoute serverSentEventRoute = new ServerSentEventRoute(); + + //when + serverSentEventRoute.to(url); + + //then + Set serverSentEventRoutes = Router.getRoutes().stream() + .filter(ServerSentEventRoute.class::isInstance) + .map(ServerSentEventRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = serverSentEventRoutes.stream() + .filter(r -> r.getUrl().equals(url)) + .collect(Collectors.toSet()); + + assertThat(collectedRoutes.size(), equalTo(1)); + } + + @Test + public void testWithAuthentication() { + //given + String url = "/" + UUID.randomUUID().toString(); + ServerSentEventRoute serverSentEventRoute = new ServerSentEventRoute(); + + //when + serverSentEventRoute.to(url).requireAuthentication(); + + //then + Set serverSentEventRoutes = Router.getRoutes().stream() + .filter(ServerSentEventRoute.class::isInstance) + .map(ServerSentEventRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = serverSentEventRoutes.stream() + .filter(r -> r.getUrl().equals(url)) + .collect(Collectors.toSet()); + + assertThat(collectedRoutes.size(), equalTo(1)); + assertThat(collectedRoutes.iterator().next().hasAuthentication(), equalTo(true)); + } +} diff --git a/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/WebSocketRouteTest.java b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/WebSocketRouteTest.java new file mode 100644 index 0000000000..1edeab3e21 --- /dev/null +++ b/mangooio-integration-test/src/test/java/io/mangoo/routing/routes/WebSocketRouteTest.java @@ -0,0 +1,94 @@ +package io.mangoo.routing.routes; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import controllers.WebSocketController; +import io.mangoo.TestExtension; +import io.mangoo.routing.Router; + +@ExtendWith({TestExtension.class}) +public class WebSocketRouteTest { + + @Test + public void testTo() { + //given + WebSocketRoute webSocketRoute = new WebSocketRoute(); + + //when + webSocketRoute.to("foo"); + + //then + assertThat(webSocketRoute.getUrl(), equalTo("/foo")); + + //when + webSocketRoute.to("/bar"); + + //then + assertThat(webSocketRoute.getUrl(), equalTo("/bar")); + } + + @Test + public void testWithController() { + //given + WebSocketRoute webSocketRoute = new WebSocketRoute(); + + //when + webSocketRoute.onController(WebSocketController.class); + + //then + assertThat(webSocketRoute.getControllerClass(), equalTo(WebSocketController.class)); + } + + @Test + public void testAddingRoute() { + //given + String url = "/" + UUID.randomUUID().toString(); + WebSocketRoute webSocketRoute = new WebSocketRoute(); + + //when + webSocketRoute.to(url); + + //then + Set webSocketRoutes = Router.getRoutes().stream() + .filter(WebSocketRoute.class::isInstance) + .map(WebSocketRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = webSocketRoutes.stream() + .filter(r -> r.getUrl().equals(url)) + .collect(Collectors.toSet()); + + assertThat(collectedRoutes.size(), equalTo(1)); + } + + @Test + public void testWithAuthentication() { + //given + String url = "/" + UUID.randomUUID().toString(); + WebSocketRoute webSocketRoute = new WebSocketRoute(); + + //when + webSocketRoute.to(url).requireAuthentication(); + + //then + Set webSocketRoutes = Router.getRoutes().stream() + .filter(WebSocketRoute.class::isInstance) + .map(WebSocketRoute.class::cast) + .collect(Collectors.toSet()); + + Set collectedRoutes = webSocketRoutes.stream() + .filter(r -> r.getUrl().equals(url)) + .collect(Collectors.toSet()); + + assertThat(collectedRoutes.size(), equalTo(1)); + assertThat(collectedRoutes.iterator().next().hasAuthentication(), equalTo(true)); + } +} diff --git a/mangooio-test/src/main/java/io/mangoo/test/TestRunner.java b/mangooio-test/src/main/java/io/mangoo/test/TestRunner.java index e9e3bce483..85f0cbe362 100644 --- a/mangooio-test/src/main/java/io/mangoo/test/TestRunner.java +++ b/mangooio-test/src/main/java/io/mangoo/test/TestRunner.java @@ -23,6 +23,7 @@ public void beforeAll(ExtensionContext context) throws Exception { if (!started) { init(); Application.start(Mode.TEST); + started = true; } } diff --git a/mangooio-test/src/main/java/io/mangoo/test/utils/WebResponse.java b/mangooio-test/src/main/java/io/mangoo/test/utils/WebResponse.java index 1fb90faa69..24146275cc 100644 --- a/mangooio-test/src/main/java/io/mangoo/test/utils/WebResponse.java +++ b/mangooio-test/src/main/java/io/mangoo/test/utils/WebResponse.java @@ -228,7 +228,7 @@ public WebResponse withCookie(Cookie cookie) { * @param password The password * @return Response */ - public WebResponse withBasicauthentication(String username, String password) { + public WebResponse withBasicAuthentication(String username, String password) { Objects.requireNonNull(username, "username can not be null"); Objects.requireNonNull(password, "password can not be null"); diff --git a/pom.xml b/pom.xml index 4f79ab0235..88141bf8a7 100644 --- a/pom.xml +++ b/pom.xml @@ -356,7 +356,7 @@ org.ehcache ehcache-clustered - 3.6.0 + 3.6.1 org.slf4j @@ -367,7 +367,7 @@ org.cactoos cactoos - 0.36 + 0.37 org.llorllale @@ -392,7 +392,7 @@ io.github.classgraph classgraph - 4.1.7 + 4.2.2 org.glassfish.jersey.media @@ -489,7 +489,7 @@ org.apache.commons commons-lang3 - 3.8 + 3.8.1 de.svenkubiak