Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 62e17e1

Browse files
committed
lesson_1
1 parent 0b8d782 commit 62e17e1

File tree

12 files changed

+363
-11
lines changed

12 files changed

+363
-11
lines changed

config/tomcat/setenv.bat

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
rem run tomcat with JMX ability
2+
rem Run Tomcat as admin
3+
rem for remote connection add -Djava.rmi.server.hostname=TomcatServer_IP
4+
set CATALINA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=1099 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false

doc/lesson01.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Занятие 1 онлайн проекта <a href="http://javawebinar.ru/topjava/">Topjava</a>
2+
3+
**Напоминаю, что патчи в материалах урока необходимо накатывать (Apply Patch) на ветку MASTER и БЕЗ ВАШИХ ИЗМЕНЕНИЙ, иначе с ними будут проблемы. Делать Apply можно как по ходу видео, так и немного заранее - тогда при просмотре видео вы сразу сможете отслеживать изменения кода проекта.**
4+
## <a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFfm5hSHEtbmxmN2kxb0NocVRwWl9KanowWXVCVXRZTlhaM09wQUswZkRidTA">Материалы урока</a>
5+
6+
## <a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFOGU0a3ZUbFo3Skk">Домашнее задание: реализация getFilteredMealsWithExceeded через Stream API</a>
7+
- <a href="http://www.youtube.com/watch?v=_PDIVhEs6TM">Доступно о Java 8 Lambda</a>
8+
- **<a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFQ1UwZjdMUzRrakU">1_ Lambda_ samples.patch</a>**
9+
- **<a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFaE1ycEhQYUV2QjA">2_ HW0.patch</a>**
10+
- <a href="http://prologistic.com.ua/polnoe-rukovodstvo-po-java-8-stream.html">Перевод "Java 8 Stream Tutorial"</a>
11+
- <a href="https://docs.google.com/presentation/d/1fR1N_UsQDhOarLKo5nrgMU1r5-M8v-IbKhpS3sQTKnY">Основное в Java 8</a>
12+
13+
## <a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFdTJIQUExajZWWkE">Работа с git в IDEA. HW0: реализация через цикл.</a>
14+
- **<a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFUkRPZW9jbHFadjA">3_ HW0_ cycles.patch</a>**
15+
16+
## <a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFRmo0YkVVaDJPTVE">Обзор используемых в проекте технологий. Интеграция ПО.</a>
17+
- <a href="http://zeroturnaround.com/rebellabs/java-tools-and-technologies-landscape-for-2014/">Обзор популярности инструментов и технологий Java за 2014 г.</a>
18+
- <a href="http://www.youtube.com/watch?v=rJZHerwi8R0">Видео "Приложение Spring Pet Clinic"</a>
19+
- Приложение <a href="https://github.com/spring-projects/spring-petclinic">Spring Pet Clinic</a>.
20+
- Demo <a href="http://petclinic.cloudapp.net/">Spring Pet Clinic</a>
21+
22+
## <a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFZFBuZVRKNU5Kb3c">Maven.</a>
23+
- <a href="http://maven.apache.org/">Home Page</a>
24+
- Среда сборки проектов <a href="http://www.apache-maven.ru/" target="_blank">Maven</a>.
25+
- <a href="http://search.maven.org/#browse">The Central Repository</a>
26+
- <a href="http://habrahabr.ru/post/111408/">Maven archetype</a>. Создание проекта на основе maven-archetype-webapp. Сборка проекта.
27+
- Настройка пропертей Maven: кодировка, java version, зависимости, maven-compiler-plugin
28+
- <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html">Build Lifecycle</a>.
29+
- <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html">Dependency Mechanism</a>
30+
- <a href="http://www.ibm.com/developerworks/ru/library/j-5things13/">Зависимости, профили</a>
31+
- <a href="http://maven.apache.org/guides/mini/guide-multiple-modules.html">The Reactor</a>. Snapshots
32+
- <a href="http://habrahabr.ru/blogs/java/106717/" target="_blank">Недостатки Maven</a>. Другие инструменты сборки.
33+
- Ресурсы:
34+
- <a href="http://books.sonatype.com/mvnref-book/reference/index.html">Maven: The Complete Reference</a>
35+
- <a href="http://habrahabr.ru/post/77333/">Автоматизация сборки проекта</a>
36+
- <a href="http://www.sonatype.org/nexus/">Repository management Nexus</a>
37+
- <a href="http://blog.bintray.com/2014/02/11/bintray-as-pain-free-gateway-to-maven-central/">Bintray: gateway to Maven Central</a>
38+
39+
## <a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFT3pWNkMzWVVybnc&authuser=0">WAR. Веб-контейнер Tomcat. Сервлеты.</a>
40+
- **<a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFbWhybDhKZW5NVTA">4_ Switch_ to_ war_ packaging.patch</a>**
41+
- **<a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFS0IybUVtNzd1emM">5_ Add_ servlet_ jsp_ html.patch</a>**
42+
- **<a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFZkFBOEhsZFh0dzA">6_ Forward_ to_ redirect.patch</a>**
43+
44+
- Перевод проекта на Web.
45+
- <a href="http://tomcat.apache.org/">Tomcat Home Page</a>
46+
- <a href="http://java-course.ru/student/book1/servlet/">Сервлеты.</a>
47+
- Настройка и деплой в Tomcat. Tomcat manager. Remote debug.
48+
- Запуск Tomcat через tomcat7-maven-plugin. Конфигурирование плагина.
49+
- Запуск Tomcat из IDEA. Динамическое обновление без передеплоя.
50+
- Redirect, Forward, Application context, Servlet context
51+
- Томкат менеджер: http://localhost:8080/manager
52+
- Наше приложение: http://localhost:8080/topjava</a>
53+
- Наш сервлет: http://localhost:8080/topjava/users
54+
55+
- Ресурсы:
56+
- <a href="http://www.techinfo.net.ru/docs/web/javawebdev.html">Технологии Java для разработки веб-приложений</a>
57+
58+
## <a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFeGJCdDJHbWNyUzg&authuser=0">Логирование.</a>
59+
- **<a href="https://drive.google.com/open?id=0B9Ye2auQ_NsFcEdRUnp0ZlY2cnc">7_ Add_ logging.patch</a>**
60+
61+
- <a href="http://www.youtube.com/watch?v=Lyqc8HicPMM">Видео с TopJava01</a>
62+
- <a href="http://habrahabr.ru/post/113145/">Java Logging: история кошмара</a>
63+
- <a href="http://skipy.ru/useful/logging.html">Ведение лога приложения</a>
64+
- <a href="http://www.slf4j.org/legacy.html">Добавление зависимостей логирования</a> в проект.
65+
- <a href="http://logging.apache.org/log4j/2.x/index.html">Log4j</a>, <a href="http://logback.qos.ch/">Logback</a>
66+
- Конфигурирование логирования. Создание обертки логирования. Настройка Live Template.
67+
- Интеграция IDEA с Tomcat, деплой.
68+
- Тестирование логирования в сервлете. Переменная окружения TOPJAVA_ROOT.
69+
- Управление логированием по JMX.
70+
- Контекст приложения. Деплой в Tomcat без IDE. Remote debug.
71+
72+
## <a href="">Уровни и зависимости логгирования, JMX</a>
73+
74+
## Домашнее задание HW01
75+
76+
Попробовать разные деплои в Tomcat, remote и local debug
77+
По аналогии с Users добавить MealServlet и mealList.jsp.
78+
Добавить в JSP и index.html ссылки друг на друга
79+
Задеплоить приложение (war) в Tomcat c applicationContext=topjava и проверить работу ссылок
80+
81+
Optional
82+
83+
Сделать реализацию CRUD (create/read/update/delete) для списка еды.
84+
Цвет записи в таблице зависит от параметра isExceeded.

