REST Controllers, improvements
authorGustavo Martin Morcuende <gu.martinm@gmail.com>
Tue, 4 Oct 2016 11:59:44 +0000 (13:59 +0200)
committerGustavo Martin Morcuende <gu.martinm@gmail.com>
Tue, 4 Oct 2016 11:59:44 +0000 (13:59 +0200)
src/main/java/com/prueba/authorization/services/impl/AuthorizationServicesImpl.java
src/main/java/com/prueba/core/context/security/handle/ApiHandler.java
src/main/java/com/prueba/core/context/security/handle/LoginHandler.java
src/main/java/com/prueba/core/context/security/handle/PagesHandler.java
src/main/java/com/prueba/core/context/web/application/ApplicationWebContext.java
src/main/java/com/prueba/resources/controllers/ApiController.java [deleted file]
src/main/java/com/prueba/resources/controllers/LoginController.java [deleted file]
src/main/java/com/prueba/resources/controllers/PagesController.java [deleted file]
src/main/java/com/prueba/resources/rest/controllers/ApiController.java [new file with mode: 0644]
src/main/java/com/prueba/resources/rest/controllers/LoginController.java [new file with mode: 0644]
src/main/java/com/prueba/resources/rest/controllers/PagesController.java [new file with mode: 0644]

index 100a660..ac3f667 100644 (file)
@@ -16,7 +16,7 @@ public class AuthorizationServicesImpl {
        private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
 
        public boolean isAuthorized(String httpMethod, String uri, String userName) {
-               final String userNameParam = this.getUserNameParam(uri);
+               final String userNameParam = this.getSafeUserNameParam(uri);
                
                final ApplicationResourceDao dao = new ApplicationResourceDao();
                
@@ -34,7 +34,7 @@ public class AuthorizationServicesImpl {
                
        }
        
-       protected String getUserNameParam(String uri) {
+       protected String getSafeUserNameParam(String uri) {
                final AntPathMatcher pathMatcher = new AntPathMatcher();
                
                String userNameParam = "";
index a5f864e..ba6f5b7 100644 (file)
@@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory;
 import com.prueba.authorization.services.impl.AuthorizationServicesImpl;
 import com.prueba.core.context.security.authenticator.persistence.AuthenticationInfo;
 import com.prueba.core.context.security.persistence.context.BasicAuthenticationContext;
-import com.prueba.resources.controllers.ApiController;
+import com.prueba.resources.rest.controllers.ApiController;
 import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpHandler;
 
index fa39baf..7df730f 100644 (file)
@@ -5,7 +5,7 @@ import java.io.IOException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.prueba.resources.controllers.LoginController;
+import com.prueba.resources.rest.controllers.LoginController;
 import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpHandler;
 
index 8789103..07b0a42 100644 (file)
@@ -10,7 +10,7 @@ import com.prueba.authorization.services.impl.AuthorizationServicesImpl;
 import com.prueba.core.context.security.persistence.SessionInfo;
 import com.prueba.core.context.security.persistence.Sessions;
 import com.prueba.core.context.security.persistence.context.SessionContext;
-import com.prueba.resources.controllers.PagesController;
+import com.prueba.resources.rest.controllers.PagesController;
 import com.sun.net.httpserver.Headers;
 import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpHandler;
index 923c139..d5c947d 100644 (file)
@@ -8,8 +8,8 @@ import com.prueba.core.context.integration.liquibase.impl.LiquibaseContext;
 import com.prueba.core.context.security.handle.ApiHandler;
 import com.prueba.core.context.security.handle.LoginHandler;
 import com.prueba.core.context.security.handle.SessionHandler;
+import com.prueba.resources.rest.controllers.LoginController;
 import com.prueba.core.context.security.handle.PagesHandler;
-import com.prueba.resources.controllers.LoginController;
 import com.sun.net.httpserver.HttpHandler;
 
 
diff --git a/src/main/java/com/prueba/resources/controllers/ApiController.java b/src/main/java/com/prueba/resources/controllers/ApiController.java
deleted file mode 100644 (file)
index f8a7a1a..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-package com.prueba.resources.controllers;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.charset.Charset;
-import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.prueba.api.persistence.Account;
-import com.prueba.authorization.services.impl.AuthorizationServicesImpl;
-import com.prueba.core.context.util.AntPathMatcher;
-import com.prueba.core.web.controller.Controller;
-import com.prueba.services.impl.ApiServiceImpl;
-import com.sun.net.httpserver.Headers;
-import com.sun.net.httpserver.HttpExchange;
-
-public class ApiController implements Controller {
-       private static final Logger LOGGER = LoggerFactory.getLogger(ApiController.class);
-       private static final String USER_NAME_PARAM = "username";
-       private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
-
-       @Override
-       public void handle(HttpExchange httpExchange) throws IOException {
-               final String requestMethod = httpExchange.getRequestMethod();
-               final ApiServiceImpl apiService = new ApiServiceImpl();
-               final ObjectMapper mapper = new ObjectMapper();
-       
-               final String uri = httpExchange.getRequestURI().toString();
-               final String userNameParam = this.getUserNameParam(uri);
-               
-               switch (requestMethod) {
-                       case "GET":
-                               int statusCode = 404;
-                               Account account = apiService.findAccountByCode(userNameParam);
-                               String bodyResponse = "";
-                               if (account != null) {
-                                       statusCode = 200;
-                                       bodyResponse = mapper.writeValueAsString(account);
-                               }
-                               
-                               this.setContentTypeHeader(httpExchange);
-                               
-                               httpExchange.sendResponseHeaders(statusCode, bodyResponse.length());
-                               
-                               try (final OutputStream os = httpExchange.getResponseBody()) {
-                                       os.write(bodyResponse.getBytes());
-                               }
-                               
-                               break;
-                       case "POST":
-                               final String bodyRequest = getBody(httpExchange);
-                               final Account accountRequest = mapper.readValue(bodyRequest, Account.class);
-                               
-                               apiService.createAccount(accountRequest);
-                               
-                               this.setContentTypeHeader(httpExchange);
-                               
-                               httpExchange.sendResponseHeaders(200, 0);
-                               
-                               try (final OutputStream os = httpExchange.getResponseBody()) {
-                                       os.write(bodyRequest.getBytes());
-                               }
-                               
-                               break;
-                       case "DELETE":                  
-                               apiService.deleteAccountByCode(userNameParam);
-                               
-                               httpExchange.sendResponseHeaders(204, 0);
-                               break;
-                       default:
-                               
-                               httpExchange.sendResponseHeaders(404, 0);
-                               break;
-               }
-       }
-
-       protected String getBody (HttpExchange httpExchange) throws IOException {
-       try(final InputStream inputStream = httpExchange.getRequestBody();
-               final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) {
-               
-               final int bufferSize = 1024;
-               final byte[] buffer = new byte[bufferSize];
-       
-               int len = 0;
-               while ((len = inputStream.read(buffer)) != -1) {
-                   byteBuffer.write(buffer, 0, len);
-               }
-               
-               return new String(byteBuffer.toByteArray(), Charset.forName("UTF-8"));
-       }
-    }
-       
-    protected void setContentTypeHeader(HttpExchange httpExchange) {
-       Headers headers = httpExchange.getResponseHeaders();
-       
-       headers.remove("Content-Type");
-       headers.set("Content-Type", "application/json");
-    }
-    
-       protected String getUserNameParam(String uri) {
-               final AntPathMatcher pathMatcher = new AntPathMatcher();
-               
-               String userNameParam = "";
-               try {
-                       final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
-                       userNameParam = variables.get(USER_NAME_PARAM);
-               } catch (IllegalStateException exception) {
-                       
-                       LOGGER.warn("AntPathMatcher: ", exception);
-               }
-               
-               return userNameParam;
-       }
-}
diff --git a/src/main/java/com/prueba/resources/controllers/LoginController.java b/src/main/java/com/prueba/resources/controllers/LoginController.java
deleted file mode 100644 (file)
index 5e78073..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.prueba.resources.controllers;
-
-import java.io.IOException;
-
-import com.prueba.core.web.controller.Controller;
-import com.prueba.services.impl.LoginServiceImpl;
-import com.sun.net.httpserver.HttpExchange;
-
-public class LoginController implements Controller {
-       
-       @Override
-       public void handle(HttpExchange httpExchange) throws IOException {
-               final LoginServiceImpl loginService = new LoginServiceImpl();
-               final String requestedURI = httpExchange.getRequestURI().toString();
-               
-               if (requestedURI.startsWith("/app/login/login.html")) {
-                       
-                       final String requestMethod = httpExchange.getRequestMethod();
-                       
-                       switch (requestMethod) {
-                               case "GET":
-                                       loginService.processLoginGet(httpExchange);
-                                       break;
-                               case "POST":
-                                       loginService.processLoginPost(httpExchange);
-                                       break;
-                               default:
-                                       httpExchange.sendResponseHeaders(404, 0);
-                                       break;
-                       }
-                       
-               } else if (requestedURI.startsWith("/app/login/logout.html")) {
-                       loginService.processLogoutGet(httpExchange);
-               } else {
-                       httpExchange.sendResponseHeaders(404, 0);
-               }
-       
-       }
-       
-
-
-}
diff --git a/src/main/java/com/prueba/resources/controllers/PagesController.java b/src/main/java/com/prueba/resources/controllers/PagesController.java
deleted file mode 100644 (file)
index 4fc7baa..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-package com.prueba.resources.controllers;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-import com.prueba.core.context.security.persistence.SessionInfo;
-import com.prueba.core.context.security.persistence.context.SessionContext;
-import com.prueba.core.web.controller.Controller;
-import com.prueba.view.login.PageImpl;
-import com.sun.net.httpserver.HttpExchange;
-
-public class PagesController implements Controller {
-
-       @Override
-       public void handle(HttpExchange httpExchange) throws IOException {
-               final String requestMethod = httpExchange.getRequestMethod();
-               
-               switch (requestMethod) {
-                       case "GET":
-                               this.processPages(httpExchange);
-                               break;
-                       default:
-                               httpExchange.sendResponseHeaders(404, 0);
-                               break;
-               }
-               
-       }
-
-       protected  void processPages(HttpExchange httpExchange) throws IOException {
-               final String requestedURI = httpExchange.getRequestURI().toString();
-               final PageImpl pageImpl = new PageImpl();
-               
-               int responseStatus = 200;
-               String html = "";
-               switch (requestedURI) {
-                       case "/app/pages/page_1.html":
-                               html = pageImpl.doPage(1, getSafeUserName());
-                               break;
-                       case "/app/pages/page_2.html":
-                               html = pageImpl.doPage(2, getSafeUserName());
-                               break;
-                       case "/app/pages/page_3.html":
-                               html = pageImpl.doPage(3, getSafeUserName());
-                               break;
-                       default:
-                               responseStatus = 404;
-                               break;
-               }
-               
-               httpExchange.sendResponseHeaders(responseStatus, html.length());
-               try (final OutputStream os = httpExchange.getResponseBody()) {
-                       os.write(html.getBytes());
-               }
-       }
-       
-       protected String getSafeUserName() {
-               SessionInfo sessionInfo = SessionContext.getSession();
-               String userName = "";
-               
-               if (sessionInfo != null) {
-                       userName = sessionInfo.getUsername();
-               }
-               
-               return userName;
-       }
-       
-}
diff --git a/src/main/java/com/prueba/resources/rest/controllers/ApiController.java b/src/main/java/com/prueba/resources/rest/controllers/ApiController.java
new file mode 100644 (file)
index 0000000..cfa7da6
--- /dev/null
@@ -0,0 +1,148 @@
+package com.prueba.resources.rest.controllers;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.prueba.api.persistence.Account;
+import com.prueba.core.context.util.AntPathMatcher;
+import com.prueba.core.web.controller.Controller;
+import com.prueba.services.impl.ApiServiceImpl;
+import com.sun.net.httpserver.Headers;
+import com.sun.net.httpserver.HttpExchange;
+
+public class ApiController implements Controller {
+       private static final String CONTENT_TYPE_JSON = "application/json";
+       private static final String CONTENT_TYPE_HEADER = "Content-Type";
+       private static final Logger LOGGER = LoggerFactory.getLogger(ApiController.class);
+       private static final String USER_NAME_PARAM = "username";
+       private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
+
+       // Both are thread safe :)
+       private final ApiServiceImpl apiService = new ApiServiceImpl();
+       private final ObjectMapper mapper = new ObjectMapper();
+       
+       @Override
+       public void handle(HttpExchange httpExchange) throws IOException {
+               final String requestMethod = httpExchange.getRequestMethod();
+               
+               switch (requestMethod) {
+                       case "GET":
+                               this.processGet(httpExchange);
+                               
+                               break;
+                       case "POST":
+                               
+                               if (this.isJSONContentType(httpExchange)) {
+                                       this.processPost(httpExchange);
+                               } else {
+                                       httpExchange.sendResponseHeaders(415, 0);
+                               }
+                               
+                               break;
+                       case "DELETE":                  
+                               this.processDelete(httpExchange);
+                               
+                               break;
+                       default:
+                               // Not found
+                               httpExchange.sendResponseHeaders(404, 0);
+                               break;
+               }
+       }
+
+       protected String getBody (HttpExchange httpExchange) throws IOException {
+       try(final InputStream inputStream = httpExchange.getRequestBody();
+               final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) {
+               
+               final int bufferSize = 1024;
+               final byte[] buffer = new byte[bufferSize];
+       
+               int len = 0;
+               while ((len = inputStream.read(buffer)) != -1) {
+                   byteBuffer.write(buffer, 0, len);
+               }
+               
+               return new String(byteBuffer.toByteArray(), Charset.forName("UTF-8"));
+       }
+    }
+       
+       protected void processGet(HttpExchange httpExchange) throws IOException {
+               int statusCode = 404;
+               final String userNameParam = this.getSafeUserNameParam(httpExchange);
+               
+               Account account = apiService.findAccountByCode(userNameParam);
+               String bodyResponse = "";
+               if (account != null) {
+                       statusCode = 200;
+                       bodyResponse = mapper.writeValueAsString(account);
+               }
+               
+               this.setJSONContentType(httpExchange);
+               httpExchange.sendResponseHeaders(statusCode, bodyResponse.length());
+               
+               try (final OutputStream os = httpExchange.getResponseBody()) {
+                       os.write(bodyResponse.getBytes());
+               }
+       }
+       
+       protected void processPost(HttpExchange httpExchange) throws IOException {
+               final String bodyRequest = getBody(httpExchange);
+               final Account accountRequest = mapper.readValue(bodyRequest, Account.class);
+               
+               apiService.createAccount(accountRequest);
+               
+               this.setJSONContentType(httpExchange);
+               
+               httpExchange.sendResponseHeaders(200, 0);
+               
+               try (final OutputStream os = httpExchange.getResponseBody()) {
+                       os.write(bodyRequest.getBytes());
+               }
+       }
+       
+       protected void processDelete(HttpExchange httpExchange) throws IOException {
+               final String userNameParam = getSafeUserNameParam(httpExchange);
+               
+               apiService.deleteAccountByCode(userNameParam);
+               
+               httpExchange.sendResponseHeaders(204, 0);
+       }
+       
+    protected void setJSONContentType(HttpExchange httpExchange) {
+       final Headers headers = httpExchange.getResponseHeaders();
+       
+       headers.remove(CONTENT_TYPE_HEADER);
+       headers.set(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON);
+    }
+    
+       protected boolean isJSONContentType(HttpExchange httpExchange) {
+               final Headers headers = httpExchange.getRequestHeaders();
+               final String contentType = headers.getFirst(CONTENT_TYPE_HEADER);
+               
+               return null != contentType && contentType.equals(CONTENT_TYPE_JSON);
+       }
+       
+       protected String getSafeUserNameParam(HttpExchange httpExchange) {
+               final String uri = httpExchange.getRequestURI().toString();
+               final AntPathMatcher pathMatcher = new AntPathMatcher();
+               
+               String userNameParam = "";
+               try {
+                       final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
+                       userNameParam = variables.get(USER_NAME_PARAM);
+               } catch (IllegalStateException exception) {
+                       
+                       LOGGER.warn("AntPathMatcher: ", exception);
+               }
+               
+               return userNameParam;
+       }
+}
diff --git a/src/main/java/com/prueba/resources/rest/controllers/LoginController.java b/src/main/java/com/prueba/resources/rest/controllers/LoginController.java
new file mode 100644 (file)
index 0000000..7a8b8c5
--- /dev/null
@@ -0,0 +1,42 @@
+package com.prueba.resources.rest.controllers;
+
+import java.io.IOException;
+
+import com.prueba.core.web.controller.Controller;
+import com.prueba.services.impl.LoginServiceImpl;
+import com.sun.net.httpserver.HttpExchange;
+
+public class LoginController implements Controller {
+       
+       @Override
+       public void handle(HttpExchange httpExchange) throws IOException {
+               final LoginServiceImpl loginService = new LoginServiceImpl();
+               final String requestedURI = httpExchange.getRequestURI().toString();
+               
+               if (requestedURI.startsWith("/app/login/login.html")) {
+                       
+                       final String requestMethod = httpExchange.getRequestMethod();
+                       
+                       switch (requestMethod) {
+                               case "GET":
+                                       loginService.processLoginGet(httpExchange);
+                                       break;
+                               case "POST":
+                                       loginService.processLoginPost(httpExchange);
+                                       break;
+                               default:
+                                       httpExchange.sendResponseHeaders(404, 0);
+                                       break;
+                       }
+                       
+               } else if (requestedURI.startsWith("/app/login/logout.html")) {
+                       loginService.processLogoutGet(httpExchange);
+               } else {
+                       httpExchange.sendResponseHeaders(404, 0);
+               }
+       
+       }
+       
+
+
+}
diff --git a/src/main/java/com/prueba/resources/rest/controllers/PagesController.java b/src/main/java/com/prueba/resources/rest/controllers/PagesController.java
new file mode 100644 (file)
index 0000000..7238fe7
--- /dev/null
@@ -0,0 +1,67 @@
+package com.prueba.resources.rest.controllers;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import com.prueba.core.context.security.persistence.SessionInfo;
+import com.prueba.core.context.security.persistence.context.SessionContext;
+import com.prueba.core.web.controller.Controller;
+import com.prueba.view.login.PageImpl;
+import com.sun.net.httpserver.HttpExchange;
+
+public class PagesController implements Controller {
+
+       @Override
+       public void handle(HttpExchange httpExchange) throws IOException {
+               final String requestMethod = httpExchange.getRequestMethod();
+               
+               switch (requestMethod) {
+                       case "GET":
+                               this.processPages(httpExchange);
+                               break;
+                       default:
+                               httpExchange.sendResponseHeaders(404, 0);
+                               break;
+               }
+               
+       }
+
+       protected  void processPages(HttpExchange httpExchange) throws IOException {
+               final String requestedURI = httpExchange.getRequestURI().toString();
+               final PageImpl pageImpl = new PageImpl();
+               
+               int responseStatus = 200;
+               String html = "";
+               switch (requestedURI) {
+                       case "/app/pages/page_1.html":
+                               html = pageImpl.doPage(1, getSafeUserName());
+                               break;
+                       case "/app/pages/page_2.html":
+                               html = pageImpl.doPage(2, getSafeUserName());
+                               break;
+                       case "/app/pages/page_3.html":
+                               html = pageImpl.doPage(3, getSafeUserName());
+                               break;
+                       default:
+                               responseStatus = 404;
+                               break;
+               }
+               
+               httpExchange.sendResponseHeaders(responseStatus, html.length());
+               try (final OutputStream os = httpExchange.getResponseBody()) {
+                       os.write(html.getBytes());
+               }
+       }
+       
+       protected String getSafeUserName() {
+               SessionInfo sessionInfo = SessionContext.getSession();
+               String userName = "";
+               
+               if (sessionInfo != null) {
+                       userName = sessionInfo.getUsername();
+               }
+               
+               return userName;
+       }
+       
+}