diff --git a/pom.xml b/pom.xml index 204e2d0..1c487b2 100644 --- a/pom.xml +++ b/pom.xml @@ -61,12 +61,37 @@ + + junit + junit + 4.12 + test + + javax.servlet javax.servlet-api 3.1.0 provided + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.0 + provided + + + javax.el + javax.el-api + 3.0.0 + provided + + + javax.servlet + jstl + 1.2 + + diff --git a/src/main/java/ru/javawebinar/topjava/Dao/MealDao.java b/src/main/java/ru/javawebinar/topjava/Dao/MealDao.java new file mode 100644 index 0000000..71baf3a --- /dev/null +++ b/src/main/java/ru/javawebinar/topjava/Dao/MealDao.java @@ -0,0 +1,17 @@ +package ru.javawebinar.topjava.Dao; + +import java.util.List; + +public interface MealDao { + + void add(T t); + + T getById(String id); + + List getAll(); + + void update(T t); + + void delete(String id); +} + diff --git a/src/main/java/ru/javawebinar/topjava/Dao/MealDaoImpl.java b/src/main/java/ru/javawebinar/topjava/Dao/MealDaoImpl.java new file mode 100644 index 0000000..d3db4d3 --- /dev/null +++ b/src/main/java/ru/javawebinar/topjava/Dao/MealDaoImpl.java @@ -0,0 +1,35 @@ +package ru.javawebinar.topjava.Dao; + +import ru.javawebinar.topjava.model.Meal; +import ru.javawebinar.topjava.util.MealsUtil; + +import java.util.ArrayList; +import java.util.List; + +public class MealDaoImpl implements MealDao { + + @Override + public void add(Meal meal) { + MealsUtil.MEALS_BASE.put(meal.getId(), meal); + } + + @Override + public Meal getById(String id) { + return MealsUtil.MEALS_BASE.get(id); + } + + @Override + public List getAll() { + return new ArrayList<>(MealsUtil.MEALS_BASE.values()); + } + + @Override + public void update(Meal meal) { + MealsUtil.MEALS_BASE.put(meal.getId(), meal); + } + + @Override + public void delete(String id) { + MealsUtil.MEALS_BASE.remove(id); + } +} \ No newline at end of file diff --git a/src/main/java/ru/javawebinar/topjava/Main.java b/src/main/java/ru/javawebinar/topjava/Main.java index b23a2f0..f894b6b 100644 --- a/src/main/java/ru/javawebinar/topjava/Main.java +++ b/src/main/java/ru/javawebinar/topjava/Main.java @@ -7,8 +7,21 @@ * @link http://caloriesmng.herokuapp.com/ * @link https://github.com/JavaOPs/topjava */ + public class Main { + public static void main(String[] args) { System.out.format("Hello Topjava Enterprise!"); } } + +/*На странице кнопка add, update, delete +По кнопке add появляется форма пустая - добавляется дата, описание и кол-во каллорий + Заполняются данные, передается add=true и параметры передаются в конструктор, дефолт уникальный id, пут в лист милов, + считается эксид, рендерится страница со всеми миламиэксид. +По кнопке update появляется форма, заполненная данными мила, меняются данные. Кнопка обновить + При нажатии передается update=true и параметры передаются в конструктор, id из мила, пут в лист милов + считается эксид, рендерится страница со всеми миламиэксид +ПО кнопке delete передаётся параметр delete=true, id параметр передается на сервлет, удаляется мил с данным id, + считается эксид, рендерится страница со всеми миламиэксид + */ diff --git a/src/main/java/ru/javawebinar/topjava/model/Meal.java b/src/main/java/ru/javawebinar/topjava/model/Meal.java index 006d5ca..fb87308 100644 --- a/src/main/java/ru/javawebinar/topjava/model/Meal.java +++ b/src/main/java/ru/javawebinar/topjava/model/Meal.java @@ -3,17 +3,25 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; /** * GKislin * 11.01.2015. */ public class Meal { - private final LocalDateTime dateTime; - private final String description; + private String id = UUID.randomUUID().toString(); - private final int calories; + private LocalDateTime dateTime; + + private String description; + + private int calories; + + public Meal() { + } public Meal(LocalDateTime dateTime, String description, int calories) { this.dateTime = dateTime; @@ -21,6 +29,10 @@ public Meal(LocalDateTime dateTime, String description, int calories) { this.calories = calories; } + public String getId() { + return id; + } + public LocalDateTime getDateTime() { return dateTime; } @@ -34,10 +46,26 @@ public int getCalories() { } public LocalDate getDate() { - return dateTime.toLocalDate(); + return dateTime == null ? null : dateTime.toLocalDate(); } public LocalTime getTime() { - return dateTime.toLocalTime(); + return dateTime == null ? null : dateTime.toLocalTime(); + } + + public void setId(String id) { + this.id = id; + } + + public void setDateTime(LocalDateTime dateTime) { + this.dateTime = dateTime; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setCalories(int calories) { + this.calories = calories; } } diff --git a/src/main/java/ru/javawebinar/topjava/model/MealWithExceed.java b/src/main/java/ru/javawebinar/topjava/model/MealWithExceed.java index d14128b..64a63c6 100644 --- a/src/main/java/ru/javawebinar/topjava/model/MealWithExceed.java +++ b/src/main/java/ru/javawebinar/topjava/model/MealWithExceed.java @@ -1,12 +1,19 @@ package ru.javawebinar.topjava.model; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; /** * GKislin * 11.01.2015. */ public class MealWithExceed { + + private final String id; + private final LocalDateTime dateTime; private final String description; @@ -15,20 +22,40 @@ public class MealWithExceed { private final boolean exceed; - public MealWithExceed(LocalDateTime dateTime, String description, int calories, boolean exceed) { + public MealWithExceed(String id, LocalDateTime dateTime, String description, int calories, boolean exceed) { + this.id = id; this.dateTime = dateTime; this.description = description; this.calories = calories; this.exceed = exceed; } - @Override - public String toString() { - return "UserMealWithExceed{" + - "dateTime=" + dateTime + - ", description='" + description + '\'' + - ", calories=" + calories + - ", exceed=" + exceed + - '}'; + public String getId() { + return id; + } + + public LocalDateTime getDateTime() { + return dateTime; + } + + public String getDescription() { + return description; + } + + public int getCalories() { + return calories; } -} + + public LocalDate getDate() { + return dateTime.toLocalDate(); + } + + public LocalTime getTime() { + return dateTime.toLocalTime(); + } + + public boolean getExceed() { + return exceed; + } + +} \ No newline at end of file diff --git a/src/main/java/ru/javawebinar/topjava/util/MealsUtil.java b/src/main/java/ru/javawebinar/topjava/util/MealsUtil.java index 9f4a325..6bf7030 100644 --- a/src/main/java/ru/javawebinar/topjava/util/MealsUtil.java +++ b/src/main/java/ru/javawebinar/topjava/util/MealsUtil.java @@ -10,54 +10,43 @@ import java.util.*; import java.util.stream.Collectors; +import static java.util.stream.Collectors.toList; + /** * GKislin * 31.05.2015. */ public class MealsUtil { - public static void main(String[] args) { - List meals = Arrays.asList( - new Meal(LocalDateTime.of(2015, Month.MAY, 30, 10, 0), "Завтрак", 500), - new Meal(LocalDateTime.of(2015, Month.MAY, 30, 13, 0), "Обед", 1000), - new Meal(LocalDateTime.of(2015, Month.MAY, 30, 20, 0), "Ужин", 500), - new Meal(LocalDateTime.of(2015, Month.MAY, 31, 10, 0), "Завтрак", 1000), - new Meal(LocalDateTime.of(2015, Month.MAY, 31, 13, 0), "Обед", 500), - new Meal(LocalDateTime.of(2015, Month.MAY, 31, 20, 0), "Ужин", 510) - ); - List filteredMealsWithExceeded = getFilteredWithExceeded(meals, LocalTime.of(7, 0), LocalTime.of(12, 0), 2000); - filteredMealsWithExceeded.forEach(System.out::println); - - System.out.println(getFilteredWithExceededByCycle(meals, LocalTime.of(7, 0), LocalTime.of(12, 0), 2000)); - } - public static List getFilteredWithExceeded(List meals, LocalTime startTime, LocalTime endTime, int caloriesPerDay) { - Map caloriesSumByDate = meals.stream() - .collect( - Collectors.groupingBy(Meal::getDate, Collectors.summingInt(Meal::getCalories)) -// Collectors.toMap(Meal::getDate, Meal::getCalories, Integer::sum) - ); - - return meals.stream() - .filter(meal -> TimeUtil.isBetween(meal.getTime(), startTime, endTime)) - .map(meal -> createWithExceed(meal, caloriesSumByDate.get(meal.getDate()) > caloriesPerDay)) - .collect(Collectors.toList()); + public static final Map MEALS_BASE = new HashMap<>(); + + private static final List MEALSDEMO = Arrays.asList( + new Meal(LocalDateTime.of(2015, Month.MAY, 30, 10, 0), "Завтрак", 500), + new Meal(LocalDateTime.of(2015, Month.MAY, 30, 13, 0), "Обед", 1000), + new Meal(LocalDateTime.of(2015, Month.MAY, 30, 20, 0), "Ужин", 500), + new Meal(LocalDateTime.of(2015, Month.MAY, 31, 10, 0), "Завтрак", 1000), + new Meal(LocalDateTime.of(2015, Month.MAY, 31, 13, 0), "Обед", 500), + new Meal(LocalDateTime.of(2015, Month.MAY, 31, 20, 0), "Ужин", 510) + ); + + static { + for (Meal meal : MEALSDEMO) { + MEALS_BASE.put(meal.getId(), meal); + } } - public static List getFilteredWithExceededByCycle(List meals, LocalTime startTime, LocalTime endTime, int caloriesPerDay) { - + public static List getFilteredWithExceeded(List meals, int caloriesPerDay) { final Map caloriesSumByDate = new HashMap<>(); meals.forEach(meal -> caloriesSumByDate.merge(meal.getDate(), meal.getCalories(), Integer::sum)); final List mealExceeded = new ArrayList<>(); - meals.forEach(meal -> { - if (TimeUtil.isBetween(meal.getTime(), startTime, endTime)) { - mealExceeded.add(createWithExceed(meal, caloriesSumByDate.get(meal.getDate()) > caloriesPerDay)); - } - }); + meals.forEach(meal -> + mealExceeded.add(createWithExceed(meal, caloriesSumByDate.get(meal.getDate()) > caloriesPerDay)) + ); return mealExceeded; } - public static MealWithExceed createWithExceed(Meal meal, boolean exceeded) { - return new MealWithExceed(meal.getDateTime(), meal.getDescription(), meal.getCalories(), exceeded); + private static MealWithExceed createWithExceed(Meal meal, boolean exceeded) { + return new MealWithExceed(meal.getId(), meal.getDateTime(), meal.getDescription(), meal.getCalories(), exceeded); } } \ No newline at end of file diff --git a/src/main/java/ru/javawebinar/topjava/util/TimeUtil.java b/src/main/java/ru/javawebinar/topjava/util/TimeUtil.java index 02399b7..4be1358 100644 --- a/src/main/java/ru/javawebinar/topjava/util/TimeUtil.java +++ b/src/main/java/ru/javawebinar/topjava/util/TimeUtil.java @@ -7,6 +7,7 @@ * 07.01.2015. */ public class TimeUtil { + public static boolean isBetween(LocalTime lt, LocalTime startTime, LocalTime endTime) { return lt.compareTo(startTime) >= 0 && lt.compareTo(endTime) <= 0; } diff --git a/src/main/java/ru/javawebinar/topjava/web/Avg.java b/src/main/java/ru/javawebinar/topjava/web/Avg.java new file mode 100644 index 0000000..f547631 --- /dev/null +++ b/src/main/java/ru/javawebinar/topjava/web/Avg.java @@ -0,0 +1,24 @@ +package ru.javawebinar.topjava.web; + +import java.util.Arrays; +import java.util.List; + +public class Avg { + + public static void main(String[] args) { + List listInt = Arrays.asList(1, 2, 3, 4, 5, 0); + System.out.println(midInt(listInt)); + } + + static double midInt(List listInt) { + long sum = 0; + if (listInt.size() < 1) { + throw new UnsupportedOperationException("List size must be bigger than 0 elements"); + } + for (Integer integer : listInt) { + sum += integer; + } + double result = ((double) sum) / listInt.size(); + return result; + } +} diff --git a/src/main/java/ru/javawebinar/topjava/web/MealServlet.java b/src/main/java/ru/javawebinar/topjava/web/MealServlet.java new file mode 100644 index 0000000..7ca8e5d --- /dev/null +++ b/src/main/java/ru/javawebinar/topjava/web/MealServlet.java @@ -0,0 +1,79 @@ +package ru.javawebinar.topjava.web; + +import ru.javawebinar.topjava.Dao.MealDao; +import ru.javawebinar.topjava.Dao.MealDaoImpl; +import ru.javawebinar.topjava.model.Meal; +import ru.javawebinar.topjava.model.MealWithExceed; +import ru.javawebinar.topjava.util.MealsUtil; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +/** + * User: gkislin + * Date: 19.08.2014 + */ +public class MealServlet extends HttpServlet { + private MealDao mealDao = new MealDaoImpl(); + public static final String PATTERN = "yyyy/MM/dd HH:mm"; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if (request.getParameter("del") != null && request.getParameter("id") != null) { + String id = request.getParameter("id"); + mealDao.delete(id); + } + if ("add".equals(request.getParameter("formtype"))) { + Meal meal = createMealByRequest(request); + mealDao.add(meal); + } + if ("edit".equals(request.getParameter("formtype")) && request.getParameter("id") != null) { + Meal meal = createMealByRequest(request); + mealDao.update(meal); + } + List mealsWithExceed = MealsUtil.getFilteredWithExceeded(new ArrayList<>(MealsUtil.MEALS_BASE.values()), 2000); + request.setAttribute("mealsWithExceedList", mealsWithExceed); + + RequestDispatcher requestDispatcher = request.getRequestDispatcher("/meals-jsp"); + requestDispatcher.forward(request, response); + } + + private Meal createMealByRequest(HttpServletRequest request) { + Meal meal=new Meal(); + if (request.getParameter("id") != null) { + meal.setId(request.getParameter("id")); + } + String description; + try { + description = request.getParameter("description"); + } catch (Exception e) { + description = "no description"; + } + int calories; + try { + calories = Integer.parseInt(request.getParameter("calories")); + } catch (Exception e) { + calories = 0; + } + LocalDateTime localDateTime; + try { + localDateTime = LocalDateTime.parse(request.getParameter("date"), DateTimeFormatter.ofPattern(PATTERN)); + } catch (Exception e) { + localDateTime = LocalDateTime.now(); + } + meal.setDescription(description); + meal.setCalories(calories); + meal.setDateTime(localDateTime); + return meal; + } +} \ No newline at end of file diff --git a/src/main/java/ru/javawebinar/topjava/web/UserServlet.java b/src/main/java/ru/javawebinar/topjava/web/UserServlet.java index d4024e4..5ddd38f 100644 --- a/src/main/java/ru/javawebinar/topjava/web/UserServlet.java +++ b/src/main/java/ru/javawebinar/topjava/web/UserServlet.java @@ -15,12 +15,13 @@ * Date: 19.08.2014 */ public class UserServlet extends HttpServlet { - private static final Logger LOG = getLogger(UserServlet.class); + private static final Logger log = getLogger(UserServlet.class); + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { -// LOG.debug("redirect to userList"); + log.debug("redirect to users"); - request.getRequestDispatcher("topjava/userList.jsp").forward(request, response); -// response.sendRedirect("userList.jsp"); +// request.getRequestDispatcher("/users.jsp").forward(request, response); + response.sendRedirect("users.jsp"); } } diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index 8ee5f21..a92e8c9 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -30,4 +30,4 @@ - + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml index f346a5e..9428947 100644 --- a/src/main/webapp/WEB-INF/web.xml +++ b/src/main/webapp/WEB-INF/web.xml @@ -6,13 +6,52 @@ Topjava - userServlet + UserServlet ru.javawebinar.topjava.web.UserServlet 0 - userServlet + UserServlet /users - + + MealServlet + ru.javawebinar.topjava.web.MealServlet + 0 + + + MealServlet + /mealServlet + + + + UsersJsp + /users.jsp + 0 + + + UsersJsp + /users-jsp + + + + MealsJsp + /meals.jsp + 0 + + + MealsJsp + /meals-jsp + + + + Form + /form.jsp + 0 + + + Form + /form-jsp + + \ No newline at end of file diff --git a/src/main/webapp/form.jsp b/src/main/webapp/form.jsp new file mode 100644 index 0000000..adf7195 --- /dev/null +++ b/src/main/webapp/form.jsp @@ -0,0 +1,39 @@ +<%-- + Created by IntelliJ IDEA. + User: User + Date: 28.01.2019 + Time: 0:36 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Editing + + + +
+ Set meal properties
+
+ > + > + + + + + + + + + + + + + +
Date
Description
Calories
+ + +
+
+ + \ No newline at end of file diff --git a/src/main/webapp/index.html b/src/main/webapp/index.jsp similarity index 72% rename from src/main/webapp/index.html rename to src/main/webapp/index.jsp index c65c875..5829280 100644 --- a/src/main/webapp/index.html +++ b/src/main/webapp/index.jsp @@ -1,4 +1,4 @@ - +<%@ page contentType="text/html;charset=UTF-8" language="java" %> @@ -9,6 +9,7 @@

