summaryrefslogtreecommitdiffstats
path: root/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java
blob: 0373694a66077e498b45bba5cd8d0d5d53791b5a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anjocaido.groupmanager.dataholder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.anjocaido.groupmanager.GroupManager;
import org.anjocaido.groupmanager.data.Group;
import org.anjocaido.groupmanager.data.User;
import org.anjocaido.groupmanager.events.GMGroupEvent;
import org.anjocaido.groupmanager.events.GMSystemEvent;
import org.anjocaido.groupmanager.events.GMUserEvent;
import org.anjocaido.groupmanager.events.GMUserEvent.Action;
import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.reader.UnicodeReader;

/**
 * One instance of this should exist per world/mirror it contains all functions
 * to manage these data sets and points to the relevant users and groups
 * objects.
 * 
 * @author gabrielcouto, ElgarL
 */
public class WorldDataHolder {

	/**
	 * World name
	 */
	protected String name;
	/**
	 * The actual groups holder
	 */
	protected GroupsDataHolder groups = new GroupsDataHolder();
	/**
	 * The actual users holder
	 */
	protected UsersDataHolder users = new UsersDataHolder();
	
	/**
	 * List of UUID's associated with this user name.
	 */
	protected static Map<String, Set<String>> nameToUUIDLookup = new TreeMap<String, Set<String>>();
	/**
     *
     */
	protected AnjoPermissionsHandler permissionsHandler;

	/**
	 * Prevent direct instantiation
	 * 
	 * @param worldName
	 */
	public WorldDataHolder(String worldName) {

		name = worldName;
	}

	/**
	 * The main constructor for a new WorldDataHolder
	 * 
	 * @param worldName
	 * @param groups
	 * @param users
	 */
	public WorldDataHolder(String worldName, GroupsDataHolder groups, UsersDataHolder users) {

		this.name = worldName;
		this.groups = groups;
		this.users = users;

		// this.defaultGroup = defaultGroup;
	}

	/**
	 * update the dataSource to point to this object.
	 * 
	 * This should be called whenever a set of world data is fetched.
	 */
	public void updateDataSource() {

		this.groups.setDataSource(this);
		this.users.setDataSource(this);
	}

	/**
	 * Search for a user. If it doesn't exist, create a new one with default
	 * group.
	 * 
	 * @param userId the UUID String or name of the user
	 * @return class that manage that user permission
	 */
	public User getUser(String userId) {
		
		if (getUsers().containsKey(userId.toLowerCase())) {
			return getUsers().get(userId.toLowerCase());
		}
		
		// Legacy name matching
		if (userId.length() < 36) {

			// Search for a name to UUID match
			for (String uid : getUUIDLookup(userId)) {
				
				User user = getUsers().get(uid);
				
				if (user.getLastName().equalsIgnoreCase(userId)) {
					return user;
				}
			}
			
		}
		
		// No user account found so create a new one.
		User newUser = createUser(userId);
		
		return newUser;
	}
	
	/**
	 * *** Internal GM use only ***
	 * This is called when a player joins to update/add their UUID.
	 * 
	 * @param uUID the player objects UUID.
	 * @param currentName the name they have just logged in with.
	 * @return the user object for this player.
	 */
	public User getUser(String uUID, String currentName) {
		
		// Check for a UUID account
		User user = getUsers().get(uUID.toLowerCase());
		
		if (user != null) {
			
			user.setLastName(currentName);
			return user;
			
		}
		
		// Search for a LastName match
		for (String uid : getUUIDLookup(currentName)) {
			
			User usr = getUsers().get(uid);
			
			if (usr.getLastName().equalsIgnoreCase(currentName) && usr.getUUID().equalsIgnoreCase(usr.getLastName())) {
				
				// Clone this user so we can set it's uUID
				user = usr.clone(uUID, currentName);
				
				// Delete it and replace with the new clone.
				this.removeUser(usr.getUUID());
				this.addUser(user);
				
				return getUsers().get(uUID.toLowerCase());
			}
			
		}
			
		
		// No user account found so create a new one.
		User newUser = createUser(uUID);
		newUser.setLastName(currentName);
		
		return newUser;
	}

	/**
	 * Add a user to the list. If it already exists, overwrite the old.
	 * 
	 * @param theUser the user you want to add to the permission list
	 */
	public void addUser(User theUser) {

		if (theUser.getDataSource() != this) {
			theUser = theUser.clone(this);
		}
		if (theUser == null) {
			return;
		}
		if ((theUser.getGroup() == null)) {
			theUser.setGroup(groups.getDefaultGroup());
		}
		removeUser(theUser.getUUID());
		getUsers().put(theUser.getUUID().toLowerCase(), theUser);
		
		// Store for name to UUID lookups.
		//putUUIDLookup(theUser.getLastName(), theUser.getUUID().toLowerCase());
		
		setUsersChanged(true);
		if (GroupManager.isLoaded())
			GroupManager.getGMEventHandler().callEvent(theUser, Action.USER_ADDED);
	}

