PROG_LAB5-7/src/main/java/me/zinch/commands/Add.java

32 lines
1.1 KiB
Java

package me.zinch.commands;
import me.zinch.console.Console;
import me.zinch.exceptions.CommandActionException;
import me.zinch.exceptions.ValidationException;
import me.zinch.validator.Validators;
import me.zinch.wrapper.ProductCollection;
import java.util.regex.Pattern;
/**
* The Add class represents a command to add a new element to a collection.
* It extends the Command class.
*/
public class Add extends Command {
public Add() {
super("add {element}", "добавить новый элемент в коллекцию", Pattern.compile("^add"));
}
@Override
public String action(ProductCollection productCollection) throws CommandActionException {
var productDTO = Console.readProductDTO();
try {
Validators.validateObject(productDTO).throwIfNotValid();
var product = productCollection.addProduct(productDTO);
return String.format("Продукт %s был добавлен под id %d", product.getName(), product.getId());
} catch (ValidationException e) {
throw new CommandActionException(String.format("Произошла ошибка при добавлении%n%s", e.getMessage()));
}
}
}