changed some methods that would return null in place of a message in CommandResult

removed null check when calling CommandResult#getValue()
This commit is contained in:
Egor 2022-05-09 17:22:26 +03:00
parent a74c7496a5
commit dda459c971
13 changed files with 53 additions and 39 deletions

View file

@ -1,2 +1,2 @@
hostname=helios.se.ifmo.ru hostname=localhost
port=1234 port=1234

View file

@ -1,2 +1,2 @@
hostname=s316304@helios.se.ifmo.ru hostname=localhost
port=1234 port=2222

View file

@ -1,8 +1,10 @@
package client.commandline; package client.commandline;
import client.net.UDPClient; import client.net.UDPClient;
import common.commandline.Executables;
import common.commandline.response.CommandResult; import common.commandline.response.CommandResult;
import common.commandline.response.DefaultResponse; import common.commandline.response.DefaultResponse;
import common.commandline.response.Response;
import common.parser.ConnectionProperties; import common.parser.ConnectionProperties;
import common.util.UtilFunctions; import common.util.UtilFunctions;
@ -68,7 +70,7 @@ public final class CommandLineHandler {
System.out.flush(); System.out.flush();
} }
} catch (IOException | InterruptedException e) { } catch (IOException | InterruptedException e) {
e.printStackTrace(); System.err.println("Что-то пошло не так");
} }
} }
@ -92,11 +94,10 @@ public final class CommandLineHandler {
} }
boolean argsValid = command.validate(args); boolean argsValid = command.validate(args);
if (!argsValid) return; if (!argsValid) return;
CommandResult result = command.isClientOnly() || clientMode ? boolean isClient = command.isClientOnly() || clientMode;
command.executeOnClient() : executeOnServer(udp, command); CommandResult result = isClient ? command.executeOnClient() : executeOnServer(udp, command);
PrintStream ps = result.getResponse() == DefaultResponse.OK ? System.out : System.err; PrintStream ps = result.getResponse() == DefaultResponse.OK ? System.out : System.err;
if (result.getValue() == null) ps.println(result.getResponse().getMsg()); ps.println(result.getValue());
else ps.println(result.getValue());
updateHistory(alias); updateHistory(alias);
} }
@ -243,18 +244,21 @@ public final class CommandLineHandler {
args -> { args -> {
String fileName = (String) args[0]; String fileName = (String) args[0];
File file = new File(fileName); File file = new File(fileName);
if (!file.exists() || file.isDirectory()) if (!file.exists() || file.isDirectory()) {
return new CommandResult(null, DefaultResponse.FILE_NOT_FOUND); Response response = DefaultResponse.FILE_NOT_FOUND;
return new CommandResult(response.getMsg(), response);
}
Reader streamReader; Reader streamReader;
try { try {
streamReader = new InputStreamReader(new FileInputStream(file)); streamReader = new InputStreamReader(new FileInputStream(file));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); Response response = DefaultResponse.UNKNOWN;
return new CommandResult(null, DefaultResponse.UNKNOWN); return new CommandResult(response.getMsg(), response);
} }
instance.addNewInput(streamReader, fileName); instance.addNewInput(streamReader, fileName);
return new CommandResult(null, DefaultResponse.OK); Response response = DefaultResponse.OK;
return new CommandResult(response.getMsg(), response);
}); });
} }

View file