	/**
	 * Removes the user from the list. (he might become a default user)
	 * 
	 * @param userId the UUID or username for the user to remove
	 * @return true if it had something to remove
	 */
	public boolean removeUser(String userId) {

		if (getUsers().containsKey(userId.toLowerCase())) {
			
			User user = getUser(userId.toLowerCase());
			
			// Remove the name to UUID lookup for this user object.
			removeUUIDLookup(user.getLastName(), user.getUUID());
			
			getUsers().remove(userId.toLowerCase());
			
			setUsersChanged(true);
			
			if (GroupManager.isLoaded())
				GroupManager.getGMEventHandler().callEvent(userId, GMUserEvent.Action.USER_REMOVED);
			
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @param userId
	 * @return true if we have data for this player.
	 */
	public boolean isUserDeclared(String userId) {

		return getUsers().containsKey(userId.toLowerCase());
	}

	/**
	 * Change the default group of the file.
	 * 
	 * @param group the group you want make default.
	 */
	public void setDefaultGroup(Group group) {

		if (!getGroups().containsKey(group.getName().toLowerCase()) || (group.getDataSource() != this)) {
			addGroup(group);
		}
		groups.setDefaultGroup(getGroup(group.getName()));
		setGroupsChanged(true);
		if (GroupManager.isLoaded())
			GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.DEFAULT_GROUP_CHANGED);
	}

	/**
	 * Returns the default group of the file
	 * 
	 * @return the default group
	 */
	public Group getDefaultGroup() {

		return groups.getDefaultGroup();
	}

	/**
	 * Returns a group of the given name
	 * 
	 * @param groupName the name of the group
	 * @return a group if it is found. null if not found.
	 */
	public Group getGroup(String groupName) {

		if (groupName.toLowerCase().startsWith("g:"))
			return GroupManager.getGlobalGroups().getGroup(groupName);
		else
			return getGroups().get(groupName.toLowerCase());
	}

	/**
	 * Check if a group exists. Its the same of getGroup, but check if it is
	 * null.
	 * 
	 * @param groupName the name of the group
	 * @return true if exists. false if not.
	 */
	public boolean groupExists(String groupName) {

		if (groupName.toLowerCase().startsWith("g:"))
			return GroupManager.getGlobalGroups().hasGroup(groupName);
		else
			return getGroups().containsKey(groupName.toLowerCase());
	}

	/**
	 * Add a group to the list
	 * 
	 * @param groupToAdd
	 */
	public void addGroup(Group groupToAdd) {

		if (groupToAdd.getName().toLowerCase().startsWith("g:")) {
			GroupManager.getGlobalGroups().addGroup(groupToAdd);
			GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED);
			return;
		}

		if (groupToAdd.getDataSource() != this) {
			groupToAdd = groupToAdd.clone(this);
		}
		removeGroup(groupToAdd.getName());
		getGroups().put(groupToAdd.getName().toLowerCase(), groupToAdd);
		setGroupsChanged(true);
		if (GroupManager.isLoaded())
			GroupManager.getGMEventHandler().callEvent(groupToAdd, GMGroupEvent.Action.GROUP_ADDED);
	}

	/**
	 * Remove the group from the list
	 * 
	 * @param groupName
	 * @return true if had something to remove. false the group was default or
	 *         non-existant
	 */
	public boolean removeGroup(String groupName) {

		if (groupName.toLowerCase().startsWith("g:")) {
			return GroupManager.getGlobalGroups().removeGroup(groupName);
		}

		if (getDefaultGroup() != null && groupName.equalsIgnoreCase(getDefaultGroup().getName())) {
			return false;
		}
		if (getGroups().containsKey(groupName.toLowerCase())) {
			getGroups().remove(groupName.toLowerCase());
			setGroupsChanged(true);
			if (GroupManager.isLoaded())
				GroupManager.getGMEventHandler().callEvent(groupName.toLowerCase(), GMGroupEvent.Action.GROUP_REMOVED);
			return true;
		}
		return false;

	}

	/**
	 * Creates a new User with the given name and adds it to this holder.
	 * 
	 * @param userId the UUID or username you want
	 * @return null if user already exists. or new User
	 */
	public User createUser(String userId) {

		if (getUsers().containsKey(userId.toLowerCase())) {
			return null;
		}
		User newUser = new User(this, userId);
		newUser.setGroup(groups.getDefaultGroup(), false);
		addUser(newUser);
		setUsersChanged(true);
		return newUser;
	}

	/**
	 * Creates a new Group with the given name and adds it to this holder
	 * 
	 * @param groupName the groupname you want
	 * @return null if group already exists. or new Group
	 */
	public Group createGroup(String groupName) {

		if (groupName.toLowerCase().startsWith("g:")) {
			Group newGroup = new Group(groupName);
			return GroupManager.getGlobalGroups().newGroup(newGroup);
		}

		if (getGroups().containsKey(groupName.toLowerCase())) {
			return null;
		}

		Group newGroup = new Group(this, groupName);
		addGroup(newGroup);
		setGroupsChanged(true);
		return newGroup;
	}

	/**
	 * 
	 * @return a collection of the groups
	 */
	public Collection<Group> getGroupList() {

		synchronized (getGroups()) {
			return new ArrayList<Group>(getGroups().values());
		}
	}

	/**
	 * 
	 * @return a collection of the users
	 */
	public Collection<User> getUserList() {

		synchronized (getUsers()) {
			return new ArrayList<User>(getUsers().values());
		}
	}