pom.xml

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
<groupId>ru.javawebinar</groupId>
66
<artifactId>topjava</artifactId>
7-
<packaging>jar</packaging>
7+
<packaging>war</packaging>
88

99
<version>1.0-SNAPSHOT</version>
1010

@@ -13,13 +13,18 @@
1313

1414
<properties>
1515
<java.version>1.8</java.version>
16+
1617
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
1718
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
19+
20+
<!-- Logging -->
21+
<logback.version>1.1.2</logback.version>
22+
<slf4j.version>1.7.7</slf4j.version>
1823
</properties>
1924

2025
<build>
2126
<finalName>topjava</finalName>
22-
<defaultGoal>install</defaultGoal>
27+
<defaultGoal>package</defaultGoal>
2328
<plugins>
2429
<plugin>
2530
<groupId>org.apache.maven.plugins</groupId>
@@ -34,6 +39,43 @@
3439
</build>
3540

3641
<dependencies>
42+
<!-- Logging with SLF4J & LogBack -->
43+
<dependency>
44+
<groupId>org.slf4j</groupId>
45+
<artifactId>slf4j-api</artifactId>
46+
<version>${slf4j.version}</version>
47+
<scope>compile</scope>
48+
</dependency>
49+
50+
<dependency>
51+
<groupId>org.slf4j</groupId>
52+
<artifactId>jcl-over-slf4j</artifactId>
53+
<version>${slf4j.version}</version>
54+
<scope>runtime</scope>
55+
</dependency>
56+
57+
<dependency>
58+
<groupId>org.slf4j</groupId>
59+
<artifactId>jul-to-slf4j</artifactId>
60+
<version>${slf4j.version}</version>
61+
<scope>runtime</scope>
62+
</dependency>
63+
64+
<dependency>
65+
<groupId>ch.qos.logback</groupId>
66+
<artifactId>logback-classic</artifactId>
67+
<version>${logback.version}</version>
68+
<scope>runtime</scope>
69+
</dependency>
70+
71+
<!--Web-->
72+
<dependency>
73+
<groupId>javax.servlet</groupId>
74+
<artifactId>servlet-api</artifactId>
75+
<version>2.5</version>
76+
<scope>provided</scope>
77+
</dependency>
78+
3779
</dependencies>
3880

