From 1cb5f485262860d9dfc97a9bf95380837a750483 Mon Sep 17 00:00:00 2001 From: Gustavo Martin Morcuende Date: Tue, 4 Oct 2016 14:20:03 +0200 Subject: [PATCH] package names improvements --- .../java/com/prueba/api/persistence/Account.java | 46 ------- .../persistence/dao/ApplicationResourceDao.java | 46 ------- .../services/impl/AuthorizationServicesImpl.java | 51 ------- .../com/prueba/controllers/rest/ApiController.java | 148 +++++++++++++++++++++ .../prueba/controllers/rest/LoginController.java | 42 ++++++ .../prueba/controllers/rest/PagesController.java | 67 ++++++++++ .../integration/database/DataBaseAccess.java | 3 + .../database/impl/DataBaseAccessImpl.java | 5 +- .../datasource/impl/DoDataSourceContext.java | 2 +- .../core/context/security/handle/ApiHandler.java | 4 +- .../core/context/security/handle/LoginHandler.java | 2 +- .../core/context/security/handle/PagesHandler.java | 4 +- .../web/application/ApplicationWebContext.java | 3 +- .../com/prueba/persistence/dao/AccountDao.java | 19 +-- .../persistence/dao/ApplicationResourceDao.java | 46 +++++++ .../prueba/persistence/domain/AccountResource.java | 46 +++++++ .../resources/rest/controllers/ApiController.java | 148 --------------------- .../rest/controllers/LoginController.java | 42 ------ .../rest/controllers/PagesController.java | 67 ---------- .../com/prueba/services/impl/ApiServiceImpl.java | 6 +- .../services/impl/AuthorizationServicesImpl.java | 51 +++++++ .../persistence/dao/AccountDaoIntegrationTest.java | 26 ++-- 22 files changed, 439 insertions(+), 435 deletions(-) delete mode 100644 src/main/java/com/prueba/api/persistence/Account.java delete mode 100644 src/main/java/com/prueba/authorization/persistence/dao/ApplicationResourceDao.java delete mode 100644 src/main/java/com/prueba/authorization/services/impl/AuthorizationServicesImpl.java create mode 100644 src/main/java/com/prueba/controllers/rest/ApiController.java create mode 100644 src/main/java/com/prueba/controllers/rest/LoginController.java create mode 100644 src/main/java/com/prueba/controllers/rest/PagesController.java create mode 100644 src/main/java/com/prueba/persistence/dao/ApplicationResourceDao.java create mode 100644 src/main/java/com/prueba/persistence/domain/AccountResource.java delete mode 100644 src/main/java/com/prueba/resources/rest/controllers/ApiController.java delete mode 100644 src/main/java/com/prueba/resources/rest/controllers/LoginController.java delete mode 100644 src/main/java/com/prueba/resources/rest/controllers/PagesController.java create mode 100644 src/main/java/com/prueba/services/impl/AuthorizationServicesImpl.java diff --git a/src/main/java/com/prueba/api/persistence/Account.java b/src/main/java/com/prueba/api/persistence/Account.java deleted file mode 100644 index ee4f09a..0000000 --- a/src/main/java/com/prueba/api/persistence/Account.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.prueba.api.persistence; - -public class Account { - private final String code; - private final String name; - private final String surname; - 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; - this.surname = surname; - this.password = password; - this.role = role; - } - - public String getCode() { - return code; - } - - public String getName() { - return name; - } - - public String getSurname() { - return surname; - } - - public String getPassword() { - return password; - } - - public String getRole() { - return role; - } - -} diff --git a/src/main/java/com/prueba/authorization/persistence/dao/ApplicationResourceDao.java b/src/main/java/com/prueba/authorization/persistence/dao/ApplicationResourceDao.java deleted file mode 100644 index c8dbe70..0000000 --- a/src/main/java/com/prueba/authorization/persistence/dao/ApplicationResourceDao.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.prueba.authorization.persistence.dao; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.sql.DataSource; - -import com.prueba.core.context.integration.database.impl.DataBaseAccessImpl; -import com.prueba.core.context.web.application.ApplicationWebContext; - -public class ApplicationResourceDao { - public static final String URL_PATTERN = "URL_PATTERN"; - public static final String HTTP_METHOD = "HTTP_METHOD"; - - public List> findURLsByUserName(String userName) { - final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource(); - final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource); - - return dataBaseAccess.executeQuery("" - + "SELECT APP_RES.URL_PATTERN, APP_RES.HTTP_METHOD FROM APPLICATION_ROLE APP_ROLE " - + "INNER JOIN APPLICATION_RESOURCE_APPLICATION_ROLE APP_RES_APP_ROLE ON APP_ROLE.CODE = APP_RES_APP_ROLE.APPLICATION_ROLE_CODE " - + "INNER JOIN APPLICATION_RESOURCE APP_RES ON APP_RES.URL_PATTERN = APP_RES_APP_ROLE.APPLICATION_RESOURCE_URL_PATTERN " - + "INNER JOIN ACCOUNT ACC ON ACC.APPLICATION_ROLE_CODE = APP_ROLE.CODE " - + "WHERE ACC.CODE = ? ", - answer -> - { - final List> result = new ArrayList<>(); - while (answer.next()) { - final Map row = new HashMap<>(); - String urlPatternValue = answer.getString(URL_PATTERN); - String httpMethodValue = answer.getString(HTTP_METHOD); - row.put(URL_PATTERN, urlPatternValue); - row.put(HTTP_METHOD, httpMethodValue); - result.add(row); - } - - return result; - }, - preparedStatement -> { - preparedStatement.setString(1, userName); - }); - } -} - diff --git a/src/main/java/com/prueba/authorization/services/impl/AuthorizationServicesImpl.java b/src/main/java/com/prueba/authorization/services/impl/AuthorizationServicesImpl.java deleted file mode 100644 index ac3f667..0000000 --- a/src/main/java/com/prueba/authorization/services/impl/AuthorizationServicesImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -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/users/{" + USER_NAME_PARAM + "}"; - - public boolean isAuthorized(String httpMethod, String uri, String userName) { - final String userNameParam = this.getSafeUserNameParam(uri); - - final ApplicationResourceDao dao = new ApplicationResourceDao(); - - final List> urls = dao.findURLsByUserName(userName); - - return urls.stream().anyMatch(urlMap -> - { - final String urlPatternValue = urlMap.get(ApplicationResourceDao.URL_PATTERN); - final String urlReplacedPatternValue = urlPatternValue.replace("{" + USER_NAME_PARAM + "}", userNameParam); - - final String httpMethodValue = urlMap.get(ApplicationResourceDao.HTTP_METHOD); - - return urlReplacedPatternValue.equals(uri) && httpMethodValue.equals(httpMethod); - }); - - } - - protected String getSafeUserNameParam(String uri) { - final AntPathMatcher pathMatcher = new AntPathMatcher(); - - String userNameParam = ""; - try { - final Map 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/controllers/rest/ApiController.java b/src/main/java/com/prueba/controllers/rest/ApiController.java new file mode 100644 index 0000000..5f7b4e6 --- /dev/null +++ b/src/main/java/com/prueba/controllers/rest/ApiController.java @@ -0,0 +1,148 @@ +package com.prueba.controllers.rest; + +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.core.context.util.AntPathMatcher; +import com.prueba.core.web.controller.Controller; +import com.prueba.persistence.domain.AccountResource; +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); + + AccountResource 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 AccountResource accountRequest = mapper.readValue(bodyRequest, AccountResource.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 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/controllers/rest/LoginController.java b/src/main/java/com/prueba/controllers/rest/LoginController.java new file mode 100644 index 0000000..e0ef2d4 --- /dev/null +++ b/src/main/java/com/prueba/controllers/rest/LoginController.java @@ -0,0 +1,42 @@ +package com.prueba.controllers.rest; + +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/controllers/rest/PagesController.java b/src/main/java/com/prueba/controllers/rest/PagesController.java new file mode 100644 index 0000000..38c10d9 --- /dev/null +++ b/src/main/java/com/prueba/controllers/rest/PagesController.java @@ -0,0 +1,67 @@ +package com.prueba.controllers.rest; + +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/core/context/integration/database/DataBaseAccess.java b/src/main/java/com/prueba/core/context/integration/database/DataBaseAccess.java index dbf78f0..febf73e 100644 --- a/src/main/java/com/prueba/core/context/integration/database/DataBaseAccess.java +++ b/src/main/java/com/prueba/core/context/integration/database/DataBaseAccess.java @@ -26,4 +26,7 @@ public interface DataBaseAccess { List> executeQuery( final String query, final ExecuteResultSet executeResultSet, FillPreparedStatement fillStatement); + + + void executeUpdate(String query, FillPreparedStatement fillStatement); } diff --git a/src/main/java/com/prueba/core/context/integration/database/impl/DataBaseAccessImpl.java b/src/main/java/com/prueba/core/context/integration/database/impl/DataBaseAccessImpl.java index e3ef9c1..54564df 100644 --- a/src/main/java/com/prueba/core/context/integration/database/impl/DataBaseAccessImpl.java +++ b/src/main/java/com/prueba/core/context/integration/database/impl/DataBaseAccessImpl.java @@ -73,14 +73,15 @@ public class DataBaseAccessImpl implements DataBaseAccess { } + @Override public void executeUpdate(String query, FillPreparedStatement fillStatement) { try { this.executeUpdateThrowable(query, fillStatement); } catch (SQLException exception) { - LOGGER.error("Query error: ", exception); + LOGGER.error("Update error: ", exception); - throw new IllegalStateException("Querry error", exception); + throw new IllegalStateException("Update error", exception); } } diff --git a/src/main/java/com/prueba/core/context/integration/datasource/impl/DoDataSourceContext.java b/src/main/java/com/prueba/core/context/integration/datasource/impl/DoDataSourceContext.java index bb7779d..f5b6025 100644 --- a/src/main/java/com/prueba/core/context/integration/datasource/impl/DoDataSourceContext.java +++ b/src/main/java/com/prueba/core/context/integration/datasource/impl/DoDataSourceContext.java @@ -51,7 +51,7 @@ public class DoDataSourceContext implements DoDataSource { pool.setPassword(PASSWORD); pool.setDriverClass(DRIVER_CLASS); pool.setJdbcUrl(JDBC_URL); - pool.setInitialPoolSize(5); + pool.setInitialPoolSize(10); pool.setMaxPoolSize(35); pool.setMinPoolSize(10); pool.setAcquireIncrement(1); diff --git a/src/main/java/com/prueba/core/context/security/handle/ApiHandler.java b/src/main/java/com/prueba/core/context/security/handle/ApiHandler.java index ba6f5b7..109bdeb 100644 --- a/src/main/java/com/prueba/core/context/security/handle/ApiHandler.java +++ b/src/main/java/com/prueba/core/context/security/handle/ApiHandler.java @@ -5,10 +5,10 @@ import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.prueba.authorization.services.impl.AuthorizationServicesImpl; +import com.prueba.controllers.rest.ApiController; import com.prueba.core.context.security.authenticator.persistence.AuthenticationInfo; import com.prueba.core.context.security.persistence.context.BasicAuthenticationContext; -import com.prueba.resources.rest.controllers.ApiController; +import com.prueba.services.impl.AuthorizationServicesImpl; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; diff --git a/src/main/java/com/prueba/core/context/security/handle/LoginHandler.java b/src/main/java/com/prueba/core/context/security/handle/LoginHandler.java index 7df730f..62b180b 100644 --- a/src/main/java/com/prueba/core/context/security/handle/LoginHandler.java +++ b/src/main/java/com/prueba/core/context/security/handle/LoginHandler.java @@ -5,7 +5,7 @@ import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.prueba.resources.rest.controllers.LoginController; +import com.prueba.controllers.rest.LoginController; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; diff --git a/src/main/java/com/prueba/core/context/security/handle/PagesHandler.java b/src/main/java/com/prueba/core/context/security/handle/PagesHandler.java index 07b0a42..bc0eab4 100644 --- a/src/main/java/com/prueba/core/context/security/handle/PagesHandler.java +++ b/src/main/java/com/prueba/core/context/security/handle/PagesHandler.java @@ -6,11 +6,11 @@ import java.net.URI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.prueba.authorization.services.impl.AuthorizationServicesImpl; +import com.prueba.controllers.rest.PagesController; 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.rest.controllers.PagesController; +import com.prueba.services.impl.AuthorizationServicesImpl; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; diff --git a/src/main/java/com/prueba/core/context/web/application/ApplicationWebContext.java b/src/main/java/com/prueba/core/context/web/application/ApplicationWebContext.java index d5c947d..76e36c4 100644 --- a/src/main/java/com/prueba/core/context/web/application/ApplicationWebContext.java +++ b/src/main/java/com/prueba/core/context/web/application/ApplicationWebContext.java @@ -7,9 +7,8 @@ import com.prueba.core.context.integration.datasource.impl.DoDataSourceContext; 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.core.context.security.handle.SessionHandler; import com.sun.net.httpserver.HttpHandler; diff --git a/src/main/java/com/prueba/persistence/dao/AccountDao.java b/src/main/java/com/prueba/persistence/dao/AccountDao.java index 01406f1..19bf2d9 100644 --- a/src/main/java/com/prueba/persistence/dao/AccountDao.java +++ b/src/main/java/com/prueba/persistence/dao/AccountDao.java @@ -7,9 +7,10 @@ import java.util.Map; import javax.sql.DataSource; -import com.prueba.api.persistence.Account; +import com.prueba.core.context.integration.database.DataBaseAccess; import com.prueba.core.context.integration.database.impl.DataBaseAccessImpl; import com.prueba.core.context.web.application.ApplicationWebContext; +import com.prueba.persistence.domain.AccountResource; public class AccountDao { private static final String CODE = "CODE"; @@ -18,9 +19,9 @@ public class AccountDao { private static final String PASSWORD = "PASSWORD"; private static final String APP_ROLE_CODE = "APPLICATION_ROLE_CODE"; - public Account findByCode(String accountCode) { + public AccountResource findByCode(String accountCode) { final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource(); - final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource); + final DataBaseAccess dataBaseAccess = new DataBaseAccessImpl(dataSource); final List> results = dataBaseAccess.executeQuery("SELECT * FROM ACCOUNT WHERE CODE = ?", @@ -43,18 +44,18 @@ public class AccountDao { preparedStatement.setString(1, accountCode); }); - Account account = null; + AccountResource account = null; if (!results.isEmpty()) { final Map row = results.get(0); - account = new Account(row.get(CODE), row.get(NAME), + account = new AccountResource(row.get(CODE), row.get(NAME), row.get(SURNAME), null, row.get(APP_ROLE_CODE)); } return account; } - public void create(Account account) { + public void create(AccountResource account) { final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource(); final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource); @@ -81,7 +82,7 @@ public class AccountDao { } - public Account findByCodeAndPassword(String username, String password) { + public AccountResource findByCodeAndPassword(String username, String password) { final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource(); final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource); @@ -107,11 +108,11 @@ public class AccountDao { preparedStatement.setString(2, password); }); - Account account = null; + AccountResource account = null; if (!results.isEmpty()) { final Map row = results.get(0); - account = new Account(row.get(CODE), row.get(NAME), + account = new AccountResource(row.get(CODE), row.get(NAME), row.get(SURNAME), null, row.get(APP_ROLE_CODE)); } diff --git a/src/main/java/com/prueba/persistence/dao/ApplicationResourceDao.java b/src/main/java/com/prueba/persistence/dao/ApplicationResourceDao.java new file mode 100644 index 0000000..0df20bb --- /dev/null +++ b/src/main/java/com/prueba/persistence/dao/ApplicationResourceDao.java @@ -0,0 +1,46 @@ +package com.prueba.persistence.dao; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.sql.DataSource; + +import com.prueba.core.context.integration.database.impl.DataBaseAccessImpl; +import com.prueba.core.context.web.application.ApplicationWebContext; + +public class ApplicationResourceDao { + public static final String URL_PATTERN = "URL_PATTERN"; + public static final String HTTP_METHOD = "HTTP_METHOD"; + + public List> findURLsByUserName(String userName) { + final DataSource dataSource = ApplicationWebContext.getInstance().getDataSource(); + final DataBaseAccessImpl dataBaseAccess = new DataBaseAccessImpl(dataSource); + + return dataBaseAccess.executeQuery("" + + "SELECT APP_RES.URL_PATTERN, APP_RES.HTTP_METHOD FROM APPLICATION_ROLE APP_ROLE " + + "INNER JOIN APPLICATION_RESOURCE_APPLICATION_ROLE APP_RES_APP_ROLE ON APP_ROLE.CODE = APP_RES_APP_ROLE.APPLICATION_ROLE_CODE " + + "INNER JOIN APPLICATION_RESOURCE APP_RES ON APP_RES.URL_PATTERN = APP_RES_APP_ROLE.APPLICATION_RESOURCE_URL_PATTERN " + + "INNER JOIN ACCOUNT ACC ON ACC.APPLICATION_ROLE_CODE = APP_ROLE.CODE " + + "WHERE ACC.CODE = ? ", + answer -> + { + final List> result = new ArrayList<>(); + while (answer.next()) { + final Map row = new HashMap<>(); + String urlPatternValue = answer.getString(URL_PATTERN); + String httpMethodValue = answer.getString(HTTP_METHOD); + row.put(URL_PATTERN, urlPatternValue); + row.put(HTTP_METHOD, httpMethodValue); + result.add(row); + } + + return result; + }, + preparedStatement -> { + preparedStatement.setString(1, userName); + }); + } +} + diff --git a/src/main/java/com/prueba/persistence/domain/AccountResource.java b/src/main/java/com/prueba/persistence/domain/AccountResource.java new file mode 100644 index 0000000..bcac09d --- /dev/null +++ b/src/main/java/com/prueba/persistence/domain/AccountResource.java @@ -0,0 +1,46 @@ +package com.prueba.persistence.domain; + +public class AccountResource { + private final String code; + private final String name; + private final String surname; + private final String password; + private final String role; + + public AccountResource() { + this.code = null; + this.name = null; + this.surname = null; + this.password = null; + this.role = null; + } + + public AccountResource(String code, String name, String surname, String password, String role) { + this.code = code; + this.name = name; + this.surname = surname; + this.password = password; + this.role = role; + } + + public String getCode() { + return code; + } + + public String getName() { + return name; + } + + public String getSurname() { + return surname; + } + + public String getPassword() { + return password; + } + + public String getRole() { + return role; + } + +} diff --git a/src/main/java/com/prueba/resources/rest/controllers/ApiController.java b/src/main/java/com/prueba/resources/rest/controllers/ApiController.java deleted file mode 100644 index cfa7da6..0000000 --- a/src/main/java/com/prueba/resources/rest/controllers/ApiController.java +++ /dev/null @@ -1,148 +0,0 @@ -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 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 deleted file mode 100644 index 7a8b8c5..0000000 --- a/src/main/java/com/prueba/resources/rest/controllers/LoginController.java +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 7238fe7..0000000 --- a/src/main/java/com/prueba/resources/rest/controllers/PagesController.java +++ /dev/null @@ -1,67 +0,0 @@ -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; - } - -} diff --git a/src/main/java/com/prueba/services/impl/ApiServiceImpl.java b/src/main/java/com/prueba/services/impl/ApiServiceImpl.java index 1c9663c..312bd30 100644 --- a/src/main/java/com/prueba/services/impl/ApiServiceImpl.java +++ b/src/main/java/com/prueba/services/impl/ApiServiceImpl.java @@ -1,17 +1,17 @@ package com.prueba.services.impl; -import com.prueba.api.persistence.Account; import com.prueba.persistence.dao.AccountDao; +import com.prueba.persistence.domain.AccountResource; public class ApiServiceImpl { - public Account findAccountByCode(String accountCode) { + public AccountResource findAccountByCode(String accountCode) { AccountDao accountDao = new AccountDao(); return accountDao.findByCode(accountCode); } - public void createAccount(Account account) { + public void createAccount(AccountResource account) { AccountDao accountDao = new AccountDao(); accountDao.create(account); diff --git a/src/main/java/com/prueba/services/impl/AuthorizationServicesImpl.java b/src/main/java/com/prueba/services/impl/AuthorizationServicesImpl.java new file mode 100644 index 0000000..77e9f22 --- /dev/null +++ b/src/main/java/com/prueba/services/impl/AuthorizationServicesImpl.java @@ -0,0 +1,51 @@ +package com.prueba.services.impl; + +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.prueba.core.context.util.AntPathMatcher; +import com.prueba.persistence.dao.ApplicationResourceDao; + +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/users/{" + USER_NAME_PARAM + "}"; + + public boolean isAuthorized(String httpMethod, String uri, String userName) { + final String userNameParam = this.getSafeUserNameParam(uri); + + final ApplicationResourceDao dao = new ApplicationResourceDao(); + + final List> urls = dao.findURLsByUserName(userName); + + return urls.stream().anyMatch(urlMap -> + { + final String urlPatternValue = urlMap.get(ApplicationResourceDao.URL_PATTERN); + final String urlReplacedPatternValue = urlPatternValue.replace("{" + USER_NAME_PARAM + "}", userNameParam); + + final String httpMethodValue = urlMap.get(ApplicationResourceDao.HTTP_METHOD); + + return urlReplacedPatternValue.equals(uri) && httpMethodValue.equals(httpMethod); + }); + + } + + protected String getSafeUserNameParam(String uri) { + final AntPathMatcher pathMatcher = new AntPathMatcher(); + + String userNameParam = ""; + try { + final Map 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/test/java/com/prueba/persistence/dao/AccountDaoIntegrationTest.java b/src/test/java/com/prueba/persistence/dao/AccountDaoIntegrationTest.java index ed65fe4..bd168c5 100644 --- a/src/test/java/com/prueba/persistence/dao/AccountDaoIntegrationTest.java +++ b/src/test/java/com/prueba/persistence/dao/AccountDaoIntegrationTest.java @@ -9,9 +9,9 @@ import javax.sql.DataSource; import org.junit.Before; import org.junit.Test; -import com.prueba.api.persistence.Account; import com.prueba.core.context.integration.datasource.impl.DoDataSourceContext; import com.prueba.core.context.integration.liquibase.impl.LiquibaseContext; +import com.prueba.persistence.domain.AccountResource; public class AccountDaoIntegrationTest { private AccountDao accountDao; @@ -28,9 +28,9 @@ public class AccountDaoIntegrationTest { @Test public void whenFindAccountByCodeAndPasswordThenRetrieveAccount() { - Account expectedAccount = doAccount(); + AccountResource expectedAccount = doAccount(); - Account account = accountDao.findByCodeAndPassword( + AccountResource account = accountDao.findByCodeAndPassword( expectedAccount.getCode(), expectedAccount.getPassword()); assertNotNull(account); @@ -43,11 +43,11 @@ public class AccountDaoIntegrationTest { @Test public void whenCreateNewAccountThenRetrieveNewAccount() { - Account expectedAccount = doSampleAccount(); + AccountResource expectedAccount = doSampleAccount(); accountDao.create(expectedAccount); - Account account = accountDao.findByCode(expectedAccount.getCode()); + AccountResource account = accountDao.findByCode(expectedAccount.getCode()); assertNotNull(account); assertEquals(expectedAccount.getCode(), account.getCode()); @@ -59,10 +59,10 @@ public class AccountDaoIntegrationTest { @Test public void whenDeleteAccountThenDoNotRetrieveAgainAccount() { - Account expectedAccount = doOtherSampleAccount(); + AccountResource expectedAccount = doOtherSampleAccount(); accountDao.create(expectedAccount); - Account account = accountDao.findByCode(expectedAccount.getCode()); + AccountResource account = accountDao.findByCode(expectedAccount.getCode()); assertNotNull(account); assertEquals(expectedAccount.getCode(), account.getCode()); @@ -77,33 +77,33 @@ public class AccountDaoIntegrationTest { assertNull(account); } - private Account doAccount() { + private AccountResource doAccount() { final String expectedCode = "GUMARTIN"; final String expectedName = "Gustavo"; final String expectedSurname = "Martin Morcuende"; final String expectedPassword = "lame"; final String expectedAppRoleCode = "ROLE_APP_ADMIN"; - return new Account(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode); + return new AccountResource(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode); } - private Account doSampleAccount() { + private AccountResource doSampleAccount() { final String expectedCode = "PRUEBA"; final String expectedName = "Gustavo"; final String expectedSurname = "Martin Morcuende"; final String expectedPassword = "lame"; final String expectedAppRoleCode = "ROLE_APP_ADMIN"; - return new Account(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode); + return new AccountResource(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode); } - private Account doOtherSampleAccount() { + private AccountResource doOtherSampleAccount() { final String expectedCode = "OTRAPRUEBA"; final String expectedName = "Gustavo"; final String expectedSurname = "Martin Morcuende"; final String expectedPassword = "lame"; final String expectedAppRoleCode = "ROLE_APP_ADMIN"; - return new Account(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode); + return new AccountResource(expectedCode, expectedName, expectedSurname, expectedPassword, expectedAppRoleCode); } } -- 2.1.4