	/**
	 * reads the file again
	 */
	public void reload() {

		try {
			reloadGroups();
			reloadUsers();
		} catch (Exception ex) {
			Logger.getLogger(WorldDataHolder.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	/**
	 * Refresh Group data from file
	 */
	public void reloadGroups() {

		GroupManager.setLoaded(false);
		try {
			// temporary holder in case the load fails.
			WorldDataHolder ph = new WorldDataHolder(this.getName());

			loadGroups(ph, getGroupsFile());
			// transfer new data
			resetGroups();
			for (Group tempGroup : ph.getGroupList()) {
				tempGroup.clone(this);
			}
			this.setDefaultGroup(getGroup(ph.getDefaultGroup().getName()));
			this.removeGroupsChangedFlag();
			this.setTimeStampGroups(getGroupsFile().lastModified());

			ph = null;
		} catch (Exception ex) {
			Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex);
		}
		GroupManager.setLoaded(true);
		GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.RELOADED);
	}

	/**
	 * Refresh Users data from file
	 */
	public void reloadUsers() {

		GroupManager.setLoaded(false);
		try {
			// temporary holder in case the load fails.
			WorldDataHolder ph = new WorldDataHolder(this.getName());
			// copy groups for reference
			for (Group tempGroup : this.getGroupList()) {
				tempGroup.clone(ph);
			}
			// setup the default group before loading user data.
			ph.setDefaultGroup(ph.getGroup(getDefaultGroup().getName()));
			loadUsers(ph, getUsersFile());
			// transfer new data
			resetUsers();
			for (User tempUser : ph.getUserList()) {
				tempUser.clone(this);
			}
			this.removeUsersChangedFlag();
			this.setTimeStampUsers(getUsersFile().lastModified());

			ph = null;
		} catch (Exception ex) {
			Logger.getLogger(WorldDataHolder.class.getName()).log(Level.WARNING, null, ex);
		}
		GroupManager.setLoaded(true);
		GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.RELOADED);
	}

