diff --git a/.classpath b/.classpath
index 3aa4c20..7d79d2a 100644
--- a/.classpath
+++ b/.classpath
@@ -2,18 +2,18 @@
+
+
+
+
+
+
+
+ #
+
+
+
+
+
+
+
+
+ ${order.id}
+ ${order.topic}
+ ${order.customer.firstName} ${order.customer.lastName}
+ ${order.customer.company}
+
+
+ ${order.date}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ #
+
+
+
+
+
+
+
+ ${order.id}
+ ${order.topic}
+
+
+ ${order.date}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Id
+
+
+
+
+
+
+
+
+ ${user.id}
+ ${user.email}
+ ${user.firstName}
+ ${user.lastName}
+
+ ${user.registrationDate}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Click here
+
+ + +
++ + ${feedback.fileName} +
+Action interface provides a method for http request
+ * processing.
+ *
+ * @date Dec 14, 2014
+ * @author Andrey Kovalskiy
+ * @see com.epam.devteam.action.ActionResult
+ */
+public interface Action {
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException;
+
+}
diff --git a/src/com/epam/devteam/action/ActionFactory.java b/src/com/epam/devteam/action/ActionFactory.java
new file mode 100644
index 0000000..e00b270
--- /dev/null
+++ b/src/com/epam/devteam/action/ActionFactory.java
@@ -0,0 +1,98 @@
+/**
+ *
+ */
+package com.epam.devteam.action;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.account.ActivateAccountAction;
+import com.epam.devteam.action.account.ChangeAccountPasswordAction;
+import com.epam.devteam.action.account.CreateAccountAction;
+import com.epam.devteam.action.account.DeactivateAccountAction;
+import com.epam.devteam.action.account.SaveAccountAction;
+import com.epam.devteam.action.account.ShowAccountsManagementPageAction;
+import com.epam.devteam.action.account.ShowCreateAccountPageAction;
+import com.epam.devteam.action.account.ShowEditAccountPageAction;
+import com.epam.devteam.action.account.SigninAction;
+import com.epam.devteam.action.account.SignoutAction;
+import com.epam.devteam.action.feedback.CreateFeedbackAction;
+import com.epam.devteam.action.general.DownloadFileAction;
+import com.epam.devteam.action.general.SetLanguageAction;
+import com.epam.devteam.action.general.ShowAboutUsPageAction;
+import com.epam.devteam.action.general.ShowContactsPageAction;
+import com.epam.devteam.action.general.ShowErrorPageAction;
+import com.epam.devteam.action.general.ShowMainPageAction;
+import com.epam.devteam.action.general.ShowSuccessPageAction;
+import com.epam.devteam.action.order.CreateOrderAction;
+import com.epam.devteam.action.order.SaveOrderAction;
+import com.epam.devteam.action.order.ShowAllOrdersPageAction;
+import com.epam.devteam.action.order.ShowCreateOrderPageAction;
+import com.epam.devteam.action.order.ShowCustomerOrdersPageAction;
+import com.epam.devteam.action.order.ShowEditOrderPageAction;
+import com.epam.devteam.action.order.ShowOrderPageAction;
+import com.epam.devteam.action.order.ShowProcessOrderPageAction;
+import com.epam.devteam.action.order.TerminateOrderAction;
+
+/**
+ * @date Jan 5, 2014
+ * @author Andrey Kovalskiy
+ */
+public class ActionFactory {
+ private static final Logger LOGGER = Logger.getLogger(ActionFactory.class);
+ private static MapActionResult represents a result of Action
+ * class performing. It contains fields that are used by Controller
+ * to perform method (Get or Post) and display view.
+ *
+ * @date Jan 14, 2014
+ * @author Andrey Kovalskiy
+ * @see com.epam.devteam.servlet.Controller
+ * @see com.epam.devteam.action.Action
+ *
+ */
+public class ActionResult {
+ public enum METHOD {
+ FORWARD, REDIRECT
+ }
+
+ private METHOD method;
+ private String view;
+
+ /**
+ * Initializes a newly created {@code ActionResult} object.
+ */
+ public ActionResult() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code ActionResult} object with given
+ * values.
+ *
+ * @param method Method to perform
+ * @param view View to show.
+ */
+ public ActionResult(METHOD method, String view) {
+ super();
+ this.method = method;
+ this.view = view;
+ }
+
+ /**
+ * Returns the method field value.
+ *
+ * @return The method.
+ */
+ public METHOD getMethod() {
+ return method;
+ }
+
+ /**
+ * Sets the method field value.
+ *
+ * @param method The method to set.
+ */
+ public void setMethod(METHOD method) {
+ this.method = method;
+ }
+
+ /**
+ * Returns the view field value.
+ *
+ * @return The view.
+ */
+ public String getView() {
+ return view;
+ }
+
+ /**
+ * Sets the view field value.
+ *
+ * @param view The view to set.
+ */
+ public void setView(String view) {
+ this.view = view;
+ }
+
+}
diff --git a/src/com/epam/devteam/action/account/ActivateAccountAction.java b/src/com/epam/devteam/action/account/ActivateAccountAction.java
new file mode 100644
index 0000000..31a6935
--- /dev/null
+++ b/src/com/epam/devteam/action/account/ActivateAccountAction.java
@@ -0,0 +1,98 @@
+package com.epam.devteam.action.account;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+
+public class ActivateAccountAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ActivateAccountAction.class);
+ private DaoFactory factory;
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ String tempId = request.getParameter("id");
+ boolean idFieldEqualsNull = false;
+ boolean idFieldEmpty = false;
+ int id = 0;
+ idFieldEqualsNull = RequestFieldsValidator.equalNull(tempId);
+ if (idFieldEqualsNull) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.debug("Id form field equals null.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ idFieldEmpty = RequestFieldsValidator.empty(tempId);
+ if (idFieldEmpty) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.debug("Id form field value is empty.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ try {
+ id = Integer.parseInt(tempId);
+ } catch (IllegalArgumentException e) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.debug("Id format is wrong.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ try {
+ userDao().updateActiveStatus(id, true);
+ ;
+ LOGGER.warn("User has been deleted.");
+ } catch (DaoException e) {
+ LOGGER.warn("User cannot be deleted.");
+ throw new ActionDatabaseFailException(e);
+ }
+ session.setAttribute("success", "account.activateSuccess");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "success");
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get user dao. It initializes dao during the first use.
+ *
+ * @return The user.
+ * @throws DaoException If something fails.
+ */
+ private UserDao userDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getUserDao();
+ }
+ return dao;
+ }
+
+}
diff --git a/src/com/epam/devteam/action/account/ChangeAccountPasswordAction.java b/src/com/epam/devteam/action/account/ChangeAccountPasswordAction.java
new file mode 100644
index 0000000..3ae5455
--- /dev/null
+++ b/src/com/epam/devteam/action/account/ChangeAccountPasswordAction.java
@@ -0,0 +1,166 @@
+package com.epam.devteam.action.account;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+import com.epam.devteam.util.validator.ValidationException;
+
+/**
+ * The ChangeAccountPasswordAction is used to set new account
+ * password. At first it checks old password. If old password is correct new
+ * password will be set.
+ *
+ * @date Jan 17, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ChangeAccountPasswordAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(CreateAccountAction.class);
+ private DaoFactory factory;
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ User user = (User) session.getAttribute("user");
+ String tempId = request.getParameter("id");
+ UserRole userRole = user.getRole();
+ String oldPassword = request.getParameter("old-password");
+ String newPassword1 = request.getParameter("new-password1");
+ String newPassword2 = request.getParameter("new-password2");
+ int id = 0;
+ boolean passwordFieldsNull = false;
+ boolean newPasswordEmpty = false;
+ boolean newPasswordValid = false;
+ try {
+ id = Integer.parseInt(tempId);
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Id field is not valid.");
+ throw new ActionBadRequestException();
+ }
+ session.setAttribute("oldPassword", oldPassword);
+ session.setAttribute("newPassword1", newPassword1);
+ session.setAttribute("newPassword2", newPassword2);
+ LOGGER.debug(oldPassword);
+ LOGGER.debug(newPassword1);
+ LOGGER.debug(newPassword2);
+ LOGGER.debug(user.getPassword());
+ if (!userRole.equals(UserRole.ADMINISTRATOR)) {
+ if (!user.getPassword().equals(oldPassword)) {
+ session.removeAttribute("passwordError");
+ session.setAttribute("oldPasswordError",
+ "account.oldPasswordWrong");
+ LOGGER.debug("Old password value is wrong.");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ request.getHeader("referer"));
+ }
+ session.removeAttribute("oldPasswordError");
+
+ }
+ passwordFieldsNull = RequestFieldsValidator.equalNull(newPassword1,
+ newPassword2);
+ if (passwordFieldsNull) {
+ LOGGER.warn("Old password field is not valid.");
+ throw new ActionBadRequestException();
+ }
+ newPasswordEmpty = RequestFieldsValidator.empty(newPassword1);
+ if (newPasswordEmpty) {
+ session.setAttribute("passwordError", "account.passwordEmpty");
+ LOGGER.debug("New password value is empty.");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ request.getHeader("referer"));
+ }
+ try {
+ newPasswordValid = RequestFieldsValidator
+ .passwordValid(newPassword1);
+ } catch (ValidationException e) {
+ LOGGER.debug("Password cannot be validated.");
+ throw new ActionException();
+ }
+ if (!newPasswordValid) {
+ session.setAttribute("passwordError", "account.passwordNotValid");
+ LOGGER.debug("New password value is not valid.");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ request.getHeader("referer"));
+ }
+ if (!newPassword1.equals(newPassword2)) {
+ session.setAttribute("passwordError", "account.passwordsDontMatch");
+ LOGGER.debug("Passwords don't match.");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ request.getHeader("referer"));
+ }
+ try {
+ userDao().updatePassword(id, newPassword1);
+ LOGGER.debug("Password has been changed.");
+ } catch (DaoException e) {
+ LOGGER.warn("Password cannot be changed.");
+ throw new ActionDatabaseFailException(e);
+ }
+ if (user.getId() == id) {
+ user.setPassword(newPassword1);
+ session.setAttribute("user", user);
+ }
+ session.setAttribute("success", "account.changePasswordSuccess");
+ session.setAttribute("link", "do/edit-account?id=" + id);
+ session.removeAttribute("oldPassword");
+ session.removeAttribute("newPassword1");
+ session.removeAttribute("newPassword2");
+ session.removeAttribute("oldPasswordError");
+ session.removeAttribute("emailError");
+ session.removeAttribute("passwordError");
+ session.removeAttribute("error");
+
+ return new ActionResult(ActionResult.METHOD.REDIRECT, "success");
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get user dao. It initializes dao during the first use.
+ *
+ * @return The user.
+ * @throws DaoException If something fails.
+ */
+ private UserDao userDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getUserDao();
+ }
+ return dao;
+ }
+}
diff --git a/src/com/epam/devteam/action/account/CreateAccountAction.java b/src/com/epam/devteam/action/account/CreateAccountAction.java
new file mode 100644
index 0000000..4f8094b
--- /dev/null
+++ b/src/com/epam/devteam/action/account/CreateAccountAction.java
@@ -0,0 +1,199 @@
+/**
+ *
+ */
+package com.epam.devteam.action.account;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.entity.user.Customer;
+import com.epam.devteam.entity.user.Employee;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+import com.epam.devteam.util.validator.ValidationException;
+
+/**
+ * The CreateAccountAction class is used to save new user to
+ * database. If every field is available new user will save to database and will
+ * save in session. Success message contains a link to edit new account. If new
+ * user was created by administrator success message will contain link to manage
+ * new account. Implements Action interface.
+ *
+ * @date Jan 4, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class CreateAccountAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(CreateAccountAction.class);
+ private DaoFactory factory;
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ User user;
+ UserRole role;
+ HttpSession session = request.getSession();
+ User currentUser = (User) session.getAttribute("user");
+ String email = request.getParameter("email");
+ String password1 = request.getParameter("password1");
+ String password2 = request.getParameter("password2");
+ String stringRole = request.getParameter("role");
+ int id = 0;
+ boolean formFieldsEqualNull = false;
+ boolean emailEmpty = false;
+ boolean emailValid = false;
+ boolean passwordEmpty = false;
+ boolean passwordValid = false;
+ LOGGER.debug("Create user action...");
+ formFieldsEqualNull = RequestFieldsValidator.equalNull(stringRole,
+ email, password1, password2);
+ if (formFieldsEqualNull) {
+ LOGGER.warn("Form fields are not valid.");
+ throw new ActionBadRequestException();
+ }
+ try {
+ role = UserRole.valueOf(stringRole);
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Unknown role: " + stringRole);
+ throw new ActionBadRequestException(e);
+ }
+ session.setAttribute("email", email);
+ session.setAttribute("password1", password1);
+ session.setAttribute("password2", password2);
+ session.removeAttribute("emailError");
+ session.removeAttribute("passwordError");
+ emailEmpty = RequestFieldsValidator.empty(email);
+ if (emailEmpty) {
+ session.setAttribute("emailError", "account.emailEmpty");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ "create-account");
+ }
+ try {
+ emailValid = RequestFieldsValidator.emailValid(email);
+ } catch (ValidationException e) {
+ LOGGER.warn("Email " + email + " cannot be validated.");
+ throw new ActionException(e);
+ }
+ if (!emailValid) {
+ session.setAttribute("emailError", "account.emailNotValid");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ "create-account");
+ }
+ try {
+ user = userDao().find(email);
+ } catch (DaoException e) {
+ LOGGER.warn("User existence cannot be checked.");
+ throw new ActionDatabaseFailException(e);
+ }
+ if (user != null) {
+ session.setAttribute("error", "account.userAlreadyExists");
+ LOGGER.debug("User " + email + " is already exist");
+ return new ActionResult(ActionResult.METHOD.REDIRECT, "error");
+ }
+ passwordEmpty = RequestFieldsValidator.empty(password1);
+ if (passwordEmpty) {
+ session.setAttribute("passwordError", "account.passwordEmpty");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ "create-account");
+ }
+ try {
+ passwordValid = RequestFieldsValidator.passwordValid(password1);
+ } catch (ValidationException e) {
+ LOGGER.warn("Password cannot be validated.");
+ throw new ActionException(e);
+ }
+ if (!passwordValid) {
+ session.setAttribute("passwordError", "account.passwordNotValid");
+ LOGGER.debug("Password is not valid");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ "create-account");
+ }
+ if (!password1.equals(password2)) {
+ session.setAttribute("passwordError", "account.passwordsDontMatch");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ "create-account");
+ }
+ switch (role) {
+ case CUSTOMER:
+ user = new Customer();
+ break;
+ default:
+ user = new Employee();
+ break;
+ }
+ user.setEmail(email);
+ user.setPassword(password1);
+ user.setRole(role);
+ try {
+ id = userDao().createWithIdReturn(user);
+ user.setId(id);
+ LOGGER.debug("User " + user.getEmail()
+ + " has been created. User id: " + user.getId());
+ } catch (DaoException e) {
+ LOGGER.warn("User cannot be created.");
+ throw new ActionDatabaseFailException(e);
+ }
+ if (currentUser == null) {
+ session.setAttribute("user", user);
+ }
+ session.setAttribute("success", "account.createSuccess");
+ session.setAttribute("link", "do/edit-account?id=" + user.getId());
+ session.removeAttribute("email");
+ session.removeAttribute("password1");
+ session.removeAttribute("password2");
+ session.removeAttribute("error");
+ session.removeAttribute("emailError");
+ session.removeAttribute("passwordError");
+ return new ActionResult(ActionResult.METHOD.REDIRECT, "success");
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get user dao. It initializes dao during the first use.
+ *
+ * @return The user.
+ * @throws DaoException If something fails.
+ */
+ private UserDao userDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getUserDao();
+ }
+ return dao;
+ }
+
+}
diff --git a/src/com/epam/devteam/action/account/DeactivateAccountAction.java b/src/com/epam/devteam/action/account/DeactivateAccountAction.java
new file mode 100644
index 0000000..a1d1592
--- /dev/null
+++ b/src/com/epam/devteam/action/account/DeactivateAccountAction.java
@@ -0,0 +1,114 @@
+package com.epam.devteam.action.account;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+
+/**
+ * The DeactivateAccountAction class is used to deactivate user. It
+ * changes user active status at not active.
+ *
+ * @date Jan 17, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class DeactivateAccountAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(DeactivateAccountAction.class);
+ private DaoFactory factory;
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ User user = (User) session.getAttribute("user");
+ String tempId = request.getParameter("id");
+ boolean idFieldEqualsNull = false;
+ boolean idFieldEmpty = false;
+ int id = 0;
+ idFieldEqualsNull = RequestFieldsValidator.equalNull(tempId);
+ if (idFieldEqualsNull) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.debug("Id form field equals null.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ idFieldEmpty = RequestFieldsValidator.empty(tempId);
+ if (idFieldEmpty) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.debug("Id form field value is empty.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ try {
+ id = Integer.parseInt(tempId);
+ } catch (IllegalArgumentException e) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.debug("Id format is wrong.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ if ((user.getId() == id)
+ && user.getRole().equals(UserRole.ADMINISTRATOR)) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.debug("It is immpossible to delete administrator.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ try {
+ userDao().updateActiveStatus(id, false);
+ LOGGER.warn("User has been deactivated.");
+ } catch (DaoException e) {
+ LOGGER.warn("User cannot be deactivated.");
+ throw new ActionDatabaseFailException(e);
+ }
+ session.setAttribute("success", "account.deactivateSuccess");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "success");
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get user dao. It initializes dao during the first use.
+ *
+ * @return The user.
+ * @throws DaoException If something fails.
+ */
+ private UserDao userDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getUserDao();
+ }
+ return dao;
+ }
+
+}
diff --git a/src/com/epam/devteam/action/account/SaveAccountAction.java b/src/com/epam/devteam/action/account/SaveAccountAction.java
new file mode 100644
index 0000000..861754e
--- /dev/null
+++ b/src/com/epam/devteam/action/account/SaveAccountAction.java
@@ -0,0 +1,249 @@
+package com.epam.devteam.action.account;
+
+import java.sql.Date;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Locale;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.entity.user.Customer;
+import com.epam.devteam.entity.user.Employee;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+import com.epam.devteam.util.validator.FieldType;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+import com.epam.devteam.util.validator.ValidationException;
+
+/**
+ * The SaveAccountAction is used to save account changes.
+ *
+ * @date Jan 8, 2014
+ * @author Andrey Kovalskiy
+ */
+public class SaveAccountAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(SaveAccountAction.class);
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ User user;
+ User accountBefore = (User) session.getAttribute("account");
+ User accountAfter;
+ UserRole role;
+ String tempId = request.getParameter("id");
+ String tempRole = request.getParameter("role");
+ String tempActive = request.getParameter("is-active");
+ String firstName = request.getParameter("first-name");
+ String lastName = request.getParameter("last-name");
+ String company = request.getParameter("company");
+ String position = request.getParameter("position");
+ String address = request.getParameter("address");
+ String phone = request.getParameter("phone");
+ String qualification = request.getParameter("qualification");
+ String day = request.getParameter("day");
+ String month = request.getParameter("month");
+ String year = request.getParameter("year");
+ Date date;
+ int id = 0;
+ boolean active = false;
+ boolean fieldsEqualsNull = false;
+ boolean fieldsEmpty = false;
+ boolean fieldsLengthValid = false;
+ boolean changed = false;
+ fieldsEqualsNull = RequestFieldsValidator.equalNull(tempId, tempRole,
+ tempActive);
+ if (fieldsEqualsNull) {
+ LOGGER.warn("Fields are not valid: null");
+ throw new ActionBadRequestException();
+ }
+ fieldsEmpty = RequestFieldsValidator
+ .empty(tempId, tempRole, tempActive);
+ if (fieldsEmpty) {
+ LOGGER.warn("Fields are not valid: empty");
+ throw new ActionBadRequestException();
+ }
+ try {
+ id = Integer.parseInt(tempId);
+ } catch (IllegalArgumentException e) {
+ LOGGER.debug("Id format is wrong.");
+ throw new ActionBadRequestException(e);
+ }
+ try {
+ role = UserRole.valueOf(tempRole);
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Unknown role: " + tempRole);
+ throw new ActionBadRequestException(e);
+ }
+ try {
+ active = Boolean.parseBoolean(tempActive);
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Activity status is wrong: " + tempActive);
+ throw new ActionBadRequestException(e);
+ }
+ try {
+ date = new Date(new SimpleDateFormat("yyyy-MM-d", Locale.ENGLISH)
+ .parse(year + "-" + month + "-" + day).getTime());
+ } catch (ParseException e) {
+ LOGGER.warn("Birth date is wrong");
+ throw new ActionBadRequestException(e);
+ }
+ try {
+ switch (accountBefore.getRole()) {
+ case CUSTOMER:
+ fieldsLengthValid = RequestFieldsValidator.lengthValid(
+ FieldType.INPUT_TEXT, firstName, lastName, company,
+ position, address, phone);
+ break;
+ default:
+ fieldsLengthValid = RequestFieldsValidator.lengthValid(
+ FieldType.INPUT_TEXT, firstName, lastName,
+ qualification, address, phone);
+ break;
+ }
+ } catch (ValidationException e) {
+ LOGGER.warn("Fields cannot be validated.");
+ throw new ActionBadRequestException(e);
+ }
+ if (!fieldsLengthValid) {
+ LOGGER.warn("Fields length is not valid.");
+ throw new ActionBadRequestException();
+ }
+ switch (role) {
+ case CUSTOMER:
+ Customer customer = new Customer();
+ customer.setCompany(company);
+ customer.setPosition(position);
+ accountAfter = customer;
+ break;
+ default:
+ Employee employee = new Employee();
+ employee.setQualification(qualification);
+ accountAfter = employee;
+ break;
+ }
+ accountAfter.setEmail(accountBefore.getEmail());
+ accountAfter.setRegistrationDate(accountBefore.getRegistrationDate());
+ accountAfter.setId(id);
+ accountAfter.setRole(role);
+ accountAfter.setActive(active);
+ accountAfter.setFirstName(firstName);
+ accountAfter.setLastName(lastName);
+ accountAfter.setBirthDate(date);
+ accountAfter.setAddress(address);
+ accountAfter.setPhone(phone);
+ changed = isChanged(accountAfter, accountBefore);
+ if (!changed) {
+ LOGGER.debug("There is no changes to save.");
+ session.setAttribute("accountEditError", "account.notChanged");
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ request.getHeader("referer"));
+ }
+ LOGGER.debug("Account has been changed.");
+ try {
+ userDao().update(accountAfter);
+ LOGGER.debug("User " + accountAfter.getEmail()
+ + " has been updated.");
+ } catch (DaoException e) {
+ LOGGER.warn("User cannot be updated.");
+ throw new ActionDatabaseFailException(e);
+ }
+ user = (User) session.getAttribute("user");
+ if (user.getId() == accountAfter.getId()) {
+ LOGGER.debug("User's own account.");
+ accountAfter.setEmail(user.getEmail());
+ accountAfter.setRegistrationDate(user.getRegistrationDate());
+ session.setAttribute("user", accountAfter);
+ }
+ session.removeAttribute("account");
+ session.removeAttribute("accountEditError");
+ session.setAttribute("success", "account.saveSuccess");
+ session.setAttribute("link",
+ "do/edit-account?id=" + accountAfter.getId());
+ return new ActionResult(ActionResult.METHOD.REDIRECT, "success");
+ }
+
+ /**
+ * Is used to check whether account was modified.
+ *
+ * @param accountAfter Account
+ * @param accountBefore
+ * @return
+ */
+ private boolean isChanged(User accountAfter, User accountBefore) {
+ Customer customerAfter;
+ Customer customerBefore;
+ Employee employeeAfter;
+ Employee employeeBefore;
+ if (accountAfter.getRole() != accountBefore.getRole()
+ || accountAfter.isActive() != accountBefore.isActive()
+ || !accountAfter.getFirstName().equals(
+ accountBefore.getFirstName())
+ || !accountAfter.getLastName().equals(
+ accountBefore.getLastName())
+ || !accountAfter.getBirthDate().equals(
+ accountBefore.getBirthDate())
+ || !accountAfter.getAddress()
+ .equals(accountBefore.getAddress())
+ || !accountAfter.getPhone().equals(accountBefore.getPhone())) {
+ return true;
+ }
+ switch (accountAfter.getRole()) {
+ case CUSTOMER:
+ customerAfter = (Customer) accountAfter;
+ customerBefore = (Customer) accountBefore;
+ if (!customerAfter.getCompany().equals(customerBefore.getCompany())
+ || !customerAfter.getPosition().equals(
+ customerBefore.getPosition())) {
+ return true;
+ }
+ default:
+ employeeAfter = (Employee) accountAfter;
+ employeeBefore = (Employee) accountBefore;
+ if (!employeeAfter.getQualification().equals(
+ employeeBefore.getQualification())) {
+ return true;
+ }
+
+ }
+ return false;
+
+ }
+
+ /**
+ * Is used to get user dao. It initializes dao during the first use.
+ *
+ * @return The user.
+ * @throws DaoException If something fails.
+ */
+ private UserDao userDao() throws DaoException {
+ if (dao == null) {
+ dao = DaoFactory.getDaoFactory().getUserDao();
+ }
+ return dao;
+ }
+}
\ No newline at end of file
diff --git a/src/com/epam/devteam/action/account/ShowAccountsManagementPageAction.java b/src/com/epam/devteam/action/account/ShowAccountsManagementPageAction.java
new file mode 100644
index 0000000..ba3cfbc
--- /dev/null
+++ b/src/com/epam/devteam/action/account/ShowAccountsManagementPageAction.java
@@ -0,0 +1,108 @@
+package com.epam.devteam.action.account;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+
+/**
+ * The ShowAccountsManagementPageAction is used to show user
+ * accounts management page.
+ *
+ * @date Jan 17, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowAccountsManagementPageAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ShowAccountsManagementPageAction.class);
+ private DaoFactory factory;
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ ListShowCreateAccountPageAction returns create-account.jsp
+ * pages's name and method to show page.
+ *
+ * @date Jan 15, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowCreateAccountPageAction implements Action {
+ private final static Logger LOGGER = Logger
+ .getLogger(ShowCreateAccountPageAction.class);
+
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ LOGGER.debug("Action starts.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "create-account");
+ }
+
+}
diff --git a/src/com/epam/devteam/action/account/ShowEditAccountPageAction.java b/src/com/epam/devteam/action/account/ShowEditAccountPageAction.java
new file mode 100644
index 0000000..754452f
--- /dev/null
+++ b/src/com/epam/devteam/action/account/ShowEditAccountPageAction.java
@@ -0,0 +1,110 @@
+package com.epam.devteam.action.account;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+
+/**
+ * The ShowEditAccountPageAction returns edit-account.jsp page's
+ * name and method to show page.
+ *
+ * @date Jan 15, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowEditAccountPageAction implements Action {
+ private final static Logger LOGGER = Logger
+ .getLogger(ShowEditAccountPageAction.class);
+ private DaoFactory factory;
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ User user = (User) session.getAttribute("user");
+ String stringAccountId = request.getParameter("id");
+ User account;
+ int accountId = 0;
+ LOGGER.debug("Show edit account page action...");
+ if (stringAccountId == null || stringAccountId.isEmpty()) {
+ LOGGER.debug("Id is empty.");
+ session.setAttribute("error", "error.badRequest");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ try {
+ accountId = Integer.parseInt(stringAccountId);
+ } catch (IllegalArgumentException e) {
+ LOGGER.debug("Id format is wrong.");
+ session.setAttribute("error", "error.badRequest");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ if (user.getRole().equals(UserRole.ADMINISTRATOR)) {
+ try {
+ account = userDao().find(accountId);
+ } catch (DaoException e) {
+ LOGGER.warn("User cannot be found because of database fail.");
+ throw new ActionDatabaseFailException(e);
+ }
+ } else {
+ if (user.getId() != accountId) {
+ LOGGER.debug("User " + user.getEmail()
+ + " tried to edit other user's account.");
+ session.setAttribute("error", "error.badRequest");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+ account = user;
+ }
+ LOGGER.debug(account);
+ session.setAttribute("account", account);
+ session.removeAttribute("error");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "edit-account");
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get user dao. It initializes dao during the first use.
+ *
+ * @return The user.
+ * @throws DaoException If something fails.
+ */
+ private UserDao userDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getUserDao();
+ }
+ return dao;
+ }
+}
diff --git a/src/com/epam/devteam/action/account/SigninAction.java b/src/com/epam/devteam/action/account/SigninAction.java
new file mode 100644
index 0000000..6511459
--- /dev/null
+++ b/src/com/epam/devteam/action/account/SigninAction.java
@@ -0,0 +1,112 @@
+/**
+ *
+ */
+package com.epam.devteam.action.account;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.UserDao;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+
+/**
+ * The SigninAction is used to sign in. Implements
+ * Action interface.
+ *
+ * @see com.epam.devteam.action.Action
+ *
+ * @date Jan 5, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class SigninAction implements Action {
+ private static final Logger LOGGER = Logger.getLogger(SigninAction.class);
+ private ActionResult result = new ActionResult();
+ private UserDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ String email = request.getParameter("email");
+ String password = request.getParameter("password");
+ User user;
+ boolean fieldsEqualNull = false;
+ boolean fieldsEmpty = false;
+ fieldsEqualNull = RequestFieldsValidator.equalNull(email, password);
+ if (fieldsEqualNull) {
+ LOGGER.debug("Sign in form fields are not valid.");
+ throw new ActionBadRequestException();
+ }
+ fieldsEmpty = RequestFieldsValidator.empty(email, password);
+ if (fieldsEmpty) {
+ session.setAttribute("signInError", "account.enterEmailAndPassword");
+ LOGGER.debug("Email or/and password are empty.");
+ return new ActionResult(ActionResult.METHOD.REDIRECT, "main");
+ }
+ session.setAttribute("email", email);
+ try {
+ user = userDao().find(email, password);
+ } catch (DaoException e) {
+ LOGGER.warn("Request cannot be executed.");
+ throw new ActionBadRequestException(e);
+ }
+ if (user == null) {
+ session.setAttribute("signInError", "account.notFound");
+ LOGGER.debug("Account not found.");
+ result.setMethod(ActionResult.METHOD.REDIRECT);
+ result.setView("main");
+ return result;
+ }
+ if (user.isActive() == false) {
+ session.setAttribute("error", "account.notActive");
+ session.setAttribute("link", "do/contacts");
+ LOGGER.debug("Account is not active.");
+ result.setMethod(ActionResult.METHOD.REDIRECT);
+ result.setView("error");
+ return result;
+ }
+ LOGGER.debug(user.getPassword());
+ session.setAttribute("user", user);
+ session.removeAttribute("email");
+ session.removeAttribute("signInError");
+ session.removeAttribute("error");
+ session.removeAttribute("link");
+ LOGGER.debug("User " + user.getEmail() + " has been registered.");
+ result.setMethod(ActionResult.METHOD.REDIRECT);
+ result.setView("main");
+ return result;
+ }
+
+ /**
+ * Is used to get user dao. It initializes dao during the first use.
+ *
+ * @return The user.
+ * @throws DaoException If something fails.
+ */
+ private UserDao userDao() throws DaoException {
+ if (dao == null) {
+ dao = DaoFactory.getDaoFactory().getUserDao();
+ }
+ return dao;
+ }
+}
diff --git a/src/com/epam/devteam/action/account/SignoutAction.java b/src/com/epam/devteam/action/account/SignoutAction.java
new file mode 100644
index 0000000..dc38eb7
--- /dev/null
+++ b/src/com/epam/devteam/action/account/SignoutAction.java
@@ -0,0 +1,46 @@
+/**
+ *
+ */
+package com.epam.devteam.action.account;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.entity.user.User;
+
+/**
+ * @date Jan 6, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class SignoutAction implements Action {
+
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ User user = (User) session.getAttribute("user");
+ switch (user.getRole()) {
+ case CUSTOMER:
+ case MANAGER:
+ session.removeAttribute("orders");
+ session.removeAttribute("order");
+ session.removeAttribute("feedback");
+ break;
+ case ADMINISTRATOR:
+ session.removeAttribute("users");
+ session.removeAttribute("accountToManage");
+ break;
+ default:
+ break;
+ }
+ session.removeAttribute("user");
+ session.removeAttribute("error");
+ session.removeAttribute("success");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "main");
+ }
+}
diff --git a/src/com/epam/devteam/action/exception/ActionBadRequestException.java b/src/com/epam/devteam/action/exception/ActionBadRequestException.java
new file mode 100644
index 0000000..f3cc579
--- /dev/null
+++ b/src/com/epam/devteam/action/exception/ActionBadRequestException.java
@@ -0,0 +1,53 @@
+/**
+ *
+ */
+package com.epam.devteam.action.exception;
+
+/**
+ * The ActionBadRequestException is used when request fields are
+ * not correct or absent.
+ *
+ * @date Jan 15, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ActionBadRequestException extends ActionException {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Initializes a newly created {@code Object} object.
+ */
+ public ActionBadRequestException() {
+ super();
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param message the detail message.
+ * @param cause the cause.
+ */
+ public ActionBadRequestException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ */
+ public ActionBadRequestException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new exception with the specified cause and a detail message
+ * of (cause==null ? null : cause.toString()).
+ *
+ * @param cause the cause.
+ */
+ public ActionBadRequestException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/src/com/epam/devteam/action/exception/ActionDatabaseFailException.java b/src/com/epam/devteam/action/exception/ActionDatabaseFailException.java
new file mode 100644
index 0000000..cdb0345
--- /dev/null
+++ b/src/com/epam/devteam/action/exception/ActionDatabaseFailException.java
@@ -0,0 +1,52 @@
+/**
+ *
+ */
+package com.epam.devteam.action.exception;
+
+/**
+ * The ActionDatabaseFailException is udsed when it is impossible
+ * to work with database.
+ *
+ * @date Jan 15, 2014
+ * @author Andrey Kovalskiy
+ */
+public class ActionDatabaseFailException extends ActionException {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Initializes a newly created {@code Object} object.
+ */
+ public ActionDatabaseFailException() {
+ super();
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param message the detail message.
+ * @param cause the cause.
+ */
+ public ActionDatabaseFailException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ */
+ public ActionDatabaseFailException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new exception with the specified cause and a detail message
+ * of (cause==null ? null : cause.toString()).
+ *
+ * @param cause the cause.
+ */
+ public ActionDatabaseFailException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/src/com/epam/devteam/action/exception/ActionException.java b/src/com/epam/devteam/action/exception/ActionException.java
new file mode 100644
index 0000000..1793d1b
--- /dev/null
+++ b/src/com/epam/devteam/action/exception/ActionException.java
@@ -0,0 +1,53 @@
+/**
+ *
+ */
+package com.epam.devteam.action.exception;
+
+/**
+ * The ActionException is used when something fails during action.
+ * It is a wrapper for all exceptions that occur during action performing.
+ *
+ * @date Dec 14, 2013
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ActionException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructs a new exception with null as its detail message.
+ */
+ public ActionException() {
+ super();
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param message the detail message.
+ * @param cause the cause.
+ */
+ public ActionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ */
+ public ActionException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new exception with the specified cause and a detail message
+ * of (cause==null ? null : cause.toString()).
+ *
+ * @param cause the cause.
+ */
+ public ActionException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/src/com/epam/devteam/action/feedback/CreateFeedbackAction.java b/src/com/epam/devteam/action/feedback/CreateFeedbackAction.java
new file mode 100644
index 0000000..74323b1
--- /dev/null
+++ b/src/com/epam/devteam/action/feedback/CreateFeedbackAction.java
@@ -0,0 +1,186 @@
+package com.epam.devteam.action.feedback;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.Date;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.entity.feedback.Feedback;
+import com.epam.devteam.entity.order.Order;
+import com.epam.devteam.entity.order.OrderStatus;
+import com.epam.devteam.entity.user.Employee;
+import com.epam.devteam.service.FeedbackService;
+import com.epam.devteam.service.ServiceException;
+import com.epam.devteam.util.validator.FieldType;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+import com.epam.devteam.util.validator.ValidationException;
+
+public class CreateFeedbackAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(CreateFeedbackAction.class);
+ private static final long fileMaxSize = 10485760L;
+ private static final ServletFileUpload fileUpload = initServletFileUpload();
+ private ActionResult result = new ActionResult();
+ private FeedbackService feedbackCreator = new FeedbackService();
+
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ Employee manager;
+ Feedback feedback;
+ ListDownloadFileAction is used to download files from order or
+ * feedback.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class DownloadFileAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(DownloadFileAction.class);
+ private static final int DEFAULT_BUFFER_SIZE = 10240;
+ private ActionResult result = new ActionResult();
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ Order order;
+ Feedback feedback;
+ String source = request.getParameter("source");
+ BufferedInputStream input = null;
+ BufferedOutputStream output = null;
+ String fileName;
+ byte[] fileContent;
+ LOGGER.debug("Download file action...");
+ if ("order".equals(source)) {
+ order = (Order) session.getAttribute("order");
+ fileName = order.getFileName();
+ fileContent = order.getFileContent();
+ } else if ("feedback".equals(source)) {
+ feedback = (Feedback) session.getAttribute("feedback");
+ fileName = feedback.getFileName();
+ fileContent = feedback.getFileContent();
+ } else {
+ LOGGER.warn("Source not defined.");
+ throw new ActionBadRequestException();
+ }
+ response.reset();
+ response.setBufferSize(DEFAULT_BUFFER_SIZE);
+ response.setContentType("application/octet-stream");
+ response.setHeader("Content-Length", fileName);
+ response.setHeader("Content-Disposition", "attachment; filename=\""
+ + fileName + "\"");
+ try {
+ input = new BufferedInputStream(new ByteArrayInputStream(
+ fileContent), DEFAULT_BUFFER_SIZE);
+ output = new BufferedOutputStream(response.getOutputStream(),
+ DEFAULT_BUFFER_SIZE);
+ byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
+ int length;
+ while ((length = input.read(buffer)) > 0) {
+ output.write(buffer, 0, length);
+ }
+ } catch (IOException e) {
+ LOGGER.debug("File cannot be downloaded.");
+ throw new ActionException();
+ } finally {
+ close(output);
+ close(input);
+ }
+ result.setMethod(ActionResult.METHOD.REDIRECT);
+ result.setView(request.getHeader("referer"));
+ return result;
+ }
+
+ /**
+ * Is used to close input and output streams.
+ *
+ * @param resource The resource to close.
+ */
+ private void close(Closeable resource) {
+ if (resource != null) {
+ try {
+ resource.close();
+ } catch (IOException e) {
+ LOGGER.warn("Resource cannot be closed.");
+ }
+ }
+ }
+}
diff --git a/src/com/epam/devteam/action/general/SetLanguageAction.java b/src/com/epam/devteam/action/general/SetLanguageAction.java
new file mode 100644
index 0000000..ff03e4d
--- /dev/null
+++ b/src/com/epam/devteam/action/general/SetLanguageAction.java
@@ -0,0 +1,40 @@
+package com.epam.devteam.action.general;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import javax.servlet.jsp.jstl.core.Config;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+
+/**
+ * The SetLanguageAction to set localization.
+ *
+ * @date Jan 13, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class SetLanguageAction implements Action {
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ String locale = request.getParameter("locale");
+ Config.set(session, Config.FMT_LOCALE, new java.util.Locale(locale));
+ return new ActionResult(ActionResult.METHOD.REDIRECT,
+ request.getHeader("referer"));
+ }
+
+}
diff --git a/src/com/epam/devteam/action/general/ShowAboutUsPageAction.java b/src/com/epam/devteam/action/general/ShowAboutUsPageAction.java
new file mode 100644
index 0000000..835b9a9
--- /dev/null
+++ b/src/com/epam/devteam/action/general/ShowAboutUsPageAction.java
@@ -0,0 +1,39 @@
+package com.epam.devteam.action.general;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+
+/**
+ * The ShowAboutUsPageAction is used to show page with information about company.
+ *
+ * @date Jan 18, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowAboutUsPageAction implements Action {
+ private final static Logger LOGGER = Logger
+ .getLogger(ShowAboutUsPageAction.class);
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ LOGGER.debug("Show about us page action...");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "about-us");
+ }
+
+}
diff --git a/src/com/epam/devteam/action/general/ShowContactsPageAction.java b/src/com/epam/devteam/action/general/ShowContactsPageAction.java
new file mode 100644
index 0000000..36fc8cd
--- /dev/null
+++ b/src/com/epam/devteam/action/general/ShowContactsPageAction.java
@@ -0,0 +1,38 @@
+package com.epam.devteam.action.general;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+
+/**
+ * The ShowContactsPageAction is used to show page with contacts.
+ *
+ * @date Jan 18, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowContactsPageAction implements Action {
+ private final static Logger LOGGER = Logger
+ .getLogger(ShowContactsPageAction.class);
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ LOGGER.debug("Show contacts page action...");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "contacts");
+ }
+}
diff --git a/src/com/epam/devteam/action/general/ShowErrorPageAction.java b/src/com/epam/devteam/action/general/ShowErrorPageAction.java
new file mode 100644
index 0000000..f80bfd5
--- /dev/null
+++ b/src/com/epam/devteam/action/general/ShowErrorPageAction.java
@@ -0,0 +1,26 @@
+/**
+ *
+ */
+package com.epam.devteam.action.general;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+
+/**
+ * @date Jan 5, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowErrorPageAction implements Action {
+
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ return new ActionResult(ActionResult.METHOD.FORWARD, "error");
+ }
+
+}
diff --git a/src/com/epam/devteam/action/general/ShowMainPageAction.java b/src/com/epam/devteam/action/general/ShowMainPageAction.java
new file mode 100644
index 0000000..5a7c006
--- /dev/null
+++ b/src/com/epam/devteam/action/general/ShowMainPageAction.java
@@ -0,0 +1,42 @@
+/**
+ *
+ */
+package com.epam.devteam.action.general;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+
+/**
+ * The ShowMainPageAction returns main.jsp page's name and method
+ * to show it.
+ *
+ * @date Jan 5, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowMainPageAction implements Action {
+ private final static Logger LOGGER = Logger
+ .getLogger(ShowMainPageAction.class);
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ LOGGER.debug("Action starts.");
+ return new ActionResult(ActionResult.METHOD.FORWARD, "main");
+ }
+}
diff --git a/src/com/epam/devteam/action/general/ShowSuccessPageAction.java b/src/com/epam/devteam/action/general/ShowSuccessPageAction.java
new file mode 100644
index 0000000..201a43c
--- /dev/null
+++ b/src/com/epam/devteam/action/general/ShowSuccessPageAction.java
@@ -0,0 +1,26 @@
+/**
+ *
+ */
+package com.epam.devteam.action.general;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+
+/**
+ * @date Jan 10, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowSuccessPageAction implements Action {
+
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ return new ActionResult(ActionResult.METHOD.FORWARD, "success");
+ }
+
+}
diff --git a/src/com/epam/devteam/action/order/CreateOrderAction.java b/src/com/epam/devteam/action/order/CreateOrderAction.java
new file mode 100644
index 0000000..0cd8060
--- /dev/null
+++ b/src/com/epam/devteam/action/order/CreateOrderAction.java
@@ -0,0 +1,221 @@
+package com.epam.devteam.action.order;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.sql.Date;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.commons.fileupload.FileItem;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.disk.DiskFileItemFactory;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.OrderDao;
+import com.epam.devteam.entity.order.Order;
+import com.epam.devteam.entity.order.OrderStatus;
+import com.epam.devteam.entity.order.OrderSubject;
+import com.epam.devteam.entity.user.Customer;
+import com.epam.devteam.util.validator.FieldType;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+import com.epam.devteam.util.validator.ValidationException;
+
+/**
+ * The CreateOrderAction is used to create an order.
+ *
+ * @date Jan 11, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class CreateOrderAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(CreateOrderAction.class);
+ private static final long fileMaxSize = 10485760L;
+ private static final ServletFileUpload fileUpload = initServletFileUpload();
+ private ActionResult result = new ActionResult();
+ private DaoFactory factory;
+ private OrderDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ Customer customer;
+ Order order;
+ ListClass ...
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class SaveOrderAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(CreateOrderAction.class);
+ private static final long fileMaxSize = 10485760L;
+ private static final ServletFileUpload fileUpload = initServletFileUpload();
+ private ActionResult result = new ActionResult();
+ private DaoFactory factory;
+ private OrderDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ Customer customer;
+ Order order;
+ ListShowAllOrdersPageAction is used to show all orders.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowAllOrdersPageAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ShowCustomerOrdersPageAction.class);
+ private ActionResult result = new ActionResult();
+ private DaoFactory factory;
+ private OrderDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ ListShowCreateOrderPageAction class is used to show page where
+ * customer can create a new order.
+ *
+ * @date Jan 11, 2014
+ * @author Andrey Kovalskiy
+ */
+public class ShowCreateOrderPageAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ShowCreateOrderPageAction.class);
+ private ActionResult result = new ActionResult();
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ LOGGER.debug("Show create order page...");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("create-order");
+ return result;
+ }
+
+}
diff --git a/src/com/epam/devteam/action/order/ShowCustomerOrdersPageAction.java b/src/com/epam/devteam/action/order/ShowCustomerOrdersPageAction.java
new file mode 100644
index 0000000..7cb8f92
--- /dev/null
+++ b/src/com/epam/devteam/action/order/ShowCustomerOrdersPageAction.java
@@ -0,0 +1,120 @@
+package com.epam.devteam.action.order;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.OrderDao;
+import com.epam.devteam.entity.order.Order;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.util.validator.RequestFieldsValidator;
+
+/**
+ * The ShowCustomerOrdersPageAction is used to show page where user
+ * can check all orders created by him.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowCustomerOrdersPageAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ShowCustomerOrdersPageAction.class);
+ private ActionResult result = new ActionResult();
+ private DaoFactory factory;
+ private OrderDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ User user = (User) session.getAttribute("user");
+ ListShowEditOrderPageAction is used to prepare and show page
+ * where customer can edit his order.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowEditOrderPageAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ShowEditOrderPageAction.class);
+ private ActionResult result = new ActionResult();
+ private DaoFactory factory;
+ private OrderDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session;
+ User user;
+ Order order;
+ int id;
+ LOGGER.debug("Show order page action...");
+ try {
+ id = Integer.valueOf(request.getParameter("id"));
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Order id is not valid.");
+ throw new ActionBadRequestException(e);
+ }
+ session = request.getSession();
+ order = (Order) session.getAttribute("order");
+ user = (User) session.getAttribute("user");
+ if ((order != null) && (order.getId() == id)) {
+ if (order.getCustomer().getId() == user.getId()) {
+ LOGGER.debug("Order from session.");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("edit-order");
+ return result;
+ } else {
+ LOGGER.debug("Order cannot be edited: access denied.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ }
+ try {
+ LOGGER.debug("Order from database.");
+ order = orderDao().find(id);
+ } catch (DaoException e) {
+ LOGGER.warn("Order cannot be fetched from database.");
+ throw new ActionBadRequestException(e);
+ }
+ if (order == null) {
+ LOGGER.debug("Order with required id is absent.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ if (order.getCustomer().getId() != user.getId()) {
+ LOGGER.debug("Order cannot be edited: access denied.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ session.setAttribute("order", order);
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("edit-order");
+ return result;
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get order dao. It initializes dao during the first use.
+ *
+ * @return The order dao.
+ * @throws DaoException If something fails.
+ */
+ private OrderDao orderDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getOrderDao();
+ }
+ return dao;
+ }
+}
diff --git a/src/com/epam/devteam/action/order/ShowOrderPageAction.java b/src/com/epam/devteam/action/order/ShowOrderPageAction.java
new file mode 100644
index 0000000..038c326
--- /dev/null
+++ b/src/com/epam/devteam/action/order/ShowOrderPageAction.java
@@ -0,0 +1,131 @@
+package com.epam.devteam.action.order;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.FeedbackDao;
+import com.epam.devteam.dao.OrderDao;
+import com.epam.devteam.entity.feedback.Feedback;
+import com.epam.devteam.entity.order.Order;
+import com.epam.devteam.entity.order.OrderStatus;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+
+/**
+ * The ShowOrderPageAction is used to show page with required id.
+ * Any customer can't watch other customers' orders. Managers can watch every
+ * order.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowOrderPageAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ShowOrderPageAction.class);
+ private ActionResult result = new ActionResult();
+ private OrderDao orderDao;
+ private FeedbackDao feedbackDao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ LOGGER.debug("Show order page action...");
+ HttpSession session;
+ User user;
+ Order order;
+ OrderStatus status;
+ Feedback feedback;
+ int id;
+ try {
+ id = Integer.valueOf(request.getParameter("id"));
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Order id is not valid.");
+ throw new ActionBadRequestException(e);
+ }
+ try {
+ order = orderDao().find(id);
+ } catch (DaoException e) {
+ LOGGER.warn("Order cannot be fetched from database.");
+ throw new ActionBadRequestException(e);
+ }
+ session = request.getSession();
+ if (order == null) {
+ LOGGER.debug("Order with required id not found.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ user = (User) session.getAttribute("user");
+ if (user.getRole().equals(UserRole.CUSTOMER)) {
+ if (order.getCustomer().getId() != user.getId()) {
+ LOGGER.debug("Order cannot be shown: access denied.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ }
+ status = order.getStatus();
+ if (status.equals(OrderStatus.ACCEPTED)
+ || status.equals(OrderStatus.DENIED)) {
+ try {
+ feedback = feedbackDao().findByOrderId(id);
+ session.setAttribute("feedback", feedback);
+ } catch (DaoException e) {
+ LOGGER.warn("Feedback cannot be fetched from database.");
+ }
+ } else {
+ session.removeAttribute("feedback");
+ }
+ session.setAttribute("order", order);
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("order");
+ return result;
+ }
+
+ /**
+ * Is used to get order dao. It initializes dao during the first use.
+ *
+ * @return The order dao.
+ * @throws DaoException If something fails.
+ */
+ private OrderDao orderDao() throws DaoException {
+ if (orderDao == null) {
+ orderDao = DaoFactory.getDaoFactory().getOrderDao();
+ }
+ return orderDao;
+ }
+
+ /**
+ * Is used to get feedback dao. It initializes dao during the first use.
+ *
+ * @return The feedback dao.
+ * @throws DaoException If something fails.
+ */
+ private FeedbackDao feedbackDao() throws DaoException {
+ if (feedbackDao == null) {
+ feedbackDao = DaoFactory.getDaoFactory().getFeedbackDao();
+ }
+ return feedbackDao;
+ }
+}
diff --git a/src/com/epam/devteam/action/order/ShowProcessOrderPageAction.java b/src/com/epam/devteam/action/order/ShowProcessOrderPageAction.java
new file mode 100644
index 0000000..dbe8586
--- /dev/null
+++ b/src/com/epam/devteam/action/order/ShowProcessOrderPageAction.java
@@ -0,0 +1,116 @@
+package com.epam.devteam.action.order;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.OrderDao;
+import com.epam.devteam.entity.order.Order;
+import com.epam.devteam.entity.order.OrderStatus;
+
+/**
+ * The ShowProcessOrderPageAction is used to leave feedback for the
+ * order.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ShowProcessOrderPageAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(ShowProcessOrderPageAction.class);
+ private ActionResult result = new ActionResult();
+ private DaoFactory factory;
+ private OrderDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session = request.getSession();
+ String tempId = request.getParameter("id");
+ Order order = (Order) session.getAttribute("order");
+ int id;
+ LOGGER.debug("Show process order page action...");
+ try {
+ id = Integer.valueOf(tempId);
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Order id value is not valid.");
+ throw new ActionBadRequestException(e);
+ }
+ if ((order != null) && (order.getId() == id)) {
+ if (order.getStatus().equals(OrderStatus.PENDING)) {
+ LOGGER.debug("Order from session.");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("process-order");
+ return result;
+ } else {
+ LOGGER.debug("Order has already been processed");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ }
+ try {
+ LOGGER.debug("Order from database.");
+ order = orderDao().find(id);
+ } catch (DaoException e) {
+ LOGGER.warn("Order cannot be fetched from database.");
+ throw new ActionBadRequestException(e);
+ }
+ if ((order == null) || (!order.getStatus().equals(OrderStatus.PENDING))) {
+ LOGGER.debug("Order cannot be processed.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ session.setAttribute("order", order);
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("process-order");
+ return result;
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get order dao. It initializes dao during the first use.
+ *
+ * @return The order dao.
+ * @throws DaoException If something fails.
+ */
+ private OrderDao orderDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getOrderDao();
+ }
+ return dao;
+ }
+}
diff --git a/src/com/epam/devteam/action/order/TerminateOrderAction.java b/src/com/epam/devteam/action/order/TerminateOrderAction.java
new file mode 100644
index 0000000..6b52ce9
--- /dev/null
+++ b/src/com/epam/devteam/action/order/TerminateOrderAction.java
@@ -0,0 +1,118 @@
+package com.epam.devteam.action.order;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionException;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.OrderDao;
+import com.epam.devteam.entity.order.Order;
+import com.epam.devteam.entity.order.OrderStatus;
+import com.epam.devteam.entity.user.User;
+
+/**
+ * The TerminateOrderAction is used to terminate order. Only a
+ * customer who created order can terminate it.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class TerminateOrderAction implements Action {
+ private static final Logger LOGGER = Logger
+ .getLogger(TerminateOrderAction.class);
+ private ActionResult result = new ActionResult();
+ private DaoFactory factory;
+ private OrderDao dao;
+
+ /**
+ * Is used to perform required actions and define method and view for
+ * Controller. Returns result as ActionResult.
+ *
+ * @param request Request to process.
+ * @param response Response to send.
+ * @return ActionResult where to redirect user
+ * @throws ActionException If something fails during method performing.
+ */
+ @Override
+ public ActionResult execute(HttpServletRequest request,
+ HttpServletResponse response) throws ActionException {
+ HttpSession session;
+ User user;
+ Order order;
+ int id;
+ LOGGER.debug("Terminate order action...");
+ try {
+ id = Integer.valueOf(request.getParameter("id"));
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Order id is not valid.");
+ throw new ActionBadRequestException(e);
+ }
+ try {
+ order = orderDao().find(id);
+ } catch (DaoException e) {
+ LOGGER.warn("Order cannot be fetched from database.");
+ throw new ActionBadRequestException(e);
+ }
+ session = request.getSession();
+ if (order == null) {
+ LOGGER.debug("Order with required id is not found.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ user = (User) session.getAttribute("user");
+ if (order.getCustomer().getId() != user.getId()) {
+ LOGGER.debug("Order cannot be terminated: access denied.");
+ session.setAttribute("error", "error.badRequest");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("error");
+ return result;
+ }
+ try {
+ orderDao().updateStatus(id, OrderStatus.TERMINATED);
+ } catch (DaoException e) {
+ LOGGER.warn("Order status cannot be updated.");
+ throw new ActionBadRequestException(e);
+ }
+ session.setAttribute("success", "order.terminateSuccess");
+ result.setMethod(ActionResult.METHOD.FORWARD);
+ result.setView("success");
+ return result;
+ }
+
+ /**
+ * Is used to get dao factory. It initializes factory during the first use.
+ *
+ * @return Dao factory.
+ * @throws DaoException If something fails.
+ */
+ private DaoFactory daoFactory() throws DaoException {
+ if (factory == null) {
+ factory = DaoFactory.getDaoFactory();
+ }
+ return factory;
+ }
+
+ /**
+ * Is used to get order dao. It initializes dao during the first use.
+ *
+ * @return The order dao.
+ * @throws DaoException If something fails.
+ */
+ private OrderDao orderDao() throws DaoException {
+ if (dao == null) {
+ dao = daoFactory().getOrderDao();
+ }
+ return dao;
+ }
+
+}
diff --git a/src/com/epam/devteam/dao/AbstractDao.java b/src/com/epam/devteam/dao/AbstractDao.java
new file mode 100644
index 0000000..bbc8346
--- /dev/null
+++ b/src/com/epam/devteam/dao/AbstractDao.java
@@ -0,0 +1,55 @@
+/**
+ *
+ */
+package com.epam.devteam.dao;
+
+import com.epam.devteam.db.ConnectionPool;
+
+/**
+ * The AbstractDao determines constructors, fields, and methods
+ * that should has every dao class, which works with database.
+ *
+ * @date Jan 2, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public abstract class AbstractDao {
+
+ private ConnectionPool connectionPool;
+
+ /**
+ * Initializes a newly created {@code AbstractDao} object.
+ */
+ public AbstractDao() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code AbstractDao} object and connection
+ * with the given connection value.
+ *
+ * @param connection The connection to use to connect to the database.
+ */
+ public AbstractDao(ConnectionPool connectionPool) {
+ this.connectionPool = connectionPool;
+ }
+
+ /**
+ * Returns the connectionPool field value.
+ *
+ * @return the connectionPool
+ */
+ public ConnectionPool getConnectionPool() {
+ return connectionPool;
+ }
+
+ /**
+ * Sets the connectionPool field value.
+ *
+ * @param connectionPool the connectionPool to set
+ */
+ public void setConnectionPool(ConnectionPool connectionPool) {
+ this.connectionPool = connectionPool;
+ }
+
+}
diff --git a/src/com/epam/devteam/dao/Dao.java b/src/com/epam/devteam/dao/Dao.java
new file mode 100644
index 0000000..94e820a
--- /dev/null
+++ b/src/com/epam/devteam/dao/Dao.java
@@ -0,0 +1,71 @@
+/**
+ *
+ */
+package com.epam.devteam.dao;
+
+import java.util.List;
+
+/**
+ * The provides methods to work with database and required
+ * entities. Every dao class should instantiate this interface.
+ *
+ * @date Jan 2, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public interface DaoDaoFactory is used to get instances of required dao
+ * implementations.
+ *
* @date Dec 15, 2013
* @author Andrey Kovalskiy
*
*/
public abstract class DaoFactory {
private static final Logger LOGGER = Logger.getLogger(DaoFactory.class);
-
+ private static DatabaseType databaseType;
+
/**
- * Is used to set connection pool to the dao factory.
+ * Is used to get dao factory implementation to work with required database.
+ * Database type is defined in property file.
*
- * @param connectionPool The connection pool to set.
- */
- public abstract void setConnectionPool(ConnectionPool connectionPool);
-
- /**
- * Is used to take user dao.
- * @return The user dao implementation.
- * @throws DaoException If something fails.
- */
- public abstract UserDao takeUserDao() throws DaoException;
-
- /**
- * Is used to take dao factory implementation to work with required database.
* @param daoFactoryTypes The implementation type.
* @return The dao factory instance.
- * @throws DaoException If required databse type is not required.
+ * @throws DaoException If something wrong with database type or something
+ * fails with connection pool.
+ * @see DatabaseType
*/
- public static DaoFactory takeDaoFactory(DaoFactoryTypes daoFactoryTypes)
- throws DaoException {
+ public static DaoFactory getDaoFactory() throws DaoException {
DaoFactory daoFactory = null;
- switch (daoFactoryTypes) {
+ ConnectionPool connectionPool = null;
+ if (databaseType == null) {
+ initDatabaseType();
+ }
+ try {
+ connectionPool = ConnectionPool.getInstance();
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection pool cannot be initialized.");
+ throw new DaoException();
+ }
+ switch (databaseType) {
case POSTGRESQL:
- daoFactory = new PostgresqlDaoFactory();
+ daoFactory = new PostgresqlDaoFactory(connectionPool);
break;
default:
- LOGGER.error("Not available dao factory type!");
+ LOGGER.warn("Database type is defined but not available.");
throw new DaoException();
}
+
return daoFactory;
}
+ /**
+ * Is used to initialize current used database type during the first dao
+ * factory access.
+ *
+ * @throws DaoException If something fails with property manager or current
+ * database property is wrong.
+ * @see DatabaseType
+ */
+ private static void initDatabaseType() throws DaoException {
+ try {
+ PropertyManager propertyManager = PropertyManager.getInstance();
+ databaseType = DatabaseType.valueOf(propertyManager.getString(
+ "db.name").toUpperCase());
+ LOGGER.debug("Database type was initialized as " + databaseType);
+ } catch (PropertyManagerException e) {
+ LOGGER.warn("Database type can not be initialized.");
+ throw new DaoException();
+ }
+ }
+
+ /**
+ * Is used to get user dao.
+ *
+ * @return The user dao implementation.
+ * @throws DaoException If something fails.
+ */
+ public abstract UserDao getUserDao();
+
+ /**
+ * Is used to get order dao.
+ *
+ * @return The order dao implementation.
+ * @throws DaoException If something fails.
+ */
+ public abstract OrderDao getOrderDao();
+
+ /**
+ * Is used to get order feedback dao.
+ *
+ * @return The order dao implementation.
+ * @throws DaoException If something fails.
+ */
+ public abstract FeedbackDao getFeedbackDao();
+
}
diff --git a/src/com/epam/devteam/dao/DaoFactoryTypes.java b/src/com/epam/devteam/dao/DaoFactoryTypes.java
deleted file mode 100644
index e4dfbd8..0000000
--- a/src/com/epam/devteam/dao/DaoFactoryTypes.java
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- *
- */
-package com.epam.devteam.dao;
-
-/**
- * @date Dec 15, 2013
- * @author anjey
- *
- */
-public enum DaoFactoryTypes {
-
- POSTGRESQL;
-
-}
diff --git a/src/com/epam/devteam/dao/FeedbackDao.java b/src/com/epam/devteam/dao/FeedbackDao.java
new file mode 100644
index 0000000..59795af
--- /dev/null
+++ b/src/com/epam/devteam/dao/FeedbackDao.java
@@ -0,0 +1,26 @@
+package com.epam.devteam.dao;
+
+import com.epam.devteam.entity.feedback.Feedback;
+
+/**
+ * The FeedbackDao extends Dao interface and provides
+ * additional methods to work with database and feedback entities.
+ *
+ * @date Jan 20, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public interface FeedbackDao extends DaoOrderDao extends Dao interfaces and provides
+ * additional methods to work with database and Order entities.
+ *
+ * @date Jan 11, 2014
+ * @author Andrey Kovalskiy
+ */
+public interface OrderDao extends DaoUserDao interface extends Dao interface and
+ * provides additional methods to work with User> entity and database.
*
+ * @date Dec 15, 2014
+ * @author Andrey Kovalskiy
+ * @see com.epam.devteam.dao.Dao
+ * @see com.epam.devteam.entity.User
*/
-public interface UserDao {
-
- /**
- * Is used to create the given user in the database.
- * @param user The user to create.
- * @throws DaoException If something fails at database level.
- */
- void createUser(User user) throws DaoException;
-
- /**
- * Is used to find a user in the database by the given id, otherwise {@code null}.
- * @param id The id of the user to be returned.
- * @return The user from the database with required id, otherwise {@code null}.
- * @throws DaoException If something fails at database level.
- */
- User findUser(Long id) throws DaoException;
-
- /**
- * Is used to find a user in the database by email and password, otherwise {@code null}.
- * @param email The email of the user to be returned.
- * @param password The password of the user to be returned.
- * @return The user from the database with required email and password, otherwise {@code null}.
- * @throws DaoException If something fails at database level.
- */
- User findUser(String email, String password) throws DaoException;
-
- /**
- * Is used to update the given user.
- * @param user The user to update.
- * @throws DaoException If something fails at database level.
- */
- void updateUser(User user) throws DaoException;
-
- /**
- * Is used to delete the given user from the database.
- * @param user The user to delete.
- * @throws DaoException If something fails at database level.
- */
- void deleteUser(User user) throws DaoException;
-
- /**
- * Is used to get all of the users from the database.
- * @return The list of all users in the database.
- * @throws DaoException If something fails at database level.
- */
- List listUsers() throws DaoException;
-
+public interface UserDao extends Dao {
+
+
+ /**
+ * Is used to create and return id of a new object.
+ *
+ * @param object The object to create.
+ * @return Object id.
+ * @throws DaoException If something fails at database level
+ */
+ int createWithIdReturn(User object) throws DaoException;
+
+ /**
+ * Is used to get user by email. Method returns null if there is no user in
+ * database .
+ *
+ * @param email The user email.
+ * @return The user with the given email, null otherwise.
+ * @throws DaoException If something fails during method performing.
+ */
+ User find(String email) throws DaoException;
+
+ /**
+ * Is used to get user with the given email and password. Method returns
+ * null if there is no user in database .
+ *
+ * @param email The user email.
+ * @param password The user password.
+ * @return The user, null otherwise.
+ * @throws DaoException If something fails during method performing.
+ */
+ User find(String email, String password) throws DaoException;
+
+ /**
+ * Is used to set new status for a user wit the given id in database .
+ *
+ * @param id The id of the user.
+ * @param newStatus The status to be set.
+ * @throws DaoException If something fails during method performing.
+ */
+ void updateActiveStatus(int id, boolean newStatus) throws DaoException;
+
+ /**
+ * Is used to set new password for a user wit the given id in database .
+ *
+ * @param id The id of the user.
+ * @param newPassword The new password to be set.
+ * @throws DaoException If something fails during method performing.
+ */
+ void updatePassword(int id, String newPassword) throws DaoException;
+
}
diff --git a/src/com/epam/devteam/dao/impl/PostgresqlDaoFactory.java b/src/com/epam/devteam/dao/impl/PostgresqlDaoFactory.java
index f404f33..76410eb 100644
--- a/src/com/epam/devteam/dao/impl/PostgresqlDaoFactory.java
+++ b/src/com/epam/devteam/dao/impl/PostgresqlDaoFactory.java
@@ -3,10 +3,10 @@
*/
package com.epam.devteam.dao.impl;
-import java.sql.Connection;
-
import com.epam.devteam.dao.DaoException;
import com.epam.devteam.dao.DaoFactory;
+import com.epam.devteam.dao.FeedbackDao;
+import com.epam.devteam.dao.OrderDao;
import com.epam.devteam.dao.UserDao;
import com.epam.devteam.db.ConnectionPool;
@@ -20,33 +20,40 @@ public class PostgresqlDaoFactory extends DaoFactory {
private ConnectionPool connectionPool;
/**
- * Initializes a newly created {@code Object} object.
+ * Initializes a newly created {@code PostgresqlDaoFactory} object.
*/
- public PostgresqlDaoFactory() {
- super();
+ public PostgresqlDaoFactory(ConnectionPool connectionPool) {
+ this.connectionPool = connectionPool;
}
/**
- * Is used to set connection pool to the dao factory.
+ * Is used to get user dao.
*
- * @param connectionPool The connection pool to set.
+ * @return The request dao implementation.
+ * @throws DaoException If something fails.
*/
- @Override
- public void setConnectionPool(ConnectionPool connectionPool) {
- this.connectionPool = connectionPool;
+ public UserDao getUserDao() {
+ return new PostgresqlUserDao(connectionPool);
}
-
+
/**
- * Is used to take user dao.
- * @return The user dao implementation.
+ * Is used to get order dao.
+ *
+ * @return The order dao implementation.
* @throws DaoException If something fails.
*/
- @Override
- public UserDao takeUserDao() throws DaoException {
- Connection connection = connectionPool.takeConnection();
- if (connection == null) {
- throw new DaoException("Cannot take connection!");
- }
- return new PostgresqlUserDao(connection);
+ public OrderDao getOrderDao() {
+ return new PostgresqlOrderDao(connectionPool);
}
+
+ /**
+ * Is used to get order feedback dao.
+ *
+ * @return The order feedback dao implementation.
+ * @throws DaoException If something fails.
+ */
+ public FeedbackDao getFeedbackDao() {
+ return new PostgresqlFeedbackDao(connectionPool);
+ }
+
}
diff --git a/src/com/epam/devteam/dao/impl/PostgresqlFeedbackDao.java b/src/com/epam/devteam/dao/impl/PostgresqlFeedbackDao.java
new file mode 100644
index 0000000..3587f9e
--- /dev/null
+++ b/src/com/epam/devteam/dao/impl/PostgresqlFeedbackDao.java
@@ -0,0 +1,257 @@
+package com.epam.devteam.dao.impl;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.dao.AbstractDao;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.FeedbackDao;
+import com.epam.devteam.db.ConnectionPool;
+import com.epam.devteam.db.ConnectionPoolException;
+import com.epam.devteam.entity.feedback.Feedback;
+import com.epam.devteam.entity.user.Employee;
+
+/**
+ * The PostgresqlFeedbackDao implements FeedbackDao
+ * interface for Postgresql database.
+ *
+ * @date Jan 20, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class PostgresqlFeedbackDao extends AbstractDao implements FeedbackDao {
+ private static final Logger LOGGER = Logger
+ .getLogger(PostgresqlFeedbackDao.class);
+ private final static String sqlCreate = "INSERT INTO feedbacks (date, order_id, message, file_name, file_content, manager_id) VALUES (?,?,?,?,?,?)";
+ private final static String sqlFindByOrderId = "SELECT * FROM feedbacks JOIN users ON feedbacks.manager_id=users.id WHERE feedbacks.order_id=";
+
+ /**
+ * Initializes a newly created {@code PostgresqlFeedbackDao} object.
+ */
+ public PostgresqlFeedbackDao() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code PostgresqlFeedbackDao} object.
+ *
+ * @param connectionPool
+ */
+ public PostgresqlFeedbackDao(ConnectionPool connectionPool) {
+ super(connectionPool);
+ }
+
+ /**
+ * Is used to create the given feedback in the database.
+ *
+ * @param object The feedback to create.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public void create(Feedback object) throws DaoException {
+ LOGGER.debug("create()");
+ Feedback feedback;
+ Connection connection;
+ PreparedStatement statement;
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException();
+ }
+ feedback = (Feedback) object;
+ try {
+ statement = connection.prepareStatement(sqlCreate);
+ statement.setDate(1, feedback.getDate());
+ statement.setInt(2, feedback.getOrderId());
+ statement.setString(3, feedback.getMessage());
+ statement.setString(4, feedback.getFileName());
+ statement.setBytes(5, feedback.getFileContent());
+ statement.setInt(6, feedback.getManager().getId());
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ getConnectionPool().returnConnection(connection);
+ LOGGER.warn("Statement cannot be created.", e);
+ throw new DaoException();
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.", e);
+ throw new DaoException();
+ }
+ freeConnection(connection, statement);
+
+ }
+
+ /**
+ * Is used to return a feedback from the database by the given id, otherwise
+ * {@code null}.
+ *
+ * @param id The id of the feedback to be returned.
+ * @return The object from the database with required id, otherwise
+ * {@code null}.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public Feedback find(int id) throws DaoException {
+ LOGGER.warn("Method is not implemeted");
+ throw new DaoException();
+ }
+
+ /**
+ * Is used to update the given feedback.
+ *
+ * @param object The feedback to update.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public void update(Feedback object) throws DaoException {
+ LOGGER.warn("Method is not implemeted");
+ throw new DaoException();
+ }
+
+ /**
+ * Is used to delete the feedback with the given id from the database.
+ *
+ * @param id The id of the feedback to be deleted.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public void delete(int id) throws DaoException {
+ LOGGER.warn("Method is not implemeted");
+ throw new DaoException();
+ }
+
+ /**
+ * Is used to get all of the feedbacks from the database.
+ *
+ * @return The list of all feedbacks in the database.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public List list() throws DaoException {
+ LOGGER.warn("Method is not implemeted");
+ throw new DaoException();
+ }
+
+ /**
+ * Is used to get feedbacks from the database with paging.
+ *
+ * @param firstRow The row from where to start list feedbacks.
+ * @param rowNumber The number of feedbacks to list.
+ * @return The list of feedbacks in the database.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public List list(int firstRow, int rowNumber) throws DaoException {
+ LOGGER.warn("Method is not implemeted");
+ throw new DaoException();
+ }
+
+ /**
+ *
+ * Is used to find feedback by order id. if there is now feedback with
+ * required id it returns null.
+ *
+ * @param id The order id.
+ * @return The feedback, null otherwise.
+ * @throws DaoException If something fails during method performing.
+ */
+ @Override
+ public Feedback findByOrderId(int id) throws DaoException {
+ LOGGER.debug("findByOrderId()");
+ Feedback feedback;
+ Connection connection;
+ Statement statement;
+ ResultSet resultSet;
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException();
+ }
+ try {
+ statement = connection.createStatement();
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ getConnectionPool().returnConnection(connection);
+ LOGGER.warn("Statement cannot be created.", e);
+ throw new DaoException();
+ }
+ try {
+ resultSet = statement.executeQuery(sqlFindByOrderId + id + ";");
+ feedback = new Feedback();
+ if (resultSet.next()) {
+ feedback = createFeedback(resultSet);
+ }
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.", e);
+ throw new DaoException();
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return feedback;
+ }
+
+ /**
+ * Is used to create feedback from result set.
+ *
+ * @param resultSet The result set.
+ * @param customerFlag If true creates and sets the customer.
+ * @return The order.
+ * @throws SQLException If something fails.
+ */
+ private Feedback createFeedback(ResultSet resultSet) throws SQLException {
+ Feedback feedback = new Feedback();
+ feedback.setOrderId(resultSet.getInt("order_id"));
+ feedback.setDate(resultSet.getDate("date"));
+ feedback.setMessage(resultSet.getString("message"));
+ feedback.setFileName(resultSet.getString("file_name"));
+ feedback.setFileContent(resultSet.getBytes("file_content"));
+ Employee manager = new Employee();
+ manager.setId(resultSet.getInt("manager_id"));
+ manager.setFirstName(resultSet.getString("first_name"));
+ manager.setLastName(resultSet.getString("last_name"));
+ manager.setEmail(resultSet.getString("email"));
+ manager.setPhone(resultSet.getString("phone"));
+ manager.setAddress(resultSet.getString("address"));
+ feedback.setManager(manager);
+ return feedback;
+ }
+
+ /**
+ * Is used to close statement and return connection to the connection pool.
+ *
+ * @param connection The connection to return.
+ * @param statement The statement to close.
+ */
+ private void freeConnection(Connection connection, Statement statement) {
+ if (statement != null) {
+ try {
+ statement.close();
+ LOGGER.debug("Statement has been closed.");
+ } catch (SQLException e) {
+ LOGGER.warn("Statement cannot be closed.");
+ }
+ }
+ getConnectionPool().returnConnection(connection);
+ }
+}
diff --git a/src/com/epam/devteam/dao/impl/PostgresqlOrderDao.java b/src/com/epam/devteam/dao/impl/PostgresqlOrderDao.java
new file mode 100644
index 0000000..706129c
--- /dev/null
+++ b/src/com/epam/devteam/dao/impl/PostgresqlOrderDao.java
@@ -0,0 +1,475 @@
+/**
+ *
+ */
+package com.epam.devteam.dao.impl;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.dao.AbstractDao;
+import com.epam.devteam.dao.DaoException;
+import com.epam.devteam.dao.OrderDao;
+import com.epam.devteam.db.ConnectionPool;
+import com.epam.devteam.db.ConnectionPoolException;
+import com.epam.devteam.entity.order.Order;
+import com.epam.devteam.entity.order.OrderStatus;
+import com.epam.devteam.entity.order.OrderSubject;
+import com.epam.devteam.entity.user.Customer;
+
+/**
+ * @date Jan 11, 2014
+ * @author Andrey Kovalskiy
+ */
+public class PostgresqlOrderDao extends AbstractDao implements OrderDao {
+ private static final Logger LOGGER = Logger
+ .getLogger(PostgresqlOrderDao.class);
+
+ /**
+ * Initializes a newly created {@code connectionPool} object.
+ */
+ public PostgresqlOrderDao() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code connectionPool} object.
+ *
+ * @param connectionPool
+ */
+ public PostgresqlOrderDao(ConnectionPool connectionPool) {
+ super(connectionPool);
+ }
+
+ /**
+ * Is used to create the given order in the database.
+ *
+ * @param object The order to create.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public void create(Order object) throws DaoException {
+ Order order = (Order) object;
+ Connection connection;
+ PreparedStatement statement = null;
+ LOGGER.debug("Create order action...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("INSERT INTO orders (date, status, subject, topic, message, file_name, file_content, customer_id) VALUES (?,?,?,?,?,?,?,?)");
+ statement.setDate(1, order.getDate());
+ statement.setString(2, order.getStatus().name());
+ statement.setString(3, order.getSubject().name());
+ statement.setString(4, order.getTopic());
+ statement.setString(5, order.getMessage());
+ statement.setString(6, order.getFileName());
+ statement.setBytes(7, order.getFileContent());
+ statement.setInt(8, order.getCustomer().getId());
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ freeConnection(connection, statement);
+ }
+
+ /**
+ * Is used to return an order from the database by the given id, otherwise
+ * {@code null}.
+ *
+ * @param id The id of the order to be returned.
+ * @return The order from the database with required id, otherwise
+ * {@code null}.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public Order find(int id) throws DaoException {
+ Order order = null;
+ Connection connection;
+ Statement statement = null;
+ ResultSet resultSet;
+ LOGGER.debug("Find order...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection.createStatement();
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement
+ .executeQuery("SELECT orders.id, orders.date, orders.status, orders.subject, orders.topic, orders.message, orders.file_content, orders.file_name, orders.customer_id, users.first_name, users.last_name, users.company, users.position, users.phone, users.address, users.email FROM orders JOIN users ON orders.customer_id=users.id WHERE orders.id="
+ + id + ";");
+ LOGGER.debug("Statement has been executed.");
+ if (resultSet.next()) {
+ order = createOrder(resultSet, true);
+ }
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return order;
+ }
+
+ /**
+ * Is used to update the given order.
+ *
+ * @param object The order to update.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public void update(Order object) throws DaoException {
+ Order order = (Order) object;
+ Connection connection;
+ PreparedStatement statement = null;
+ LOGGER.debug("Update order action...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("UPDATE orders SET status = ?, date = ?, subject = ?, topic = ?, message = ?, file_name = ?, file_content = ? WHERE id = ?");
+ statement.setString(1, order.getStatus().name());
+ statement.setDate(2, order.getDate());
+ statement.setString(3, order.getSubject().name());
+ statement.setString(4, order.getTopic());
+ statement.setString(5, order.getMessage());
+ statement.setString(6, order.getFileName());
+ statement.setBytes(7, order.getFileContent());
+ statement.setInt(8, order.getId());
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ freeConnection(connection, statement);
+ }
+
+ /**
+ * Is used to delete the order with the given id from the database.
+ *
+ * @param id The id of the order to be deleted.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public void delete(int id) throws DaoException {
+ LOGGER.warn("Method is not implemented.");
+ throw new DaoException();
+ }
+
+ /**
+ * Is used to get all of the objects from the database.
+ *
+ * @return The list of all objects in the database.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public List list() throws DaoException {
+ List orders;
+ Order order;
+ Connection connection;
+ Statement statement = null;
+ ResultSet resultSet;
+ LOGGER.debug("List orders action...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection.createStatement();
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement
+ .executeQuery("SELECT orders.id, orders.date, orders.status, orders.subject, orders.topic, orders.message, orders.file_content, orders.file_name, orders.customer_id, users.first_name, users.last_name, users.company, users.position, users.phone, users.address, users.email FROM orders JOIN users ON orders.customer_id=users.id;");
+ LOGGER.debug("Statement has been executed.");
+ orders = new ArrayList();
+ while (resultSet.next()) {
+ order = createOrder(resultSet, true);
+ orders.add(order);
+ }
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return orders;
+ }
+
+ /**
+ * Is used to get orders from the database with paging.
+ *
+ * @param firstRow The row from where to start list orders.
+ * @param rowNumber The number of orders to list.
+ * @return The list of all orders in the database.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public List list(int firstRow, int rowNumber) throws DaoException {
+ List orders;
+ Order order;
+ Connection connection;
+ PreparedStatement statement = null;
+ ResultSet resultSet;
+ LOGGER.debug("List orders action...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("SELECT orders.id, orders.date, orders.status, orders.subject, orders.topic, orders.message, orders.file_content, orders.file_name, orders.customer_id, users.first_name, users.last_name, users.company, users.position, users.phone, users.address, users.email FROM orders JOIN users ON orders.customer_id=users.id WHERE orders.status != 'TERMINATED' ORDER BY date DESC OFFSET ? LIMIT ?");
+ statement.setInt(1, firstRow);
+ statement.setInt(2, rowNumber);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement.executeQuery();
+ LOGGER.debug("Statement has been executed.");
+ orders = new ArrayList();
+ while (resultSet.next()) {
+ order = createOrder(resultSet, true);
+ orders.add(order);
+ }
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return orders;
+ }
+
+ /**
+ * Is used to get orders from the database with paging. Method returns
+ * orders that were created by customer with the given id.
+ *
+ * @param id The customer id.
+ * @param firstRow The row from where to start list orders.
+ * @param rowNumber The number of orders to list.
+ * @return The list of all orders in the database.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public List listByCustomerId(int id, int firstRow, int rowNumber)
+ throws DaoException {
+ List orders;
+ Order order;
+ Connection connection;
+ PreparedStatement statement = null;
+ ResultSet resultSet;
+ LOGGER.debug("List orders by customer id action...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("SELECT id, date, status, subject, topic, message, file_content, file_name FROM orders WHERE customer_id = ? ORDER BY date DESC OFFSET ? LIMIT ?");
+ statement.setInt(1, id);
+ statement.setInt(2, firstRow);
+ statement.setInt(3, rowNumber);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement.executeQuery();
+ LOGGER.debug("Statement has been executed.");
+ orders = new ArrayList();
+ while (resultSet.next()) {
+ order = createOrder(resultSet, false);
+ orders.add(order);
+ }
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return orders;
+ }
+
+ /**
+ * Is used to update order status.
+ *
+ * @param id The order id to be updated.
+ * @param status The status to set.
+ * @throws DaoException If something fails.
+ */
+ @Override
+ public void updateStatus(int id, OrderStatus status) throws DaoException {
+ Connection connection;
+ PreparedStatement statement = null;
+ LOGGER.debug("Update order satus...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("UPDATE orders set status = ? WHERE id = ?");
+ statement.setString(1, status.name());
+ statement.setInt(2, id);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ freeConnection(connection, statement);
+ }
+
+ /**
+ * Is used to create order from result set.
+ *
+ * @param resultSet The result set.
+ * @param customerFlag If true creates and sets the customer.
+ * @return The order.
+ * @throws SQLException If something fails.
+ */
+ private Order createOrder(ResultSet resultSet, boolean customerFlag)
+ throws SQLException {
+ Order order = new Order();
+ order.setId(resultSet.getInt("id"));
+ order.setDate(resultSet.getDate("date"));
+ order.setStatus(OrderStatus.valueOf(resultSet.getString("status")));
+ order.setSubject(OrderSubject.valueOf(resultSet.getString("subject")));
+ order.setTopic(resultSet.getString("topic"));
+ order.setMessage(resultSet.getString("message"));
+ order.setFileName(resultSet.getString("file_name"));
+ order.setFileContent(resultSet.getBytes("file_content"));
+ if (customerFlag) {
+ Customer customer = new Customer();
+ customer.setId(resultSet.getInt("customer_id"));
+ customer.setFirstName(resultSet.getString("first_name"));
+ customer.setLastName(resultSet.getString("last_name"));
+ customer.setCompany(resultSet.getString("company"));
+ customer.setPosition(resultSet.getString("position"));
+ customer.setEmail(resultSet.getString("email"));
+ customer.setPhone(resultSet.getString("phone"));
+ customer.setAddress(resultSet.getString("address"));
+ order.setCustomer(customer);
+ }
+ return order;
+ }
+
+ /**
+ * Is used to close statement and return connection to the connection pool.
+ *
+ * @param connection The connection to return.
+ * @param statement The statement to close.
+ */
+ private void freeConnection(Connection connection, Statement statement) {
+ if (statement != null) {
+ try {
+ statement.close();
+ LOGGER.debug("Statement has been closed.");
+ } catch (SQLException e) {
+ LOGGER.warn("Statement cannot be closed.");
+ }
+ }
+ getConnectionPool().returnConnection(connection);
+ LOGGER.debug("Connection has been returned.");
+ }
+
+}
diff --git a/src/com/epam/devteam/dao/impl/PostgresqlUserDao.java b/src/com/epam/devteam/dao/impl/PostgresqlUserDao.java
index 13b6a5f..c742167 100644
--- a/src/com/epam/devteam/dao/impl/PostgresqlUserDao.java
+++ b/src/com/epam/devteam/dao/impl/PostgresqlUserDao.java
@@ -1,9 +1,8 @@
-/**
- *
- */
package com.epam.devteam.dao.impl;
import java.sql.Connection;
+import java.sql.Date;
+import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@@ -12,91 +11,716 @@
import org.apache.log4j.Logger;
+import com.epam.devteam.dao.AbstractDao;
import com.epam.devteam.dao.DaoException;
import com.epam.devteam.dao.UserDao;
-import com.epam.devteam.entity.User;
-
-/**
- * @date Dec 15, 2013
- * @author anjey
- *
- */
-public class PostgresqlUserDao implements UserDao {
+import com.epam.devteam.db.ConnectionPool;
+import com.epam.devteam.db.ConnectionPoolException;
+import com.epam.devteam.entity.user.Customer;
+import com.epam.devteam.entity.user.Employee;
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+
+public class PostgresqlUserDao extends AbstractDao implements UserDao {
private static final Logger LOGGER = Logger
.getLogger(PostgresqlUserDao.class);
- private Connection connection;
/**
- * Initializes a newly created {@code PostgresqlUserDao} object.
+ * Initializes a newly created {@code PostgresqlCustomerDao} object.
*/
public PostgresqlUserDao() {
super();
}
/**
- * Initializes a newly created {@code PostgresqlUserDao} object and
+ * Initializes a newly created {@code PostgresqlCustomerDao} object and
* connection with the given connection value.
*
* @param connection The connection to use to connect to the database.
*/
- public PostgresqlUserDao(Connection connection) {
- this.connection = connection;
+ public PostgresqlUserDao(ConnectionPool connectionPool) {
+ setConnectionPool(connectionPool);
}
+ /**
+ * Is used to create the given user in the database.
+ *
+ * @param object The user to create.
+ * @throws DaoException If something fails at database level.
+ */
@Override
- public void createUser(User user) throws DaoException {
- // TODO Auto-generated method stub
-
+ public void create(User object) throws DaoException {
+ User user;
+ Connection connection;
+ PreparedStatement statement = null;
+ LOGGER.debug("Create user...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ switch (object.getRole()) {
+ case CUSTOMER:
+ Customer customer = (Customer) object;
+ statement = connection
+ .prepareStatement("INSERT INTO users (email, password, registration_date, role, is_active, first_name, last_name, birth_date, address, phone, company, position) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
+ statement.setString(11, customer.getCompany());
+ statement.setString(12, customer.getPosition());
+ user = customer;
+ break;
+ default:
+ Employee employee = (Employee) object;
+ statement = connection
+ .prepareStatement("INSERT INTO users (email, password, registration_date, role, is_active, first_name, last_name, birth_date, address, phone, qualification) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
+ statement.setString(11, employee.getQualification());
+ user = employee;
+ break;
+ }
+ statement.setString(1, user.getEmail());
+ statement.setString(2, user.getPassword());
+ statement.setDate(3, new Date(new java.util.Date().getTime()));
+ statement.setString(4, user.getRole().name());
+ statement.setBoolean(5, true);
+ statement.setString(6, user.getFirstName());
+ statement.setString(7, user.getLastName());
+ statement.setDate(8, user.getBirthDate());
+ statement.setString(9, user.getAddress());
+ statement.setString(10, user.getPhone());
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ freeConnection(connection, statement);
}
+ /**
+ * Is used to create and return id of a new user.
+ *
+ * @param object The user to create.
+ * @return User id.
+ * @throws DaoException If something fails at database level
+ */
@Override
- public User findUser(Long id) throws DaoException {
- // TODO Auto-generated method stub
- return null;
+ public int createWithIdReturn(User object) throws DaoException {
+ Connection connection;
+ PreparedStatement statement = null;
+ ResultSet resultSet;
+ User user = (User) object;
+ int id = 0;
+ LOGGER.debug("Create user with id return...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Conection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("INSERT INTO users (email, password, registration_date, role, is_active) VALUES (?,?,?,?,?) RETURNING id");
+ statement.setString(1, user.getEmail());
+ statement.setString(2, user.getPassword());
+ statement.setDate(3, new Date(new java.util.Date().getTime()));
+ statement.setString(4, user.getRole().name());
+ statement.setBoolean(5, true);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement.executeQuery();
+ if (resultSet.next()) {
+ id = resultSet.getInt("id");
+ }
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return id;
}
+ /**
+ * Is used to return a user from the database by the given id, otherwise
+ * {@code null}.
+ *
+ * @param id The id of the user to be returned.
+ * @return The user from the database with required id, otherwise
+ * {@code null}.
+ * @throws DaoException If something fails at database level.
+ */
@Override
- public User findUser(String email, String password) throws DaoException {
- // TODO Auto-generated method stub
- return null;
+ public User find(int id) throws DaoException {
+ Connection connection;
+ PreparedStatement statement = null;
+ ResultSet resultSet;
+ User user = null;
+ LOGGER.debug("Find user...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connecton has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("SELECT users.id, users.email, users.password, users.registration_date, users.role, users.is_active, users.first_name, users.last_name, users.birth_date, users.phone, users.address, users.company, users.position, users.qualification FROM users WHERE (users.id=?)");
+ statement.setInt(1, id);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement.executeQuery();
+ if (resultSet.next()) {
+ UserRole role;
+ try {
+ role = UserRole.valueOf(resultSet.getString("role"));
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Unknown role: " + resultSet.getString("role"));
+ throw new DaoException();
+ }
+ switch (role) {
+ case CUSTOMER:
+ Customer customer = new Customer();
+ customer.setCompany(resultSet.getString("company"));
+ customer.setPosition(resultSet.getString("position"));
+ user = customer;
+ break;
+ default:
+ Employee employee = new Employee();
+ employee.setQualification(resultSet
+ .getString("qualification"));
+ user = employee;
+ break;
+ }
+ user.setId(resultSet.getInt("id"));
+ user.setEmail(resultSet.getString("email"));
+ user.setPassword(resultSet.getString("password"));
+ user.setRole(role);
+ user.setActive(resultSet.getBoolean("is_active"));
+ user.setRegistrationDate(resultSet.getDate("registration_date"));
+ user.setFirstName(resultSet.getString("first_name"));
+ user.setLastName(resultSet.getString("last_name"));
+ user.setBirthDate(resultSet.getDate("birth_date"));
+ user.setAddress(resultSet.getString("address"));
+ user.setPhone(resultSet.getString("phone"));
+ LOGGER.debug("Statement has been executed.");
+ }
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return user;
}
+ /**
+ * Is used to update the given user.
+ *
+ * @param object The user to update.
+ * @throws DaoException If something fails at database level.
+ */
@Override
- public void updateUser(User user) throws DaoException {
- // TODO Auto-generated method stub
-
+ public void update(User object) throws DaoException {
+ User user;
+ Connection connection;
+ PreparedStatement statement = null;
+ LOGGER.debug("Update user...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ switch (object.getRole()) {
+ case CUSTOMER:
+ Customer customer = (Customer) object;
+ statement = connection
+ .prepareStatement("UPDATE users set role = ?, is_active = ?, first_name = ?, last_name = ?, birth_date = ?, address = ?, phone = ?, company = ?, position = ? WHERE id = ?");
+ statement.setString(8, customer.getCompany());
+ statement.setString(9, customer.getPosition());
+ statement.setInt(10, customer.getId());
+ user = customer;
+ break;
+ default:
+ Employee employee = (Employee) object;
+ statement = connection
+ .prepareStatement("UPDATE users set role = ?, is_active = ?, first_name = ?, last_name = ?, birth_date = ?, address = ?, phone = ?, qualification = ? WHERE id = ?");
+ statement.setString(8, employee.getQualification());
+ statement.setInt(9, employee.getId());
+ user = employee;
+ break;
+ }
+ statement.setString(1, user.getRole().name());
+ statement.setBoolean(2, user.isActive());
+ statement.setString(3, user.getFirstName());
+ statement.setString(4, user.getLastName());
+ statement.setDate(5, user.getBirthDate());
+ statement.setString(6, user.getAddress());
+ statement.setString(7, user.getPhone());
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.", e);
+ throw new DaoException(e);
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ freeConnection(connection, statement);
}
+ /**
+ * Is used to delete the object with the given id from the database.
+ *
+ * @param id The id of the object to be deleted.
+ * @throws DaoException If something fails at database level.
+ */
@Override
- public void deleteUser(User user) throws DaoException {
- // TODO Auto-generated method stub
-
+ public void delete(int id) throws DaoException {
+ throw new DaoException("Unsupported operation.");
}
+ /**
+ * Is used to get all of the users from the database.
+ *
+ * @return The list of all users in the database.
+ * @throws DaoException If something fails at database level.
+ */
@Override
- public List listUsers() throws DaoException {
- List users = null;
- User user = null;
+ public List list() throws DaoException {
+ List users;
+ Connection connection;
Statement statement = null;
- ResultSet resultSet = null;
+ ResultSet resultSet;
+ LOGGER.debug("List users...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
try {
statement = connection.createStatement();
- LOGGER.debug("A statement was created");
- resultSet = statement.executeQuery("SELECT * FROM users");
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement
+ .executeQuery("SELECT users.id, users.email, users.password, users.registration_date, users.role, users.is_active, users.first_name, users.last_name, users.birth_date, users.address, users.phone, users.qualification, users.company, users.position FROM users ORDER BY users.id");
+ LOGGER.debug("Statement was executed.");
+ User user;
users = new ArrayList();
while (resultSet.next()) {
- user = new User();
- user.setId(resultSet.getLong("id"));
+ UserRole role;
+ try {
+ role = UserRole.valueOf(resultSet.getString("role"));
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Unknown role: " + resultSet.getString("role"));
+ throw new DaoException(e);
+ }
+ switch (role) {
+ case CUSTOMER:
+ Customer customer = new Customer();
+ customer.setCompany(resultSet.getString("company"));
+ customer.setPosition(resultSet.getString("position"));
+ user = customer;
+ break;
+ default:
+ Employee employee = new Employee();
+ employee.setQualification(resultSet
+ .getString("qualification"));
+ user = employee;
+ break;
+ }
+ user.setId(resultSet.getInt("id"));
+ user.setEmail(resultSet.getString("email"));
user.setPassword(resultSet.getString("password"));
- user.setFirstname(resultSet.getString("firstname"));
- user.setLastname(resultSet.getString("lastname"));
- user.setPatronymic(resultSet.getString("patronymic"));
- user.setBirthdate(resultSet.getDate("birthdate"));
+ user.setRole(role);
+ user.setActive(resultSet.getBoolean("is_active"));
+ user.setRegistrationDate(resultSet.getDate("registration_date"));
+ user.setFirstName(resultSet.getString("first_name"));
+ user.setLastName(resultSet.getString("last_name"));
+ user.setBirthDate(resultSet.getDate("birth_date"));
+ user.setAddress(resultSet.getString("address"));
+ user.setPhone(resultSet.getString("phone"));
+ users.add(user);
+ LOGGER.debug("Statement has been executed.");
+ }
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return users;
+ }
+
+ /**
+ * Is used to get active users from the database with paging.
+ *
+ * @param firstrow The row from where to start list user.
+ * @param rownumber The number of users to list.
+ * @param limit The number of users to list.
+ * @return The list of all users in the database.
+ * @throws DaoException If something fails at database level.
+ */
+ @Override
+ public List list(int firstRow, int rowNumber) throws DaoException {
+ List users;
+ Connection connection;
+ PreparedStatement statement = null;
+ ResultSet resultSet;
+ LOGGER.debug("List users...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("SELECT users.id, users.email, users.registration_date, users.role, users.is_active, users.first_name, users.last_name FROM users ORDER BY users.id OFFSET ? LIMIT ?");
+ statement.setInt(1, firstRow);
+ statement.setInt(2, rowNumber);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement.executeQuery();
+ LOGGER.debug("Statement was executed.");
+ User user;
+ users = new ArrayList();
+ while (resultSet.next()) {
+ UserRole role;
+ try {
+ role = UserRole.valueOf(resultSet.getString("role"));
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Unknown role: " + resultSet.getString("role"));
+ throw new DaoException();
+ }
+ user = new User();
+ user.setId(resultSet.getInt("id"));
+ user.setEmail(resultSet.getString("email"));
+ user.setActive(resultSet.getBoolean("is_active"));
+ user.setRole(role);
+ user.setRegistrationDate(resultSet.getDate("registration_date"));
+ user.setFirstName(resultSet.getString("first_name"));
+ user.setLastName(resultSet.getString("last_name"));
users.add(user);
+ LOGGER.debug("Statement has been executed.");
}
} catch (SQLException e) {
- LOGGER.warn("Can't create a statement.");
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
}
+ freeConnection(connection, statement);
return users;
}
-}
+
+ /**
+ * Is used to get user with the given email and password. Method returns
+ * null if there is no user in database .
+ *
+ * @param email The user email.
+ * @param password The user password.
+ * @return The user, null otherwise.
+ * @throws DaoException If something fails during method performing.
+ */
+ @Override
+ public User find(String email, String password) throws DaoException {
+ User user = null;
+ Connection connection;
+ PreparedStatement statement = null;
+ ResultSet resultSet;
+ LOGGER.debug("Find user by email and password...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("SELECT users.id, users.registration_date, users.role, users.is_active, users.birth_date, users.first_name, users.last_name, users.address, users. phone, users.company, users.position, users.qualification FROM users WHERE (users.email=? AND users.password=?)");
+ statement.setString(1, email);
+ statement.setString(2, password);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement.executeQuery();
+ LOGGER.debug("Statement was executed.");
+ if (resultSet.next()) {
+ UserRole role;
+ try {
+ role = UserRole.valueOf(resultSet.getString("role"));
+ } catch (IllegalArgumentException e) {
+ LOGGER.warn("Unknown role: " + resultSet.getString("role"));
+ throw new DaoException();
+ }
+ switch (role) {
+ case CUSTOMER:
+ Customer customer = new Customer();
+ customer.setCompany(resultSet.getString("company"));
+ customer.setPosition(resultSet.getString("position"));
+ user = customer;
+ break;
+ default:
+ Employee employee = new Employee();
+ employee.setQualification(resultSet
+ .getString("qualification"));
+ user = employee;
+ break;
+ }
+ user.setId(resultSet.getInt("id"));
+ user.setEmail(email);
+ user.setPassword(password);
+ user.setRole(role);
+ user.setActive(resultSet.getBoolean("is_active"));
+ user.setRegistrationDate(resultSet.getDate("registration_date"));
+ user.setFirstName(resultSet.getString("first_name"));
+ user.setLastName(resultSet.getString("last_name"));
+ user.setBirthDate(resultSet.getDate("birth_date"));
+ user.setAddress(resultSet.getString("address"));
+ user.setPhone(resultSet.getString("phone"));
+ LOGGER.debug("Statement has been executed.");
+ }
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return user;
+ }
+
+ /**
+ * Is used to get user by email. Method returns null if there is no user in
+ * database.
+ *
+ * @param email The user email.
+ * @return The user with the given email, null otherwise.
+ * @throws DaoException If something fails during method performing.
+ */
+ @Override
+ public User find(String email) throws DaoException {
+ User user = null;
+ Connection connection;
+ Statement statement = null;
+ ResultSet resultSet;
+ LOGGER.debug("Find user by email...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection.createStatement();
+ LOGGER.debug("Statement has been created");
+ } catch (SQLException e) {
+ LOGGER.warn("Statement cannot be created.");
+ freeConnection(connection, statement);
+ throw new DaoException(e);
+ }
+ try {
+ resultSet = statement
+ .executeQuery("SELECT users.id FROM users WHERE users.email='"
+ + email + "';");
+ if (resultSet.next()) {
+ user = new User();
+ user.setId(resultSet.getInt("id"));
+ }
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ LOGGER.warn("Statement cannot be executed.");
+ freeConnection(connection, statement);
+ throw new DaoException(e);
+ }
+ try {
+ resultSet.close();
+ LOGGER.debug("Result set has been closed.");
+ } catch (SQLException e) {
+ LOGGER.debug("Result set cannot be closed.");
+ }
+ freeConnection(connection, statement);
+ return user;
+ }
+
+ /**
+ * Is used to set new status for a user wit the given id in database .
+ *
+ * @param id The id of the user.
+ * @param newStatus The status to be set.
+ * @throws DaoException If something fails during method performing.
+ */
+ @Override
+ public void updateActiveStatus(int id, boolean newStatus)
+ throws DaoException {
+ Connection connection;
+ PreparedStatement statement = null;
+ LOGGER.debug("Delete user...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("UPDATE users SET is_active = ? WHERE id = ?");
+ statement.setBoolean(1, newStatus);
+ statement.setInt(2, id);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ freeConnection(connection, statement);
+ }
+
+ /**
+ * Is used to set new password for a user wit the given id in database .
+ *
+ * @param id The id of the user.
+ * @param newPassword The new password to be set.
+ * @throws DaoException If something fails during method performing.
+ */
+ @Override
+ public void updatePassword(int id, String newPassword) throws DaoException {
+ Connection connection;
+ PreparedStatement statement = null;
+ LOGGER.debug("Delete user...");
+ try {
+ connection = getConnectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new DaoException(e);
+ }
+ try {
+ statement = connection
+ .prepareStatement("UPDATE users SET password = ? WHERE id = ?");
+ statement.setString(1, newPassword);
+ statement.setInt(2, id);
+ LOGGER.debug("Statement has been created.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be created.");
+ throw new DaoException(e);
+ }
+ try {
+ statement.execute();
+ LOGGER.debug("Statement has been executed.");
+ } catch (SQLException e) {
+ freeConnection(connection, statement);
+ LOGGER.warn("Statement cannot be executed.");
+ throw new DaoException(e);
+ }
+ freeConnection(connection, statement);
+ }
+
+ /**
+ * Is used to close statement and return connection to the connection pool.
+ *
+ * @param connection The connection to return.
+ * @param statement The statement to close.
+ */
+ private void freeConnection(Connection connection, Statement statement) {
+ if (statement != null) {
+ try {
+ statement.close();
+ LOGGER.debug("Statement has been closed.");
+ } catch (SQLException e) {
+ LOGGER.warn("Statement cannot be closed.");
+ }
+ }
+ getConnectionPool().returnConnection(connection);
+ LOGGER.debug("Statement has been returned.");
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/epam/devteam/db/ConnectionPool.java b/src/com/epam/devteam/db/ConnectionPool.java
index a332c06..b65af48 100644
--- a/src/com/epam/devteam/db/ConnectionPool.java
+++ b/src/com/epam/devteam/db/ConnectionPool.java
@@ -6,64 +6,80 @@
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
+import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
+import com.epam.devteam.util.property.PropertyManager;
+import com.epam.devteam.util.property.PropertyManagerException;
+
/**
* @date Dec 15, 2013
* @author Andrey Kovalskiy
*
*/
-public enum ConnectionPool {
-
- INSTANCE;
+public class ConnectionPool {
private static final Logger LOGGER = Logger.getLogger(ConnectionPool.class);
- private static final String DRIVER_NAME = "org.postgresql.Driver";
- private static final String URL = "jdbc:postgresql://localhost:5432/postgres";
- private static final String USER = "postgres";
- private static final String PASSWORD = "postgres";
- private static final int CONNECTIONS_QUANTITY = 10;
- private static final long MAX_WAIT_TIME = 5000;
- private Semaphore semaphore;
+ private static volatile ConnectionPool instance;
+ private String driver;
+ private String url;
+ private String user;
+ private String password;
+ private int connections;
+ private long waitTime;
private BlockingQueue freeConnections;
- /**
- * It is not possible to initialize this object outside of this class.
- */
- private ConnectionPool() {
- // init(); ????
+ public static ConnectionPool getInstance() throws ConnectionPoolException {
+ ConnectionPool localInstance = instance;
+ if (localInstance == null) {
+ synchronized (ConnectionPool.class) {
+ localInstance = instance;
+ if (localInstance == null) {
+ instance = localInstance = new ConnectionPool();
+ instance.init();
+ }
+ }
+ }
+ return localInstance;
}
/**
- * Is is used to initialize connection pool instance.
+ * It is used to initialize connection pool instance.
*
* @throws ConnectionPoolException
*/
- public void init() throws ConnectionPoolException {
-
+ private void init() throws ConnectionPoolException {
try {
- Class.forName(DRIVER_NAME);
+ PropertyManager propertyManager = PropertyManager.getInstance();
+ String db = "db." + propertyManager.getString("db.name");
+ driver = propertyManager.getString(db + ".driver");
+ url = propertyManager.getString(db + ".url");
+ user = propertyManager.getString(db + ".user");
+ password = propertyManager.getString(db + ".password");
+ connections = propertyManager.getInt(db + ".connections");
+ waitTime = propertyManager.getLong(db + ".waitTime");
+ LOGGER.debug("Connection pool fields were initialized.");
+ } catch (PropertyManagerException e) {
+ LOGGER.error("Connection pool fields cannot be initialized.");
+ throw new ConnectionPoolException();
+ }
+ try {
+ Class.forName(driver);
+ LOGGER.debug("Database driver was initialized.");
} catch (ClassNotFoundException e) {
- LOGGER.error("Data base driver not found");
+ LOGGER.error("Data base driver was not found.");
throw new ConnectionPoolException();
}
- semaphore = new Semaphore(CONNECTIONS_QUANTITY);
- for (int i = 0; i < CONNECTIONS_QUANTITY; i++) {
- Connection connection;
- try {
- connection = DriverManager.getConnection(URL, USER, PASSWORD);
- } catch (SQLException e) {
- LOGGER.error("Can't initialize pool connections!");
- throw new ConnectionPoolException();
- }
+ freeConnections = new ArrayBlockingQueue(connections);
+ for (int i = 0; i < connections; i++) {
+ Connection connection = createConnection();
freeConnections.add(connection);
}
- LOGGER.debug("Connection pool was initialized with "
- + CONNECTIONS_QUANTITY + "connections.");
+ LOGGER.debug("Connection pool was initialized with " + connections
+ + " connections.");
}
/**
@@ -71,18 +87,24 @@ public void init() throws ConnectionPoolException {
* will wait for a while. If there is still no free connections method will
* return null.
*
- * @return Free connection, otherwise null.
+ * @return Free connection from the connection pool.
+ * @throws ConnectionPoolException If connection cannot be taken or is not
+ * valid and cannot be created.
*/
- public Connection takeConnection() {
+ public Connection takeConnection() throws ConnectionPoolException {
Connection connection = null;
try {
- if (semaphore.tryAcquire(MAX_WAIT_TIME, TimeUnit.MILLISECONDS)) {
- connection = freeConnections.poll(MAX_WAIT_TIME,
- TimeUnit.MILLISECONDS);
- }
+ connection = freeConnections.poll(waitTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
- LOGGER.warn("Can't take connection");
+ LOGGER.warn("Interrupted while waiting");
+ throw new ConnectionPoolException();
}
+ if (!isConnectionValid(connection)) {
+ LOGGER.debug("Connection is not valid.");
+ Connection newConnection = createConnection();
+ connection = newConnection;
+ }
+ //LOGGER.debug("Connection has been taken.");
return connection;
}
@@ -93,11 +115,10 @@ public Connection takeConnection() {
*/
public void returnConnection(Connection connection) {
try {
- freeConnections.offer(connection, MAX_WAIT_TIME,
- TimeUnit.MILLISECONDS);
- semaphore.release();
+ freeConnections.offer(connection, waitTime, TimeUnit.MILLISECONDS);
+ LOGGER.debug("Connection has been returned.");
} catch (InterruptedException e) {
- LOGGER.warn("Can't return connection!");
+ LOGGER.debug("Connection cannot be returned");
}
}
@@ -108,11 +129,49 @@ public void closeConnections() {
for (Connection connection : freeConnections) {
try {
connection.close();
- semaphore.release();
+ LOGGER.debug("Connection has been closed.");
} catch (SQLException e) {
- LOGGER.error("Can't close connection!");
+ LOGGER.error("Connection cannot be closed.");
}
}
}
+ /**
+ * Is used to create new connection.
+ *
+ * @return The new connection.
+ * @throws ConnectionPoolException If connection cannot be created.
+ */
+ private Connection createConnection() throws ConnectionPoolException {
+ Connection connection;
+ try {
+ connection = DriverManager.getConnection(url, user, password);
+ LOGGER.debug("Connection has been created.");
+ } catch (SQLException e) {
+ LOGGER.warn("Connection cannot be created.");
+ throw new ConnectionPoolException();
+ }
+ return connection;
+ }
+
+ /**
+ * Is used to check if the connection has not been closed and still is
+ * valid.
+ *
+ * @return true if connection is valid, false otherwise.
+ * @throws ConnectionPoolException If something wrong with connection
+ * validation.
+ */
+ private boolean isConnectionValid(Connection connection)
+ throws ConnectionPoolException {
+ boolean result = false;
+ try {
+ result = connection.isValid((int) waitTime);
+ } catch (SQLException e) {
+ LOGGER.warn("Connection validation failed.");
+ throw new ConnectionPoolException();
+ }
+ return result;
+ }
+
}
diff --git a/src/com/epam/devteam/db/ConnectionPoolException.java b/src/com/epam/devteam/db/ConnectionPoolException.java
index 6713cc1..3479b49 100644
--- a/src/com/epam/devteam/db/ConnectionPoolException.java
+++ b/src/com/epam/devteam/db/ConnectionPoolException.java
@@ -5,7 +5,7 @@
/**
* @date Dec 15, 2013
- * @author anjey
+ * @author Andrey Kovalskiy
*
*/
public class ConnectionPoolException extends Exception {
diff --git a/src/com/epam/devteam/db/DatabaseType.java b/src/com/epam/devteam/db/DatabaseType.java
new file mode 100644
index 0000000..401d916
--- /dev/null
+++ b/src/com/epam/devteam/db/DatabaseType.java
@@ -0,0 +1,22 @@
+/**
+ *
+ */
+package com.epam.devteam.db;
+
+/**
+ * The DatabaseType defines with what database types application
+ * can work.
+ *
+ * @date Dec 15, 2013
+ * @author Andrey Kovalskiy
+ *
+ */
+public enum DatabaseType {
+
+ POSTGRESQL;
+
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
+}
diff --git a/src/com/epam/devteam/entity/User.java b/src/com/epam/devteam/entity/User.java
deleted file mode 100644
index 6f1e476..0000000
--- a/src/com/epam/devteam/entity/User.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/**
- *
- */
-package com.epam.devteam.entity;
-
-import java.io.Serializable;
-import java.util.Date;
-
-/**
- * @date Dec 15, 2013
- * @author Andrey Kovalskiy
- *
- */
-public class User implements Serializable {
- /**
- * Serial version id.
- */
- private static final long serialVersionUID = 1L;
- private Long id;
- private String email;
- private String password;
- private String firstname;
- private String lastname;
- private String patronymic;
- private Date birthdate;
-
- /**
- * Initializes a newly created {@code User} object with empty fields.
- */
- public User() {
- super();
- }
-
- /**
- * Initializes a newly created {@code User} object with the given field
- * values.
- *
- * @param id the user id.
- * @param email the user email.
- * @param password the user password.
- * @param firstname the user first name.
- * @param lastname the user last name.
- * @param patronymic the user patronymic.
- * @param birthdate the user birthdate.
- */
- public User(long id, String email, String password, String firstname,
- String lastname, String patronymic, Date birthdate) {
- super();
- this.id = id;
- this.email = email;
- this.password = password;
- this.firstname = firstname;
- this.lastname = lastname;
- this.patronymic = patronymic;
- this.birthdate = birthdate;
- }
-
- /**
- * Returns the id field value.
- *
- * @return the id
- */
- public Long getId() {
- return id;
- }
-
- /**
- * Sets the id field value.
- *
- * @param id the id to set
- */
- public void setId(Long id) {
- this.id = id;
- }
-
- /**
- * Returns the email field value.
- *
- * @return the email
- */
- public String getEmail() {
- return email;
- }
-
- /**
- * Sets the email field value.
- *
- * @param email the email to set
- */
- public void setEmail(String email) {
- this.email = email;
- }
-
- /**
- * Returns the password field value.
- *
- * @return the password
- */
- public String getPassword() {
- return password;
- }
-
- /**
- * Sets the password field value.
- *
- * @param password the password to set
- */
- public void setPassword(String password) {
- this.password = password;
- }
-
- /**
- * Returns the firstname field value.
- *
- * @return the firstname
- */
- public String getFirstname() {
- return firstname;
- }
-
- /**
- * Sets the firstname field value.
- *
- * @param firstname the firstname to set
- */
- public void setFirstname(String firstname) {
- this.firstname = firstname;
- }
-
- /**
- * Returns the lastname field value.
- *
- * @return the lastname
- */
- public String getLastname() {
- return lastname;
- }
-
- /**
- * Sets the lastname field value.
- *
- * @param lastname the lastname to set
- */
- public void setLastname(String lastname) {
- this.lastname = lastname;
- }
-
- /**
- * Returns the patronymic field value.
- *
- * @return the patronymic
- */
- public String getPatronymic() {
- return patronymic;
- }
-
- /**
- * Sets the patronymic field value.
- *
- * @param patronymic the patronymic to set
- */
- public void setPatronymic(String patronymic) {
- this.patronymic = patronymic;
- }
-
- /**
- * Returns the birthdate field value.
- *
- * @return the birthdate
- */
- public Date getBirthdate() {
- return birthdate;
- }
-
- /**
- * Sets the birthdate field value.
- *
- * @param birthdate the birthdate to set
- */
- public void setBirthdate(Date birthdate) {
- this.birthdate = birthdate;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (this.getClass() == obj.getClass()) {
- User otherUser = (User) obj;
- return (this.id.equals(otherUser.id))
- && (this.email.equals(otherUser.email))
- && (this.password.equals(otherUser.password))
- && (this.firstname.equals(otherUser.firstname))
- && (this.lastname.equals(otherUser.lastname))
- && (this.patronymic.equals(otherUser.patronymic))
- && (this.birthdate.equals(otherUser.birthdate));
- } else {
- return false;
- }
- }
-
- @Override
- public int hashCode() {
- return (int) (31 * id.hashCode()
- + ((email == null) ? 0 : email.hashCode()) + ((password == null) ? 0
- : password.hashCode()))
- + ((firstname == null) ? 0 : firstname.hashCode())
- + ((lastname == null) ? 0 : lastname.hashCode())
- + ((patronymic == null) ? 0 : patronymic.hashCode())
- + ((birthdate == null) ? 0 : birthdate.hashCode());
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("user:").append(lastname).append(" ").append(firstname)
- .append(" ").append(patronymic).append(" birthdate:")
- .append(birthdate).append(" email:").append(email);
- return sb.toString();
- }
-}
diff --git a/src/com/epam/devteam/entity/feedback/Feedback.java b/src/com/epam/devteam/entity/feedback/Feedback.java
new file mode 100644
index 0000000..59e6b66
--- /dev/null
+++ b/src/com/epam/devteam/entity/feedback/Feedback.java
@@ -0,0 +1,247 @@
+package com.epam.devteam.entity.feedback;
+
+import java.io.Serializable;
+import java.sql.Date;
+
+import com.epam.devteam.entity.user.Employee;
+
+public class Feedback implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private int id;
+ private Date date;
+ private int orderId;
+ private Employee manager;
+ private String message;
+ private String fileName;
+ private byte[] fileContent;
+
+ /**
+ * Initializes a newly created {@code Feedback} object.
+ */
+ public Feedback() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code Feedback} object.
+ *
+ * @param id
+ * @param date
+ * @param orderId
+ * @param manager
+ * @param message
+ * @param fileName
+ * @param fileContent
+ */
+ public Feedback(int id, Date date, int orderId, Employee manager,
+ String message, String fileName, byte[] fileContent) {
+ super();
+ this.id = id;
+ this.date = date;
+ this.orderId = orderId;
+ this.manager = manager;
+ this.message = message;
+ this.fileName = fileName;
+ this.fileContent = fileContent;
+ }
+
+ /**
+ * Returns the id field value.
+ *
+ * @return The id.
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Sets the id field value.
+ *
+ * @param id The id to set.
+ */
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ /**
+ * Returns the date field value.
+ *
+ * @return The date.
+ */
+ public Date getDate() {
+ return date;
+ }
+
+ /**
+ * Sets the date field value.
+ *
+ * @param date The date to set.
+ */
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ /**
+ * Returns the orderId field value.
+ *
+ * @return The orderId.
+ */
+ public int getOrderId() {
+ return orderId;
+ }
+
+ /**
+ * Sets the orderId field value.
+ *
+ * @param orderId The orderId to set.
+ */
+ public void setOrderId(int orderId) {
+ this.orderId = orderId;
+ }
+
+ /**
+ * Returns the manager field value.
+ *
+ * @return The manager.
+ */
+ public Employee getManager() {
+ return manager;
+ }
+
+ /**
+ * Sets the manager field value.
+ *
+ * @param manager The manager to set.
+ */
+ public void setManager(Employee manager) {
+ this.manager = manager;
+ }
+
+ /**
+ * Returns the message field value.
+ *
+ * @return The message.
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Sets the message field value.
+ *
+ * @param message The message to set.
+ */
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ /**
+ * Returns the fileName field value.
+ *
+ * @return The fileName.
+ */
+ public String getFileName() {
+ return fileName;
+ }
+
+ /**
+ * Sets the fileName field value.
+ *
+ * @param fileName The fileName to set.
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ /**
+ * Returns the fileContent field value.
+ *
+ * @return The fileContent.
+ */
+ public byte[] getFileContent() {
+ return fileContent;
+ }
+
+ /**
+ * Sets the fileContent field value.
+ *
+ * @param fileContent The fileContent to set.
+ */
+ public void setFileContent(byte[] fileContent) {
+ this.fileContent = fileContent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((date == null) ? 0 : date.hashCode());
+ result = prime * result
+ + ((fileName == null) ? 0 : fileName.hashCode());
+ result = prime * result + id;
+ result = prime * result + ((manager == null) ? 0 : manager.hashCode());
+ result = prime * result + ((message == null) ? 0 : message.hashCode());
+ result = prime * result + orderId;
+ return result;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Feedback other = (Feedback) obj;
+ if (date == null) {
+ if (other.date != null)
+ return false;
+ } else if (!date.equals(other.date))
+ return false;
+ if (fileName == null) {
+ if (other.fileName != null)
+ return false;
+ } else if (!fileName.equals(other.fileName))
+ return false;
+ if (id != other.id)
+ return false;
+ if (manager == null) {
+ if (other.manager != null)
+ return false;
+ } else if (!manager.equals(other.manager))
+ return false;
+ if (message == null) {
+ if (other.message != null)
+ return false;
+ } else if (!message.equals(other.message))
+ return false;
+ if (orderId != other.orderId)
+ return false;
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "Feedback [id=" + id + ", date=" + date + ", orderId=" + orderId
+ + ", manager=" + manager + ", message=" + message
+ + ", fileName=" + fileName + "]";
+ }
+
+}
diff --git a/src/com/epam/devteam/entity/order/Order.java b/src/com/epam/devteam/entity/order/Order.java
new file mode 100644
index 0000000..10a00d1
--- /dev/null
+++ b/src/com/epam/devteam/entity/order/Order.java
@@ -0,0 +1,284 @@
+package com.epam.devteam.entity.order;
+
+import java.io.Serializable;
+import java.sql.Date;
+
+import com.epam.devteam.entity.user.Customer;
+
+/**
+ * The Order class contain all information about order.
+ *
+ * @date Jan 11, 2014
+ * @author Andrey Kovalskiy
+ * @see com.epam.devteam.entity.order.OrderStatus
+ * @see com.epam.devteam.entity.order.OrderSubject
+ */
+public class Order implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private int id;
+ private Date date;
+ private OrderStatus status;
+ private OrderSubject subject;
+ private String topic;
+ private String message;
+ private String fileName;
+ private byte[] fileContent;
+ private Customer customer;
+
+ /**
+ * Initializes a newly created {@code Order} object.
+ */
+ public Order() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code Object} object.
+ *
+ * @param id The order id.
+ * @param date The date of creation of the order.
+ * @param status The order status.
+ * @param subject The order subject.
+ * @param topic The order topic.
+ * @param message The order message.
+ * @param fileName The name of the file attached to the order.
+ * @param fileContent The content of the file attached to the order.
+ * @param customer The customer who created the order.
+ */
+ public Order(int id, Date date, OrderStatus status, OrderSubject subject,
+ String topic, String message, String fileName, byte[] fileContent,
+ Customer customer) {
+ super();
+ this.id = id;
+ this.date = date;
+ this.status = status;
+ this.subject = subject;
+ this.topic = topic;
+ this.message = message;
+ this.fileName = fileName;
+ this.fileContent = fileContent;
+ this.customer = customer;
+ }
+
+ /**
+ * Returns the id field value.
+ *
+ * @return The id.
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Sets the id field value.
+ *
+ * @param id The id to set.
+ */
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ /**
+ * Returns the date field value.
+ *
+ * @return The date.
+ */
+ public Date getDate() {
+ return date;
+ }
+
+ /**
+ * Sets the date field value.
+ *
+ * @param date The date to set.
+ */
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ /**
+ * Returns the status field value.
+ *
+ * @return The status.
+ */
+ public OrderStatus getStatus() {
+ return status;
+ }
+
+ /**
+ * Sets the status field value.
+ *
+ * @param status The status to set.
+ */
+ public void setStatus(OrderStatus status) {
+ this.status = status;
+ }
+
+ /**
+ * Returns the subject field value.
+ *
+ * @return The subject.
+ */
+ public OrderSubject getSubject() {
+ return subject;
+ }
+
+ /**
+ * Sets the subject field value.
+ *
+ * @param subject The subject to set.
+ */
+ public void setSubject(OrderSubject subject) {
+ this.subject = subject;
+ }
+
+ /**
+ * Returns the topic field value.
+ *
+ * @return The topic.
+ */
+ public String getTopic() {
+ return topic;
+ }
+
+ /**
+ * Sets the topic field value.
+ *
+ * @param topic The topic to set.
+ */
+ public void setTopic(String topic) {
+ this.topic = topic;
+ }
+
+ /**
+ * Returns the message field value.
+ *
+ * @return The message.
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Sets the message field value.
+ *
+ * @param message The message to set.
+ */
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ /**
+ * Returns the fileName field value.
+ *
+ * @return The fileName.
+ */
+ public String getFileName() {
+ return fileName;
+ }
+
+ /**
+ * Sets the fileName field value.
+ *
+ * @param fileName The fileName to set.
+ */
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ /**
+ * Returns the fileContent field value.
+ *
+ * @return The fileContent.
+ */
+ public byte[] getFileContent() {
+ return fileContent;
+ }
+
+ /**
+ * Sets the fileContent field value.
+ *
+ * @param fileContent The fileContent to set.
+ */
+ public void setFileContent(byte[] fileContent) {
+ this.fileContent = fileContent;
+ }
+
+ /**
+ * Returns the customer field value.
+ *
+ * @return The customer.
+ */
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ /**
+ * Sets the customer field value.
+ *
+ * @param customer The customer to set.
+ */
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ /**
+ * Returns hashcode of the object.
+ */
+ @Override
+ public int hashCode() {
+ return 31 * id + ((customer == null) ? 0 : customer.hashCode())
+ + ((date == null) ? 0 : date.hashCode())
+ + ((fileName == null) ? 0 : fileName.hashCode())
+ + ((message == null) ? 0 : message.hashCode())
+ + ((status == null) ? 0 : status.hashCode())
+ + ((subject == null) ? 0 : subject.hashCode())
+ + ((topic == null) ? 0 : topic.hashCode());
+ }
+
+ /**
+ * Indicates whether some other object is "equal to" this one.
+ *
+ * @param obj The reference object with which to compare.
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (this.getClass() == obj.getClass()) {
+ Order otherOrder = (Order) obj;
+ return (this.id == otherOrder.id)
+ && (this.date.equals(otherOrder.date))
+ && (this.status.equals(otherOrder.status))
+ && (this.subject.equals(otherOrder.subject))
+ && (this.topic.equals(otherOrder.topic))
+ && (this.message.equals(otherOrder.message))
+ && (this.fileName.equals(otherOrder.fileName))
+ && (this.fileContent.equals(otherOrder.fileContent))
+ && (this.customer.equals(otherOrder.customer));
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Returns a string representation of the object.
+ */
+ @Override
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("Order id:").append(id).append(", date:").append(date)
+ .append(", status:").append(status).append(", subject:")
+ .append(subject).append(", topic:").append(topic)
+ .append(", message:").append(message).append(", fileName:")
+ .append(fileName).append(", customer:")
+ .append(customer.getFirstName()).append(" ")
+ .append(customer.getLastName());
+ return sb.toString();
+ }
+
+}
diff --git a/src/com/epam/devteam/entity/order/OrderStatus.java b/src/com/epam/devteam/entity/order/OrderStatus.java
new file mode 100644
index 0000000..fb0074a
--- /dev/null
+++ b/src/com/epam/devteam/entity/order/OrderStatus.java
@@ -0,0 +1,12 @@
+package com.epam.devteam.entity.order;
+
+/**
+ * The OrderStatus contains available statuses of the order.
+ *
+ * @date Jan 11, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public enum OrderStatus {
+ PENDING, TERMINATED, ACCEPTED, DENIED
+}
diff --git a/src/com/epam/devteam/entity/order/OrderSubject.java b/src/com/epam/devteam/entity/order/OrderSubject.java
new file mode 100644
index 0000000..3188fb6
--- /dev/null
+++ b/src/com/epam/devteam/entity/order/OrderSubject.java
@@ -0,0 +1,12 @@
+package com.epam.devteam.entity.order;
+
+/**
+ * The OrderSubject contains all available subjects of orders.
+ *
+ * @date Jan 11, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public enum OrderSubject {
+ OTHER, APPLICATION_DEVELOPMENT, APPLICATION_TESTING, APPLICATION_SUPPORT
+}
diff --git a/src/com/epam/devteam/entity/project/Project.java b/src/com/epam/devteam/entity/project/Project.java
new file mode 100644
index 0000000..58423f3
--- /dev/null
+++ b/src/com/epam/devteam/entity/project/Project.java
@@ -0,0 +1,5 @@
+package com.epam.devteam.entity.project;
+
+public class Project {
+
+}
diff --git a/src/com/epam/devteam/entity/user/Customer.java b/src/com/epam/devteam/entity/user/Customer.java
new file mode 100644
index 0000000..5d03142
--- /dev/null
+++ b/src/com/epam/devteam/entity/user/Customer.java
@@ -0,0 +1,143 @@
+package com.epam.devteam.entity.user;
+
+import java.sql.Date;
+
+/**
+ * The Customer class extends User class and contains
+ * unique fields for customers as company and position.
+ *
+ * @date Jan 4, 2014
+ * @author Andrey Kovalskiy
+ * @see com.epam.devteam.entity.user.User
+ * @see com.epam.devteam.entity.user.UserRole
+ */
+public class Customer extends User {
+ private static final long serialVersionUID = 1L;
+ private String company;
+ private String position;
+
+ /**
+ * Initializes a newly created {@code Customer} object.
+ */
+ public Customer() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code Customer} object with the given
+ * values.
+ *
+ * @param id The user id.
+ * @param email The user email.
+ * @param password The user password.
+ * @param registrationDate The date of registration.
+ * @param role The role of the user.
+ * @param active The status of the user.
+ * @param firstName The user first name.
+ * @param lastName The user last name.
+ * @param birthDate The user birth date.
+ * @param address The user address.
+ * @param phone The contact phone number.
+ * @param company The company where the customer works.
+ * @param position The position of the customer.
+ */
+ public Customer(int id, String email, String password,
+ Date registrationDate, UserRole role, boolean active,
+ String firstName, String lastName, Date birthDate, String address,
+ String phone, String company, String position) {
+ super(id, email, password, registrationDate, role, active, firstName,
+ lastName, birthDate, address, phone);
+ this.company = company;
+ this.position = position;
+ }
+
+ /**
+ * Returns the company field value.
+ *
+ * @return The company.
+ */
+ public String getCompany() {
+ return company;
+ }
+
+ /**
+ * Sets the company field value.
+ *
+ * @param company The company to set.
+ */
+ public void setCompany(String company) {
+ this.company = company;
+ }
+
+ /**
+ * Returns the position field value.
+ *
+ * @return The position.
+ */
+ public String getPosition() {
+ return position;
+ }
+
+ /**
+ * Sets the position field value.
+ *
+ * @param position The position to set.
+ */
+ public void setPosition(String position) {
+ super.setFirstName("name");
+ this.position = position;
+ }
+
+ /**
+ * Returns a hash code value for the object.
+ *
+ * @param The object's hash code.
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = super.hashCode();
+ result = prime * result + ((company == null) ? 0 : company.hashCode());
+ result = prime * result
+ + ((position == null) ? 0 : position.hashCode());
+ return result;
+ }
+
+ /**
+ * Indicates whether some other object is "equal to" this one.
+ *
+ * @param obj The reference object with which to compare.
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (!super.equals(obj))
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Customer other = (Customer) obj;
+ if (company == null) {
+ if (other.company != null)
+ return false;
+ } else if (!company.equals(other.company))
+ return false;
+ if (position == null) {
+ if (other.position != null)
+ return false;
+ } else if (!position.equals(other.position))
+ return false;
+ return true;
+ }
+
+ /**
+ * Returns a string representation of the object.
+ */
+ @Override
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append(super.toString()).append(" company:").append(company)
+ .append(" position:").append(position);
+ return sb.toString();
+ }
+}
diff --git a/src/com/epam/devteam/entity/user/Employee.java b/src/com/epam/devteam/entity/user/Employee.java
new file mode 100644
index 0000000..191f1cb
--- /dev/null
+++ b/src/com/epam/devteam/entity/user/Employee.java
@@ -0,0 +1,115 @@
+package com.epam.devteam.entity.user;
+
+import java.sql.Date;
+
+/**
+ * The Employee class extends User class and contains
+ * unique fields for employees as qualification.
+ *
+ * @date Jan 4, 2014
+ * @author Andrey Kovalskiy
+ * @see com.epam.devteam.entity.user.User
+ * @see com.epam.devteam.entity.user.UserRole
+ */
+public class Employee extends User {
+ private static final long serialVersionUID = 1L;
+ private String qualification;
+
+ /**
+ * Initializes a newly created {@code Employee} object.
+ */
+ public Employee() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code Employee} object with the given field
+ * values.
+ *
+ * @param id The user id.
+ * @param email The user email.
+ * @param password The user password.
+ * @param registrationDate The date of registration.
+ * @param role The role of the user.
+ * @param active The status of the user.
+ * @param firstName The user first name.
+ * @param lastName The user last name.
+ * @param birthDate The user birth date.
+ * @param address The user address.
+ * @param phone The contact phone number.
+ * @param qualifiaction The employee qualification.
+ */
+ public Employee(int id, String email, String password,
+ Date registrationDate, UserRole role, boolean active,
+ String firstName, String lastName, Date birthDate, String address,
+ String phone, String qualification) {
+ super(id, email, password, registrationDate, role, active, firstName,
+ lastName, birthDate, address, phone);
+ this.qualification = qualification;
+ }
+
+ /**
+ * Returns the qualification field value.
+ *
+ * @return The qualification.
+ */
+ public String getQualification() {
+ return qualification;
+ }
+
+ /**
+ * Sets the qualification field value.
+ *
+ * @param qualification The qualification to set.
+ */
+ public void setQualification(String qualification) {
+ this.qualification = qualification;
+ }
+
+ /**
+ * Returns a hash code value for the object.
+ *
+ * @param The object's hash code.
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = super.hashCode();
+ result = prime * result
+ + ((qualification == null) ? 0 : qualification.hashCode());
+ return result;
+ }
+
+ /**
+ * Indicates whether some other object is "equal to" this one.
+ *
+ * @param obj The reference object with which to compare.
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (!super.equals(obj))
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Employee other = (Employee) obj;
+ if (qualification == null) {
+ if (other.qualification != null)
+ return false;
+ } else if (!qualification.equals(other.qualification))
+ return false;
+ return true;
+ }
+
+ /**
+ * Returns a string representation of the object.
+ */
+ @Override
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append(super.toString()).append(" qualification:")
+ .append(qualification);
+ return sb.toString();
+ }
+}
diff --git a/src/com/epam/devteam/entity/user/User.java b/src/com/epam/devteam/entity/user/User.java
new file mode 100644
index 0000000..81710d7
--- /dev/null
+++ b/src/com/epam/devteam/entity/user/User.java
@@ -0,0 +1,377 @@
+/**
+ *
+ */
+package com.epam.devteam.entity.user;
+
+import java.io.Serializable;
+import java.sql.Date;
+
+/**
+ * The User provides basic fields and methods for all users.
+ *
+ * @date Dec 15, 2013
+ * @author Andrey Kovalskiy
+ * @see com.epam.devteam.entity.user.UserRole
+ */
+public class User implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private int id;
+ private String email;
+ private String password;
+ private Date registrationDate;
+ private UserRole role;
+ private boolean active;
+ private String firstName;
+ private String lastName;
+ private Date birthDate;
+ private String address;
+ private String phone;
+
+ /**
+ * Initializes a newly created {@code User} object with empty fields.
+ */
+ public User() {
+ super();
+ }
+
+ /**
+ * Initializes a newly created {@code User} object with the given field
+ * values.
+ *
+ * @param id The user id.
+ * @param email The user email.
+ * @param password The user password.
+ * @param registrationDate The date of registration.
+ * @param role The role of the user.
+ * @param active The status of the user.
+ * @param firstName The user first name.
+ * @param lastName The user last name.
+ * @param birthDate The user birth date.
+ * @param address The user address.
+ * @param phone The contact phone number.
+ */
+ public User(Integer id, String email, String password,
+ Date registrationDate, UserRole role, boolean active,
+ String firstName, String lastName, Date birthDate, String address,
+ String phone) {
+ super();
+ this.id = id;
+ this.email = email;
+ this.password = password;
+ this.registrationDate = registrationDate;
+ this.role = role;
+ this.active = active;
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.birthDate = birthDate;
+ this.address = address;
+ this.phone = phone;
+ }
+
+ /**
+ * Returns the id field value.
+ *
+ * @return The id.
+ */
+ public int getId() {
+ return id;
+ }
+
+ /**
+ * Sets the id field value.
+ *
+ * @param id The id to set.
+ */
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ /**
+ * Returns the email field value.
+ *
+ * @return The email.
+ */
+ public String getEmail() {
+ return email;
+ }
+
+ /**
+ * Sets the email field value.
+ *
+ * @param email The email to set.
+ */
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ /**
+ * Returns the password field value.
+ *
+ * @return The password.
+ */
+ public String getPassword() {
+ return password;
+ }
+
+ /**
+ * Sets the password field value.
+ *
+ * @param password The password to set.
+ */
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ /**
+ * Returns the registrationDate field value.
+ *
+ * @return The registrationDate.
+ */
+ public Date getRegistrationDate() {
+ return registrationDate;
+ }
+
+ /**
+ * Sets the registrationDate field value.
+ *
+ * @param registrationDate The registrationDate to set.
+ */
+ public void setRegistrationDate(Date registrationDate) {
+ this.registrationDate = registrationDate;
+ }
+
+ /**
+ * Returns the user role field value.
+ *
+ * @return The user role.
+ */
+ public UserRole getRole() {
+ return role;
+ }
+
+ /**
+ * Sets the role field value.
+ *
+ * @param role The role to set.
+ */
+ public void setRole(UserRole role) {
+ this.role = role;
+ }
+
+ /**
+ * Returns the isActive field value.
+ *
+ * @return The isActive.
+ */
+ public boolean isActive() {
+ return active;
+ }
+
+ /**
+ * Sets the isActive field value.
+ *
+ * @param isActive The isActive to set.
+ */
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ /**
+ * Returns the firstName field value.
+ *
+ * @return The firstName.
+ */
+ public String getFirstName() {
+ return firstName;
+ }
+
+ /**
+ * Sets the firstName field value.
+ *
+ * @param firstName The firstName to set.
+ */
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ /**
+ * Returns the lastName field value.
+ *
+ * @return The lastName.
+ */
+ public String getLastName() {
+ return lastName;
+ }
+
+ /**
+ * Sets the lastName field value.
+ *
+ * @param lastName The lastName to set.
+ */
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ /**
+ * Returns the birthDate field value.
+ *
+ * @return The birthDate.
+ */
+ public Date getBirthDate() {
+ return birthDate;
+ }
+
+ /**
+ * Sets the birthDate field value.
+ *
+ * @param birthDate The birthDate to set.
+ */
+ public void setBirthDate(Date birthDate) {
+ this.birthDate = birthDate;
+ }
+
+ /**
+ * Returns the address field value.
+ *
+ * @return The address.
+ */
+ public String getAddress() {
+ return address;
+ }
+
+ /**
+ * Sets the address field value.
+ *
+ * @param address The address to set.
+ */
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ /**
+ * Returns the phone field value.
+ *
+ * @return The phone.
+ */
+ public String getPhone() {
+ return phone;
+ }
+
+ /**
+ * Sets the phone field value.
+ *
+ * @param phone The phone to set.
+ */
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+
+ /**
+ * Returns a hash code value for the object.
+ *
+ * @param The object's hash code.
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (active ? 1231 : 1237);
+ result = prime * result + ((address == null) ? 0 : address.hashCode());
+ result = prime * result
+ + ((birthDate == null) ? 0 : birthDate.hashCode());
+ result = prime * result + ((email == null) ? 0 : email.hashCode());
+ result = prime * result
+ + ((firstName == null) ? 0 : firstName.hashCode());
+ result = prime * result + id;
+ result = prime * result
+ + ((lastName == null) ? 0 : lastName.hashCode());
+ result = prime * result
+ + ((password == null) ? 0 : password.hashCode());
+ result = prime * result + ((phone == null) ? 0 : phone.hashCode());
+ result = prime
+ * result
+ + ((registrationDate == null) ? 0 : registrationDate.hashCode());
+ result = prime * result + ((role == null) ? 0 : role.hashCode());
+ return result;
+ }
+
+ /**
+ * Indicates whether some other object is "equal to" this one.
+ *
+ * @param obj The reference object with which to compare.
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ User other = (User) obj;
+ if (active != other.active)
+ return false;
+ if (address == null) {
+ if (other.address != null)
+ return false;
+ } else if (!address.equals(other.address))
+ return false;
+ if (birthDate == null) {
+ if (other.birthDate != null)
+ return false;
+ } else if (!birthDate.equals(other.birthDate))
+ return false;
+ if (email == null) {
+ if (other.email != null)
+ return false;
+ } else if (!email.equals(other.email))
+ return false;
+ if (firstName == null) {
+ if (other.firstName != null)
+ return false;
+ } else if (!firstName.equals(other.firstName))
+ return false;
+ if (id != other.id)
+ return false;
+ if (lastName == null) {
+ if (other.lastName != null)
+ return false;
+ } else if (!lastName.equals(other.lastName))
+ return false;
+ if (password == null) {
+ if (other.password != null)
+ return false;
+ } else if (!password.equals(other.password))
+ return false;
+ if (phone == null) {
+ if (other.phone != null)
+ return false;
+ } else if (!phone.equals(other.phone))
+ return false;
+ if (registrationDate == null) {
+ if (other.registrationDate != null)
+ return false;
+ } else if (!registrationDate.equals(other.registrationDate))
+ return false;
+ if (role != other.role)
+ return false;
+ return true;
+ }
+
+ /**
+ * Returns a string representation of the object.
+ */
+ @Override
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("User id:").append(id).append(" email:").append(email)
+ .append(" registered:").append(registrationDate)
+ .append(" status:").append(active).append(" role:")
+ .append(role).append(" name:").append(lastName).append(" ")
+ .append(firstName).append(" birthdate:").append(birthDate)
+ .append(" address:").append(address).append(" phone:")
+ .append(phone);
+ return sb.toString();
+ }
+}
diff --git a/src/com/epam/devteam/entity/user/UserRole.java b/src/com/epam/devteam/entity/user/UserRole.java
new file mode 100644
index 0000000..449ac1a
--- /dev/null
+++ b/src/com/epam/devteam/entity/user/UserRole.java
@@ -0,0 +1,15 @@
+/**
+ *
+ */
+package com.epam.devteam.entity.user;
+
+/**
+ * The UserRole contains all available user roles.
+ *
+ * @date Jan 4, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public enum UserRole {
+ UNREGISTERED_USER, ADMINISTRATOR, MANAGER, DEVELOPER, CUSTOMER;
+}
diff --git a/src/com/epam/devteam/filter/CacheControlFilter.java b/src/com/epam/devteam/filter/CacheControlFilter.java
new file mode 100644
index 0000000..b5fb683
--- /dev/null
+++ b/src/com/epam/devteam/filter/CacheControlFilter.java
@@ -0,0 +1,38 @@
+package com.epam.devteam.filter;
+
+import java.io.IOException;
+import java.util.Date;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
+
+public class CacheControlFilter implements Filter {
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ HttpServletResponse httpResponse = (HttpServletResponse) response;
+ httpResponse.setHeader("Cache-Control",
+ "no-cache, no-store, must-revalidate");
+ httpResponse.setHeader("Pragma", "no-cache");
+ httpResponse.setDateHeader("Expires", 0);
+ httpResponse.setDateHeader("Last-Modified", new Date().getTime());
+ chain.doFilter(request, response);
+ }
+
+ @Override
+ public void destroy() {
+
+ }
+
+}
diff --git a/src/com/epam/devteam/filter/CharsetFilter.java b/src/com/epam/devteam/filter/CharsetFilter.java
new file mode 100644
index 0000000..07d2846
--- /dev/null
+++ b/src/com/epam/devteam/filter/CharsetFilter.java
@@ -0,0 +1,41 @@
+package com.epam.devteam.filter;
+
+import java.io.IOException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.apache.log4j.Logger;
+
+/**
+ * The CharsetFilter is used to set UTF-8 encoding for request.
+ *
+ * @date Jan 22, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class CharsetFilter implements Filter {
+ private final static Logger LOGGER = Logger.getLogger(CharsetFilter.class);
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ LOGGER.debug("Charset filter");
+ request.setCharacterEncoding("UTF-8");
+ LOGGER.debug(request.getParameter("topic"));
+ chain.doFilter(request, response);
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/epam/devteam/filter/SecurityFilter.java b/src/com/epam/devteam/filter/SecurityFilter.java
new file mode 100644
index 0000000..745db69
--- /dev/null
+++ b/src/com/epam/devteam/filter/SecurityFilter.java
@@ -0,0 +1,112 @@
+package com.epam.devteam.filter;
+
+import java.io.IOException;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import com.epam.devteam.entity.user.User;
+import com.epam.devteam.entity.user.UserRole;
+
+/**
+ * The SecurityFilter is used to check user right to access any
+ * resource or perform any action. If access is denied user will be forwarded at
+ * "Error" page.
+ *
+ * @date Jan 22, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class SecurityFilter implements Filter {
+ private Map> actions = new HashMap>();
+
+ /**
+ * Creates a map of URLs and users who have rights to access it.
+ */
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ EnumSet all = EnumSet.of(UserRole.UNREGISTERED_USER,
+ UserRole.CUSTOMER, UserRole.DEVELOPER, UserRole.MANAGER,
+ UserRole.ADMINISTRATOR);
+ EnumSet authorized = EnumSet.of(UserRole.CUSTOMER,
+ UserRole.DEVELOPER, UserRole.MANAGER, UserRole.ADMINISTRATOR);
+ EnumSet customer = EnumSet.of(UserRole.CUSTOMER);
+ EnumSet administrator = EnumSet.of(UserRole.ADMINISTRATOR);
+ EnumSet manager = EnumSet.of(UserRole.MANAGER);
+ actions.put("GET/main", all);
+ actions.put("GET/contacts", all);
+ actions.put("GET/about-us", all);
+ actions.put("GET/error", all);
+ actions.put("GET/success", all);
+ actions.put("GET/download-file", authorized);
+ actions.put("POST/set-language", all);
+ actions.put("POST/signin", all);
+ actions.put("GET/signout", authorized);
+ actions.put("GET/create-account", all);
+ actions.put("POST/create-account", all);
+ actions.put("GET/edit-account", authorized);
+ actions.put("POST/save-account", authorized);
+ actions.put("GET/manage-accounts", authorized);
+ actions.put("GET/deactivate-account", administrator);
+ actions.put("GET/activate-account", administrator);
+ actions.put("POST/change-password", authorized);
+ actions.put("GET/create-order", customer);
+ actions.put("POST/create-order", customer);
+ actions.put("GET/customer-orders", customer);
+ actions.put("GET/show-order", authorized);
+ actions.put("GET/terminate-order", customer);
+ actions.put("GET/edit-order", customer);
+ actions.put("POST/save-order", customer);
+ actions.put("GET/show-all-orders", manager);
+ actions.put("GET/process-order", manager);
+ actions.put("POST/create-feedback", manager);
+
+ }
+
+ /**
+ * Checks current request URL. If User has rights to access this URL filter
+ * pass request to next filter, otherwise User will be forwarded to the
+ * 'Error' page.
+ */
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ HttpServletRequest httpRequest = (HttpServletRequest) request;
+ HttpSession session = httpRequest.getSession();
+ EnumSet allowedRoles = actions.get(httpRequest.getMethod()
+ + httpRequest.getPathInfo());
+ System.out.println(httpRequest.getMethod() + httpRequest.getPathInfo());
+ User currentUser = (User) session.getAttribute("user");
+ UserRole currentUserRole;
+ if (currentUser == null) {
+ currentUserRole = UserRole.UNREGISTERED_USER;
+ } else {
+ currentUserRole = currentUser.getRole();
+ }
+ if (allowedRoles == null) {
+ chain.doFilter(request, response);
+ return;
+ }
+ if (!allowedRoles.contains(currentUserRole)) {
+ session.setAttribute("error", "error.accessDenied");
+ request.getRequestDispatcher("error").forward(request, response);
+ return;
+ }
+ chain.doFilter(request, response);
+ }
+
+ @Override
+ public void destroy() {
+
+ }
+
+}
diff --git a/src/com/epam/devteam/listener/ContextListener.java b/src/com/epam/devteam/listener/ContextListener.java
new file mode 100644
index 0000000..571f4e4
--- /dev/null
+++ b/src/com/epam/devteam/listener/ContextListener.java
@@ -0,0 +1,50 @@
+/**
+ *
+ */
+package com.epam.devteam.listener;
+
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.db.ConnectionPool;
+import com.epam.devteam.db.ConnectionPoolException;
+
+/**
+ * @date Dec 19, 2013
+ * @author Andrey Kovalskiy
+ *
+ */
+public final class ContextListener implements ServletContextListener {
+ private static final Logger LOGGER = Logger
+ .getLogger(ContextListener.class);
+
+ /**
+ ** Notification that the web application initialization process is starting.
+ * All ServletContextListeners are notified of context initialization before
+ * any filter or servlet in the web application is initialized.
+ */
+ @Override
+ public void contextInitialized(ServletContextEvent sce) {
+ LOGGER.debug("Servlet initilization...");
+ }
+
+ /**
+ ** Notification that the servlet context is about to be shut down. All
+ * servlets and filters have been destroy()ed before any
+ * ServletContextListeners are notified of context destruction.
+ */
+ @Override
+ public void contextDestroyed(ServletContextEvent sce) {
+ ConnectionPool connectionPool;
+ try {
+ connectionPool = ConnectionPool.getInstance();
+ connectionPool.closeConnections();
+ LOGGER.debug("Connections have been closed.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.error("Somethng fails with connection pool.");
+ }
+ }
+
+}
diff --git a/src/com/epam/devteam/service/FeedbackService.java b/src/com/epam/devteam/service/FeedbackService.java
new file mode 100644
index 0000000..fe01dde
--- /dev/null
+++ b/src/com/epam/devteam/service/FeedbackService.java
@@ -0,0 +1,103 @@
+package com.epam.devteam.service;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.db.ConnectionPool;
+import com.epam.devteam.db.ConnectionPoolException;
+import com.epam.devteam.entity.feedback.Feedback;
+import com.epam.devteam.entity.order.Order;
+
+public class FeedbackService {
+ private final static Logger LOGGER = Logger
+ .getLogger(FeedbackService.class);
+ private ConnectionPool connectionPool;
+
+ public void createFeedback(Feedback feedback, Order order)
+ throws ServiceException {
+ Connection connection;
+ PreparedStatement feedbackStatement = null;
+ PreparedStatement orderStatement = null;
+ LOGGER.debug("Feedback create service...");
+ try {
+ connection = connectionPool().takeConnection();
+ LOGGER.debug("Connection has been taken.");
+ } catch (ConnectionPoolException e) {
+ LOGGER.warn("Connection cannot be taken.");
+ throw new ServiceException(e);
+ }
+ try {
+ connection.setAutoCommit(false);
+ LOGGER.debug("Auto commit has been disabled.");
+ } catch (SQLException e) {
+ connectionPool.returnConnection(connection);
+ LOGGER.warn("Auto commit cannot be set.");
+ throw new ServiceException(e);
+ }
+ try {
+ feedbackStatement = connection
+ .prepareStatement("INSERT INTO feedbacks (date, order_id, message, file_name, file_content, manager_id) VALUES (?,?,?,?,?,?)");
+ feedbackStatement.setDate(1, feedback.getDate());
+ feedbackStatement.setInt(2, feedback.getOrderId());
+ feedbackStatement.setString(3, feedback.getMessage());
+ feedbackStatement.setString(4, feedback.getFileName());
+ feedbackStatement.setBytes(5, feedback.getFileContent());
+ feedbackStatement.setInt(6, feedback.getManager().getId());
+ LOGGER.debug("Feedback statement has been created.");
+ feedbackStatement.execute();
+ LOGGER.debug("Feedback statement has been executed.");
+ orderStatement = connection
+ .prepareStatement("UPDATE orders SET status = ? WHERE id = ?");
+ orderStatement.setString(1, order.getStatus().name());
+ orderStatement.setInt(2, order.getId());
+ LOGGER.debug("Order statement has been created.");
+ orderStatement.execute();
+ LOGGER.debug("Order statement has been executed.");
+ connection.commit();
+ LOGGER.debug("Commit success.");
+ connection.setAutoCommit(true);
+ LOGGER.debug("Auto commit has been enabled.");
+ } catch (SQLException e) {
+ LOGGER.debug("Feedback cannot be created");
+ try {
+ connection.rollback();
+ LOGGER.debug("Roll back success");
+ } catch (SQLException e1) {
+ LOGGER.warn("Roll back failed.");
+ }
+ throw new ServiceException(e);
+ } finally {
+ try {
+ if (feedbackStatement != null) {
+ feedbackStatement.close();
+ LOGGER.debug("Feedback statement has been closed.");
+ }
+ if (orderStatement != null) {
+ orderStatement.close();
+ LOGGER.debug("Order statement has been closed.");
+ }
+ } catch (SQLException e) {
+ LOGGER.debug("Statements cannot be closed.");
+ }
+ connectionPool.returnConnection(connection);
+ }
+ }
+
+ /**
+ * Is used to get connection pool. It initializes pool during the first use.
+ *
+ * @return The connection pool instance.
+ * @throws ConnectionPoolException
+ */
+ private ConnectionPool connectionPool() throws ConnectionPoolException {
+ if (connectionPool == null) {
+ connectionPool = ConnectionPool.getInstance();
+ LOGGER.debug("Connection pool has been taken.");
+ }
+ return connectionPool;
+ }
+
+}
diff --git a/src/com/epam/devteam/service/ServiceException.java b/src/com/epam/devteam/service/ServiceException.java
new file mode 100644
index 0000000..93a1c7d
--- /dev/null
+++ b/src/com/epam/devteam/service/ServiceException.java
@@ -0,0 +1,49 @@
+package com.epam.devteam.service;
+
+/**
+ * The ServiceException is used to wrap any exception that occurs
+ * during service performing.
+ *
+ * @date Jan 19, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ServiceException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructs a new exception with null as its detail message.
+ */
+ public ServiceException() {
+ super();
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param message the detail message.
+ * @param cause the cause.
+ */
+ public ServiceException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ */
+ public ServiceException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new exception with the specified cause and a detail message
+ * of (cause==null ? null : cause.toString()).
+ *
+ * @param cause the cause.
+ */
+ public ServiceException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/src/com/epam/devteam/servlet/Controller.java b/src/com/epam/devteam/servlet/Controller.java
index e42e392..2eeaddb 100644
--- a/src/com/epam/devteam/servlet/Controller.java
+++ b/src/com/epam/devteam/servlet/Controller.java
@@ -1,39 +1,90 @@
package com.epam.devteam.servlet;
import java.io.IOException;
+
import javax.servlet.ServletException;
-import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.Action;
+import com.epam.devteam.action.ActionFactory;
+import com.epam.devteam.action.ActionResult;
+import com.epam.devteam.action.exception.ActionException;
+
/**
- * Servlet implementation class Controller
+ * Is used to handle all the requests that are addressed to this web site.
*/
-@WebServlet("/Controller")
public class Controller extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
+ private static final Logger LOGGER = Logger.getLogger(Controller.class);
+ private static final long serialVersionUID = 1L;
+
/**
- * @see HttpServlet#HttpServlet()
+ * Is used to process GET request.
+ *
+ * @param request Http request.
+ * @param response Http response.
+ * @throws ServletException If the target resource throws this exception
+ * @throws IOException If the target resource throws this exception
+ * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
+ * response)
*/
- public Controller() {
- super();
- // TODO Auto-generated constructor stub
+ protected void doGet(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ doAction(request, response);
}
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
- }
+ /**
+ * Is used to process POST request.
+ *
+ * @param request Http request.
+ * @param response Http response.
+ * @throws ServletException If the target resource throws this exception
+ * @throws IOException If the target resource throws this exception
+ * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
+ * response)
+ */
+ protected void doPost(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ doAction(request, response);
+ }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // TODO Auto-generated method stub
+ /**
+ * Is used to process current request, perform any action and show jsp page
+ * with result.
+ *
+ * @param request Http request
+ * @param response Http response
+ * @throws ServletException If the target resource throws this exception
+ * @throws IOException If the target resource throws this exception
+ */
+ protected void doAction(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ Action action;
+ ActionResult result;
+ ActionResult.METHOD method;
+ String view;
+ action = ActionFactory.getAction(request);
+ try {
+ result = action.execute(request, response);
+ } catch (ActionException e) {
+ throw new ServletException(e);
}
+ method = result.getMethod();
+ view = result.getView();
+ LOGGER.debug(method + "/" + view);
+ switch (method) {
+ case FORWARD:
+ request.getRequestDispatcher("/WEB-INF/jsp/" + view + ".jsp")
+ .forward(request, response);
+ break;
+ case REDIRECT:
+ response.sendRedirect(view);
+ break;
+ }
+
+ }
-}
+}
\ No newline at end of file
diff --git a/src/com/epam/devteam/servlet/ErrorHandler.java b/src/com/epam/devteam/servlet/ErrorHandler.java
new file mode 100644
index 0000000..d15bc22
--- /dev/null
+++ b/src/com/epam/devteam/servlet/ErrorHandler.java
@@ -0,0 +1,72 @@
+package com.epam.devteam.servlet;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.action.exception.ActionBadRequestException;
+import com.epam.devteam.action.exception.ActionDatabaseFailException;
+
+/**
+ * The ErrorHandler is used to process exceptions.
+ */
+public class ErrorHandler extends HttpServlet {
+ private static final long serialVersionUID = 1L;
+ private static final Logger LOGGER = Logger.getLogger(ErrorHandler.class);
+
+ /**
+ * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
+ * response)
+ */
+ protected void doGet(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ handleError(request, response);
+ request.getRequestDispatcher("error").forward(request, response);
+ }
+
+ /**
+ * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
+ * response)
+ */
+ protected void doPost(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ handleError(request, response);
+ response.sendRedirect("error");
+ }
+
+ /**
+ * Is used to process exception. It defines a type of exception and sets
+ * required error message to session.
+ *
+ * @param request The http request.
+ * @param response The http response.
+ * @throws ServletException If something fails.
+ * @throws IOException If something fails.
+ */
+ private void handleError(HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ HttpSession session = request.getSession();
+ Throwable exception = (Throwable) request
+ .getAttribute("javax.servlet.error.exception");
+ LOGGER.debug("Error Handler...");
+ if (exception.getClass().equals(ActionBadRequestException.class)) {
+ session.setAttribute("error", "error.badRequest");
+ LOGGER.warn("Bad request.");
+ } else if (exception.getClass().equals(
+ ActionDatabaseFailException.class)) {
+ session.setAttribute("error", "error.actionFailed ");
+ LOGGER.warn("Database fail.");
+ } else {
+ session.setAttribute("error", "error.serverError");
+ LOGGER.warn("Server error.");
+ }
+ LOGGER.debug("Details:", exception);
+ }
+
+}
diff --git a/src/com/epam/devteam/tag/LogInfoTag.java b/src/com/epam/devteam/tag/LogInfoTag.java
new file mode 100644
index 0000000..028877a
--- /dev/null
+++ b/src/com/epam/devteam/tag/LogInfoTag.java
@@ -0,0 +1,42 @@
+/**
+ *
+ */
+package com.epam.devteam.tag;
+
+import java.io.IOException;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.JspWriter;
+import javax.servlet.jsp.tagext.TagSupport;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.entity.user.User;
+
+/**
+ * @date Jan 6, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class LogInfoTag extends TagSupport {
+ private static final Logger LOGGER = Logger.getLogger(SigninTag.class);
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public int doStartTag() throws JspException {
+ User user = (User) pageContext.getSession().getAttribute("user");
+ String str;
+ if (user == null) {
+ str = "Please authorise to get access to all features.";
+ } else {
+ str = "Welcome: " + user.getFirstName() + " " + user.getLastName() + "";
+ }
+ try {
+ JspWriter out = pageContext.getOut();
+ out.print(str);
+ } catch (IOException e) {
+ LOGGER.warn("Jsp write failed.");
+ }
+ return SKIP_BODY;
+ }
+}
diff --git a/src/com/epam/devteam/tag/SigninTag.java b/src/com/epam/devteam/tag/SigninTag.java
new file mode 100644
index 0000000..219dd54
--- /dev/null
+++ b/src/com/epam/devteam/tag/SigninTag.java
@@ -0,0 +1,43 @@
+/**
+ *
+ */
+package com.epam.devteam.tag;
+
+import java.io.IOException;
+
+import javax.servlet.jsp.JspException;
+import javax.servlet.jsp.JspWriter;
+import javax.servlet.jsp.tagext.TagSupport;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.entity.user.User;
+
+/**
+ * @date Jan 6, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class SigninTag extends TagSupport {
+ private static final Logger LOGGER = Logger.getLogger(SigninTag.class);
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public int doStartTag() throws JspException {
+ User user = (User) pageContext.getSession().getAttribute("user");
+ String str;
+ if (user == null) {
+ str = "Sign in";
+ } else {
+ str = "Sign out";
+ }
+ try {
+ JspWriter out = pageContext.getOut();
+ out.print(str);
+ } catch (IOException e) {
+ LOGGER.warn("Jsp write failed.");
+ }
+ return SKIP_BODY;
+ }
+
+}
diff --git a/src/com/epam/devteam/util/property/PropertyManager.java b/src/com/epam/devteam/util/property/PropertyManager.java
new file mode 100644
index 0000000..1cd4a3c
--- /dev/null
+++ b/src/com/epam/devteam/util/property/PropertyManager.java
@@ -0,0 +1,227 @@
+/**
+ *
+ */
+package com.epam.devteam.util.property;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import org.apache.log4j.Logger;
+
+/**
+ * @date Dec 18, 2013
+ * @author Andrey Kovalskiy
+ *
+ */
+public class PropertyManager {
+
+ private static final Logger LOGGER = Logger
+ .getLogger(PropertyManager.class);
+ private static volatile PropertyManager instance = null;
+ private Properties properties = null;
+
+ /**
+ * Is used to get property manager implementation instance. Initialization
+ * is to be during the first access.
+ *
+ * @return The property manager instance.
+ * @throws PropertyManagerException If initialization fails.
+ */
+ public static PropertyManager getInstance() throws PropertyManagerException {
+ PropertyManager localInstance = instance;
+ if (localInstance == null) {
+ synchronized (PropertyManager.class) {
+ localInstance = instance;
+ if (localInstance == null) {
+ instance = localInstance = new PropertyManager();
+ instance.init();
+ }
+ }
+ }
+ return instance;
+ }
+
+ /**
+ * Is used to initialize property manager instance.
+ *
+ * @throws PropertyManagerException If the property file can not be loaded.
+ */
+ private void init() throws PropertyManagerException {
+ properties = new Properties();
+ InputStream stream = PropertyManager.class.getClassLoader()
+ .getResourceAsStream("properties.properties");
+ if (stream == null) {
+ LOGGER.error("Property file cannot be found.");
+ throw new PropertyManagerException();
+ }
+ try {
+ properties.load(stream);
+ } catch (IOException e) {
+ LOGGER.error("Can not load property file.");
+ throw new PropertyManagerException(e);
+ }
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * string.
+ *
+ * @param key The property key.
+ * @return The required property.
+ * @throws PropertyManagerException If property is not found.
+ */
+ public String getString(String key) throws PropertyManagerException {
+ String value = null;
+ value = properties.getProperty(key);
+ if (value == null) {
+ LOGGER.warn("Value " + key + " is not defined.");
+ throw new PropertyManagerException();
+ }
+ return value;
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * a string. If property value is not found or has wrong format method will
+ * return default value.
+ *
+ * @param key The property key.
+ * @param defaultValue The value to be returned if something wrong with
+ * property value.
+ * @return The required property.
+ */
+ public String getString(String key, String defaultValue) {
+ String value = null;
+ try {
+ value = getString(key);
+ } catch (PropertyManagerException e) {
+ value = defaultValue;
+ }
+ return value;
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * a long number.
+ *
+ * @param key The property key.
+ * @return The required property.
+ * @throws PropertyManagerException If property is not found or has wrong
+ * format.
+ */
+ public long getLong(String key) throws PropertyManagerException {
+ long value = 0;
+ String temp = getString(key);
+ try {
+ value = Long.parseLong(temp);
+ } catch (NumberFormatException e) {
+ LOGGER.warn("Wrong " + key + " value format.");
+ throw new PropertyManagerException(e);
+ }
+ return value;
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * a long number. If property value is not found or has wrong format method
+ * will return default value.
+ *
+ * @param key The property key.
+ * @param defaultValue The value to be returned if something wrong with
+ * property value.
+ * @return The required property.
+ */
+ public long getLong(String key, long defaultValue) {
+ long value = 0;
+ try {
+ value = getLong(key);
+ } catch (PropertyManagerException e) {
+ value = defaultValue;
+ }
+ return value;
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * an integer number.
+ *
+ * @param key The property key.
+ * @return The required property.
+ * @throws PropertyManagerException If property is not found or has wrong
+ * format.
+ */
+ public int getInt(String key) throws PropertyManagerException {
+ int value = 0;
+ String temp = getString(key);
+ try {
+ value = Integer.parseInt(temp);
+ } catch (NumberFormatException e) {
+ LOGGER.warn("Wrong " + key + " value format.");
+ throw new PropertyManagerException(e);
+ }
+ return value;
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * an integer number. If property value is not found or has wrong format
+ * method will return default value.
+ *
+ * @param key The property key.
+ * @param defaultValue The value to be returned if something wrong with
+ * property value.
+ * @return The required property.
+ */
+ public int getInt(String key, int defaultValue) {
+ int value = 0;
+ try {
+ value = getInt(key);
+ } catch (PropertyManagerException e) {
+ value = defaultValue;
+ }
+ return value;
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * double number.
+ *
+ * @param key The property key.
+ * @return The required property.
+ * @throws PropertyManagerException If property is not found or has wrong
+ * format.
+ */
+ public double getDouble(String key) throws PropertyManagerException {
+ double value = 0;
+ String temp = getString(key);
+ try {
+ value = Double.parseDouble(temp);
+ } catch (NumberFormatException e) {
+ LOGGER.warn("Wrong " + key + " value format.");
+ throw new PropertyManagerException(e);
+ }
+ return value;
+ }
+
+ /**
+ * Is used to get the property with specified key. Returns property value as
+ * a double number. If property value is not found or has wrong format
+ * method will return default value.
+ *
+ * @param key The property key.
+ * @param defaultValue The value to be returned if something wrong with
+ * property value.
+ * @return The required property.
+ */
+ public double getDouble(String key, double defaultValue) {
+ double value = 0;
+ try {
+ value = getLong(key);
+ } catch (PropertyManagerException e) {
+ value = defaultValue;
+ }
+ return value;
+ }
+
+}
diff --git a/src/com/epam/devteam/util/property/PropertyManagerException.java b/src/com/epam/devteam/util/property/PropertyManagerException.java
new file mode 100644
index 0000000..acb91c2
--- /dev/null
+++ b/src/com/epam/devteam/util/property/PropertyManagerException.java
@@ -0,0 +1,49 @@
+/**
+ *
+ */
+package com.epam.devteam.util.property;
+
+/**
+ * @date Dec 18, 2013
+ * @author Andrey Kovalskiy
+ *
+ */
+public class PropertyManagerException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructs a new exception with null as its detail message.
+ */
+ public PropertyManagerException() {
+ super();
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ */
+ public PropertyManagerException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new exception with the specified cause and a detail message
+ * of (cause==null ? null : cause.toString())
+ *
+ * @param cause the cause.
+ */
+ public PropertyManagerException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param message the detail message.
+ * @param cause the cause.
+ */
+ public PropertyManagerException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/src/com/epam/devteam/util/validator/FieldType.java b/src/com/epam/devteam/util/validator/FieldType.java
new file mode 100644
index 0000000..7395f5d
--- /dev/null
+++ b/src/com/epam/devteam/util/validator/FieldType.java
@@ -0,0 +1,12 @@
+package com.epam.devteam.util.validator;
+
+/**
+ * The FieldType defines field types which can be validated.
+ *
+ * @date Jan 16, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public enum FieldType {
+ INPUT_TEXT, TEXTAREA
+}
diff --git a/src/com/epam/devteam/util/validator/RequestFieldsValidator.java b/src/com/epam/devteam/util/validator/RequestFieldsValidator.java
new file mode 100644
index 0000000..885f763
--- /dev/null
+++ b/src/com/epam/devteam/util/validator/RequestFieldsValidator.java
@@ -0,0 +1,167 @@
+package com.epam.devteam.util.validator;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import org.apache.log4j.Logger;
+
+import com.epam.devteam.util.property.PropertyManager;
+import com.epam.devteam.util.property.PropertyManagerException;
+
+/**
+ * The FieldsValidator to check fields values at null pointer
+ *
+ * @date Jan 16, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class RequestFieldsValidator {
+ private final static Logger LOGGER = Logger
+ .getLogger(RequestFieldsValidator.class);
+
+ /**
+ * Is used to check whether values are null or not.
+ *
+ * @param values The values to check.
+ * @return true if there is at least one null value, false otherwise.
+ */
+ public static boolean equalNull(String... values) {
+ boolean result = false;
+ for (int i = 0; i < values.length; i++) {
+ if (values[i] == null) {
+ result = true;
+ break;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Is used to check whether values are null or not.
+ *
+ * @param values The values to check.
+ * @return true if there is at least one empty value, false otherwise.
+ */
+ public static boolean empty(String... values) {
+ boolean result = false;
+ for (int i = 0; i < values.length; i++) {
+ if (values[i].isEmpty()) {
+ result = true;
+ break;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Is used to check whether values length is not more than max available
+ * length.
+ *
+ * @param values The values to check.
+ * @return True if all values length is valid.
+ * @throws ValidationException
+ */
+ public static boolean lengthValid(FieldType type, String... values)
+ throws ValidationException {
+ String key;
+ boolean result = true;
+ int maxLength = 0;
+ switch (type) {
+ case INPUT_TEXT:
+ key = "validation.fields.maxLength.inputText";
+ break;
+ case TEXTAREA:
+ key = "validation.fields.maxLength.textarea";
+ break;
+ default:
+ LOGGER.warn("Unknown field type.");
+ throw new ValidationException();
+ }
+ try {
+ maxLength = PropertyManager.getInstance().getInt(key);
+ } catch (PropertyManagerException e) {
+ LOGGER.warn("Input field length cannot be initialized.");
+ throw new ValidationException(e);
+ }
+ for (int i = 0; i < values.length; i++) {
+ if (values[i] == null){
+ return false;
+ }
+ if (values[i].length() > maxLength) {
+ result = false;
+ break;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Is used to check whether email value is valid.
+ *
+ * @param email The user email.
+ * @return True if email is valid, false otherwise.
+ * @throws ValidationException If property manager cannot be taken or email
+ * pattern is not valid
+ */
+ public static boolean emailValid(String email) throws ValidationException {
+ Pattern pattern;
+ Matcher matcher;
+ PropertyManager propertyManager;
+ String emailRegex;
+ try {
+ propertyManager = PropertyManager.getInstance();
+ emailRegex = propertyManager.getString("validation.email");
+ } catch (PropertyManagerException e) {
+ LOGGER.debug("Email regex cannot be taken.");
+ throw new ValidationException(e);
+ }
+ try {
+ pattern = Pattern.compile(emailRegex);
+ } catch (PatternSyntaxException e) {
+ LOGGER.debug("Email pattern cannot be compiled.");
+ throw new ValidationException(e);
+ }
+ matcher = pattern.matcher(email);
+ if (!matcher.matches()) {
+ LOGGER.debug("User email is not valid.");
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Is used to check whether password value is valid.
+ *
+ * @param password The user password to validate.
+ * @return True if password is valid, false otherwise.
+ * @throws ValidationException If property manager cannot be taken or email
+ * pattern is not valid
+ */
+ public static boolean passwordValid(String password)
+ throws ValidationException {
+ Pattern pattern;
+ Matcher matcher;
+ PropertyManager propertyManager;
+ String passwordRegex;
+ try {
+ propertyManager = PropertyManager.getInstance();
+ passwordRegex = propertyManager.getString("validation.password");
+ } catch (PropertyManagerException e) {
+ LOGGER.debug("Password regex cannot be taken.");
+ throw new ValidationException(e);
+ }
+ try {
+ pattern = Pattern.compile(passwordRegex);
+ } catch (PatternSyntaxException e) {
+ LOGGER.debug("Password pattern cannot be compiled.");
+ throw new ValidationException(e);
+ }
+ matcher = pattern.matcher(password);
+ if (!matcher.matches()) {
+ LOGGER.debug("User password is not valid.");
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/src/com/epam/devteam/util/validator/ValidationException.java b/src/com/epam/devteam/util/validator/ValidationException.java
new file mode 100644
index 0000000..bce1645
--- /dev/null
+++ b/src/com/epam/devteam/util/validator/ValidationException.java
@@ -0,0 +1,48 @@
+package com.epam.devteam.util.validator;
+
+/**
+ * The Class ...
+ *
+ * @date Jan 16, 2014
+ * @author Andrey Kovalskiy
+ *
+ */
+public class ValidationException extends Exception {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructs a new exception with null as its detail message.
+ */
+ public ValidationException() {
+ super();
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ */
+ public ValidationException(String message) {
+ super(message);
+ }
+
+ /**
+ * Constructs a new exception with the specified cause and a detail message
+ * of (cause==null ? null : cause.toString())
+ *
+ * @param cause the cause.
+ */
+ public ValidationException(Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param message the detail message.
+ * @param cause the cause.
+ */
+ public ValidationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}