Проект "User List +
  • Meal List
  • diff --git a/src/main/webapp/meals.jsp b/src/main/webapp/meals.jsp new file mode 100644 index 0000000..6804701 --- /dev/null +++ b/src/main/webapp/meals.jsp @@ -0,0 +1,56 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Meals + + + + + + + +

    Home

    Add meal

    +
    + + + + + + + + + + + + <%-- table data--%> + + <%--set color--%> + + + + + + + + + <%-- set horizontal line--%> + + + + + + + + <%-- editing. Add id to url for getting it in method doGet()--%> + + <%-- deleting. Add id to url for getting it in method doGet()--%> + + + +
    ДатаОписаниеКол-во калорийEditDelete
    +
    +
    ${meal.getDate()} ${meal.getTime()}${meal.getDescription()}${meal.getCalories()}editdelete
    +
    + + \ No newline at end of file diff --git a/src/main/webapp/userList.jsp b/src/main/webapp/users.jsp similarity index 80% rename from src/main/webapp/userList.jsp rename to src/main/webapp/users.jsp index fbd40d3..7af8245 100644 --- a/src/main/webapp/userList.jsp +++ b/src/main/webapp/users.jsp @@ -4,7 +4,7 @@ User list -

    Home

    +

    Home

    User list

    diff --git a/src/test/java/ru/javawebinar/topjava/web/AvgTest.java b/src/test/java/ru/javawebinar/topjava/web/AvgTest.java new file mode 100644 index 0000000..0c267a6 --- /dev/null +++ b/src/test/java/ru/javawebinar/topjava/web/AvgTest.java @@ -0,0 +1,27 @@ +package ru.javawebinar.topjava.web; + +import org.junit.Assert; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; +import static ru.javawebinar.topjava.web.Avg.midInt; + +public class AvgTest { + + + @org.junit.Test + public void midIntTest1() { + List listInt = Arrays.asList(1, 2, 3, 4, 5, 0); + Double expected = BigDecimal.valueOf(((double) 15) / 6) + .setScale(3, RoundingMode.HALF_UP) + .doubleValue(); + Double actual = BigDecimal.valueOf(midInt(listInt)) + .setScale(3, RoundingMode.HALF_UP) + .doubleValue(); + assertEquals(expected, actual); + } +} \ No newline at end of file