ApiController
authorGustavo Martin Morcuende <gu.martinm@gmail.com>
Mon, 3 Oct 2016 21:06:14 +0000 (23:06 +0200)
committerGustavo Martin Morcuende <gu.martinm@gmail.com>
Mon, 3 Oct 2016 21:06:14 +0000 (23:06 +0200)
src/main/java/com/prueba/api/persistence/Account.java
src/main/java/com/prueba/authorization/services/impl/AuthorizationServicesImpl.java
src/main/java/com/prueba/core/context/integration/database/impl/DataBaseAccessImpl.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/resources/controllers/ApiController.java
src/main/resources/liquibase/dml.sql

index ff34f40..ee4f09a 100644 (file)
@@ -7,6 +7,14 @@ public class Account {
        private final String password;  
        private final String role;
        
+       public Account() {
+               this.code = null;
+               this.name = null;
+               this.surname = null;
+               this.password = null;
+               this.role = null;
+       }
+       
        public Account(String code, String name, String surname, String password, String role) {
                this.code = code;
                this.name = name;
index 57d3516..100a660 100644 (file)
@@ -3,17 +3,20 @@ package com.prueba.authorization.services.impl;
 import java.util.List;
 import java.util.Map;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.prueba.authorization.persistence.dao.ApplicationResourceDao;
 import com.prueba.core.context.util.AntPathMatcher;
 
 public class AuthorizationServicesImpl {
+       private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationServicesImpl.class);
+
        private static final String USER_NAME_PARAM = "username";
-       private static final String API_URL_PATTERN = "/app/api/{" + USER_NAME_PARAM + "}";
+       private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
 
        public boolean isAuthorized(String httpMethod, String uri, String userName) {
-               final AntPathMatcher pathMatcher = new AntPathMatcher();
-               final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
-               final String userNameParam = variables.get(USER_NAME_PARAM);
+               final String userNameParam = this.getUserNameParam(uri);
                
                final ApplicationResourceDao dao = new ApplicationResourceDao();
                
@@ -30,4 +33,19 @@ public class AuthorizationServicesImpl {
                });
                
        }
+       
+       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;
+       }
 }
index 47b5c6e..e3ef9c1 100644 (file)
@@ -32,6 +32,8 @@ public class DataBaseAccessImpl implements DataBaseAccess {
                        result = this.executeQueryThrowable(query, executeResultSet, fillStatement);
                } catch (SQLException exception) {
                        LOGGER.error("Query error: ", exception);
+                       
+                       throw new IllegalStateException("Querry error", exception);
                }
                
                return result;
@@ -77,6 +79,8 @@ public class DataBaseAccessImpl implements DataBaseAccess {
                        this.executeUpdateThrowable(query, fillStatement);
                } catch (SQLException exception) {
                        LOGGER.error("Query error: ", exception);
+                       
+                       throw new IllegalStateException("Querry error", exception);
                }
 
        }
index f0bddf5..a5f864e 100644 (file)
@@ -2,6 +2,9 @@ package com.prueba.core.context.security.handle;
 
 import java.io.IOException;
 
