cn.nukkit.Server Java Examples

The following examples show how to use cn.nukkit.Server. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RakNetInterface.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #2
Source File: BaseChunk.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #3
Source File: PlayerChatEvent.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
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;
    }
}
 
Example #4
Source File: ServerScheduler.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example #5
Source File: ZippedResourcePack.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: Item.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #7
Source File: Level.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: BaseChunk.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #9
Source File: BaseChunk.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: Level.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example #11
Source File: BlockLava.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: Timings.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: TimingsExport.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #14
Source File: PermissibleBase.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example #15
Source File: GenerationTask.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #16
Source File: BlockCrops.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onActivate(Item item, Player player) {
    //Bone meal
    if (item.getId() == Item.DYE && item.getDamage() == 0x0f) {
        BlockCrops block = (BlockCrops) this.clone();
        if (this.meta < 7) {
            block.meta += new Random().nextInt(3) + 2;
            if (block.meta > 7) {
                block.meta = 7;
            }
            BlockGrowEvent ev = new BlockGrowEvent(this, block);
            Server.getInstance().getPluginManager().callEvent(ev);

            if (ev.isCancelled()) {
                return false;
            }

            this.getLevel().setBlock(this, ev.getNewState(), true, true);
        }

        this.level.addParticle(new BoneMealParticle(this.add(0.5, 0.5, 0.5)));
        item.count--;
        return true;
    }

    return false;
}
 
Example #17
Source File: BaseChunk.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Block getAndSetBlock(int x, int y, int z, Block block) {
    int Y = y >> 4;
    try {
        setChanged();
        return this.sections[Y].getAndSetBlock(x, y & 0x0f, z, block);
    } 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].getAndSetBlock(x, y & 0x0f, z, block);
    }
}
 
Example #18
Source File: Level.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
public void sendBlockExtraData(int x, int y, int z, int id, int data, Player[] players) {
    LevelEventPacket pk = new LevelEventPacket();
    pk.evid = LevelEventPacket.EVENT_SET_DATA;
    pk.x = x + 0.5f;
    pk.y = y + 0.5f;
    pk.z = z + 0.5f;
    pk.data = (data << 8) | id;

    Server.broadcastPacket(players, pk);
}
 
Example #19
Source File: PermissibleBase.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public void clearPermissions() {
    for (String name : this.permissions.keySet()) {
        Server.getInstance().getPluginManager().unsubscribeFromPermission(name, this.parent != null ? this.parent : this);
    }


    Server.getInstance().getPluginManager().unsubscribeFromDefaultPerms(false, this.parent != null ? this.parent : this);
    Server.getInstance().getPluginManager().unsubscribeFromDefaultPerms(true, this.parent != null ? this.parent : this);

    this.permissions.clear();
}
 
Example #20
Source File: Config.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
public boolean load(InputStream inputStream) {
    if (inputStream == null) return false;
    if (this.correct) {
        String content;
        try {
            content = Utils.readFile(new BufferedInputStream(inputStream));
        } catch (IOException e) {
            Server.getInstance().getLogger().logException(e);
            return false;
        }
        this.parseContent(content);
    }
    return correct;
}
 
Example #21
Source File: LevelProviderManager.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public static void addProvider(Server server, Class<? extends LevelProvider> clazz) {
    try {
        providers.put((String) clazz.getMethod("getProviderName").invoke(null), clazz);
    } catch (Exception e) {
        Server.getInstance().getLogger().logException(e);
    }
}
 
Example #22
Source File: BlockCactus.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onUpdate(int type) {
    if (type == Level.BLOCK_UPDATE_NORMAL) {
        Block down = down();
        if (down.getId() != SAND && down.getId() != CACTUS) {
            this.getLevel().useBreakOn(this);
        } else {
            for (int side = 2; side <= 5; ++side) {
                Block block = getSide(BlockFace.fromIndex(side));
                if (!block.canBeFlowedInto()) {
                    this.getLevel().useBreakOn(this);
                }
            }
        }
    } else if (type == Level.BLOCK_UPDATE_RANDOM) {
        if (down().getId() != CACTUS) {
            if (this.meta == 0x0F) {
                for (int y = 1; y < 3; ++y) {
                    Block b = this.getLevel().getBlock(new Vector3(this.x, this.y + y, this.z));
                    if (b.getId() == AIR) {
                        BlockGrowEvent event = new BlockGrowEvent(b, new BlockCactus());
                        Server.getInstance().getPluginManager().callEvent(event);
                        if (!event.isCancelled()) {
                            this.getLevel().setBlock(b, event.getNewState(), true);
                        }
                    }
                }
                this.meta = 0;
                this.getLevel().setBlock(this, this);
            } else {
                ++this.meta;
                this.getLevel().setBlock(this, this);
            }
        }
    }

    return 0;
}
 
Example #23
Source File: PluginManager.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) throws PluginException {
    if (!plugin.isEnabled()) {
        throw new PluginException("Plugin attempted to register " + event + " while not enabled");
    }

    try {
        Timing timing = Timings.getPluginEventTiming(event, listener, executor, plugin);
        this.getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled, timing));
    } catch (IllegalAccessException e) {
        Server.getInstance().getLogger().logException(e);
    }
}
 
