Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hw01 #175

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Hw01 #175

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ log
*.patch


/src/main/java/META-INF/MANIFEST.MF
code/
43 changes: 41 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>ru.javawebinar</groupId>
<artifactId>topjava</artifactId>
<packaging>jar</packaging>
<packaging>war</packaging>

<version>1.0-SNAPSHOT</version>

Expand All @@ -15,6 +15,10 @@
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<!-- Logging -->
<logback.version>1.2.3</logback.version>
<slf4j.version>1.7.28</slf4j.version>
</properties>

<build>
Expand All @@ -34,6 +38,41 @@
</build>

<dependencies>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>

<!--Web-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>

<profiles>
Expand Down
11 changes: 0 additions & 11 deletions src/main/java/ru/javawebinar/topjava/Main.java

This file was deleted.

60 changes: 60 additions & 0 deletions src/main/java/ru/javawebinar/topjava/model/Meal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package ru.javawebinar.topjava.model;

import java.time.LocalDateTime;

public class Meal {
private Integer id;

private final LocalDateTime dateTime;
private final String description;
private final int calories;

public Meal(LocalDateTime dateTime, String description, int calories) {
this(null, dateTime, description, calories);
}

public Meal(Integer id, LocalDateTime dateTime, String description, int calories) {
this.id = id;
this.dateTime = dateTime;
this.description = description;
this.calories = calories;
}

public void setId(int id) {
this.id = id;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public LocalDateTime getDateTime() {
return dateTime;
}

public String getDescription() {
return description;
}

public int getCalories() {
return calories;
}

public boolean isNew() {
return id == null;
}

@Override
public String toString() {
return "Meal{" +
"id=" + id +
", dateTime=" + dateTime +
", description='" + description + '\'' +
", calories=" + calories +
'}';
}
}
43 changes: 43 additions & 0 deletions src/main/java/ru/javawebinar/topjava/model/MealTo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package ru.javawebinar.topjava.model;

import java.time.LocalDateTime;

public class MealTo {
protected Integer id;
private final LocalDateTime dateTime;
private final String description;
private final int calories;
private final boolean excess;

public MealTo(Integer id, LocalDateTime dateTime, String description, int calories, boolean excess) {
this.id = id;
this.dateTime = dateTime;
this.description = description;
this.calories = calories;
this.excess = excess;
}

public LocalDateTime getDateTime() {
return dateTime;
}

public String getDescription() {
return description;
}

public int getCalories() {
return calories;
}

public boolean isExcess() {
return excess;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package ru.javawebinar.topjava.repository;

import ru.javawebinar.topjava.model.Meal;

import java.time.LocalDateTime;
import java.time.Month;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class InMemoryUserMealRepository implements MealRepository {
private Map<Integer, Meal> repository = new ConcurrentHashMap<>();
private AtomicInteger counter = new AtomicInteger(0);

{
save(new Meal(LocalDateTime.of(2015, Month.MAY, 30, 10, 0), "Завтрак", 500));
save(new Meal(LocalDateTime.of(2015, Month.MAY, 30, 13, 0), "Обед", 1000));
save(new Meal(LocalDateTime.of(2015, Month.MAY, 30, 20, 0), "Ужин", 500));
save(new Meal(LocalDateTime.of(2015, Month.MAY, 31, 10, 0), "Завтрак", 1000));
save(new Meal(LocalDateTime.of(2015, Month.MAY, 31, 13, 0), "Обед", 500));
save(new Meal(LocalDateTime.of(2015, Month.MAY, 31, 20, 0), "Ужин", 510));
}

@Override
public Collection<Meal> getAll() {
return repository.values();
}

@Override
public Meal save(Meal meal) {
if (meal.isNew()) {
meal.setId(counter.incrementAndGet());
}
return repository.put(meal.getId(), meal);
}

@Override
public boolean delete(int id) {
return repository.remove(id) != null;
}

@Override
public Meal get(int id) {
return repository.get(id);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package ru.javawebinar.topjava.repository;

import ru.javawebinar.topjava.model.Meal;

import java.util.Collection;

public interface MealRepository {
// null if not found, when updated
Meal save(Meal meal);

// false if not found
boolean delete(int id);

// null if not found
Meal get(int id);

Collection<Meal> getAll();
}
18 changes: 18 additions & 0 deletions src/main/java/ru/javawebinar/topjava/util/DateTimeUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package ru.javawebinar.topjava.util;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class DateTimeUtil {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

public static boolean isBetween(LocalTime lt, LocalTime startTime, LocalTime endTime) {
return lt.compareTo(startTime) >= 0 && lt.compareTo(endTime) <= 0;
}

public static String toString(LocalDateTime ldt) {
return ldt == null ? "" : ldt.format(DATE_TIME_FORMATTER);
}
}

38 changes: 38 additions & 0 deletions src/main/java/ru/javawebinar/topjava/util/MealsUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package ru.javawebinar.topjava.util;

import ru.javawebinar.topjava.model.Meal;
import ru.javawebinar.topjava.model.MealTo;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class MealsUtil {

public static final int DEFAULT_CALORIES_PER_DAY = 1000;

public static List<MealTo> getTos(Collection<Meal> meals, int caloriesPerDay) {
return getFiltered(meals, caloriesPerDay, meal -> true);
}

public static List<MealTo> getFilteredTos(Collection<Meal> meals, int caloriesPerDay, LocalTime startTime, LocalTime endTime) {
return getFiltered(meals, caloriesPerDay, meal -> DateTimeUtil.isBetween(meal.getDateTime().toLocalTime(), startTime, endTime));
}

private static List<MealTo> getFiltered(Collection<Meal> meals, int caloriesPerDay, Predicate<Meal> filter) {
Map<LocalDateTime, Integer> caloriesSumByDate = meals.stream()
.collect(Collectors.groupingBy(Meal::getDateTime, Collectors.summingInt(Meal::getCalories)));
return meals.stream()
.filter(filter)
.map(meal -> createTo(meal, caloriesSumByDate.get(meal.getDateTime()) > caloriesPerDay))
.collect(Collectors.toList());
}

private static MealTo createTo(Meal meal, boolean excess) {
return new MealTo(meal.getId(), meal.getDateTime(), meal.getDescription(), meal.getCalories(), excess);
}
}
79 changes: 79 additions & 0 deletions src/main/java/ru/javawebinar/topjava/web/MealServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package ru.javawebinar.topjava.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.javawebinar.topjava.model.Meal;
import ru.javawebinar.topjava.repository.InMemoryUserMealRepository;
import ru.javawebinar.topjava.repository.MealRepository;
import ru.javawebinar.topjava.util.MealsUtil;

import javax.servlet.ServletConfig;
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.temporal.ChronoUnit;
import java.util.Objects;

public class MealServlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(MealServlet.class);

private MealRepository repository;

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
repository = new InMemoryUserMealRepository();
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");

Meal meal = new Meal(id.isEmpty() ? null : Integer.valueOf(id),
LocalDateTime.parse(request.getParameter("dateTime")),
request.getParameter("description"),
Integer.parseInt(request.getParameter("calories")));

log.info(meal.isNew() ? "Create {}" : "Update {}", meal);
repository.save(meal);
response.sendRedirect("meals");
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");

switch (action == null ? "all" : action) {
case "delete":
int id = getId(request);
log.info("Delete {}", id);
repository.delete(id);
response.sendRedirect("meals");
break;
case "create":
case "update":
final Meal meal = "create".equals(action) ?
new Meal(LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES), "", 1000) :
repository.get(getId(request));
request.setAttribute("meal", meal);
request.getRequestDispatcher("/mealForm.jsp").forward(request, response);
break;
case "all":
default:
log.info("getAll");
request.setAttribute("meals",
MealsUtil.getTos(repository.getAll(), MealsUtil.DEFAULT_CALORIES_PER_DAY));
request.getRequestDispatcher("/meals.jsp").forward(request, response);
break;
}
}

private int getId(HttpServletRequest request) {
String paramId = Objects.requireNonNull(request.getParameter("id"));
return Integer.parseInt(paramId);
}
}
Loading