-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrders.java
More file actions
238 lines (217 loc) · 9.85 KB
/
Copy pathOrders.java
File metadata and controls
238 lines (217 loc) · 9.85 KB
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
import com.google.gson.Gson;
import java.io.*;
import java.net.DatagramPacket;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;
import com.google.gson.reflect.TypeToken;
import com.google.gson.JsonSyntaxException;
public class Orders {
public static String lastPath = new String("");
public static String lastImportedCollection = new String("");
public static Date date = new Date();
public static Type type = new TypeToken<ConcurrentHashMap<String, Human>>(){}.getType();
static Gson gson = new Gson();
static byte[] buffer = new byte[1000000000];
static String sout = new String("");
/****
* Перебирает коллекцию и показвает информацию о каждом элементе
* @param collection
*/
public static void show (ConcurrentHashMap<String, Human> collection, DatagramPacket request){
sout="";
collection.entrySet().stream().forEach(o -> sout = sout.concat("Key: " + o.getKey() + " - " + o.getValue().toString() + "\n"));
/*for(ConcurrentHashMap.Entry<String, Human> item : collection.entrySet()){
Object h = item.getValue();
sout = sout.concat("Key: " + item.getKey() + " - " + h.toString() + "\n");
}*/
send(sout, request);
}
/**
* Добавляет элемент в коллекцию
* @param collection
* @param order Значения элемента в json
* @return collection Возвращает коллекцию с добавленным элементом
*/
public static synchronized ConcurrentHashMap<String, Human> insert (ConcurrentHashMap<String, Human> collection, String order, DatagramPacket request){
sout="";
String[] splitedLine = order.split("[}]\\s*", 2);
splitedLine[0] = splitedLine[0].concat("}");
System.out.println(splitedLine[0] + " and " + splitedLine[1]);
try {
splitedLine[0] = gson.fromJson(splitedLine[0],Key.class).toString();
if (splitedLine[0] == null){
throw new JsonSyntaxException("");
}
Human h = gson.fromJson(splitedLine[1], Human.class);
h.setDate();
collection.put(splitedLine[0], h);
sout = "В коллекцию успешно добавлен новый элемент.";
}
catch(JsonSyntaxException mes){
sout = "Неверный формат данных";
}
send(sout, request);
return collection;
}
/********
* Выходит из программы и сохраняет коллекцию в файл
* @param collection
* @param path
*/
public static void exit(ConcurrentHashMap<String, Human> collection, String path, DatagramPacket request){
sout="";
try {
String JSON = gson.toJson(collection);
FileWriter writer = new FileWriter(path);
writer.write(JSON);
writer.close();
sout = "Файл успешно сохранен";
}
catch(IOException ex){
sout =ex.getMessage();
}
catch (SecurityException mes) {
sout = mes.getMessage();
}
catch(JsonSyntaxException mes){
sout = "Неверный формат данных";
}
send(sout,request);
}
/***
* Выводит информацию о коллекции
* @param collection
*/
public static void info(ConcurrentHashMap<String, Human> collection, DatagramPacket request){
sout="";
String sout = new String("Коллкция имеет тип ConcurrentHashMap и содержит в себе объекты типа Human \n" +
"Инициализирована " + date + "\n" +
"Содержит в себе " + collection.size() + " элементов");
send(sout, request);
}
/***
*
* @param path
* @return перезагруженную коллекцию
*/
public static synchronized ConcurrentHashMap<String, Human> load(String path) {
sout="";
ConcurrentHashMap<String, Human> collection = new ConcurrentHashMap<>();
try {
File importedFile = new File(path);
if (!(importedFile.isFile())) throw new FileNotFoundException("Путь не указывает на файл.");
if (!(importedFile.exists()))
throw new FileNotFoundException("Файла по указанному пути не существует.");
if (!(importedFile.canRead())) throw new SecurityException("Данный файл не может быть прочитан.");
Scanner importedFileText = new Scanner(importedFile);
String importedCollectionText = new String();
while (importedFileText.hasNextLine()) {
importedCollectionText = importedCollectionText.concat(importedFileText.nextLine());
}
importedFileText.close();
collection = gson.fromJson(importedCollectionText, type);
} catch (FileNotFoundException mes) {
System.out.println(mes);
} catch (SecurityException mes) {
System.out.println(mes);
}
catch(JsonSyntaxException mes){
System.out.println("Неверный формат данных");
}
return collection;
}
/*****
*
* @param collection
* @return Возвращает коллекцию, импортированную из файла
*/
public static synchronized ConcurrentHashMap<String, Human> importCollection(ConcurrentHashMap<String, Human> collection, String importedCollectionText, DatagramPacket request) {
try {
collection = gson.fromJson(importedCollectionText, type);
sout = "Коллекция успешно импортирована";
lastImportedCollection = importedCollectionText;
}
catch(JsonSyntaxException mes){
sout = "Неверный формат данных";
}
send(sout, request);
return collection;
}
public static ConcurrentHashMap<String, Human> importCollection(ConcurrentHashMap<String, Human> collection, String path) {
try {
File importedFile = new File(path);
if (!(importedFile.canRead())) throw new SecurityException("Данный файл не может быть прочитан.");
//date = new Date(importedFile.lastModified());
Scanner importedFileText = new Scanner(System.in);
importedFileText = new Scanner(importedFile);
String importedCollectionText = new String();
while (importedFileText.hasNextLine()) {
importedCollectionText = importedCollectionText.concat(importedFileText.nextLine());
}
importedFileText.close();
collection = gson.fromJson(importedCollectionText, type);
System.out.println("Коллекция успешно импортирована");
lastPath = path;
} catch (FileNotFoundException mes) {
System.out.println(mes);
} catch (SecurityException mes) {
System.out.println(mes);
}
catch(JsonSyntaxException mes){
System.out.println("Неверный формат данных");
}
return collection;
}
/****
* Удаляет элемент из коллекциюю по ключу
* @param collection
* @param value
* @return Коллекцию, без удаленного элемента
*/
public static synchronized ConcurrentHashMap<String, Human> removeFromCollection(ConcurrentHashMap<String, Human> collection, String value, DatagramPacket request){
try {
final String valueFinal = gson.fromJson(value, Key.class).toString();
if (collection.containsKey(valueFinal)) {
collection.remove(value);
sout = "Элемент успешно удален";
} else {
sout = "Нет элемента с таким ключом";
}
}
catch(JsonSyntaxException mes){
sout = "Неверный формат данных";
}
send(sout, request);
return collection;
}
/*****
* Удаляет все элементы, у которых ключ превышает параметр value
* @param collection
* @param value
* @return collection
*/
public static synchronized ConcurrentHashMap<String, Human> removeGreaterCollection(ConcurrentHashMap<String, Human> collection, String value){
try {
final String valueFinal = gson.fromJson(value, Key.class).toString();
collection.entrySet().removeIf(o -> valueFinal.compareTo(o.getKey()) < 0);
}
catch(JsonSyntaxException mes){
sout = "Неверный формат данных";
}
return collection;
}
public static void send(String mes, DatagramPacket request){
buffer = mes.getBytes();
DatagramPacket response = new DatagramPacket(buffer, buffer.length, request.getAddress(), request.getPort());
try{
Server.socket.send(response);
}
catch (IOException o){
System.out.println(o);
}
}
}