3981
<profiles>
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package ru.javawebinar.topjava;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
/**
7+
* User: gkislin
8+
* Date: 22.01.14
9+
*/
10+
public class LoggerWrapper {
11+
12+
private Logger logger;
13+
14+
public LoggerWrapper(Logger logger) {
15+
this.logger = logger;
16+
}
17+
18+
public static LoggerWrapper get(Class aClass) {
19+
return new LoggerWrapper(LoggerFactory.getLogger(aClass));
20+
}
21+
22+
public void debug(String msg) {
23+
logger.debug(msg);
24+
}
25+
26+
public void info(String msg, Object... arguments) {
27+
logger.info(msg, arguments);
28+
}
29+
30+
public void warn(String msg) {
31+
logger.warn(msg);
32+
}
33+
34+
public void warn(String msg, Throwable t) {
35+
logger.warn(msg, t);
36+
}
37+
38+
public void error(String msg) {
39+
logger.error(msg);
40+
}
41+
42+
public void error(String msg, Throwable t) {
43+
logger.error(msg, t);
44+
}
45+
46+
public boolean isDebug() {
47+
return logger.isDebugEnabled();
48+
}
49+
50+
public IllegalStateException getIllegalStateException(String msg) {
51+
return getIllegalStateException(msg, null);
52+
}
53+
54+
public IllegalStateException getIllegalStateException(String msg, Throwable e) {
55+
logger.error(msg, e);
56+
return new IllegalStateException(msg, e);
57+
}
58+
59+
public IllegalArgumentException getIllegalArgumentException(String msg) {
60+
return getIllegalArgumentException(msg, null);
61+
}
62+
63+
public IllegalArgumentException getIllegalArgumentException(String msg, Throwable e) {
64+
logger.error(msg, e);
65+
return new IllegalArgumentException(msg, e);
66+
}
67+
68+
public UnsupportedOperationException getUnsupportedOperationException(String msg) {
69+
logger.error(msg);
70+
return new UnsupportedOperationException(msg);
71+
}
72+
}
Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,32 @@
11
package ru.javawebinar.topjava;
22

3+
import java.util.function.Consumer;
4+
35
/**
46
* User: gkislin
57
* Date: 05.08.2015
68
*
7-
* @link http://caloriesmng.herokuapp.com/
9+
* @link http://javawebinar.ru/topjava/
810
* @link https://github.com/JavaOPs/topjava
911
*/
1012
public class Main {
1113
public static void main(String[] args) {
14+
execute(() -> {
15+
System.out.println("Hello Topjava!");
16+
});
17+
consume(System.out::println, "Hello Topjava!");
18+
}
19+
20+
private static void execute(Runnable runnable) {
21+
System.out.println("Start runner");
22+
runnable.run();
23+
System.out.println("End runner");
24+
}
25+
26+
private static <String> void consume(Consumer<String> consumer, String out) {
27+
System.out.println("Start consume");
28+
consumer.accept(out);
29+
System.out.println("End consume");
1230
System.out.format("Hello Topjava Enterprise!");
1331
}
1432
}

src/main/java/ru/javawebinar/topjava/model/UserMealWithExceed.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,14 @@ public UserMealWithExceed(LocalDateTime dateTime, String description, int calori
2121
this.calories = calories;
2222
this.exceed = exceed;
2323
}
24+
25+
@Override
26+
public String toString() {
27+
return "UserMealWithExceed{" +
28+
"dateTime=" + dateTime +
29+
", description='" + description + '\'' +
30+
", calories=" + calories +
31+
", exceed=" + exceed +
32+
'}';
33+
}
2434
}