+import org.slf4j.Logger;
+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;
@@ -10,13 +13,28 @@ import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpHandler;
 
 public class ApiHandler implements HttpHandler {
-       public static final String CONTEXT = "/app/api/";
+       public static final String CONTEXT = "/app/api/users/";
+       
+       private static final Logger LOGGER = LoggerFactory.getLogger(ApiHandler.class);
        
        private final ApiController apiController = new ApiController();
        private final AuthorizationServicesImpl authorizationService = new AuthorizationServicesImpl();
 
        @Override
        public void handle(HttpExchange httpExchange) throws IOException  {
+               
+               try {
+                       this.handleThrowable(httpExchange);     
+               } catch (Exception exception) {
+                       LOGGER.error("ApiHandler error: ", exception);
+                       
+                       httpExchange.sendResponseHeaders(500, 0);
+               } finally {
+                       httpExchange.close();
+               }
+       }
+       
+       protected void handleThrowable(HttpExchange httpExchange) throws IOException  {
                AuthenticationInfo authenticationInfo = BasicAuthenticationContext.getAuthentication();
                
                if(authorizationService.isAuthorized(httpExchange.getRequestMethod(),
index 1b8d50c..fa39baf 100644 (file)
@@ -2,8 +2,10 @@ package com.prueba.core.context.security.handle;
 
 import java.io.IOException;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.prueba.resources.controllers.LoginController;
-import com.sun.net.httpserver.Headers;
 import com.sun.net.httpserver.HttpExchange;
 import com.sun.net.httpserver.HttpHandler;
 
@@ -12,6 +14,9 @@ public class LoginHandler implements HttpHandler {
        public static final String CONTEXT = "/app/login/";
        public static final String LOGIN_PAGE = "/app/login/login.html?serviceName=http://localhost:8080";
        
+       private static final Logger LOGGER = LoggerFactory.getLogger(LoginHandler.class);
+
+       
        private final LoginController loginController = new LoginController();
        private final HttpHandler sessionHandler;
        
@@ -21,11 +26,21 @@ public class LoginHandler implements HttpHandler {
        
        @Override
        public void handle(HttpExchange httpExchange) throws IOException  {
+               try {
+                       this.handleThrowable(httpExchange);
+               } catch (Exception exception) {
+                       LOGGER.error("LoginHandler error: ", exception);
+                       
+                       httpExchange.sendResponseHeaders(500, 0);
+               } finally {
+                       httpExchange.close();
+               }
+               
+       }
+
+       protected void handleThrowable(HttpExchange httpExchange) throws IOException  {
                sessionHandler.handle(httpExchange);
                
                loginController.handle(httpExchange);
-               
-               httpExchange.close();   
        }
-
 }
index 7a9287e..8789103 100644 (file)
@@ -3,6 +3,9 @@ package com.prueba.core.context.security.handle;
 import java.io.IOException;
 import java.net.URI;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.prueba.authorization.services.impl.AuthorizationServicesImpl;
 import com.prueba.core.context.security.persistence.SessionInfo;
 import com.prueba.core.context.security.persistence.Sessions;
@@ -16,6 +19,7 @@ import com.sun.net.httpserver.HttpHandler;
 public class PagesHandler implements HttpHandler {
        public static final String CONTEXT = "/app/pages/";
        
+       private static final Logger LOGGER = LoggerFactory.getLogger(PagesHandler.class);
        private static final String SERVER_ADDRESS = "http://localhost:8080";
                
        private final PagesController pagesController = new PagesController();
@@ -28,6 +32,18 @@ public class PagesHandler implements HttpHandler {
        
        @Override
        public void handle(HttpExchange httpExchange) throws IOException  {     
+               try {
+                       this.handleThrowable(httpExchange);
+               } catch (Exception exception) {
+                       LOGGER.error("PagesHandler error: ", exception);
+                       
+                       httpExchange.sendResponseHeaders(500, 0);
+               } finally {
+                       httpExchange.close();
+               }               
+       }
+       
+       protected void handleThrowable(HttpExchange httpExchange) throws IOException  { 
                this.sessionHandler.handle(httpExchange);
                
                if (Sessions.getInstance().isValidSession(httpExchange)) {
@@ -36,7 +52,8 @@ public class PagesHandler implements HttpHandler {
                        if(authorizationService.isAuthorized(httpExchange.getRequestMethod(),
                                        httpExchange.getRequestURI().toString(), sessionInfo.getUsername())) {
                                
-                               pagesController.handle(httpExchange);                           
+                               pagesController.handle(httpExchange);
+
                        } else {
                                httpExchange.sendResponseHeaders(403, 0);
                        }
@@ -45,8 +62,6 @@ public class PagesHandler implements HttpHandler {
                } else {
                        this.doRedirect(httpExchange);
                }
-               
-               httpExchange.close();
        }
                
        protected void doRedirect(HttpExchange httpExchange) throws IOException  {
index 657bebd..f8a7a1a 100644 (file)
@@ -7,16 +7,22 @@ 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/{" + USER_NAME_PARAM + "}";
+       private static final String API_URL_PATTERN = "/app/api/users/{" + USER_NAME_PARAM + "}";
 
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
@@ -25,19 +31,21 @@ public class ApiController implements Controller {
                final ObjectMapper mapper = new ObjectMapper();
        
                final String uri = httpExchange.getRequestURI().toString();
-               final AntPathMatcher pathMatcher = new AntPathMatcher();
-               final Map<String, String> variables = pathMatcher.extractUriTemplateVariables(API_URL_PATTERN, uri);
-               final String userNameParam = variables.get(USER_NAME_PARAM);
+               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);
                                }
                                
-                               httpExchange.sendResponseHeaders(200, bodyResponse.length());
+                               this.setContentTypeHeader(httpExchange);
+                               
+                               httpExchange.sendResponseHeaders(statusCode, bodyResponse.length());
                                
                                try (final OutputStream os = httpExchange.getResponseBody()) {
                                        os.write(bodyResponse.getBytes());
@@ -50,14 +58,22 @@ public class ApiController implements Controller {
                                
                                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(200, 0);
+                               httpExchange.sendResponseHeaders(204, 0);
                                break;
                        default:
+                               
                                httpExchange.sendResponseHeaders(404, 0);
                                break;
                }
@@ -78,4 +94,26 @@ public class ApiController implements Controller {
                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;
+       }
 }
index 18b11f0..2550254 100644 (file)
@@ -10,10 +10,10 @@ INSERT INTO APPLICATION_RESOURCE (URL_PATTERN, HTTP_METHOD) values
 ('/app/pages/page_1.html', 'GET'),
 ('/app/pages/page_2.html', 'GET'),
 ('/app/pages/page_3.html', 'GET'),
-('/app/api/{username}', 'GET'),
-('/app/api/{username}', 'PUT'),
-('/app/api/{username}', 'POST'),
-('/app/api/{username}', 'DELETE');
+('/app/api/users/{username}', 'GET'),
+('/app/api/users/{username}', 'PUT'),
+('/app/api/users/', 'POST'),
+('/app/api/users/{username}', 'DELETE');
 
 
 INSERT INTO APPLICATION_RESOURCE_APPLICATION_ROLE (APPLICATION_RESOURCE_URL_PATTERN, APPLICATION_RESOURCE_HTTP_METHOD, APPLICATION_ROLE_CODE) values
@@ -23,13 +23,13 @@ INSERT INTO APPLICATION_RESOURCE_APPLICATION_ROLE (APPLICATION_RESOURCE_URL_PATT
 ('/app/pages/page_1.html', 'GET', 'ROLE_APP_ADMIN'),
 ('/app/pages/page_2.html', 'GET', 'ROLE_APP_ADMIN'),
 ('/app/pages/page_3.html', 'GET', 'ROLE_APP_ADMIN'),
-('/app/api/{username}', 'GET', 'ROLE_APP_PAGE_1'),
-('/app/api/{username}', 'GET', 'ROLE_APP_PAGE_2'),
-('/app/api/{username}', 'GET', 'ROLE_APP_PAGE_3'),
-('/app/api/{username}', 'GET', 'ROLE_APP_ADMIN'),
-('/app/api/{username}', 'PUT', 'ROLE_APP_ADMIN'),
-('/app/api/{username}', 'POST', 'ROLE_APP_ADMIN'),
-('/app/api/{username}', 'DELETE', 'ROLE_APP_ADMIN');
+('/app/api/users/{username}', 'GET', 'ROLE_APP_PAGE_1'),
+('/app/api/users/{username}', 'GET', 'ROLE_APP_PAGE_2'),
+('/app/api/users/{username}', 'GET', 'ROLE_APP_PAGE_3'),
+('/app/api/users/{username}', 'GET', 'ROLE_APP_ADMIN'),
+('/app/api/users/{username}', 'PUT', 'ROLE_APP_ADMIN'),
+('/app/api/users/', 'POST', 'ROLE_APP_ADMIN'),
+('/app/api/users/{username}', 'DELETE', 'ROLE_APP_ADMIN');
 
 
 INSERT INTO ACCOUNT (CODE, NAME, SURNAME, PASSWORD, APPLICATION_ROLE_CODE) values