	public void loadGroups(File groupsFile) {

		GroupManager.setLoaded(false);
		try {
			setGroupsFile(groupsFile);
			loadGroups(this, groupsFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("The file which should contain groups does not exist!\n" + groupsFile.getPath());
		} catch (IOException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Error accessing the groups file!\n" + groupsFile.getPath());
		}

		GroupManager.setLoaded(true);
	}

	public void loadUsers(File usersFile) {

		GroupManager.setLoaded(false);
		try {
			setUsersFile(usersFile);
			loadUsers(this, usersFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("The file which should contain users does not exist!\n" + usersFile.getPath());
		} catch (IOException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Error accessing the users file!\n" + usersFile.getPath());
		}

		GroupManager.setLoaded(true);
	}

	/**
	 * Returns a NEW data holder containing data read from the files
	 * 
	 * @param worldName
	 * @param groupsFile
	 * @param usersFile
	 * 
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static WorldDataHolder load(String worldName, File groupsFile, File usersFile) throws FileNotFoundException, IOException {

		WorldDataHolder ph = new WorldDataHolder(worldName);

		GroupManager.setLoaded(false);
		if (groupsFile != null)
			loadGroups(ph, groupsFile);
		if (usersFile != null)
			loadUsers(ph, usersFile);
		GroupManager.setLoaded(true);

		return ph;
	}

	/**
	 * Updates the WorldDataHolder from the Groups file
	 * 
	 * @param ph
	 * @param groupsFile
	 * 
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected static void loadGroups(WorldDataHolder ph, File groupsFile) throws FileNotFoundException, IOException {

		// READ GROUPS FILE

		Yaml yamlGroups = new Yaml(new SafeConstructor());
		Map<String, Object> groupsRootDataNode;

		if (!groupsFile.exists()) {
			throw new IllegalArgumentException("The file which should contain groups does not exist!\n" + groupsFile.getPath());
		}
		FileInputStream groupsInputStream = new FileInputStream(groupsFile);
		try {
			groupsRootDataNode = (Map<String, Object>) yamlGroups.load(new UnicodeReader(groupsInputStream));
			if (groupsRootDataNode == null) {
				throw new NullPointerException();
			}
		} catch (Exception ex) {
			throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + groupsFile.getPath(), ex);
		} finally {
			groupsInputStream.close();
		}

		// PROCESS GROUPS FILE

		Map<String, List<String>> inheritance = new HashMap<String, List<String>>();
		Map<String, Object> allGroupsNode = null;

		/*
		 * Fetch all groups under the 'groups' entry.
		 */
		try {
			allGroupsNode = (Map<String, Object>) groupsRootDataNode.get("groups");
		} catch (Exception ex) {
			throw new IllegalArgumentException("Your " + groupsFile.getPath() + " file is invalid. See console for details.", ex);
		}

		if (allGroupsNode == null) {
			throw new IllegalArgumentException("You have no groups in " + groupsFile.getPath() + ".");
		}

		Iterator<String> groupItr = allGroupsNode.keySet().iterator();
		String groupKey;
		Integer groupCount = 0;

		/*
		 * loop each group entry and process it's data.
		 */
		while (groupItr.hasNext()) {

			try {
				groupCount++;
				// Attempt to fetch the next group name.
				groupKey = groupItr.next();
			} catch (Exception ex) {
				throw new IllegalArgumentException("Invalid group name for group entry (" + groupCount + ") in file: " + groupsFile.getPath(), ex);
			}

			/*
			 * Fetch this groups child nodes
			 */
			Map<String, Object> thisGroupNode = null;

			try {
				thisGroupNode = (Map<String, Object>) allGroupsNode.get(groupKey);
			} catch (Exception ex) {
				throw new IllegalArgumentException("Invalid child nodes for group '" + groupKey + "' in file: " + groupsFile.getPath(), ex);
			}

			/*
			 * Create a new group with this name in the assigned data source.
			 */
			Group thisGrp = ph.createGroup(groupKey);

			if (thisGrp == null) {
				throw new IllegalArgumentException("I think this Group was declared more than once: " + groupKey + " in file: " + groupsFile.getPath());
			}

			// DEFAULT NODE

			Object nodeData = null;
			try {
				nodeData = thisGroupNode.get("default");
			} catch (Exception ex) {
				throw new IllegalArgumentException("Bad format found in 'permissions' for group: " + groupKey + " in file: " + groupsFile.getPath());
			}

			if (nodeData == null) {
				/*
				 * If no 'default' node is found do nothing.
				 */
			} else if ((Boolean.parseBoolean(nodeData.toString()))) {
				/*
				 * Set this as the default group. Warn if some other group has
				 * already claimed that position.
				 */
				if (ph.getDefaultGroup() != null) {
					GroupManager.logger.warning("The group '" + thisGrp.getName() + "' is claiming to be default where '" + ph.getDefaultGroup().getName() + "' already was.");
					GroupManager.logger.warning("Overriding first default request in file: " + groupsFile.getPath());
				}
				ph.setDefaultGroup(thisGrp);
			}

			// PERMISSIONS NODE

			nodeData = null;
			try {
				nodeData = thisGroupNode.get("permissions");
			} catch (Exception ex) {
				throw new IllegalArgumentException("Bad format found in 'permissions' for '" + groupKey + "' in file: " + groupsFile.getPath());
			}

			if (nodeData == null) {
				/*
				 * If no permissions node is found, or it's empty do nothing.
				 */
			} else {
				/*
				 * There is a permission list Which seems to hold some data
				 */
				if (nodeData instanceof List) {
					/*
					 * Check each entry and add it as a new permission.
					 */
					try {
						for (Object o : ((List) nodeData)) {
							try {
								/*
								 * Only add this permission if it's not empty.
								 */
								if (!o.toString().isEmpty())
									thisGrp.addPermission(o.toString());

							} catch (NullPointerException ex) {
								// Ignore this entry as it's null. It can be
								// safely dropped
							}
						}
					} catch (Exception ex) {
						throw new IllegalArgumentException("Invalid formatting found in 'permissions' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex);
					}

				} else if (nodeData instanceof String) {
					/*
					 * Only add this permission if it's not empty.
					 */
					if (!nodeData.toString().isEmpty())
						thisGrp.addPermission((String) nodeData);

				} else {
					throw new IllegalArgumentException("Unknown type of 'permissions' node(Should be String or List<String>) for group:  " + thisGrp.getName() + " in file: " + groupsFile.getPath());
				}
				/*
				 * Sort all permissions so they are in the correct order for
				 * checking.
				 */
				thisGrp.sortPermissions();
			}

			// INFO NODE

			nodeData = null;
			try {
				nodeData = thisGroupNode.get("info");
			} catch (Exception ex) {
				throw new IllegalArgumentException("Bad format found in 'info' section for group: " + groupKey + " in file: " + groupsFile.getPath());
			}

			if (nodeData == null) {
				/*
				 * No info section was found, so leave all variables as
				 * defaults.
				 */
				GroupManager.logger.warning("The group '" + thisGrp.getName() + "' has no 'info' section!");
				GroupManager.logger.warning("Using default values: " + groupsFile.getPath());

			} else if (nodeData instanceof Map) {
				try {
					if (nodeData != null) {
						thisGrp.setVariables((Map<String, Object>) nodeData);
					}
				} catch (Exception ex) {
					throw new IllegalArgumentException("Invalid formatting found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex);
				}

			} else
				throw new IllegalArgumentException("Unknown entry found in 'info' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath());

			// INHERITANCE NODE

			nodeData = null;
			try {
				nodeData = thisGroupNode.get("inheritance");
			} catch (Exception ex) {
				throw new IllegalArgumentException("Bad format found in 'inheritance' section for group: " + groupKey + " in file: " + groupsFile.getPath());
			}

			if (nodeData == null || nodeData instanceof List) {
				if (nodeData == null) {
					/*
					 * If no inheritance node is found, or it's empty do
					 * nothing.
					 */
				} else if (nodeData instanceof List) {

					try {
						for (String grp : (List<String>) nodeData) {
							if (inheritance.get(groupKey) == null) {
								inheritance.put(groupKey, new ArrayList<String>());
							}
							inheritance.get(groupKey).add(grp);
						}

					} catch (Exception ex) {
						throw new IllegalArgumentException("Invalid formatting found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath(), ex);
					}

				}
			} else
				throw new IllegalArgumentException("Unknown entry found in 'inheritance' section for group: " + thisGrp.getName() + " in file: " + groupsFile.getPath());

			// END GROUP

		}

		if (ph.getDefaultGroup() == null) {
			throw new IllegalArgumentException("There was no Default Group declared in file: " + groupsFile.getPath());
		}

		/*
		 * Build the inheritance map and recored any errors
		 */
		for (String group : inheritance.keySet()) {
			List<String> inheritedList = inheritance.get(group);
			Group thisGroup = ph.getGroup(group);
			if (thisGroup != null)
				for (String inheritedKey : inheritedList) {
					if (inheritedKey != null) {
						Group inheritedGroup = ph.getGroup(inheritedKey);
						if (inheritedGroup != null) {
							thisGroup.addInherits(inheritedGroup);
						} else
							GroupManager.logger.warning("Inherited group '" + inheritedKey + "' not found for group " + thisGroup.getName() + ". Ignoring entry in file: " + groupsFile.getPath());
					}
				}
		}

		ph.removeGroupsChangedFlag();
		// Update the LastModified time.
		ph.setGroupsFile(groupsFile);
		ph.setTimeStampGroups(groupsFile.lastModified());

		// return ph;
	}

	/**
	 * Updates the WorldDataHolder from the Users file
	 * 
	 * @param ph
	 * @param usersFile
	 * 
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected static void loadUsers(WorldDataHolder ph, File usersFile) throws FileNotFoundException, IOException {

		// READ USERS FILE
		Yaml yamlUsers = new Yaml(new SafeConstructor());
		Map<String, Object> usersRootDataNode;
		if (!usersFile.exists()) {
			throw new IllegalArgumentException("The file which should contain users does not exist!\n" + usersFile.getPath());
		}
		FileInputStream usersInputStream = new FileInputStream(usersFile);
		try {
			usersRootDataNode = (Map<String, Object>) yamlUsers.load(new UnicodeReader(usersInputStream));
			if (usersRootDataNode == null) {
				throw new NullPointerException();
			}
		} catch (Exception ex) {
			throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + usersFile.getPath(), ex);
		} finally {
			usersInputStream.close();
		}

		// PROCESS USERS FILE

		Map<String, Object> allUsersNode = null;

		/*
		 * Fetch all child nodes under the 'users' entry.
		 */
		try {
			allUsersNode = (Map<String, Object>) usersRootDataNode.get("users");
		} catch (Exception ex) {
			throw new IllegalArgumentException("Your " + usersFile.getPath() + " file is invalid. See console for details.", ex);
		}

		// Load users if the file is NOT empty

		if (allUsersNode != null) {

			Iterator<String> usersItr = allUsersNode.keySet().iterator();
			String usersKey;
			Object node;
			Integer userCount = 0;

			while (usersItr.hasNext()) {
				try {
					userCount++;
					// Attempt to fetch the next user name.
					node = usersItr.next();
					if (node instanceof Integer)
						usersKey = Integer.toString((Integer) node);
					else
						usersKey = node.toString();

				} catch (Exception ex) {
					throw new IllegalArgumentException("Invalid node type for user entry (" + userCount + ") in file: " + usersFile.getPath(), ex);
				}

				Map<String, Object> thisUserNode = null;
				try {
					thisUserNode = (Map<String, Object>) allUsersNode.get(node);
				} catch (Exception ex) {
					throw new IllegalArgumentException("Bad format found for user: " + usersKey + " in file: " + usersFile.getPath());
				}

				User thisUser = ph.createUser(usersKey);
				if (thisUser == null) {
					throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey + " in file: " + usersFile.getPath());
				}

				// LASTNAME NODES

				Object nodeData = null;
				try {
					
					nodeData = thisUserNode.get("lastname");
					
				} catch (Exception ex) {
					throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath());
				}
				
				if ((nodeData != null) && (nodeData instanceof String)) {
					
					thisUser.setLastName((String) nodeData);
					
				}
				
				// USER PERMISSIONS NODES

				nodeData = null;
				try {
					nodeData = thisUserNode.get("permissions");
				} catch (Exception ex) {
					throw new IllegalArgumentException("Bad format found in 'permissions' for user: " + usersKey + " in file: " + usersFile.getPath());
				}

				if (nodeData == null) {
					/*
					 * If no permissions node is found, or it's empty do
					 * nothing.
					 */
				} else {
					try {
						if (nodeData instanceof List) {
							for (Object o : ((List) nodeData)) {
								/*
								 * Only add this permission if it's not empty
								 */
								if (!o.toString().isEmpty()) {
									thisUser.addPermission(o.toString());
								}
							}
						} else if (nodeData instanceof String) {

							/*
							 * Only add this permission if it's not empty
							 */
							if (!nodeData.toString().isEmpty()) {
								thisUser.addPermission(nodeData.toString());
							}

						}
					} catch (NullPointerException e) {
						// Ignore this entry as it's null.
					}
					thisUser.sortPermissions();
				}
				

				// SUBGROUPS NODES

				nodeData = null;
				try {
					nodeData = thisUserNode.get("subgroups");
				} catch (Exception ex) {
					throw new IllegalArgumentException("Bad format found in 'subgroups' for user: " + usersKey + " in file: " + usersFile.getPath());
				}

				if (nodeData == null) {
					/*
					 * If no subgroups node is found, or it's empty do nothing.
					 */
				} else if (nodeData instanceof List) {
					for (Object o : ((List) nodeData)) {
						if (o == null) {
							GroupManager.logger.warning("Invalid Subgroup data for user: " + thisUser.getLastName() + ". Ignoring entry in file: " + usersFile.getPath());
						} else {
							Group subGrp = ph.getGroup(o.toString());
							if (subGrp != null) {
								thisUser.addSubGroup(subGrp);
							} else {
								GroupManager.logger.warning("Subgroup '" + o.toString() + "' not found for user: " + thisUser.getLastName() + ". Ignoring entry in file: " + usersFile.getPath());
							}
						}
					}
				} else if (nodeData instanceof String) {
					Group subGrp = ph.getGroup(nodeData.toString());
					if (subGrp != null) {
						thisUser.addSubGroup(subGrp);
					} else {
						GroupManager.logger.warning("Subgroup '" + nodeData.toString() + "' not found for user: " + thisUser.getLastName() + ". Ignoring entry in file: " + usersFile.getPath());
					}
				}

				// USER INFO NODE

				nodeData = null;
				try {
					nodeData = thisUserNode.get("info");
				} catch (Exception ex) {
					throw new IllegalArgumentException("Bad format found in 'info' section for user: " + usersKey + " in file: " + usersFile.getPath());
				}

				if (nodeData == null) {
					/*
					 * If no info node is found, or it's empty do nothing.
					 */
				} else if (nodeData instanceof Map) {
					thisUser.setVariables((Map<String, Object>) nodeData);

				} else
					throw new IllegalArgumentException("Unknown entry found in 'info' section for user: " + thisUser.getLastName() + " in file: " + usersFile.getPath());

				// END INFO NODE

				// PRIMARY GROUP

				nodeData = null;
				try {
					nodeData = thisUserNode.get("group");
				} catch (Exception ex) {
					throw new IllegalArgumentException("Bad format found in 'group' section for user: " + usersKey + " in file: " + usersFile.getPath());
				}

				if (nodeData != null) {
					Group hisGroup = ph.getGroup(nodeData.toString());
					if (hisGroup == null) {
						GroupManager.logger.warning("There is no group " + thisUserNode.get("group").toString() + ", as stated for player " + thisUser.getLastName() + ": Set to '" + ph.getDefaultGroup().getName() + "' for file: " + usersFile.getPath());
						hisGroup = ph.getDefaultGroup();
					}
					thisUser.setGroup(hisGroup);
				} else {
					thisUser.setGroup(ph.getDefaultGroup());
				}
			}
		}

		ph.removeUsersChangedFlag();
		// Update the LastModified time.
		ph.setUsersFile(usersFile);
		ph.setTimeStampUsers(usersFile.lastModified());
	}

	/**
	 * Write a dataHolder in a specified file
	 * 
	 * @param ph
	 * @param groupsFile
	 */
	public static void writeGroups(WorldDataHolder ph, File groupsFile) {

		Map<String, Object> root = new HashMap<String, Object>();

		Map<String, Object> groupsMap = new HashMap<String, Object>();

		root.put("groups", groupsMap);
		synchronized (ph.getGroups()) {
			for (String groupKey : ph.getGroups().keySet()) {
				Group group = ph.getGroups().get(groupKey);

				Map<String, Object> aGroupMap = new HashMap<String, Object>();
				groupsMap.put(group.getName(), aGroupMap);

				if (ph.getDefaultGroup() == null) {
					GroupManager.logger.severe("There is no default group for world: " + ph.getName());
				}
				aGroupMap.put("default", group.equals(ph.getDefaultGroup()));

				Map<String, Object> infoMap = new HashMap<String, Object>();
				aGroupMap.put("info", infoMap);

				for (String infoKey : group.getVariables().getVarKeyList()) {
					infoMap.put(infoKey, group.getVariables().getVarObject(infoKey));
				}

				aGroupMap.put("inheritance", group.getInherits());

				aGroupMap.put("permissions", group.getPermissionList());
			}
		}

		if (!root.isEmpty()) {
			DumperOptions opt = new DumperOptions();
			opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
			final Yaml yaml = new Yaml(opt);
			try {
				OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(groupsFile), "UTF-8");

				String newLine = System.getProperty("line.separator");

				out.write("# Group inheritance" + newLine);
				out.write("#" + newLine);
				out.write("# Any inherited groups prefixed with a g: are global groups" + newLine);
				out.write("# and are inherited from the GlobalGroups.yml." + newLine);
				out.write("#" + newLine);
				out.write("# Groups without the g: prefix are groups local to this world" + newLine);
				out.write("# and are defined in the this groups.yml file." + newLine);
				out.write("#" + newLine);
				out.write("# Local group inheritances define your promotion tree when using 'manpromote/mandemote'" + newLine);
				out.write(newLine);

				yaml.dump(root, out);
				out.close();
			} catch (UnsupportedEncodingException ex) {
			} catch (FileNotFoundException ex) {
			} catch (IOException e) {
			}
		}

		// Update the LastModified time.
		ph.setGroupsFile(groupsFile);
		ph.setTimeStampGroups(groupsFile.lastModified());
		ph.removeGroupsChangedFlag();

		if (GroupManager.isLoaded())
			GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED);

		/*
		 * FileWriter tx = null; try { tx = new FileWriter(groupsFile, false);
		 * tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { }
		 * finally { try { tx.close(); } catch (IOException ex) { } }
		 */
	}