Example #24
Source File: SynapseAPI.java    From SynapseAPI with GNU General Public License v3.0 5 votes vote down vote up
public DataPacket getPacket(byte[] buffer) {
    byte pid = buffer[0] == (byte) 0xfe ? (byte) 0xff : buffer[0];

    byte start = 1;
    DataPacket data;
    data = this.getServer().getNetwork().getPacket(pid);

    if (data == null) {
        Server.getInstance().getLogger().notice("C => S Unknown packet with PID 0x" + String.format("%02x", pid));
        return null;
    }
    data.setBuffer(buffer, start);
    return data;
}
 
Example #25
Source File: BlockCrops.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onUpdate(int type) {
    if (type == Level.BLOCK_UPDATE_NORMAL) {
        if (this.down().getId() != FARMLAND) {
            this.getLevel().useBreakOn(this);
            return Level.BLOCK_UPDATE_NORMAL;
        }
    } else if (type == Level.BLOCK_UPDATE_RANDOM) {
        if (new Random().nextInt(2) == 1) {
            if (this.getDamage() < 0x07) {
                BlockCrops block = (BlockCrops) this.clone();
                block.setDamage(block.getDamage() + 1);
                BlockGrowEvent ev = new BlockGrowEvent(this, block);
                Server.getInstance().getPluginManager().callEvent(ev);

                if (!ev.isCancelled()) {
                    this.getLevel().setBlock(this, ev.getNewState(), false, true);
                } else {
                    return Level.BLOCK_UPDATE_RANDOM;
                }
            }
        } else {
            return Level.BLOCK_UPDATE_RANDOM;
        }
    }

    return 0;
}
 
Example #26
Source File: TaskHandler.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public void run(int currentTick) {
    try {
        setLastRunTick(currentTick);
        getTask().run();
    } catch (RuntimeException ex) {
        Server.getInstance().getLogger().critical("Exception while invoking run", ex);
    }
}
 
Example #27
Source File: NKServiceManager.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> boolean register(Class<T> service, T provider, Plugin plugin, ServicePriority priority) {
    Preconditions.checkNotNull(provider);
    Preconditions.checkNotNull(priority);
    Preconditions.checkNotNull(service);

    // build-in service provider needn't plugin param
    if (plugin == null && provider.getClass().getClassLoader() != Server.class.getClassLoader()) {
        throw new NullPointerException("plugin");
    }

    return provide(service, provider, plugin, priority);
}
 
Example #28
Source File: Level.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public boolean setThundering(boolean thundering) {
    ThunderChangeEvent ev = new ThunderChangeEvent(this, thundering);
    this.getServer().getPluginManager().callEvent(ev);

    if (ev.isCancelled()) {
        return false;
    }

    if (thundering && !isRaining()) {
        setRaining(true);
    }

    this.thundering = thundering;

    LevelEventPacket pk = new LevelEventPacket();
    // These numbers are from Minecraft
    if (thundering) {
        pk.evid = LevelEventPacket.EVENT_START_THUNDER;
        int time = ThreadLocalRandom.current().nextInt(12000) + 3600;
        pk.data = time;
        setThunderTime(time);
    } else {
        pk.evid = LevelEventPacket.EVENT_STOP_THUNDER;
        setThunderTime(ThreadLocalRandom.current().nextInt(168000) + 12000);
    }

    Server.broadcastPacket(this.getPlayers().values(), pk);

    return true;
}
 
Example #29
Source File: Level.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public boolean setThundering(boolean thundering) {
    ThunderChangeEvent ev = new ThunderChangeEvent(this, thundering);
    this.getServer().getPluginManager().callEvent(ev);

    if (ev.isCancelled()) {
        return false;
    }

    if (thundering && !isRaining()) {
        setRaining(true);
    }

    this.thundering = thundering;

    LevelEventPacket pk = new LevelEventPacket();
    // These numbers are from Minecraft
    if (thundering) {
        pk.evid = LevelEventPacket.EVENT_START_THUNDER;
        pk.data = ThreadLocalRandom.current().nextInt(50000) + 10000;
        setThunderTime(ThreadLocalRandom.current().nextInt(12000) + 3600);
    } else {
        pk.evid = LevelEventPacket.EVENT_STOP_THUNDER;
        setThunderTime(ThreadLocalRandom.current().nextInt(168000) + 12000);
    }

    Server.broadcastPacket(this.getPlayers().values(), pk);

    return true;
}
 
Example #30
Source File: BlockCrops.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onActivate(Item item, Player player) {
    //Bone meal
    if (item.getId() == Item.DYE && item.getDamage() == 0x0f) {
        BlockCrops block = (BlockCrops) this.clone();
        if (this.getDamage() < 7) {
            block.setDamage(block.getDamage() + new Random().nextInt(3) + 2);
            if (block.getDamage() > 7) {
                block.setDamage(7);
            }
            BlockGrowEvent ev = new BlockGrowEvent(this, block);
            Server.getInstance().getPluginManager().callEvent(ev);

            if (ev.isCancelled()) {
                return false;
            }

            this.getLevel().setBlock(this, ev.getNewState(), false, true);
        }

        this.level.addParticle(new BoneMealParticle(this.add(0.5, 0.5, 0.5)));
        item.count--;
        return true;
    }

    return false;
}