diff --git a/.classpath b/.classpath index 3aa4c20..7d79d2a 100644 --- a/.classpath +++ b/.classpath @@ -2,18 +2,18 @@ - + + + + + + + + - - - - - - - - + diff --git a/WebContent/WEB-INF/jsp/about-us.jsp b/WebContent/WEB-INF/jsp/about-us.jsp new file mode 100644 index 0000000..9c57f3b --- /dev/null +++ b/WebContent/WEB-INF/jsp/about-us.jsp @@ -0,0 +1,10 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> + + + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/all-orders.jsp b/WebContent/WEB-INF/jsp/all-orders.jsp new file mode 100644 index 0000000..cda5ad6 --- /dev/null +++ b/WebContent/WEB-INF/jsp/all-orders.jsp @@ -0,0 +1,42 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + +
+

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
#
${order.id}${order.topic}${order.customer.firstName} ${order.customer.lastName}${order.customer.company}${order.date}
+ +
+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/contacts.jsp b/WebContent/WEB-INF/jsp/contacts.jsp new file mode 100644 index 0000000..319f69e --- /dev/null +++ b/WebContent/WEB-INF/jsp/contacts.jsp @@ -0,0 +1,18 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> + + +

+ : 7 Gogol str. +

+

+ : 8-7869-35-643-69 +

+

+ : postus@devteam.com +

+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/create-account.jsp b/WebContent/WEB-INF/jsp/create-account.jsp new file mode 100644 index 0000000..8acafaa --- /dev/null +++ b/WebContent/WEB-INF/jsp/create-account.jsp @@ -0,0 +1,64 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + +
+
+
+ + + +

+ + + + + +

+

+ + + + + +

+

+ +

+ + +

+ +

+
+ + + +
+ + +
+
+
+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/create-order.jsp b/WebContent/WEB-INF/jsp/create-order.jsp new file mode 100644 index 0000000..9de7e8a --- /dev/null +++ b/WebContent/WEB-INF/jsp/create-order.jsp @@ -0,0 +1,93 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + + +

+ +

+
+
+ + + + : ${user.firstName}
+ : ${user.lastName}
+ : ${user.company}
+ : ${user.position}
+ : ${user.email}
+ : ${user.phone}
+ : ${user.address}
+
+
+
+
+

+ + +

+

+ + + +

+

+ + + +

+

+ + +
+

+ + +
+
+
+
+ diff --git a/WebContent/WEB-INF/jsp/customer-orders.jsp b/WebContent/WEB-INF/jsp/customer-orders.jsp new file mode 100644 index 0000000..fc8f5a2 --- /dev/null +++ b/WebContent/WEB-INF/jsp/customer-orders.jsp @@ -0,0 +1,51 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + +
+

+ + + + + + + + + + + + + + + + + + + + + + + + + +
#
${order.id}${order.topic}${order.date} + + + + + + + + + + +
+ +
+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/edit-account.jsp b/WebContent/WEB-INF/jsp/edit-account.jsp new file mode 100644 index 0000000..41fb418 --- /dev/null +++ b/WebContent/WEB-INF/jsp/edit-account.jsp @@ -0,0 +1,172 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + +
+
+ + +
+

+ + +

+

+ + +

+

+ + +

+
+ + +
+

+ + +

+

+ + +

+
+
+ +
+

+ + + +

+
+
+
+

+
+ +

+
+
+

+ + +

+

+ + +

+
+ + +
+ + + +
+
+ + + + +
+ +
+ +
+
+ +

+ + + + + +

+

+ + + + + +

+

+ + +

+ + +
+
+
+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/edit-order.jsp b/WebContent/WEB-INF/jsp/edit-order.jsp new file mode 100644 index 0000000..aa07b23 --- /dev/null +++ b/WebContent/WEB-INF/jsp/edit-order.jsp @@ -0,0 +1,109 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + + +

+ #${order.id} +

+

+ : ${order.date}
+ : + +

+
+
+ + + + : ${user.firstName}
+ : ${user.lastName}
+ : ${user.company}
+ : ${user.position}
+ : ${user.email}
+ : ${user.phone}
+ : ${user.address}
+
+
+
+
+ +

+ + +

+

+ + + +

+

+ + + +

+ +

+ + ${order.fileName} +

+
+

+ + +
+

+ + +
+
+
+
diff --git a/WebContent/WEB-INF/jsp/error.jsp b/WebContent/WEB-INF/jsp/error.jsp new file mode 100644 index 0000000..8aca2b9 --- /dev/null +++ b/WebContent/WEB-INF/jsp/error.jsp @@ -0,0 +1,17 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + errorPage="true" pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + +
+

+ +

+ + +
+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/main.jsp b/WebContent/WEB-INF/jsp/main.jsp new file mode 100644 index 0000000..82153b6 --- /dev/null +++ b/WebContent/WEB-INF/jsp/main.jsp @@ -0,0 +1,34 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> + + +

+ +

+
+ +
+
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras molestie ultrices diam, vel adipiscing est auctor eu. Nulla egestas ultrices lectus, ut cursus risus semper at. Aliquam vulputate lectus id ligula dapibus porttitor. Aliquam scelerisque elit nec lacus bibendum fermentum. Integer placerat est tortor. Pellentesque cursus eu orci non suscipit. +
+

+ +

+
Sed fermentum mauris porta lacinia rhoncus. Duis sit amet odio id leo ullamcorper cursus vel at nunc. In id libero dignissim leo elementum placerat in at ante. Donec lacinia, ligula eu venenatis elementum, arcu mauris feugiat tellus, sit amet lacinia orci felis sed elit. Cras at purus a ligula dictum fermentum. Proin condimentum aliquet sodales. Ut felis nisi, porttitor in tellus sed, bibendum pellentesque neque. Ut egestas mi vel enim consequat, vitae rhoncus lacus pulvinar. Vestibulum tempus dolor ligula. In vitae odio lectus. Donec consequat libero eget ipsum tincidunt lobortis. Nulla tincidunt velit sed nisi lacinia ornare. Sed vel mollis quam. Duis pretium quam mauris, eu sagittis mi eleifend at.
+
+ +
+

+ +

+
+ +
+
+ Pellentesque cursus sapien fermentum, consectetur nisi faucibus, porttitor nibh. Duis tempor, mauris ut dignissim convallis, enim mauris pellentesque risus, vel consectetur purus elit ut diam. In luctus purus nec mauris congue volutpat. Suspendisse feugiat consectetur imperdiet. Aliquam bibendum, quam sed fringilla commodo, nisl tortor adipiscing felis, in rutrum tellus velit quis nisl. Donec non purus adipiscing, consectetur felis ut, euismod lorem. Integer viverra sit amet felis et aliquet. Integer id ipsum bibendum, aliquet mauris in, rutrum velit. Sed eu sem felis. Vestibulum tortor ipsum, accumsan sit amet risus vitae, tempor euismod nulla. Ut sagittis imperdiet metus, nec blandit felis consequat quis. Nunc sit amet odio id neque fringilla eleifend. +
+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/manage-accounts.jsp b/WebContent/WEB-INF/jsp/manage-accounts.jsp new file mode 100644 index 0000000..57b1300 --- /dev/null +++ b/WebContent/WEB-INF/jsp/manage-accounts.jsp @@ -0,0 +1,60 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> + + +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Id
${user.id}${user.email}${user.firstName}${user.lastName}${user.registrationDate} + + + + + + + + + + + + + + + + + +
+ +
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/jsp/order.jsp b/WebContent/WEB-INF/jsp/order.jsp new file mode 100644 index 0000000..765fcee --- /dev/null +++ b/WebContent/WEB-INF/jsp/order.jsp @@ -0,0 +1,105 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + +

+ #${order.id} +

+

+ : ${order.date}
+ : + +
+

+
+
+ + + + + : + ${isCustomer ? user.firstName : order.customer.firstName}
+ : + ${isCustomer ? user.lastName : order.customer.lastName}
+ : + ${isCustomer ? user.company : order.customer.company}
+ : + ${isCustomer ? user.position : order.customer.position}
+ : + ${isCustomer ? user.email : order.customer.email}
+ : + ${isCustomer ? user.phone : order.customer.phone}
+ : + ${isCustomer ? user.address : order.customer.address}
+
+
+
+

+ + " /> +

+

+ + +

+

+ + +

+ +

+ + ${order.fileName} +

+
+
+ + + +
+
+ + +
+
+
+
+ + +
+
+
+ +
+ + +
+
+
+
+ + + +
+
+ diff --git a/WebContent/WEB-INF/jsp/process-order.jsp b/WebContent/WEB-INF/jsp/process-order.jsp new file mode 100644 index 0000000..eab25fa --- /dev/null +++ b/WebContent/WEB-INF/jsp/process-order.jsp @@ -0,0 +1,64 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + + + +

+ +

+
+ +

+ + +

+

+ + + +

+

+ + + +

+ +
+
+
+ diff --git a/WebContent/WEB-INF/jsp/success.jsp b/WebContent/WEB-INF/jsp/success.jsp new file mode 100644 index 0000000..d37b26a --- /dev/null +++ b/WebContent/WEB-INF/jsp/success.jsp @@ -0,0 +1,20 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + errorPage="true" pageEncoding="UTF-8"%> + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + +
+

+ + +
+ Click here +
+

+
+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/tags/account.tag b/WebContent/WEB-INF/tags/account.tag new file mode 100644 index 0000000..bd4bc4f --- /dev/null +++ b/WebContent/WEB-INF/tags/account.tag @@ -0,0 +1,66 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +
+ + +
+ + + +

+ ${user.firstName} ${user.lastName} +

+ +

+ ${user.company} +

+

+ ${user.position} +

+
+
+ +
+
+ + +
+
+ +
+ +
+
+ + + + +

+ + +

+

+ +

