Добавил валидацию при вводе значений

This commit is contained in:
Ivan Zinchenko 2024-05-02 21:48:25 +03:00
parent 96a055a29d
commit ca28cbab7d
Signed by: zinch
GPG Key ID: 6D45AA2C8FD6A37E
10 changed files with 152 additions and 6 deletions

118
db.xml
View File

@ -1 +1,117 @@
<Products><Product><id>341</id><name>ewreqr</name><coordinates><x>1432</x><y>132432</y></coordinates><creationDate>1711875600.000000000</creationDate><price>12324</price><partNumber>3214</partNumber><manufactureCost>342</manufactureCost><unitOfMeasure>CENTIMETERS</unitOfMeasure><owner><name>324324</name><passportID>32143214</passportID><hairColor>WHITE</hairColor><location><x>342.0</x><y>423</y><name>214</name></location></owner></Product><Product><id>342</id><name>Hello</name><coordinates><x>13</x><y>4</y></coordinates><creationDate>1713267558.813808800</creationDate><price>12312</price><partNumber>312</partNumber><manufactureCost>321</manufactureCost><unitOfMeasure>CENTIMETERS</unitOfMeasure><owner><name>123</name><passportID>431</passportID><hairColor>BLACK</hairColor><location><x>2321.0</x><y>432</y><name>31</name></location></owner></Product></Products>
<?xml version="1.0" encoding="UTF-8" ?>
<Products>
<Product>
<id>1</id>
<name>Product 1</name>
<coordinates>
<x>100</x>
<y>50</y>
</coordinates>
<creationDate>2024-03-01T12:00:00Z</creationDate>
<price>50</price>
<partNumber>PN123</partNumber>
<manufactureCost>30</manufactureCost>
<unitOfMeasure>KILOGRAMS</unitOfMeasure>
<owner>
<name>John Doe</name>
<passportID>AB12345</passportID>
<hairColor>BLACK</hairColor>
<location>
<x>10.5</x>
<y>20</y>
<name>Home</name>
</location>
</owner>
</Product>
<Product>
<id>2</id>
<name>Product 2</name>
<coordinates>
<x>200</x>
<y>100</y>
</coordinates>
<creationDate>2024-03-01T12:05:00Z</creationDate>
<price>80</price>
<partNumber>PN456</partNumber>
<manufactureCost>60</manufactureCost>
<unitOfMeasure>CENTIMETERS</unitOfMeasure>
<owner>
<name>Alice Smith</name>
<passportID>CD67890</passportID>
<hairColor>BLUE</hairColor>
<location>
<x>20.8</x>
<y>30</y>
<name>Office</name>
</location>
</owner>
</Product>
<Product>
<id>3</id>
<name>Product 3</name>
<coordinates>
<x>150</x>
<y>-200</y>
</coordinates>
<creationDate>2024-03-01T12:10:00Z</creationDate>
<price>120</price>
<manufactureCost>90</manufactureCost>
<unitOfMeasure>GRAMS</unitOfMeasure>
<owner>
<name>Emma Johnson</name>
<passportID>EF24680</passportID>
<hairColor>GREEN</hairColor>
<location>
<x>30.2</x>
<y>40</y>
<name>Warehouse</name>
</location>
</owner>
</Product>
<Product>
<id>4</id>
<name>Product 4</name>
<coordinates>
<x>300</x>
<y>-300</y>
</coordinates>
<creationDate>2024-03-01T12:15:00Z</creationDate>
<price>200</price>
<partNumber>PN789</partNumber>
<manufactureCost>150</manufactureCost>
<unitOfMeasure>KILOGRAMS</unitOfMeasure>
<owner>
<name>Bob Brown</name>
<passportID>GH13579</passportID>
<hairColor>ORANGE</hairColor>
<location>
<x>40.6</x>
<y>50</y>
<name>Factory</name>
</location>
</owner>
</Product>
<Product>
<id>5</id>
<name>Product 5</name>
<coordinates>
<x>400</x>
<y>400</y>
</coordinates>
<creationDate>2024-03-01T12:20:00Z</creationDate>
<price>150</price>
<partNumber>PN246</partNumber>
<manufactureCost>100</manufactureCost>
<unitOfMeasure>CENTIMETERS</unitOfMeasure>
<owner>
<name>Grace Lee</name>
<passportID>IJ35791</passportID>
<hairColor>WHITE</hairColor>
<location>
<x>50.9</x>
<y>60</y>
<name>Store</name>
</location>
</owner>
</Product>
</Products>

View File

@ -25,7 +25,7 @@ public class Add extends Command {
var product = productCollection.addProduct(productDTO);
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
} catch (ValidationException e) {
throw new CommandActionException(e.getMessage());
throw new CommandActionException(String.format("Произошла ошибка при добавлении%n%s", e.getMessage()));
}
}
}

View File