	/**
	 * Write a dataHolder in a specified file
	 * 
	 * @param ph
	 * @param usersFile
	 */
	public static void writeUsers(WorldDataHolder ph, File usersFile) {

		Map<String, Object> root = new HashMap<String, Object>();
		LinkedHashMap<String, Object> usersMap = new LinkedHashMap<String, Object>();
		
		root.put("users", usersMap);
		synchronized (ph.getUsers()) {
			
			// A sorted list of users.
			for (String userKey : new TreeSet<String>(ph.getUsers().keySet())) {
				User user = ph.getUsers().get(userKey);
				if ((user.getGroup() == null || user.getGroup().equals(ph.getDefaultGroup())) && user.getPermissionList().isEmpty() && user.getVariables().isEmpty() && user.isSubGroupsEmpty()) {
					continue;
				}

				LinkedHashMap<String, Object> aUserMap = new LinkedHashMap<String, Object>();
				usersMap.put(user.getUUID(), aUserMap);

				if (!user.getUUID().equalsIgnoreCase(user.getLastName())) {
					aUserMap.put("lastname", user.getLastName());
				}
				
				// GROUP NODE
				if (user.getGroup() == null) {
					aUserMap.put("group", ph.getDefaultGroup().getName());
				} else {
					aUserMap.put("group", user.getGroup().getName());
				}

				// SUBGROUPS NODE
				aUserMap.put("subgroups", user.subGroupListStringCopy());

				// PERMISSIONS NODE
				aUserMap.put("permissions", user.getPermissionList());

				// USER INFO NODE - BETA
				if (user.getVariables().getSize() > 0) {
					Map<String, Object> infoMap = new HashMap<String, Object>();
					aUserMap.put("info", infoMap);
					for (String infoKey : user.getVariables().getVarKeyList()) {
						infoMap.put(infoKey, user.getVariables().getVarObject(infoKey));
					}
				}
				// END USER INFO NODE - BETA

			}
		}

		if (!root.isEmpty()) {
			DumperOptions opt = new DumperOptions();
			opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
			final Yaml yaml = new Yaml(opt);
			try {
				OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(usersFile), "UTF-8");
				yaml.dump(root, out);
				out.close();
			} catch (UnsupportedEncodingException ex) {
			} catch (FileNotFoundException ex) {
			} catch (IOException e) {
			}
		}