+ + + +
+
+
+
+
+ diff --git a/WebContent/WEB-INF/tags/administrator-tools.tag b/WebContent/WEB-INF/tags/administrator-tools.tag new file mode 100644 index 0000000..46c9776 --- /dev/null +++ b/WebContent/WEB-INF/tags/administrator-tools.tag @@ -0,0 +1,20 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +
+ + + +
+ +
+
+ + + +
+
+ diff --git a/WebContent/WEB-INF/tags/customer-tools.tag b/WebContent/WEB-INF/tags/customer-tools.tag new file mode 100644 index 0000000..a20760e --- /dev/null +++ b/WebContent/WEB-INF/tags/customer-tools.tag @@ -0,0 +1,19 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +
+ + + +
+ +
+
+ + + +
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/tags/date.tag b/WebContent/WEB-INF/tags/date.tag new file mode 100644 index 0000000..1f2b9ce --- /dev/null +++ b/WebContent/WEB-INF/tags/date.tag @@ -0,0 +1,32 @@ +<%@tag import="java.text.AttributedCharacterIterator.Attribute"%> +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ attribute name="date" required="true" type="java.sql.Date"%> + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/tags/error-info.tag b/WebContent/WEB-INF/tags/error-info.tag new file mode 100644 index 0000000..91718e5 --- /dev/null +++ b/WebContent/WEB-INF/tags/error-info.tag @@ -0,0 +1,9 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ attribute name="error" required="true"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> + +
+ +
+
diff --git a/WebContent/WEB-INF/tags/feedback-info.tag b/WebContent/WEB-INF/tags/feedback-info.tag new file mode 100644 index 0000000..0664f2d --- /dev/null +++ b/WebContent/WEB-INF/tags/feedback-info.tag @@ -0,0 +1,34 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +<%@ attribute name="feedback" required="true" type="com.epam.devteam.entity.feedback.Feedback"%> +

+ +

+
+
+ + + + : ${feedback.manager.firstName}
+ : ${feedback.manager.lastName}
+ : ${feedback.manager.email}
+ : ${feedback.manager.phone}
+ : ${feedback.manager.address}
+
+
+
+

+ + +

+

+ + ${feedback.fileName} +

+
\ No newline at end of file diff --git a/WebContent/WEB-INF/tags/footer.tag b/WebContent/WEB-INF/tags/footer.tag new file mode 100644 index 0000000..f5c406a --- /dev/null +++ b/WebContent/WEB-INF/tags/footer.tag @@ -0,0 +1,17 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +
+ This site was developed by Andrey Kovalskiy for JavaLab + courses. +
+
+ +
+ +
+
diff --git a/WebContent/WEB-INF/tags/genericpage.tag b/WebContent/WEB-INF/tags/genericpage.tag new file mode 100644 index 0000000..86ee389 --- /dev/null +++ b/WebContent/WEB-INF/tags/genericpage.tag @@ -0,0 +1,45 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ attribute name="sidebar" required="true"%> +<%@ attribute name="title" required="true"%> +<%@ attribute name="body" fragment="true"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> + + + +${title} + + + + + +
+ + +
+ + + +
+ +
+
+ + + +
+
+ + +
+ + diff --git a/WebContent/WEB-INF/tags/header.tag b/WebContent/WEB-INF/tags/header.tag new file mode 100644 index 0000000..cc5b07d --- /dev/null +++ b/WebContent/WEB-INF/tags/header.tag @@ -0,0 +1,12 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +
+

Development Team

+
+
+

+ + + +

+
\ No newline at end of file diff --git a/WebContent/WEB-INF/tags/manager-tools.tag b/WebContent/WEB-INF/tags/manager-tools.tag new file mode 100644 index 0000000..eeeabb1 --- /dev/null +++ b/WebContent/WEB-INF/tags/manager-tools.tag @@ -0,0 +1,14 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +
+ + + +
+ + + +
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/tags/order-info.tag b/WebContent/WEB-INF/tags/order-info.tag new file mode 100644 index 0000000..5244b4f --- /dev/null +++ b/WebContent/WEB-INF/tags/order-info.tag @@ -0,0 +1,69 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> +<%@ attribute name="order" required="true" type="com.epam.devteam.entity.order.Order"%> +

+ #${order.id} +

+

+ : ${order.date}
+ : +
+ + + + + +

+
+
+ + + + + : + ${isCustomer ? user.firstName : order.customer.firstName}
+ : + ${isCustomer ? user.lastName : order.customer.lastName}
+ : + ${isCustomer ? user.company : order.customer.company}
+ : + ${isCustomer ? user.position : order.customer.position}
+ : + ${isCustomer ? user.email : order.customer.email}
+ : + ${isCustomer ? user.phone : order.customer.phone}
+ : + ${isCustomer ? user.address : order.customer.address}
+
+
+
+

+ + "/> +

+

+ + +

+

+ + +

+ +

+ + ${order.fileName} +

