-
Notifications
You must be signed in to change notification settings - Fork 0
/
src.java
1644 lines (1296 loc) · 45 KB
/
src.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Coordinates.java
package item;
import java.io.Serializable;
/**
*Class which represents coordinates
*/
public class Coordinates implements Cloneable, Serializable {
private long x; //Поле не может быть null
private long y; //Максимальное значение поля: 254
public Coordinates(long x, long y) {
this.x = x;
this.y = y;
}
public Coordinates clone() throws CloneNotSupportedException {
Coordinates cloned = (Coordinates) super.clone();
return cloned;
}
@Override
public String toString() {
return "{" +
"\n\t\t\"x\":" + x +
", \n\t\t\"y\":" + y +
"\n\t}";
}
}
MeleeWeapon.java
package item;
import java.io.Serializable;
/**
* Class which represents types of melee weapons
*/
public enum MeleeWeapon implements Serializable {
CHAIN_SWORD,
CHAIN_AXE,
POWER_BLADE;
}
SpaceMarine.java
package item;
import utils.ValidateInput;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Scanner;
/**
* Class that represents space marine - element of collection
*/
public class SpaceMarine implements Cloneable, Comparable<SpaceMarine>, Serializable {
private int id; //Значение поля должно быть больше 0, Значение этого поля должно быть уникальным, Значение этого поля должно генерироваться автоматически
private String name; //Поле не может быть null, Строка не может быть пустой
private Coordinates coordinates; //Поле не может быть null
private static int curId = 0;
public LocalDateTime getCreationDate() {
return creationDate;
}
private java.time.LocalDateTime creationDate; //Поле не может быть null, Значение этого поля должно генерироваться автоматически
private float health; //Значение поля должно быть больше 0
private boolean loyal;
private Weapon weaponType = null; //Поле может быть null
private MeleeWeapon meleeWeapon = null; //Поле может быть null
private Chapter chapter; //Поле не может быть null
public SpaceMarine(String name, Coordinates coordinates, float health, boolean loyal, Weapon weaponType,
MeleeWeapon meleeWeapon, Chapter chapter) {
this();
this.id = ++curId;
this.name = name;
this.coordinates = coordinates;
this.health = health;
this.loyal = loyal;
this.weaponType = weaponType;
this.meleeWeapon = meleeWeapon;
this.chapter = chapter;
}
public SpaceMarine(int id, String name, Coordinates coordinates, java.time.LocalDateTime creationDate, float health,
boolean loyal, Weapon weaponType, MeleeWeapon meleeWeapon, Chapter chapter) {
this(name, coordinates, health, loyal, weaponType, meleeWeapon, chapter);
this.id = id;
this.creationDate = creationDate;
}
public SpaceMarine() {
creationDate = LocalDateTime.now();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getHealth() {
return health;
}
public Weapon getWeaponType() {
return weaponType;
}
public Chapter getChapter() {
return chapter;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpaceMarine that = (SpaceMarine) o;
return Float.compare(that.health, health) == 0 &&
loyal == that.loyal &&
Objects.equals(name, that.name) &&
Objects.equals(coordinates, that.coordinates) &&
Objects.equals(creationDate, that.creationDate) &&
weaponType == that.weaponType &&
meleeWeapon == that.meleeWeapon &&
Objects.equals(chapter, that.chapter);
}
@Override
public int hashCode() {
return Objects.hash(coordinates, creationDate, health, loyal, weaponType, meleeWeapon, chapter);
}
/**
* Scans element from input stream with invitation to enter
* @param sc
*/
public void scan(Scanner sc) {
ValidateInput in = new ValidateInput(sc);
name = sc.next();
id = ++curId;
long x = in.validateLong();
long y = in.validateLong();
coordinates = new Coordinates(x, y);
health = in.validateFloat();
loyal = in.validateBool();
weaponType = in.validateWeapon();
meleeWeapon = in.validateMeleeWeapon();
String nameChapter = sc.next();
int count = in.validatePositiveInt();
String nameWorld = sc.next();
chapter = new Chapter(nameChapter, count, nameWorld);
}
@Override
public String toString() {
return "\"SpaceMarine\":{" +
"\n\t\"id\":" + id +
", \n\t\"name\":\"" + name + '\"' +
", \n\t\"coordinates\":" + coordinates +
", \n\t\"creationDate\":\"" + creationDate +
"\", \n\t\"health\":" + health +
", \n\t\"loyal\":" + loyal +
", \n\t\"weaponType\":\"" + weaponType +
"\", \n\t\"meleeWeapon\":\"" + meleeWeapon +
"\", \n\t\"chapter\":" + chapter +
'}';
}
@Override
public int compareTo(SpaceMarine spaceMarine) {
return name.compareTo(spaceMarine.name);
}
}
Chapter.java
package item;
import java.io.Serializable;
/**
* SpaceMarine.Chapter is a simple class which represents chapter
*/
public class Chapter implements Comparable<Chapter>, Serializable {
private String name; //Поле не может быть null, Строка не может быть пустой
private int marinesCount; //Значение поля должно быть больше 0, Максимальное значение поля: 1000
private String world; //Поле не может быть null
public Chapter(String name, int marinesCount, String world) {
this.name = name;
this.marinesCount = marinesCount;
this.world = world;
}
@Override
public String toString() {
return "{" +
"\n\t\t\"name\":\"" + name +
"\", \n\t\t\"marinesCount\":" + marinesCount +
", \n\t\t\"world\":\"" + world +
"\"\n\t}\n";
}
@Override
public int compareTo(Chapter chapter) {
if (world.equals(chapter.world)) {
return name.compareTo(chapter.name);
} else {
return world.compareTo(chapter.world);
}
}
}
Weapon.java
package item;
import java.io.Serializable;
/**
* Class which represents weapon types
*/
public enum Weapon implements Serializable {
PLASMA_GUN,
COMBI_PLASMA_GUN,
FLAMER,
INFERNO_PISTOL,
HEAVY_FLAMER;
}
ServerConsoleThread.java
package server;
import commands.CommandManager;
import java.util.Scanner;
public class ServerConsoleThread extends Thread {
private Scanner sc;
private CommandManager commandManager;
public ServerConsoleThread(CommandManager commandManager) {
this.commandManager = commandManager;
sc = new Scanner(System.in);
}
public void run() {
while (true) {
String msg = sc.nextLine();
if (msg.equals("exit")) {
System.out.println("Saving..");
commandManager.getCommand("save").execute();
System.out.println("Exiting...");
System.exit(0);
} else if (msg.equals("save")) {
System.out.println("Saving...");
commandManager.getCommand("save").execute();
} else {
System.out.println("There is no such command");
}
}
}
}
Server.java
package server;
import commands.Command;
import commands.CommandManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.List;
public class Server {
private int port;
private DatagramSocket socket;
private CommandManager commandManager;
private List<String> history;
private InetAddress clientAddr;
private int clientPort;
public Server(int port, CommandManager commandManager, List<String> history) {
this.port = port;
this.commandManager = commandManager;
this.history = history;
}
public void execute() {
try {
socket = new DatagramSocket(port);
System.out.println("Server is listening on port: " + port);
new ServerConsoleThread(commandManager).start();
while (true) {
receive();
}
} catch (IOException e) {
System.out.println("Error in the server: " + e.getMessage());
e.printStackTrace();
}
}
private void receive() {
byte[] input = new byte[10000];
DatagramPacket inputPacket = new DatagramPacket(input, input.length);
try {
socket.receive(inputPacket);
} catch (IOException e) {
System.out.println("Error in the server receive: " + e.getMessage());
e.printStackTrace();
}
clientAddr = inputPacket.getAddress();
clientPort = inputPacket.getPort();
process(input);
}
private void process(byte[] input) {
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(input);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Command cmd = (Command) objectInputStream.readObject();
cmd = commandManager.getCommand(cmd.getName());
cmd.setParameters(objectInputStream);
System.out.println("Request has been received: " + cmd.getName());
byte[] output = new byte[10000];
String answer = cmd.execute();
ByteBuffer buffer = ByteBuffer.wrap(answer.getBytes("UTF-8"));
output = answer.getBytes("UTF-8");
history.add(cmd.getName());
// send(output);
send(buffer.array());
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error in the server process: " + e.getMessage());
e.printStackTrace();
}
}
private void send(byte[] output) {
try {
DatagramPacket outputPacket = new DatagramPacket(output, output.length, clientAddr, clientPort);
// System.out.println("Reply has been sent: \n" + new String(output).trim());
socket.send(outputPacket);
System.out.println("Reply has been sent");
} catch (IOException e) {
System.out.println("Error in the server send: " + e.getMessage());
e.printStackTrace();
}
}
}
WorkWithJson.java
package utils;
import item.*;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.*;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
/**
* A simple json scanner
*/
public class WorkWithJson {
File file;
InputStreamReader isr;
String str;
LinkedHashMap<Integer, SpaceMarine> lhm;
public WorkWithJson(File file) throws IOException {
this.file = file;
isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
char[] data = new char[(int) file.length()];
isr.read(data);
isr.close();
str = new String(data);
lhm = new LinkedHashMap<>();
makeMapFromJsonString(str);
}
public LinkedHashMap<Integer, SpaceMarine> getLhm() {
return lhm;
}
private void makeMapFromJsonString(String str) {
if (!str.isEmpty()) {
try {
JSONObject jsonObject = new JSONObject(str);
JSONArray mapArray = jsonObject.getJSONArray("array");
for (int i = 0; i < mapArray.length(); i++) {
String jsonSMString = mapArray.get(i).toString();
JSONObject jsonKeyValue = new JSONObject(jsonSMString);
int key = jsonKeyValue.getInt("key");
jsonSMString = jsonKeyValue.get("SpaceMarine").toString();
JSONObject jsonSM = new JSONObject(jsonSMString);
int id = jsonSM.getInt("id");
String name = jsonSM.getString("name");
String jsonSMCoordinatesString = jsonSM.get("coordinates").toString();
JSONObject jsonCoordinates = new JSONObject(jsonSMCoordinatesString);
int x = jsonCoordinates.getInt("x");
int y = jsonCoordinates.getInt("y");
Coordinates coordinates = new Coordinates(x, y);
java.time.LocalDateTime creationDate = LocalDateTime.parse(jsonSM.get("creationDate").toString());
float health = jsonSM.getFloat("health");
boolean loyal = jsonSM.getBoolean("loyal");
Weapon weaponType = Weapon.valueOf(jsonSM.getString("weaponType"));
MeleeWeapon meleeWeapon = MeleeWeapon.valueOf(jsonSM.getString("meleeWeapon"));
String jsonSMChapterString = jsonSM.get("chapter").toString();
JSONObject jsonChapter = new JSONObject(jsonSMChapterString);
String nameChapter = jsonChapter.getString("name");
int marinesCount = jsonChapter.getInt("marinesCount");
String world = jsonChapter.getString("world");
Chapter chapter = new Chapter(nameChapter, marinesCount, world);
SpaceMarine spaceMarine = new SpaceMarine(id, name, coordinates, creationDate, health, loyal, weaponType, meleeWeapon, chapter);
lhm.put(key, spaceMarine);
}
} catch (Exception e) {
System.out.println("Wrong json file");
System.exit(0);
}
}
}
}
ValidateInput.java
package utils;
import item.MeleeWeapon;
import item.Weapon;
import java.util.Scanner;
public class ValidateInput {
private Scanner sc;
public ValidateInput(Scanner sc) {
this.sc = sc;
}
public int validatePositiveInt() {
int number;
do {
number = validateInt();
} while (number < 0);
return number;
}
public int validateInt() {
while (!sc.hasNextInt()) {
printNotValid(sc);
}
return sc.nextInt();
}
public float validateFloat() {
while (!sc.hasNextFloat()) {
printNotValid(sc);
}
return sc.nextFloat();
}
public long validateLong() {
while (!sc.hasNextLong()) {
printNotValid(sc);
}
return sc.nextLong();
}
public boolean validateBool() {
boolean result = false;
while (sc.hasNext()) {
String s = sc.next();
if (s.equals("true") || s.equals("false")) {
result = Boolean.parseBoolean(s);
break;
}
System.out.printf("\"%s\" is not a valid input.\n", s);
}
return result;
}
public Weapon validateWeapon() {
boolean check = false;
Weapon weapon = null;
do {
String name = sc.next();
for (Weapon value : Weapon.values()) {
if (value.toString().equals(name.toUpperCase())) {
check = true;
weapon = Weapon.valueOf(name.toUpperCase());
return weapon;
}
}
System.out.println("There is no such weapon");
} while (true);
}
public MeleeWeapon validateMeleeWeapon() {
boolean check = false;
MeleeWeapon weapon = null;
do {
String name = sc.next();
for (MeleeWeapon value : MeleeWeapon.values()) {
if (value.toString().equals(name.toUpperCase())) {
check = true;
weapon = MeleeWeapon.valueOf(name.toUpperCase());
return weapon;
}
}
System.out.println("There is no such weapon");
} while (true);
}
private static void printNotValid(Scanner sc) {
String input = sc.next();
System.out.printf("\"%s\" is not a valid input.\n", input);
}
}
CommandPrintFieldAscendingChapter.java
package commands;
import item.SpaceMarine;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;
import java.util.stream.Collectors;
/**
* SpaceMarine.commands.Command that prints the values of the chapter field of all elements in ascending order
*/
public class CommandPrintFieldAscendingChapter extends Command {
Map<Integer, SpaceMarine> lhm;
public CommandPrintFieldAscendingChapter(Map<Integer, SpaceMarine> lhm) {
this();
this.lhm = lhm;
}
public CommandPrintFieldAscendingChapter() {
this.name = "print_field_ascending_chapter";
this.description = "Print the values of the chapter field of all elements in ascending order";
}
@Override
public String execute() {
String s = lhm.values().stream()
.sorted((t1, t2) -> t1.getChapter().compareTo(t2.getChapter()))
.map(t -> t.getChapter().toString() + "\n")
.collect(Collectors.joining());
return s;
}
@Override
public void readParameters(Scanner sc, ObjectOutputStream oos) throws IOException {
}
@Override
public void setParameters(ObjectInputStream ois) throws IOException, ClassNotFoundException {
}
}
CommandManager.java
package commands;
import java.io.Serializable;
import java.util.HashMap;
/**
* SpaceMarine.commands.CommandManager executes a command corresponding to the input
*/
public class CommandManager implements Serializable {
HashMap<String, Command> hm = new HashMap<>();
public void addCommand(String name, Command cmd) {
hm.put(name, cmd);
}
public Command getCommand(String name) {
return hm.get(name);
}
public HashMap<String, Command> getHm() {
return hm;
}
}
CommandExit.java
package commands;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
/**
* Complete the entire program
*/
public class CommandExit extends Command {
public CommandExit() {
this.name = "exit";
this.description = "Terminate the program (without saving to a file)";
}
public String execute() {
System.exit(0);
return "";
}
@Override
public void readParameters(Scanner sc, ObjectOutputStream oos) throws IOException {
}
@Override
public void setParameters(ObjectInputStream ois) throws IOException, ClassNotFoundException {
}
}
CommandCountByWeaponType.java
package commands;
import item.SpaceMarine;
import item.Weapon;
import utils.ValidateInput;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.Scanner;
/**
* SpaceMarine.commands.Command that displays the number of elements whose weaponType field value is equal to the specified
*/
public class CommandCountByWeaponType extends Command {
private Map<Integer, SpaceMarine> lhm;
private Weapon weaponType;
public CommandCountByWeaponType(Map<Integer, SpaceMarine> lhm) {
this();
this.lhm = lhm;
}
public CommandCountByWeaponType() {
this.name = "count_by_weapon_type";
this.description = "Displays the number of elements whose weaponType field value is equal to the specified";
}
@Override
public String execute() {
long ans = lhm.values().stream()
.filter(s -> s.getWeaponType()
.equals(weaponType))
.count();
return (ans + " weapon of type " + weaponType);
}
@Override
public void readParameters(Scanner sc, ObjectOutputStream oos) throws IOException {
ValidateInput vi = new ValidateInput(sc);
weaponType = vi.validateWeapon();
oos.writeObject(weaponType);
}
@Override
public void setParameters(ObjectInputStream ois) throws IOException, ClassNotFoundException {
weaponType = (Weapon) ois.readObject();
}
}
CommandHelp.java
package commands;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* SpaceMarine.commands.Command that shows information about every command that user can use
*/
public class CommandHelp extends Command {
CommandManager commandManager;
public CommandHelp(CommandManager commandManager) {
this();
this.commandManager = commandManager;
}
public CommandHelp() {
this.name = "help";
this.description = "Shows info about every command";
}
@Override
public String execute() {
String result = "The options are:\n";
result += commandManager.getHm().values().stream()
.map(s -> String.format("%-40s%-150s\n", s.getName(), s.getDescription()))
.collect(Collectors.joining());
return result;
}
@Override
public void readParameters(Scanner sc, ObjectOutputStream oos) throws IOException {
oos.writeObject(commandManager);
}
@Override
public void setParameters(ObjectInputStream ois) throws IOException, ClassNotFoundException {
commandManager = (CommandManager) ois.readObject();
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
}
CommandSave.java
package commands;
import item.SpaceMarine;
import java.io.*;
import java.util.Map;
import java.util.Scanner;
/**
* Saves the collection to a json-file
*/
public class CommandSave extends Command {
Map<Integer, SpaceMarine> lhm;
File file;
public CommandSave(Map<Integer, SpaceMarine> lhm, File file) {
this();
this.lhm = lhm;
this.file = file;
}
public CommandSave() {
this.name = "save";
this.description = "Saves the collection to a file";
}
@Override
public String execute() {
PrintWriter pw = null;
try {
pw = new PrintWriter(file);
} catch (FileNotFoundException e) {
return ("File not found\n");
}
pw.flush();
if (!lhm.isEmpty()) {
pw.write("{\"array\":[");
int j = 0;
for (int i : lhm.keySet()) {
pw.write("{\"key\":" + i + "," + lhm.get(i) + "}");
if (j != lhm.size()-1)
pw.write(",\n");
else
pw.write("]}");
j++;
}
}
pw.close();
return "";
}
@Override
public void readParameters(Scanner sc, ObjectOutputStream oos) throws IOException {
}
@Override
public void setParameters(ObjectInputStream ois) throws IOException, ClassNotFoundException {
}
}
Executable.java
package commands;
import java.util.Scanner;
/**
* This interface imposes an execute method on the objects
* of each class that implements it
*/
public interface Executable {
String execute();
}
CommandRemoveLower.java
package commands;
import item.SpaceMarine;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* SpaceMarine.commands.Command which removes from the collection all elements smaller than the specified
*/
public class CommandRemoveLower extends Command {
Map<Integer, SpaceMarine> lhm;
private SpaceMarine spaceMarine;
public CommandRemoveLower(Map<Integer, SpaceMarine> lhm) {
this();
this.lhm = lhm;
}
public CommandRemoveLower() {
this.name = "remove_lower";
this.description = "Removes from the collection all elements smaller than the specified";
}
@Override
public String execute() {
Map<Integer, SpaceMarine> copy = lhm.entrySet().stream()
.filter(s -> s.getValue().compareTo(spaceMarine) >= 0)
.collect(Collectors.toMap((p) -> p.getKey(), (p) -> p.getValue()));
lhm.clear();
lhm.putAll(copy);
return "";
}
@Override
public void readParameters(Scanner sc, ObjectOutputStream oos) throws IOException {
SpaceMarine spaceMarine = new SpaceMarine();
spaceMarine.scan(sc);
oos.writeObject(spaceMarine);
}
@Override
public void setParameters(ObjectInputStream ois) throws IOException, ClassNotFoundException {
spaceMarine = (SpaceMarine) ois.readObject();
}
}
CommandInsert.java
package commands;
import item.SpaceMarine;
import utils.ValidateInput;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.Scanner;
/**
* SpaceMarine.commands.Command adding a new item to the collection
*/
public class CommandInsert extends Command {
private Map<Integer, SpaceMarine> lhm;
private int key;
private SpaceMarine sm;
public CommandInsert(Map<Integer, SpaceMarine> lhm) {
this();
this.lhm = lhm;
}
public CommandInsert() {
this.name = "insert";
this.description = "Add a new item with the given key";
}
@Override
public String execute() {
lhm.put(key, sm);
String result = String.format("Element with key %d has been inserted\n", key);
return result;
}
@Override
public void readParameters(Scanner sc, ObjectOutputStream oos) throws IOException {
// System.out.print("Input a key: ");
ValidateInput in = new ValidateInput(sc);
int key = in.validateInt();
SpaceMarine sm = new SpaceMarine();
sm.scan(sc);
oos.writeObject(key);
oos.writeObject(sm);
}
@Override
public void setParameters(ObjectInputStream ois) throws IOException, ClassNotFoundException {
key = (Integer) ois.readObject();
sm = (SpaceMarine) ois.readObject();
}
}
CommandFilterLessThanHealth.java
package commands;
import item.SpaceMarine;
import utils.ValidateInput;
import java.io.IOException;