4 * Copyright 2015 TJ <hacker@iam.tj>.
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 package uk.ac.ntu.n0521366.wsyd.server;
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.util.Date;
29 import java.util.ArrayList;
30 import java.text.SimpleDateFormat;
31 import java.text.ParseException;
32 import java.util.TreeSet;
33 import java.util.SortedMap;
34 import java.util.TreeMap;
36 import java.util.Collections;
37 import java.util.logging.Logger;
38 import java.util.logging.Level;
39 import java.io.BufferedReader;
40 import java.io.BufferedWriter;
42 import java.io.FileInputStream;
43 import java.io.FileOutputStream;
44 import java.io.InputStreamReader;
45 import java.io.OutputStreamWriter;
46 import java.io.ObjectInputStream;
47 import java.io.ObjectOutputStream;
48 import java.io.IOException;
49 import java.io.FileNotFoundException;
50 import java.net.InetSocketAddress;
51 import java.net.SocketException;
52 import java.util.Arrays;
53 import java.util.logging.LogRecord;
54 import javax.swing.Timer;
55 import uk.ac.ntu.n0521366.wsyd.libs.WSYD_Member;
56 import uk.ac.ntu.n0521366.wsyd.libs.WSYD_Member_Comparator_UserID;
57 import uk.ac.ntu.n0521366.wsyd.libs.message.MessagePresence;
58 import uk.ac.ntu.n0521366.wsyd.libs.message.MessageServerControl;
59 import uk.ac.ntu.n0521366.wsyd.libs.net.Network;
60 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessage;
61 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessageEvent;
62 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkServerUDPMulticast;
63 import uk.ac.ntu.n0521366.wsyd.libs.net.WSYD_SocketAddress;
64 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessageEventListener;
65 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkServerUDP;
66 import uk.ac.ntu.n0521366.wsyd.libs.net.ServiceAddressMap;
67 import uk.ac.ntu.n0521366.wsyd.libs.net.ServiceAddressMap.LastSeenHost;
70 * The main Social Network server.
72 * Can be restarted or stopped using the class static attributes
73 * exitRequested and restartRequested. This can be done by an optional
74 * Management GUI application.
76 * @author TJ <hacker@iam.tj>
78 public final class ServerSocial implements NetworkMessageEventListener {
80 * Persistent storage in file-system when server exits.
82 static final String _membersFile = "WSYD_Members.serialized";
87 * If it exists in the file system, only used if there is no _membersFile
89 static final String _testData = "WSYD_TestData.csv";
92 * Readable/displayable name of this application
94 final String _title = "ServerSocial";
97 * Network services to address map.
99 ServiceAddressMap _serviceToAddressMap;
102 * Indicates to start() loop and main() methods to exit completely.
104 public static boolean exitRequested = false;
107 * Indicates to start() loop to exit, and to main() to restart the server.
109 public static boolean restartRequested = true;
112 * Handles display and sending of log messages.
114 @SuppressWarnings("NonConstantLogger")
115 private static Logger LOGGER;
118 * SortedMap wraps a TreeMap that has been made thread-safe by
119 * Collections.synchronizedSortedMap() in readMembers().
121 * Long key, the userID
122 * WSYD_Member member record
124 SortedMap<Long, WSYD_Member> _members;
127 * userIDs of members currently logged in
129 ArrayList<Long> _membersOnline;
134 WSYD_SocketAddress _multicastAdvertiserSA;
139 NetworkServerUDPMulticast _multicastService;
141 Timer _servicesAnnounce;
143 WSYD_SocketAddress _udpControlServiceSA;
145 NetworkServerUDP _udpControlService;
149 * Default constructor.
151 public ServerSocial() {
152 String[] className = this.getClass().getName().split("\\.");
153 LOGGER = Logger.getLogger(className[className.length - 1]);
154 LOGGER.setLevel(Level.ALL);
155 _serviceToAddressMap = new ServiceAddressMap(_title, LOGGER);
156 readMembers(_membersFile);
157 _membersOnline = new ArrayList<>();
163 ServerSocial InitListeners()
165 _multicastAdvertiserSA = new WSYD_SocketAddress(Network.MULTICAST_IP, Network.PORTS_MULTICAST_DISCOVERY, WSYD_SocketAddress.Protocol.UDP);
166 _multicastService = new NetworkServerUDPMulticast(_multicastAdvertiserSA, _title + "MC", _serviceToAddressMap, LOGGER);
167 _multicastService.addNetworkMessageEventListener(this, "Neighbour");
168 _multicastService.execute();
169 _serviceToAddressMap.put("all", new LastSeenHost(new InetSocketAddress(Network.MULTICAST_IP, Network.PORTS_MULTICAST_DISCOVERY), LastSeenHost.STATE.STATIC));
171 _udpControlServiceSA = new WSYD_SocketAddress(Network.IPv4_WILDCARD, Network.PORTS_EPHEMERAL, WSYD_SocketAddress.Protocol.UDP);
172 _udpControlService = new NetworkServerUDP(_udpControlServiceSA, _title + "Control", _serviceToAddressMap, LOGGER);
173 _udpControlService.addNetworkMessageEventListener(this, "Control");
174 _udpControlService.execute();
176 ActionListener servicesAnnounceActionListener = new ActionListener() {
178 * Activated by timer events to send multi-cast neighbour announcements and other regular notifications.
182 public void actionPerformed(ActionEvent e) {
184 // Announce the Social Server Neighbour service
185 MessagePresence mp = new MessagePresence(_title, _multicastService.getSocketAddress());
186 NetworkMessage nm = NetworkMessage.createNetworkMessage("Neighbour", "all", mp);
187 nm.setSender(_title + "MC");
188 _multicastService.queueMessage(nm);
189 LOGGER.log(Level.INFO, "Neighbour advert");
191 // Notify ServerManagement of the Social Server Control service
192 String target = "ServerManagementControl";
193 LastSeenHost targetHost = _serviceToAddressMap.get(target);
194 if (targetHost != null) {
195 mp = new MessagePresence(_title + "Control", _udpControlService.getSocketAddress());
196 nm = NetworkMessage.createNetworkMessage("Control", target, mp);
197 nm.setSender(_title + "Control");
199 _udpControlService.queueMessage(nm);
200 LOGGER.log(Level.INFO, "Control notification sent to ServerManagement");
201 } catch (IllegalArgumentException ex) {
202 // Not fatal - ServerManagement may not be currently known
206 // clean up the known hosts map
207 ArrayList<String> servicesRemoved = _serviceToAddressMap.cleanServiceAddressMap(5000);
208 for (String service: servicesRemoved) {
209 // FIXME: does the process care if hosts have been removed? if not, remove this array iteration
217 _servicesAnnounce = new Timer(1000, servicesAnnounceActionListener);
218 _servicesAnnounce.setInitialDelay(100);
219 _servicesAnnounce.start();
225 * Main execution loop of the server
227 * @return true if no errors encountered
228 * @throws java.lang.InterruptedException
230 @SuppressWarnings("SleepWhileInLoop")
231 public boolean start() throws InterruptedException {
234 // TODO: start() create TCP listener
235 // TODO: start() create UDP Multicast group listener and broadcast adverts
236 // wait for connections
238 while (!ServerSocial.exitRequested && ! ServerSocial.restartRequested) {
239 Thread.sleep(1000); // wait a second
240 System.out.println("start() loop " + loopCount);
241 if (loopCount-- == 0)
242 ServerSocial.exitRequested = true;
246 _multicastServer.serverClose();
248 catch (SocketException e)
252 _servicesAnnounce.stop();
253 _multicastService.cancel(true);
254 _udpControlService.cancel(true);
256 result = writeMembers(_membersFile);
262 * Deserialize the collection of WSYD_Members from file
264 * @param fileName serialized members data file
265 * @return true if successfully deserialized
267 @SuppressWarnings("CallToPrintStackTrace")
268 public boolean readMembers(String fileName) {
269 boolean result = false;
272 FileInputStream f = new FileInputStream(fileName);
273 ObjectInputStream in = new ObjectInputStream(f);
276 if (_members == null)
277 /* XXX: do not pass a Comparator to the constructor if collection is being deserialized as one was already saved during serialization.
278 * If the Comparator is passed to the constructor the serialized object will 'grow' by ~17 bytes each time as multi Comparator
279 * objects are written each time the collection is serialized.
281 _members = Collections.synchronizedSortedMap( new TreeMap<Long, WSYD_Member>() );
282 if (!_members.isEmpty())
284 /* Need explicit cast to SortedMap for Object type returned by readObject()
285 * but this can cause an "unchecked cast" compiler warning since the compiler
286 * cannot be sure the Object returned from readObject() is really a
287 * SortedMap<Long, WSYD_Member> so need to tell the compiler that in this case
288 * we are sure it is. The following for() iteration will cause a
289 * ClassCastException if the type is not as expected.
291 @SuppressWarnings("unchecked")
292 SortedMap<Long, WSYD_Member> temp = (SortedMap<Long, WSYD_Member>) in.readObject();
293 _members = Collections.synchronizedSortedMap( temp );
294 for (Map.Entry<Long, WSYD_Member> e : _members.entrySet()) {
295 System.out.println(e.getKey() + ": " + e.getValue().toString());
297 LOGGER.log(Level.INFO, "Members database read from {0}", fileName);
300 catch(FileNotFoundException e) {
301 _members = Collections.synchronizedSortedMap( new TreeMap<Long, WSYD_Member>( new WSYD_Member_Comparator_UserID() ) );
302 LOGGER.log(Level.INFO, "Starting new members database: no database file found ({0})", fileName);
305 // if test data CSV exists import it
306 File csv = new File(_testData);
307 if (csv.exists() && csv.isFile()) {
308 LOGGER.log(Level.INFO, "Importing test data from {0}", _testData);
309 importCSV(_testData);
313 catch(IOException e) {
314 LOGGER.log(Level.SEVERE, "Unable to read database file {0}", fileName);
317 catch(ClassNotFoundException e) {
318 LOGGER.log(Level.SEVERE, "Unable to deserialize database file {0}", fileName);
326 * Serialize the WSYD_Members collection to a file
328 * @param fileName database file
329 * @return true if collection was successfully serialized
331 @SuppressWarnings("CallToPrintStackTrace")
332 public boolean writeMembers(String fileName) {
333 boolean result = false;
335 if (!_members.isEmpty()) { // don't write an empty database
337 FileOutputStream f = new FileOutputStream(fileName);
338 ObjectOutputStream out = new ObjectOutputStream(f);
341 out.writeObject(_members);
343 LOGGER.log(Level.INFO, "Members database written to {0}", fileName);
346 catch(IOException e) {
347 LOGGER.log(Level.SEVERE, "Unable to write database file {0}", fileName);
358 * Read a CSV file containing WSYD_Member records and add it to the in-memory
361 * @param fileName name of CSV file
362 * @return true if successfully imported
364 @SuppressWarnings("CallToPrintStackTrace")
365 public boolean importCSV(String fileName) {
366 boolean result = false;
369 FileInputStream fis = new FileInputStream(fileName);
370 InputStreamReader isr = new InputStreamReader(fis);
371 BufferedReader br = new BufferedReader(isr);
375 while ((line = br.readLine()) != null) {
376 LOGGER.log(Level.FINEST, line);
378 WSYD_Member temp = WSYD_Member.createWSYD_Member(line);
380 _members.put(temp._userID, temp); // add new member to collection
381 } catch (IllegalArgumentException e) {
382 LOGGER.log(Level.WARNING, "Ignoring bad CSV import line");
386 catch(IOException e) {
387 LOGGER.log(Level.SEVERE, "Unable to import CSV file {0}", fileName);
395 * Export WSYD_Members collection to a CSV file.
397 * @param fileName name of the CSV file to write
398 * @return true if successful
400 @SuppressWarnings("CallToPrintStackTrace")
401 public boolean exportCSV(String fileName) {
402 boolean result = false;
405 FileOutputStream fos = new FileOutputStream(fileName);
406 OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
407 BufferedWriter bw = new BufferedWriter(osw);
410 bw.write("# 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9");
411 bw.write("# userID, userName, password, currentLocation, bio, birthDate, interests, friends, friendsRequestsSent, friendsRequestsReceived");
412 for (Map.Entry<Long, WSYD_Member> e: _members.entrySet()) {
413 bw.write(e.getKey() + ": " + e.getValue().toString());
416 catch(IOException e) {
417 LOGGER.log(Level.SEVERE, "Unable to export to CSV file {0}", fileName);
425 public void NetworkMessageReceived(NetworkMessageEvent event)
427 //TODO: NetworkMessageReceived: Handle Messages
428 NetworkMessage nm = event.getNetworkMessage();
432 System.err.println("Packet Received for intent " + nm.getIntent());
433 if ("Control".equals(nm.getIntent()))
435 String type = nm.getMessage().getMessageType();
436 if (type.equals(MessageServerControl.getType())) { // ServerControl
437 if ("ServerManagement".equals(nm.getSender())) {
438 MessageServerControl mp = (MessageServerControl)nm.getMessage();
439 if (mp.exitReq == MessageServerControl.EXIT.YES) ServerSocial.exitRequested = true;
440 if (mp.restartReq == MessageServerControl.RESTART.YES) ServerSocial.restartRequested = true;
447 * Entry point which starts, restarts, and exits the application.
449 * @param args the command line arguments
450 * @throws java.lang.InterruptedException
452 public static void main(String[] args) throws InterruptedException {
453 while (!ServerSocial.exitRequested && ServerSocial.restartRequested) {
454 ServerSocial app = new ServerSocial().InitListeners();
455 ServerSocial.restartRequested = false;
457 System.err.println("Encountered error running Social Server");
458 break; // leave the while loop