+
+
\ No newline at end of file diff --git a/WebContent/WEB-INF/tags/order-status-info.tag b/WebContent/WEB-INF/tags/order-status-info.tag new file mode 100644 index 0000000..1fee0f8 --- /dev/null +++ b/WebContent/WEB-INF/tags/order-status-info.tag @@ -0,0 +1,24 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ attribute name="status" required="true" %> + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/tags/order-subject-info.tag b/WebContent/WEB-INF/tags/order-subject-info.tag new file mode 100644 index 0000000..2937e6c --- /dev/null +++ b/WebContent/WEB-INF/tags/order-subject-info.tag @@ -0,0 +1,16 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ attribute name="subject" required="true" %> + + + + + + + + + + + + \ No newline at end of file diff --git a/WebContent/WEB-INF/tags/paging-controller.tag b/WebContent/WEB-INF/tags/paging-controller.tag new file mode 100644 index 0000000..b9ea5cc --- /dev/null +++ b/WebContent/WEB-INF/tags/paging-controller.tag @@ -0,0 +1,35 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ attribute name="action" required="true"%> + + + + +
+
+ + + +
+
+ +
+
+
+ + + +
+ diff --git a/WebContent/WEB-INF/tags/role-info.tag b/WebContent/WEB-INF/tags/role-info.tag new file mode 100644 index 0000000..94450d2 --- /dev/null +++ b/WebContent/WEB-INF/tags/role-info.tag @@ -0,0 +1,21 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ attribute name="role" required="true"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + + + + + + + + + + + + + ${role} + + diff --git a/WebContent/WEB-INF/tags/sidebar.tag b/WebContent/WEB-INF/tags/sidebar.tag new file mode 100644 index 0000000..2d8a9e2 --- /dev/null +++ b/WebContent/WEB-INF/tags/sidebar.tag @@ -0,0 +1,14 @@ +<%@ tag language="java" pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%> + + + + + + + + + + + diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml index e1e4ab0..6d39237 100644 --- a/WebContent/WEB-INF/web.xml +++ b/WebContent/WEB-INF/web.xml @@ -1,12 +1,70 @@ - + devteam - index.html - index.htm index.jsp - default.html - default.htm - default.jsp + + + Controller + Controller + com.epam.devteam.servlet.Controller + + + Controller + /do/* + + + + ErrorHandler + ErrorHandler + com.epam.devteam.servlet.ErrorHandler + + + ErrorHandler + /do/error-handler + + + + java.lang.Throwable + + /do/error-handler + + + + ContextListener + com.epam.devteam.listener.ContextListener + + + CharsetFilter + com.epam.devteam.filter.CharsetFilter + + + CharsetFilter + /* + + + CacheControlFilter + com.epam.devteam.filter.CacheControlFilter + + + CacheControlFilter + /* + + + SecurityFilter + com.epam.devteam.filter.SecurityFilter + + + SecurityFilter + /* + + + javax.servlet.jsp.jstl.fmt.localizationContext + messages + + + javax.servlet.jsp.jstl.fmt.fallbackLocale + en_US + \ No newline at end of file diff --git a/WebContent/css/print.css b/WebContent/css/print.css new file mode 100644 index 0000000..bd79afd --- /dev/null +++ b/WebContent/css/print.css @@ -0,0 +1,29 @@ +/* ----------------------------------------------------------------------- + + + Blueprint CSS Framework 1.0.1 + http://blueprintcss.org + + * Copyright (c) 2007-Present. See LICENSE for more info. + * See README for instructions on how to use Blueprint. + * For credits and origins, see AUTHORS. + * This is a compressed file. See the sources in the 'src' directory. + +----------------------------------------------------------------------- */ + +/* print.css */ +body {line-height:1.5;font-family:"Helvetica Neue", Arial, Helvetica, sans-serif;color:#000;background:none;font-size:10pt;} +.container {background:none;} +hr {background:#ccc;color:#ccc;width:100%;height:2px;margin:2em 0;padding:0;border:none;} +hr.space {background:#fff;color:#fff;visibility:hidden;} +h1, h2, h3, h4, h5, h6 {font-family:"Helvetica Neue", Arial, "Lucida Grande", sans-serif;} +code {font:.9em "Courier New", Monaco, Courier, monospace;} +a img {border:none;} +p img.top {margin-top:0;} +blockquote {margin:1.5em;padding:1em;font-style:italic;font-size:.9em;} +.small {font-size:.9em;} +.large {font-size:1.1em;} +.quiet {color:#999;} +.hide {display:none;} +a:link, a:visited {background:transparent;font-weight:700;text-decoration:underline;} +a:link:after, a:visited:after {content:" (" attr(href) ")";font-size:90%;} \ No newline at end of file diff --git a/WebContent/css/screen.css b/WebContent/css/screen.css new file mode 100644 index 0000000..9d9e0d7 --- /dev/null +++ b/WebContent/css/screen.css @@ -0,0 +1,269 @@ +/* ----------------------------------------------------------------------- + + + Blueprint CSS Framework 1.0.1 + http://blueprintcss.org + + * Copyright (c) 2007-Present. See LICENSE for more info. + * See README for instructions on how to use Blueprint. + * For credits and origins, see AUTHORS. + * This is a compressed file. See the sources in the 'src' directory. + +----------------------------------------------------------------------- */ + +/* reset.css */ + +body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, dialog, figure, footer, header, hgroup, nav, section {margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;} +article, aside, details, figcaption, figure, dialog, footer, header, hgroup, menu, nav, section {display:block;} +body {line-height:1.5;background:white;} +table {border-collapse:separate;border-spacing:0;} +caption, th, td {text-align:left;font-weight:normal;float:none !important;} +table, th, td {vertical-align:middle;} +blockquote:before, blockquote:after, q:before, q:after {content:'';} +blockquote, q {quotes:"" "";} +a img {border:none;} +:focus {outline:0;} + +/* typography.css */ +html {font-size:100.01%;} +body {font-size:75%;color:#222;background:#fff;font-family:"Helvetica Neue", Arial, Helvetica, sans-serif;} +h1, h2, h3, h4, h5, h6 {font-weight:normal;color:#111; } +h1 {font-size:3em;line-height:1;margin-bottom:0.5em;} +h2 {font-size:2em;margin-bottom:0.75em;} +h3 {font-size:1.5em;line-height:1;margin-bottom:1em;} +h4 {font-size:1.2em;line-height:1.25;margin-bottom:1.25em;} +h5 {font-size:1em;font-weight:bold;margin-bottom:1.5em;} +h6 {font-size:1em;font-weight:bold;} +h1 img, h2 img, h3 img, h4 img, h5 img, h6 img {margin:0;} +p {margin:0 0 1.5em;} +.left {float:left !important;} +p .left {margin:1.5em 1.5em 1.5em 0;padding:0;} +.right {float:right !important;} +p .right {margin:1.5em 0 1.5em 1.5em;padding:0;} +a:focus, a:hover {color:#09f;} +a {color:#06c;text-decoration:underline;} +blockquote {margin:1.5em;color:#666;font-style:italic;} +strong, dfn {font-weight:bold;} +em, dfn {font-style:italic;} +sup, sub {line-height:0;} +abbr, acronym {border-bottom:1px dotted #666;} +address {margin:0 0 1.5em;font-style:italic;} +del {color:#666;} +pre {margin:1.5em 0;white-space:pre;} +pre, code, tt {font:1em 'andale mono', 'lucida console', monospace;line-height:1.5;} +li ul, li ol {margin:0;} +ul, ol {margin:0 1.5em 1.5em 0;padding-left:1.5em;} +ul {list-style-type:disc;} +ol {list-style-type:decimal;} +dl {margin:0 0 1.5em 0;} +dl dt {font-weight:bold;} +dd {margin-left:1.5em;} +table {margin-bottom:1.4em;width:100%;} +th {font-weight:bold;} +thead th {background:orange;color:white} +th, td, caption {padding:4px 10px 4px 5px;} +tbody tr:nth-child(even) td, tbody tr.even td {background:#FFCC33;} +tfoot {font-style:italic;} +caption {background:#eee;} +.small {font-size:.8em;margin-bottom:1.875em;line-height:1.875em;} +.large {font-size:1.2em;line-height:2.5em;margin-bottom:1.25em;} +.hide {display:none;} +.quiet {color:#666;} +.loud {color:#000;} +.highlight {background:#ff0;} +.added {background:#060;color:#fff;} +.removed {background:#900;color:#fff;} +.first {margin-left:0;padding-left:0;} +.last {margin-right:0;padding-right:0;} +.top {margin-top:0;padding-top:0;} +.bottom {margin-bottom:0;padding-bottom:0;} + +/* forms.css */ +button {background: orange; color: white} +label {font-weight:bold;} +fieldset {padding:0 1.4em 1.4em 1.4em;margin:0 0 1.5em 0;border:1px solid #ccc;border-color: orange} +legend {font-weight:bold;font-size:1.2em;margin-top:-0.2em;margin-bottom:1em; } +fieldset, #IE8#HACK {padding-top:1.4em;} +legend, #IE8#HACK {margin-top:0;margin-bottom:0; } +input[type=text], input[type=password], input[type=url], input[type=email], input.text, input.title, textarea {background-color:#fff;border:1px solid #bbb;color:#000;border-color:orange;} +input[type=text]:focus, input[type=password]:focus, input[type=url]:focus, input[type=email]:focus, input.text:focus, input.title:focus, textarea:focus {border-color:red;} +select {background-color:#fff;border-width:1px;border-style:solid;border-color: orange;} +input[type=text], input[type=password], input[type=url], input[type=email], input.text, input.title, textarea, select {margin:0.5em 0;} +input.text, input.title {width:300px;padding:5px;} +input.title {font-size:1.5em;} +textarea {width:390px;height:250px;padding:5px;border-color: orange} +form.inline {line-height:3;} +form.inline p {margin-bottom:0;} +.error, .alert, .notice, .success, .info, .banner {padding:0.8em;margin-bottom:1em;border:2px solid #ddd;} +.error, .alert {background:#fbe3e4;color:#8a1f11;border-color:#fbc2c4;} +.notice {background:#fff6bf;color:#514721;border-color:#ffd324;} +.success {background:#e6efc2;color:#264409;border-color:#c6d880;} +.info {background:#d5edf8;color:#205791;border-color:#92cae4;} +.error a, .alert a {color:#8a1f11;} +.banner {background:orange;color:#514721;border-color:#ffd324;} +.notice a {color:#514721;} +.success a {color:#264409;} +.info a {color:#205791;} +.banner h1 {color:white;} +.banner a {color:white;} + +/* grid.css */ +.container {width:950px;margin:0 auto;} +.showgrid {background:url(src/grid.png);} +.column, .span-1, .span-2, .span-3, .span-4, .span-5, .span-6, .span-7, .span-8, .span-9, .span-10, .span-11, .span-12, .span-13, .span-14, .span-15, .span-16, .span-17, .span-18, .span-19, .span-20, .span-21, .span-22, .span-23, .span-24 {float:left;margin-right:10px;} +.last {margin-right:0;} +.span-1 {width:30px;} +.span-2 {width:70px;} +.span-3 {width:110px;} +.span-4 {width:150px;} +.span-5 {width:190px;} +.span-6 {width:230px;} +.span-7 {width:270px;} +.span-8 {width:310px;} +.span-9 {width:350px;} +.span-10 {width:390px;} +.span-11 {width:430px;} +.span-12 {width:470px;} +.span-13 {width:510px;} +.span-14 {width:550px;} +.span-15 {width:590px;} +.span-16 {width:630px;} +.span-17 {width:670px;} +.span-18 {width:710px;} +.span-19 {width:750px;} +.span-20 {width:790px;} +.span-21 {width:830px;} +.span-22 {width:870px;} +.span-23 {width:910px;} +.span-24 {width:950px;margin-right:0;} +input.span-1, textarea.span-1, input.span-2, textarea.span-2, input.span-3, textarea.span-3, input.span-4, textarea.span-4, input.span-5, textarea.span-5, input.span-6, textarea.span-6, input.span-7, textarea.span-7, input.span-8, textarea.span-8, input.span-9, textarea.span-9, input.span-10, textarea.span-10, input.span-11, textarea.span-11, input.span-12, textarea.span-12, input.span-13, textarea.span-13, input.span-14, textarea.span-14, input.span-15, textarea.span-15, input.span-16, textarea.span-16, input.span-17, textarea.span-17, input.span-18, textarea.span-18, input.span-19, textarea.span-19, input.span-20, textarea.span-20, input.span-21, textarea.span-21, input.span-22, textarea.span-22, input.span-23, textarea.span-23, input.span-24, textarea.span-24 {border-left-width:1px;border-right-width:1px;padding-left:5px;padding-right:5px;} +input.span-1, textarea.span-1 {width:18px;} +input.span-2, textarea.span-2 {width:58px;} +input.span-3, textarea.span-3 {width:98px;} +input.span-4, textarea.span-4 {width:138px;} +input.span-5, textarea.span-5 {width:178px;} +input.span-6, textarea.span-6 {width:218px;} +input.span-7, textarea.span-7 {width:258px;} +input.span-8, textarea.span-8 {width:298px;} +input.span-9, textarea.span-9 {width:338px;} +input.span-10, textarea.span-10 {width:378px;} +input.span-11, textarea.span-11 {width:418px;} +input.span-12, textarea.span-12 {width:458px;} +input.span-13, textarea.span-13 {width:498px;} +input.span-14, textarea.span-14 {width:538px;} +input.span-15, textarea.span-15 {width:578px;} +input.span-16, textarea.span-16 {width:618px;} +input.span-17, textarea.span-17 {width:658px;} +input.span-18, textarea.span-18 {width:698px;} +input.span-19, textarea.span-19 {width:738px;} +input.span-20, textarea.span-20 {width:778px;} +input.span-21, textarea.span-21 {width:818px;} +input.span-22, textarea.span-22 {width:858px;} +input.span-23, textarea.span-23 {width:898px;} +input.span-24, textarea.span-24 {width:938px;} +.append-1 {padding-right:40px;} +.append-2 {padding-right:80px;} +.append-3 {padding-right:120px;} +.append-4 {padding-right:160px;} +.append-5 {padding-right:200px;} +.append-6 {padding-right:240px;} +.append-7 {padding-right:280px;} +.append-8 {padding-right:320px;} +.append-9 {padding-right:360px;} +.append-10 {padding-right:400px;} +.append-11 {padding-right:440px;} +.append-12 {padding-right:480px;} +.append-13 {padding-right:520px;} +.append-14 {padding-right:560px;} +.append-15 {padding-right:600px;} +.append-16 {padding-right:640px;} +.append-17 {padding-right:680px;} +.append-18 {padding-right:720px;} +.append-19 {padding-right:760px;} +.append-20 {padding-right:800px;} +.append-21 {padding-right:840px;} +.append-22 {padding-right:880px;} +.append-23 {padding-right:920px;} +.prepend-1 {padding-left:40px;} +.prepend-2 {padding-left:80px;} +.prepend-3 {padding-left:120px;} +.prepend-4 {padding-left:160px;} +.prepend-5 {padding-left:200px;} +.prepend-6 {padding-left:240px;} +.prepend-7 {padding-left:280px;} +.prepend-8 {padding-left:320px;} +.prepend-9 {padding-left:360px;} +.prepend-10 {padding-left:400px;} +.prepend-11 {padding-left:440px;} +.prepend-12 {padding-left:480px;} +.prepend-13 {padding-left:520px;} +.prepend-14 {padding-left:560px;} +.prepend-15 {padding-left:600px;} +.prepend-16 {padding-left:640px;} +.prepend-17 {padding-left:680px;} +.prepend-18 {padding-left:720px;} +.prepend-19 {padding-left:760px;} +.prepend-20 {padding-left:800px;} +.prepend-21 {padding-left:840px;} +.prepend-22 {padding-left:880px;} +.prepend-23 {padding-left:920px;} +.border {padding-right:4px;margin-right:5px;border-right:1px solid #ddd;} +.colborder {padding-right:24px;margin-right:25px;border-right:1px solid #ddd;border-color: orange} +.pull-1 {margin-left:-40px;} +.pull-2 {margin-left:-80px;} +.pull-3 {margin-left:-120px;} +.pull-4 {margin-left:-160px;} +.pull-5 {margin-left:-200px;} +.pull-6 {margin-left:-240px;} +.pull-7 {margin-left:-280px;} +.pull-8 {margin-left:-320px;} +.pull-9 {margin-left:-360px;} +.pull-10 {margin-left:-400px;} +.pull-11 {margin-left:-440px;} +.pull-12 {margin-left:-480px;} +.pull-13 {margin-left:-520px;} +.pull-14 {margin-left:-560px;} +.pull-15 {margin-left:-600px;} +.pull-16 {margin-left:-640px;} +.pull-17 {margin-left:-680px;} +.pull-18 {margin-left:-720px;} +.pull-19 {margin-left:-760px;} +.pull-20 {margin-left:-800px;} +.pull-21 {margin-left:-840px;} +.pull-22 {margin-left:-880px;} +.pull-23 {margin-left:-920px;} +.pull-24 {margin-left:-960px;} +.pull-1, .pull-2, .pull-3, .pull-4, .pull-5, .pull-6, .pull-7, .pull-8, .pull-9, .pull-10, .pull-11, .pull-12, .pull-13, .pull-14, .pull-15, .pull-16, .pull-17, .pull-18, .pull-19, .pull-20, .pull-21, .pull-22, .pull-23, .pull-24 {float:left;position:relative;} +.push-1 {margin:0 -40px 1.5em 40px;} +.push-2 {margin:0 -80px 1.5em 80px;} +.push-3 {margin:0 -120px 1.5em 120px;} +.push-4 {margin:0 -160px 1.5em 160px;} +.push-5 {margin:0 -200px 1.5em 200px;} +.push-6 {margin:0 -240px 1.5em 240px;} +.push-7 {margin:0 -280px 1.5em 280px;} +.push-8 {margin:0 -320px 1.5em 320px;} +.push-9 {margin:0 -360px 1.5em 360px;} +.push-10 {margin:0 -400px 1.5em 400px;} +.push-11 {margin:0 -440px 1.5em 440px;} +.push-12 {margin:0 -480px 1.5em 480px;} +.push-13 {margin:0 -520px 1.5em 520px;} +.push-14 {margin:0 -560px 1.5em 560px;} +.push-15 {margin:0 -600px 1.5em 600px;} +.push-16 {margin:0 -640px 1.5em 640px;} +.push-17 {margin:0 -680px 1.5em 680px;} +.push-18 {margin:0 -720px 1.5em 720px;} +.push-19 {margin:0 -760px 1.5em 760px;} +.push-20 {margin:0 -800px 1.5em 800px;} +.push-21 {margin:0 -840px 1.5em 840px;} +.push-22 {margin:0 -880px 1.5em 880px;} +.push-23 {margin:0 -920px 1.5em 920px;} +.push-24 {margin:0 -960px 1.5em 960px;} +.push-1, .push-2, .push-3, .push-4, .push-5, .push-6, .push-7, .push-8, .push-9, .push-10, .push-11, .push-12, .push-13, .push-14, .push-15, .push-16, .push-17, .push-18, .push-19, .push-20, .push-21, .push-22, .push-23, .push-24 {float:left;position:relative;} +div.prepend-top, .prepend-top {margin-top:1.5em;} +div.append-bottom, .append-bottom {margin-bottom:1.5em;} +.box {padding:1.5em;margin-bottom:1.5em;background:#e5eCf9;} +hr {background:orange;color:#ddd;clear:both;float:none;width:100%;height:1px;margin:0 0 17px;border:none;} +hr.space {background:#fff;color:#fff;visibility:hidden;} +.clearfix:after, .container:after {content:"\0020";display:block;height:0;clear:both;visibility:hidden;overflow:hidden;} +.clearfix, .container {display:block;} +.clear {clear:both;} \ No newline at end of file diff --git a/WebContent/index.jsp b/WebContent/index.jsp new file mode 100644 index 0000000..5562575 --- /dev/null +++ b/WebContent/index.jsp @@ -0,0 +1,3 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> + \ No newline at end of file diff --git a/WebContent/static/activate.png b/WebContent/static/activate.png new file mode 100644 index 0000000..f951f9f Binary files /dev/null and b/WebContent/static/activate.png differ diff --git a/WebContent/static/delete.png b/WebContent/static/delete.png new file mode 100644 index 0000000..9b87de5 Binary files /dev/null and b/WebContent/static/delete.png differ diff --git a/WebContent/static/development.jpg b/WebContent/static/development.jpg new file mode 100644 index 0000000..9a4b523 Binary files /dev/null and b/WebContent/static/development.jpg differ diff --git a/WebContent/static/edit.png b/WebContent/static/edit.png new file mode 100644 index 0000000..b659af1 Binary files /dev/null and b/WebContent/static/edit.png differ diff --git a/WebContent/static/error.png b/WebContent/static/error.png new file mode 100644 index 0000000..cafb568 Binary files /dev/null and b/WebContent/static/error.png differ diff --git a/WebContent/static/support.jpg b/WebContent/static/support.jpg new file mode 100644 index 0000000..3ad318d Binary files /dev/null and b/WebContent/static/support.jpg differ diff --git a/WebContent/static/team.jpg b/WebContent/static/team.jpg new file mode 100644 index 0000000..7256cf4 Binary files /dev/null and b/WebContent/static/team.jpg differ diff --git a/WebContent/static/testing.jpeg b/WebContent/static/testing.jpeg new file mode 100644 index 0000000..4e447ee Binary files /dev/null and b/WebContent/static/testing.jpeg differ diff --git a/WebContent/static/trash-delete.png b/WebContent/static/trash-delete.png new file mode 100644 index 0000000..745665e Binary files /dev/null and b/WebContent/static/trash-delete.png differ diff --git a/resources/log4j.properties b/resources/log4j.properties new file mode 100644 index 0000000..6b851f9 --- /dev/null +++ b/resources/log4j.properties @@ -0,0 +1,16 @@ +# Root logger option +log4j.rootLogger=DEBUG, file, stdout + +# Direct log messages to a log file +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=/home/anjey/loging.log +log4j.appender.file.MaxFileSize=1MB +log4j.appender.file.MaxBackupIndex=1 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}: - %m%n + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}: - %m%n \ No newline at end of file diff --git a/resources/messages_en.properties b/resources/messages_en.properties new file mode 100644 index 0000000..1349b60 --- /dev/null +++ b/resources/messages_en.properties @@ -0,0 +1,103 @@ +error.serverError = 500 Internal server error. +error.notFound = 404 not found. +error.badRequest = 400 Bad request. +error.accessDenied = 403 Forbidden. +error.actionFailed = This operation is not available now. Please try later. + +account.emailEmpty = Email is empty. +account.emailNotValid = Email is not valid. +account.passwordEmpty = Password is empty. +account.passwordNotValid = Password is not valid. +account.passwordsDontMatch = Passwords don't match. +account.oldPasswordWrong = Old password is wrong. +account.changePasswordSuccess = Password was changed successfully. You can continue to edit account. +account.userAlreadyExists = Account with this email is already exists. +account.createSuccess = Account has been created successfully. You can edit personal information. +account.saveSuccess = Account has been saved successfully. You can continue to edit account. +account.deactivateSuccess = Account has been deactivated successfully. +account.activateSuccess = Account has been activated successfully. +account.enterEmailAndPassword = Enter email and password. +account.notFound = Account with such combination of email and password is not found. +account.notActive = Account is not active. Contact the site administration. +account.notChanged = There are no changes to save. +password.help = Password length should be at least 8 characters. Password should contain at least one number, one lower case character, one upper case character. + +header.main = Main +header.contacts = Contacts +header.aboutUs = About Us + +common.user = User +common.accounts = Accounts +common.email = Email +common.password = Password +common.oldPassword = Old password +common.newPassword = New password +common.createPassword = Create password +common.confirmPassword = Confirm password +common.firstName = First Name +common.lastName = Last Name +common.birthDate = Birth Date +common.company = Company +common.position = Position +common.qualification = Qualification +common.address = Address +common.phone = Phone +common.date = Date +common.status = Status +common.active = Active +common.notActive = Not Active +common.role = Role +common.registered = Registered +common.role.customer = Customer +common.role.developer = Developer +common.role.manager = Manager +common.role.administrator = Administrator +common.tools = Tools +common.tools.administrator = Administration +common.tools.manager = Management +common.tools.customer = Customer tools +common.newOrder = New Order +common.order = Order +common.orders = Orders +common.orderNewStatus = Order new status +common.feedback = Feedback +common.customerInfo = Customer Info +common.managerInfo = Manager Info +common.subject = Subject +common.other = Other +common.applicationDevelopment = Application Development +common.applicationTesting = Application Testing +common.applicationSupport = Application Support +common.topic = Topic +common.message = Message (up to 2000 symbols) +common.attachFile = Attach file (up to 10Mb) +common.file = File + +action.submit = Submit +action.signIn = Sign in +action.signOut = Sign out +action.createAccount = Create an account +action.editAccount = Edit account +action.editAccounts = Edit accounts +action.saveAccount = Save account +action.changePassword = Change password +action.createOrder = Create order +action.editOrder = Edit order +action.terminateOrder = Terminate order +action.saveOrder = Save order +action.processOrder = Process order +action.allOrders = All orders +action.readFeedback = Read Feedback + +tag.paging.next = Next +tag.paging.previous = Previous + +order.topicEmpty = Topic is Empty +order.messageEmpty = Message is Empty +order.createSuccess = Order has been created successfully. +order.terminateSuccess = Order has been terminated successfully. +order.saveSuccess = Order has been saved successfully. +order.status.pending = Pending +order.status.terminated = Terminated +order.status.accepted = Accepted +order.status.denied = Denied diff --git a/resources/messages_ru.properties b/resources/messages_ru.properties new file mode 100644 index 0000000..a16e3ad --- /dev/null +++ b/resources/messages_ru.properties @@ -0,0 +1,102 @@ +error.serverError = 500 \u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +error.notFound = 404 \u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E +error.badRequest = 400 \u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0437\u0430\u043F\u0440\u043E\u0441 +error.accessDenied = 403 \u0417\u0430\u043F\u0440\u0435\u0449\u0435\u043Do +error.actionFailed = \u0412 \u0434\u0430\u043D\u043D\u044B\u0439 \u043C\u043E\u043C\u0435\u043D\u0442 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435 \u043E\u043F\u0435\u0440\u0430\u0446\u0438\u0438 \u043D\u0435 \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E. \u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0435 \u043F\u043E\u043F\u044B\u0442\u043A\u0443 \u043F\u043E\u0437\u0434\u043D\u0435\u0435 + +account.emailEmpty = \u041F\u043E\u043B\u0435 \u044D\u043B.\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0435 \u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u043D\u043E +account.emailNotValid = \u042D\u043B.\u0430\u0434\u0440\u0435\u0441 \u043D\u0435 \u0432\u0435\u0440\u0435\u043D +account.passwordEmpty = \u041F\u043E\u043B\u0435 \u043F\u0430\u0440\u043E\u043B\u044F \u043D\u0435 \u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u043D\u043E +account.passwordNotValid = \u041F\u0430\u0440\u043E\u043B\u044C \u043D\u0435 \u0432\u0435\u0440\u0435\u043D +account.passwordsDontMatch = \u041F\u0430\u0440\u043E\u043B\u0438 \u043D\u0435 \u0441\u043E\u0432\u043F\u0430\u0434\u0430\u044E\u0442 +account.oldPasswordWrong = \u0421\u0442\u0430\u0440\u044B\u0439 \u043F\u0430\u0440\u043E\u043B\u044C \u043D\u0435 \u0432\u0435\u0440\u0435\u043D +account.changePasswordSuccess = \u041F\u0430\u0440\u043E\u043B\u044C \u0438\u0437\u043C\u0435\u043D\u0435\u043D \u0443\u0441\u043F\u0435\u0448\u043D\u043E. \u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u0430\u043A\u043A\u0430\u0443\u043D\u0442\u0430 +account.userAlreadyExists = \u0410\u043A\u043A\u0430\u0443\u043D\u0442 \u0441 \u0442\u0430\u043A\u0438\u043C \u044D\u043B.\u0430\u0434\u0440\u0435\u0441\u043E\u043C \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 +account.createSuccess = \u0410\u043A\u043A\u0430\u0443\u043D\u0442 \u0441\u043E\u0437\u0434\u0430\u043D \u0443\u0441\u043F\u0435\u0448\u043D\u043E. \u0421\u0435\u0439\u0447\u0430\u0441 \u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u043E\u0442\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043B\u0438\u0447\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 +account.saveSuccess = \u0410\u043A\u043A\u0430\u0443\u043D\u0442 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D \u0443\u0441\u043F\u0435\u0448\u043D\u043E. \u041C\u043E\u0436\u0435\u0442\u0435 \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u0430\u043A\u043A\u0430\u0443\u043D\u0442\u0430 +account.deactivateSuccess = \u0410\u043A\u043A\u0430\u0443\u043D\u0442 \u0434\u0435\u0430\u043A\u0442\u0438\u0432\u0438\u0440\u043E\u0432\u0430\u043D \u0443\u0441\u043F\u0435\u0448\u043D\u043E +account.activateSuccess = \u0410\u043A\u043A\u0430\u0443\u043D\u0442 \u0430\u043A\u0442\u0438\u0432\u0438\u0440\u043E\u0432\u0430\u043D \u0443\u0441\u043F\u0435\u0448\u043D\u043E +account.enterEmailAndPassword = \u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u044D\u043B.\u0430\u0434\u0440\u0435\u0441 \u0438 \u043F\u0430\u0440\u043E\u043B\u044C +account.notFound = \u0410\u043A\u043A\u0430\u0443\u043D\u0442 \u0441 \u0442\u0430\u043A\u043E\u0439 \u043A\u043E\u043C\u0431\u0438\u043D\u0430\u0446\u0438\u0435\u0439 \u044D\u043B.\u0430\u0434\u0440\u0435\u0441\u0430 \u0438 \u043F\u0430\u0440\u043E\u043B\u044F \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D +account.notActive = \u0410\u043A\u043A\u0430\u0443\u043D\u0442 \u043D\u0435 \u0430\u043A\u0442\u0438\u0432\u0435\u043D. \u0421\u0432\u044F\u0436\u0438\u0442\u0435\u0441\u044C \u0441 \u0430\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0435\u0439 \u0441\u0430\u0439\u0442\u0430 +account.notChanged = \u041D\u0435\u0442 \u043D\u0438\u043A\u0430\u043A\u0438\u0445 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439, \u0447\u0442\u043E\u0431\u044B \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C +password.help = \u041F\u0430\u0440\u043E\u043B\u044C \u0434\u043E\u043B\u0436\u0435\u043D \u0441\u043E\u0434\u0435\u0440\u0436a\u0442\u044C \u043C\u0438\u043D\u0438\u043C\u0443\u043C \u043E\u0434\u043D\u0443 \u0446\u0438\u0444\u0440\u0443, \u043F\u043E \u043E\u0434\u043D\u043E\u0439 \u0431\u0443\u043A\u0432\u0435 \u0432\u0435\u0440\u0445\u043D\u0435\u0433\u043E \u0438 \u043D\u0438\u0436\u043D\u0435\u0433\u043E \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430 \u043B\u0430\u0442\u0438\u043D\u0441\u043A\u043E\u0433\u043E \u0430\u043B\u0444\u0430\u0432\u0438\u0442\u0430. \u0414\u043B\u0438\u043D\u0430 \u0434\u043E\u043B\u0436\u043D\u0430 \u0431\u044B\u0442\u044C \u043D\u0435 \u043C\u0435\u043D\u0435\u0435 8 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 + +header.main = \u0413\u043B\u0430\u0432\u043D\u0430\u044F +header.contacts = \u041A\u043E\u043D\u0442\u0430\u043A\u0442\u044B +header.aboutUs = \u041E \u043D\u0430\u0441 + +common.user = \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C +common.accounts = \u0410\u043A\u043A\u0430\u0443\u043D\u0442\u044B +common.email = \u042D\u043B.\u0430\u0434\u0440\u0435\u0441 +common.password = \u041F\u0430\u0440\u043E\u043B\u044C +common.oldPassword = \u0421\u0442\u0430\u0440\u044B\u0439 \u043F\u0430\u0440\u043E\u043B\u044C +common.newPassword = \u041D\u043E\u0432\u044B\u0439 \u043F\u0430\u0440\u043E\u043B\u044C +common.createPassword = \u0421\u043E\u0437\u0434\u0430\u0439\u0442\u0435 \u043F\u0430\u0440\u043E\u043B\u044C +common.confirmPassword = \u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u0435 \u043F\u0430\u0440\u043E\u043B\u044C +common.firstName = \u0418\u043C\u044F +common.lastName = \u0424\u0430\u043C\u0438\u043B\u0438\u044F +common.birthDate = \u0414\u0430\u0442\u0430 \u0440\u043E\u0436\u0434\u0435\u043D\u0438\u044F +common.company = \u041A\u043E\u043C\u043F\u0430\u043D\u0438\u044F +common.position = \u0414\u043E\u043B\u0436\u043D\u043E\u0441\u0442\u044C +common.qualification = \u041A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F +common.address = \u0410\u0434\u0440\u0435\u0441 +common.phone = \u041D\u043E\u043C\u0435\u0440 \u0442\u0435\u043B\u0435\u0444\u043E\u043D\u0430 +common.date = \u0414\u0430\u0442\u0430 +common.status = \u0421\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 +common.active = \u0410\u043A\u0442\u0438\u0432\u0435\u043D +common.notActive = \u041D\u0435 \u0430\u043A\u0442\u0438\u0432\u0435\u043D +common.role = \u0420\u043E\u043B\u044C +common.registered = \u0417\u0430\u0440\u0435\u0433\u0435\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D +common.role.customer = \u0417\u0430\u043A\u0430\u0437\u0447\u0438\u043A +common.role.developer = \u0420\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A +common.role.manager = \u041C\u0435\u043D\u0435\u0434\u0436\u0435\u0440 +common.role.administrator = \u0410\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0430\u0442\u043E\u0440 +common.tools = \u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B +common.tools.administrator = \u0410\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 +common.tools.manager = \u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 +common.tools.customer = \u0417\u0430\u044F\u0432\u043A\u0438 +common.newOrder = \u041D\u043E\u0432\u0430\u044F \u0437\u0430\u044F\u0432\u043A\u0430 +common.order = \u0417\u0430\u044F\u0432\u043A\u0430 +common.orders = \u0417\u0430\u044F\u0432\u043A\u0438 +common.orderNewStatus = \u041D\u043E\u0432\u044B\u0439 \u0441\u0442\u0430\u0442\u0443\u0441 \u0437\u0430\u044F\u0432\u043A\u0438 +common.feedback = \u041E\u0442\u0432\u0435\u0442 +common.customerInfo = \u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u043E \u0437\u0430\u043A\u0430\u0437\u0447\u0438\u043A\u0435 +common.managerInfo = \u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u043E \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u0435 +common.subject = \u0422\u0435\u043C\u0430 +common.other = \u0414\u0440\u0443\u0433\u043E\u0435 +common.applicationDevelopment = \u0420\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u043A\u0430 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F +common.applicationTesting = \u0422\u0435\u0441\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F +common.applicationSupport = \u0421\u043E\u043F\u0440\u043E\u0432\u043E\u0436\u0434\u0435\u043D\u0438\u0435 \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F +common.topic = \u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A +common.message = \u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 (\u0434\u043E 2000 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432) +common.attachFile = \u041F\u0440\u0438\u043A\u0440\u0435\u043F\u0438\u0442\u044C \u0444\u0430\u0439\u043B (\u0434\u043E 10Mb) +common.file = \u0424\u0430\u0439\u043B + +action.submit = \u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u044C +action.signIn = \u0412\u043E\u0439\u0442\u0438 +action.signOut = \u0412\u044B\u0439\u0442\u0438 +action.createAccount = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0430\u043A\u043A\u0430\u0443\u043D\u0442 +action.editAccount = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0430\u043A\u043A\u0430\u0443\u043D\u0442 +action.editAccounts = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0430\u043A\u043A\u0430\u0443\u043D\u0442\u044B +action.saveAccount = \u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0430\u043A\u043A\u0430\u0443\u043D\u0442 +action.changePassword = \u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u043F\u0430\u0440\u043E\u043B\u044C +action.createOrder = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0437\u0430\u044F\u0432\u043A\u0443 +action.editOrder = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0437\u0430\u044F\u0432\u043A\u0443 +action.terminateOrder = \u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C \u0437\u0430\u044F\u0432\u043A\u0443 +action.saveOrder = \u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0437\u0430\u044F\u0432\u043A\u0443 +action.processOrder = \u041E\u0431\u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C \u0437\u0430\u044F\u0432\u043A\u0443 +action.allOrders = \u0412\u0441\u0435 \u0437\u0430\u044F\u0432\u043A\u0438 + +tag.paging.next = \u0414\u0430\u043B\u0435\u0435 +tag.paging.previous = \u041D\u0430\u0437\u0430\u0434 + +order.topicEmpty = \u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u043F\u0443\u0441\u0442 +order.messageEmpty = \u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043F\u0443\u0441\u0442\u043E +order.createSuccess = \u0417\u0430\u044F\u0432\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0430 \u0443\u0441\u043F\u0435\u0448\u043D\u043E +order.terminateSuccess = \u0417\u0430\u044F\u0432\u043A\u0430 \u043E\u0442\u043C\u0435\u043D\u0435\u043D\u0430 \u0443\u0441\u043F\u0435\u0448\u043D\u043E +order.saveSuccess = \u0417\u0430\u044F\u0432\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0430 \u0443\u0441\u043F\u0435\u0448\u043D\u043E +order.status.pending = \u0412 \u043E\u0436\u0438\u0434\u0430\u043D\u0438\u0438 +order.status.terminated = \u041E\u0442\u043C\u0435\u043D\u0435\u043D\u0430 +order.status.accepted = \u041F\u0440\u0438\u043D\u044F\u0442\u0430 +order.status.denied = \u041E\u0442\u043A\u043B\u043E\u043D\u0435\u043D\u0430 diff --git a/resources/properties.properties b/resources/properties.properties new file mode 100644 index 0000000..5379a90 --- /dev/null +++ b/resources/properties.properties @@ -0,0 +1,11 @@ +db.name=postgresql +db.postgresql.driver=org.postgresql.Driver +db.postgresql.url=jdbc:postgresql://localhost:5432/devteam +db.postgresql.user=postgres +db.postgresql.password=postgres +db.postgresql.connections=10 +db.postgresql.waitTime=5000 +validation.email=^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$ +validation.password=((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,}) +validation.fields.maxLength.inputText=256 +validation.fields.maxLength.textarea=2000 diff --git a/src/com/epam/devteam/action/Action.java b/src/com/epam/devteam/action/Action.java new file mode 100644 index 0000000..fa9513d --- /dev/null +++ b/src/com/epam/devteam/action/Action.java @@ -0,0 +1,33 @@ +/** + * + */ +package com.epam.devteam.action; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.epam.devteam.action.exception.ActionException; + +/** + * The 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 Map actions = createInitialMap(); + + private static Map createInitialMap() { + Map actions = new HashMap(); + actions.put("GET/", new ShowMainPageAction()); + actions.put("GET/*", new ShowMainPageAction()); + actions.put("GET/main", new ShowMainPageAction()); + actions.put("GET/contacts", new ShowContactsPageAction()); + actions.put("GET/about-us", new ShowAboutUsPageAction()); + actions.put("GET/error", new ShowErrorPageAction()); + actions.put("GET/success", new ShowSuccessPageAction()); + actions.put("POST/set-language", new SetLanguageAction()); + actions.put("GET/download-file", new DownloadFileAction()); + actions.put("POST/signin", new SigninAction()); + actions.put("GET/signout", new SignoutAction()); + actions.put("GET/create-account", new ShowCreateAccountPageAction()); + actions.put("POST/create-account", new CreateAccountAction()); + actions.put("GET/edit-account", new ShowEditAccountPageAction()); + actions.put("POST/save-account", new SaveAccountAction()); + actions.put("GET/manage-accounts", + new ShowAccountsManagementPageAction()); + actions.put("GET/deactivate-account", new DeactivateAccountAction()); + actions.put("GET/activate-account", new ActivateAccountAction()); + actions.put("POST/change-password", new ChangeAccountPasswordAction()); + actions.put("GET/show-order", new ShowOrderPageAction()); + actions.put("GET/create-order", new ShowCreateOrderPageAction()); + actions.put("POST/create-order", new CreateOrderAction()); + actions.put("GET/customer-orders", new ShowCustomerOrdersPageAction()); + actions.put("GET/terminate-order", new TerminateOrderAction()); + actions.put("GET/edit-order", new ShowEditOrderPageAction()); + actions.put("POST/save-order", new SaveOrderAction()); + actions.put("GET/show-all-orders", new ShowAllOrdersPageAction()); + actions.put("GET/process-order", new ShowProcessOrderPageAction()); + actions.put("POST/create-feedback", new CreateFeedbackAction()); + return actions; + } + + public static Action getAction(HttpServletRequest request) { + HttpSession session; + String req = request.getMethod() + request.getPathInfo(); + Action action = actions.get(req); + if (action == null) { + action = actions.get("GET/error"); + session = request.getSession(); + session.setAttribute("error", "error.notFound"); + LOGGER.debug("Unknown request."); + return action; + } + return action; + } +} diff --git a/src/com/epam/devteam/action/ActionResult.java b/src/com/epam/devteam/action/ActionResult.java new file mode 100644 index 0000000..4709096 --- /dev/null +++ b/src/com/epam/devteam/action/ActionResult.java @@ -0,0 +1,78 @@ +package com.epam.devteam.action; + +/** + * The ActionResult 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(); + List users; + String tempFirstRow = (String) request.getParameter("first-row"); + String tempRowNumber = (String) request.getParameter("row-number"); + int firstRow = 0; + int rowNumber = 0; + if (RequestFieldsValidator.equalNull(tempFirstRow, tempRowNumber) + || RequestFieldsValidator.empty(tempFirstRow, tempRowNumber)) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Form fields are not valid: equas null"); + return new ActionResult(ActionResult.METHOD.FORWARD, "error"); + } + try { + firstRow = Integer.parseInt(tempFirstRow); + rowNumber = Integer.parseInt(tempRowNumber); + } catch (IllegalArgumentException e) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Form fields are not valid: not a number"); + return new ActionResult(ActionResult.METHOD.FORWARD, "error"); + } + if ((rowNumber % 5 != 0) || (rowNumber > 50)) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Row number is not valid"); + return new ActionResult(ActionResult.METHOD.FORWARD, "error"); + } + try { + users = userDao().list(firstRow, rowNumber); + } catch (DaoException e) { + LOGGER.warn("Request cannot be executed."); + throw new ActionDatabaseFailException(e); + } + session.setAttribute("users", users); + return new ActionResult(ActionResult.METHOD.FORWARD, "manage-accounts"); + } + + /** + * 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/ShowCreateAccountPageAction.java b/src/com/epam/devteam/action/account/ShowCreateAccountPageAction.java new file mode 100644 index 0000000..7fa392f --- /dev/null +++ b/src/com/epam/devteam/action/account/ShowCreateAccountPageAction.java @@ -0,0 +1,34 @@ +/** + * + */ +package com.epam.devteam.action.account; + +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 ShowCreateAccountPageAction 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; + List items; + InputStream stream; + Order order; + String tempOrderId = null; + OrderStatus newOrderStatus = null; + String message = null; + String fieldName; + String fieldValue; + String fileName = null; + int orderId = 0; + byte[] fileContent = null; + boolean formFieldsEqualNull = false; + boolean fileNameLengthValid = false; + boolean messageLengthValid = false; + LOGGER.debug("Create feedback action..."); + session.removeAttribute("messageError"); + try { + items = fileUpload.parseRequest(request); + } catch (FileUploadException e) { + LOGGER.debug("Excessive file size."); + throw new ActionBadRequestException(e); + } + for (FileItem item : items) { + if (item.isFormField()) { + fieldName = item.getFieldName(); + fieldValue = item.getString(); + if ("order-status".equals(fieldName)) { + try { + newOrderStatus = OrderStatus.valueOf(fieldValue); + } catch (IllegalArgumentException e) { + LOGGER.warn("Unknown order status: " + fieldValue); + throw new ActionBadRequestException(e); + } + } + if ("order-id".equals(fieldName)) { + tempOrderId = fieldValue; + } + if ("message".equals(fieldName)) { + message = fieldValue; + } + } else { + fieldName = item.getFieldName(); + if ("file".equals(fieldName)) { + fileName = FilenameUtils.getName(item.getName()); + try { + stream = item.getInputStream(); + fileContent = IOUtils.toByteArray(stream); + } catch (IOException e) { + LOGGER.warn("Input stream error."); + throw new ActionException(e); + } + LOGGER.debug("File " + fileName + " has been uploaded."); + } + } + } + formFieldsEqualNull = RequestFieldsValidator.equalNull(tempOrderId, + message); + if (formFieldsEqualNull) { + LOGGER.warn("Form fields are not valid"); + throw new ActionBadRequestException(); + } + try { + orderId = Integer.parseInt(tempOrderId); + } catch (IllegalArgumentException e) { + LOGGER.warn("Id field value is not valid."); + throw new ActionBadRequestException(e); + } + order = (Order) session.getAttribute("order"); + if ((order == null) || (order.getId() != orderId)) { + LOGGER.warn("Feedback cannot be created for required order."); + throw new ActionBadRequestException(); + } + session.setAttribute("message", message); + if (RequestFieldsValidator.empty(message)) { + session.setAttribute("messageError", "order.messageEmpty"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView(request.getHeader("referer")); + return result; + } + try { + fileNameLengthValid = RequestFieldsValidator.lengthValid( + FieldType.INPUT_TEXT, fileName); + } catch (ValidationException e) { + LOGGER.warn("File name cannot be validated."); + throw new ActionException(e); + } + if (!fileNameLengthValid) { + LOGGER.warn("File name value is not valid."); + throw new ActionBadRequestException(); + } + try { + messageLengthValid = RequestFieldsValidator.lengthValid( + FieldType.TEXTAREA, message); + } catch (ValidationException e) { + LOGGER.warn("Message field cannot be validated."); + throw new ActionException(e); + } + if (!messageLengthValid) { + LOGGER.warn("Message field value is not valid."); + throw new ActionBadRequestException(); + } + manager = (Employee) session.getAttribute("user"); + feedback = new Feedback(); + feedback.setOrderId(order.getId()); + feedback.setDate(new Date(new java.util.Date().getTime())); + feedback.setMessage(message); + feedback.setFileName(fileName); + feedback.setFileContent(fileContent); + feedback.setManager(manager); + order.setStatus(newOrderStatus); + try { + feedbackCreator.createFeedback(feedback, order); + LOGGER.debug("Order has been created."); + } catch (ServiceException e) { + LOGGER.warn("Feedback cannot be created."); + throw new ActionException(e); + } + session.setAttribute("success", "order.createSuccess"); + session.removeAttribute("message"); + session.removeAttribute("order"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView("success"); + return result; + } + + /** + * Is used to initialize files handler and set maximum size of uploaded + * files as 10Mb. + * + * @return The files handler. + */ + private static ServletFileUpload initServletFileUpload() { + DiskFileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload fileUpload = new ServletFileUpload(factory); + fileUpload.setFileSizeMax(fileMaxSize); + return fileUpload; + } + +} diff --git a/src/com/epam/devteam/action/general/DownloadFileAction.java b/src/com/epam/devteam/action/general/DownloadFileAction.java new file mode 100644 index 0000000..92b9c53 --- /dev/null +++ b/src/com/epam/devteam/action/general/DownloadFileAction.java @@ -0,0 +1,111 @@ +package com.epam.devteam.action.general; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.Closeable; +import java.io.IOException; + +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.entity.feedback.Feedback; +import com.epam.devteam.entity.order.Order; + +/** + * The DownloadFileAction 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; + List items; + InputStream stream; + OrderSubject subject = null; + String topic = null; + String message = null; + String fieldName; + String fieldValue; + String fileName = null; + byte[] fileContent = null; + boolean formFieldsEqualNull = false; + boolean topicLengthValid = false; + boolean messageLengthValid = false; + LOGGER.debug("Create order action..."); + session.removeAttribute("topicError"); + session.removeAttribute("messageError"); + try { + items = fileUpload.parseRequest(request); + } catch (FileUploadException e) { + LOGGER.debug("Excessive file size."); + throw new ActionBadRequestException(e); + } + for (FileItem item : items) { + if (item.isFormField()) { + fieldName = item.getFieldName(); + try { + fieldValue = new String (item.get(),"UTF-8"); + } catch (UnsupportedEncodingException e1) { + throw new ActionException(); + } + if ("subject".equals(fieldName)) { + try { + subject = OrderSubject.valueOf(fieldValue); + } catch (IllegalArgumentException e) { + LOGGER.warn("Unknown order subject: " + fieldValue); + throw new ActionBadRequestException(e); + } + } + if ("topic".equals(fieldName)) { + topic = fieldValue; + System.out.println("Topic :" + topic); + } + if ("message".equals(fieldName)) { + message = fieldValue; + } + } else { + fieldName = item.getFieldName(); + if ("file".equals(fieldName)) { + fileName = FilenameUtils.getName(item.getName()); + try { + stream = item.getInputStream(); + fileContent = IOUtils.toByteArray(stream); + } catch (IOException e) { + LOGGER.warn("Input stream error."); + throw new ActionException(e); + } + LOGGER.debug("File " + fileName + " has been uploaded."); + } + } + } + formFieldsEqualNull = RequestFieldsValidator.equalNull(topic, message); + if (formFieldsEqualNull) { + LOGGER.warn("Form fields are not valid"); + throw new ActionBadRequestException(); + } + session.setAttribute("topic", topic); + session.setAttribute("message", message); + if (RequestFieldsValidator.empty(topic)) { + session.setAttribute("topicError", "order.topicEmpty"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView("create-order"); + return result; + } + if (RequestFieldsValidator.empty(message)) { + session.setAttribute("messageError", "order.messageEmpty"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView("create-order"); + return result; + } + try { + topicLengthValid = RequestFieldsValidator.lengthValid( + FieldType.INPUT_TEXT, topic, fileName); + messageLengthValid = RequestFieldsValidator.lengthValid( + FieldType.TEXTAREA, message); + } catch (ValidationException e) { + LOGGER.warn("Fields cannot be validated."); + throw new ActionException(e); + } + if (!topicLengthValid || !messageLengthValid) { + LOGGER.warn("Fields are not valid."); + throw new ActionBadRequestException(); + } + customer = (Customer) session.getAttribute("user"); + order = new Order(); + order.setDate(new Date(new java.util.Date().getTime())); + order.setStatus(OrderStatus.PENDING); + order.setSubject(subject); + order.setTopic(topic); + order.setMessage(message); + order.setFileName(fileName); + order.setFileContent(fileContent); + order.setCustomer(customer); + try { + orderDao().create(order); + LOGGER.debug("Order has been created."); + } catch (DaoException e) { + LOGGER.warn("Order cannot be created."); + throw new ActionException(); + } + session.setAttribute("success", "order.createSuccess"); + session.removeAttribute("topic"); + session.removeAttribute("message"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView("success"); + return result; + } + + /** + * Is used to initialize files handler and set maximum size of uploaded + * files as 10Mb. + * + * @return The files handler. + */ + private static ServletFileUpload initServletFileUpload() { + DiskFileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload fileUpload = new ServletFileUpload(factory); + fileUpload.setFileSizeMax(fileMaxSize); + return fileUpload; + } + + /** + * 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/SaveOrderAction.java b/src/com/epam/devteam/action/order/SaveOrderAction.java new file mode 100644 index 0000000..faf0401 --- /dev/null +++ b/src/com/epam/devteam/action/order/SaveOrderAction.java @@ -0,0 +1,235 @@ +package com.epam.devteam.action.order; + +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.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 Class ... + * + * @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; + List items; + InputStream stream; + String tempId = null; + OrderSubject subject = null; + String topic = null; + String message = null; + String fieldName; + String fieldValue; + String fileName = null; + int id = 0; + byte[] fileContent = null; + boolean formFieldsEqualNull = false; + boolean topicLengthValid = false; + boolean messageLengthValid = false; + LOGGER.debug("Save order action..."); + session.removeAttribute("topicError"); + session.removeAttribute("messageError"); + try { + items = fileUpload.parseRequest(request); + } catch (FileUploadException e) { + LOGGER.debug("Excessive file size."); + throw new ActionBadRequestException(e); + } + for (FileItem item : items) { + if (item.isFormField()) { + fieldName = item.getFieldName(); + fieldValue = item.getString(); + if ("subject".equals(fieldName)) { + try { + subject = OrderSubject.valueOf(fieldValue); + } catch (IllegalArgumentException e) { + LOGGER.warn("Unknown order subject: " + fieldValue); + throw new ActionException(); + } + } + if ("id".equals(fieldName)) { + tempId = fieldValue; + } + if ("topic".equals(fieldName)) { + topic = fieldValue; + } + if ("message".equals(fieldName)) { + message = fieldValue; + } + } else { + fieldName = item.getFieldName(); + if ("file".equals(fieldName)) { + fileName = FilenameUtils.getName(item.getName()); + try { + stream = item.getInputStream(); + fileContent = IOUtils.toByteArray(stream); + } catch (IOException e) { + LOGGER.warn("Input stream error."); + throw new ActionException(e); + } + LOGGER.debug("File " + fileName + " has been uploaded."); + } + } + } + formFieldsEqualNull = RequestFieldsValidator.equalNull(tempId, topic, + message); + if (formFieldsEqualNull) { + LOGGER.warn("Form fields are not valid"); + throw new ActionBadRequestException(); + } + try { + id = Integer.valueOf(tempId); + } catch (IllegalArgumentException e) { + LOGGER.warn("Order id is not valid."); + throw new ActionBadRequestException(e); + } + customer = (Customer) session.getAttribute("user"); + order = (Order) session.getAttribute("order"); + if ((order == null) || (order.getId() != id)) { + session.setAttribute("error", "error.badRequest"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView("error"); + LOGGER.debug("Order cannot be saved: not in the session."); + return result; + } + session.setAttribute("topic", topic); + session.setAttribute("message", message); + if (RequestFieldsValidator.empty(topic)) { + session.setAttribute("topicError", "order.topicEmpty"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView(request.getHeader("referer")); + LOGGER.debug("Order topic is empty."); + return result; + } + if (RequestFieldsValidator.empty(message)) { + session.setAttribute("messageError", "order.messageEmpty"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView(request.getHeader("referer")); + LOGGER.debug("Order message is empty."); + return result; + } + try { + topicLengthValid = RequestFieldsValidator.lengthValid( + FieldType.INPUT_TEXT, topic, fileName); + messageLengthValid = RequestFieldsValidator.lengthValid( + FieldType.TEXTAREA, message); + } catch (ValidationException e) { + LOGGER.warn("Fields length cannot be validated."); + throw new ActionException(e); + } + if (!topicLengthValid || !messageLengthValid) { + LOGGER.warn("Fields length is not valid."); + throw new ActionBadRequestException(); + } + order.setDate(new Date(new java.util.Date().getTime())); + order.setStatus(OrderStatus.PENDING); + order.setSubject(subject); + order.setTopic(topic); + order.setMessage(message); + order.setFileName(fileName); + order.setFileContent(fileContent); + order.setCustomer(customer); + try { + orderDao().update(order); + LOGGER.debug("Order has been updated."); + } catch (DaoException e) { + LOGGER.warn("Order cannot be updated."); + throw new ActionException(); + } + session.setAttribute("success", "order.saveSuccess"); + result.setMethod(ActionResult.METHOD.REDIRECT); + result.setView("success"); + return result; + } + + /** + * Is used to initialize files handler and set maximum size of uploaded + * files as 10Mb. + * + * @return The files handler. + */ + private static ServletFileUpload initServletFileUpload() { + DiskFileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload fileUpload = new ServletFileUpload(factory); + fileUpload.setFileSizeMax(fileMaxSize); + return fileUpload; + } + + /** + * 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/ShowAllOrdersPageAction.java b/src/com/epam/devteam/action/order/ShowAllOrdersPageAction.java new file mode 100644 index 0000000..be19fae --- /dev/null +++ b/src/com/epam/devteam/action/order/ShowAllOrdersPageAction.java @@ -0,0 +1,116 @@ +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.util.validator.RequestFieldsValidator; + +/** + * The ShowAllOrdersPageAction 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(); + List orders = null; + String tempFirstRow = (String) request.getParameter("first-row"); + String tempRowNumber = (String) request.getParameter("row-number"); + int firstRow = 0; + int rowNumber = 0; + LOGGER.debug("Show customer's orders action..."); + if (RequestFieldsValidator.equalNull(tempFirstRow, tempRowNumber) + || RequestFieldsValidator.empty(tempFirstRow, tempRowNumber)) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Form fields are not valid: equal null"); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("error"); + return result; + } + try { + firstRow = Integer.parseInt(tempFirstRow); + rowNumber = Integer.parseInt(tempRowNumber); + } catch (IllegalArgumentException e) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Form fields are not valid: not a number"); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("error"); + return result; + } + if ((rowNumber % 5 != 0) || (rowNumber > 50)) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Row number is not valid"); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("error"); + return result; + } + try { + orders = orderDao().list(firstRow, rowNumber); + } catch (DaoException e) { + LOGGER.warn("Orders cannot be fetched from database."); + throw new ActionBadRequestException(e); + } + session.setAttribute("orders", orders); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("all-orders"); + 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/ShowCreateOrderPageAction.java b/src/com/epam/devteam/action/order/ShowCreateOrderPageAction.java new file mode 100644 index 0000000..e0dc3ed --- /dev/null +++ b/src/com/epam/devteam/action/order/ShowCreateOrderPageAction.java @@ -0,0 +1,42 @@ +package com.epam.devteam.action.order; + +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 ShowCreateOrderPageAction 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"); + List orders = null; + String tempFirstRow = (String) request.getParameter("first-row"); + String tempRowNumber = (String) request.getParameter("row-number"); + int firstRow = 0; + int rowNumber = 0; + LOGGER.debug("Show customer's orders action..."); + if (RequestFieldsValidator.equalNull(tempFirstRow, tempRowNumber) + || RequestFieldsValidator.empty(tempFirstRow, tempRowNumber)) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Form fields are not valid: equal null"); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("error"); + return result; + } + try { + firstRow = Integer.parseInt(tempFirstRow); + rowNumber = Integer.parseInt(tempRowNumber); + } catch (IllegalArgumentException e) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Form fields are not valid: not a number"); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("error"); + return result; + } + if ((rowNumber % 5 != 0) || (rowNumber > 50)) { + session.setAttribute("error", "error.badRequest"); + LOGGER.warn("Row number is not valid"); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("error"); + return result; + } + try { + orders = orderDao().listByCustomerId(user.getId(), firstRow, + rowNumber); + } catch (DaoException e) { + LOGGER.warn("Orders cannot be fetched from database."); + throw new ActionBadRequestException(e); + } + session.setAttribute("orders", orders); + result.setMethod(ActionResult.METHOD.FORWARD); + result.setView("customer-orders"); + 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/ShowEditOrderPageAction.java b/src/com/epam/devteam/action/order/ShowEditOrderPageAction.java new file mode 100644 index 0000000..7d32d12 --- /dev/null +++ b/src/com/epam/devteam/action/order/ShowEditOrderPageAction.java @@ -0,0 +1,126 @@ +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.user.User; + +/** + * The ShowEditOrderPageAction 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 Dao { + + /** + * Is used to create the given object in the database. + * + * @param object The object to create. + * @throws DaoException If something fails at database level. + */ + void create(T object) throws DaoException; + + /** + * Is used to return an object from the database by the given id, otherwise + * {@code null}. + * + * @param id The id of the object to be returned. + * @return The object from the database with required id, otherwise + * {@code null}. + * @throws DaoException If something fails at database level. + */ + T find(int id) throws DaoException; + + /** + * Is used to update the given object. + * + * @param object The object to update. + * @throws DaoException If something fails at database level. + */ + void update(T object) throws DaoException; + + /** + * 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. + */ + void delete(int id) throws 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. + */ + List list() throws DaoException; + + /** + * Is used to get objects from the database with paging. + * + * @param firstRow The row from where to start list objects. + * @param rowNumber The number of objects to list. + * @return The list of objects in the database. + * @throws DaoException If something fails at database level. + */ + List list(int firstRow, int rowNumber) throws DaoException; + +} diff --git a/src/com/epam/devteam/dao/DaoException.java b/src/com/epam/devteam/dao/DaoException.java index 94686fb..45cb88b 100644 --- a/src/com/epam/devteam/dao/DaoException.java +++ b/src/com/epam/devteam/dao/DaoException.java @@ -5,7 +5,7 @@ /** * @date Dec 15, 2013 - * @author anjey + * @author Andrey Kovalskiy * */ public class DaoException extends Exception { diff --git a/src/com/epam/devteam/dao/DaoFactory.java b/src/com/epam/devteam/dao/DaoFactory.java index d3919e2..cfb9b34 100644 --- a/src/com/epam/devteam/dao/DaoFactory.java +++ b/src/com/epam/devteam/dao/DaoFactory.java @@ -7,47 +7,99 @@ import com.epam.devteam.dao.impl.PostgresqlDaoFactory; import com.epam.devteam.db.ConnectionPool; +import com.epam.devteam.db.ConnectionPoolException; +import com.epam.devteam.db.DatabaseType; +import com.epam.devteam.util.property.PropertyManager; +import com.epam.devteam.util.property.PropertyManagerException; /** + * The DaoFactory 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 Dao { + + /** + * + * 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. + */ + Feedback findByOrderId(int id) throws DaoException; + +} diff --git a/src/com/epam/devteam/dao/OrderDao.java b/src/com/epam/devteam/dao/OrderDao.java new file mode 100644 index 0000000..f6dee57 --- /dev/null +++ b/src/com/epam/devteam/dao/OrderDao.java @@ -0,0 +1,42 @@ +/** + * + */ +package com.epam.devteam.dao; + +import java.util.List; + +import com.epam.devteam.entity.order.Order; +import com.epam.devteam.entity.order.OrderStatus; + +/** + * The OrderDao 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 Dao { + + /** + * 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. + */ + List listByCustomerId(int id, int firstRow, int row) + throws DaoException; + + /** + * 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. + */ + void updateStatus(int id, OrderStatus status) throws DaoException; + +} diff --git a/src/com/epam/devteam/dao/UserDao.java b/src/com/epam/devteam/dao/UserDao.java index 772a348..1101fbc 100644 --- a/src/com/epam/devteam/dao/UserDao.java +++ b/src/com/epam/devteam/dao/UserDao.java @@ -3,60 +3,66 @@ */ package com.epam.devteam.dao; -import java.util.List; - -import com.epam.devteam.entity.User; +import com.epam.devteam.entity.user.User; /** - * @date Dec 15, 2013 - * @author Andrey Kovalskiy + * The UserDao 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); + } +}