@ -45,10 +45,8 @@ public class UDPClient {
public CommandResult send(Executable executable, Object[] args) { public CommandResult send(Executable executable, Object[] args) {
if (!available) return new CommandResult(null, DefaultResponse.HOST_NOT_FOUND); if (!available) return new CommandResult(null, DefaultResponse.HOST_NOT_FOUND);
byte[] buffer; byte[] buffer;
try ( try (ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()) {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream)
) {
objectOutputStream.writeObject(executable); objectOutputStream.writeObject(executable);
objectOutputStream.writeObject(args); objectOutputStream.writeObject(args);
buffer = byteOutputStream.toByteArray(); buffer = byteOutputStream.toByteArray();

View file

@ -91,8 +91,8 @@
<ul> <ul>
<li type="circle">java.lang.Enum&lt;E&gt; (implements java.lang.Comparable&lt;T&gt;, java.io.Serializable) <li type="circle">java.lang.Enum&lt;E&gt; (implements java.lang.Comparable&lt;T&gt;, java.io.Serializable)
<ul> <ul>
<li type="circle">common.data.<a href="../../common/data/Country.html" title="enum in common.data"><span class="typeNameLink">Country</span></a> (implements java.io.Serializable)</li>
<li type="circle">common.data.<a href="../../common/data/Color.html" title="enum in common.data"><span class="typeNameLink">Color</span></a> (implements java.io.Serializable)</li> <li type="circle">common.data.<a href="../../common/data/Color.html" title="enum in common.data"><span class="typeNameLink">Color</span></a> (implements java.io.Serializable)</li>
<li type="circle">common.data.<a href="../../common/data/Country.html" title="enum in common.data"><span class="typeNameLink">Country</span></a> (implements java.io.Serializable)</li>
</ul> </ul>
</li> </li>
</ul> </ul>

Binary file not shown.

View file

@ -5,6 +5,7 @@ import common.collection.PeopleDatabase;
import common.commandline.response.CommandResult; import common.commandline.response.CommandResult;
import common.commandline.response.DefaultResponse; import common.commandline.response.DefaultResponse;
import common.commandline.response.PeopleDatabaseResponse; import common.commandline.response.PeopleDatabaseResponse;
import common.commandline.response.Response;
import common.data.Person; import common.data.Person;
import java.util.Collections; import java.util.Collections;
@ -15,26 +16,30 @@ public enum Executables {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
Person person = (Person) args[1]; Person person = (Person) args[1];
boolean success = peopleDatabase.getCollection().add(person); boolean success = peopleDatabase.getCollection().add(person);
return new CommandResult(null, success ? DefaultResponse.OK : PeopleDatabaseResponse.FAILED_TO_ADD); Response response = success ? DefaultResponse.OK : PeopleDatabaseResponse.FAILED_TO_ADD;
return new CommandResult(response.getMsg(), response);
}), }),
ADD_IF_MAX(args -> { ADD_IF_MAX(args -> {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
Person person = (Person) args[1]; Person person = (Person) args[1];
Person last = peopleDatabase.getCollection().last(); Person last = peopleDatabase.getCollection().last();
if (person.compareTo(last) > 0) return ADD.executable.execute(args); if (person.compareTo(last) > 0) return ADD.executable.execute(args);
return new CommandResult(null, PeopleDatabaseResponse.FAILED_TO_ADD); Response response = PeopleDatabaseResponse.FAILED_TO_ADD;
return new CommandResult(response.getMsg(), response);
}), }),
ADD_IF_MIN(args -> { ADD_IF_MIN(args -> {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
Person person = (Person) args[1]; Person person = (Person) args[1];
Person first = peopleDatabase.getCollection().first(); Person first = peopleDatabase.getCollection().first();
if (person.compareTo(first) < 0) return ADD.executable.execute(args); if (person.compareTo(first) < 0) return ADD.executable.execute(args);
return new CommandResult(null, PeopleDatabaseResponse.FAILED_TO_ADD); Response response = PeopleDatabaseResponse.FAILED_TO_ADD;
return new CommandResult(response.getMsg(), response);
}), }),
CLEAR(args -> { CLEAR(args -> {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
peopleDatabase.getCollection().clear(); peopleDatabase.getCollection().clear();
return new CommandResult(null, DefaultResponse.OK); Response response = DefaultResponse.OK;
return new CommandResult(response.getMsg(), response);
}), }),
FILTER_CONTAINS_NAME(args -> { FILTER_CONTAINS_NAME(args -> {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
@ -64,13 +69,15 @@ public enum Executables {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
long id = (long) args[1]; long id = (long) args[1];
boolean success = peopleDatabase.getCollection().removeIf(p -> p.getId().equals(id)); boolean success = peopleDatabase.getCollection().removeIf(p -> p.getId().equals(id));
return new CommandResult(null, success ? DefaultResponse.OK : PeopleDatabaseResponse.ELEMENT_NOT_FOUND); Response response = success ? DefaultResponse.OK : PeopleDatabaseResponse.ELEMENT_NOT_FOUND;
return new CommandResult(response.getMsg(), response);
}), }),
SAVE(args -> { SAVE(args -> {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
try { try {
peopleDatabase.save(); peopleDatabase.save();
return new CommandResult(null, DefaultResponse.OK); Response response = DefaultResponse.OK;
return new CommandResult(response.getMsg(), response);
} catch (Database.DatabaseSaveFailedException e) { } catch (Database.DatabaseSaveFailedException e) {
return new CommandResult(e.getMessage(), PeopleDatabaseResponse.SAVE_FAILED); return new CommandResult(e.getMessage(), PeopleDatabaseResponse.SAVE_FAILED);
} }
@ -83,11 +90,11 @@ public enum Executables {
}), }),
SUM_OF_HEIGHT(args -> { SUM_OF_HEIGHT(args -> {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
int sum = peopleDatabase.getCollection() String sum = "Сумма ростов всех людей в коллекции - " + peopleDatabase.getCollection()
.stream() .stream()
.mapToInt(p -> p.getHeight() == null ? 0 : p.getHeight()) .mapToInt(p -> p.getHeight() == null ? 0 : p.getHeight())
.sum(); .sum();
return new CommandResult("Сумма ростов всех людей в коллекции - " + sum, DefaultResponse.OK); return new CommandResult(sum, DefaultResponse.OK);
}), }),
UPDATE(args -> { UPDATE(args -> {
PeopleDatabase peopleDatabase = (PeopleDatabase) args[0]; PeopleDatabase peopleDatabase = (PeopleDatabase) args[0];
@ -97,7 +104,8 @@ public enum Executables {
.stream() .stream()
.filter(p -> p.getId().equals(id)) .filter(p -> p.getId().equals(id))
.findFirst(); .findFirst();
if (!optionalPerson.isPresent()) return new CommandResult(null, PeopleDatabaseResponse.ELEMENT_NOT_FOUND); Response response = PeopleDatabaseResponse.ELEMENT_NOT_FOUND;
if (!optionalPerson.isPresent()) return new CommandResult(response.getMsg(), response);
Person oldPerson = optionalPerson.get(); Person oldPerson = optionalPerson.get();
CommandResult result = REMOVE_BY_ID.executable.execute(new Object[]{ peopleDatabase, id }); CommandResult result = REMOVE_BY_ID.executable.execute(new Object[]{ peopleDatabase, id });
if (result.getResponse() != DefaultResponse.OK) return result; if (result.getResponse() != DefaultResponse.OK) return result;

View file

@ -1,2 +1,2 @@
hostname=localhost hostname=s316304@helios.se.ifmo.ru
port=1234 port=1234

View file

@ -2,8 +2,10 @@ package server.net;
import common.collection.PeopleDatabase; import common.collection.PeopleDatabase;
import common.commandline.Executable; import common.commandline.Executable;
import common.commandline.Executables;
import common.commandline.response.CommandResult; import common.commandline.response.CommandResult;
import common.commandline.response.DefaultResponse; import common.commandline.response.DefaultResponse;
import common.commandline.response.Response;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
@ -51,10 +53,8 @@ public class UDPServer {
public void send(CommandResult result, InetAddress address, int port) { public void send(CommandResult result, InetAddress address, int port) {
byte[] buffer; byte[] buffer;
try ( try (ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()) {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream)
) {
objectOutputStream.writeObject(result); objectOutputStream.writeObject(result);
buffer = byteOutputStream.toByteArray(); buffer = byteOutputStream.toByteArray();
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port); DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port);
@ -80,17 +80,21 @@ public class UDPServer {
if (args[0] == null) args[0] = peopleDatabase; if (args[0] == null) args[0] = peopleDatabase;
result = command.execute(args); result = command.execute(args);
} catch (IOException e) { } catch (IOException e) {
logger.info("Не удалось преобразовать полученные данные, данные были повреждены во время передачи"); logger.severe("Не удалось преобразовать полученные данные, данные были повреждены во время передачи");
result = new CommandResult(null, DefaultResponse.SERVER_ERROR); Response response = DefaultResponse.SERVER_ERROR;
result = new CommandResult(response.getMsg(), response);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
logger.info("Не удалось преобразовать полученные данные, классов полученных объектов не существует"); logger.severe("Не удалось преобразовать полученные данные, классов полученных объектов не существует");
result = new CommandResult(null, DefaultResponse.CLASS_NOT_FOUND); Response response = DefaultResponse.CLASS_NOT_FOUND;
result = new CommandResult(response.getMsg(), response);
} catch (ClassCastException e) { } catch (ClassCastException e) {
logger.info("Не удалось преобразовать полученные данные, ожидались объекты другого типа"); logger.severe("Не удалось преобразовать полученные данные, ожидались объекты другого типа");
result = new CommandResult(null, DefaultResponse.TYPE_ERROR); Response response = DefaultResponse.TYPE_ERROR;
result = new CommandResult(response.getMsg(), response);
} }
logger.info("Команда выполнена, отправляем результат клиенту..."); logger.info("Команда выполнена, сохраняем результат и отправляем результат клиенту...");
Executables.SAVE.getExecutable().execute(new Object[]{ peopleDatabase });
send(result, request.getAddress(), request.getPort()); send(result, request.getAddress(), request.getPort());
} }
} }