-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopaSystem.java
436 lines (409 loc) · 16.7 KB
/
CopaSystem.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
/*
* Copyright (C) 2013 UniCoPA
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package unicopa.copa.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import unicopa.copa.base.ServerInfo;
import unicopa.copa.base.com.exception.APIException;
import unicopa.copa.base.com.request.AbstractRequest;
import unicopa.copa.base.com.request.AbstractResponse;
import unicopa.copa.base.com.request.GetSingleEventRequest;
import unicopa.copa.base.com.exception.InternalErrorException;
import unicopa.copa.base.com.exception.PermissionException;
import unicopa.copa.base.com.exception.RequestNotPracticableException;
import unicopa.copa.base.com.request.AddRoleToUserRequest;
import unicopa.copa.base.com.request.AddSingleEventRequest;
import unicopa.copa.base.com.request.AddSingleEventUpdateRequest;
import unicopa.copa.base.com.request.CancelSingleEventRequest;
import unicopa.copa.base.com.request.DropRoleRequest;
import unicopa.copa.base.com.request.GetAllDeputiesRequest;
import unicopa.copa.base.com.request.GetAllOwnersRequest;
import unicopa.copa.base.com.request.GetAllRightholdersRequest;
import unicopa.copa.base.com.request.GetCategoriesRequest;
import unicopa.copa.base.com.request.GetCurrentSingleEventsRequest;
import unicopa.copa.base.com.request.GetEventGroupRequest;
import unicopa.copa.base.com.request.GetEventGroupsRequest;
import unicopa.copa.base.com.request.GetEventRequest;
import unicopa.copa.base.com.request.GetEventsRequest;
import unicopa.copa.base.com.request.GetMyAppointedUsersRequest;
import unicopa.copa.base.com.request.GetMyEventsRequest;
import unicopa.copa.base.com.request.GetServerInfoRequest;
import unicopa.copa.base.com.request.GetServerStatusNotesRequest;
import unicopa.copa.base.com.request.GetSingleEventUpdatesRequest;
import unicopa.copa.base.com.request.GetSubscribedSingleEventUpdatesRequest;
import unicopa.copa.base.com.request.GetUserDataRequest;
import unicopa.copa.base.com.request.GetUserSettingsRequest;
import unicopa.copa.base.com.request.RemoveRoleFromUserRequest;
import unicopa.copa.base.com.request.SetUserSettingsRequest;
import unicopa.copa.base.com.request.TestRequest;
import unicopa.copa.base.com.serialization.ServerSerializer;
import unicopa.copa.server.com.requestHandler.RequestHandler;
import unicopa.copa.server.database.DatabaseService;
import unicopa.copa.server.database.IncorrectObjectException;
import unicopa.copa.server.database.ObjectAlreadyExsistsException;
import unicopa.copa.server.database.ObjectNotFoundException;
import unicopa.copa.server.database.util.DatabaseUtil;
import unicopa.copa.server.module.eventimport.EventImportService;
import unicopa.copa.server.module.eventimport.impl.tuilmenau.TUIlmenauEventImportService;
import unicopa.copa.server.module.eventimport.model.EventImportContainer;
import unicopa.copa.server.notification.EmailNotificationService;
import unicopa.copa.server.notification.GoogleCloudNotificationService;
import unicopa.copa.server.notification.Notifier;
/**
* This class represents the core of the system. It receives client messages,
* processes them and returns responses. It is to be used by a wrapper that
* provides the communication with clients. Due to allow simple access by these
* wrappers, the class is a singleton.
*
* @author Felix Wiemuth
*/
public class CopaSystem {
private static final boolean DEBUG_MODE = true; // this enables debug
// logging - attention, may
// result in big log files
private static final Logger LOG = Logger.getLogger(CopaSystem.class
.getName());
private static final Logger DEBUG_LOG = Logger.getLogger("debug");
private static final File databaseDirectory = new File("database");
private static CopaSystem instance = new CopaSystem();
private Properties systemProperties = new Properties(); // TODO use
private CopaSystemContext context;
private Registration registration;
private EventImportService eventImportService;
private Map<Class<? extends AbstractRequest>, RequestHandler> requestHandlers = new HashMap<>();
private boolean initializedDatabase = false;
private CopaSystem() {
try {
// TODO get database from system properties
File baseDir = new File(System.getProperty("user.home")
+ File.separator + ".unicopa" + File.separator + "copa");
baseDir.mkdirs();
File logDirectory = new File(baseDir, "logs");
logDirectory.mkdirs();
// Activate logging to files first
LOG.addHandler(new FileHandler(logDirectory.getCanonicalPath()
+ "/copa-system.log", 10000000, 1, true));
if (DEBUG_MODE) {
DEBUG_LOG.addHandler(new FileHandler(logDirectory
.getCanonicalPath() + "/copa-debug.log", 10000000, 1,
true));
}
// Logger for EventImport module
Logger.getLogger(EventImportService.class.getName()).addHandler(
new FileHandler(logDirectory.getCanonicalPath()
+ "/event-import.log", 10000000, 1, true));
DatabaseService dbservice = initializeDatabase();
Properties serverInfoProperties = new Properties();
serverInfoProperties.load(getClass().getResourceAsStream(
"/system/version.properties"));
Notifier notifier = new Notifier();
context = new CopaSystemContext(dbservice, notifier, baseDir,
logDirectory, DEBUG_LOG, null); // serverInfo is initialized
// below because of cyclic
// dependency
List<String> availableRequests = loadRequestHandlers(); // needs
// context
// to be
// initialized
Date startDate = new Date();
ServerInfo serverInfo = new ServerInfo(serverInfoProperties,
startDate, availableRequests);
context.setServerInfo(serverInfo);
loadSystemProperties();
initializeEventImportService();
registration = new Registration(context);
EmailNotificationService emailNotificationService = new EmailNotificationService(
context);
GoogleCloudNotificationService googleCloudNotificationService = new GoogleCloudNotificationService(
context);
notifier.addNotificationService(emailNotificationService);
notifier.addNotificationService(googleCloudNotificationService);
LOG.log(Level.INFO,
"System fully initialized, started {0}.\nversion: {1}\nAPI version: {2}\ncommit ID: {3}",
new Object[] { startDate, serverInfo.getVersion(),
serverInfo.getApiVersion(),
serverInfo.getCommitID() });
} catch (Exception ex) {
LOG.log(Level.SEVERE, null, ex);
throw new RuntimeException(
"Could not fully initialize the system - safety abort.", ex); // cannot
// continue
// with
// this
// failure
}
if (initializedDatabase) {
if (systemProperties.getProperty("runEventImportOnInitialization")
.equals("true")) {
LOG.info("Starting event import because database was created...");
try {
EventImportContainer snapshot = eventImportService
.getSnapshot();
LOG.info("Fetched event import from remote, inserting into database...");
context.getDbservice().importEvents(snapshot);
LOG.info("Event import finished.");
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Event import failed", ex);
}
}
initializedDatabase = false;
} else if (systemProperties.getProperty("runEventImportOnNextStartup")
.equals("true")) {
LOG.info("Starting event import (activated via properties)...");
// systemProperties.setProperty("runEventImportOnNextStartup",
// "false");
// File systemPropertiesFile = new
// File(context.getSettingsDirectory(),
// "system.properties");
// try {
// systemProperties.store(new
// FileOutputStream(systemPropertiesFile), "comments");
// } catch (IOException ex) {
// LOG.log(Level.SEVERE, "Writing to system properties file failed",
// ex);
// }
try {
EventImportContainer snapshot = eventImportService
.getSnapshot();
LOG.info("Fetched event import from remote, inserting into database...");
context.getDbservice().importEvents(snapshot);
LOG.info("Event import finished.");
} catch (Exception ex) {
LOG.log(Level.SEVERE, "Event import failed", ex);
}
}
}
/**
* Get the instance of the CopaSystem. Do not use this if not absolutely
* necessary. Components of the system are provided with the needed
* information by the system itself.
*
* @return
*/
public static CopaSystem getInstance() {
return instance;
}
private void initializeEventImportService() throws Exception {
File eventImportSettings = new File(context.getSettingsDirectory(),
"eventImport.xml");
if (!eventImportSettings.exists()) {
throw new Exception(
"The configuration file for the event import module does not exist - expected: "
+ eventImportSettings.getAbsolutePath());
}
// TODO generalize: load class from file
eventImportService = new TUIlmenauEventImportService(
new FileInputStream(eventImportSettings));
}
/**
* Initialize DatabaseService and create database if it doesn´t exist.
*
* @return
*/
private DatabaseService initializeDatabase() throws Exception {
DatabaseService databaseService;
if (!databaseDirectory.isDirectory()) {
if (databaseDirectory.exists()) {
throw new Exception(
String.format(
"The path {0} should be either the database directory or nonexistent. Delete it for new database initialization.",
databaseDirectory.getAbsolutePath()));
} else {
DatabaseUtil.createNewDatabase(databaseDirectory);
LOG.log(Level.WARNING, "Created new Database in {0}",
databaseDirectory.getAbsolutePath());
DatabaseService.initDB(databaseDirectory);
databaseService = new DatabaseService(databaseDirectory);
initializedDatabase = true;
}
} else {
databaseService = new DatabaseService(databaseDirectory);
}
return databaseService;
}
/**
* Create the systems settings directory if necessary and load properties.
*/
private void loadSystemProperties() throws URISyntaxException, IOException {
File systemPropertiesFile = new File(context.getSettingsDirectory(),
"system.properties");
if (!systemPropertiesFile.isFile()) {
LOG.warning("System configuration file "
+ systemPropertiesFile.getAbsolutePath()
+ " does not exist, creating default configuration.");
File src = new File(this.getClass()
.getResource("/system/system.properties").toURI());
unicopa.copa.server.util.IOutils
.copyFile(src, systemPropertiesFile);
}
systemProperties = new Properties();
systemProperties.load(new FileInputStream(systemPropertiesFile));
}
/**
* Load the request handlers for the specified requests. The requests for
* which handlers should be loaded must be entered below.
*
* @return a list with the simple names of all Request classes loaded (where
* a handler was found)
*/
private List<String> loadRequestHandlers() {
// TODO (improvement) load class files from directory
// Enable requests (select those for which a RequestHandler should be
// registered below)
List<Class<? extends AbstractRequest>> requests = new ArrayList<Class<? extends AbstractRequest>>() {
{
// sort alphabetically
add(AddRoleToUserRequest.class);
add(AddSingleEventRequest.class);
add(AddSingleEventUpdateRequest.class);
add(CancelSingleEventRequest.class);
add(DropRoleRequest.class);
add(GetAllDeputiesRequest.class);
add(GetAllOwnersRequest.class);
add(GetAllRightholdersRequest.class);
add(GetCategoriesRequest.class);
add(GetCurrentSingleEventsRequest.class);
add(GetEventGroupRequest.class);
add(GetEventGroupsRequest.class);
add(GetEventRequest.class);
add(GetEventsRequest.class);
add(GetMyAppointedUsersRequest.class);
add(GetMyEventsRequest.class);
add(GetServerInfoRequest.class);
add(GetServerStatusNotesRequest.class);
add(GetSingleEventRequest.class);
add(GetSingleEventUpdatesRequest.class);
add(GetSubscribedSingleEventUpdatesRequest.class);
add(GetUserDataRequest.class);
add(GetUserSettingsRequest.class);
add(RemoveRoleFromUserRequest.class);
add(SetUserSettingsRequest.class);
add(TestRequest.class);
}
};
List<String> availableRequests = new LinkedList<>();
// Map Requests to appropriate RequestHandlers
for (Class req : requests) {
StringBuilder handlerName = new StringBuilder();
handlerName.append(RequestHandler.class.getPackage().getName());
handlerName.append('.');
handlerName.append(req.getSimpleName());
handlerName.append("Handler");
Class reqHandlerClass = null;
try {
reqHandlerClass = Class.forName(handlerName.toString());
} catch (ClassNotFoundException ex) {
LOG.log(Level.SEVERE,
"The request hanlder for \""
+ req.getSimpleName()
+ "\" could not be found! This will result in the system not being able to handle this request and return InternatlErrorException instead.",
ex);
continue;
}
RequestHandler reqHandler = null;
try {
reqHandler = (RequestHandler) reqHandlerClass.getConstructor(
CopaSystemContext.class).newInstance(context);
} catch (NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException ex) {
LOG.log(Level.SEVERE, null, ex);
continue;
}
requestHandlers.put(req, reqHandler);
availableRequests.add(req.getSimpleName());
}
return availableRequests;
}
/**
* Process a message sent from a client.
*
* @param json
* the message from the client (expected in JSON format)
* @param userName
* the unique user name of the user whose message to process
*
* @return the message to be sent back to the client
*/
public String processClientMessage(String json, String userName,
GeneralUserPermission userPermission) {
try {
int userID;
try {
userID = context.getDbservice().getUserID(userName);
} catch (ObjectNotFoundException ex) {
// user does not exist in database - register and try again
try {
registration.register(userName, userPermission);
userID = context.getDbservice().getUserID(userName);
// new user registered - make him owner at events where he
// is eligible
context.getDbservice().matchOwners(userID);
} catch (NamingException | ObjectAlreadyExsistsException
| IncorrectObjectException ex1) {
throw new InternalErrorException(
"Fatal: The user could not be registered to the system (which is required to process requests): "
+ ex1.getMessage());
} catch (ObjectNotFoundException ex1) {
throw new InternalErrorException(
"Fatal: Registration was performed but user still cannot be found in the database: "
+ ex1.getMessage());
}
}
AbstractRequest request = AbstractRequest.deserialize(json);
AbstractResponse response = getRequestHandler(request.getClass())
.handleRequest(request, userID);
if (response == null) {
throw new InternalErrorException(
"The request handler for the request returned a null object.");
}
return response.serialize();
} catch (InternalErrorException | APIException | PermissionException
| RequestNotPracticableException ex) {
LOG.log(Level.SEVERE, "Exception while processing client message:",
ex);
return ServerSerializer.serialize(ex); // pass exception to client
}
}
private RequestHandler getRequestHandler(Class requestClass)
throws InternalErrorException {
RequestHandler requestHandler = requestHandlers.get(requestClass);
if (requestHandler == null) {
throw new InternalErrorException(
"There is no request handler available for request "
+ requestClass.getSimpleName() + ".");
}
return requestHandler;
}
public CopaSystemContext getContext() {
return context;
}
}