src/main/java/ru/javawebinar/topjava/util/UserMealsUtil.java

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
import ru.javawebinar.topjava.model.UserMeal;
44
import ru.javawebinar.topjava.model.UserMealWithExceed;
55

6+
import java.time.LocalDate;
67
import java.time.LocalDateTime;
78
import java.time.LocalTime;
89
import java.time.Month;
9-
import java.util.Arrays;
10-
import java.util.List;
10+
import java.util.*;
11+
import java.util.stream.Collectors;
1112

1213
/**
1314
* GKislin
@@ -23,13 +24,40 @@ public static void main(String[] args) {
2324
new UserMeal(LocalDateTime.of(2015, Month.MAY, 31,13,0), "Обед", 500),
2425
new UserMeal(LocalDateTime.of(2015, Month.MAY, 31,20,0), "Ужин", 510)
2526
);
26-
getFilteredMealsWithExceeded(mealList, LocalTime.of(7, 0), LocalTime.of(12,0), 2000);
27-
// .toLocalDate();
28-
// .toLocalTime();
27+
List<UserMealWithExceed> filteredMealsWithExceeded = getFilteredMealsWithExceeded(mealList, LocalTime.of(7, 0), LocalTime.of(12, 0), 2000);
28+
filteredMealsWithExceeded.forEach(System.out::println);
29+
30+
System.out.println(getFilteredMealsWithExceededByCycle(mealList, LocalTime.of(7, 0), LocalTime.of(12, 0), 2000));
2931
}
3032

31-
public static List<UserMealWithExceed> getFilteredMealsWithExceeded(List<UserMeal> mealList, LocalTime startTime, LocalTime endTime, int caloriesPerDay) {
32-
// TODO return filtered list with correctly exceeded field
33-
return null;
33+
public static List<UserMealWithExceed> getFilteredMealsWithExceeded(List<UserMeal> mealList, LocalTime startTime, LocalTime endTime, int caloriesPerDay) {
34+
Map<LocalDate, Integer> caloriesSumByDate = mealList.stream().collect(Collectors.groupingBy(um -> um.getDateTime().toLocalDate(),
35+
Collectors.summingInt(UserMeal::getCalories)));
36+
37+
return mealList.stream()
38+
.filter(um->TimeUtil.isBetween(um.getDateTime().toLocalTime(), startTime, endTime))
39+
.map(um->new UserMealWithExceed(um.getDateTime(), um.getDescription(), um.getCalories(),
40+
caloriesSumByDate.get(um.getDateTime().toLocalDate())> caloriesPerDay))
41+
.collect(Collectors.toList());
3442
}
43+
44+
public static List<UserMealWithExceed> getFilteredMealsWithExceededByCycle(List<UserMeal> mealList, LocalTime startTime, LocalTime endTime, int caloriesPerDay) {
45+
46+
Map<LocalDate, Integer> caloriesSumPerDate = new HashMap<>();
47+
for (UserMeal meal : mealList) {
48+
LocalDate mealDate = meal.getDateTime().toLocalDate();
49+
caloriesSumPerDate.put(mealDate, caloriesSumPerDate.getOrDefault(mealDate, 0) + meal.getCalories());
50+
}
51+
52+
List<UserMealWithExceed> mealExceeded = new ArrayList<>();
53+
for (UserMeal meal : mealList) {
54+
LocalDateTime dateTime = meal.getDateTime();
55+
if (TimeUtil.isBetween(dateTime.toLocalTime(), startTime, endTime)) {
56+
mealExceeded.add(new UserMealWithExceed(dateTime, meal.getDescription(), meal.getCalories(),
57+
caloriesSumPerDate.get(dateTime.toLocalDate()) > caloriesPerDay));
58+
}
59+
}
60+
return mealExceeded;
61+
}
62+
3563
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package ru.javawebinar.topjava.web;
2+
3+
import ru.javawebinar.topjava.LoggerWrapper;
4+
5+
import javax.servlet.ServletException;
6+
import javax.servlet.http.HttpServlet;
7+
import javax.servlet.http.HttpServletRequest;
8+
import javax.servlet.http.HttpServletResponse;
9+
import java.io.IOException;
10+
11+
/**
12+
* User: gkislin
13+
* Date: 19.08.2014
14+
*/
15+
public class UserServlet extends HttpServlet {
16+
private static final LoggerWrapper LOG = LoggerWrapper.get(UserServlet.class);
17+
18+
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19+
LOG.debug("redirect to userList");
20+
21+
// request.getRequestDispatcher("/userList.jsp").forward(request, response);
22+
response.sendRedirect("userList.jsp");
23+
}
24+
}

0 commit comments

Comments
 (0)