-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
16 changed files
with
412 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
.gradle/ | ||
build/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
test: | ||
gradle test | ||
|
||
example: | ||
java src/main/java/exercise/Example.java |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
# Генерация кода | ||
|
||
В этом задании вам предстоит поработать с библиотекой Lombok, которая позволяет генерировать код с помощью аннотаций. | ||
|
||
## Ссылки | ||
|
||
* [Проект Lombok](https://projectlombok.org/) | ||
* [Объект DataMapper](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html) | ||
* [Метод readValue()](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#readValue(java.lang.String,%20java.lang.Class)) | ||
* [Метод writeValueAsString()](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#writeValueAsString(java.lang.Object)) | ||
* [Класс Files для работы с файлами](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html) | ||
|
||
## main/java/exercise/User.java | ||
|
||
## Задачи | ||
|
||
* В файле создан класс `User`, который описывает владельца автомобиля. В классе уже определены все свойства, но нет конструктора и геттеров. Допишите нужную аннотацию lombock, чтобы автоматически сгенерировать конструктор и геттеры для всех свойств и сделать класс неизменяемым. | ||
|
||
```java | ||
User owner = new User(1, "Ivan", "P", 25); | ||
// Вызываем автоматически сгенерированный геттер | ||
owner.getFirstName(); // "Ivan" | ||
``` | ||
|
||
## main/java/exercise/Car.java | ||
|
||
## Задачи | ||
|
||
* В файле уже создан класс `Car`, который описывает автомобиль. Допишите нужную аннотацию lombock, чтобы автоматически сгенерировать конструктор и геттеры для всех свойств и сделать класс неизменяемым. | ||
|
||
* Дополнительно создайте в классе два метода: | ||
|
||
* Публичный метод `serialize()` — cериализует объект. Метод возвращает JSON представление объекта (в виде строки). | ||
* Публичный статический метод `unserialize()`, который принимает в качестве аргумента строку (JSON представление объекта класса `Car`) и возвращает объект класса `Car` с соответствующими свойствами. | ||
|
||
```java | ||
Car car = new Car(1, "bmv", "x5", "black", owner); | ||
String jsonRepresentation = car.serialize(); | ||
System.out.println(jsonRepresentation); // => | ||
/* | ||
{ | ||
"id":1, | ||
"brand":"bmv", | ||
"model":"x5", | ||
"color":"black", | ||
"owner":{ | ||
"id":1, | ||
"firstName":"Ivan", | ||
"lastName":"P", | ||
"age":25 | ||
} | ||
} | ||
*/ | ||
|
||
String jsonRepresentation = // получаем JSON представление объекта | ||
Car instance = Car.unserialize(jsonRepresentation); | ||
instance.getBrand(); // "bmv" | ||
instance.getModel(); // "x5" | ||
``` | ||
|
||
## main/java/exercise/App.java | ||
|
||
## Задачи | ||
|
||
* Создайте класс `App` с публичными статическими методами: | ||
|
||
* `save()` — принимает в качестве аргумента путь к файлу (объект класса `Path`) и объект класса `Car`. Метод сохраняет представление объекта в файл по переданному пути. Чтобы сохранить объект в файл, вам нужно будет представить его в виде строки (сериализовать). | ||
|
||
* `extract()` — принимает в качестве аргумента путь к файлу (объект класса `Path`), в котором содержится JSON представление объекта `Car` и возвращает инстанс класса `Car` с соответствующими свойствами. | ||
|
||
```java | ||
Path path1 = Paths.get("/tmp/file1.json"); | ||
Car car1 = new Car(1, "audi", "q3", "black", owner); | ||
App.save(path1, car1); // Сохраняет представление объекта в файл | ||
|
||
Path path2 = Paths.get("/tmp/file2.json"); | ||
Car car2 = App.extract(path2); // Возвращает инстанс класса Car | ||
car2.getModel(); // "passat" | ||
``` | ||
|
||
## Подсказки | ||
|
||
* Для преобразования объекта в JSON строку и обратно, воспользуйтесь классом [ObjectMapper](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
plugins { | ||
id 'java' | ||
id 'com.adarshr.test-logger' version '2.1.1' | ||
} | ||
|
||
repositories { | ||
mavenCentral() | ||
} | ||
|
||
dependencies { | ||
compileOnly 'org.projectlombok:lombok:1.18.20' | ||
annotationProcessor 'org.projectlombok:lombok:1.18.20' | ||
testCompileOnly 'org.projectlombok:lombok:1.18.20' | ||
testAnnotationProcessor 'org.projectlombok:lombok:1.18.20' | ||
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.0-M1' | ||
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.0-M1' | ||
testImplementation 'org.assertj:assertj-core:3.19.0' | ||
|
||
implementation 'com.fasterxml.jackson.core:jackson-core:2.8.8' | ||
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.8.8' | ||
implementation 'com.fasterxml.jackson.core:jackson-databind:2.8.8' | ||
} | ||
|
||
test { | ||
useJUnitPlatform() | ||
} | ||
|
||
testlogger { | ||
showStandardStreams = true | ||
} | ||
|
||
tasks.withType(JavaCompile) { | ||
options.encoding = "UTF-8" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package exercise; | ||
|
||
import exercise.demo.Item; | ||
|
||
class Example { | ||
public static void main(String[] args) { | ||
//data + getter/setter/toString | ||
// Item milk = new Item(); | ||
// milk.setId(1); | ||
// milk.setName("Молоко"); | ||
// milk.setPrice(99.90); | ||
// System.out.println(milk); | ||
//// | ||
// Item bread = new Item(); | ||
// bread.setId(1); | ||
// bread.setName("Хлеб"); | ||
// bread.setPrice(69.90); | ||
|
||
// System.out.println(milk.equals(bread)); | ||
|
||
|
||
// // builder | ||
// Item item = Item.builder() | ||
// .id(1) | ||
// .name("Котлета") | ||
// .price(100.0) | ||
// .build(); | ||
//// | ||
// System.out.println(item); | ||
|
||
// nonNull | ||
Item item = Item.builder() | ||
.price(10.0) | ||
.name("Йогурт") | ||
.id(12) | ||
.build(); | ||
System.out.println(item); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
lombok.anyConstructor.addConstructorProperties=true | ||
config.stopBubbling = true |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
rootProject.name = 'code-generation' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package exercise; | ||
|
||
import java.nio.file.Path; | ||
import java.nio.file.Files; | ||
import java.nio.file.StandardOpenOption; | ||
|
||
// BEGIN | ||
|
||
// END |
19 changes: 19 additions & 0 deletions
19
java-oop-ru/code-generation/src/main/java/exercise/Car.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package exercise; | ||
|
||
import lombok.Value; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
|
||
// BEGIN | ||
|
||
// END | ||
class Car { | ||
int id; | ||
String brand; | ||
String model; | ||
String color; | ||
User owner; | ||
|
||
// BEGIN | ||
|
||
// END | ||
} |
13 changes: 13 additions & 0 deletions
13
java-oop-ru/code-generation/src/main/java/exercise/User.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package exercise; | ||
|
||
import lombok.Value; | ||
|
||
// BEGIN | ||
|
||
// END | ||
class User { | ||
int id; | ||
String firstName; | ||
String lastName; | ||
int age; | ||
} |
12 changes: 12 additions & 0 deletions
12
java-oop-ru/code-generation/src/main/java/exercise/demo/Item.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
package exercise.demo; | ||
|
||
import lombok.Builder; | ||
import lombok.NonNull; | ||
|
||
@Builder | ||
public class Item { | ||
@NonNull | ||
private Integer id; | ||
private String name; | ||
private Double price; | ||
} |
71 changes: 71 additions & 0 deletions
71
java-oop-ru/code-generation/src/test/java/exercise/AppTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package exercise; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.junit.jupiter.api.BeforeAll; | ||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.AfterEach; | ||
import static org.assertj.core.api.Assertions.assertThat; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import java.nio.file.Paths; | ||
import java.nio.file.Path; | ||
import java.nio.file.Files; | ||
import java.util.Map; | ||
import java.util.HashMap; | ||
|
||
|
||
|
||
class ValidationTest { | ||
|
||
private static ObjectMapper objectMapper; | ||
private static Path tempPath; | ||
|
||
@BeforeAll | ||
static void setUp() throws Exception { | ||
objectMapper = new ObjectMapper(); | ||
} | ||
|
||
@BeforeEach | ||
void createTempFile() throws Exception { | ||
tempPath = Files.createTempFile("temp", ""); | ||
} | ||
|
||
@AfterEach | ||
void deleteTempFile() throws Exception { | ||
Files.deleteIfExists(tempPath); | ||
} | ||
|
||
private static String readFile(Path path) throws Exception { | ||
return Files.readString(path); | ||
} | ||
|
||
private static Path getFixturePath(String fileName) { | ||
return Paths.get("src/test/resources/", fileName).toAbsolutePath().normalize(); | ||
} | ||
|
||
@Test | ||
void testSave() throws Exception { | ||
User owner = new User(1, "Ivan", "Petrov", 25); | ||
Car car = new Car(1, "bmv", "x5", "black", owner); | ||
App.save(tempPath, car); | ||
String actualContent = readFile(tempPath); | ||
Map<String, Object> actual = objectMapper.readValue(actualContent, HashMap.class); | ||
String expectedContent = readFile(getFixturePath("expected1.json")); | ||
Map<String, Object> expected = objectMapper.readValue(expectedContent, HashMap.class); | ||
assertThat(actual).isEqualTo(expected); | ||
} | ||
|
||
@Test | ||
void testExtract() throws Exception { | ||
Path fixturePath = getFixturePath("car.json"); | ||
Car instance = App.extract(fixturePath); | ||
assertThat(instance).isInstanceOf(Car.class); | ||
assertThat(instance.getId()).isEqualTo(5); | ||
assertThat(instance.getBrand()).isEqualTo("audi"); | ||
assertThat(instance.getModel()).isEqualTo("q7"); | ||
assertThat(instance.getColor()).isEqualTo("white"); | ||
User owner = instance.getOwner(); | ||
assertThat(owner).isInstanceOf(User.class); | ||
assertThat(owner.getFirstName()).isEqualTo("Nikolay"); | ||
assertThat(owner.getLastName()).isEqualTo("Ivanov"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
{"id":5,"brand":"audi","model":"q7","color":"white","owner":{"id":8,"firstName":"Nikolay","lastName":"Ivanov","age":50}} |
12 changes: 12 additions & 0 deletions
12
java-oop-ru/code-generation/src/test/resources/expected1.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
{ | ||
"id":1, | ||
"brand":"bmv", | ||
"model":"x5", | ||
"color":"black", | ||
"owner":{ | ||
"id":1, | ||
"firstName":"Ivan", | ||
"lastName":"Petrov", | ||
"age":25 | ||
} | ||
} |