@ -36,6 +36,7 @@ public class ExecuteScript extends Command {
try {
var result = new StringBuilder();
var scriptFile = Console.getLastCommand().split(" ")[1];
result.append(String.format("Скрипт %s начинает работу.%n", scriptFile));
addFileToStack(scriptFile);
var commandList = ScriptLoader.loadList(scriptFile);
for (var input: commandList) {

View File

@ -108,8 +108,10 @@ public class Console {
try {
function.run();
return;
} catch (NullPointerException e) {
System.out.println("Произошла ошибка при заполнении поля\оле не может быть null");
} catch (Exception e) {
System.out.format("Произошла ошибка при заполнении поля\n%s\n", e.getMessage());
System.out.format("Произошла ошибка при заполнении поля%n%s%n", e.getMessage());
}
}
}
@ -150,8 +152,10 @@ public class Console {
.map(ValidateResult::getMessage)
.toList()));
}
var productCollection = new ProductCollection(productList);
System.out.println("Добро пожаловать! Для просмотра команд введите help");
while(isRunning) {
System.out.print(":");
try {

View File

@ -9,4 +9,8 @@ public class DbInitializationException extends IOException {
public DbInitializationException() {
super("Ошибка! Не удалось инициализировать БД. Проверьте, что структура БД верна.");
}
public DbInitializationException(String message) {
super(message);
}
}

View File

@ -7,6 +7,7 @@ import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import me.zinch.exceptions.DbInitializationException;
import me.zinch.exceptions.ValidationException;
import me.zinch.models.Product;
import java.io.BufferedInputStream;
@ -59,6 +60,9 @@ public class DbController {
} catch (FileNotFoundException e) {
throw new FileNotFoundException("Не удалось найти файл " + path);
} catch (DatabindException e) {
if (e.getCause() instanceof ValidationException) {
throw new DbInitializationException(String.format("Ошибка при валидации базы%n%s", e.getCause().getMessage()));
}
throw new DbInitializationException();
} catch (IOException e) {
throw new IOException("Произошла неожиданная ошибка во время работы с файлом!");

View File

@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import me.zinch.exceptions.ValidationException;
import java.util.Objects;
@ -15,7 +16,7 @@ public class Coordinates {
@JsonProperty("x")
private long x; //Максимальное значение поля: 883
@NotNull(message = "Coordinates: Поле не может быть null")
@NotNull(message = "Coordinates: Поле y не может быть null")
@Min(value = -427, message = "Значение координаты y должно быть больше -427")
@JsonProperty("y")
private Long y; //Значение поля должно быть больше -427, Поле не может быть null
@ -28,10 +29,13 @@ public class Coordinates {
}
public void setX(long x) {
if (x > 883) throw new ValidationException("Максимальное значение координаты x: 883");
this.x = x;
}
public void setY(Long y) {
if (y == null) throw new ValidationException("Поле y не может быть null");
if (y < -427) throw new ValidationException("Значение координаты y должно быть больше -427");
this.y = y;
}

View File

@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import me.zinch.exceptions.ValidationException;
import java.util.Objects;
@ -36,10 +37,13 @@ public class Person {
}
public void setName(String name) {
if (name == null || name.isEmpty()) throw new ValidationException("Имя персоны не может быть пустым или null");
this.name = name;
}
public void setPassportID(String passportID) {
if (passportID == null) throw new ValidationException("Поле passportID не может быть null");
if (passportID.length() < 5 || passportID.length() > 22) throw new ValidationException("Длина строки passportID должна быть не меньше 5 и не должна быть больше 22");
this.passportID = passportID;
}

View File

@ -6,6 +6,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import me.zinch.exceptions.ValidationException;
import me.zinch.validator.NotEmpty;
@ -24,7 +25,7 @@ public class ProductDTO {
private Coordinates coordinates; //Поле не может быть null
@NotNull(message = "ProductDTO: Поле price не может быть null")
@Min(value = 1, message = "Поле price не может быть null")
@Min(value = 1, message = "ProductDTO: Значение поля price должно быть больше 0")
@JsonProperty("price")
private Long price; //Поле не может быть null, Значение поля должно быть больше 0
@ -97,18 +98,24 @@ public class ProductDTO {
}
public void setName(String name) {
if (name == null || name.isEmpty()) throw new ValidationException("Строка name не может быть пустой или null");
this.name = name;
}
public void setCoordinates(Coordinates coordinates) {
if (coordinates == null) throw new ValidationException("Поле coordinates не может быть null");
this.coordinates = coordinates;
}
public void setPrice(Long price) {
if (price == null) throw new ValidationException("Поле price не может быть null");
if (price <= 0) throw new ValidationException("Поле price не может быть null");
this.price = price;
}
public void setPartNumber(String partNumber) {
if (partNumber.isEmpty()) throw new ValidationException("Строка partNumber не может быть пустой");
if (partNumber.length() > 82) throw new ValidationException("Длина строки partNumber не должна быть больше 82");
this.partNumber = partNumber;
}
@ -117,10 +124,12 @@ public class ProductDTO {
}
public void setUnitOfMeasure(UnitOfMeasure unitOfMeasure) {
if (unitOfMeasure == null) throw new ValidationException("Поле unitOfMeasure не может быть null");
this.unitOfMeasure = unitOfMeasure;
}
public void setOwner(Person owner) {
if (owner == null) throw new ValidationException("Поле owner не может быть null");
this.owner = owner;
}
}

View File

@ -1,7 +1,7 @@
package me.zinch.validator;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ValidationException;
import me.zinch.exceptions.ValidationException;
import java.util.Set;