下面列出了io.netty.util.collection.CharObjectHashMap#cn.nukkit.Server 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
private static void initCreativeItems() {
clearCreativeItems();
Config config = new Config(Config.YAML);
config.load(Server.class.getClassLoader().getResourceAsStream("creativeitems.json"));
List<Map> list = config.getMapList("items");
for (Map map : list) {
try {
addCreativeItem(fromJson(map));
} catch (Exception e) {
MainLogger.getLogger().logException(e);
}
}
}
public static void setHistoryLength(int length) {
//Cap at 12 History Frames, 1 hour at 5 minute frames.
int maxLength = historyInterval * MAX_HISTORY_FRAMES;
//For special cases of servers with special permission to bypass the max.
//This max helps keep data file sizes reasonable for processing on Aikar's Timing parser side.
//Setting this will not help you bypass the max unless Aikar has added an exception on the API side.
if (Server.getInstance().getConfig().getBoolean("timings.bypass-max", false)) {
maxLength = Integer.MAX_VALUE;
}
historyLength = Math.max(Math.min(maxLength, length), historyInterval);
Queue<TimingsHistory> oldQueue = TimingsManager.HISTORY;
int frames = (getHistoryLength() / getHistoryInterval());
if (length > maxLength) {
Server.getInstance().getLogger().warning(
"Timings Length too high. Requested " + length + ", max is " + maxLength
+ ". To get longer history, you must increase your interval. Set Interval to "
+ Math.ceil(length / MAX_HISTORY_FRAMES)
+ " to achieve this length.");
}
TimingsManager.HISTORY = new TimingsManager.BoundedQueue<>(frames);
TimingsManager.HISTORY.addAll(oldQueue);
}
@Override
public void recalculatePermissions() {
Timings.permissibleCalculationTimer.startTiming();
this.clearPermissions();
Map<String, Permission> defaults = Server.getInstance().getPluginManager().getDefaultPermissions(this.isOp());
Server.getInstance().getPluginManager().subscribeToDefaultPerms(this.isOp(), this.parent != null ? this.parent : this);
for (Permission perm : defaults.values()) {
String name = perm.getName();
this.permissions.put(name, new PermissionAttachmentInfo(this.parent != null ? this.parent : this, name, null, true));
Server.getInstance().getPluginManager().subscribeToPermission(name, this.parent != null ? this.parent : this);
this.calculateChildPermissions(perm.getChildren(), false, null);
}
for (PermissionAttachment attachment : this.attachments) {
this.calculateChildPermissions(attachment.getPermissions(), false, attachment);
}
Timings.permissibleCalculationTimer.stopTiming();
}
@Override
public void setBlockId(int x, int y, int z, int id) {
int Y = y >> 4;
try {
this.sections[Y].setBlockId(x, y & 0x0f, z, id);
setChanged();
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
this.sections[Y].setBlockId(x, y & 0x0f, z, id);
} finally {
removeInvalidTile(x, y, z);
}
}
@Override
public void onCompletion(Server server) {
if (level != null) {
if (!this.state) {
return;
}
BaseFullChunk chunk = this.chunk;
if (chunk == null) {
return;
}
level.generateChunkCallback(chunk.getX(), chunk.getZ(), chunk);
}
}
@Override
public byte[] getPackChunk(int off, int len) {
byte[] chunk;
if (this.getPackSize() - off > len) {
chunk = new byte[len];
} else {
chunk = new byte[this.getPackSize() - off];
}
try (FileInputStream fis = new FileInputStream(this.file)) {
fis.skip(off);
fis.read(chunk);
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
return chunk;
}
public void cancelTask(Plugin plugin) {
if (plugin == null) {
throw new NullPointerException("Plugin cannot be null!");
}
for (Map.Entry<Integer, TaskHandler> entry : taskMap.entrySet()) {
TaskHandler taskHandler = entry.getValue();
// TODO: Remove the "taskHandler.getPlugin() == null" check
// It is only there for backwards compatibility!
if (taskHandler.getPlugin() == null || plugin.equals(taskHandler.getPlugin())) {
try {
taskHandler.cancel(); /* It will remove from task map automatic in next main heartbeat. */
} catch (RuntimeException ex) {
Server.getInstance().getLogger().critical("Exception while invoking onCancel", ex);
}
}
}
}
@Override
public void onEntityCollide(Entity entity) {
entity.highestPosition -= (entity.highestPosition - entity.y) * 0.5;
// Always setting the duration to 15 seconds? TODO
EntityCombustByBlockEvent ev = new EntityCombustByBlockEvent(this, entity, 15);
Server.getInstance().getPluginManager().callEvent(ev);
if (!ev.isCancelled()
// Making sure the entity is actually alive and not invulnerable.
&& entity.isAlive()
&& entity.noDamageTicks == 0) {
entity.setOnFire(ev.getDuration());
}
if (!entity.hasEffect(Effect.FIRE_RESISTANCE)) {
entity.attack(new EntityDamageByBlockEvent(this, entity, DamageCause.LAVA, 4));
}
super.onEntityCollide(entity);
}
@Override
public boolean setBlock(int x, int y, int z, Integer blockId, Integer meta) {
int id = blockId == null ? 0 : blockId;
int damage = meta == null ? 0 : meta;
try {
this.hasChanged = true;
return this.sections[y >> 4].setBlock(x, y & 0x0f, z, id, damage);
} catch (ChunkException e) {
int Y = y >> 4;
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
return this.sections[y >> 4].setBlock(x, y & 0x0f, z, id, damage);
}
}
@Override
public void openSession(String identifier, String address, int port, long clientID) {
PlayerCreationEvent ev = new PlayerCreationEvent(this, Player.class, Player.class, null, address, port);
this.server.getPluginManager().callEvent(ev);
Class<? extends Player> clazz = ev.getPlayerClass();
try {
Constructor constructor = clazz.getConstructor(SourceInterface.class, Long.class, String.class, int.class);
Player player = (Player) constructor.newInstance(this, ev.getClientId(), ev.getAddress(), ev.getPort());
this.players.put(identifier, player);
this.networkLatency.put(identifier, 0);
this.identifiersACK.put(identifier, 0);
this.identifiers.put(player.rawHashCode(), identifier);
this.server.addPlayer(identifier, player);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
Server.getInstance().getLogger().logException(e);
}
}
private String getResponse(HttpURLConnection con) throws IOException {
InputStream is = null;
try {
is = con.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
return bos.toString();
} catch (IOException exception) {
this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError"));
Server.getInstance().getLogger().warning(con.getResponseMessage(), exception);
return null;
} finally {
if (is != null) {
is.close();
}
}
}
public void addParticle(Particle particle, Player[] players) {
DataPacket[] packets = particle.encode();
if (players == null) {
if (packets != null) {
for (DataPacket packet : packets) {
this.addChunkPacket((int) particle.x >> 4, (int) particle.z >> 4, packet);
}
}
} else {
if (packets != null) {
if (packets.length == 1) {
Server.broadcastPacket(players, packets[0]);
} else {
this.server.batchPackets(players, packets, false);
}
}
}
}
@Override
public boolean setFullBlockId(int x, int y, int z, int fullId) {
int Y = y >> 4;
try {
setChanged();
return this.sections[Y].setFullBlockId(x, y & 0x0f, z, fullId);
} catch (ChunkException e) {
try {
this.setInternalSection(Y, (ChunkSection) this.providerClass.getMethod("createChunkSection", int.class).invoke(this.providerClass, Y));
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
Server.getInstance().getLogger().logException(e1);
}
return this.sections[Y].setFullBlockId(x, y & 0x0f, z, fullId);
} finally {
removeInvalidTile(x, y, z);
}
}
public void sendWeather(Player[] players) {
if (players == null) {
players = this.getPlayers().values().stream().toArray(Player[]::new);
}
LevelEventPacket pk = new LevelEventPacket();
if (this.isRaining()) {
pk.evid = LevelEventPacket.EVENT_START_RAIN;
pk.data = rand.nextInt(50000) + 10000;
} else {
pk.evid = LevelEventPacket.EVENT_STOP_RAIN;
}
Server.broadcastPacket(players, pk);
if (this.isThundering()) {
pk.evid = LevelEventPacket.EVENT_START_THUNDER;
pk.data = rand.nextInt(50000) + 10000;
} else {
pk.evid = LevelEventPacket.EVENT_STOP_THUNDER;
}
Server.broadcastPacket(players, pk);
}
public PlayerChatEvent(Player player, String message, String format, Set<CommandSender> recipients) {
this.player = player;
this.message = message;
this.format = format;
if (recipients == null) {
for (Permissible permissible : Server.getInstance().getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_USERS)) {
if (permissible instanceof CommandSender) {
this.recipients.add((CommandSender) permissible);
}
}
} else {
this.recipients = recipients;
}
}
public boolean save(Boolean async) {
if (this.file == null) throw new IllegalStateException("Failed to save Config. File object is undefined.");
if (this.correct) {
String content = "";
switch (this.type) {
case Config.PROPERTIES:
content = this.writeProperties();
break;
case Config.JSON:
content = new GsonBuilder().setPrettyPrinting().create().toJson(this.config);
break;
case Config.YAML:
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
content = yaml.dump(this.config);
break;
case Config.ENUM:
for (Object o : this.config.entrySet()) {
Map.Entry entry = (Map.Entry) o;
content += String.valueOf(entry.getKey()) + "\r\n";
}
break;
}
if (async) {
Server.getInstance().getScheduler().scheduleAsyncTask(new FileWriteTask(this.file, content));
} else {
try {
Utils.writeFile(this.file, content);
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
return true;
} else {
return false;
}
}
public void cancel() {
try {
this.getHandler().cancel();
} catch (RuntimeException ex) {
Server.getInstance().getLogger().critical("Exception while invoking onCancel", ex);
}
}
@Override
public boolean clear(int index, boolean send) {
if (this.slots.containsKey(index)) {
Item item = new ItemBlock(new BlockAir(), null, 0);
Item old = this.slots.get(index);
InventoryHolder holder = this.getHolder();
if (holder instanceof Entity) {
EntityInventoryChangeEvent ev = new EntityInventoryChangeEvent((Entity) holder, old, item, index);
Server.getInstance().getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
this.sendSlot(index, this.getViewers());
return false;
}
item = ev.getNewItem();
}
if (item.getId() != Item.AIR) {
this.slots.put(index, item.clone());
} else {
this.slots.remove(index);
}
this.onSlotChange(index, old, send);
}
return true;
}
@Override
public void onCollideWithPlayer(Player player) {
if(this.getPickupDelay() > 0) {
return;
}
Item item = this.getItem();
PlayerInventory playerInventory = player.getInventory();
if(!(item instanceof Item) || (player.isSurvival() && !playerInventory.canAddItem(item))) {
return;
}
InventoryPickupItemEvent ev;
this.server.getPluginManager().callEvent(ev = new InventoryPickupItemEvent(playerInventory, this));
if(ev.isCancelled()) {
return;
}
TakeItemEntityPacket pk = new TakeItemEntityPacket();
pk.entityRuntimeId = player.getId();
pk.target = this.getId();
Server.broadcastPacket(this.getViewers().values(), pk);
playerInventory.addItem(item);
this.kill();
}
@Override
public void run() {
this.setName("RakNet Thread #" + Thread.currentThread().getId());
Runtime.getRuntime().addShutdownHook(new ShutdownHandler());
UDPServerSocket socket = new UDPServerSocket(this.getLogger(), port, this.interfaz);
try {
new SessionManager(this, socket);
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
}
private void calculateChildPermissions(Map<String, Boolean> children, boolean invert, PermissionAttachment attachment) {
for (Map.Entry<String, Boolean> entry : children.entrySet()) {
String name = entry.getKey();
Permission perm = Server.getInstance().getPluginManager().getPermission(name);
boolean v = entry.getValue();
boolean value = (v ^ invert);
this.permissions.put(name, new PermissionAttachmentInfo(this.parent != null ? this.parent : this, name, attachment, value));
Server.getInstance().getPluginManager().subscribeToPermission(name, this.parent != null ? this.parent : this);
if (perm != null) {
this.calculateChildPermissions(perm.getChildren(), !value, attachment);
}
}
}
public AsyncPool(Server server, int size) {
this.currentThread = new AtomicInteger();
this.size = size;
this.pool = new ThreadPoolExecutor(size, Integer.MAX_VALUE,
60, TimeUnit.MILLISECONDS, new SynchronousQueue<>(),
runnable -> new Thread(runnable) {{
setDaemon(true);
setName(String.format("Nukkit Asynchronous Task Handler #%s", currentThread.incrementAndGet()));
}}
);
this.server = server;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
Server.getInstance().getLogger().debug("client-ChannelInactive");
this.getSynapseClient().setConnected(false);
this.getSynapseClient().getClientGroup().shutdownGracefully();
this.getSynapseClient().reconnect();
}
public void addMotion(double motionX, double motionY, double motionZ) {
SetEntityMotionPacket pk = new SetEntityMotionPacket();
pk.eid = this.id;
pk.motionX = (float) motionX;
pk.motionY = (float) motionY;
pk.motionZ = (float) motionZ;
Server.broadcastPacket(this.hasSpawned.values(), pk);
}
public void recalculatePermissibles() {
Set<Permissible> perms = this.getPermissibles();
Server.getInstance().getPluginManager().recalculatePermissionDefaults(this);
for (Permissible p : perms) {
p.recalculatePermissions();
}
}
public Permission addParent(String name, boolean value) {
Permission perm = Server.getInstance().getPluginManager().getPermission(name);
if (perm == null) {
perm = new Permission(name);
Server.getInstance().getPluginManager().addPermission(perm);
}
this.addParent(perm, value);
return perm;
}
private void calculateChildPermissions(Map<String, Boolean> children, boolean invert, PermissionAttachment attachment) {
for (Map.Entry<String, Boolean> entry : children.entrySet()) {
String name = entry.getKey();
Permission perm = Server.getInstance().getPluginManager().getPermission(name);
boolean v = entry.getValue();
boolean value = (v ^ invert);
this.permissions.put(name, new PermissionAttachmentInfo(this.parent != null ? this.parent : this, name, attachment, value));
Server.getInstance().getPluginManager().subscribeToPermission(name, this.parent != null ? this.parent : this);
if (perm != null) {
this.calculateChildPermissions(perm.getChildren(), !value, attachment);
}
}
}
public static BanEntry fromString(String str) {
Map<String, String> map = new Gson().fromJson(str, new TypeToken<TreeMap<String, String>>() {
}.getType());
BanEntry banEntry = new BanEntry(map.get("name"));
try {
banEntry.setCreationDate(new SimpleDateFormat(format).parse(map.get("creationDate")));
banEntry.setExpirationDate(!map.get("expireDate").equals("Forever") ? new SimpleDateFormat(format).parse(map.get("expireDate")) : null);
} catch (ParseException e) {
Server.getInstance().getLogger().logException(e);
}
banEntry.setSource(map.get("source"));
banEntry.setReason(map.get("reason"));
return banEntry;
}
public void cancel() {
try {
this.getHandler().cancel();
} catch (RuntimeException ex) {
Server.getInstance().getLogger().critical("Exception while invoking onCancel", ex);
}
}
public static Class<? extends LevelProvider> getProvider(String path) {
for (Class<? extends LevelProvider> provider : providers.values()) {
try {
if ((boolean) provider.getMethod("isValid", String.class).invoke(null, path)) {
return provider;
}
} catch (Exception e) {
Server.getInstance().getLogger().logException(e);
}
}
return null;
}