		// Update the LastModified time.
		ph.setUsersFile(usersFile);
		ph.setTimeStampUsers(usersFile.lastModified());
		ph.removeUsersChangedFlag();

		if (GroupManager.isLoaded())
			GroupManager.getGMEventHandler().callEvent(GMSystemEvent.Action.SAVED);

		/*
		 * FileWriter tx = null; try { tx = new FileWriter(usersFile, false);
		 * tx.write(yaml.dump(root)); tx.flush(); } catch (Exception e) { }
		 * finally { try { tx.close(); } catch (IOException ex) { } }
		 */
	}

	/**
	 * Don't use this. Unless you want to make this plugin to interact with
	 * original Nijikokun Permissions This method is supposed to make the
	 * original one reload the file, and propagate the changes made here.
	 * 
	 * Prefer to use the AnjoCaido's fake version of Nijikokun's Permission
	 * plugin. The AnjoCaido's Permission can propagate the changes made on this
	 * plugin instantly, without need to save the file.
	 * 
	 * @param server the server that holds the plugin
	 * @deprecated it is not used anymore... unless if you use original
	 *             Permissions
	 */
	@Deprecated
	public static void reloadOldPlugins(Server server) {

		// Only reload permissions
		PluginManager pm = server.getPluginManager();
		Plugin[] plugins = pm.getPlugins();
		for (int i = 0; i < plugins.length; i++) {
			// plugins[i].getConfiguration().load();
			try {
				plugins[i].getClass().getMethod("setupPermissions").invoke(plugins[i]);
			} catch (Exception ex) {
				continue;
			}
		}
	}

	/**
	 * @return the permissionsHandler
	 */
	public AnjoPermissionsHandler getPermissionsHandler() {

		if (permissionsHandler == null) {
			permissionsHandler = new AnjoPermissionsHandler(this);
		}
		return permissionsHandler;
	}

	/**
	 * @param haveUsersChanged the haveUsersChanged to set
	 */
	public void setUsersChanged(boolean haveUsersChanged) {

		users.setUsersChanged(haveUsersChanged);
	}

	/**
	 * 
	 * @return true if any user data has changed
	 */
	public boolean haveUsersChanged() {

		if (users.HaveUsersChanged()) {
			return true;
		}
		synchronized (users.getUsers()) {
			for (User u : users.getUsers().values()) {
				if (u.isChanged()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * @param setGroupsChanged the haveGroupsChanged to set
	 */
	public void setGroupsChanged(boolean setGroupsChanged) {

		groups.setGroupsChanged(setGroupsChanged);
	}

	/**
	 * 
	 * @return true if any group data has changed.
	 */
	public boolean haveGroupsChanged() {

		if (groups.HaveGroupsChanged()) {
			return true;
		}
		synchronized (groups.getGroups()) {
			for (Group g : groups.getGroups().values()) {
				if (g.isChanged()) {
					return true;
				}
			}
		}
		return false;
	}

	/**
     *
     */
	public void removeUsersChangedFlag() {

		setUsersChanged(false);
		synchronized (getUsers()) {
			for (User u : getUsers().values()) {
				u.flagAsSaved();
			}
		}
	}

	/**
     *
     */
	public void removeGroupsChangedFlag() {

		setGroupsChanged(false);
		synchronized (getGroups()) {
			for (Group g : getGroups().values()) {
				g.flagAsSaved();
			}
		}
	}

	/**
	 * @return the usersFile
	 */
	public File getUsersFile() {

		return users.getUsersFile();
	}

	/**
	 * @param file the usersFile to set
	 */
	public void setUsersFile(File file) {

		users.setUsersFile(file);
	}

	/**
	 * @return the groupsFile
	 */
	public File getGroupsFile() {

		return groups.getGroupsFile();
	}

	/**
	 * @param file the groupsFile to set
	 */
	public void setGroupsFile(File file) {

		groups.setGroupsFile(file);
	}

	/**
	 * @return the name
	 */
	public String getName() {

		return name;
	}

	/**
	 * Resets Groups.
	 */
	public void resetGroups() {

		// setDefaultGroup(null);
		groups.resetGroups();
	}

	/**
	 * Resets Users
	 */
	public void resetUsers() {

		users.resetUsers();
		this.clearUUIDLookup();
	}

	/**
	 * Note: Iteration over this object has to be synchronized!
	 * 
	 * @return the groups
	 */
	public Map<String, Group> getGroups() {

		return groups.getGroups();
	}

	/**
	 * Note: Iteration over this object has to be synchronized!
	 * 
	 * @return the users
	 */
	public Map<String, User> getUsers() {

		return users.getUsers();
	}

	/**
	 * @return the groups
	 */
	public GroupsDataHolder getGroupsObject() {

		return groups;
	}

	/**
	 * @param groupsDataHolder the GroupsDataHolder to set
	 */
	public void setGroupsObject(GroupsDataHolder groupsDataHolder) {

		groups = groupsDataHolder;
	}

	/**
	 * @return the users
	 */
	public UsersDataHolder getUsersObject() {

		return users;
	}

	/**
	 * @param usersDataHolder the UsersDataHolder to set
	 */
	public void setUsersObject(UsersDataHolder usersDataHolder) {

		users = usersDataHolder;
	}

	/**
	 * @return the timeStampGroups
	 */
	public long getTimeStampGroups() {

		return groups.getTimeStampGroups();
	}

	/**
	 * @return the timeStampUsers
	 */
	public long getTimeStampUsers() {

		return users.getTimeStampUsers();
	}

	/**
	 * @param timeStampGroups the timeStampGroups to set
	 */
	protected void setTimeStampGroups(long timeStampGroups) {

		groups.setTimeStampGroups(timeStampGroups);
	}

	/**
	 * @param timeStampUsers the timeStampUsers to set
	 */
	protected void setTimeStampUsers(long timeStampUsers) {

		users.setTimeStampUsers(timeStampUsers);
	}

	public void setTimeStamps() {

		if (getGroupsFile() != null)
			setTimeStampGroups(getGroupsFile().lastModified());
		if (getUsersFile() != null)
			setTimeStampUsers(getUsersFile().lastModified());
	}
	
	/** Name to UUID lookups **/
	
	/**
	 * Add a new name to UUID lookup.
	 * 
	 * @param name the User name key to index on.
	 * @param UUID the User object UUID (same as name if there is no UUID).
	 */
	public void putUUIDLookup(String name, String UUID) {
		
		Set<String> lookup = getUUIDLookup(name);
		
		if (lookup == null)
			lookup = new TreeSet<String>();
		
		lookup.add(UUID);
		
		nameToUUIDLookup.put(name, lookup);
	}
	
	/**
	 * Delete a name lookup.
	 * Allows for multiple UUID's assigned to a single name (offline/online)
	 * 
	 * @param name
	 * @param UUID 
	 */
	public void removeUUIDLookup(String name, String UUID) {
		
		if (nameToUUIDLookup.containsKey(name)) {
			
			Set<String> lookup = getUUIDLookup(name);
			
			lookup.remove(UUID);
			
			if (lookup.isEmpty()) {
				nameToUUIDLookup.remove(name);
				return;				
			}
				
			nameToUUIDLookup.put(name, lookup);
			
		}
		
	}
	
	/**
	 * 
	 * @param name
	 * @return a Set of strings containing the User objects UUID (or name if they don't have a UUID)
	 */
	public Set<String> getUUIDLookup(String name) {
		
		return nameToUUIDLookup.get(name);
	}
	
	/**
	 * Reset the UUID Lookup cache
	 */
	protected void clearUUIDLookup() {
		
		nameToUUIDLookup.clear();
	}

}