-
Notifications
You must be signed in to change notification settings - Fork 0
/
CraftServer.java
1816 lines (1519 loc) · 64.5 KB
/
CraftServer.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
package org.bukkit.craftbukkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.bukkit.BanList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.UnsafeValues;
import org.bukkit.Warning.WarningState;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarFlag;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import org.bukkit.conversations.Conversable;
import org.bukkit.craftbukkit.boss.CraftBossBar;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.craftbukkit.generator.CraftChunkData;
import org.bukkit.craftbukkit.help.SimpleHelpMap;
import org.bukkit.craftbukkit.inventory.CraftFurnaceRecipe;
import org.bukkit.craftbukkit.inventory.CraftInventoryCustom;
import org.bukkit.craftbukkit.inventory.CraftItemFactory;
import org.bukkit.craftbukkit.inventory.CraftMerchantCustom;
import org.bukkit.craftbukkit.inventory.CraftRecipe;
import org.bukkit.craftbukkit.inventory.CraftShapedRecipe;
import org.bukkit.craftbukkit.inventory.CraftShapelessRecipe;
import org.bukkit.craftbukkit.inventory.RecipeIterator;
import org.bukkit.craftbukkit.map.CraftMapView;
import org.bukkit.craftbukkit.metadata.EntityMetadataStore;
import org.bukkit.craftbukkit.metadata.PlayerMetadataStore;
import org.bukkit.craftbukkit.metadata.WorldMetadataStore;
import org.bukkit.craftbukkit.potion.CraftPotionBrewer;
import org.bukkit.craftbukkit.scheduler.CraftScheduler;
import org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager;
import org.bukkit.craftbukkit.util.CraftIconCache;
import org.bukkit.craftbukkit.util.CraftMagicNumbers;
import org.bukkit.craftbukkit.util.DatFileFilter;
import org.bukkit.craftbukkit.util.Versioning;
import org.bukkit.craftbukkit.util.permissions.CraftDefaultPermissions;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;
import org.bukkit.event.server.BroadcastMessageEvent;
import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.help.HelpMap;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Merchant;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginLoadOrder;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicesManager;
import org.bukkit.plugin.SimplePluginManager;
import org.bukkit.plugin.SimpleServicesManager;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.plugin.messaging.StandardMessenger;
import org.bukkit.scheduler.BukkitWorker;
import org.bukkit.util.StringUtil;
import org.bukkit.util.permissions.DefaultPermissions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.error.MarkedYAMLException;
import org.apache.commons.lang.Validate;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.tree.CommandNode;
import com.mojang.brigadier.tree.LiteralCommandNode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.buffer.Unpooled;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.bukkit.Keyed;
import org.bukkit.NamespacedKey;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.bukkit.craftbukkit.command.BukkitCommandWrapper;
import org.bukkit.craftbukkit.command.CraftCommandMap;
import org.bukkit.craftbukkit.command.VanillaCommandWrapper;
import org.bukkit.craftbukkit.tag.CraftBlockTag;
import org.bukkit.craftbukkit.tag.CraftItemTag;
import org.bukkit.craftbukkit.util.CraftNamespacedKey;
import org.bukkit.event.server.TabCompleteEvent;
import net.minecraft.advancements.Advancement;
import net.minecraft.command.CommandSenderWrapper;
import net.minecraft.command.ServerCommandManager;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Enchantments;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemMap;
import net.minecraft.server.dedicated.DedicatedPlayerList;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.dedicated.PendingCommand;
import net.minecraft.server.dedicated.PropertyManager;
import net.minecraft.server.management.PlayerList;
import net.minecraft.server.management.UserListEntry;
import net.minecraft.util.IProgressUpdate;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.GameType;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.ServerWorldEventHandler;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import net.minecraft.world.chunk.storage.AnvilSaveConverter;
import net.minecraft.world.chunk.storage.AnvilSaveHandler;
import net.minecraft.world.storage.ISaveFormat;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.storage.MapData;
import net.minecraft.world.storage.MapStorage;
import net.minecraft.world.storage.SaveHandler;
import net.minecraft.world.storage.WorldInfo;
public final class CraftServer implements Server {
private final String serverName = "CraftBukkit";
private final String serverVersion;
private final String bukkitVersion = Versioning.getBukkitVersion();
private final Logger logger = Logger.getLogger("Minecraft");
private final ServicesManager servicesManager = new SimpleServicesManager();
private final CraftScheduler scheduler = new CraftScheduler();
private final CraftCommandMap commandMap = new CraftCommandMap(this);
private final SimpleHelpMap helpMap = new SimpleHelpMap(this);
private final StandardMessenger messenger = new StandardMessenger();
private final SimplePluginManager pluginManager = new SimplePluginManager(this, commandMap);
protected final MinecraftServer console;
protected final DedicatedPlayerList playerList;
private final Map<String, World> worlds = new LinkedHashMap<String, World>();
private YamlConfiguration configuration;
private YamlConfiguration commandsConfiguration;
private final Yaml yaml = new Yaml(new SafeConstructor());
private final Map<UUID, OfflinePlayer> offlinePlayers = new MapMaker().weakValues().makeMap();
private final EntityMetadataStore entityMetadata = new EntityMetadataStore();
private final PlayerMetadataStore playerMetadata = new PlayerMetadataStore();
private final WorldMetadataStore worldMetadata = new WorldMetadataStore();
private int monsterSpawn = -1;
private int animalSpawn = -1;
private int waterAnimalSpawn = -1;
private int ambientSpawn = -1;
public int chunkGCPeriod = -1;
public int chunkGCLoadThresh = 0;
private File container;
private WarningState warningState = WarningState.DEFAULT;
private final BooleanWrapper online = new BooleanWrapper();
public CraftScoreboardManager scoreboardManager;
public boolean playerCommandState;
private boolean printSaveWarning;
private CraftIconCache icon;
private boolean overrideAllCommandBlockCommands = false;
public boolean ignoreVanillaPermissions = false;
private final List<CraftPlayer> playerView;
public int reloadCount;
private final class BooleanWrapper {
private boolean value = true;
}
static {
ConfigurationSerialization.registerClass(CraftOfflinePlayer.class);
CraftItemFactory.instance();
}
public CraftServer(MinecraftServer console, PlayerList playerList) {
this.console = console;
this.playerList = (DedicatedPlayerList) playerList;
this.playerView = Collections.unmodifiableList(Lists.transform(playerList.playerEntityList, new Function<EntityPlayerMP, CraftPlayer>() {
@Override
public CraftPlayer apply(EntityPlayerMP player) {
return player.getBukkitEntity();
}
}));
this.serverVersion = CraftServer.class.getPackage().getImplementationVersion();
online.value = console.getPropertyManager().getBooleanProperty("online-mode", true);
Bukkit.setServer(this);
// Register all the Enchantments and PotionTypes now so we can stop new registration immediately after
Enchantments.SHARPNESS.getClass();
org.bukkit.enchantments.Enchantment.stopAcceptingRegistrations();
Potion.setPotionBrewer(new CraftPotionBrewer());
MobEffects.BLINDNESS.getClass();
PotionEffectType.stopAcceptingRegistrations();
// Ugly hack :(
if (!Main.useConsole) {
getLogger().info("Console input is disabled due to --noconsole command argument");
}
configuration = YamlConfiguration.loadConfiguration(getConfigFile());
configuration.options().copyDefaults(true);
configuration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/bukkit.yml"), Charsets.UTF_8)));
ConfigurationSection legacyAlias = null;
if (!configuration.isString("aliases")) {
legacyAlias = configuration.getConfigurationSection("aliases");
configuration.set("aliases", "now-in-commands.yml");
}
saveConfig();
if (getCommandsConfigFile().isFile()) {
legacyAlias = null;
}
commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile());
commandsConfiguration.options().copyDefaults(true);
commandsConfiguration.setDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("configurations/commands.yml"), Charsets.UTF_8)));
saveCommandsConfig();
// Migrate aliases from old file and add previously implicit $1- to pass all arguments
if (legacyAlias != null) {
ConfigurationSection aliases = commandsConfiguration.createSection("aliases");
for (String key : legacyAlias.getKeys(false)) {
ArrayList<String> commands = new ArrayList<String>();
if (legacyAlias.isList(key)) {
for (String command : legacyAlias.getStringList(key)) {
commands.add(command + " $1-");
}
} else {
commands.add(legacyAlias.getString(key) + " $1-");
}
aliases.set(key, commands);
}
}
saveCommandsConfig();
overrideAllCommandBlockCommands = commandsConfiguration.getStringList("command-block-overrides").contains("*");
ignoreVanillaPermissions = commandsConfiguration.getBoolean("ignore-vanilla-permissions");
pluginManager.useTimings(configuration.getBoolean("settings.plugin-profiling"));
monsterSpawn = configuration.getInt("spawn-limits.monsters");
animalSpawn = configuration.getInt("spawn-limits.animals");
waterAnimalSpawn = configuration.getInt("spawn-limits.water-animals");
ambientSpawn = configuration.getInt("spawn-limits.ambient");
console.autosavePeriod = configuration.getInt("ticks-per.autosave");
warningState = WarningState.value(configuration.getString("settings.deprecated-verbose"));
chunkGCPeriod = configuration.getInt("chunk-gc.period-in-ticks");
chunkGCLoadThresh = configuration.getInt("chunk-gc.load-threshold");
loadIcon();
}
public boolean getCommandBlockOverride(String command) {
return overrideAllCommandBlockCommands || commandsConfiguration.getStringList("command-block-overrides").contains(command);
}
private File getConfigFile() {
return (File) console.options.valueOf("bukkit-settings");
}
private File getCommandsConfigFile() {
return (File) console.options.valueOf("commands-settings");
}
private void saveConfig() {
try {
configuration.save(getConfigFile());
} catch (IOException ex) {
Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + getConfigFile(), ex);
}
}
private void saveCommandsConfig() {
try {
commandsConfiguration.save(getCommandsConfigFile());
} catch (IOException ex) {
Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, "Could not save " + getCommandsConfigFile(), ex);
}
}
public void loadPlugins() {
pluginManager.registerInterface(JavaPluginLoader.class);
File pluginFolder = (File) console.options.valueOf("plugins");
if (pluginFolder.exists()) {
Plugin[] plugins = pluginManager.loadPlugins(pluginFolder);
for (Plugin plugin : plugins) {
try {
String message = String.format("Loading %s", plugin.getDescription().getFullName());
plugin.getLogger().info(message);
plugin.onLoad();
} catch (Throwable ex) {
Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, ex.getMessage() + " initializing " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex);
}
}
} else {
pluginFolder.mkdir();
}
}
public void enablePlugins(PluginLoadOrder type) {
if (type == PluginLoadOrder.STARTUP) {
helpMap.clear();
helpMap.initializeGeneralTopics();
}
Plugin[] plugins = pluginManager.getPlugins();
for (Plugin plugin : plugins) {
if ((!plugin.isEnabled()) && (plugin.getDescription().getLoad() == type)) {
enablePlugin(plugin);
}
}
if (type == PluginLoadOrder.POSTWORLD) {
commandMap.setFallbackCommands();
setVanillaCommands();
commandMap.registerServerAliases();
loadCustomPermissions();
DefaultPermissions.registerCorePermissions();
CraftDefaultPermissions.registerCorePermissions();
helpMap.initializeCommands();
syncCommands();
}
}
public void disablePlugins() {
pluginManager.disablePlugins();
}
private void setVanillaCommands() {
ServerCommandManager dispatcher = console.vanillaCommandDispatcher;
// Build a list of all Vanilla commands and create wrappers
for (CommandNode<CommandSenderWrapper> cmd : dispatcher.a().getRoot().getChildren()) {
commandMap.register("minecraft", new VanillaCommandWrapper(dispatcher, cmd));
}
}
private void syncCommands() {
// Clear existing commands
ServerCommandManager dispatcher = console.commandDispatcher = new ServerCommandManager();
// Register all commands, vanilla ones will be using the old dispatcher references
for (Map.Entry<String, Command> entry : commandMap.getKnownCommands().entrySet()) {
String label = entry.getKey();
Command command = entry.getValue();
if (command instanceof VanillaCommandWrapper) {
LiteralCommandNode<CommandSenderWrapper> node = (LiteralCommandNode<CommandSenderWrapper>) ((VanillaCommandWrapper) command).vanillaCommand;
if (!node.getLiteral().equals(label)) {
LiteralCommandNode<CommandSenderWrapper> clone = new LiteralCommandNode(label, node.getCommand(), node.getRequirement(), node.getRedirect(), node.getRedirectModifier(), node.isFork());
for (CommandNode<CommandSenderWrapper> child : node.getChildren()) {
clone.addChild(child);
}
node = clone;
}
dispatcher.a().getRoot().addChild(node);
} else {
new BukkitCommandWrapper(this, entry.getValue()).register(dispatcher.a(), label);
}
}
// Refresh commands
for (EntityPlayerMP player : getHandle().playerEntityList) {
dispatcher.a(player);
}
}
private void enablePlugin(Plugin plugin) {
try {
List<Permission> perms = plugin.getDescription().getPermissions();
for (Permission perm : perms) {
try {
pluginManager.addPermission(perm, false);
} catch (IllegalArgumentException ex) {
getLogger().log(Level.WARNING, "Plugin " + plugin.getDescription().getFullName() + " tried to register permission '" + perm.getName() + "' but it's already registered", ex);
}
}
pluginManager.dirtyPermissibles();
pluginManager.enablePlugin(plugin);
} catch (Throwable ex) {
Logger.getLogger(CraftServer.class.getName()).log(Level.SEVERE, ex.getMessage() + " loading " + plugin.getDescription().getFullName() + " (Is it up to date?)", ex);
}
}
@Override
public String getName() {
return serverName;
}
@Override
public String getVersion() {
return serverVersion + " (MC: " + console.getMinecraftVersion() + ")";
}
@Override
public String getBukkitVersion() {
return bukkitVersion;
}
@Override
public List<CraftPlayer> getOnlinePlayers() {
return this.playerView;
}
@Override
@Deprecated
public Player getPlayer(final String name) {
Validate.notNull(name, "Name cannot be null");
Player found = getPlayerExact(name);
// Try for an exact match first.
if (found != null) {
return found;
}
String lowerName = name.toLowerCase(java.util.Locale.ENGLISH);
int delta = Integer.MAX_VALUE;
for (Player player : getOnlinePlayers()) {
if (player.getName().toLowerCase(java.util.Locale.ENGLISH).startsWith(lowerName)) {
int curDelta = Math.abs(player.getName().length() - lowerName.length());
if (curDelta < delta) {
found = player;
delta = curDelta;
}
if (curDelta == 0) break;
}
}
return found;
}
@Override
@Deprecated
public Player getPlayerExact(String name) {
Validate.notNull(name, "Name cannot be null");
EntityPlayerMP player = playerList.getPlayerByUsername(name);
return (player != null) ? player.getBukkitEntity() : null;
}
@Override
public Player getPlayer(UUID id) {
EntityPlayerMP player = playerList.getPlayerByUUID(id);
if (player != null) {
return player.getBukkitEntity();
}
return null;
}
@Override
public int broadcastMessage(String message) {
return broadcast(message, BROADCAST_CHANNEL_USERS);
}
public Player getPlayer(final EntityPlayerMP entity) {
return entity.getBukkitEntity();
}
@Override
@Deprecated
public List<Player> matchPlayer(String partialName) {
Validate.notNull(partialName, "PartialName cannot be null");
List<Player> matchedPlayers = new ArrayList<Player>();
for (Player iterPlayer : this.getOnlinePlayers()) {
String iterPlayerName = iterPlayer.getName();
if (partialName.equalsIgnoreCase(iterPlayerName)) {
// Exact match
matchedPlayers.clear();
matchedPlayers.add(iterPlayer);
break;
}
if (iterPlayerName.toLowerCase(java.util.Locale.ENGLISH).contains(partialName.toLowerCase(java.util.Locale.ENGLISH))) {
// Partial match
matchedPlayers.add(iterPlayer);
}
}
return matchedPlayers;
}
@Override
public int getMaxPlayers() {
return playerList.getMaxPlayers();
}
// NOTE: These are dependent on the corresponding call in MinecraftServer
// so if that changes this will need to as well
@Override
public int getPort() {
return this.getConfigInt("server-port", 25565);
}
@Override
public int getViewDistance() {
return this.getConfigInt("view-distance", 10);
}
@Override
public String getIp() {
return this.getConfigString("server-ip", "");
}
@Override
public String getServerName() {
return this.getConfigString("server-name", "Unknown Server");
}
@Override
public String getServerId() {
return this.getConfigString("server-id", "unnamed");
}
@Override
public String getWorldType() {
return this.getConfigString("level-type", "DEFAULT");
}
@Override
public boolean getGenerateStructures() {
return this.getConfigBoolean("generate-structures", true);
}
@Override
public boolean getAllowEnd() {
return this.configuration.getBoolean("settings.allow-end");
}
@Override
public boolean getAllowNether() {
return this.getConfigBoolean("allow-nether", true);
}
public boolean getWarnOnOverload() {
return this.configuration.getBoolean("settings.warn-on-overload");
}
public boolean getQueryPlugins() {
return this.configuration.getBoolean("settings.query-plugins");
}
@Override
public boolean hasWhitelist() {
return this.getConfigBoolean("white-list", false);
}
// NOTE: Temporary calls through to server.properies until its replaced
private String getConfigString(String variable, String defaultValue) {
return this.console.getPropertyManager().getStringProperty(variable, defaultValue);
}
private int getConfigInt(String variable, int defaultValue) {
return this.console.getPropertyManager().getIntProperty(variable, defaultValue);
}
private boolean getConfigBoolean(String variable, boolean defaultValue) {
return this.console.getPropertyManager().getBooleanProperty(variable, defaultValue);
}
// End Temporary calls
@Override
public String getUpdateFolder() {
return this.configuration.getString("settings.update-folder", "update");
}
@Override
public File getUpdateFolderFile() {
return new File((File) console.options.valueOf("plugins"), this.configuration.getString("settings.update-folder", "update"));
}
@Override
public long getConnectionThrottle() {
return this.configuration.getInt("settings.connection-throttle");
}
@Override
public int getTicksPerAnimalSpawns() {
return this.configuration.getInt("ticks-per.animal-spawns");
}
@Override
public int getTicksPerMonsterSpawns() {
return this.configuration.getInt("ticks-per.monster-spawns");
}
@Override
public PluginManager getPluginManager() {
return pluginManager;
}
@Override
public CraftScheduler getScheduler() {
return scheduler;
}
@Override
public ServicesManager getServicesManager() {
return servicesManager;
}
@Override
public List<World> getWorlds() {
return new ArrayList<World>(worlds.values());
}
public DedicatedPlayerList getHandle() {
return playerList;
}
// NOTE: Should only be called from DedicatedServer.ah()
public boolean dispatchServerCommand(CommandSender sender, PendingCommand serverCommand) {
if (sender instanceof Conversable) {
Conversable conversable = (Conversable)sender;
if (conversable.isConversing()) {
conversable.acceptConversationInput(serverCommand.command);
return true;
}
}
try {
this.playerCommandState = true;
return dispatchCommand(sender, serverCommand.command);
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Unexpected exception while parsing console command \"" + serverCommand.command + '"', ex);
return false;
} finally {
this.playerCommandState = false;
}
}
@Override
public boolean dispatchCommand(CommandSender sender, String commandLine) {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(commandLine, "CommandLine cannot be null");
if (commandMap.dispatch(sender, commandLine)) {
return true;
}
if (sender instanceof Player) {
sender.sendMessage("Unknown command. Type \"/help\" for help.");
} else {
sender.sendMessage("Unknown command. Type \"help\" for help.");
}
return false;
}
@Override
public void reload() {
reloadCount++;
configuration = YamlConfiguration.loadConfiguration(getConfigFile());
commandsConfiguration = YamlConfiguration.loadConfiguration(getCommandsConfigFile());
PropertyManager config = new PropertyManager(console.options);
((DedicatedServer) console).settings = config;
boolean animals = config.getBooleanProperty("spawn-animals", console.getCanSpawnAnimals());
boolean monsters = config.getBooleanProperty("spawn-monsters", console.worlds.get(0).getDifficulty() != EnumDifficulty.PEACEFUL);
EnumDifficulty difficulty = EnumDifficulty.getDifficultyEnum(config.getIntProperty("difficulty", console.worlds.get(0).getDifficulty().ordinal()));
online.value = config.getBooleanProperty("online-mode", console.isServerInOnlineMode());
console.setCanSpawnAnimals(config.getBooleanProperty("spawn-animals", console.getCanSpawnAnimals()));
console.setAllowPvp(config.getBooleanProperty("pvp", console.isPVPEnabled()));
console.setAllowFlight(config.getBooleanProperty("allow-flight", console.isFlightAllowed()));
console.setMOTD(config.getStringProperty("motd", console.getMOTD()));
monsterSpawn = configuration.getInt("spawn-limits.monsters");
animalSpawn = configuration.getInt("spawn-limits.animals");
waterAnimalSpawn = configuration.getInt("spawn-limits.water-animals");
ambientSpawn = configuration.getInt("spawn-limits.ambient");
warningState = WarningState.value(configuration.getString("settings.deprecated-verbose"));
printSaveWarning = false;
console.autosavePeriod = configuration.getInt("ticks-per.autosave");
chunkGCPeriod = configuration.getInt("chunk-gc.period-in-ticks");
chunkGCLoadThresh = configuration.getInt("chunk-gc.load-threshold");
loadIcon();
try {
playerList.getBannedIPs().readSavedFile();
} catch (IOException ex) {
logger.log(Level.WARNING, "Failed to load banned-ips.json, " + ex.getMessage());
}
try {
playerList.getBannedPlayers().readSavedFile();
} catch (IOException ex) {
logger.log(Level.WARNING, "Failed to load banned-players.json, " + ex.getMessage());
}
for (WorldServer world : console.worlds) {
world.worldInfo.setDifficulty(difficulty);
world.setAllowedSpawnTypes(monsters, animals);
if (this.getTicksPerAnimalSpawns() < 0) {
world.ticksPerAnimalSpawns = 400;
} else {
world.ticksPerAnimalSpawns = this.getTicksPerAnimalSpawns();
}
if (this.getTicksPerMonsterSpawns() < 0) {
world.ticksPerMonsterSpawns = 1;
} else {
world.ticksPerMonsterSpawns = this.getTicksPerMonsterSpawns();
}
}
pluginManager.clearPlugins();
commandMap.clearCommands();
resetRecipes();
reloadData();
overrideAllCommandBlockCommands = commandsConfiguration.getStringList("command-block-overrides").contains("*");
ignoreVanillaPermissions = commandsConfiguration.getBoolean("ignore-vanilla-permissions");
int pollCount = 0;
// Wait for at most 2.5 seconds for plugins to close their threads
while (pollCount < 50 && getScheduler().getActiveWorkers().size() > 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {}
pollCount++;
}
List<BukkitWorker> overdueWorkers = getScheduler().getActiveWorkers();
for (BukkitWorker worker : overdueWorkers) {
Plugin plugin = worker.getOwner();
String author = "<NoAuthorGiven>";
if (plugin.getDescription().getAuthors().size() > 0) {
author = plugin.getDescription().getAuthors().get(0);
}
getLogger().log(Level.SEVERE, String.format(
"Nag author: '%s' of '%s' about the following: %s",
author,
plugin.getDescription().getName(),
"This plugin is not properly shutting down its async tasks when it is being reloaded. This may cause conflicts with the newly loaded version of the plugin"
));
}
loadPlugins();
enablePlugins(PluginLoadOrder.STARTUP);
enablePlugins(PluginLoadOrder.POSTWORLD);
}
@Override
public void reloadData() {
console.reload();
}
private void loadIcon() {
icon = new CraftIconCache(null);
try {
final File file = new File(new File("."), "server-icon.png");
if (file.isFile()) {
icon = loadServerIcon0(file);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Couldn't load server icon", ex);
}
}
@SuppressWarnings({ "unchecked", "finally" })
private void loadCustomPermissions() {
File file = new File(configuration.getString("settings.permissions-file"));
FileInputStream stream;
try {
stream = new FileInputStream(file);
} catch (FileNotFoundException ex) {
try {
file.createNewFile();
} finally {
return;
}
}
Map<String, Map<String, Object>> perms;
try {
perms = (Map<String, Map<String, Object>>) yaml.load(stream);
} catch (MarkedYAMLException ex) {
getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML: " + ex.toString());
return;
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Server permissions file " + file + " is not valid YAML.", ex);
return;
} finally {
try {
stream.close();
} catch (IOException ex) {}
}
if (perms == null) {
getLogger().log(Level.INFO, "Server permissions file " + file + " is empty, ignoring it");
return;
}
List<Permission> permsList = Permission.loadPermissions(perms, "Permission node '%s' in " + file + " is invalid", Permission.DEFAULT_PERMISSION);
for (Permission perm : permsList) {
try {
pluginManager.addPermission(perm);
} catch (IllegalArgumentException ex) {
getLogger().log(Level.SEVERE, "Permission in " + file + " was already defined", ex);
}
}
}
@Override
public String toString() {
return "CraftServer{" + "serverName=" + serverName + ",serverVersion=" + serverVersion + ",minecraftVersion=" + console.getMinecraftVersion() + '}';
}
public World createWorld(String name, World.Environment environment) {
return WorldCreator.name(name).environment(environment).createWorld();
}
public World createWorld(String name, World.Environment environment, long seed) {
return WorldCreator.name(name).environment(environment).seed(seed).createWorld();
}
public World createWorld(String name, Environment environment, ChunkGenerator generator) {
return WorldCreator.name(name).environment(environment).generator(generator).createWorld();
}
public World createWorld(String name, Environment environment, long seed, ChunkGenerator generator) {
return WorldCreator.name(name).environment(environment).seed(seed).generator(generator).createWorld();
}
@Override
public World createWorld(WorldCreator creator) {
Validate.notNull(creator, "Creator may not be null");
String name = creator.name();
ChunkGenerator generator = creator.generator();
File folder = new File(getWorldContainer(), name);
World world = getWorld(name);
WorldType type = WorldType.parseWorldType(creator.type().getName());
boolean generateStructures = creator.generateStructures();
if (world != null) {
return world;
}
if ((folder.exists()) && (!folder.isDirectory())) {
throw new IllegalArgumentException("File exists with the name '" + name + "' and isn't a folder");
}
if (generator == null) {
generator = getGenerator(name);
}
ISaveFormat converter = new AnvilSaveConverter(getWorldContainer().toPath(), getWorldContainer().toPath().resolveSibling("../backups"), getHandle().getServerInstance().dataFixer);
if (converter.isOldMapFormat(name)) {
getLogger().info("Converting world '" + name + "'");
converter.convertMapFormat(name, new IProgressUpdate() {
private long b = System.currentTimeMillis();
public void a(ITextComponent ichatbasecomponent) {}
public void setLoadingProgress(int i) {
if (System.currentTimeMillis() - this.b >= 1000L) {
this.b = System.currentTimeMillis();
MinecraftServer.LOGGER.info("Converting... {}%", Integer.valueOf(i));
}
}
public void c(ITextComponent ichatbasecomponent) {}
});
}
int dimension = CraftWorld.CUSTOM_DIMENSION_OFFSET + console.worlds.size();
boolean used = false;
do {
for (WorldServer server : console.worlds) {
used = server.dimension == dimension;
if (used) {
dimension++;
break;
}
}
} while(used);
boolean hardcore = false;
ISaveHandler sdm = new AnvilSaveHandler(getWorldContainer(), name, getServer(), getHandle().getServerInstance().dataFixer);
WorldInfo worlddata = sdm.loadWorldInfo();
WorldSettings worldSettings = null;
if (worlddata == null) {
worldSettings = new WorldSettings(creator.seed(), GameType.getByID(getDefaultGameMode().getValue()), generateStructures, hardcore, type);
JsonElement parsedSettings = new JsonParser().parse(creator.generatorSettings());
if (parsedSettings.isJsonObject()) {
worldSettings.setGeneratorSettings(parsedSettings.getAsJsonObject());
}
worlddata = new WorldInfo(worldSettings, name);
}
worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to take the last loaded world as respawn (in this case the end)
WorldServer internal = (WorldServer) new WorldServer(console, sdm, worlddata, dimension, console.profiler, creator.environment(), generator).b();
if (!(worlds.containsKey(name.toLowerCase(java.util.Locale.ENGLISH)))) {
return null;
}
if (worldSettings != null) {
internal.initialize(worldSettings);
}
internal.entityTracker = new EntityTracker(internal);
internal.addEventListener(new ServerWorldEventHandler(console, internal));
internal.worldInfo.setDifficulty(EnumDifficulty.EASY);
internal.setAllowedSpawnTypes(true, true);
console.worlds.add(internal);
pluginManager.callEvent(new WorldInitEvent(internal.getWorld()));
System.out.println("Preparing start region for level " + (console.worlds.size() - 1) + " (Seed: " + internal.getSeed() + ")");
if (internal.getWorld().getKeepSpawnInMemory()) {
short short1 = 196;
long i = System.currentTimeMillis();
for (int j = -short1; j <= short1; j += 16) {
for (int k = -short1; k <= short1; k += 16) {
long l = System.currentTimeMillis();
if (l < i) {
i = l;
}
if (l > i + 1000L) {
int i1 = (short1 * 2 + 1) * (short1 * 2 + 1);
int j1 = (j + short1) * (short1 * 2 + 1) + k + 1;
System.out.println("Preparing spawn area for " + name + ", " + (j1 * 100 / i1) + "%");
i = l;
}
BlockPos chunkcoordinates = internal.getSpawn();
internal.getChunkProviderServer().getChunkAt(chunkcoordinates.getX() + j >> 4, chunkcoordinates.getZ() + k >> 4);
}
}