Skip to content

Commit

Permalink
chore: restored arguments validation
Browse files Browse the repository at this point in the history
Signed-off-by: Zerumi <46845708+Zerumi@users.noreply.github.com>
  • Loading branch information
Zerumi committed Apr 10, 2023
1 parent 7bfca2e commit a3029b1
Show file tree
Hide file tree
Showing 18 changed files with 167 additions and 355 deletions.
355 changes: 61 additions & 294 deletions .idea/workspace.xml

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion client/src/commandManager/CommandManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import exceptions.CommandInterruptedException;
import exceptions.UnknownCommandException;
import exceptions.WrongAmountOfArgumentsException;
import main.Utilities;
import models.Route;
import models.handlers.ModuleHandler;
import models.handlers.nonUserMode.RouteNonCLIHandler;
Expand Down Expand Up @@ -85,7 +86,10 @@ public LinkedHashMap<String, BaseCommand> getCommands() {
*/
public void executeCommand(String[] args) {
try {
Optional.ofNullable(commands.get(args[0])).orElseThrow(() -> new UnknownCommandException("Указанная команда не была обнаружена")).execute(args);
BaseCommand command = Optional.ofNullable(commands.get(args[0])).orElseThrow(() -> new UnknownCommandException("Указанная команда не была обнаружена"));
if (command.getArgCount() > 0)
Utilities.checkArgumentsOrThrow(args.length, command.getArgCount());
command.execute(args);
} catch (IllegalArgumentException | NullPointerException e) {
myLogger.log(Level.SEVERE, "Выполнение команды пропущено из-за неправильных предоставленных аргументов! (" + e.getMessage() + ")");
throw new CommandInterruptedException(e);
Expand Down
10 changes: 7 additions & 3 deletions client/src/commandManager/commands/ExecuteScriptCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,16 @@ private boolean checkRecursion(Path path, ArrayDeque<Path> stack) throws IOExcep
String str = Files.readString(path);
Pattern pattern = Pattern.compile("execute_script .*");
var patternMatcher = pattern.matcher(str);
while (patternMatcher.find())
{
while (patternMatcher.find()) {
Path newPath = Path.of(patternMatcher.group().split(" ")[1]);
if(checkRecursion(newPath, stack)) return true;
if (checkRecursion(newPath, stack)) return true;
}
stack.removeLast();
return false;
}

@Override
public int getArgCount() {
return 1;
}
}
22 changes: 0 additions & 22 deletions client/src/main/Utilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,6 @@
import java.util.Scanner;

public class Utilities {
public static boolean isNotNumeric(String str) {
return !str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}

public static Long handleUserInputID(String input) {
if (Utilities.isNotNumeric(input)) {
System.out.println("Provided argument id: \"" + input + "\" is not a number! Try again.");
return null;
} else if (input.contains(".")) {
System.out.println("ID field cannot accept decimal values. Try again.");
return null;
}

Long id = null;
try {
id = Long.valueOf(input);
} catch (NumberFormatException e) {
System.out.println("Provided argument: \"" + input + "\" is too large for ID field. Try again.");
}
return id;
}

public static void checkArgumentsOrThrow(int provided, int expected) throws WrongAmountOfArgumentsException {
if (provided - 1 != expected)
throw new WrongAmountOfArgumentsException("Provided " + (provided - 1) + " arguments, expected " + expected);
Expand Down
3 changes: 3 additions & 0 deletions server/src/commandManager/CommandManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ public void executeCommand(CommandClientRequest command) {
} catch (IllegalArgumentException | NullPointerException e) {
response = new CommandStatusResponse("Выполнение команды пропущено из-за неправильных предоставленных аргументов! (" + e.getMessage() + ")", -90);
logger.fatal(response.getResponse(), e);
} catch (IndexOutOfBoundsException e) {
response = new CommandStatusResponse("В команде предоставлено неправильное количество аргументов. Возможно, вам нужно обновить клиент", -91);
logger.fatal(response.getResponse(), e);
} catch (Exception e) {
response = new CommandStatusResponse("В командном менеджере произошла непредвиденная ошибка!", -92);
logger.fatal(response.getResponse(), e);
Expand Down
14 changes: 0 additions & 14 deletions server/src/commandManager/CommandMode.java

This file was deleted.

6 changes: 2 additions & 4 deletions server/src/commandManager/commands/AddIfMaxCommand.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package commandManager.commands;

import dataTransferObjects.models.RouteDTO;
import models.Route;
import models.comparators.RouteDistanceComparator;
import models.handlers.CollectionHandler;
import models.handlers.RoutesHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import requestLogic.dtoMappers.RouteDTOMapper;
import responseLogic.responses.CommandStatusResponse;

import java.util.HashSet;
Expand Down Expand Up @@ -39,14 +37,14 @@ public String getArgs() {
}

@Override
public void execute(String[] args) throws ClassNotFoundException {
public void execute(String[] args) {
CollectionHandler<HashSet<Route>, Route> collectionHandler = RoutesHandler.getInstance();

if (obj.compareTo(collectionHandler.getMax(new RouteDistanceComparator())) > 0) {
collectionHandler.addElementToCollection(obj);
response = CommandStatusResponse.ofString("Element added!");
} else {
response = CommandStatusResponse.ofString("Element not added: it's not greater than max value.");
response = new CommandStatusResponse("Element not added: it's not greater than max value.", 3);
}

logger.info(response.getResponse());
Expand Down
6 changes: 2 additions & 4 deletions server/src/commandManager/commands/AddIfMinCommand.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package commandManager.commands;

import dataTransferObjects.models.RouteDTO;
import models.Route;
import models.comparators.RouteDistanceComparator;
import models.handlers.CollectionHandler;
import models.handlers.RoutesHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import requestLogic.dtoMappers.RouteDTOMapper;
import responseLogic.responses.CommandStatusResponse;

import java.util.HashSet;
Expand Down Expand Up @@ -39,14 +37,14 @@ public String getArgs() {
}

@Override
public void execute(String[] args) throws ClassNotFoundException {
public void execute(String[] args) {
CollectionHandler<HashSet<Route>, Route> collectionHandler = RoutesHandler.getInstance();

if (obj.compareTo(collectionHandler.getMin(new RouteDistanceComparator())) < 0) {
collectionHandler.addElementToCollection(obj);
response = CommandStatusResponse.ofString("Element added!");
} else {
response = CommandStatusResponse.ofString("Element not added: it's not lower than min value.");
response = new CommandStatusResponse("Element not added: it's not lower than min value.", 3);
}

logger.info(response.getResponse());
Expand Down
7 changes: 7 additions & 0 deletions server/src/commandManager/commands/ArgumentConsumer.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package commandManager.commands;

/**
* Provides Argument Consumer
*
* @param <T> Argument param
* @author zerumi
* @since 2.1
*/
public interface ArgumentConsumer<T> {
void setObj(T obj);
}
6 changes: 2 additions & 4 deletions server/src/commandManager/commands/BaseCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,14 @@

import responseLogic.responses.CommandStatusResponse;

import java.io.Serializable;

/**
* Base interface for command implementation. You should implement it before applying command in CommandManager
*
* @author Zerumi
* @see commandManager.CommandManager
* @since 1.0
*/
public interface BaseCommand extends Serializable {
public interface BaseCommand {
/**
* Base method for show command name
*
Expand Down Expand Up @@ -41,7 +39,7 @@ default String getArgs() {
* @param args full array of entered line.
* @throws IllegalArgumentException when command can't understand given arguments
*/
void execute(String[] args) throws IllegalArgumentException, ClassNotFoundException;
void execute(String[] args) throws IllegalArgumentException;

/**
* Base method for get command Output
Expand Down
4 changes: 1 addition & 3 deletions server/src/commandManager/commands/RemoveGreaterCommand.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package commandManager.commands;

import dataTransferObjects.models.RouteDTO;
import models.Route;
import models.comparators.RouteDistanceComparator;
import models.handlers.CollectionHandler;
import models.handlers.RoutesHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import requestLogic.dtoMappers.RouteDTOMapper;
import responseLogic.responses.CommandStatusResponse;

import java.util.HashSet;
Expand Down Expand Up @@ -39,7 +37,7 @@ public String getArgs() {
}

@Override
public void execute(String[] args) throws ClassNotFoundException {
public void execute(String[] args) {
RouteDistanceComparator comparator = new RouteDistanceComparator();

CollectionHandler<HashSet<Route>, Route> collectionHandler = RoutesHandler.getInstance();
Expand Down
4 changes: 1 addition & 3 deletions server/src/commandManager/commands/UpdateCommand.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package commandManager.commands;

import dataTransferObjects.models.RouteDTO;
import models.Route;
import models.handlers.CollectionHandler;
import models.handlers.RoutesHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import requestLogic.dtoMappers.RouteDTOMapper;
import responseLogic.responses.CommandStatusResponse;

import java.util.HashSet;
Expand Down Expand Up @@ -39,7 +37,7 @@ public String getArgs() {
}

@Override
public void execute(String[] args) throws ClassNotFoundException {
public void execute(String[] args) {
CollectionHandler<HashSet<Route>, Route> collectionHandler = RoutesHandler.getInstance();

Long finalId = Long.valueOf(args[1]);
Expand Down
4 changes: 4 additions & 0 deletions shared/src/commandLogic/commands/BaseCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ public interface BaseCommand {

String getName();

default int getArgCount() {
return 0;
}

/**
* Base method for command executing.
*
Expand Down
12 changes: 12 additions & 0 deletions shared/src/commandLogic/commands/argCommands/UpdateCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import commandLogic.commandReceiverLogic.ReceiverType;
import commandLogic.commands.BaseCommand;
import main.LibUtilities;

/**
* Updates element by its ID.
Expand All @@ -20,4 +21,15 @@ public UpdateCommand(ReceiverType type) {
public String getName() {
return "update";
}

@Override
public int getArgCount() {
return 1;
}

@Override
public void execute(String[] args) throws Exception {
if (LibUtilities.handleUserInputID(args[1]) != null)
super.execute(args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@


import commandLogic.commands.BaseCommand;
import main.LibUtilities;

/**
* Shows count of the elements greater than distance value.
Expand All @@ -14,4 +15,23 @@ public class CountGreaterThanDistanceCommand extends NoArgumentCommand implement
public String getName() {
return "count_greater_than_distance";
}

@Override
public int getArgCount() {
return 1;
}

@Override
public void execute(String[] args) throws Exception {

if (LibUtilities.isNotNumeric(args[1])) {
System.out.println("Provided argument \"" + args[1] + "\" is not a number! Try again.");
return;
} else if (args[1].contains(",")) {
System.out.println("Distance field cannot accept decimal values. Try again");
return;
}

super.execute(args);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package commandLogic.commands.noArgCommands;

import commandLogic.commands.BaseCommand;
import main.LibUtilities;

/**
* Removes element from collection by id.
Expand All @@ -15,7 +16,13 @@ public String getName() {
}

@Override
public void execute(String[] args) {
// TODO: validate id?
public int getArgCount() {
return 1;
}

@Override
public void execute(String[] args) throws Exception {
if (LibUtilities.handleUserInputID(args[1]) != null)
super.execute(args);
}
}
25 changes: 25 additions & 0 deletions shared/src/main/LibUtilities.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main;

public class LibUtilities {
public static boolean isNotNumeric(String str) {
return !str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}

public static Long handleUserInputID(String input) {
if (LibUtilities.isNotNumeric(input)) {
System.out.println("Provided argument id: \"" + input + "\" is not a number! Try again.");
return null;
} else if (input.contains(".")) {
System.out.println("ID field cannot accept decimal values. Try again.");
return null;
}

Long id = null;
try {
id = Long.valueOf(input);
} catch (NumberFormatException e) {
System.out.println("Provided argument: \"" + input + "\" is too large for ID field. Try again.");
}
return id;
}
}
7 changes: 6 additions & 1 deletion shared/src/main/Main.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package main;

public class Main {

public static void main(String[] args) {
System.out.println("""
Однажды Вася спросил у своего старшего брата-сеньора Пети:
"Петя, зачем вообще нам нужно запускать общую библиотеку классов?"
На что Петя ответил: "Братиш, для того, чтобы практик на защите прочитал этот текст.\"""");
}
}

1 comment on commit a3029b1

@Zerumi
Copy link
Owner Author

@Zerumi Zerumi commented on a3029b1 Apr 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo

  • update pre-validation

Please sign in to comment.