file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Session.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/server/Session.java | package cn.nukkit.raknet.server;
import cn.nukkit.raknet.RakNet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.EncapsulatedPacket;
import cn.nukkit.raknet.protocol.Packet;
import cn.nukkit.raknet.protocol.packet.*;
import cn.nukkit.utils.Binary;
import cn.nukkit.utils.BinaryStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Session {
public final static int STATE_UNCONNECTED = 0;
public final static int STATE_CONNECTING_1 = 1;
public final static int STATE_CONNECTING_2 = 2;
public final static int STATE_CONNECTED = 3;
public final static int MAX_SPLIT_SIZE = 128;
public final static int MAX_SPLIT_COUNT = 4;
public static final int WINDOW_SIZE = 2048;
private int messageIndex = 0;
private final Map<Integer, Integer> channelIndex = new ConcurrentHashMap<>();
private SessionManager sessionManager;
private final String address;
private final int port;
private int state = STATE_UNCONNECTED;
//private List<EncapsulatedPacket> preJoinQueue = new ArrayList<>();
private int mtuSize = 548; //Min size
private long id = 0;
private int splitID = 0;
private int sendSeqNumber = 0;
private int lastSeqNumber = -1;
private long lastUpdate;
private final long startTime;
private boolean isTemporal = true;
private final List<DataPacket> packetToSend = new ArrayList<>();
private boolean isActive;
private Map<Integer, Integer> ACKQueue = new HashMap<>();
private Map<Integer, Integer> NACKQueue = new HashMap<>();
private final Map<Integer, DataPacket> recoveryQueue = new TreeMap<>();
private final Map<Integer, Map<Integer, EncapsulatedPacket>> splitPackets = new HashMap<>();
private final Map<Integer, Map<Integer, Integer>> needACK = new TreeMap<>();
private DataPacket sendQueue;
private int windowStart;
private final Map<Integer, Integer> receivedWindow = new TreeMap<>();
private int windowEnd;
private int reliableWindowStart;
private int reliableWindowEnd;
private final Map<Integer, EncapsulatedPacket> reliableWindow = new TreeMap<>();
private int lastReliableIndex = -1;
public Session(SessionManager sessionManager, String address, int port) {
this.sessionManager = sessionManager;
this.address = address;
this.port = port;
this.sendQueue = new DATA_PACKET_4();
this.lastUpdate = System.currentTimeMillis();
this.startTime = System.currentTimeMillis();
this.isActive = false;
this.windowStart = -1;
this.windowEnd = WINDOW_SIZE;
this.reliableWindowStart = 0;
this.reliableWindowEnd = WINDOW_SIZE;
for (int i = 0; i < 32; i++) {
this.channelIndex.put(i, 0);
}
}
public String getAddress() {
return this.address;
}
public int getPort() {
return this.port;
}
public long getID() {
return this.id;
}
public void update(long time) throws Exception {
if (!this.isActive && (this.lastUpdate + 10000) < time) { //10 second timeout
this.disconnect("timeout");
return;
}
this.isActive = false;
if (!this.ACKQueue.isEmpty()) {
ACK pk = new ACK();
pk.packets = new TreeMap<>(this.ACKQueue);
this.sendPacket(pk);
this.ACKQueue = new HashMap<>();
}
if (!this.NACKQueue.isEmpty()) {
NACK pk = new NACK();
pk.packets = new TreeMap<>(this.NACKQueue);
this.sendPacket(pk);
this.NACKQueue = new HashMap<>();
}
if (!this.packetToSend.isEmpty()) {
int limit = 16;
for (int i = 0; i < this.packetToSend.size(); i++) {
DataPacket pk = this.packetToSend.get(i);
pk.sendTime = time;
pk.encode();
this.recoveryQueue.put(pk.seqNumber, pk);
this.packetToSend.remove(pk);
this.sendPacket(pk);
if (limit-- <= 0) {
break;
}
}
}
if (this.packetToSend.size() > WINDOW_SIZE) {
this.packetToSend.clear();
}
if (!this.needACK.isEmpty()) {
for (int identifierACK : new ArrayList<>(this.needACK.keySet())) {
Map<Integer, Integer> indexes = this.needACK.get(identifierACK);
if (indexes.isEmpty()) {
this.needACK.remove(identifierACK);
this.sessionManager.notifyACK(this, identifierACK);
}
}
}
for (int seq : new ArrayList<>(this.recoveryQueue.keySet())) {
DataPacket pk = this.recoveryQueue.get(seq);
if (pk.sendTime < System.currentTimeMillis() - 8000) {
this.packetToSend.add(pk);
this.recoveryQueue.remove(seq);
} else {
break;
}
}
for (int seq : new ArrayList<>(this.receivedWindow.keySet())) {
if (seq < this.windowStart) {
this.receivedWindow.remove(seq);
} else {
break;
}
}
this.sendQueue();
}
public void disconnect() throws Exception {
this.disconnect("unknown");
}
public void disconnect(String reason) throws Exception {
this.sessionManager.removeSession(this, reason);
}
private void sendPacket(Packet packet) throws IOException {
this.sessionManager.sendPacket(packet, this.address, this.port);
}
public void sendQueue() throws IOException {
if (!this.sendQueue.packets.isEmpty()) {
this.sendQueue.seqNumber = sendSeqNumber++;
this.sendPacket(sendQueue);
this.sendQueue.sendTime = System.currentTimeMillis();
this.recoveryQueue.put(this.sendQueue.seqNumber, this.sendQueue);
this.sendQueue = new DATA_PACKET_4();
}
}
private void addToQueue(EncapsulatedPacket pk) throws Exception {
addToQueue(pk, RakNet.PRIORITY_NORMAL);
}
private void addToQueue(EncapsulatedPacket pk, int flags) throws Exception {
int priority = flags & 0b0000111;
if (pk.needACK && pk.messageIndex != null) {
if (!this.needACK.containsKey(pk.identifierACK)) {
this.needACK.put(pk.identifierACK, new HashMap<>());
}
this.needACK.get(pk.identifierACK).put(pk.messageIndex, pk.messageIndex);
}
if (priority == RakNet.PRIORITY_IMMEDIATE) { //Skip queues
DataPacket packet = new DATA_PACKET_0();
packet.seqNumber = this.sendSeqNumber++;
if (pk.needACK) {
packet.packets.add(pk.clone());
pk.needACK = false;
} else {
packet.packets.add(pk.toBinary());
}
this.sendPacket(packet);
packet.sendTime = System.currentTimeMillis();
this.recoveryQueue.put(packet.seqNumber, packet);
return;
}
int length = this.sendQueue.length();
if (length + pk.getTotalLength() > this.mtuSize) {
this.sendQueue();
}
if (pk.needACK) {
this.sendQueue.packets.add(pk.clone());
pk.needACK = false;
} else {
this.sendQueue.packets.add(pk.toBinary());
}
}
public void addEncapsulatedToQueue(EncapsulatedPacket packet) throws Exception {
addEncapsulatedToQueue(packet, RakNet.PRIORITY_NORMAL);
}
public void addEncapsulatedToQueue(EncapsulatedPacket packet, int flags) throws Exception {
if ((packet.needACK = (flags & RakNet.FLAG_NEED_ACK) > 0)) {
this.needACK.put(packet.identifierACK, new HashMap<>());
}
if (packet.reliability == 2 ||
packet.reliability == 3 ||
packet.reliability == 4 ||
packet.reliability == 6 ||
packet.reliability == 7) {
packet.messageIndex = this.messageIndex++;
if (packet.reliability == 3) {
int index = this.channelIndex.get(packet.orderChannel) + 1;
packet.orderIndex = index;
channelIndex.put(packet.orderChannel, index);
}
}
if (packet.getTotalLength() + 4 > this.mtuSize) {
byte[][] buffers = Binary.splitBytes(packet.buffer, this.mtuSize - 34);
int splitID = ++this.splitID % 65536;
for (int count = 0; count < buffers.length; count++) {
byte[] buffer = buffers[count];
EncapsulatedPacket pk = new EncapsulatedPacket();
pk.splitID = splitID;
pk.hasSplit = true;
pk.splitCount = buffers.length;
pk.reliability = packet.reliability;
pk.splitIndex = count;
pk.buffer = buffer;
if (count > 0) {
pk.messageIndex = this.messageIndex++;
} else {
pk.messageIndex = packet.messageIndex;
}
if (pk.reliability == 3) {
pk.orderChannel = packet.orderChannel;
pk.orderIndex = packet.orderIndex;
}
this.addToQueue(pk, flags | RakNet.PRIORITY_IMMEDIATE);
}
} else {
this.addToQueue(packet, flags);
}
}
private void handleSplit(EncapsulatedPacket packet) throws Exception {
if (packet.splitCount >= MAX_SPLIT_SIZE || packet.splitIndex >= MAX_SPLIT_SIZE || packet.splitIndex < 0) {
return;
}
if (!this.splitPackets.containsKey(packet.splitID)) {
if (this.splitPackets.size() >= MAX_SPLIT_COUNT) {
return;
}
this.splitPackets.put(packet.splitID, new HashMap<Integer, EncapsulatedPacket>() {{
put(packet.splitIndex, packet);
}});
} else {
this.splitPackets.get(packet.splitID).put(packet.splitIndex, packet);
}
if (this.splitPackets.get(packet.splitID).size() == packet.splitCount) {
EncapsulatedPacket pk = new EncapsulatedPacket();
BinaryStream stream = new BinaryStream();
for (int i = 0; i < packet.splitCount; i++) {
stream.put(this.splitPackets.get(packet.splitID).get(i).buffer);
}
pk.buffer = stream.getBuffer();
pk.length = pk.buffer.length;
this.splitPackets.remove(packet.splitID);
this.handleEncapsulatedPacketRoute(pk);
}
}
private void handleEncapsulatedPacket(EncapsulatedPacket packet) throws Exception {
if (packet.messageIndex == null) {
this.handleEncapsulatedPacketRoute(packet);
} else {
if (packet.messageIndex < this.reliableWindowStart || packet.messageIndex > this.reliableWindowEnd) {
return;
}
if ((packet.messageIndex - this.lastReliableIndex) == 1) {
this.lastReliableIndex++;
this.reliableWindowStart++;
this.reliableWindowEnd++;
this.handleEncapsulatedPacketRoute(packet);
if (!this.reliableWindow.isEmpty()) {
TreeMap<Integer, EncapsulatedPacket> sortedMap = new TreeMap<>(this.reliableWindow);
for (int index : sortedMap.keySet()) {
EncapsulatedPacket pk = this.reliableWindow.get(index);
if ((index - this.lastReliableIndex) != 1) {
break;
}
this.lastReliableIndex++;
this.reliableWindowStart++;
this.reliableWindowEnd++;
this.handleEncapsulatedPacketRoute(pk);
this.reliableWindow.remove(index);
}
}
} else {
this.reliableWindow.put(packet.messageIndex, packet);
}
}
}
public int getState() {
return state;
}
public boolean isTemporal() {
return isTemporal;
}
private void handleEncapsulatedPacketRoute(EncapsulatedPacket packet) throws Exception {
if (this.sessionManager == null) {
return;
}
if (packet.hasSplit) {
if (this.state == STATE_CONNECTED) {
this.handleSplit(packet);
}
return;
}
byte id = packet.buffer[0];
if ((id & 0xff) < 0x80) { //internal data packet
if (state == STATE_CONNECTING_2) {
if (id == CLIENT_CONNECT_DataPacket.ID) {
CLIENT_CONNECT_DataPacket dataPacket = new CLIENT_CONNECT_DataPacket();
dataPacket.buffer = packet.buffer;
dataPacket.decode();
SERVER_HANDSHAKE_DataPacket pk = new SERVER_HANDSHAKE_DataPacket();
pk.address = this.address;
pk.port = this.port;
pk.sendPing = dataPacket.sendPing;
pk.sendPong = dataPacket.sendPing + 1000L;
pk.encode();
EncapsulatedPacket sendPacket = new EncapsulatedPacket();
sendPacket.reliability = 0;
sendPacket.buffer = pk.buffer;
this.addToQueue(sendPacket, RakNet.PRIORITY_IMMEDIATE);
} else if (id == CLIENT_HANDSHAKE_DataPacket.ID) {
CLIENT_HANDSHAKE_DataPacket dataPacket = new CLIENT_HANDSHAKE_DataPacket();
dataPacket.buffer = packet.buffer;
dataPacket.decode();
if (dataPacket.port == this.sessionManager.getPort() || !this.sessionManager.portChecking) {
this.state = STATE_CONNECTED; //FINALLY!
this.isTemporal = false;
this.sessionManager.openSession(this);
}
}
} else if (id == CLIENT_DISCONNECT_DataPacket.ID) {
disconnect("client disconnect");
} else if (id == PING_DataPacket.ID) {
PING_DataPacket dataPacket = new PING_DataPacket();
dataPacket.buffer = packet.buffer;
dataPacket.decode();
PONG_DataPacket pk = new PONG_DataPacket();
pk.pingID = dataPacket.pingID;
pk.encode();
EncapsulatedPacket sendPacket = new EncapsulatedPacket();
sendPacket.reliability = 0;
sendPacket.buffer = pk.buffer;
this.addToQueue(sendPacket);
//Latency measurement
PING_DataPacket pingPacket = new PING_DataPacket();
pingPacket.pingID = System.currentTimeMillis();
pingPacket.encode();
sendPacket = new EncapsulatedPacket();
sendPacket.reliability = 0;
sendPacket.buffer = pingPacket.buffer;
this.addToQueue(sendPacket);
} else if (id == PONG_DataPacket.ID) {
if (state == STATE_CONNECTED) {
PONG_DataPacket dataPacket = new PONG_DataPacket();
dataPacket.buffer = packet.buffer;
dataPacket.decode();
if (state == STATE_CONNECTED) {
PING_DataPacket pingPacket = new PING_DataPacket();
pingPacket.pingID = (System.currentTimeMillis() - dataPacket.pingID) / 10;
pingPacket.encode();
packet.buffer = pingPacket.buffer;
this.sessionManager.streamEncapsulated(this, packet);
}
}
}
} else if (state == STATE_CONNECTED) {
this.sessionManager.streamEncapsulated(this, packet);
} else {
//this.sessionManager.getLogger().notice("Received packet before connection: "+Binary.bytesToHexString(packet.buffer));
}
}
public void handlePacket(Packet packet) throws Exception {
this.isActive = true;
this.lastUpdate = System.currentTimeMillis();
if (this.state == STATE_CONNECTED || this.state == STATE_CONNECTING_2) {
if (((packet.buffer[0] & 0xff) >= 0x80 || (packet.buffer[0] & 0xff) <= 0x8f) && packet instanceof DataPacket) {
DataPacket dp = (DataPacket) packet;
dp.decode();
if (dp.seqNumber < this.windowStart || dp.seqNumber > this.windowEnd || this.receivedWindow.containsKey(dp.seqNumber)) {
return;
}
int diff = dp.seqNumber - this.lastSeqNumber;
this.NACKQueue.remove(dp.seqNumber);
this.ACKQueue.put(dp.seqNumber, dp.seqNumber);
this.receivedWindow.put(dp.seqNumber, dp.seqNumber);
if (diff != 1) {
for (int i = this.lastSeqNumber + 1; i < dp.seqNumber; i++) {
if (!this.receivedWindow.containsKey(i)) {
this.NACKQueue.put(i, i);
}
}
}
if (diff >= 1) {
this.lastSeqNumber = dp.seqNumber;
this.windowStart += diff;
this.windowEnd += diff;
}
for (Object pk : dp.packets) {
if (pk instanceof EncapsulatedPacket) {
this.handleEncapsulatedPacket((EncapsulatedPacket) pk);
}
}
} else {
if (packet instanceof ACK) {
packet.decode();
for (int seq : new ArrayList<>(((ACK) packet).packets.values())) {
if (this.recoveryQueue.containsKey(seq)) {
for (Object pk : this.recoveryQueue.get(seq).packets) {
if (pk instanceof EncapsulatedPacket && ((EncapsulatedPacket) pk).needACK && ((EncapsulatedPacket) pk).messageIndex != null) {
if (this.needACK.containsKey(((EncapsulatedPacket) pk).identifierACK)) {
this.needACK.get(((EncapsulatedPacket) pk).identifierACK).remove(((EncapsulatedPacket) pk).messageIndex);
}
}
}
this.recoveryQueue.remove(seq);
}
}
} else if (packet instanceof NACK) {
packet.decode();
for (int seq : new ArrayList<>(((NACK) packet).packets.values())) {
if (this.recoveryQueue.containsKey(seq)) {
DataPacket pk = this.recoveryQueue.get(seq);
pk.seqNumber = this.sendSeqNumber++;
this.packetToSend.add(pk);
this.recoveryQueue.remove(seq);
}
}
}
}
} else if ((packet.buffer[0] & 0xff) > 0x00 || (packet.buffer[0] & 0xff) < 0x80) { //Not Data packet :)
packet.decode();
if (packet instanceof OPEN_CONNECTION_REQUEST_1) {
//TODO: check protocol number and refuse connections
OPEN_CONNECTION_REPLY_1 pk = new OPEN_CONNECTION_REPLY_1();
pk.mtuSize = ((OPEN_CONNECTION_REQUEST_1) packet).mtuSize;
pk.serverID = sessionManager.getID();
this.sendPacket(pk);
this.state = STATE_CONNECTING_1;
} else if (this.state == STATE_CONNECTING_1 && packet instanceof OPEN_CONNECTION_REQUEST_2) {
this.id = ((OPEN_CONNECTION_REQUEST_2) packet).clientID;
if (((OPEN_CONNECTION_REQUEST_2) packet).serverPort == this.sessionManager.getPort() || !this.sessionManager.portChecking) {
this.mtuSize = Math.min(Math.abs(((OPEN_CONNECTION_REQUEST_2) packet).mtuSize), 1464); //Max size, do not allow creating large buffers to fill server memory
OPEN_CONNECTION_REPLY_2 pk = new OPEN_CONNECTION_REPLY_2();
pk.mtuSize = (short) this.mtuSize;
pk.serverID = this.sessionManager.getID();
pk.clientAddress = this.address;
pk.clientPort = this.port;
this.sendPacket(pk);
this.state = STATE_CONNECTING_2;
}
}
}
}
public void close() throws Exception {
byte[] data = new byte[]{0x60, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15}; //CLIENT_DISCONNECT packet 0x15
this.addEncapsulatedToQueue(EncapsulatedPacket.fromBinary(data));
this.sessionManager = null;
}
}
| 21,449 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DataPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/DataPacket.java | package cn.nukkit.raknet.protocol;
import cn.nukkit.utils.Binary;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class DataPacket extends Packet {
public ConcurrentLinkedQueue<Object> packets = new ConcurrentLinkedQueue<>();
public Integer seqNumber;
@Override
public void encode() {
super.encode();
this.putLTriad(this.seqNumber);
for (Object packet : this.packets) {
this.put(packet instanceof EncapsulatedPacket ? ((EncapsulatedPacket) packet).toBinary() : (byte[]) packet);
}
}
public int length() {
int length = 4;
for (Object packet : this.packets) {
length += packet instanceof EncapsulatedPacket ? ((EncapsulatedPacket) packet).getTotalLength() : ((byte[]) packet).length;
}
return length;
}
@Override
public void decode() {
super.decode();
this.seqNumber = this.getLTriad();
while (!this.feof()) {
byte[] data = Binary.subBytes(this.buffer, this.offset);
EncapsulatedPacket packet = EncapsulatedPacket.fromBinary(data, false);
this.offset += packet.getOffset();
if (packet.buffer.length == 0) {
break;
}
this.packets.add(packet);
}
}
@Override
public Packet clean() {
this.packets = new ConcurrentLinkedQueue<>();
this.seqNumber = null;
return super.clean();
}
@Override
public DataPacket clone() throws CloneNotSupportedException {
DataPacket packet = (DataPacket) super.clone();
packet.packets = new ConcurrentLinkedQueue<>(this.packets);
return packet;
}
}
| 1,771 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
EncapsulatedPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/EncapsulatedPacket.java | package cn.nukkit.raknet.protocol;
import cn.nukkit.utils.Binary;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class EncapsulatedPacket implements Cloneable {
public int reliability;
public boolean hasSplit = false;
public int length = 0;
public Integer messageIndex = null;
public Integer orderIndex = null;
public Integer orderChannel = null;
public Integer splitCount = null;
public Integer splitID = null;
public Integer splitIndex = null;
public byte[] buffer;
public boolean needACK = false;
public Integer identifierACK = null;
private int offset;
public int getOffset() {
return offset;
}
public static EncapsulatedPacket fromBinary(byte[] binary) {
return fromBinary(binary, false);
}
public static EncapsulatedPacket fromBinary(byte[] binary, boolean internal) {
EncapsulatedPacket packet = new EncapsulatedPacket();
int flags = binary[0] & 0xff;
packet.reliability = ((flags & 0b11100000) >> 5);
packet.hasSplit = (flags & 0b00010000) > 0;
int length, offset;
if (internal) {
length = Binary.readInt(Binary.subBytes(binary, 1, 4));
packet.identifierACK = Binary.readInt(Binary.subBytes(binary, 5, 4));
offset = 9;
} else {
length = (int) Math.ceil(((double) Binary.readShort(Binary.subBytes(binary, 1, 2)) / 8));
offset = 3;
packet.identifierACK = null;
}
if (packet.reliability > 0) {
if (packet.reliability >= 2 && packet.reliability != 5) {
packet.messageIndex = Binary.readLTriad(Binary.subBytes(binary, offset, 3));
offset += 3;
}
if (packet.reliability <= 4 && packet.reliability != 2) {
packet.orderIndex = Binary.readLTriad(Binary.subBytes(binary, offset, 3));
offset += 3;
packet.orderChannel = binary[offset++] & 0xff;
}
}
if (packet.hasSplit) {
packet.splitCount = Binary.readInt(Binary.subBytes(binary, offset, 4));
offset += 4;
packet.splitID = Binary.readShort(Binary.subBytes(binary, offset, 2));
offset += 2;
packet.splitIndex = Binary.readInt(Binary.subBytes(binary, offset, 4));
offset += 4;
}
packet.buffer = Binary.subBytes(binary, offset, length);
offset += length;
packet.offset = offset;
return packet;
}
public int getTotalLength() {
return 3 + this.buffer.length + (this.messageIndex != null ? 3 : 0) + (this.orderIndex != null ? 4 : 0) + (this.hasSplit ? 10 : 0);
}
public byte[] toBinary() {
return toBinary(false);
}
public byte[] toBinary(boolean internal) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
stream.write((reliability << 5) | (hasSplit ? 0b00010000 : 0));
if (internal) {
stream.write(Binary.writeInt(buffer.length));
stream.write(Binary.writeInt(identifierACK == null ? 0 : identifierACK));
} else {
stream.write(Binary.writeShort(buffer.length << 3));
}
if (reliability > 0) {
if (reliability >= 2 && reliability != 5) {
stream.write(Binary.writeLTriad(messageIndex == null ? 0 : messageIndex));
}
if (reliability <= 4 && reliability != 2) {
stream.write(Binary.writeLTriad(orderIndex));
stream.write((byte) (orderChannel & 0xff));
}
}
if (hasSplit) {
stream.write(Binary.writeInt(splitCount));
stream.write(Binary.writeShort(splitID));
stream.write(Binary.writeInt(splitIndex));
}
stream.write(buffer);
} catch (IOException e) {
throw new RuntimeException(e);
}
return stream.toByteArray();
}
@Override
public String toString() {
return Binary.bytesToHexString(this.toBinary());
}
@Override
public EncapsulatedPacket clone() throws CloneNotSupportedException {
EncapsulatedPacket packet = (EncapsulatedPacket) super.clone();
packet.buffer = this.buffer.clone();
return packet;
}
}
| 4,526 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Packet.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/Packet.java | package cn.nukkit.raknet.protocol;
import cn.nukkit.utils.Binary;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class Packet implements Cloneable {
protected int offset = 0;
public byte[] buffer;
public Long sendTime;
public abstract byte getID();
protected byte[] get(int len) {
if (len < 0) {
this.offset = this.buffer.length - 1;
return new byte[0];
}
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = this.buffer[this.offset++];
}
return buffer;
}
protected byte[] getAll() {
return this.get();
}
protected byte[] get() {
try {
return Arrays.copyOfRange(this.buffer, this.offset, this.buffer.length - 1);
} catch (Exception e) {
return new byte[0];
}
}
protected long getLong() {
return Binary.readLong(this.get(8));
}
protected int getInt() {
return Binary.readInt(this.get(4));
}
protected short getSignedShort() {
return (short) this.getShort();
}
protected int getShort() {
return Binary.readShort(this.get(2));
}
protected int getTriad() {
return Binary.readTriad(this.get(3));
}
protected int getLTriad() {
return Binary.readLTriad(this.get(3));
}
protected byte getByte() {
return this.buffer[this.offset++];
}
protected String getString() {
return new String(this.get(this.getSignedShort()), StandardCharsets.UTF_8);
}
protected InetSocketAddress getAddress() {
byte version = this.getByte();
if (version == 4) {
String addr = ((~this.getByte()) & 0xff) + "." + ((~this.getByte()) & 0xff) + "." + ((~this.getByte()) & 0xff) + "." + ((~this.getByte()) & 0xff);
int port = this.getShort();
return new InetSocketAddress(addr, port);
} else {
//todo IPV6 SUPPORT
return null;
}
}
protected boolean feof() {
return !(this.offset >= 0 && this.offset + 1 <= this.buffer.length);
}
protected void put(byte[] b) {
this.buffer = Binary.appendBytes(this.buffer, b);
}
protected void putLong(long v) {
this.put(Binary.writeLong(v));
}
protected void putInt(int v) {
this.put(Binary.writeInt(v));
}
protected void putShort(int v) {
this.put(Binary.writeShort(v));
}
protected void putSignedShort(short v) {
this.put(Binary.writeShort(v & 0xffff));
}
protected void putTriad(int v) {
this.put(Binary.writeTriad(v));
}
protected void putLTriad(int v) {
this.put(Binary.writeLTriad(v));
}
protected void putByte(byte b) {
byte[] newBytes = new byte[this.buffer.length + 1];
System.arraycopy(this.buffer, 0, newBytes, 0, this.buffer.length);
newBytes[this.buffer.length] = b;
this.buffer = newBytes;
}
protected void putString(String str) {
byte[] b = str.getBytes(StandardCharsets.UTF_8);
this.putShort(b.length);
this.put(b);
}
protected void putAddress(String addr, int port) {
this.putAddress(addr, port, (byte) 4);
}
protected void putAddress(String addr, int port, byte version) {
this.putByte(version);
if (version == 4) {
for (String b : addr.split("\\.")) {
this.putByte((byte) ((~Integer.valueOf(b)) & 0xff));
}
this.putShort(port);
} else {
//todo ipv6
}
}
protected void putAddress(InetSocketAddress address) {
this.putAddress(address.getHostString(), address.getPort());
}
public void encode() {
this.buffer = new byte[]{getID()};
}
public void decode() {
this.offset = 1;
}
public Packet clean() {
this.buffer = null;
this.offset = 0;
this.sendTime = null;
return this;
}
@Override
public Packet clone() throws CloneNotSupportedException {
Packet packet = (Packet) super.clone();
packet.buffer = this.buffer.clone();
return packet;
}
/**
* A factory to create new packet instances
*/
public interface PacketFactory {
/**
* Creates the packet
*/
Packet create();
}
}
| 4,565 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
AcknowledgePacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/AcknowledgePacket.java | package cn.nukkit.raknet.protocol;
import cn.nukkit.utils.Binary;
import cn.nukkit.utils.BinaryStream;
import java.util.TreeMap;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class AcknowledgePacket extends Packet {
public TreeMap<Integer, Integer> packets;
@Override
public void encode() {
super.encode();
int count = this.packets.size();
int[] packets = new int[count];
int index = 0;
for (int i : this.packets.values()) {
packets[index++] = i;
}
short records = 0;
BinaryStream payload = new BinaryStream();
if (count > 0) {
int pointer = 1;
int start = packets[0];
int last = packets[0];
while (pointer < count) {
int current = packets[pointer++];
int diff = current - last;
if (diff == 1) {
last = current;
} else if (diff > 1) {
if (start == last) {
payload.putByte((byte) 0x01);
payload.put(Binary.writeLTriad(start));
start = last = current;
} else {
payload.putByte((byte) 0x00);
payload.put(Binary.writeLTriad(start));
payload.put(Binary.writeLTriad(last));
start = last = current;
}
++records;
}
}
if (start == last) {
payload.putByte((byte) 0x01);
payload.put(Binary.writeLTriad(start));
} else {
payload.putByte((byte) 0x00);
payload.put(Binary.writeLTriad(start));
payload.put(Binary.writeLTriad(last));
}
++records;
}
this.putShort(records);
this.buffer = Binary.appendBytes(
this.buffer,
payload.getBuffer()
);
}
@Override
public void decode() {
super.decode();
short count = this.getSignedShort();
this.packets = new TreeMap<>();
int cnt = 0;
for (int i = 0; i < count && !this.feof() && cnt < 4096; ++i) {
if (this.getByte() == 0) {
int start = this.getLTriad();
int end = this.getLTriad();
if ((end - start) > 512) {
end = start + 512;
}
for (int c = start; c <= end; ++c) {
packets.put(cnt++, c);
}
} else {
this.packets.put(cnt++, this.getLTriad());
}
}
}
@Override
public Packet clean() {
this.packets = new TreeMap<>();
return super.clean();
}
@Override
public AcknowledgePacket clone() throws CloneNotSupportedException {
AcknowledgePacket packet = (AcknowledgePacket) super.clone();
packet.packets = new TreeMap<>(this.packets);
return packet;
}
}
| 3,118 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PONG_DataPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/PONG_DataPacket.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class PONG_DataPacket extends Packet {
public static final byte ID = (byte) 0x03;
@Override
public byte getID() {
return ID;
}
public long pingID;
@Override
public void encode() {
super.encode();
this.putLong(this.pingID);
}
@Override
public void decode() {
super.decode();
this.pingID = this.getLong();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new PONG_DataPacket();
}
}
}
| 721 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_5.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_5.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_5 extends DataPacket {
public static final byte ID = (byte) 0x85;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_5();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_E.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_E.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_E extends DataPacket {
public static final byte ID = (byte) 0x8e;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_E();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
OPEN_CONNECTION_REPLY_1.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/OPEN_CONNECTION_REPLY_1.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.RakNet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class OPEN_CONNECTION_REPLY_1 extends Packet {
public static final byte ID = (byte) 0x06;
@Override
public byte getID() {
return ID;
}
public long serverID;
public short mtuSize;
@Override
public void encode() {
super.encode();
this.put(RakNet.MAGIC);
this.putLong(this.serverID);
this.putByte((byte) 0); //server security
this.putShort(this.mtuSize);
}
@Override
public void decode() {
super.decode();
this.offset += 16; //skip magic bytes
this.serverID = this.getLong();
this.getByte(); //skip security
this.mtuSize = this.getSignedShort();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new OPEN_CONNECTION_REPLY_1();
}
}
}
| 1,052 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PING_DataPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/PING_DataPacket.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class PING_DataPacket extends Packet {
public static final byte ID = (byte) 0x00;
@Override
public byte getID() {
return ID;
}
public long pingID;
@Override
public void encode() {
super.encode();
this.putLong(this.pingID);
}
@Override
public void decode() {
super.decode();
this.pingID = this.getLong();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new PING_DataPacket();
}
}
}
| 721 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
UNCONNECTED_PING.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/UNCONNECTED_PING.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.RakNet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class UNCONNECTED_PING extends Packet {
public static final byte ID = (byte) 0x01;
@Override
public byte getID() {
return ID;
}
public long pingID;
@Override
public void encode() {
super.encode();
this.putLong(this.pingID);
this.put(RakNet.MAGIC);
}
@Override
public void decode() {
super.decode();
this.pingID = this.getLong();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new UNCONNECTED_PING();
}
}
}
| 787 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
SERVER_HANDSHAKE_DataPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/SERVER_HANDSHAKE_DataPacket.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
import java.net.InetSocketAddress;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class SERVER_HANDSHAKE_DataPacket extends Packet {
public static final byte ID = (byte) 0x10;
@Override
public byte getID() {
return ID;
}
public String address;
public int port;
public final InetSocketAddress[] systemAddresses = new InetSocketAddress[]{
new InetSocketAddress("127.0.0.1", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0),
new InetSocketAddress("0.0.0.0", 0)
};
public long sendPing;
public long sendPong;
@Override
public void encode() {
super.encode();
this.putAddress(new InetSocketAddress(this.address, this.port));
this.putShort(0);
for (int i = 0; i < 10; ++i) {
this.putAddress(this.systemAddresses[i]);
}
this.putLong(this.sendPing);
this.putLong(this.sendPong);
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new SERVER_HANDSHAKE_DataPacket();
}
}
}
| 1,569 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_4.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_4.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_4 extends DataPacket {
public static final byte ID = (byte) 0x84;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_4();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_D.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_D.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_D extends DataPacket {
public static final byte ID = (byte) 0x8d;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_D();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_7.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_7.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_7 extends DataPacket {
public static final byte ID = (byte) 0x87;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_7();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_F.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_F.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_F extends DataPacket {
public static final byte ID = (byte) 0x8f;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_F();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ACK.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/ACK.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.AcknowledgePacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ACK extends AcknowledgePacket {
public static final byte ID = (byte) 0xc0;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new ACK();
}
}
}
| 519 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
CLIENT_DISCONNECT_DataPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/CLIENT_DISCONNECT_DataPacket.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class CLIENT_DISCONNECT_DataPacket extends Packet {
public static final byte ID = (byte) 0x15;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new CLIENT_DISCONNECT_DataPacket();
}
}
}
| 505 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_0.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_0.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_0 extends DataPacket {
public static final byte ID = (byte) 0x80;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_0();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_3.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_3.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_3 extends DataPacket {
public static final byte ID = (byte) 0x83;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_3();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
NACK.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/NACK.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.AcknowledgePacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class NACK extends AcknowledgePacket {
public static final byte ID = (byte) 0xa0;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new NACK();
}
}
}
| 521 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_B.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_B.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_B extends DataPacket {
public static final byte ID = (byte) 0x8b;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_B();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
OPEN_CONNECTION_REPLY_2.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/OPEN_CONNECTION_REPLY_2.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.RakNet;
import cn.nukkit.raknet.protocol.Packet;
import java.net.InetSocketAddress;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class OPEN_CONNECTION_REPLY_2 extends Packet {
public static final byte ID = (byte) 0x08;
@Override
public byte getID() {
return ID;
}
public long serverID;
public String clientAddress;
public int clientPort;
public short mtuSize;
@Override
public void encode() {
super.encode();
this.put(RakNet.MAGIC);
this.putLong(this.serverID);
this.putAddress(this.clientAddress, this.clientPort);
this.putShort(this.mtuSize);
this.putByte((byte) 0); //server security
}
@Override
public void decode() {
super.decode();
this.offset += 16; //skip magic bytes
this.serverID = this.getLong();
InetSocketAddress address = this.getAddress();
this.clientAddress = address.getHostString();
this.clientPort = address.getPort();
this.mtuSize = this.getSignedShort();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new OPEN_CONNECTION_REPLY_2();
}
}
}
| 1,324 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ADVERTISE_SYSTEM.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/ADVERTISE_SYSTEM.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class ADVERTISE_SYSTEM extends UNCONNECTED_PONG {
public static final byte ID = (byte) 0x1d;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new ADVERTISE_SYSTEM();
}
}
}
| 491 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_8.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_8.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_8 extends DataPacket {
public static final byte ID = (byte) 0x88;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_8();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
OPEN_CONNECTION_REQUEST_1.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/OPEN_CONNECTION_REQUEST_1.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.RakNet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class OPEN_CONNECTION_REQUEST_1 extends Packet {
public static final byte ID = (byte) 0x05;
@Override
public byte getID() {
return ID;
}
public byte protocol = RakNet.PROTOCOL;
public short mtuSize;
@Override
public void encode() {
super.encode();
this.put(RakNet.MAGIC);
this.putByte(this.protocol);
this.put(new byte[this.mtuSize - 18]);
}
@Override
public void decode() {
super.decode();
this.offset += 16; //skip magic bytes
this.protocol = this.getByte();
this.mtuSize = (short) this.buffer.length;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new OPEN_CONNECTION_REQUEST_1();
}
}
}
| 1,000 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_C.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_C.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_C extends DataPacket {
public static final byte ID = (byte) 0x8c;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_C();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_A.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_A.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_A extends DataPacket {
public static final byte ID = (byte) 0x8a;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_A();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_1.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_1.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_1 extends DataPacket {
public static final byte ID = (byte) 0x81;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_1();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_9.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_9.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_9 extends DataPacket {
public static final byte ID = (byte) 0x89;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_9();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
CLIENT_CONNECT_DataPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/CLIENT_CONNECT_DataPacket.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class CLIENT_CONNECT_DataPacket extends Packet {
public static final byte ID = (byte) 0x09;
@Override
public byte getID() {
return ID;
}
public long clientID;
public long sendPing;
public boolean useSecurity = false;
@Override
public void encode() {
super.encode();
this.putLong(this.clientID);
this.putLong(this.sendPing);
this.putByte((byte) (this.useSecurity ? 1 : 0));
}
@Override
public void decode() {
super.decode();
this.clientID = this.getLong();
this.sendPing = this.getLong();
this.useSecurity = this.getByte() > 0;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new CLIENT_CONNECT_DataPacket();
}
}
}
| 994 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
OPEN_CONNECTION_REQUEST_2.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/OPEN_CONNECTION_REQUEST_2.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.RakNet;
import cn.nukkit.raknet.protocol.Packet;
import java.net.InetSocketAddress;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class OPEN_CONNECTION_REQUEST_2 extends Packet {
public static final byte ID = (byte) 0x07;
@Override
public byte getID() {
return ID;
}
public long clientID;
public String serverAddress;
public int serverPort;
public short mtuSize;
@Override
public void encode() {
super.encode();
this.put(RakNet.MAGIC);
this.putAddress(this.serverAddress, this.serverPort);
this.putShort(this.mtuSize);
this.putLong(this.clientID);
}
@Override
public void decode() {
super.decode();
this.offset += 16; //skip magic bytes
InetSocketAddress address = this.getAddress();
this.serverAddress = address.getHostString();
this.serverPort = address.getPort();
this.mtuSize = this.getSignedShort();
this.clientID = this.getLong();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new OPEN_CONNECTION_REQUEST_2();
}
}
}
| 1,278 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
CLIENT_HANDSHAKE_DataPacket.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/CLIENT_HANDSHAKE_DataPacket.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
import java.net.InetSocketAddress;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class CLIENT_HANDSHAKE_DataPacket extends Packet {
public static final byte ID = (byte) 0x13;
@Override
public byte getID() {
return ID;
}
public String address;
public int port;
public final InetSocketAddress[] systemAddresses = new InetSocketAddress[10];
public long sendPing;
public long sendPong;
@Override
public void encode() {
}
@Override
public void decode() {
super.decode();
InetSocketAddress addr = this.getAddress();
this.address = addr.getHostString();
this.port = addr.getPort();
for (int i = 0; i < 10; i++) {
this.systemAddresses[i] = this.getAddress();
}
this.sendPing = this.getLong();
this.sendPong = this.getLong();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new CLIENT_HANDSHAKE_DataPacket();
}
}
}
| 1,165 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_2.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_2.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_2 extends DataPacket {
public static final byte ID = (byte) 0x82;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_2();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
DATA_PACKET_6.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/DATA_PACKET_6.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.DataPacket;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class DATA_PACKET_6 extends DataPacket {
public static final byte ID = (byte) 0x86;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new DATA_PACKET_6();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
UNCONNECTED_PING_OPEN_CONNECTIONS.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/UNCONNECTED_PING_OPEN_CONNECTIONS.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class UNCONNECTED_PING_OPEN_CONNECTIONS extends UNCONNECTED_PING {
public static final byte ID = (byte) 0x02;
@Override
public byte getID() {
return ID;
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new UNCONNECTED_PING_OPEN_CONNECTIONS();
}
}
}
| 525 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
UNCONNECTED_PONG.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/raknet/protocol/packet/UNCONNECTED_PONG.java | package cn.nukkit.raknet.protocol.packet;
import cn.nukkit.raknet.RakNet;
import cn.nukkit.raknet.protocol.Packet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class UNCONNECTED_PONG extends Packet {
public static final byte ID = (byte) 0x1c;
@Override
public byte getID() {
return ID;
}
public long pingID;
public long serverID;
public String serverName;
@Override
public void encode() {
super.encode();
this.putLong(this.pingID);
this.putLong(this.serverID);
this.put(RakNet.MAGIC);
this.putString(this.serverName);
}
@Override
public void decode() {
super.decode();
this.pingID = this.getLong();
this.serverID = this.getLong();
this.offset += 16; //skip magic bytes todo:check magic?
this.serverName = this.getString();
}
public static final class Factory implements Packet.PacketFactory {
@Override
public Packet create() {
return new UNCONNECTED_PONG();
}
}
}
| 1,069 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityChest.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityChest.java | package cn.nukkit.blockentity;
import cn.nukkit.Player;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockAir;
import cn.nukkit.inventory.BaseInventory;
import cn.nukkit.inventory.ChestInventory;
import cn.nukkit.inventory.DoubleChestInventory;
import cn.nukkit.inventory.InventoryHolder;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.ListTag;
import java.util.HashSet;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class BlockEntityChest extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable {
protected ChestInventory inventory;
protected DoubleChestInventory doubleInventory = null;
public BlockEntityChest(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
this.inventory = new ChestInventory(this);
if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) {
this.namedTag.putList(new ListTag<CompoundTag>("Items"));
}
/* for (int i = 0; i < this.getSize(); i++) {
this.inventory.setItem(i, this.getItem(i));
} */
ListTag<CompoundTag> list = (ListTag<CompoundTag>) this.namedTag.getList("Items");
for (CompoundTag compound : list.getAll()) {
Item item = NBTIO.getItemHelper(compound);
this.inventory.slots.put(compound.getByte("Slot"), item);
}
super.initBlockEntity();
}
@Override
public void close() {
if (!this.closed) {
for (Player player : new HashSet<>(this.getInventory().getViewers())) {
player.removeWindow(this.getInventory());
}
for (Player player : new HashSet<>(this.getInventory().getViewers())) {
player.removeWindow(this.getRealInventory());
}
super.close();
}
}
@Override
public void saveNBT() {
this.namedTag.putList(new ListTag<CompoundTag>("Items"));
for (int index = 0; index < this.getSize(); index++) {
this.setItem(index, this.inventory.getItem(index));
}
}
@Override
public boolean isBlockEntityValid() {
// TODO: 2016/2/4 TRAPPED_CHEST?
return getBlock().getId() == Block.CHEST;
}
@Override
public int getSize() {
return 27;
}
protected int getSlotIndex(int index) {
ListTag<CompoundTag> list = this.namedTag.getList("Items", CompoundTag.class);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getByte("Slot") == index) {
return i;
}
}
return -1;
}
@Override
public Item getItem(int index) {
int i = this.getSlotIndex(index);
if (i < 0) {
return new ItemBlock(new BlockAir(), 0, 0);
} else {
CompoundTag data = (CompoundTag) this.namedTag.getList("Items").get(i);
return NBTIO.getItemHelper(data);
}
}
@Override
public void setItem(int index, Item item) {
int i = this.getSlotIndex(index);
CompoundTag d = NBTIO.putItemHelper(item, index);
// If item is air or count less than 0, remove the item from the "Items" list
if (item.getId() == Item.AIR || item.getCount() <= 0) {
if (i >= 0) {
this.namedTag.getList("Items").remove(i);
}
} else if (i < 0) {
// If it is less than i, then it is a new item, so we are going to add it at the end of the list
(this.namedTag.getList("Items", CompoundTag.class)).add(d);
} else {
// If it is more than i, then it is an update on a inventorySlot, so we are going to overwrite the item in the list
(this.namedTag.getList("Items", CompoundTag.class)).add(i, d);
}
}
@Override
public BaseInventory getInventory() {
if (this.doubleInventory == null && this.isPaired()) {
this.checkPairing();
}
return this.doubleInventory != null ? this.doubleInventory : this.inventory;
}
public ChestInventory getRealInventory() {
return inventory;
}
protected void checkPairing() {
BlockEntityChest pair = this.getPair();
if (pair != null) {
if (!pair.isPaired()) {
pair.createPair(this);
pair.checkPairing();
}
if (this.doubleInventory == null) {
if ((pair.x + ((int) pair.z << 15)) > (this.x + ((int) this.z << 15))) { //Order them correctly
this.doubleInventory = new DoubleChestInventory(pair, this);
} else {
this.doubleInventory = new DoubleChestInventory(this, pair);
}
}
} else {
this.doubleInventory = null;
this.namedTag.remove("pairx");
this.namedTag.remove("pairz");
}
}
@Override
public String getName() {
return this.hasName() ? this.namedTag.getString("CustomName") : "Chest";
}
@Override
public boolean hasName() {
return this.namedTag.contains("CustomName");
}
@Override
public void setName(String name) {
if (name == null || name.equals("")) {
this.namedTag.remove("CustomName");
return;
}
this.namedTag.putString("CustomName", name);
}
public boolean isPaired() {
return this.namedTag.contains("pairx") && this.namedTag.contains("pairz");
}
public BlockEntityChest getPair() {
if (this.isPaired()) {
BlockEntity blockEntity = this.getLevel().getBlockEntity(new Vector3(this.namedTag.getInt("pairx"), this.y, this.namedTag.getInt("pairz")));
if (blockEntity instanceof BlockEntityChest) {
return (BlockEntityChest) blockEntity;
}
}
return null;
}
public boolean pairWith(BlockEntityChest chest) {
if (this.isPaired() || chest.isPaired()) {
return false;
}
this.createPair(chest);
chest.spawnToAll();
this.spawnToAll();
this.checkPairing();
return true;
}
public void createPair(BlockEntityChest chest) {
this.namedTag.putInt("pairx", (int) chest.x);
this.namedTag.putInt("pairz", (int) chest.z);
chest.namedTag.putInt("pairx", (int) this.x);
chest.namedTag.putInt("pairz", (int) this.z);
}
public boolean unpair() {
if (!this.isPaired()) {
return false;
}
BlockEntityChest chest = this.getPair();
this.namedTag.remove("pairx");
this.namedTag.remove("pairz");
this.spawnToAll();
if (chest != null) {
chest.namedTag.remove("pairx");
chest.namedTag.remove("pairz");
chest.checkPairing();
chest.spawnToAll();
}
this.checkPairing();
return true;
}
@Override
public CompoundTag getSpawnCompound() {
CompoundTag c;
if (this.isPaired()) {
c = new CompoundTag()
.putString("id", BlockEntity.CHEST)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putInt("pairx", this.namedTag.getInt("pairx"))
.putInt("pairz", this.namedTag.getInt("pairz"));
} else {
c = new CompoundTag()
.putString("id", BlockEntity.CHEST)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z);
}
if (this.hasName()) {
c.put("CustomName", this.namedTag.get("CustomName"));
}
return c;
}
}
| 8,123 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityBrewingStand.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityBrewingStand.java | package cn.nukkit.blockentity;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockAir;
import cn.nukkit.block.BlockBrewingStand;
import cn.nukkit.event.inventory.BrewEvent;
import cn.nukkit.event.inventory.StartBrewEvent;
import cn.nukkit.inventory.BrewingInventory;
import cn.nukkit.inventory.BrewingRecipe;
import cn.nukkit.inventory.InventoryHolder;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.network.protocol.ContainerSetDataPacket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class BlockEntityBrewingStand extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable {
protected BrewingInventory inventory;
public static final int MAX_BREW_TIME = 400;
public int brewTime = MAX_BREW_TIME;
public int fuelTotal;
public int fuelAmount;
public static final List<Integer> ingredients = new ArrayList<Integer>() {
{
addAll(Arrays.asList(Item.NETHER_WART, Item.GOLD_NUGGET, Item.GHAST_TEAR, Item.GLOWSTONE_DUST, Item.REDSTONE_DUST, Item.GUNPOWDER, Item.MAGMA_CREAM, Item.BLAZE_POWDER, Item.GOLDEN_CARROT, Item.SPIDER_EYE, Item.FERMENTED_SPIDER_EYE, Item.GLISTERING_MELON, Item.SUGAR, Item.RAW_FISH));
}
};
public BlockEntityBrewingStand(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
inventory = new BrewingInventory(this);
if (!namedTag.contains("Items") || !(namedTag.get("Items") instanceof ListTag)) {
namedTag.putList(new ListTag<CompoundTag>("Items"));
}
for (int i = 0; i < getSize(); i++) {
inventory.setItem(i, this.getItem(i));
}
if (!namedTag.contains("CookTime") || namedTag.getShort("CookTime") > MAX_BREW_TIME) {
this.brewTime = MAX_BREW_TIME;
} else {
this.brewTime = namedTag.getShort("CookTime");
}
this.fuelAmount = namedTag.getShort("FuelAmount");
this.fuelTotal = namedTag.getShort("FuelTotal");
if (brewTime < MAX_BREW_TIME) {
this.scheduleUpdate();
}
super.initBlockEntity();
}
@Override
public String getName() {
return this.hasName() ? this.namedTag.getString("CustomName") : "Brewing Stand";
}
@Override
public boolean hasName() {
return namedTag.contains("CustomName");
}
@Override
public void setName(String name) {
if (name == null || name.equals("")) {
namedTag.remove("CustomName");
return;
}
namedTag.putString("CustomName", name);
}
@Override
public void close() {
if (!closed) {
for (Player player : new HashSet<>(getInventory().getViewers())) {
player.removeWindow(getInventory());
}
super.close();
}
}
@Override
public void saveNBT() {
namedTag.putList(new ListTag<CompoundTag>("Items"));
for (int index = 0; index < getSize(); index++) {
this.setItem(index, inventory.getItem(index));
}
namedTag.putShort("CookTime", brewTime);
namedTag.putShort("FuelAmount", this.fuelAmount);
namedTag.putShort("FuelTotal", this.fuelTotal);
}
@Override
public boolean isBlockEntityValid() {
return getBlock().getId() == Block.BREWING_STAND_BLOCK;
}
@Override
public int getSize() {
return 4;
}
protected int getSlotIndex(int index) {
ListTag<CompoundTag> list = this.namedTag.getList("Items", CompoundTag.class);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getByte("Slot") == index) {
return i;
}
}
return -1;
}
@Override
public Item getItem(int index) {
int i = this.getSlotIndex(index);
if (i < 0) {
return new ItemBlock(new BlockAir(), 0, 0);
} else {
CompoundTag data = (CompoundTag) this.namedTag.getList("Items").get(i);
return NBTIO.getItemHelper(data);
}
}
@Override
public void setItem(int index, Item item) {
int i = this.getSlotIndex(index);
CompoundTag d = NBTIO.putItemHelper(item, index);
if (item.getId() == Item.AIR || item.getCount() <= 0) {
if (i >= 0) {
this.namedTag.getList("Items").getAll().remove(i);
}
} else if (i < 0) {
(this.namedTag.getList("Items", CompoundTag.class)).add(d);
} else {
(this.namedTag.getList("Items", CompoundTag.class)).add(i, d);
}
}
@Override
public BrewingInventory getInventory() {
return inventory;
}
protected boolean checkIngredient(Item ingredient) {
return ingredients.contains(ingredient.getId());
}
@Override
public boolean onUpdate() {
if (closed) {
return false;
}
boolean ret = false;
Item ingredient = this.inventory.getIngredient();
boolean canBrew = false;
Item fuel = this.getInventory().getFuel();
if (this.fuelAmount <= 0 && fuel.getId() == Item.BLAZE_POWDER && fuel.getCount() > 0) {
fuel.count--;
this.fuelAmount = 20;
this.fuelTotal = 20;
this.inventory.setFuel(fuel);
this.sendFuel();
}
if (this.fuelAmount > 0) {
for (int i = 1; i <= 3; i++) {
if (this.inventory.getItem(i).getId() == Item.POTION) {
canBrew = true;
}
}
if (this.brewTime <= MAX_BREW_TIME && canBrew && ingredient.getCount() > 0) {
if (!this.checkIngredient(ingredient)) {
canBrew = false;
}
} else {
canBrew = false;
}
}
if (canBrew) {
if (this.brewTime == MAX_BREW_TIME) {
this.sendBrewTime();
StartBrewEvent e = new StartBrewEvent(this);
this.server.getPluginManager().callEvent(e);
if (e.isCancelled()) {
return false;
}
}
this.brewTime--;
if (this.brewTime <= 0) { //20 seconds
BrewEvent e = new BrewEvent(this);
this.server.getPluginManager().callEvent(e);
if (!e.isCancelled()) {
for (int i = 1; i <= 3; i++) {
Item potion = this.inventory.getItem(i);
BrewingRecipe recipe = Server.getInstance().getCraftingManager().matchBrewingRecipe(ingredient, potion);
if (recipe != null) {
this.inventory.setItem(i, recipe.getResult());
}
}
ingredient.count--;
this.inventory.setIngredient(ingredient);
this.fuelAmount--;
this.sendFuel();
}
this.brewTime = MAX_BREW_TIME;
}
ret = true;
} else {
this.brewTime = MAX_BREW_TIME;
}
//this.sendBrewTime();
lastUpdate = System.currentTimeMillis();
return ret;
}
protected void sendFuel() {
ContainerSetDataPacket pk = new ContainerSetDataPacket();
for (Player p : this.inventory.getViewers()) {
int windowId = p.getWindowId(this.inventory);
if (windowId > 0) {
pk.windowId = windowId;
pk.property = ContainerSetDataPacket.PROPERTY_BREWING_STAND_FUEL_AMOUNT;
pk.value = this.fuelAmount;
p.dataPacket(pk);
pk.property = ContainerSetDataPacket.PROPERTY_BREWING_STAND_FUEL_TOTAL;
pk.value = this.fuelTotal;
p.dataPacket(pk);
}
}
}
protected void sendBrewTime() {
ContainerSetDataPacket pk = new ContainerSetDataPacket();
pk.property = ContainerSetDataPacket.PROPERTY_BREWING_STAND_BREW_TIME;
pk.value = this.brewTime;
for (Player p : this.inventory.getViewers()) {
int windowId = p.getWindowId(this.inventory);
if (windowId > 0) {
pk.windowId = windowId;
p.dataPacket(pk);
}
}
}
public void updateBlock() {
Block block = this.getLevelBlock();
if (!(block instanceof BlockBrewingStand)) {
return;
}
int meta = 0;
for (int i = 1; i <= 3; ++i) {
Item potion = this.inventory.getItem(i);
if (potion.getId() == Item.POTION && potion.getCount() > 0) {
meta |= 1 << i;
}
}
block.setDamage(meta);
this.level.setBlock(block, block, false, false);
}
public int getFuel() {
return fuelAmount;
}
public void setFuel(int fuel) {
this.fuelAmount = fuel;
}
@Override
public CompoundTag getSpawnCompound() {
CompoundTag nbt = new CompoundTag()
.putString("id", BlockEntity.BREWING_STAND)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putShort("FuelTotal", this.fuelTotal)
.putShort("FuelAmount", this.fuelAmount);
if (this.brewTime < MAX_BREW_TIME) {
nbt.putShort("CookTime", this.brewTime);
}
if (this.hasName()) {
nbt.put("CustomName", namedTag.get("CustomName"));
}
return nbt;
}
} | 10,075 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityJukebox.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityJukebox.java | package cn.nukkit.blockentity;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemRecord;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.network.protocol.PlaySoundPacket;
import cn.nukkit.network.protocol.StopSoundPacket;
import java.util.Objects;
/**
* @author CreeperFace
*/
public class BlockEntityJukebox extends BlockEntitySpawnable {
private Item recordItem;
public BlockEntityJukebox(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (namedTag.contains("RecordItem")) {
this.recordItem = NBTIO.getItemHelper(namedTag.getCompound("RecordItem"));
} else {
this.recordItem = Item.get(0);
}
super.initBlockEntity();
}
@Override
public boolean isBlockEntityValid() {
return this.getLevel().getBlockIdAt(getFloorX(), getFloorY(), getFloorZ()) == Block.JUKEBOX;
}
public void setRecordItem(Item recordItem) {
Objects.requireNonNull(recordItem, "Record item cannot be null");
this.recordItem = recordItem;
}
public Item getRecordItem() {
return recordItem;
}
public void play() {
if (this.recordItem instanceof ItemRecord) {
PlaySoundPacket pk = new PlaySoundPacket();
pk.name = ((ItemRecord) this.recordItem).getSoundId();
pk.pitch = 1;
pk.volume = 1;
pk.x = getFloorX();
pk.y = getFloorY();
pk.z = getFloorZ();
Server.broadcastPacket(this.level.getPlayers().values(), pk);
}
}
public void stop() {
if (this.recordItem instanceof ItemRecord) {
StopSoundPacket pk = new StopSoundPacket();
pk.name = ((ItemRecord) this.recordItem).getSoundId();
Server.broadcastPacket(this.level.getPlayers().values(), pk);
}
}
public void dropItem() {
if (this.recordItem.getId() != 0) {
stop();
this.level.dropItem(this.up(), this.recordItem);
this.recordItem = Item.get(0);
}
}
@Override
public void saveNBT() {
super.saveNBT();
this.namedTag.putCompound("RecordItem", NBTIO.putItemHelper(this.recordItem));
}
@Override
public CompoundTag getSpawnCompound() {
return getDefaultCompound(this, JUKEBOX)
.putCompound("RecordItem", NBTIO.putItemHelper(this.recordItem));
}
}
| 2,616 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityEnchantTable.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityEnchantTable.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class BlockEntityEnchantTable extends BlockEntitySpawnable implements BlockEntityNameable {
public BlockEntityEnchantTable(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
public boolean isBlockEntityValid() {
return getBlock().getId() == Block.ENCHANT_TABLE;
}
@Override
public String getName() {
return this.hasName() ? this.namedTag.getString("CustomName") : "Enchanting Table";
}
@Override
public boolean hasName() {
return this.namedTag.contains("CustomName");
}
@Override
public void setName(String name) {
if (name == null || name.equals("")) {
this.namedTag.remove("CustomName");
return;
}
this.namedTag.putString("CustomName", name);
}
@Override
public CompoundTag getSpawnCompound() {
CompoundTag c = new CompoundTag()
.putString("id", BlockEntity.ENCHANT_TABLE)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z);
if (this.hasName()) {
c.put("CustomName", this.namedTag.get("CustomName"));
}
return c;
}
}
| 1,429 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityBeacon.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityBeacon.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
public class BlockEntityBeacon extends BlockEntitySpawnable {
public BlockEntityBeacon(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (!namedTag.contains("Lock")) {
namedTag.putString("Lock", "");
}
if (!namedTag.contains("Levels")) {
namedTag.putInt("Levels", 0);
}
if (!namedTag.contains("Primary")) {
namedTag.putInt("Primary", 0);
}
if (!namedTag.contains("Secondary")) {
namedTag.putInt("Secondary", 0);
}
scheduleUpdate();
super.initBlockEntity();
}
@Override
public boolean isBlockEntityValid() {
int blockID = getBlock().getId();
return blockID == Block.BEACON;
}
@Override
public CompoundTag getSpawnCompound() {
return new CompoundTag()
.putString("id", BlockEntity.BEACON)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putString("Lock", this.namedTag.getString("Lock"))
.putInt("Levels", this.namedTag.getInt("Levels"))
.putInt("Primary", this.namedTag.getInt("Primary"))
.putInt("Secondary", this.namedTag.getInt("Secondary"));
}
private long currentTick = 0;
@Override
public boolean onUpdate() {
//Only check every 100 ticks
if (currentTick++ % 100 != 0) {
return true;
}
setPowerLevel(calculatePowerLevel());
return true;
}
private static final int POWER_LEVEL_MAX = 4;
private int calculatePowerLevel() {
int tileX = getFloorX();
int tileY = getFloorY();
int tileZ = getFloorZ();
//The power level that we're testing for
for (int powerLevel = 1; powerLevel <= POWER_LEVEL_MAX; powerLevel++) {
int queryY = tileY - powerLevel; //Layer below the beacon block
for (int queryX = tileX - powerLevel; queryX <= tileX + powerLevel; queryX++) {
for (int queryZ = tileZ - powerLevel; queryZ <= tileZ + powerLevel; queryZ++) {
int testBlockId = level.getBlockIdAt(queryX, queryY, queryZ);
if (
testBlockId != Block.IRON_BLOCK &&
testBlockId != Block.GOLD_BLOCK &&
testBlockId != Block.EMERALD_BLOCK &&
testBlockId != Block.DIAMOND_BLOCK
) {
return powerLevel - 1;
}
}
}
}
return POWER_LEVEL_MAX;
}
public int getPowerLevel() {
return namedTag.getInt("Level");
}
public void setPowerLevel(int level) {
int currentLevel = getPowerLevel();
if (level != currentLevel) {
namedTag.putInt("Level", level);
chunk.setChanged();
this.spawnToAll();
}
}
}
| 3,276 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityFurnace.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityFurnace.java | package cn.nukkit.blockentity;
import cn.nukkit.Player;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockAir;
import cn.nukkit.block.BlockFurnace;
import cn.nukkit.block.BlockFurnaceBurning;
import cn.nukkit.event.inventory.FurnaceBurnEvent;
import cn.nukkit.event.inventory.FurnaceSmeltEvent;
import cn.nukkit.inventory.FurnaceInventory;
import cn.nukkit.inventory.FurnaceRecipe;
import cn.nukkit.inventory.InventoryHolder;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.network.protocol.ContainerSetDataPacket;
import java.util.HashSet;
/**
* @author MagicDroidX
*/
public class BlockEntityFurnace extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable {
protected FurnaceInventory inventory;
private int burnTime = 0;
private int burnDuration = 0;
private int cookTime = 0;
private int maxTime = 0;
public BlockEntityFurnace(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
this.inventory = new FurnaceInventory(this);
if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) {
this.namedTag.putList(new ListTag<CompoundTag>("Items"));
}
for (int i = 0; i < this.getSize(); i++) {
this.inventory.setItem(i, this.getItem(i));
}
if (!this.namedTag.contains("BurnTime") || this.namedTag.getShort("BurnTime") < 0) {
burnTime = 0;
} else {
burnTime = this.namedTag.getShort("BurnTime");
}
if (!this.namedTag.contains("CookTime") || this.namedTag.getShort("CookTime") < 0 || (this.namedTag.getShort("BurnTime") == 0 && this.namedTag.getShort("CookTime") > 0)) {
cookTime = 0;
} else {
cookTime = this.namedTag.getShort("CookTime");
}
if (!this.namedTag.contains("MaxTime")) {
maxTime = burnTime;
burnDuration = 0;
} else {
maxTime = this.namedTag.getShort("MaxTime");
}
if (this.namedTag.contains("BurnTicks")) {
burnDuration = this.namedTag.getShort("BurnTicks");
this.namedTag.remove("BurnTicks");
}
if (burnTime > 0) {
this.scheduleUpdate();
}
super.initBlockEntity();
}
@Override
public String getName() {
return this.hasName() ? this.namedTag.getString("CustomName") : "Furnace";
}
@Override
public boolean hasName() {
return this.namedTag.contains("CustomName");
}
@Override
public void setName(String name) {
if (name == null || name.equals("")) {
this.namedTag.remove("CustomName");
return;
}
this.namedTag.putString("CustomName", name);
}
@Override
public void close() {
if (!this.closed) {
for (Player player : new HashSet<>(this.getInventory().getViewers())) {
player.removeWindow(this.getInventory());
}
super.close();
}
}
@Override
public void saveNBT() {
this.namedTag.putList(new ListTag<CompoundTag>("Items"));
for (int index = 0; index < this.getSize(); index++) {
this.setItem(index, this.inventory.getItem(index));
}
this.namedTag.putShort("CookTime", cookTime);
this.namedTag.putShort("BurnTime", burnTime);
this.namedTag.putShort("BurnDuration", burnDuration);
this.namedTag.putShort("MaxTime", maxTime);
}
@Override
public boolean isBlockEntityValid() {
int blockID = getBlock().getId();
return blockID == Block.FURNACE || blockID == Block.BURNING_FURNACE;
}
@Override
public int getSize() {
return 3;
}
protected int getSlotIndex(int index) {
ListTag<CompoundTag> list = this.namedTag.getList("Items", CompoundTag.class);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getByte("Slot") == index) {
return i;
}
}
return -1;
}
@Override
public Item getItem(int index) {
int i = this.getSlotIndex(index);
if (i < 0) {
return new ItemBlock(new BlockAir(), 0, 0);
} else {
CompoundTag data = (CompoundTag) this.namedTag.getList("Items").get(i);
return NBTIO.getItemHelper(data);
}
}
@Override
public void setItem(int index, Item item) {
int i = this.getSlotIndex(index);
CompoundTag d = NBTIO.putItemHelper(item, index);
if (item.getId() == Item.AIR || item.getCount() <= 0) {
if (i >= 0) {
this.namedTag.getList("Items").getAll().remove(i);
}
} else if (i < 0) {
(this.namedTag.getList("Items", CompoundTag.class)).add(d);
} else {
(this.namedTag.getList("Items", CompoundTag.class)).add(i, d);
}
}
@Override
public FurnaceInventory getInventory() {
return inventory;
}
protected void checkFuel(Item fuel) {
FurnaceBurnEvent ev = new FurnaceBurnEvent(this, fuel, fuel.getFuelTime() == null ? 0 : fuel.getFuelTime());
if (ev.isCancelled()) {
return;
}
maxTime = ev.getBurnTime();
burnTime = ev.getBurnTime();
burnDuration = 0;
if (this.getBlock().getId() == Item.FURNACE) {
this.getLevel().setBlock(this, new BlockFurnaceBurning(this.getBlock().getDamage()), true);
}
if (burnTime > 0 && ev.isBurning()) {
fuel.setCount(fuel.getCount() - 1);
if (fuel.getCount() == 0) {
if (fuel.getId() == Item.BUCKET && fuel.getDamage() == 10) {
fuel.setDamage(0);
fuel.setCount(1);
} else {
fuel = new ItemBlock(new BlockAir(), 0, 0);
}
}
this.inventory.setFuel(fuel);
}
}
@Override
public boolean onUpdate() {
if (this.closed) {
return false;
}
this.timing.startTiming();
boolean ret = false;
Item fuel = this.inventory.getFuel();
Item raw = this.inventory.getSmelting();
Item product = this.inventory.getResult();
FurnaceRecipe smelt = this.server.getCraftingManager().matchFurnaceRecipe(raw);
boolean canSmelt = (smelt != null && raw.getCount() > 0 && ((smelt.getResult().equals(product, true) && product.getCount() < product.getMaxStackSize()) || product.getId() == Item.AIR));
if (burnTime <= 0 && canSmelt && fuel.getFuelTime() != null && fuel.getCount() > 0) {
this.checkFuel(fuel);
}
if (burnTime > 0) {
burnTime--;
burnDuration = (int) Math.ceil(burnTime / maxTime * 200);
if (smelt != null && canSmelt) {
cookTime++;
if (cookTime >= 200) {
product = Item.get(smelt.getResult().getId(), smelt.getResult().getDamage(), product.getCount() + 1);
FurnaceSmeltEvent ev = new FurnaceSmeltEvent(this, raw, product);
this.server.getPluginManager().callEvent(ev);
if (!ev.isCancelled()) {
this.inventory.setResult(ev.getResult());
raw.setCount(raw.getCount() - 1);
if (raw.getCount() == 0) {
raw = new ItemBlock(new BlockAir(), 0, 0);
}
this.inventory.setSmelting(raw);
}
cookTime -= 200;
}
} else if (burnTime <= 0) {
burnTime = 0;
cookTime = 0;
burnDuration = 0;
} else {
cookTime = 0;
}
ret = true;
} else {
if (this.getBlock().getId() == Item.BURNING_FURNACE) {
this.getLevel().setBlock(this, new BlockFurnace(this.getBlock().getDamage()), true);
}
burnTime = 0;
cookTime = 0;
burnDuration = 0;
}
for (Player player : this.getInventory().getViewers()) {
int windowId = player.getWindowId(this.getInventory());
if (windowId > 0) {
ContainerSetDataPacket pk = new ContainerSetDataPacket();
pk.windowId = windowId;
pk.property = ContainerSetDataPacket.PROPERTY_FURNACE_TICK_COUNT;
;
pk.value = cookTime;
player.dataPacket(pk);
pk = new ContainerSetDataPacket();
pk.windowId = windowId;
pk.property = ContainerSetDataPacket.PROPERTY_FURNACE_LIT_TIME;
pk.value = burnDuration;
player.dataPacket(pk);
}
}
this.lastUpdate = System.currentTimeMillis();
this.timing.stopTiming();
return ret;
}
@Override
public CompoundTag getSpawnCompound() {
CompoundTag c = new CompoundTag()
.putString("id", BlockEntity.FURNACE)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putShort("BurnDuration", burnDuration)
.putShort("BurnTime", burnTime)
.putShort("CookTime", cookTime);
if (this.hasName()) {
c.put("CustomName", this.namedTag.get("CustomName"));
}
return c;
}
}
| 9,896 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityCauldron.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityCauldron.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
import java.awt.*;
/**
* author: CreeperFace
* Nukkit Project
*/
public class BlockEntityCauldron extends BlockEntitySpawnable {
public BlockEntityCauldron(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (!namedTag.contains("PotionId")) {
namedTag.putShort("PotionId", 0xffff);
}
if (!namedTag.contains("SplashPotion")) {
namedTag.putByte("SplashPotion", 0);
}
super.initBlockEntity();
}
public int getPotionId() {
return namedTag.getShort("PotionId");
}
public void setPotionId(int potionId) {
namedTag.putShort("PotionId", potionId);
this.spawnToAll();
}
public boolean hasPotion() {
return getPotionId() != 0xffff;
}
public boolean isSplashPotion() {
return namedTag.getByte("SplashPotion") > 0;
}
public void setSplashPotion(boolean value) {
namedTag.putByte("SplashPotion", value ? 1 : 0);
}
public Color getCustomColor() {
if (isCustomColor()) {
int color = namedTag.getInt("CustomColor");
int red = (color >> 16) & 0xff;
int green = (color >> 8) & 0xff;
int blue = (color) & 0xff;
return new Color(red, green, blue);
}
return null;
}
public boolean isCustomColor() {
return namedTag.contains("CustomColor");
}
public void setCustomColor(Color color) {
setCustomColor(color.getRed(), color.getGreen(), color.getBlue());
}
public void setCustomColor(int r, int g, int b) {
int color = (r << 16 | g << 8 | b) & 0xffffff;
namedTag.putInt("CustomColor", color);
spawnToAll();
}
public void clearCustomColor() {
namedTag.remove("CustomColor");
spawnToAll();
}
@Override
public boolean isBlockEntityValid() {
return getBlock().getId() == Block.CAULDRON_BLOCK;
}
@Override
public CompoundTag getSpawnCompound() {
return new CompoundTag()
.putString("id", BlockEntity.CAULDRON)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putShort("PotionId", namedTag.getShort("PotionId"))
.putByte("SplashPotion", namedTag.getByte("SplashPotion"));
}
}
| 2,593 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityHopper.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityHopper.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockAir;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.item.EntityItem;
import cn.nukkit.inventory.HopperInventory;
import cn.nukkit.inventory.Inventory;
import cn.nukkit.inventory.InventoryHolder;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.math.AxisAlignedBB;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.SimpleAxisAlignedBB;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.ListTag;
/**
* Created by CreeperFace on 8.5.2017.
*/
public class BlockEntityHopper extends BlockEntitySpawnable implements InventoryHolder, BlockEntityContainer, BlockEntityNameable {
protected HopperInventory inventory;
public int transferCooldown = 8;
private AxisAlignedBB pickupArea;
public BlockEntityHopper(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (this.namedTag.contains("TransferCooldown")) {
this.transferCooldown = this.namedTag.getInt("TransferCooldown");
}
this.inventory = new HopperInventory(this);
if (!this.namedTag.contains("Items") || !(this.namedTag.get("Items") instanceof ListTag)) {
this.namedTag.putList(new ListTag<CompoundTag>("Items"));
}
for (int i = 0; i < this.getSize(); i++) {
this.inventory.setItem(i, this.getItem(i));
}
this.pickupArea = new SimpleAxisAlignedBB(this.x, this.y, this.z, this.x + 1, this.y + 2, this.z + 1);
this.scheduleUpdate();
super.initBlockEntity();
}
@Override
public boolean isBlockEntityValid() {
return this.level.getBlockIdAt(this.getFloorX(), this.getFloorY(), this.getFloorZ()) == Block.HOPPER_BLOCK;
}
@Override
public String getName() {
return this.hasName() ? this.namedTag.getString("CustomName") : "Furnace";
}
@Override
public boolean hasName() {
return this.namedTag.contains("CustomName");
}
@Override
public void setName(String name) {
if (name == null || name.equals("")) {
this.namedTag.remove("CustomName");
return;
}
this.namedTag.putString("CustomName", name);
}
public boolean isOnTransferCooldown() {
return this.transferCooldown > 0;
}
public void setTransferCooldown(int transferCooldown) {
this.transferCooldown = transferCooldown;
}
@Override
public int getSize() {
return 3;
}
protected int getSlotIndex(int index) {
ListTag<CompoundTag> list = this.namedTag.getList("Items", CompoundTag.class);
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getByte("Slot") == index) {
return i;
}
}
return -1;
}
@Override
public Item getItem(int index) {
int i = this.getSlotIndex(index);
if (i < 0) {
return new ItemBlock(new BlockAir(), 0, 0);
} else {
CompoundTag data = (CompoundTag) this.namedTag.getList("Items").get(i);
return NBTIO.getItemHelper(data);
}
}
@Override
public void setItem(int index, Item item) {
int i = this.getSlotIndex(index);
CompoundTag d = NBTIO.putItemHelper(item, index);
if (item.getId() == Item.AIR || item.getCount() <= 0) {
if (i >= 0) {
this.namedTag.getList("Items").getAll().remove(i);
}
} else if (i < 0) {
(this.namedTag.getList("Items", CompoundTag.class)).add(d);
} else {
(this.namedTag.getList("Items", CompoundTag.class)).add(i, d);
}
}
@Override
public void saveNBT() {
this.namedTag.putList(new ListTag<CompoundTag>("Items"));
for (int index = 0; index < this.getSize(); index++) {
this.setItem(index, this.inventory.getItem(index));
}
this.namedTag.putInt("TransferCooldown", this.transferCooldown);
}
@Override
public HopperInventory getInventory() {
return inventory;
}
@Override
public boolean onUpdate() {
if (this.closed) {
return false;
}
this.transferCooldown--;
if (!this.isOnTransferCooldown()) {
boolean transfer = this.transferItemsOut();
boolean pickup = this.pickupDroppedItems();
if (transfer || pickup) {
//this.setTransferCooldown(8); TODO: maybe we should update hopper every tick if nothing happens?
this.chunk.setChanged(true);
}
this.setTransferCooldown(8);
}
return true;
}
public boolean pickupDroppedItems() {
if (this.inventory.isFull()) {
return false;
}
boolean update = false;
for (Entity entity : this.level.getCollidingEntities(this.pickupArea)) {
if (!(entity instanceof EntityItem)) {
continue;
}
EntityItem itemEntity = (EntityItem) entity;
Item item = itemEntity.getItem();
if (item.getId() == 0 || item.getCount() < 1) {
continue;
}
int originalCount = item.getCount();
Item[] items = this.inventory.addItem(item);
if (items.length == 0) {
entity.close();
update = true;
continue;
}
if (items[0].getCount() != originalCount) {
update = true;
}
}
BlockEntity blockEntity = this.level.getBlockEntity(this.up());
if (blockEntity instanceof InventoryHolder) {
Inventory inv = ((InventoryHolder) blockEntity).getInventory();
for (int i = 0; i < inv.getSize(); i++) {
Item item = inv.getItem(i);
if (item.getId() != 0 && item.getCount() > 0) {
Item itemToAdd = item.clone();
itemToAdd.count = 1;
Item[] items = this.inventory.addItem(itemToAdd);
if (items.length >= 1) {
continue;
}
item.count--;
if (item.count <= 0) {
item = Item.get(0);
}
inv.setItem(i, item);
update = true;
break;
}
}
}
//TODO: check for minecart
return update;
}
public boolean transferItemsOut() {
if (this.inventory.isEmpty()) {
return false;
}
if (!(this.level.getBlockEntity(this.down()) instanceof BlockEntityHopper)) {
BlockEntity be = this.level.getBlockEntity(this.getSide(BlockFace.fromIndex(this.level.getBlockDataAt(this.getFloorX(), this.getFloorY(), this.getFloorZ()))));
if (be instanceof InventoryHolder) {
Inventory inventory = ((InventoryHolder) be).getInventory();
if (inventory.isFull()) {
return false;
}
for (int i = 0; i < inventory.getSize(); i++) {
Item item = this.inventory.getItem(i);
if (item.getId() != 0 && item.getCount() > 0) {
Item itemToAdd = item.clone();
itemToAdd.setCount(1);
Item[] items = inventory.addItem(itemToAdd);
if (items.length > 0) {
continue;
}
inventory.sendContents(inventory.getViewers()); //whats wrong?
item.count--;
this.inventory.setItem(i, item);
return true;
}
}
}
//TODO: check for minecart
}
return false;
}
@Override
public CompoundTag getSpawnCompound() {
CompoundTag c = new CompoundTag()
.putString("id", BlockEntity.HOPPER)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z);
if (this.hasName()) {
c.put("CustomName", this.namedTag.get("CustomName"));
}
return c;
}
}
| 8,602 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityBed.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityBed.java | package cn.nukkit.blockentity;
import cn.nukkit.item.Item;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.utils.DyeColor;
/**
* Created by CreeperFace on 2.6.2017.
*/
public class BlockEntityBed extends BlockEntitySpawnable {
public int color;
public BlockEntityBed(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (!this.namedTag.contains("color")) {
this.namedTag.putByte("color", 0);
}
this.color = this.namedTag.getByte("color");
super.initBlockEntity();
}
@Override
public boolean isBlockEntityValid() {
return this.level.getBlockIdAt(this.getFloorX(), this.getFloorY(), this.getFloorZ()) == Item.BED_BLOCK;
}
@Override
public void saveNBT() {
super.saveNBT();
this.namedTag.putByte("color", this.color);
}
@Override
public CompoundTag getSpawnCompound() {
return new CompoundTag()
.putString("id", BlockEntity.BED)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putByte("color", this.color);
}
public DyeColor getDyeColor() {
return DyeColor.getByWoolData(color);
}
}
| 1,367 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityItemFrame.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityItemFrame.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockAir;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
/**
* Created by Pub4Game on 03.07.2016.
*/
public class BlockEntityItemFrame extends BlockEntitySpawnable {
public BlockEntityItemFrame(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (!namedTag.contains("Item")) {
namedTag.putCompound("Item", NBTIO.putItemHelper(new ItemBlock(new BlockAir())));
}
if (!namedTag.contains("ItemRotation")) {
namedTag.putByte("ItemRotation", 0);
}
if (!namedTag.contains("ItemDropChance")) {
namedTag.putFloat("ItemDropChance", 1.0f);
}
this.level.updateComparatorOutputLevel(this);
super.initBlockEntity();
}
@Override
public String getName() {
return "Item Frame";
}
@Override
public boolean isBlockEntityValid() {
return this.getBlock().getId() == Block.ITEM_FRAME_BLOCK;
}
public int getItemRotation() {
return this.namedTag.getByte("ItemRotation");
}
public void setItemRotation(int itemRotation) {
this.namedTag.putByte("ItemRotation", itemRotation);
this.level.updateComparatorOutputLevel(this);
this.setChanged();
}
public Item getItem() {
CompoundTag NBTTag = this.namedTag.getCompound("Item");
return NBTIO.getItemHelper(NBTTag);
}
public void setItem(Item item) {
this.setItem(item, true);
}
public void setItem(Item item, boolean setChanged) {
this.namedTag.putCompound("Item", NBTIO.putItemHelper(item));
if (setChanged) {
this.setChanged();
}
this.level.updateComparatorOutputLevel(this);
}
public float getItemDropChance() {
return this.namedTag.getFloat("ItemDropChance");
}
public void setItemDropChance(float chance) {
this.namedTag.putFloat("ItemDropChance", chance);
}
private void setChanged() {
this.spawnToAll();
if (this.chunk != null) {
this.chunk.setChanged();
}
}
@Override
public CompoundTag getSpawnCompound() {
if (!this.namedTag.contains("Item")) {
this.setItem(new ItemBlock(new BlockAir()), false);
}
CompoundTag NBTItem = namedTag.getCompound("Item").copy();
NBTItem.setName("Item");
boolean item = NBTItem.getShort("id") == Item.AIR;
return new CompoundTag()
.putString("id", BlockEntity.ITEM_FRAME)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putCompound("Item", item ? NBTIO.putItemHelper(new ItemBlock(new BlockAir())) : NBTItem)
.putByte("ItemRotation", item ? 0 : this.getItemRotation());
// TODO: This crashes the client, why?
// .putFloat("ItemDropChance", this.getItemDropChance());
}
public int getAnalogOutput() {
return this.getItem() == null || this.getItem().getId() == 0 ? 0 : this.getItemRotation() % 8 + 1;
}
}
| 3,357 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityEnderChest.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityEnderChest.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
public class BlockEntityEnderChest extends BlockEntitySpawnable {
public BlockEntityEnderChest(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
public boolean isBlockEntityValid() {
return this.getBlock().getId() == Block.ENDER_CHEST;
}
@Override
public String getName() {
return "EnderChest";
}
@Override
public CompoundTag getSpawnCompound() {
return new CompoundTag()
.putString("id", BlockEntity.ENDER_CHEST)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z);
}
}
| 803 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityNameable.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityNameable.java | package cn.nukkit.blockentity;
/**
* 表达一个能被命名的事物的接口。<br>
* An interface describes an object that can be named.
*
* @author MagicDroidX(code) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public interface BlockEntityNameable {
/**
* 返回这个事物的名字。<br>
* Gets the name of this object.
*
* @return 这个事物的名字。<br>The name of this object.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
String getName();
/**
* 设置或更改这个事物的名字。<br>
* Changes the name of this object, or names it.
*
* @param name 这个事物的新名字。<br>The new name of this object.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void setName(String name);
/**
* 返回这个事物是否有名字。<br>
* Whether this object has a name.
*
* @return 如果有名字,返回 {@code true}。<br>{@code true} for this object has a name.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
boolean hasName();
}
| 1,125 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntitySpawnable.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntitySpawnable.java | package cn.nukkit.blockentity;
import cn.nukkit.Player;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.network.protocol.BlockEntityDataPacket;
import java.io.IOException;
import java.nio.ByteOrder;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class BlockEntitySpawnable extends BlockEntity {
public BlockEntitySpawnable(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
super.initBlockEntity();
this.spawnToAll();
}
public abstract CompoundTag getSpawnCompound();
public void spawnTo(Player player) {
if (this.closed) {
return;
}
CompoundTag tag = this.getSpawnCompound();
BlockEntityDataPacket pk = new BlockEntityDataPacket();
pk.x = (int) this.x;
pk.y = (int) this.y;
pk.z = (int) this.z;
try {
pk.namedTag = NBTIO.write(tag, ByteOrder.LITTLE_ENDIAN, true);
} catch (IOException e) {
throw new RuntimeException(e);
}
player.dataPacket(pk);
}
public void spawnToAll() {
if (this.closed) {
return;
}
for (Player player : this.getLevel().getChunkPlayers(this.chunk.getX(), this.chunk.getZ()).values()) {
if (player.spawned) {
this.spawnTo(player);
}
}
}
/**
* Called when a player updates a block entity's NBT data
* for example when writing on a sign.
*
* @return bool indication of success, will respawn the tile to the player if false.
*/
public boolean updateCompoundTag(CompoundTag nbt, Player player) {
return false;
}
}
| 1,805 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityPistonArm.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityPistonArm.java | package cn.nukkit.blockentity;
import cn.nukkit.entity.Entity;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.math.AxisAlignedBB;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.SimpleAxisAlignedBB;
import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.IntTag;
import cn.nukkit.nbt.tag.ListTag;
/**
* @author CreeperFace
*/
public class BlockEntityPistonArm extends BlockEntity {
public float progress = 1.0F;
public float lastProgress = 1.0F;
public BlockFace facing;
public boolean extending = false;
public boolean sticky = false;
public byte state = 1;
public byte newState = 1;
public Vector3 attachedBlock = null;
public boolean isMovable = true;
public boolean powered = false;
public BlockEntityPistonArm(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (namedTag.contains("Progress")) {
this.progress = namedTag.getFloat("Progress");
}
if (namedTag.contains("LastProgress")) {
this.lastProgress = (float) namedTag.getInt("LastProgress");
}
if (namedTag.contains("Sticky")) {
this.sticky = namedTag.getBoolean("Sticky");
}
if (namedTag.contains("Extending")) {
this.extending = namedTag.getBoolean("Extending");
}
if (namedTag.contains("powered")) {
this.powered = namedTag.getBoolean("powered");
}
if (namedTag.contains("AttachedBlocks")) {
ListTag blocks = namedTag.getList("AttachedBlocks", IntTag.class);
if (blocks != null && blocks.size() > 0) {
this.attachedBlock = new Vector3((double) ((IntTag) blocks.get(0)).getData(), (double) ((IntTag) blocks.get(1)).getData(), (double) ((IntTag) blocks.get(2)).getData());
}
} else {
namedTag.putList(new ListTag("AttachedBlocks"));
}
super.initBlockEntity();
}
private void pushEntities() {
float lastProgress = this.getExtendedProgress(this.lastProgress);
double x = (double) (lastProgress * (float) this.facing.getXOffset());
double y = (double) (lastProgress * (float) this.facing.getYOffset());
double z = (double) (lastProgress * (float) this.facing.getZOffset());
AxisAlignedBB bb = new SimpleAxisAlignedBB(x, y, z, x + 1.0D, y + 1.0D, z + 1.0D);
Entity[] entities = this.level.getCollidingEntities(bb);
if (entities.length != 0) {
;
}
}
private float getExtendedProgress(float progress) {
return this.extending ? progress - 1.0F : 1.0F - progress;
}
public boolean isBlockEntityValid() {
return true;
}
public void saveNBT() {
super.saveNBT();
this.namedTag.putBoolean("isMovable", this.isMovable);
this.namedTag.putByte("State", this.state);
this.namedTag.putByte("NewState", this.newState);
this.namedTag.putFloat("Progress", this.progress);
this.namedTag.putFloat("LastProgress", this.lastProgress);
this.namedTag.putBoolean("powered", this.powered);
}
public CompoundTag getSpawnCompound() {
return (new CompoundTag()).putString("id", "PistonArm").putInt("x", (int) this.x).putInt("y", (int) this.y).putInt("z", (int) this.z);
}
} | 3,431 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityComparator.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityComparator.java | package cn.nukkit.blockentity;
import cn.nukkit.block.BlockRedstoneComparator;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
/**
* @author CreeperFace
*/
public class BlockEntityComparator extends BlockEntity {
private int outputSignal;
public BlockEntityComparator(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
if (!nbt.contains("OutputSignal")) {
nbt.putInt("OutputSignal", 0);
}
this.outputSignal = nbt.getInt("OutputSignal");
}
@Override
public boolean isBlockEntityValid() {
return this.getLevelBlock() instanceof BlockRedstoneComparator;
}
public int getOutputSignal() {
return outputSignal;
}
public void setOutputSignal(int outputSignal) {
this.outputSignal = outputSignal;
}
@Override
public void saveNBT() {
super.saveNBT();
this.namedTag.putInt("OutputSignal", this.outputSignal);
}
}
| 986 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityContainer.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityContainer.java | package cn.nukkit.blockentity;
import cn.nukkit.item.Item;
/**
* 表达一个容器的接口。<br>
* An interface describes a container.
* <p>
* <p>{@code BlockEntityContainer}容器必须包含物品的{@code Item}对象。<br>
* A {@code BlockEntityContainer} must contain items as {@code Item} objects.</p>
*
* @author MagicDroidX(code) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @see BlockEntityChest
* @see BlockEntityFurnace
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public interface BlockEntityContainer {
/**
* 返回一个存储在容器里的物品的{@code Item}对象。<br>
* Returns an item that stores in this container, as an {@code Item} object.
*
* @param index 这个物品的索引序号。<br>The index number of this item.
* @return 这个物品的 {@code Item}对象。<br>An {@code Item} object for this item.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
Item getItem(int index);
/**
* 把一个物品存储进容器。<br>
* Sets or stores this item into this container.
* <p>
* <p>注意:如果这个容器相应的索引序号已经有了物品,那么新存储的物品将会替换原有的物品。<br>
* Notice: If there is already an item for this index number, the new item being stored will REPLACE the old one.</p>
*
* @param index 这个物品的索引序号。<br>The index number of this item.
* @param item 描述这个物品的 {@code Item}对象。<br>The {@code Item} object that describes this item.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void setItem(int index, Item item);
/**
* 返回这个容器最多能包含的物品数量。<br>
* Returns the max number of items that this container can contain.
*
* @return 最多能包含的物品数量。<br>The max number.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
int getSize();
}
| 1,956 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityFlowerPot.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityFlowerPot.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
/**
* Created by Snake1999 on 2016/2/4.
* Package cn.nukkit.blockentity in project Nukkit.
*/
public class BlockEntityFlowerPot extends BlockEntitySpawnable {
public BlockEntityFlowerPot(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (!namedTag.contains("item")) {
namedTag.putShort("item", 0);
}
if (!namedTag.contains("data")) {
if (namedTag.contains("mData")) {
namedTag.putInt("data", namedTag.getInt("mData"));
namedTag.remove("mData");
} else {
namedTag.putInt("data", 0);
}
}
super.initBlockEntity();
}
@Override
public boolean isBlockEntityValid() {
int blockID = getBlock().getId();
return blockID == Block.FLOWER_POT_BLOCK;
}
@Override
public CompoundTag getSpawnCompound() {
return new CompoundTag()
.putString("id", BlockEntity.FLOWER_POT)
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.putShort("item", this.namedTag.getShort("item"))
.putInt("mData", this.namedTag.getInt("data"));
}
}
| 1,452 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntitySign.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntitySign.java | package cn.nukkit.blockentity;
import cn.nukkit.Player;
import cn.nukkit.block.Block;
import cn.nukkit.event.block.SignChangeEvent;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.utils.TextFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class BlockEntitySign extends BlockEntitySpawnable {
public BlockEntitySign(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (!namedTag.contains("Text")) {
List<String> lines = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
String key = "Text" + i;
if (namedTag.contains(key)) {
String line = namedTag.getString(key);
lines.add(line);
namedTag.remove(key);
}
}
namedTag.putString("Text", String.join("\n", lines));
}
super.initBlockEntity();
}
@Override
public void saveNBT() {
super.saveNBT();
this.namedTag.remove("Creator");
}
@Override
public boolean isBlockEntityValid() {
int blockID = getBlock().getId();
return blockID == Block.SIGN_POST || blockID == Block.WALL_SIGN;
}
public boolean setText(String... lines) {
this.namedTag.putString("Text", String.join("\n", lines));
this.spawnToAll();
if (this.chunk != null) {
this.chunk.setChanged();
}
return true;
}
public String[] getText() {
return this.namedTag.getString("Text").split("\n");
}
@Override
public boolean updateCompoundTag(CompoundTag nbt, Player player) {
if (!nbt.getString("id").equals(BlockEntity.SIGN)) {
return false;
}
String[] text = nbt.getString("Text").split("\n", 4);
SignChangeEvent signChangeEvent = new SignChangeEvent(this.getBlock(), player, text);
if (!this.namedTag.contains("Creator") || !Objects.equals(player.getUniqueId().toString(), this.namedTag.getString("Creator"))) {
signChangeEvent.setCancelled();
}
if (player.getRemoveFormat()) {
for (int i = 0; i < text.length; i++) {
text[i] = TextFormat.clean(text[i]);
}
}
this.server.getPluginManager().callEvent(signChangeEvent);
if (!signChangeEvent.isCancelled()) {
this.setText(signChangeEvent.getLines());
return true;
}
return false;
}
@Override
public CompoundTag getSpawnCompound() {
return new CompoundTag()
.putString("id", BlockEntity.SIGN)
.putString("Text", this.namedTag.getString("Text"))
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z);
}
}
| 3,030 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntity.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntity.java | package cn.nukkit.blockentity;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.level.Position;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.utils.ChunkException;
import cn.nukkit.utils.MainLogger;
import co.aikar.timings.Timing;
import co.aikar.timings.Timings;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
/**
* @author MagicDroidX
*/
public abstract class BlockEntity extends Position {
//WARNING: DO NOT CHANGE ANY NAME HERE, OR THE CLIENT WILL CRASH
public static final String CHEST = "Chest";
public static final String ENDER_CHEST = "EnderChest";
public static final String FURNACE = "Furnace";
public static final String SIGN = "Sign";
public static final String MOB_SPAWNER = "MobSpawner";
public static final String ENCHANT_TABLE = "EnchantTable";
public static final String SKULL = "Skull";
public static final String FLOWER_POT = "FlowerPot";
public static final String BREWING_STAND = "BrewingStand";
public static final String DAYLIGHT_DETECTOR = "DaylightDetector";
public static final String MUSIC = "Music";
public static final String ITEM_FRAME = "ItemFrame";
public static final String CAULDRON = "Cauldron";
public static final String BEACON = "Beacon";
public static final String PISTON_ARM = "PistonArm";
public static final String MOVING_BLOCK = "MovingBlock";
public static final String COMPARATOR = "Comparator";
public static final String HOPPER = "Hopper";
public static final String BED = "Bed";
public static final String JUKEBOX = "Jukebox";
public static long count = 1;
private static final Map<String, Class<? extends BlockEntity>> knownBlockEntities = new HashMap<>();
private static final Map<String, String> shortNames = new HashMap<>();
public FullChunk chunk;
public String name;
public long id;
public boolean movable = true;
public boolean closed = false;
public CompoundTag namedTag;
protected long lastUpdate;
protected Server server;
protected Timing timing;
public BlockEntity(FullChunk chunk, CompoundTag nbt) {
if (chunk == null || chunk.getProvider() == null) {
throw new ChunkException("Invalid garbage Chunk given to Block Entity");
}
this.timing = Timings.getBlockEntityTiming(this);
this.server = chunk.getProvider().getLevel().getServer();
this.chunk = chunk;
this.setLevel(chunk.getProvider().getLevel());
this.namedTag = nbt;
this.name = "";
this.lastUpdate = System.currentTimeMillis();
this.id = BlockEntity.count++;
this.x = this.namedTag.getInt("x");
this.y = this.namedTag.getInt("y");
this.z = this.namedTag.getInt("z");
this.movable = this.namedTag.getBoolean("isMovable");
this.initBlockEntity();
this.chunk.addBlockEntity(this);
this.getLevel().addBlockEntity(this);
}
protected void initBlockEntity() {
}
public static BlockEntity createBlockEntity(String type, FullChunk chunk, CompoundTag nbt, Object... args) {
type = type.replaceFirst("BlockEntity", ""); //TODO: Remove this after the first release
BlockEntity blockEntity = null;
if (knownBlockEntities.containsKey(type)) {
Class<? extends BlockEntity> clazz = knownBlockEntities.get(type);
if (clazz == null) {
return null;
}
for (Constructor constructor : clazz.getConstructors()) {
if (blockEntity != null) {
break;
}
if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) {
continue;
}
try {
if (args == null || args.length == 0) {
blockEntity = (BlockEntity) constructor.newInstance(chunk, nbt);
} else {
Object[] objects = new Object[args.length + 2];
objects[0] = chunk;
objects[1] = nbt;
System.arraycopy(args, 0, objects, 2, args.length);
blockEntity = (BlockEntity) constructor.newInstance(objects);
}
} catch (Exception e) {
MainLogger.getLogger().logException(e);
}
}
}
return blockEntity;
}
public static boolean registerBlockEntity(String name, Class<? extends BlockEntity> c) {
if (c == null) {
return false;
}
knownBlockEntities.put(name, c);
shortNames.put(c.getSimpleName(), name);
return true;
}
public final String getSaveId() {
String simpleName = getClass().getName();
simpleName = simpleName.substring(22, simpleName.length());
return shortNames.getOrDefault(simpleName, "");
}
public long getId() {
return id;
}
public void saveNBT() {
this.namedTag.putString("id", this.getSaveId());
this.namedTag.putInt("x", (int) this.getX());
this.namedTag.putInt("y", (int) this.getY());
this.namedTag.putInt("z", (int) this.getZ());
this.namedTag.putBoolean("isMovable", this.movable);
}
public CompoundTag getCleanedNBT() {
this.saveNBT();
CompoundTag tag = this.namedTag.clone();
tag.remove("x").remove("y").remove("z").remove("id");
if (tag.getTags().size() > 0) {
return tag;
} else {
return null;
}
}
public Block getBlock() {
return this.getLevelBlock();
}
public abstract boolean isBlockEntityValid();
public boolean onUpdate() {
return false;
}
public final void scheduleUpdate() {
this.level.updateBlockEntities.put(this.id, this);
}
public void close() {
if (!this.closed) {
this.closed = true;
this.level.updateBlockEntities.remove(this.id);
if (this.chunk != null) {
this.chunk.removeBlockEntity(this);
}
if (this.level != null) {
this.level.removeBlockEntity(this);
}
this.level = null;
}
}
public String getName() {
return name;
}
public boolean isMovable() {
return movable;
}
public static CompoundTag getDefaultCompound(Vector3 pos, String id) {
return new CompoundTag("")
.putString("id", id)
.putInt("x", pos.getFloorX())
.putInt("y", pos.getFloorY())
.putInt("z", pos.getFloorZ());
}
}
| 6,883 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntityMovingBlock.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntityMovingBlock.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.math.BlockVector3;
import cn.nukkit.nbt.tag.CompoundTag;
/**
* Created by CreeperFace on 11.4.2017.
*/
public class BlockEntityMovingBlock extends BlockEntitySpawnable {
public Block block;
public BlockVector3 piston;
public int progress;
public BlockEntityMovingBlock(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (namedTag.contains("movingBlockData") && namedTag.contains("movingBlockId")) {
this.block = Block.get(namedTag.getInt("movingBlockId"), namedTag.getInt("movingBlockData"));
} else {
this.close();
}
if (namedTag.contains("pistonPosX") && namedTag.contains("pistonPosY") && namedTag.contains("pistonPosZ")) {
this.piston = new BlockVector3(namedTag.getInt("pistonPosX"), namedTag.getInt("pistonPosY"), namedTag.getInt("pistonPosZ"));
} else {
this.close();
}
super.initBlockEntity();
}
public Block getBlock() {
return this.block;
}
@Override
public boolean isBlockEntityValid() {
return true;
}
@Override
public CompoundTag getSpawnCompound() {
return getDefaultCompound(this, MOVING_BLOCK)
.putFloat("movingBlockId", this.block.getId())
.putFloat("movingBlockData", this.block.getDamage())
.putInt("pistonPosX", this.piston.x)
.putInt("pistonPosY", this.piston.y)
.putInt("pistonPosZ", this.piston.z);
}
}
| 1,692 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockEntitySkull.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/blockentity/BlockEntitySkull.java | package cn.nukkit.blockentity;
import cn.nukkit.block.Block;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
/**
* Created by Snake1999 on 2016/2/3.
* Package cn.nukkit.blockentity in project Nukkit.
*/
public class BlockEntitySkull extends BlockEntitySpawnable {
public BlockEntitySkull(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
protected void initBlockEntity() {
if (!namedTag.contains("SkullType")) {
namedTag.putByte("SkullType", 0);
}
if (!namedTag.contains("Rot")) {
namedTag.putByte("Rot", 0);
}
super.initBlockEntity();
}
@Override
public void saveNBT() {
super.saveNBT();
this.namedTag.remove("Creator");
}
@Override
public boolean isBlockEntityValid() {
return getBlock().getId() == Block.SKULL_BLOCK;
}
@Override
public CompoundTag getSpawnCompound() {
return new CompoundTag()
.putString("id", BlockEntity.SKULL)
.put("SkullType", this.namedTag.get("SkullType"))
.putInt("x", (int) this.x)
.putInt("y", (int) this.y)
.putInt("z", (int) this.z)
.put("Rot", this.namedTag.get("Rot"));
}
} | 1,321 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginManager.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/PluginManager.java | package cn.nukkit.plugin;
import cn.nukkit.Server;
import cn.nukkit.command.PluginCommand;
import cn.nukkit.command.SimpleCommandMap;
import cn.nukkit.event.*;
import cn.nukkit.permission.Permissible;
import cn.nukkit.permission.Permission;
import cn.nukkit.utils.MainLogger;
import cn.nukkit.utils.PluginException;
import cn.nukkit.utils.Utils;
import co.aikar.timings.Timing;
import co.aikar.timings.Timings;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author MagicDroidX
*/
public class PluginManager {
private final Server server;
private final SimpleCommandMap commandMap;
protected final Map<String, Plugin> plugins = new LinkedHashMap<>();
protected final Map<String, Permission> permissions = new HashMap<>();
protected final Map<String, Permission> defaultPerms = new HashMap<>();
protected final Map<String, Permission> defaultPermsOp = new HashMap<>();
protected final Map<String, WeakHashMap<Permissible, Permissible>> permSubs = new HashMap<>();
protected final Map<Permissible, Permissible> defSubs = new WeakHashMap<>();
protected final Map<Permissible, Permissible> defSubsOp = new WeakHashMap<>();
protected final Map<String, PluginLoader> fileAssociations = new HashMap<>();
public PluginManager(Server server, SimpleCommandMap commandMap) {
this.server = server;
this.commandMap = commandMap;
}
public Plugin getPlugin(String name) {
if (this.plugins.containsKey(name)) {
return this.plugins.get(name);
}
return null;
}
public boolean registerInterface(Class<? extends PluginLoader> loaderClass) {
if (loaderClass != null) {
try {
Constructor constructor = loaderClass.getDeclaredConstructor(Server.class);
constructor.setAccessible(true);
this.fileAssociations.put(loaderClass.getName(), (PluginLoader) constructor.newInstance(this.server));
return true;
} catch (Exception e) {
return false;
}
}
return false;
}
public Map<String, Plugin> getPlugins() {
return plugins;
}
public Plugin loadPlugin(String path) {
return this.loadPlugin(path, null);
}
public Plugin loadPlugin(File file) {
return this.loadPlugin(file, null);
}
public Plugin loadPlugin(String path, Map<String, PluginLoader> loaders) {
return this.loadPlugin(new File(path), loaders);
}
public Plugin loadPlugin(File file, Map<String, PluginLoader> loaders) {
for (PluginLoader loader : (loaders == null ? this.fileAssociations : loaders).values()) {
for (Pattern pattern : loader.getPluginFilters()) {
if (pattern.matcher(file.getName()).matches()) {
PluginDescription description = loader.getPluginDescription(file);
if (description != null) {
try {
Plugin plugin = loader.loadPlugin(file);
if (plugin != null) {
this.plugins.put(plugin.getDescription().getName(), plugin);
List<PluginCommand> pluginCommands = this.parseYamlCommands(plugin);
if (!pluginCommands.isEmpty()) {
this.commandMap.registerAll(plugin.getDescription().getName(), pluginCommands);
}
return plugin;
}
} catch (Exception e) {
Server.getInstance().getLogger().debug("Could not load plugin", e);
return null;
}
}
}
}
}
return null;
}
public Map<String, Plugin> loadPlugins(String dictionary) {
return this.loadPlugins(new File(dictionary));
}
public Map<String, Plugin> loadPlugins(File dictionary) {
return this.loadPlugins(dictionary, null);
}
public Map<String, Plugin> loadPlugins(String dictionary, List<String> newLoaders) {
return this.loadPlugins(new File(dictionary), newLoaders);
}
public Map<String, Plugin> loadPlugins(File dictionary, List<String> newLoaders) {
return this.loadPlugins(dictionary, newLoaders, false);
}
public Map<String, Plugin> loadPlugins(File dictionary, List<String> newLoaders, boolean includeDir) {
if (dictionary.isDirectory()) {
Map<String, File> plugins = new LinkedHashMap<>();
Map<String, Plugin> loadedPlugins = new LinkedHashMap<>();
Map<String, List<String>> dependencies = new LinkedHashMap<>();
Map<String, List<String>> softDependencies = new LinkedHashMap<>();
Map<String, PluginLoader> loaders = new LinkedHashMap<>();
if (newLoaders != null) {
for (String key : newLoaders) {
if (this.fileAssociations.containsKey(key)) {
loaders.put(key, this.fileAssociations.get(key));
}
}
} else {
loaders = this.fileAssociations;
}
for (final PluginLoader loader : loaders.values()) {
for (File file : dictionary.listFiles((dir, name) -> {
for (Pattern pattern : loader.getPluginFilters()) {
if (pattern.matcher(name).matches()) {
return true;
}
}
return false;
})) {
if (file.isDirectory() && !includeDir) {
continue;
}
try {
PluginDescription description = loader.getPluginDescription(file);
if (description != null) {
String name = description.getName();
if (plugins.containsKey(name) || this.getPlugin(name) != null) {
this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin.duplicateError", name));
continue;
}
boolean compatible = false;
for (String version : description.getCompatibleAPIs()) {
//Check the format: majorVersion.minorVersion.patch
if (!Pattern.matches("[0-9]\\.[0-9]\\.[0-9]", version)) {
this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin.loadError", new String[]{name, "Wrong API format"}));
continue;
}
String[] versionArray = version.split("\\.");
String[] apiVersion = this.server.getApiVersion().split("\\.");
//Completely different API version
if (!Objects.equals(Integer.valueOf(versionArray[0]), Integer.valueOf(apiVersion[0]))) {
continue;
}
//If the plugin requires new API features, being backwards compatible
if (Integer.valueOf(versionArray[1]) > Integer.valueOf(apiVersion[1])) {
continue;
}
compatible = true;
break;
}
if (!compatible) {
this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin.loadError", new String[]{name, "%nukkit.plugin.incompatibleAPI"}));
}
plugins.put(name, file);
softDependencies.put(name, description.getSoftDepend());
dependencies.put(name, description.getDepend());
for (String before : description.getLoadBefore()) {
if (softDependencies.containsKey(before)) {
softDependencies.get(before).add(name);
} else {
List<String> list = new ArrayList<>();
list.add(name);
softDependencies.put(before, list);
}
}
}
} catch (Exception e) {
this.server.getLogger().error(this.server.getLanguage().translateString("nukkit.plugin" +
".fileError", file.getName(), dictionary.toString(), Utils
.getExceptionMessage(e)));
MainLogger logger = this.server.getLogger();
if (logger != null) {
logger.logException(e);
}
}
}
}
while (!plugins.isEmpty()) {
boolean missingDependency = true;
for (String name : new ArrayList<>(plugins.keySet())) {
File file = plugins.get(name);
if (dependencies.containsKey(name)) {
for (String dependency : new ArrayList<>(dependencies.get(name))) {
if (loadedPlugins.containsKey(dependency) || this.getPlugin(dependency) != null) {
dependencies.get(name).remove(dependency);
} else if (!plugins.containsKey(dependency)) {
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit" +
".plugin.loadError", new String[]{name, "%nukkit.plugin.unknownDependency"}));
break;
}
}
if (dependencies.get(name).isEmpty()) {
dependencies.remove(name);
}
}
if (softDependencies.containsKey(name)) {
for (String dependency : new ArrayList<>(softDependencies.get(name))) {
if (loadedPlugins.containsKey(dependency) || this.getPlugin(dependency) != null) {
softDependencies.get(name).remove(dependency);
}
}
if (softDependencies.get(name).isEmpty()) {
softDependencies.remove(name);
}
}
if (!dependencies.containsKey(name) && !softDependencies.containsKey(name)) {
plugins.remove(name);
missingDependency = false;
Plugin plugin = this.loadPlugin(file, loaders);
if (plugin != null) {
loadedPlugins.put(name, plugin);
} else {
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.genericLoadError", name));
}
}
}
if (missingDependency) {
for (String name : new ArrayList<>(plugins.keySet())) {
File file = plugins.get(name);
if (!dependencies.containsKey(name)) {
softDependencies.remove(name);
plugins.remove(name);
missingDependency = false;
Plugin plugin = this.loadPlugin(file, loaders);
if (plugin != null) {
loadedPlugins.put(name, plugin);
} else {
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.genericLoadError", name));
}
}
}
if (missingDependency) {
for (String name : plugins.keySet()) {
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.loadError", new String[]{name, "%nukkit.plugin.circularDependency"}));
}
plugins.clear();
}
}
}
return loadedPlugins;
} else {
return new HashMap<>();
}
}
public Permission getPermission(String name) {
if (this.permissions.containsKey(name)) {
return this.permissions.get(name);
}
return null;
}
public boolean addPermission(Permission permission) {
if (!this.permissions.containsKey(permission.getName())) {
this.permissions.put(permission.getName(), permission);
this.calculatePermissionDefault(permission);
return true;
}
return false;
}
public void removePermission(String name) {
this.permissions.remove(name);
}
public void removePermission(Permission permission) {
this.removePermission(permission.getName());
}
public Map<String, Permission> getDefaultPermissions(boolean op) {
if (op) {
return this.defaultPermsOp;
} else {
return this.defaultPerms;
}
}
public void recalculatePermissionDefaults(Permission permission) {
if (this.permissions.containsKey(permission.getName())) {
this.defaultPermsOp.remove(permission.getName());
this.defaultPerms.remove(permission.getName());
this.calculatePermissionDefault(permission);
}
}
private void calculatePermissionDefault(Permission permission) {
Timings.permissionDefaultTimer.startTiming();
if (permission.getDefault().equals(Permission.DEFAULT_OP) || permission.getDefault().equals(Permission.DEFAULT_TRUE)) {
this.defaultPermsOp.put(permission.getName(), permission);
this.dirtyPermissibles(true);
}
if (permission.getDefault().equals(Permission.DEFAULT_NOT_OP) || permission.getDefault().equals(Permission.DEFAULT_TRUE)) {
this.defaultPerms.put(permission.getName(), permission);
this.dirtyPermissibles(false);
}
Timings.permissionDefaultTimer.startTiming();
}
private void dirtyPermissibles(boolean op) {
for (Permissible p : this.getDefaultPermSubscriptions(op)) {
p.recalculatePermissions();
}
}
public void subscribeToPermission(String permission, Permissible permissible) {
if (!this.permSubs.containsKey(permission)) {
this.permSubs.put(permission, new WeakHashMap<>());
}
this.permSubs.get(permission).put(permissible, permissible);
}
public void unsubscribeFromPermission(String permission, Permissible permissible) {
if (this.permSubs.containsKey(permission)) {
this.permSubs.get(permission).remove(permissible);
if (this.permSubs.get(permission).size() == 0) {
this.permSubs.remove(permission);
}
}
}
public Set<Permissible> getPermissionSubscriptions(String permission) {
if (this.permSubs.containsKey(permission)) {
Set<Permissible> subs = new HashSet<>();
for (Permissible p : this.permSubs.get(permission).values()) {
subs.add(p);
}
return subs;
}
return new HashSet<>();
}
public void subscribeToDefaultPerms(boolean op, Permissible permissible) {
if (op) {
this.defSubsOp.put(permissible, permissible);
} else {
this.defSubs.put(permissible, permissible);
}
}
public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible) {
if (op) {
this.defSubsOp.remove(permissible);
} else {
this.defSubs.remove(permissible);
}
}
public Set<Permissible> getDefaultPermSubscriptions(boolean op) {
Set<Permissible> subs = new HashSet<>();
if (op) {
for (Permissible p : this.defSubsOp.values()) {
subs.add(p);
}
} else {
for (Permissible p : this.defSubs.values()) {
subs.add(p);
}
}
return subs;
}
public Map<String, Permission> getPermissions() {
return permissions;
}
public boolean isPluginEnabled(Plugin plugin) {
if (plugin != null && this.plugins.containsKey(plugin.getDescription().getName())) {
return plugin.isEnabled();
} else {
return false;
}
}
public void enablePlugin(Plugin plugin) {
if (!plugin.isEnabled()) {
try {
for (Permission permission : plugin.getDescription().getPermissions()) {
this.addPermission(permission);
}
plugin.getPluginLoader().enablePlugin(plugin);
} catch (Throwable e) {
MainLogger logger = this.server.getLogger();
if (logger != null) {
logger.logException(new RuntimeException(e));
}
this.disablePlugin(plugin);
}
}
}
protected List<PluginCommand> parseYamlCommands(Plugin plugin) {
List<PluginCommand> pluginCmds = new ArrayList<>();
for (Map.Entry entry : plugin.getDescription().getCommands().entrySet()) {
String key = (String) entry.getKey();
Object data = entry.getValue();
if (key.contains(":")) {
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.commandError", new String[]{key, plugin.getDescription().getFullName()}));
continue;
}
if (data instanceof Map) {
PluginCommand newCmd = new PluginCommand<>(key, plugin);
if (((Map) data).containsKey("description")) {
newCmd.setDescription((String) ((Map) data).get("description"));
}
if (((Map) data).containsKey("usage")) {
newCmd.setUsage((String) ((Map) data).get("usage"));
}
if (((Map) data).containsKey("aliases")) {
Object aliases = ((Map) data).get("aliases");
if (aliases instanceof List) {
List<String> aliasList = new ArrayList<>();
for (String alias : (List<String>) aliases) {
if (alias.contains(":")) {
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.aliasError", new String[]{alias, plugin.getDescription().getFullName()}));
continue;
}
aliasList.add(alias);
}
newCmd.setAliases(aliasList.stream().toArray(String[]::new));
}
}
if (((Map) data).containsKey("permission")) {
newCmd.setPermission((String) ((Map) data).get("permission"));
}
if (((Map) data).containsKey("permission-message")) {
newCmd.setPermissionMessage((String) ((Map) data).get("permission-message"));
}
pluginCmds.add(newCmd);
}
}
return pluginCmds;
}
public void disablePlugins() {
ListIterator<Plugin> plugins = new ArrayList<>(this.getPlugins().values()).listIterator(this.getPlugins().size());
while (plugins.hasPrevious()) {
this.disablePlugin(plugins.previous());
}
}
public void disablePlugin(Plugin plugin) {
if (plugin.isEnabled()) {
try {
plugin.getPluginLoader().disablePlugin(plugin);
} catch (Exception e) {
MainLogger logger = this.server.getLogger();
if (logger != null) {
logger.logException(e);
}
}
this.server.getScheduler().cancelTask(plugin);
HandlerList.unregisterAll(plugin);
for (Permission permission : plugin.getDescription().getPermissions()) {
this.removePermission(permission);
}
}
}
public void clearPlugins() {
this.disablePlugins();
this.plugins.clear();
this.fileAssociations.clear();
this.permissions.clear();
this.defaultPerms.clear();
this.defaultPermsOp.clear();
}
public void callEvent(Event event) {
try {
for (RegisteredListener registration : getEventListeners(event.getClass()).getRegisteredListeners()) {
if (!registration.getPlugin().isEnabled()) {
continue;
}
try {
registration.callEvent(event);
} catch (Exception e) {
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.plugin.eventError", event.getEventName(), registration.getPlugin().getDescription().getFullName(), e.getMessage(), registration.getListener().getClass().getName()));
this.server.getLogger().logException(e);
}
}
} catch (IllegalAccessException e) {
this.server.getLogger().logException(e);
}
}
public void registerEvents(Listener listener, Plugin plugin) {
if (!plugin.isEnabled()) {
throw new PluginException("Plugin attempted to register " + listener.getClass().getName() + " while not enabled");
}
Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<>();
Set<Method> methods;
try {
Method[] publicMethods = listener.getClass().getMethods();
Method[] privateMethods = listener.getClass().getDeclaredMethods();
methods = new HashSet<>(publicMethods.length + privateMethods.length, 1.0f);
Collections.addAll(methods, publicMethods);
Collections.addAll(methods, privateMethods);
} catch (NoClassDefFoundError e) {
plugin.getLogger().error("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist.");
return;
}
for (final Method method : methods) {
final EventHandler eh = method.getAnnotation(EventHandler.class);
if (eh == null) continue;
if (method.isBridge() || method.isSynthetic()) {
continue;
}
final Class<?> checkClass;
if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
plugin.getLogger().error(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass());
continue;
}
final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
method.setAccessible(true);
for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
// This loop checks for extending deprecated events
if (clazz.getAnnotation(Deprecated.class) != null) {
if (Boolean.valueOf(String.valueOf(this.server.getConfig("settings.deprecated-verbpse", true)))) {
this.server.getLogger().warning(this.server.getLanguage().translateString("nukkit.plugin.deprecatedEvent", plugin.getName(), clazz.getName(), listener.getClass().getName() + "." + method.getName() + "()"));
}
break;
}
}
this.registerEvent(eventClass, listener, eh.priority(), new MethodEventExecutor(method), plugin, eh.ignoreCancelled());
}
}
public void registerEvent(Class<? extends Event> event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) throws PluginException {
this.registerEvent(event, listener, priority, executor, plugin, false);
}
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);
}
}
private HandlerList getEventListeners(Class<? extends Event> type) throws IllegalAccessException {
try {
Method method = getRegistrationClass(type).getDeclaredMethod("getHandlers");
method.setAccessible(true);
return (HandlerList) method.invoke(null);
} catch (Exception e) {
throw new IllegalAccessException(Utils.getExceptionMessage(e));
}
}
private Class<? extends Event> getRegistrationClass(Class<? extends Event> clazz) throws IllegalAccessException {
try {
clazz.getDeclaredMethod("getHandlers");
return clazz;
} catch (NoSuchMethodException e) {
if (clazz.getSuperclass() != null
&& !clazz.getSuperclass().equals(Event.class)
&& Event.class.isAssignableFrom(clazz.getSuperclass())) {
return getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class));
} else {
throw new IllegalAccessException("Unable to find handler list for event " + clazz.getName() + ". Static getHandlers method required!");
}
}
}
}
| 27,281 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginClassLoader.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/PluginClassLoader.java | package cn.nukkit.plugin;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class PluginClassLoader extends URLClassLoader {
private JavaPluginLoader loader;
private final Map<String, Class> classes = new HashMap<>();
public PluginClassLoader(JavaPluginLoader loader, ClassLoader parent, File file) throws MalformedURLException {
super(new URL[]{file.toURI().toURL()}, parent);
this.loader = loader;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return this.findClass(name, true);
}
protected Class<?> findClass(String name, boolean checkGlobal) throws ClassNotFoundException {
if (name.startsWith("cn.nukkit.") || name.startsWith("net.minecraft.")) {
throw new ClassNotFoundException(name);
}
Class<?> result = classes.get(name);
if (result == null) {
if (checkGlobal) {
result = loader.getClassByName(name);
}
if (result == null) {
result = super.findClass(name);
if (result != null) {
loader.setClass(name, result);
}
}
classes.put(name, result);
}
return result;
}
Set<String> getClasses() {
return classes.keySet();
}
}
| 1,549 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginBase.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/PluginBase.java | package cn.nukkit.plugin;
import cn.nukkit.Server;
import cn.nukkit.command.Command;
import cn.nukkit.command.CommandSender;
import cn.nukkit.command.PluginIdentifiableCommand;
import cn.nukkit.utils.Config;
import cn.nukkit.utils.Utils;
import com.google.common.base.Preconditions;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
/**
* 一般的Nukkit插件需要继承的类。<br>
* A class to be extended by a normal Nukkit plugin.
*
* @author MagicDroidX(code) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @see cn.nukkit.plugin.PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
abstract public class PluginBase implements Plugin {
private PluginLoader loader;
private Server server;
private boolean isEnabled = false;
private boolean initialized = false;
private PluginDescription description;
private File dataFolder;
private Config config;
private File configFile;
private File file;
private PluginLogger logger;
public void onLoad() {
}
public void onEnable() {
}
public void onDisable() {
}
public final boolean isEnabled() {
return isEnabled;
}
/**
* 加载这个插件。<br>
* Enables this plugin.
* <p>
* <p>如果你需要卸载这个插件,建议使用{@link #setEnabled(boolean)}<br>
* If you need to disable this plugin, it's recommended to use {@link #setEnabled(boolean)}</p>
*
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public final void setEnabled() {
this.setEnabled(true);
}
/**
* 加载或卸载这个插件。<br>
* Enables or disables this plugin.
* <p>
* <p>插件管理器插件常常使用这个方法。<br>
* It's normally used by a plugin manager plugin to manage plugins.</p>
*
* @param value {@code true}为加载,{@code false}为卸载。<br>{@code true} for enable, {@code false} for disable.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public final void setEnabled(boolean value) {
if (isEnabled != value) {
isEnabled = value;
if (isEnabled) {
onEnable();
} else {
onDisable();
}
}
}
public final boolean isDisabled() {
return !isEnabled;
}
public final File getDataFolder() {
return dataFolder;
}
public final PluginDescription getDescription() {
return description;
}
/**
* 初始化这个插件。<br>
* Initialize the plugin.
* <p>
* <p>这个方法会在加载(load)之前被插件加载器调用,初始化关于插件的一些事项,不能被重写。<br>
* Called by plugin loader before load, and initialize the plugin. Can't be overridden.</p>
*
* @param loader 加载这个插件的插件加载器的{@code PluginLoader}对象。<br>
* The plugin loader ,which loads this plugin, as a {@code PluginLoader} object.
* @param server 运行这个插件的服务器的{@code Server}对象。<br>
* The server running this plugin, as a {@code Server} object.
* @param description 描述这个插件的{@code PluginDescription}对象。<br>
* A {@code PluginDescription} object that describes this plugin.
* @param dataFolder 这个插件的数据的文件夹。<br>
* The data folder of this plugin.
* @param file 这个插件的文件{@code File}对象。对于jar格式的插件,就是jar文件本身。<br>
* The {@code File} object of this plugin itself. For jar-packed plugins, it is the jar file itself.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public final void init(PluginLoader loader, Server server, PluginDescription description, File dataFolder, File file) {
if (!initialized) {
initialized = true;
this.loader = loader;
this.server = server;
this.description = description;
this.dataFolder = dataFolder;
this.file = file;
this.configFile = new File(this.dataFolder, "config.yml");
this.logger = new PluginLogger(this);
}
}
public PluginLogger getLogger() {
return logger;
}
/**
* 返回这个插件是否已经初始化。<br>
* Returns if this plugin is initialized.
*
* @return 这个插件是否已初始化。<br>if this plugin is initialized.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public final boolean isInitialized() {
return initialized;
}
/**
* TODO: FINISH JAVADOC
*/
public PluginIdentifiableCommand getCommand(String name) {
PluginIdentifiableCommand command = this.getServer().getPluginCommand(name);
if (command == null || !command.getPlugin().equals(this)) {
command = this.getServer().getPluginCommand(this.description.getName().toLowerCase() + ":" + name);
}
if (command != null && command.getPlugin().equals(this)) {
return command;
} else {
return null;
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return false;
}
@Override
public InputStream getResource(String filename) {
return this.getClass().getClassLoader().getResourceAsStream(filename);
}
@Override
public boolean saveResource(String filename) {
return saveResource(filename, false);
}
@Override
public boolean saveResource(String filename, boolean replace) {
return saveResource(filename, filename, replace);
}
@Override
public boolean saveResource(String filename, String outputName, boolean replace) {
Preconditions.checkArgument(filename != null && outputName != null, "Filename can not be null!");
Preconditions.checkArgument(filename.trim().length() != 0 && outputName.trim().length() != 0, "Filename can not be empty!");
File out = new File(dataFolder, outputName);
if (!out.exists() || replace) {
try (InputStream resource = getResource(filename)) {
if (resource != null) {
File outFolder = out.getParentFile();
if (!outFolder.exists()) {
outFolder.mkdirs();
}
Utils.writeFile(out, resource);
return true;
}
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
return false;
}
@Override
public Config getConfig() {
if (this.config == null) {
this.reloadConfig();
}
return this.config;
}
@Override
public void saveConfig() {
if (!this.getConfig().save()) {
this.getLogger().critical("Could not save config to " + this.configFile.toString());
}
}
@Override
public void saveDefaultConfig() {
if (!this.configFile.exists()) {
this.saveResource("config.yml", false);
}
}
@Override
public void reloadConfig() {
this.config = new Config(this.configFile);
InputStream configStream = this.getResource("config.yml");
if (configStream != null) {
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
try {
this.config.setDefault(yaml.loadAs(Utils.readFile(this.configFile), LinkedHashMap.class));
} catch (IOException e) {
Server.getInstance().getLogger().logException(e);
}
}
}
@Override
public Server getServer() {
return server;
}
@Override
public String getName() {
return this.description.getName();
}
/**
* 返回这个插件完整的名字。<br>
* Returns the full name of this plugin.
* <p>
* <p>一个插件完整的名字由{@code 名字+" v"+版本号}组成。比如:<br>
* A full name of a plugin is composed by {@code name+" v"+version}.for example:</p>
* <p>{@code HelloWorld v1.0.0}</p>
*
* @return 这个插件完整的名字。<br>The full name of this plugin.
* @see cn.nukkit.plugin.PluginDescription#getFullName
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public final String getFullName() {
return this.description.getFullName();
}
/**
* 返回这个插件的文件{@code File}对象。对于jar格式的插件,就是jar文件本身。<br>
* Returns the {@code File} object of this plugin itself. For jar-packed plugins, it is the jar file itself.
*
* @return 这个插件的文件 {@code File}对象。<br>The {@code File} object of this plugin itself.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
protected File getFile() {
return file;
}
@Override
public PluginLoader getPluginLoader() {
return this.loader;
}
}
| 9,435 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LibraryLoadException.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/LibraryLoadException.java | package cn.nukkit.plugin;
/**
* Created on 15-12-13.
*/
public class LibraryLoadException extends RuntimeException {
public LibraryLoadException(Library library) {
super("Load library " + library.getArtifactId() + " failed!");
}
}
| 252 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
LibraryLoader.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/LibraryLoader.java | package cn.nukkit.plugin;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.util.logging.Logger;
/**
* Created on 15-12-13.
*/
public class LibraryLoader {
private static final File BASE_FOLDER = new File("./libraries");
private static final Logger LOGGER = Logger.getLogger("LibraryLoader");
private static final String SUFFIX = ".jar";
static {
if (BASE_FOLDER.mkdir()) {
LOGGER.info("Created libraries folder.");
}
}
public static void load(String library) {
String[] split = library.split(":");
if (split.length != 3) {
throw new IllegalArgumentException(library);
}
load(new Library() {
public String getGroupId() {
return split[0];
}
public String getArtifactId() {
return split[1];
}
public String getVersion() {
return split[2];
}
});
}
public static void load(Library library) {
String filePath = library.getGroupId().replace('.', '/') + '/' + library.getArtifactId() + '/' + library.getVersion();
String fileName = library.getArtifactId() + '-' + library.getVersion() + SUFFIX;
File folder = new File(BASE_FOLDER, filePath);
if (folder.mkdirs()) {
LOGGER.info("Created " + folder.getPath() + '.');
}
File file = new File(folder, fileName);
if (!file.isFile()) try {
URL url = new URL("https://repo1.maven.org/maven2/" + filePath + '/' + fileName);
LOGGER.info("Get library from " + url + '.');
Files.copy(url.openStream(), file.toPath());
LOGGER.info("Get library " + fileName + " done!");
} catch (IOException e) {
throw new LibraryLoadException(library);
}
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
boolean accessible = method.isAccessible();
if (!accessible) {
method.setAccessible(true);
}
URLClassLoader classLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
URL url = file.toURI().toURL();
method.invoke(classLoader, url);
method.setAccessible(accessible);
} catch (NoSuchMethodException | MalformedURLException | IllegalAccessException | InvocationTargetException e) {
throw new LibraryLoadException(library);
}
LOGGER.info("Load library " + fileName + " done!");
}
public static File getBaseFolder() {
return BASE_FOLDER;
}
}
| 2,893 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
JavaPluginLoader.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/JavaPluginLoader.java | package cn.nukkit.plugin;
import cn.nukkit.Server;
import cn.nukkit.event.plugin.PluginDisableEvent;
import cn.nukkit.event.plugin.PluginEnableEvent;
import cn.nukkit.utils.PluginException;
import cn.nukkit.utils.Utils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
/**
* Created by Nukkit Team.
*/
public class JavaPluginLoader implements PluginLoader {
private final Server server;
private final Map<String, Class> classes = new HashMap<>();
private final Map<String, PluginClassLoader> classLoaders = new HashMap<>();
public JavaPluginLoader(Server server) {
this.server = server;
}
@Override
public Plugin loadPlugin(File file) throws Exception {
PluginDescription description = this.getPluginDescription(file);
if (description != null) {
this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.plugin.load", description.getFullName()));
File dataFolder = new File(file.getParentFile(), description.getName());
if (dataFolder.exists() && !dataFolder.isDirectory()) {
throw new IllegalStateException("Projected dataFolder '" + dataFolder.toString() + "' for " + description.getName() + " exists and is not a directory");
}
String className = description.getMain();
PluginClassLoader classLoader = new PluginClassLoader(this, this.getClass().getClassLoader(), file);
this.classLoaders.put(description.getName(), classLoader);
PluginBase plugin;
try {
Class javaClass = classLoader.loadClass(className);
try {
Class<? extends PluginBase> pluginClass = javaClass.asSubclass(PluginBase.class);
plugin = pluginClass.newInstance();
this.initPlugin(plugin, description, dataFolder, file);
return plugin;
} catch (ClassCastException e) {
throw new PluginException("main class `" + description.getMain() + "' does not extend PluginBase");
} catch (InstantiationException | IllegalAccessException e) {
Server.getInstance().getLogger().logException(e);
}
} catch (ClassNotFoundException e) {
throw new PluginException("Couldn't load plugin " + description.getName() + ": main class not found");
}
}
return null;
}
@Override
public Plugin loadPlugin(String filename) throws Exception {
return this.loadPlugin(new File(filename));
}
@Override
public PluginDescription getPluginDescription(File file) {
try (JarFile jar = new JarFile(file)) {
JarEntry entry = jar.getJarEntry("nukkit.yml");
if (entry == null) {
entry = jar.getJarEntry("plugin.yml");
if (entry == null) {
return null;
}
}
try (InputStream stream = jar.getInputStream(entry)) {
return new PluginDescription(Utils.readFile(stream));
}
} catch (IOException e) {
return null;
}
}
@Override
public PluginDescription getPluginDescription(String filename) {
return this.getPluginDescription(new File(filename));
}
@Override
public Pattern[] getPluginFilters() {
return new Pattern[]{Pattern.compile("^.+\\.jar$")};
}
private void initPlugin(PluginBase plugin, PluginDescription description, File dataFolder, File file) {
plugin.init(this, this.server, description, dataFolder, file);
plugin.onLoad();
}
@Override
public void enablePlugin(Plugin plugin) {
if (plugin instanceof PluginBase && !plugin.isEnabled()) {
this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.plugin.enable", plugin.getDescription().getFullName()));
((PluginBase) plugin).setEnabled(true);
this.server.getPluginManager().callEvent(new PluginEnableEvent(plugin));
}
}
@Override
public void disablePlugin(Plugin plugin) {
if (plugin instanceof PluginBase && plugin.isEnabled()) {
this.server.getLogger().info(this.server.getLanguage().translateString("nukkit.plugin.disable", plugin.getDescription().getFullName()));
this.server.getServiceManager().cancel(plugin);
this.server.getPluginManager().callEvent(new PluginDisableEvent(plugin));
((PluginBase) plugin).setEnabled(false);
}
}
Class<?> getClassByName(final String name) {
Class<?> cachedClass = classes.get(name);
if (cachedClass != null) {
return cachedClass;
} else {
for (PluginClassLoader loader : this.classLoaders.values()) {
try {
cachedClass = loader.findClass(name, false);
} catch (ClassNotFoundException e) {
//ignore
}
if (cachedClass != null) {
return cachedClass;
}
}
}
return null;
}
void setClass(final String name, final Class<?> clazz) {
if (!classes.containsKey(name)) {
classes.put(name, clazz);
}
}
private void removeClass(String name) {
Class<?> clazz = classes.remove(name);
}
}
| 5,662 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
MethodEventExecutor.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/MethodEventExecutor.java | package cn.nukkit.plugin;
import cn.nukkit.event.Event;
import cn.nukkit.event.Listener;
import cn.nukkit.utils.EventException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class MethodEventExecutor implements EventExecutor {
private final Method method;
public MethodEventExecutor(Method method) {
this.method = method;
}
@SuppressWarnings("unchecked")
@Override
public void execute(Listener listener, Event event) throws EventException {
try {
Class<Event>[] params = (Class<Event>[]) method.getParameterTypes();
for (Class<Event> param : params) {
if (param.isAssignableFrom(event.getClass())) {
method.invoke(listener, event);
break;
}
}
} catch (InvocationTargetException ex) {
throw new EventException(ex.getCause());
} catch (ClassCastException ex) {
// We are going to ignore ClassCastException because EntityDamageEvent can't be cast to EntityDamageByEntityEvent
} catch (Throwable t) {
throw new EventException(t);
}
}
public Method getMethod() {
return method;
}
} | 1,314 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
EventExecutor.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/EventExecutor.java | package cn.nukkit.plugin;
import cn.nukkit.event.Event;
import cn.nukkit.event.Listener;
import cn.nukkit.utils.EventException;
/**
* author: iNevet
* Nukkit Project
*/
public interface EventExecutor {
void execute(Listener listener, Event event) throws EventException;
}
| 282 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Plugin.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/Plugin.java | package cn.nukkit.plugin;
import cn.nukkit.Server;
import cn.nukkit.command.CommandExecutor;
import cn.nukkit.utils.Config;
import java.io.File;
import java.io.InputStream;
/**
* 所有Nukkit插件必须实现的接口。<br>
* An interface what must be implemented by all Nukkit plugins.
* <p>
* <p>对于插件作者,我们建议让插件主类继承{@link cn.nukkit.plugin.PluginBase}类,而不是实现这个接口。<br>
* For plugin developers: it's recommended to use {@link cn.nukkit.plugin.PluginBase} for an actual plugin
* instead of implement this interface.</p>
*
* @author MagicDroidX(code) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @see cn.nukkit.plugin.PluginBase
* @see cn.nukkit.plugin.PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public interface Plugin extends CommandExecutor {
/**
* 在一个Nukkit插件被加载时调用的方法。这个方法会在{@link Plugin#onEnable()}之前调用。<br>
* Called when a Nukkit plugin is loaded, before {@link Plugin#onEnable()} .
* <p>
* <p>应该填写加载插件时需要作出的动作。例如:初始化数组、初始化数据库连接。<br>
* Use this to init a Nukkit plugin, such as init arrays or init database connections.</p>
*
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void onLoad();
/**
* 在一个Nukkit插件被启用时调用的方法。<br>
* Called when a Nukkit plugin is enabled.
* <p>
* <p>应该填写插件启用时需要作出的动作。例如:读取配置文件、读取资源、连接数据库。<br>
* Use this to open config files, open resources, connect databases.</p>
* <p>
* <p>注意到可能存在的插件管理器插件,这个方法在插件多次重启时可能被调用多次。<br>
* Notes that there may be plugin manager plugins,
* this method can be called many times when a plugin is restarted many times.</p>
*
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void onEnable();
/**
* 返回这个Nukkit插件是否已启用。<br>
* Whether this Nukkit plugin is enabled.
*
* @return 这个插件是否已经启用。<br>Whether this plugin is enabled.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
boolean isEnabled();
/**
* 在一个Nukkit插件被停用时调用的方法。<br>
* Called when a Nukkit plugin is disabled.
* <p>
* <p>应该填写插件停用时需要作出的动作。例如:关闭数据库,断开资源。<br>
* Use this to free open things and finish actions,
* such as disconnecting databases and close resources.</p>
* <p>
* <p>注意到可能存在的插件管理器插件,这个方法在插件多次重启时可能被调用多次。<br>
* Notes that there may be plugin manager plugins,
* this method can be called many times when a plugin is restarted many times.</p>
*
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void onDisable();
/**
* 返回这个Nukkit插件是否已停用。<br>
* Whether this Nukkit plugin is disabled.
*
* @return 这个插件是否已经停用。<br>Whether this plugin is disabled.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
boolean isDisabled();
/**
* 返回这个Nukkit插件的数据文件夹。<br>
* The data folder of this Nukkit plugin.
* <p>
* <p>一般情况下,数据文件夹名字与插件名字相同,而且都放在nukkit安装目录下的plugins文件夹里。<br>
* Under normal circumstances, the data folder has the same name with the plugin,
* and is placed in the 'plugins' folder inside the nukkit installation directory.</p>
*
* @return 这个插件的数据文件夹。<br>The data folder of this plugin.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
File getDataFolder();
/**
* 返回描述这个Nukkit插件的{@link PluginDescription}对象。<br>
* The description this Nukkit plugin as a {@link PluginDescription} object.
* <p>
* <p>对于jar格式的Nukkit插件,插件的描述在plugin.yml文件内定义。<br>
* For jar-packed Nukkit plugins, the description is defined in the 'plugin.yml' file.</p>
*
* @return 这个插件的描述。<br>A description of this plugin.
* @see cn.nukkit.plugin.PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
PluginDescription getDescription();
/**
* 读取这个插件特定的资源文件,并返回为{@code InputStream}对象。<br>
* Reads a resource of this plugin, and returns as an {@code InputStream} object.
* <p>
* <p>对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹(一般为resources文件夹)寻找资源文件。<br>
* For jar-packed Nukkit plugins, Nukkit will look for your resource file in the resources folder,
* which is normally named 'resources' and placed in plugin jar file.</p>
* <p>
* <p>当你需要把一个文件的所有内容读取为字符串,可以使用{@link cn.nukkit.utils.Utils#readFile}函数,
* 来从{@code InputStream}读取所有内容为字符串。例如:<br>
* When you need to read the whole file content as a String, you can use {@link cn.nukkit.utils.Utils#readFile}
* to read from a {@code InputStream} and get whole content as a String. For example:</p>
* <p><code>String string = Utils.readFile(this.getResource("string.txt"));</code></p>
*
* @param filename 要读取的资源文件名字。<br>The name of the resource file to read.
* @return 读取的资源文件的 {@code InputStream}对象。若错误会返回{@code null}<br>
* The resource as an {@code InputStream} object, or {@code null} when an error occurred.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
InputStream getResource(String filename);
/**
* 保存这个Nukkit插件的资源。<br>
* Saves the resource of this plugin.
* <p>
* <p>对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹寻找资源文件,然后保存到数据文件夹。<br>
* For jar-packed Nukkit plugins, Nukkit will look for your resource file in the resources folder,
* which is normally named 'resources' and placed in plugin jar file, and copy it into data folder.</p>
* <p>
* <p>这个函数通常用来在插件被加载(load)时,保存默认的资源文件。这样插件在启用(enable)时不会错误读取空的资源文件,
* 用户也无需从开发者处手动下载资源文件后再使用插件。<br>
* This is usually used to save the default plugin resource when the plugin is LOADED .If this is used,
* it won't happen to load an empty resource when plugin is ENABLED, and plugin users are not required to get
* default resources from the developer and place it manually. </p>
* <p>
* <p>如果需要替换已存在的资源文件,建议使用{@link cn.nukkit.plugin.Plugin#saveResource(String, boolean)}<br>
* If you need to REPLACE an existing resource file, it's recommended
* to use {@link cn.nukkit.plugin.Plugin#saveResource(String, boolean)}.</p>
*
* @param filename 要保存的资源文件名字。<br>The name of the resource file to save.
* @return 保存是否成功。<br>true if the saving action is successful.
* @see cn.nukkit.plugin.Plugin#saveDefaultConfig
* @see cn.nukkit.plugin.Plugin#saveResource(String, boolean)
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
boolean saveResource(String filename);
/**
* 保存或替换这个Nukkit插件的资源。<br>
* Saves or replaces the resource of this plugin.
* <p>
* <p>对于jar格式的Nukkit插件,Nukkit会在jar包内的资源文件夹寻找资源文件,然后保存到数据文件夹。<br>
* For jar-packed Nukkit plugins, Nukkit will look for your resource file in the resources folder,
* which is normally named 'resources' and placed in plugin jar file, and copy it into data folder.</p>
* <p>
* <p>如果需要保存默认的资源文件,建议使用{@link cn.nukkit.plugin.Plugin#saveResource(String)}<br>
* If you need to SAVE DEFAULT resource file, it's recommended
* to use {@link cn.nukkit.plugin.Plugin#saveResource(String)}.</p>
*
* @param filename 要保存的资源文件名字。<br>The name of the resource file to save.
* @param replace 是否替换目标文件。<br>if true, Nukkit will replace the target resource file.
* @return 保存是否成功。<br>true if the saving action is successful.
* @see cn.nukkit.plugin.Plugin#saveResource(String)
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
boolean saveResource(String filename, boolean replace);
boolean saveResource(String filename, String outputName, boolean replace);
/**
* 返回这个Nukkit插件配置文件的{@link cn.nukkit.utils.Config}对象。<br>
* The config file this Nukkit plugin as a {@link cn.nukkit.utils.Config} object.
* <p>
* <p>一般地,插件的配置保存在数据文件夹下的config.yml文件。<br>
* Normally, the plugin config is saved in the 'config.yml' file in its data folder.</p>
*
* @return 插件的配置文件。<br>The configuration of this plugin.
* @see cn.nukkit.plugin.Plugin#getDataFolder
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
Config getConfig();
/**
* 保存这个Nukkit插件的配置文件。<br>
* Saves the plugin config.
*
* @see cn.nukkit.plugin.Plugin#getDataFolder
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void saveConfig();
/**
* 保存这个Nukkit插件的默认配置文件。<br>
* Saves the DEFAULT plugin config.
* <p>
* <p>执行这个函数时,Nukkit会在资源文件夹内寻找开发者配置好的默认配置文件config.yml,然后保存在数据文件夹。
* 如果数据文件夹已经有一个config.yml文件,Nukkit不会替换这个文件。<br>
* When this is used, Nukkit will look for the default 'config.yml' file which is configured by plugin developer
* and save it to the data folder. If a config.yml file exists in the data folder, Nukkit won't replace it.</p>
* <p>
* <p>这个函数通常用来在插件被加载(load)时,保存默认的配置文件。这样插件在启用(enable)时不会错误读取空的配置文件,
* 用户也无需从开发者处手动下载配置文件保存后再使用插件。<br>
* This is usually used to save the default plugin config when the plugin is LOADED .If this is used,
* it won't happen to load an empty config when plugin is ENABLED, and plugin users are not required to get
* default config from the developer and place it manually. </p>
*
* @see cn.nukkit.plugin.Plugin#getDataFolder
* @see cn.nukkit.plugin.Plugin#saveResource
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void saveDefaultConfig();
/**
* 重新读取这个Nukkit插件的默认配置文件。<br>
* Reloads the plugin config.
* <p>
* <p>执行这个函数时,Nukkit会从数据文件夹中的config.yml文件重新加载配置。
* 这样用户在调整插件配置后,无需重启就可以马上使用新的配置。<br>
* By using this, Nukkit will reload the config from 'config.yml' file, then it isn't necessary to restart
* for plugin user who changes the config and needs to use new config at once.</p>
*
* @see cn.nukkit.plugin.Plugin#getDataFolder
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void reloadConfig();
/**
* 返回运行这个插件的服务器的{@link cn.nukkit.Server}对象。<br>
* Gets the server which is running this plugin, and returns as a {@link cn.nukkit.Server} object.
*
* @see cn.nukkit.Server
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
Server getServer();
/**
* 返回这个插件的名字。<br>
* Returns the name of this plugin.
* <p>
* <p>Nukkit会从已经读取的插件描述中获取插件的名字。<br>
* Nukkit will read plugin name from plugin description.</p>
*
* @see cn.nukkit.plugin.Plugin#getDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
String getName();
/**
* 返回这个插件的日志记录器为{@link cn.nukkit.plugin.PluginLogger}对象。<br>
* Returns the logger of this plugin as a {@link cn.nukkit.plugin.PluginLogger} object.
* <p>
* <p>使用日志记录器,你可以在控制台和日志文件输出信息。<br>
* You can use a plugin logger to output messages to the console and log file.</p>
*
* @see cn.nukkit.plugin.PluginLogger
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
PluginLogger getLogger();
/**
* 返回这个插件的加载器为{@link cn.nukkit.plugin.PluginLoader}对象。<br>
* Returns the loader of this plugin as a {@link cn.nukkit.plugin.PluginLoader} object.
*
* @see cn.nukkit.plugin.PluginLoader
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
PluginLoader getPluginLoader();
}
| 13,363 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginLogger.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/PluginLogger.java | package cn.nukkit.plugin;
import cn.nukkit.Server;
import cn.nukkit.utils.LogLevel;
import cn.nukkit.utils.Logger;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class PluginLogger implements Logger {
private final String pluginName;
public PluginLogger(Plugin context) {
String prefix = context.getDescription().getPrefix();
this.pluginName = prefix != null ? "[" + prefix + "] " : "[" + context.getDescription().getName() + "] ";
}
@Override
public void emergency(String message) {
this.log(LogLevel.EMERGENCY, message);
}
@Override
public void alert(String message) {
this.log(LogLevel.ALERT, message);
}
@Override
public void critical(String message) {
this.log(LogLevel.CRITICAL, message);
}
@Override
public void error(String message) {
this.log(LogLevel.ERROR, message);
}
@Override
public void warning(String message) {
this.log(LogLevel.WARNING, message);
}
@Override
public void notice(String message) {
this.log(LogLevel.NOTICE, message);
}
@Override
public void info(String message) {
this.log(LogLevel.INFO, message);
}
@Override
public void debug(String message) {
this.log(LogLevel.DEBUG, message);
}
@Override
public void log(LogLevel level, String message) {
Server.getInstance().getLogger().log(level, this.pluginName + message);
}
@Override
public void emergency(String message, Throwable t) {
this.log(LogLevel.EMERGENCY, message, t);
}
@Override
public void alert(String message, Throwable t) {
this.log(LogLevel.ALERT, message, t);
}
@Override
public void critical(String message, Throwable t) {
this.log(LogLevel.CRITICAL, message, t);
}
@Override
public void error(String message, Throwable t) {
this.log(LogLevel.ERROR, message, t);
}
@Override
public void warning(String message, Throwable t) {
this.log(LogLevel.WARNING, message, t);
}
@Override
public void notice(String message, Throwable t) {
this.log(LogLevel.NOTICE, message, t);
}
@Override
public void info(String message, Throwable t) {
this.log(LogLevel.INFO, message, t);
}
@Override
public void debug(String message, Throwable t) {
this.log(LogLevel.DEBUG, message, t);
}
@Override
public void log(LogLevel level, String message, Throwable t) {
Server.getInstance().getLogger().log(level, this.pluginName + message, t);
}
}
| 2,632 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginLoadOrder.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/PluginLoadOrder.java | package cn.nukkit.plugin;
/**
* 描述一个Nukkit插件加载顺序的类。<br>
* Describes a Nukkit plugin load order.
* <p>
* <p>Nukkit插件的加载顺序有两个:{@link cn.nukkit.plugin.PluginLoadOrder#STARTUP}
* 和 {@link cn.nukkit.plugin.PluginLoadOrder#POSTWORLD}。<br>
* The load order of a Nukkit plugin can be {@link cn.nukkit.plugin.PluginLoadOrder#STARTUP}
* or {@link cn.nukkit.plugin.PluginLoadOrder#POSTWORLD}.</p>
*
* @author MagicDroidX(code) @ Nukkit Project
* @author iNevet(code) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public enum PluginLoadOrder {
/**
* 表示这个插件在服务器启动时就开始加载。<br>
* Indicates that the plugin will be loaded at startup.
*
* @see cn.nukkit.plugin.PluginLoadOrder
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
STARTUP,
/**
* 表示这个插件在第一个世界加载完成后开始加载。<br>
* Indicates that the plugin will be loaded after the first/default world was created.
*
* @see cn.nukkit.plugin.PluginLoadOrder
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
POSTWORLD
}
| 1,209 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Library.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/Library.java | package cn.nukkit.plugin;
/**
* Created on 15-12-13.
*/
public interface Library {
String getGroupId();
String getArtifactId();
String getVersion();
}
| 170 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginLoader.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/PluginLoader.java | package cn.nukkit.plugin;
import java.io.File;
import java.util.regex.Pattern;
/**
* 描述一个插件加载器的接口。<br>
* An interface to describe a plugin loader.
*
* @author iNevet(code) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @see JavaPluginLoader
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public interface PluginLoader {
/**
* 通过文件名字的字符串,来加载和初始化一个插件。<br>
* Loads and initializes a plugin by its file name.
* <p>
* <p>这个方法应该设置好插件的相关属性。比如,插件所在的服务器对象,插件的加载器对象,插件的描述对象,插件的数据文件夹。<br>
* Properties for loaded plugin should be set in this method. Such as, the {@code Server} object for which this
* plugin is running in, the {@code PluginLoader} object for its loader, and the {@code File} object for its
* data folder.</p>
* <p>
* <p>如果插件加载失败,这个方法应该返回{@code null},或者抛出异常。<br>
* If the plugin loader does not load this plugin successfully, a {@code null} should be returned,
* or an exception should be thrown.</p>
*
* @param filename 这个插件的文件名字字符串。<br>A string of its file name.
* @return 加载完毕的插件的 {@code Plugin}对象。<br>The loaded plugin as a {@code Plugin} object.
* @throws java.lang.Exception 插件加载失败所抛出的异常。<br>Thrown when an error occurred.
* @see #loadPlugin(File)
* @see cn.nukkit.plugin.PluginBase#init(PluginLoader, cn.nukkit.Server, PluginDescription, File, File)
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
Plugin loadPlugin(String filename) throws Exception;
/**
* 通过插件的 {@code File}对象,来加载和初始化一个插件。<br>
* Loads and initializes a plugin by a {@code File} object describes the file.
* <p>
* <p>这个方法应该设置好插件的相关属性。比如,插件所在的服务器对象,插件的加载器对象,插件的描述对象,插件的数据文件夹。<br>
* Properties for loaded plugin should be set in this method. Such as, the {@code Server} object for which this
* plugin is running in, the {@code PluginLoader} object for its loader, and the {@code File} object for its
* data folder.</p>
* <p>
* <p>如果插件加载失败,这个方法应该返回{@code null},或者抛出异常。<br>
* If the plugin loader does not load this plugin successfully, a {@code null} should be returned,
* or an exception should be thrown.</p>
*
* @param file 这个插件的文件的 {@code File}对象。<br>A {@code File} object for this plugin.
* @return 加载完毕的插件的 {@code Plugin}对象。<br>The loaded plugin as a {@code Plugin} object.
* @throws java.lang.Exception 插件加载失败所抛出的异常。<br>Thrown when an error occurred.
* @see #loadPlugin(String)
* @see cn.nukkit.plugin.PluginBase#init(PluginLoader, cn.nukkit.Server, PluginDescription, File, File)
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
Plugin loadPlugin(File file) throws Exception;
/**
* 通过插件文件名的字符串,来获得描述这个插件的 {@code PluginDescription}对象。<br>
* Gets a {@code PluginDescription} object describes the plugin by its file name.
* <p>
* <p>如果插件的描述对象获取失败,这个方法应该返回{@code null}。<br>
* If the plugin loader does not get its description successfully, a {@code null} should be returned.</p>
*
* @param filename 这个插件的文件名字。<br>A string of its file name.
* @return 描述这个插件的 {@code PluginDescription}对象。<br>
* A {@code PluginDescription} object describes the plugin.
* @see #getPluginDescription(File)
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
PluginDescription getPluginDescription(String filename);
/**
* 通过插件的 {@code File}对象,来获得描述这个插件的 {@code PluginDescription}对象。<br>
* Gets a {@code PluginDescription} object describes the plugin by a {@code File} object describes the plugin file.
* <p>
* <p>如果插件的描述对象获取失败,这个方法应该返回{@code null}。<br>
* If the plugin loader does not get its description successfully, a {@code null} should be returned.</p>
*
* @param file 这个插件的文件的 {@code File}对象。<br>A {@code File} object for this plugin.
* @return 描述这个插件的 {@code PluginDescription}对象。<br>
* A {@code PluginDescription} object describes the plugin.
* @see #getPluginDescription(String)
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
PluginDescription getPluginDescription(File file);
/**
* 返回这个插件加载器支持的文件类型。<br>
* Returns the file types this plugin loader supports.
* <p>
* <p>在Nukkit读取所有插件时,插件管理器会查找所有已经安装的插件加载器,通过识别这个插件是否满足下面的条件,
* 来选择对应的插件加载器。<br>
* When Nukkit is trying to load all its plugins, the plugin manager will look for all installed plugin loader,
* and choose the correct one by checking if this plugin matches the filters given below.</p>
* <p>
* <p>举个例子,识别这个文件是否以jar为扩展名,它的正则表达式是:<br>
* For example, to check if this file is has a "jar" extension, the regular expression should be:<br>
* {@code ^.+\\.jar$}<br>
* 所以只读取jar扩展名的插件加载器,这个函数应该写成:<br>
* So, for a jar-extension-only file plugin loader, this method should be:
* <pre> {@code @Override}
* public Pattern[] getPluginFilters() {
* return new Pattern[]{Pattern.compile("^.+\\.jar$")};
* }</pre>
* </p>
*
* @return 表达这个插件加载器支持的文件类型的正则表达式数组。<br>
* An array of regular expressions, that describes what kind of file this plugin loader supports.
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
Pattern[] getPluginFilters();
/**
* 启用一个插件。<br>
* Enables a plugin.
*
* @param plugin 要被启用的插件。<br>The plugin to enable.
* @see #disablePlugin
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void enablePlugin(Plugin plugin);
/**
* 停用一个插件。<br>
* Disables a plugin.
*
* @param plugin 要被停用的插件。<br>The plugin to disable.
* @see #enablePlugin
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
void disablePlugin(Plugin plugin);
}
| 6,930 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
RegisteredListener.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/RegisteredListener.java | package cn.nukkit.plugin;
import cn.nukkit.event.Cancellable;
import cn.nukkit.event.Event;
import cn.nukkit.event.EventPriority;
import cn.nukkit.event.Listener;
import cn.nukkit.utils.EventException;
import co.aikar.timings.Timing;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class RegisteredListener {
private final Listener listener;
private final EventPriority priority;
private final Plugin plugin;
private final EventExecutor executor;
private final boolean ignoreCancelled;
private final Timing timing;
public RegisteredListener(Listener listener, EventExecutor executor, EventPriority priority, Plugin plugin, boolean ignoreCancelled, Timing timing) {
this.listener = listener;
this.priority = priority;
this.plugin = plugin;
this.executor = executor;
this.ignoreCancelled = ignoreCancelled;
this.timing = timing;
}
public Listener getListener() {
return listener;
}
public Plugin getPlugin() {
return plugin;
}
public EventPriority getPriority() {
return priority;
}
public void callEvent(Event event) throws EventException {
if (event instanceof Cancellable) {
if (event.isCancelled() && isIgnoringCancelled()) {
return;
}
}
this.timing.startTiming();
executor.execute(listener, event);
this.timing.stopTiming();
}
public boolean isIgnoringCancelled() {
return ignoreCancelled;
}
}
| 1,551 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
PluginDescription.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/PluginDescription.java | package cn.nukkit.plugin;
import cn.nukkit.permission.Permission;
import cn.nukkit.utils.PluginException;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.util.*;
/* TODO Add these to Javadoc:
* <li><i>softdepend</i><br>
* <br>
* </li>
* <li><i>loadbefore</i><br>
* <br>
* </li>
*/
/**
* 描述一个Nukkit插件的类。<br>
* Describes a Nukkit plugin.
* <p>
* <p>在jar格式的插件中,插件的描述内容可以在plugin.yml中定义。比如这个:<br>
* The description of a jar-packed plugin can be defined in the 'plugin.yml' file. For example:
* <blockquote><pre>
* <b>name:</b> HelloWorldPlugin
* <b>main:</b> com.cnblogs.xtypr.helloworldplugin.HelloWorldPlugin
* <b>version:</b> "1.0.0"
* <b>api:</b> ["1.0.0"]
* load: POSTWORLD
* author: 粉鞋大妈
* description: A simple Hello World plugin for Nukkit
* website: http://www.cnblogs.com/xtypr
* permissions:
* helloworldplugin.command.helloworld:
* description: Allows to use helloworld command.
* default: true
* commands:
* helloworld:
* description: the helloworld command
* usage: "/helloworld"
* permission: helloworldplugin.command.helloworld
* depend:
* - TestPlugin1
* </pre></blockquote>
* 在使用plugin.yml来定义插件时,{@code name}、{@code main}、{@code version}、{@code api}这几个字段是必需的,
* 要让Nukkit能够正常加载你的插件,必须要合理地填写这几个字段。<br>
* When using plugin.yml file to define your plugin, it's REQUIRED to fill these items:
* {@code name},{@code main},{@code version} and {@code api}.You are supposed to fill these items to make sure
* your plugin can be normally loaded by Nukkit.<br>
* </p>
* <p>
* <p>接下来对所有的字段做一些说明,<b>加粗</b>的字段表示必需,<i>斜体</i>表示可选:(来自
* <a href="http://www.cnblogs.com/xtypr/p/nukkit_plugin_start_from_0_about_config.html">粉鞋大妈的博客文章</a>)<br>
* Here are some instructions for there items, <b>bold</b> means required, <i>italic</i> means optional: (From
* <a href="http://www.cnblogs.com/xtypr/p/nukkit_plugin_start_from_0_about_config.html">a blog article of @粉鞋大妈</a>)
* <ul>
* <li><b>name</b><br>
* 字符串,表示这个插件的名字,名字是区分不同插件的标准之一。
* 插件的名字<i>不能包含“nukkit”“minecraft”“mojang”</i>这几个字符串,而且不应该包含空格。<br>
* String, the plugin name. Name is one of the ways to distinguish different plugins.
* A plugin name <i>can't contain 'nukkit' 'minecraft' 'mojang'</i>, and shouldn't contain spaces.</li>
* <li><b>version</b><br>
* 字符串,表示这个插件的版本号。使用类似于1.0.0这样的版本号时,应该使用引号包围来防止误识别。<br>
* String, the version string of plugin. When using the version string like "1.0.0",
* quotation marks are required to add, or there will be an exception.</li>
* <li><b>api</b><br>
* 字符串序列,表示这个插件支持的Nukkit API版本号列表。插件作者应该调试能支持的API,然后把版本号添加到这个列表。<br>
* A set of String, the Nukkit API versions that the plugin supports. Plugin developers should debug in different
* Nukkit APIs and try out the versions supported, and add them to this list. </li>
* <li><b>main</b><br>
* 字符串,表示这个插件的主类。插件的主类<i>不能放在“cn.nukkit”包下</i>。<br>
* String, the main class of plugin. The main class<i> can't be placed at 'cn.nukkit' package</i>.</li>
* <li><i>author</i> or <i>authors</i><br>
* 字符串/字符串序列,两个任选一个,表示这个插件的作者/作者列表。<br>
* String or A set of String. One of two is chosen, to describe the author or the list of authors.</li>
* <li><i>website</i><br>
* 字符串,表示这个插件的网站。插件使用者或者开发者可以访问这个网站来获取插件更多的信息。
* 这个网站可以是插件发布帖子或者插件官网等。<br>
* String, the website of plugin. More information can be found by visiting this website. The website
* can be a forum post or the official website.</li>
* <li><i>description</i><br>
* 字符串,表示这个插件的一些描述。<br>
* String, some description of plugin.</li>
* <li><i>depend</i><br>
* 序列,表示这个插件所依赖的一个或一些插件的名字的列表。参见:{@link PluginDescription#getDepend()}<br>
* List, strings for plugin names, what is depended on by this plugin. See:
* {@link PluginDescription#getDepend()}</li>
* <li><i>prefix</i><br>
* 字符串,表示这个插件的消息头衔。参见:{@link PluginDescription#getPrefix()}<br>
* String, the message title of the plugin. See: {@link PluginDescription#getPrefix()}</li>
* <li><i>load</i><br>
* 字符串,表示这个插件的加载顺序,或者说在什么时候加载。参见:{@link PluginLoadOrder}<br>
* String, the load order of plugin, or when the plugin loads. See: {@link PluginLoadOrder}</li>
* <li><i>commands</i><br>
* 序列,表示这个插件的命令列表。<br>
* List, the command list.</li>
* <li><i>permissions</i><br>
* 序列,表示这个插件的权限组列表。<br>
* List, the list of permission groups defined.</li>
* </ul></p>
*
* @author MagicDroidX(code) @ Nukkit Project
* @author iNevet(code and javadoc) @ Nukkit Project
* @author 粉鞋大妈(javadoc) @ Nukkit Project
* @see Plugin
* @see PluginLoadOrder
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public class PluginDescription {
private String name;
private String main;
private List<String> api;
private List<String> depend = new ArrayList<>();
private List<String> softDepend = new ArrayList<>();
private List<String> loadBefore = new ArrayList<>();
private String version;
private Map<String, Object> commands = new HashMap<>();
private String description;
private final List<String> authors = new ArrayList<>();
private String website;
private String prefix;
private PluginLoadOrder order = PluginLoadOrder.POSTWORLD;
private List<Permission> permissions = new ArrayList<>();
public PluginDescription(Map<String, Object> yamlMap) {
this.loadMap(yamlMap);
}
public PluginDescription(String yamlString) {
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
this.loadMap(yaml.loadAs(yamlString, LinkedHashMap.class));
}
private void loadMap(Map<String, Object> plugin) throws PluginException {
this.name = ((String) plugin.get("name")).replaceAll("[^A-Za-z0-9 _.-]", "");
if (this.name.equals("")) {
throw new PluginException("Invalid PluginDescription name");
}
this.name = this.name.replace(" ", "_");
this.version = String.valueOf(plugin.get("version"));
this.main = (String) plugin.get("main");
Object api = plugin.get("api");
if (api instanceof List) {
this.api = (List<String>) api;
} else {
List<String> list = new ArrayList<>();
list.add((String) api);
this.api = list;
}
if (this.main.startsWith("cn.nukkit.")) {
throw new PluginException("Invalid PluginDescription main, cannot start within the cn.nukkit. package");
}
if (plugin.containsKey("commands") && plugin.get("commands") instanceof Map) {
this.commands = (Map<String, Object>) plugin.get("commands");
}
if (plugin.containsKey("depend")) {
this.depend = (List<String>) plugin.get("depend");
}
if (plugin.containsKey("softdepend")) {
this.softDepend = (List<String>) plugin.get("softdepend");
}
if (plugin.containsKey("loadbefore")) {
this.loadBefore = (List<String>) plugin.get("loadbefore");
}
if (plugin.containsKey("website")) {
this.website = (String) plugin.get("website");
}
if (plugin.containsKey("description")) {
this.description = (String) plugin.get("description");
}
if (plugin.containsKey("prefix")) {
this.prefix = (String) plugin.get("prefix");
}
if (plugin.containsKey("load")) {
String order = (String) plugin.get("load");
try {
this.order = PluginLoadOrder.valueOf(order);
} catch (Exception e) {
throw new PluginException("Invalid PluginDescription load");
}
}
if (plugin.containsKey("author")) {
this.authors.add((String) plugin.get("author"));
}
if (plugin.containsKey("authors")) {
this.authors.addAll((Collection<? extends String>) plugin.get("authors"));
}
if (plugin.containsKey("permissions")) {
this.permissions = Permission.loadPermissions((Map<String, Object>) plugin.get("permissions"));
}
}
/**
* 返回这个插件完整的名字。<br>
* Returns the full name of this plugin.
* <p>
* <p>一个插件完整的名字由{@code 名字+" v"+版本号}组成。比如:<br>
* A full name of a plugin is composed by {@code name+" v"+version}.for example:</p>
* <p>{@code HelloWorld v1.0.0}</p>
*
* @return 这个插件完整的名字。<br>The full name of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public String getFullName() {
return this.name + " v" + this.version;
}
/**
* 返回这个插件支持的Nukkit API版本列表。<br>
* Returns all Nukkit API versions this plugin supports.
*
* @return 这个插件支持的Nukkit API版本列表。<br>A list of all Nukkit API versions String this plugin supports.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public List<String> getCompatibleAPIs() {
return api;
}
/**
* 返回这个插件的作者列表。<br>
* Returns all the authors of this plugin.
*
* @return 这个插件的作者列表。<br>A list of all authors of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public List<String> getAuthors() {
return authors;
}
/**
* 返回这个插件的信息前缀。<br>
* Returns the message title of this plugin.
* <p>
* <p>插件的信息前缀在记录器记录信息时,会作为信息头衔使用。如果没有定义记录器,会使用插件的名字作为信息头衔。<br>
* When a PluginLogger logs, the message title is used as the prefix of message. If prefix is undefined,
* the plugin name will be used instead. </p>
*
* @return 这个插件的作信息前缀。如果没定义,返回{@code null}。<br>
* The message title of this plugin, or{@code null} if undefined.
* @see PluginLogger
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public String getPrefix() {
return prefix;
}
/**
* 返回这个插件定义的命令列表。<br>
* Returns all the defined commands of this plugin.
*
* @return 这个插件定义的命令列表。<br>A map of all defined commands of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public Map<String, Object> getCommands() {
return commands;
}
/**
* 返回这个插件所依赖的插件名字。<br>
* The names of the plugins what is depended by this plugin.
* <p>
* <p>Nukkit插件的依赖有这些注意事项:<br>Here are some note for Nukkit plugin depending:
* <ul>
* <li>一个插件不能依赖自己(否则会报错)。<br>A plugin can not depend on itself (or there will be an exception).</li>
* <li>如果一个插件依赖另一个插件,那么必须要安装依赖的插件后才能加载这个插件。<br>
* If a plugin relies on another one, the another one must be installed at the same time, or Nukkit
* won't load this plugin.</li>
* <li>当一个插件所依赖的插件不存在时,Nukkit不会加载这个插件,但是会提醒用户去安装所依赖的插件。<br>
* When the required dependency plugin does not exists, Nukkit won't load this plugin, but will tell the
* user that this dependency is required.</li>
* </ul></p>
* <p>
* <p>举个例子,如果A插件依赖于B插件,在没有安装B插件而安装A插件的情况下,Nukkit会阻止A插件的加载。
* 只有在安装B插件前安装了它所依赖的A插件,Nukkit才会允许加载B插件。<br>
* For example, there is a Plugin A which relies on Plugin B. If you installed A without installing B,
* Nukkit won't load A because its dependency B is lost. Only when B is installed, A will be loaded
* by Nukkit.</p>
*
* @return 插件名字列表的 {@code List}对象。<br>A {@code List} object carries the plugin names.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public List<String> getDepend() {
return depend;
}
/**
* 返回这个插件的描述文字。<br>
* Returns the description text of this plugin.
*
* @return 这个插件的描述文字。<br>The description text of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public String getDescription() {
return description;
}
/**
* TODO finish javadoc
*/
public List<String> getLoadBefore() {
return loadBefore;
}
/**
* 返回这个插件的主类名。<br>
* Returns the main class name of this plugin.
* <p>
* <p>一个插件的加载都是从主类开始的。主类的名字在插件的配置文件中定义后可以通过这个函数返回。一个返回值例子:<br>
* The load action of a Nukkit plugin begins from main class. The name of main class should be defined
* in the plugin configuration, and it can be returned by this function. An example for return value: <br>
* {@code "com.example.ExamplePlugin"}</p>
*
* @return 这个插件的主类名。<br>The main class name of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public String getMain() {
return main;
}
/**
* 返回这个插件的名字。<br>
* Returns the name of this plugin.
*
* @return 这个插件的名字。<br>The name of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public String getName() {
return name;
}
/**
* 返回这个插件加载的顺序,即插件应该在什么时候加载。<br>
* Returns the order the plugin loads, or when the plugin is loaded.
*
* @return 这个插件加载的顺序。<br>The order the plugin loads.
* @see PluginDescription
* @see PluginLoadOrder
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public PluginLoadOrder getOrder() {
return order;
}
/**
* 返回这个插件定义的权限列表。<br>
* Returns all the defined permissions of this plugin.
*
* @return 这个插件定义的权限列表。<br>A map of all defined permissions of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public List<Permission> getPermissions() {
return permissions;
}
/**
* TODO finish javadoc
*/
public List<String> getSoftDepend() {
return softDepend;
}
/**
* 返回这个插件的版本号。<br>
* Returns the version string of this plugin.
*
* @return 这个插件的版本号。<br>The version string od this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public String getVersion() {
return version;
}
/**
* 返回这个插件的网站。<br>
* Returns the website of this plugin.
*
* @return 这个插件的网站。<br>The website of this plugin.
* @see PluginDescription
* @since Nukkit 1.0 | Nukkit API 1.0.0
*/
public String getWebsite() {
return website;
}
}
| 16,683 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
NKServiceManager.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/service/NKServiceManager.java | package cn.nukkit.plugin.service;
import cn.nukkit.Server;
import cn.nukkit.plugin.Plugin;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.*;
/**
* Created on 16-11-20.
*/
public class NKServiceManager implements ServiceManager {
private final Map<Class<?>, List<RegisteredServiceProvider<?>>> handle = new HashMap<>();
@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);
}
protected <T> boolean provide(Class<T> service, T instance, Plugin plugin, ServicePriority priority) {
synchronized (handle) {
List<RegisteredServiceProvider<?>> list = handle.get(service);
if (list == null) {
handle.put(service, list = new ArrayList<>());
}
RegisteredServiceProvider<T> registered = new RegisteredServiceProvider<>(service, instance, priority, plugin);
int position = Collections.binarySearch(list, registered);
if (position > -1) return false;
list.add(-(position + 1), registered);
}
return true;
}
@Override
public List<RegisteredServiceProvider<?>> cancel(Plugin plugin) {
ImmutableList.Builder<RegisteredServiceProvider<?>> builder = ImmutableList.builder();
Iterator<RegisteredServiceProvider<?>> it;
RegisteredServiceProvider<?> registered;
synchronized (handle) {
for (List<RegisteredServiceProvider<?>> list : handle.values()) {
it = list.iterator();
while (it.hasNext()) {
registered = it.next();
if (registered.getPlugin() == plugin) {
it.remove();
builder.add(registered);
}
}
}
}
return builder.build();
}
@Override
public <T> RegisteredServiceProvider<T> cancel(Class<T> service, T provider) {
RegisteredServiceProvider<T> result = null;
synchronized (handle) {
Iterator<RegisteredServiceProvider<?>> it = handle.get(service).iterator();
RegisteredServiceProvider next;
while (it.hasNext() && result == null) {
next = it.next();
if (next.getProvider() == provider) {
it.remove();
result = next;
}
}
}
return result;
}
@Override
public <T> RegisteredServiceProvider<T> getProvider(Class<T> service) {
synchronized (handle) {
List<RegisteredServiceProvider<?>> list = handle.get(service);
if (list == null || list.isEmpty()) return null;
return (RegisteredServiceProvider<T>) list.get(0);
}
}
@Override
public List<Class<?>> getKnownService() {
return ImmutableList.copyOf(handle.keySet());
}
}
| 3,426 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ServiceManager.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/service/ServiceManager.java | package cn.nukkit.plugin.service;
import cn.nukkit.plugin.Plugin;
import java.util.List;
/**
* Created on 16-11-20.
*/
public interface ServiceManager {
/**
* Register an object as a service's provider.
*
* @param service the service
* @param provider the service provider
* @param plugin the plugin
* @param priority the priority
* @return {@code true}, or {@code false} only if {@code provider}
* already registered
*/
<T> boolean register(Class<T> service, T provider, Plugin plugin, ServicePriority priority);
/**
* Cancel service's provider(s) offered this plugin.
*
* @param plugin the plugin
* @return a {@link com.google.common.collect.ImmutableList}
* contains cancelled {@link RegisteredServiceProvider}
*/
List<RegisteredServiceProvider<?>> cancel(Plugin plugin);
/**
* Cancel a service's provider.
*
* @param service the service
* @param provider the provider
* @return the cancelled {@link RegisteredServiceProvider}, or {@code null} if not
* any provider cancelled
*/
<T> RegisteredServiceProvider<T> cancel(Class<T> service, T provider);
/**
* Return the service's provider.
*
* @param service the target service
* @return a {@lingetProvider()k RegisteredService<T>} registered highest priority, or
* {@code null} if not exists
*/
<T> RegisteredServiceProvider<T> getProvider(Class<T> service);
/**
* Return the known service(s).
*
* @return a {@link com.google.common.collect.ImmutableList} contains the
* known service(s)
*/
List<Class<?>> getKnownService();
}
| 1,699 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
RegisteredServiceProvider.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/service/RegisteredServiceProvider.java | package cn.nukkit.plugin.service;
import cn.nukkit.plugin.Plugin;
/**
* Created on 16-11-20.
*/
public class RegisteredServiceProvider<T> implements Comparable<RegisteredServiceProvider<T>> {
private Plugin plugin;
private ServicePriority priority;
private Class<T> service;
private T provider;
RegisteredServiceProvider(Class<T> service, T provider, ServicePriority priority, Plugin plugin) {
this.plugin = plugin;
this.provider = provider;
this.service = service;
this.priority = priority;
}
/**
* Return the provided service.
*
* @return the provided service
*/
public Class<T> getService() {
return this.service;
}
/**
* Return the plugin provide this service.
*
* @return the plugin provide this service, or {@code null}
* only if this service provided by server
*/
public Plugin getPlugin() {
return plugin;
}
/**
* Return the service provider.
*
* @return the service provider
*/
public T getProvider() {
return provider;
}
public ServicePriority getPriority() {
return priority;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RegisteredServiceProvider<?> that = (RegisteredServiceProvider<?>) o;
return provider == that.provider || provider.equals(that.provider);
}
@Override
public int hashCode() {
return provider.hashCode();
}
public int compareTo(RegisteredServiceProvider<T> other) {
return other.priority.ordinal() - priority.ordinal();
}
}
| 1,735 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ServicePriority.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/plugin/service/ServicePriority.java | package cn.nukkit.plugin.service;
/**
* Created on 16-11-20.
*/
public enum ServicePriority {
LOWEST, LOWER, NORMAL, HIGHER, HIGHEST,
}
| 145 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormWindowCustom.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/window/FormWindowCustom.java | package cn.nukkit.form.window;
import cn.nukkit.form.element.*;
import cn.nukkit.form.response.FormResponseCustom;
import cn.nukkit.form.response.FormResponseData;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FormWindowCustom extends FormWindow {
private final String type = "custom_form"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String title = "";
private ElementButtonImageData icon;
private List<Element> content;
private FormResponseCustom response;
public FormWindowCustom(String title) {
this(title, new ArrayList<>());
}
public FormWindowCustom(String title, List<Element> contents) {
this(title, contents, "");
}
public FormWindowCustom(String title, List<Element> contents, String icon) {
this.title = title;
this.content = contents;
if (!icon.isEmpty()) this.icon = new ElementButtonImageData(ElementButtonImageData.IMAGE_DATA_TYPE_URL, icon);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Element> getElements() {
return content;
}
public void addElement(Element element) {
content.add(element);
}
public ElementButtonImageData getIcon() {
return icon;
}
public void setIcon(String icon) {
if (!icon.isEmpty()) this.icon = new ElementButtonImageData(ElementButtonImageData.IMAGE_DATA_TYPE_URL, icon);
}
public String getJSONData() {
String toModify = new Gson().toJson(this);
//We need to replace this due to Java not supporting declaring class field 'default'
return toModify.replace("defaultOptionIndex", "default")
.replace("defaultText", "default")
.replace("defaultValue", "default")
.replace("defaultStepIndex", "default");
}
public FormResponseCustom getResponse() {
return response;
}
public void setResponse(String data) {
if (data.equals("null")) {
this.closed = true;
return;
}
List<String> elementResponses = new Gson().fromJson(data, new TypeToken<List<String>>() {
}.getType());
//elementResponses.remove(elementResponses.size() - 1); //submit button //maybe mojang removed that?
int i = 0;
HashMap<Integer, FormResponseData> dropdownResponses = new HashMap<>();
HashMap<Integer, String> inputResponses = new HashMap<>();
HashMap<Integer, Float> sliderResponses = new HashMap<>();
HashMap<Integer, FormResponseData> stepSliderResponses = new HashMap<>();
HashMap<Integer, Boolean> toggleResponses = new HashMap<>();
HashMap<Integer, Object> responses = new HashMap<>();
for (String elementData : elementResponses) {
if (i >= content.size()) {
break;
}
Element e = content.get(i);
if (e == null) break;
if (e instanceof ElementLabel) {
i++;
continue;
}
if (e instanceof ElementDropdown) {
String answer = ((ElementDropdown) e).getOptions().get(Integer.parseInt(elementData));
dropdownResponses.put(i, new FormResponseData(Integer.parseInt(elementData), answer));
responses.put(i, answer);
} else if (e instanceof ElementInput) {
inputResponses.put(i, elementData);
responses.put(i, elementData);
} else if (e instanceof ElementSlider) {
Float answer = Float.parseFloat(elementData);
sliderResponses.put(i, answer);
responses.put(i, answer);
} else if (e instanceof ElementStepSlider) {
String answer = ((ElementStepSlider) e).getSteps().get(Integer.parseInt(elementData));
stepSliderResponses.put(i, new FormResponseData(Integer.parseInt(elementData), answer));
responses.put(i, answer);
} else if (e instanceof ElementToggle) {
Boolean answer = Boolean.parseBoolean(elementData);
toggleResponses.put(i, answer);
responses.put(i, answer);
}
i++;
}
this.response = new FormResponseCustom(responses, dropdownResponses, inputResponses,
sliderResponses, stepSliderResponses, toggleResponses);
}
/**
* Set Elements from Response
* Used on ServerSettings Form Response. After players set settings, we need to sync these settings to the server.
*/
public void setElementsFromResponse() {
if (this.response != null) {
this.response.getResponses().forEach((i, response) -> {
Element e = content.get(i);
if (e != null) {
if (e instanceof ElementDropdown) {
((ElementDropdown) e).setDefaultOptionIndex(((ElementDropdown) e).getOptions().indexOf(response));
} else if (e instanceof ElementInput) {
((ElementInput) e).setDefaultText((String)response);
} else if (e instanceof ElementSlider) {
((ElementSlider) e).setDefaultValue((Float)response);
} else if (e instanceof ElementStepSlider) {
((ElementStepSlider) e).setDefaultOptionIndex(((ElementStepSlider) e).getSteps().indexOf(response));
} else if (e instanceof ElementToggle) {
((ElementToggle) e).setDefaultValue((Boolean)response);
}
}
});
}
}
}
| 5,904 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormWindow.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/window/FormWindow.java | package cn.nukkit.form.window;
import cn.nukkit.form.response.FormResponse;
public abstract class FormWindow {
protected boolean closed = false;
public abstract String getJSONData();
public abstract void setResponse(String data);
public abstract FormResponse getResponse();
public boolean wasClosed() {
return closed;
}
}
| 362 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormWindowSimple.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/window/FormWindowSimple.java | package cn.nukkit.form.window;
import cn.nukkit.form.element.ElementButton;
import cn.nukkit.form.response.FormResponseSimple;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class FormWindowSimple extends FormWindow {
private final String type = "form"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String title = "";
private String content = "";
private List<ElementButton> buttons;
private FormResponseSimple response = null;
public FormWindowSimple(String title, String content) {
this(title, content, new ArrayList<>());
}
public FormWindowSimple(String title, String content, List<ElementButton> buttons) {
this.title = title;
this.content = content;
this.buttons = buttons;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<ElementButton> getButtons() {
return buttons;
}
public void addButton(ElementButton button) {
this.buttons.add(button);
}
public String getJSONData() {
return new Gson().toJson(this);
}
public FormResponseSimple getResponse() {
return response;
}
public void setResponse(String data) {
if (data.equals("null")) {
this.closed = true;
return;
}
int buttonID;
try {
buttonID = Integer.parseInt(data);
} catch (Exception e) {
return;
}
if (buttonID >= this.buttons.size()) {
this.response = new FormResponseSimple(buttonID, null);
return;
}
this.response = new FormResponseSimple(buttonID, buttons.get(buttonID));
}
}
| 1,975 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormWindowModal.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/window/FormWindowModal.java | package cn.nukkit.form.window;
import cn.nukkit.form.response.FormResponseModal;
import com.google.gson.Gson;
public class FormWindowModal extends FormWindow {
private final String type = "modal"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String title = "";
private String content = "";
private String button1 = "";
private String button2 = "";
private FormResponseModal response = null;
public FormWindowModal(String title, String content, String trueButonText, String falseButtonText) {
this.title = title;
this.content = content;
this.button1 = trueButonText;
this.button2 = falseButtonText;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getButton1() {
return button1;
}
public void setButton1(String button1) {
this.button1 = button1;
}
public String getButton2() {
return button2;
}
public void setButton2(String button2) {
this.button2 = button2;
}
public String getJSONData() {
return new Gson().toJson(this);
}
public FormResponseModal getResponse() {
return response;
}
public void setResponse(String data) {
if (data.equals("null")) {
closed = true;
return;
}
if (data.equals("true")) response = new FormResponseModal(0, button1);
else response = new FormResponseModal(1, button2);
}
}
| 1,736 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementButtonImageData.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementButtonImageData.java | package cn.nukkit.form.element;
public class ElementButtonImageData {
public static final String IMAGE_DATA_TYPE_PATH = "path";
public static final String IMAGE_DATA_TYPE_URL = "url";
private String type;
private String data;
public ElementButtonImageData(String type, String data) {
if (!type.equals(IMAGE_DATA_TYPE_URL) && !type.equals(IMAGE_DATA_TYPE_PATH)) return;
this.type = type;
this.data = data;
}
public String getType() {
return type;
}
public String getData() {
return data;
}
public void setType(String type) {
this.type = type;
}
public void setData(String data) {
this.data = data;
}
}
| 721 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementSlider.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementSlider.java | package cn.nukkit.form.element;
public class ElementSlider extends Element {
private final String type = "slider"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String text = "";
private float min = 0f;
private float max = 100f;
private int step;
private float defaultValue;
public ElementSlider(String text, float min, float max) {
this(text, min, max, -1);
}
public ElementSlider(String text, float min, float max, int step) {
this(text, min, max, step, -1);
}
public ElementSlider(String text, float min, float max, int step, float defaultValue) {
this.text = text;
this.min = min < 0f ? 0f : min;
this.max = max > this.min ? max : this.min;
if (step != -1f && step > 0) this.step = step;
if (defaultValue != -1f) this.defaultValue = defaultValue;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public float getMin() {
return min;
}
public void setMin(float min) {
this.min = min;
}
public float getMax() {
return max;
}
public void setMax(float max) {
this.max = max;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public float getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(float defaultValue) {
this.defaultValue = defaultValue;
}
}
| 1,583 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementStepSlider.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementStepSlider.java | package cn.nukkit.form.element;
import java.util.ArrayList;
import java.util.List;
public class ElementStepSlider extends Element {
private final String type = "step_slider"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String text = "";
private List<String> steps;
private int defaultStepIndex = 0;
public ElementStepSlider(String text) {
this(text, new ArrayList<>());
}
public ElementStepSlider(String text, List<String> steps) {
this(text, steps, 0);
}
public ElementStepSlider(String text, List<String> steps, int defaultStep) {
this.text = text;
this.steps = steps;
this.defaultStepIndex = defaultStep;
}
public int getDefaultStepIndex() {
return defaultStepIndex;
}
public void setDefaultOptionIndex(int index) {
if (index >= steps.size()) return;
this.defaultStepIndex = index;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<String> getSteps() {
return steps;
}
public void addStep(String step) {
addStep(step, false);
}
public void addStep(String step, boolean isDefault) {
steps.add(step);
if (isDefault) this.defaultStepIndex = steps.size() - 1;
}
}
| 1,392 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementToggle.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementToggle.java | package cn.nukkit.form.element;
public class ElementToggle extends Element {
private final String type = "toggle"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String text = "";
private boolean defaultValue = false;
public ElementToggle(String text) {
this(text, false);
}
public ElementToggle(String text, boolean defaultValue) {
this.text = text;
this.defaultValue = defaultValue;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean isDefaultValue() {
return defaultValue;
}
public void setDefaultValue(boolean defaultValue) {
this.defaultValue = defaultValue;
}
}
| 798 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementLabel.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementLabel.java | package cn.nukkit.form.element;
public class ElementLabel extends Element {
private final String type = "label"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String text = "";
public ElementLabel(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| 436 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementDropdown.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementDropdown.java | package cn.nukkit.form.element;
import java.util.ArrayList;
import java.util.List;
public class ElementDropdown extends Element {
private final String type = "dropdown"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String text = "";
private List<String> options;
private int defaultOptionIndex = 0;
public ElementDropdown(String text) {
this(text, new ArrayList<>());
}
public ElementDropdown(String text, List<String> options) {
this(text, options, 0);
}
public ElementDropdown(String text, List<String> options, int defaultOption) {
this.text = text;
this.options = options;
this.defaultOptionIndex = defaultOption;
}
public int getDefaultOptionIndex() {
return defaultOptionIndex;
}
public void setDefaultOptionIndex(int index) {
if (index >= options.size()) return;
this.defaultOptionIndex = index;
}
public List<String> getOptions() {
return options;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void addOption(String option) {
addOption(option, false);
}
public void addOption(String option, boolean isDefault) {
options.add(option);
if (isDefault) this.defaultOptionIndex = options.size() - 1;
}
}
| 1,433 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementButton.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementButton.java | package cn.nukkit.form.element;
public class ElementButton {
private String text = "";
private ElementButtonImageData image;
public ElementButton(String text) {
this.text = text;
}
public ElementButton(String text, ElementButtonImageData image) {
this.text = text;
if (!image.getData().isEmpty() && !image.getType().isEmpty()) this.image = image;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public ElementButtonImageData getImage() {
return image;
}
public void addImage(ElementButtonImageData image) {
if (!image.getData().isEmpty() && !image.getType().isEmpty()) this.image = image;
}
}
| 764 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
ElementInput.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/element/ElementInput.java | package cn.nukkit.form.element;
public class ElementInput extends Element {
private final String type = "input"; //This variable is used for JSON import operations. Do NOT delete :) -- @Snake1999
private String text = "";
private String placeholder = "";
private String defaultText = "";
public ElementInput(String text) {
this(text, "");
}
public ElementInput(String text, String placeholder) {
this(text, placeholder, "");
}
public ElementInput(String text, String placeholder, String defaultText) {
this.text = text;
this.placeholder = placeholder;
this.defaultText = defaultText;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getPlaceHolder() {
return placeholder;
}
public void setPlaceHolder(String placeholder) {
this.placeholder = placeholder;
}
public String getDefaultText() {
return defaultText;
}
public void setDefaultText(String defaultText) {
this.defaultText = defaultText;
}
}
| 1,147 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormResponseData.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/response/FormResponseData.java | package cn.nukkit.form.response;
public class FormResponseData {
private int elementID;
private String elementContent;
public FormResponseData(int id, String content) {
this.elementID = id;
this.elementContent = content;
}
public int getElementID() {
return elementID;
}
public String getElementContent() {
return elementContent;
}
}
| 404 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormResponseCustom.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/response/FormResponseCustom.java | package cn.nukkit.form.response;
import java.util.HashMap;
public class FormResponseCustom extends FormResponse {
private HashMap<Integer, Object> responses = new HashMap<>();
private HashMap<Integer, FormResponseData> dropdownResponses = new HashMap<>();
private HashMap<Integer, String> inputResponses = new HashMap<>();
private HashMap<Integer, Float> sliderResponses = new HashMap<>();
private HashMap<Integer, FormResponseData> stepSliderResponses = new HashMap<>();
private HashMap<Integer, Boolean> toggleResponses = new HashMap<>();
public FormResponseCustom(HashMap<Integer, Object> responses, HashMap<Integer, FormResponseData> dropdownResponses,
HashMap<Integer, String> inputResponses, HashMap<Integer, Float> sliderResponses,
HashMap<Integer, FormResponseData> stepSliderResponses,
HashMap<Integer, Boolean> toggleResponses) {
this.responses = responses;
this.dropdownResponses = dropdownResponses;
this.inputResponses = inputResponses;
this.sliderResponses = sliderResponses;
this.stepSliderResponses = stepSliderResponses;
this.toggleResponses = toggleResponses;
}
public HashMap<Integer, Object> getResponses() {
return responses;
}
public Object getResponse(int id) {
return responses.get(id);
}
public FormResponseData getDropdownResponse(int id) {
return dropdownResponses.get(id);
}
public String getInputResponse(int id) {
return inputResponses.get(id);
}
public float getSliderResponse(int id) {
return sliderResponses.get(id);
}
public FormResponseData getStepSliderResponse(int id) {
return stepSliderResponses.get(id);
}
public boolean getToggleResponse(int id) {
return toggleResponses.get(id);
}
}
| 1,919 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormResponseModal.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/response/FormResponseModal.java | package cn.nukkit.form.response;
public class FormResponseModal extends FormResponse {
private int clickedButtonId;
private String clickedButtonText;
public FormResponseModal(int clickedButtonId, String clickedButtonText) {
this.clickedButtonId = clickedButtonId;
this.clickedButtonText = clickedButtonText;
}
public int getClickedButtonId() {
return clickedButtonId;
}
public String getClickedButtonText() {
return clickedButtonText;
}
}
| 509 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
FormResponseSimple.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/form/response/FormResponseSimple.java | package cn.nukkit.form.response;
import cn.nukkit.form.element.ElementButton;
public class FormResponseSimple extends FormResponse {
private int clickedButtonId;
private ElementButton clickedButton;
public FormResponseSimple(int clickedButtonId, ElementButton clickedButton) {
this.clickedButtonId = clickedButtonId;
this.clickedButton = clickedButton;
}
public int getClickedButtonId() {
return clickedButtonId;
}
public ElementButton getClickedButton() {
return clickedButton;
}
}
| 554 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
BlockVector3.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/math/BlockVector3.java | package cn.nukkit.math;
public class BlockVector3 implements Cloneable {
public int x;
public int y;
public int z;
public BlockVector3(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public BlockVector3() {
}
public BlockVector3 setComponents(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
public Vector3 add(double x) {
return this.add(x, 0, 0);
}
public Vector3 add(double x, double y) {
return this.add(x, y, 0);
}
public Vector3 add(double x, double y, double z) {
return new Vector3(this.x + x, this.y + y, this.z + z);
}
public Vector3 add(Vector3 x) {
return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ());
}
public Vector3 subtract(double x) {
return this.subtract(x, 0, 0);
}
public Vector3 subtract(double x, double y) {
return this.subtract(x, y, 0);
}
public Vector3 subtract(double x, double y, double z) {
return this.add(-x, -y, -z);
}
public Vector3 subtract(Vector3 x) {
return this.add(-x.getX(), -x.getY(), -x.getZ());
}
public BlockVector3 add(int x) {
return this.add(x, 0, 0);
}
public BlockVector3 add(int x, int y) {
return this.add(x, y, 0);
}
public BlockVector3 add(int x, int y, int z) {
return new BlockVector3(this.x + x, this.y + y, this.z + z);
}
public BlockVector3 add(BlockVector3 x) {
return new BlockVector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ());
}
public BlockVector3 subtract() {
return this.subtract(0, 0, 0);
}
public BlockVector3 subtract(int x) {
return this.subtract(x, 0, 0);
}
public BlockVector3 subtract(int x, int y) {
return this.subtract(x, y, 0);
}
public BlockVector3 subtract(int x, int y, int z) {
return this.add(-x, -y, -z);
}
public BlockVector3 subtract(BlockVector3 x) {
return this.add(-x.getX(), -x.getY(), -x.getZ());
}
public BlockVector3 multiply(int number) {
return new BlockVector3(this.x * number, this.y * number, this.z * number);
}
public BlockVector3 divide(int number) {
return new BlockVector3(this.x / number, this.y / number, this.z / number);
}
public BlockVector3 getSide(BlockFace face) {
return this.getSide(face, 1);
}
public BlockVector3 getSide(BlockFace face, int step) {
return new BlockVector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step);
}
public BlockVector3 up() {
return up(1);
}
public BlockVector3 up(int step) {
return getSide(BlockFace.UP, step);
}
public BlockVector3 down() {
return down(1);
}
public BlockVector3 down(int step) {
return getSide(BlockFace.DOWN, step);
}
public BlockVector3 north() {
return north(1);
}
public BlockVector3 north(int step) {
return getSide(BlockFace.NORTH, step);
}
public BlockVector3 south() {
return south(1);
}
public BlockVector3 south(int step) {
return getSide(BlockFace.SOUTH, step);
}
public BlockVector3 east() {
return east(1);
}
public BlockVector3 east(int step) {
return getSide(BlockFace.EAST, step);
}
public BlockVector3 west() {
return west(1);
}
public BlockVector3 west(int step) {
return getSide(BlockFace.WEST, step);
}
public double distance(Vector3 pos) {
return Math.sqrt(this.distanceSquared(pos));
}
public double distance(BlockVector3 pos) {
return Math.sqrt(this.distanceSquared(pos));
}
public double distanceSquared(Vector3 pos) {
return distanceSquared(pos.x, pos.y, pos.z);
}
public double distanceSquared(BlockVector3 pos) {
return distanceSquared(pos.x, pos.y, pos.z);
}
public double distanceSquared(double x, double y, double z) {
return Math.pow(this.x - x, 2) + Math.pow(this.y - y, 2) + Math.pow(this.z - z, 2);
}
@Override
public boolean equals(Object ob) {
if (ob == null) return false;
if (ob == this) return true;
if (!(ob instanceof BlockVector3)) return false;
return
this.x == ((BlockVector3) ob).x &&
this.y == ((BlockVector3) ob).y &&
this.z == ((BlockVector3) ob).z;
}
@Override
public final int hashCode() {
return (x ^ (z << 12)) ^ (y << 24);
}
@Override
public String toString() {
return "BlockPosition(level=" + ",x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")";
}
@Override
public BlockVector3 clone() {
try {
return (BlockVector3) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public Vector3 asVector3() {
return new Vector3(this.x, this.y, this.z);
}
public Vector3f asVector3f() {
return new Vector3f(this.x, this.y, this.z);
}
}
| 5,459 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
SimpleAxisAlignedBB.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/math/SimpleAxisAlignedBB.java | package cn.nukkit.math;
/**
* auth||: MagicDroidX
* Nukkit Project
*/
public class SimpleAxisAlignedBB implements AxisAlignedBB {
private double minX;
private double minY;
private double minZ;
private double maxX;
private double maxY;
private double maxZ;
public SimpleAxisAlignedBB(Vector3 pos1, Vector3 pos2) {
this.minX = Math.min(pos1.x, pos2.x);
this.minY = Math.min(pos1.y, pos2.y);
this.minZ = Math.min(pos1.z, pos2.z);
this.maxX = Math.max(pos1.x, pos2.x);
this.maxY = Math.max(pos1.y, pos2.y);
this.maxZ = Math.max(pos1.z, pos2.z);
}
public SimpleAxisAlignedBB(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
this.minX = minX;
this.minY = minY;
this.minZ = minZ;
this.maxX = maxX;
this.maxY = maxY;
this.maxZ = maxZ;
}
@Override
public String toString() {
return "AxisAlignedBB(" + this.getMinX() + ", " + this.getMinY() + ", " + this.getMinZ() + ", " + this.getMaxX() + ", " + this.getMaxY() + ", " + this.getMaxZ() + ")";
}
@Override
public double getMinX() {
return minX;
}
@Override
public void setMinX(double minX) {
this.minX = minX;
}
@Override
public double getMinY() {
return minY;
}
@Override
public void setMinY(double minY) {
this.minY = minY;
}
@Override
public double getMinZ() {
return minZ;
}
@Override
public void setMinZ(double minZ) {
this.minZ = minZ;
}
@Override
public double getMaxX() {
return maxX;
}
@Override
public void setMaxX(double maxX) {
this.maxX = maxX;
}
@Override
public double getMaxY() {
return maxY;
}
@Override
public void setMaxY(double maxY) {
this.maxY = maxY;
}
@Override
public double getMaxZ() {
return maxZ;
}
@Override
public void setMaxZ(double maxZ) {
this.maxZ = maxZ;
}
@Override
public AxisAlignedBB clone() {
return new SimpleAxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ);
}
}
| 2,213 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Vector3.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/math/Vector3.java | package cn.nukkit.math;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Vector3 implements Cloneable {
public double x;
public double y;
public double z;
public Vector3() {
this(0, 0, 0);
}
public Vector3(double x) {
this(x, 0, 0);
}
public Vector3(double x, double y) {
this(x, y, 0);
}
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getZ() {
return this.z;
}
public int getFloorX() {
return (int) Math.floor(this.x);
}
public int getFloorY() {
return (int) Math.floor(this.y);
}
public int getFloorZ() {
return (int) Math.floor(this.z);
}
public double getRight() {
return this.x;
}
public double getUp() {
return this.y;
}
public double getForward() {
return this.z;
}
public double getSouth() {
return this.x;
}
public double getWest() {
return this.z;
}
public Vector3 add(double x) {
return this.add(x, 0, 0);
}
public Vector3 add(double x, double y) {
return this.add(x, y, 0);
}
public Vector3 add(double x, double y, double z) {
return new Vector3(this.x + x, this.y + y, this.z + z);
}
public Vector3 add(Vector3 x) {
return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ());
}
public Vector3 subtract() {
return this.subtract(0, 0, 0);
}
public Vector3 subtract(double x) {
return this.subtract(x, 0, 0);
}
public Vector3 subtract(double x, double y) {
return this.subtract(x, y, 0);
}
public Vector3 subtract(double x, double y, double z) {
return this.add(-x, -y, -z);
}
public Vector3 subtract(Vector3 x) {
return this.add(-x.getX(), -x.getY(), -x.getZ());
}
public Vector3 multiply(double number) {
return new Vector3(this.x * number, this.y * number, this.z * number);
}
public Vector3 divide(double number) {
return new Vector3(this.x / number, this.y / number, this.z / number);
}
public Vector3 ceil() {
return new Vector3((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z));
}
public Vector3 floor() {
return new Vector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
public Vector3 round() {
return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z));
}
public Vector3 abs() {
return new Vector3((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z));
}
public Vector3 getSide(BlockFace face) {
return this.getSide(face, 1);
}
public Vector3 getSide(BlockFace face, int step) {
return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step);
}
public Vector3 up() {
return up(1);
}
public Vector3 up(int step) {
return getSide(BlockFace.UP, step);
}
public Vector3 down() {
return down(1);
}
public Vector3 down(int step) {
return getSide(BlockFace.DOWN, step);
}
public Vector3 north() {
return north(1);
}
public Vector3 north(int step) {
return getSide(BlockFace.NORTH, step);
}
public Vector3 south() {
return south(1);
}
public Vector3 south(int step) {
return getSide(BlockFace.SOUTH, step);
}
public Vector3 east() {
return east(1);
}
public Vector3 east(int step) {
return getSide(BlockFace.EAST, step);
}
public Vector3 west() {
return west(1);
}
public Vector3 west(int step) {
return getSide(BlockFace.WEST, step);
}
public double distance(Vector3 pos) {
return Math.sqrt(this.distanceSquared(pos));
}
public double distanceSquared(Vector3 pos) {
return Math.pow(this.x - pos.x, 2) + Math.pow(this.y - pos.y, 2) + Math.pow(this.z - pos.z, 2);
}
public double maxPlainDistance() {
return this.maxPlainDistance(0, 0);
}
public double maxPlainDistance(double x) {
return this.maxPlainDistance(x, 0);
}
public double maxPlainDistance(double x, double z) {
return Math.max(Math.abs(this.x - x), Math.abs(this.z - z));
}
public double maxPlainDistance(Vector2 vector) {
return this.maxPlainDistance(vector.x, vector.y);
}
public double maxPlainDistance(Vector3 x) {
return this.maxPlainDistance(x.x, x.z);
}
public double length() {
return Math.sqrt(this.lengthSquared());
}
public double lengthSquared() {
return this.x * this.x + this.y * this.y + this.z * this.z;
}
public Vector3 normalize() {
double len = this.lengthSquared();
if (len > 0) {
return this.divide(Math.sqrt(len));
}
return new Vector3(0, 0, 0);
}
public double dot(Vector3 v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
public Vector3 cross(Vector3 v) {
return new Vector3(
this.y * v.z - this.z * v.y,
this.z * v.x - this.x * v.z,
this.x * v.y - this.y * v.x
);
}
/**
* Returns a new vector with x value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithXValue(Vector3 v, double x) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (xDiff * xDiff < 0.0000001) {
return null;
}
double f = (x - this.x) / xDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with y value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithYValue(Vector3 v, double y) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (yDiff * yDiff < 0.0000001) {
return null;
}
double f = (y - this.y) / yDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with z value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithZValue(Vector3 v, double z) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (zDiff * zDiff < 0.0000001) {
return null;
}
double f = (z - this.z) / zDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
public Vector3 setComponents(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public String toString() {
return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")";
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Vector3)) {
return false;
}
Vector3 other = (Vector3) obj;
return this.x == other.x && this.y == other.y && this.z == other.z;
}
@Override
public int hashCode() {
return ((int) x ^ ((int) z << 12)) ^ ((int) y << 24);
}
public int rawHashCode() {
return super.hashCode();
}
@Override
public Vector3 clone() {
try {
return (Vector3) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public Vector3f asVector3f() {
return new Vector3f((float) this.x, (float) this.y, (float) this.z);
}
public BlockVector3 asBlockVector3() {
return new BlockVector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
}
| 8,701 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Vector2f.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/math/Vector2f.java | package cn.nukkit.math;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Vector2f {
public final float x;
public final float y;
public Vector2f() {
this(0, 0);
}
public Vector2f(float x) {
this(x, 0);
}
public Vector2f(float x, float y) {
this.x = x;
this.y = y;
}
public float getX() {
return this.x;
}
public float getY() {
return this.y;
}
public int getFloorX() {
return NukkitMath.floorFloat(this.x);
}
public int getFloorY() {
return NukkitMath.floorFloat(this.y);
}
public Vector2f add(float x) {
return this.add(x, 0);
}
public Vector2f add(float x, float y) {
return new Vector2f(this.x + x, this.y + y);
}
public Vector2f add(Vector2f x) {
return this.add(x.getX(), x.getY());
}
public Vector2f subtract(float x) {
return this.subtract(x, 0);
}
public Vector2f subtract(float x, float y) {
return this.add(-x, -y);
}
public Vector2f subtract(Vector2f x) {
return this.add(-x.getX(), -x.getY());
}
public Vector2f ceil() {
return new Vector2f((int) (this.x + 1), (int) (this.y + 1));
}
public Vector2f floor() {
return new Vector2f(this.getFloorX(), this.getFloorY());
}
public Vector2f round() {
return new Vector2f(Math.round(this.x), Math.round(this.y));
}
public Vector2f abs() {
return new Vector2f(Math.abs(this.x), Math.abs(this.y));
}
public Vector2f multiply(float number) {
return new Vector2f(this.x * number, this.y * number);
}
public Vector2f divide(float number) {
return new Vector2f(this.x / number, this.y / number);
}
public double distance(float x) {
return this.distance(x, 0);
}
public double distance(float x, float y) {
return Math.sqrt(this.distanceSquared(x, y));
}
public double distance(Vector2f vector) {
return Math.sqrt(this.distanceSquared(vector.getX(), vector.getY()));
}
public double distanceSquared(float x) {
return this.distanceSquared(x, 0);
}
public double distanceSquared(float x, float y) {
return Math.pow(this.x - x, 2) + Math.pow(this.y - y, 2);
}
public double distanceSquared(Vector2f vector) {
return this.distanceSquared(vector.getX(), vector.getY());
}
public double length() {
return Math.sqrt(this.lengthSquared());
}
public float lengthSquared() {
return this.x * this.x + this.y * this.y;
}
public Vector2f normalize() {
float len = this.lengthSquared();
if (len != 0) {
return this.divide((float) Math.sqrt(len));
}
return new Vector2f(0, 0);
}
public float dot(Vector2f v) {
return this.x * v.x + this.y * v.y;
}
@Override
public String toString() {
return "Vector2(x=" + this.x + ",y=" + this.y + ")";
}
} | 3,053 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
AxisAlignedBB.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/math/AxisAlignedBB.java | package cn.nukkit.math;
import cn.nukkit.level.MovingObjectPosition;
public interface AxisAlignedBB extends Cloneable {
default AxisAlignedBB setBounds(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) {
this.setMinX(minX);
this.setMinY(minY);
this.setMinZ(minZ);
this.setMaxX(maxX);
this.setMaxY(maxY);
this.setMaxZ(maxZ);
return this;
}
default AxisAlignedBB addCoord(double x, double y, double z) {
double minX = this.getMinX();
double minY = this.getMinY();
double minZ = this.getMinZ();
double maxX = this.getMaxX();
double maxY = this.getMaxY();
double maxZ = this.getMaxZ();
if (x < 0) minX += x;
if (x > 0) maxX += x;
if (y < 0) minY += y;
if (y > 0) maxY += y;
if (z < 0) minZ += z;
if (z > 0) maxZ += z;
return new SimpleAxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ);
}
default AxisAlignedBB grow(double x, double y, double z) {
return new SimpleAxisAlignedBB(this.getMinX() - x, this.getMinY() - y, this.getMinZ() - z, this.getMaxX() + x, this.getMaxY() + y, this.getMaxZ() + z);
}
default AxisAlignedBB expand(double x, double y, double z)
{
this.setMinX(this.getMinX() - x);
this.setMinY(this.getMinY() - y);
this.setMinZ(this.getMinZ() - z);
this.setMaxX(this.getMaxX() + x);
this.setMaxY(this.getMaxY() + y);
this.setMaxZ(this.getMaxZ() + z);
return this;
}
default AxisAlignedBB offset(double x, double y, double z) {
this.setMinX(this.getMinX() + x);
this.setMinY(this.getMinY() + y);
this.setMinZ(this.getMinZ() + z);
this.setMaxX(this.getMaxX() + x);
this.setMaxY(this.getMaxY() + y);
this.setMaxZ(this.getMaxZ() + z);
return this;
}
default AxisAlignedBB shrink(double x, double y, double z) {
return new SimpleAxisAlignedBB(this.getMinX() + x, this.getMinY() + y, this.getMinZ() + z, this.getMaxX() - x, this.getMaxY() - y, this.getMaxZ() - z);
}
default AxisAlignedBB contract(double x, double y, double z) {
this.setMinX(this.getMinX() + x);
this.setMinY(this.getMinY() + y);
this.setMinZ(this.getMinZ() + z);
this.setMaxX(this.getMaxX() - x);
this.setMaxY(this.getMaxY() - y);
this.setMaxZ(this.getMaxZ() - z);
return this;
}
default AxisAlignedBB setBB(AxisAlignedBB bb) {
this.setMinX(bb.getMinX());
this.setMinY(bb.getMinY());
this.setMinZ(bb.getMinZ());
this.setMaxX(bb.getMaxX());
this.setMaxY(bb.getMaxY());
this.setMaxZ(bb.getMaxZ());
return this;
}
default AxisAlignedBB getOffsetBoundingBox(double x, double y, double z) {
return new SimpleAxisAlignedBB(this.getMinX() + x, this.getMinY() + y, this.getMinZ() + z, this.getMaxX() + x, this.getMaxY() + y, this.getMaxZ() + z);
}
default double calculateXOffset(AxisAlignedBB bb, double x) {
if (bb.getMaxY() <= this.getMinY() || bb.getMinY() >= this.getMaxY()) {
return x;
}
if (bb.getMaxZ() <= this.getMinZ() || bb.getMinZ() >= this.getMaxZ()) {
return x;
}
if (x > 0 && bb.getMaxX() <= this.getMinX()) {
double x1 = this.getMinX() - bb.getMaxX();
if (x1 < x) {
x = x1;
}
}
if (x < 0 && bb.getMinX() >= this.getMaxX()) {
double x2 = this.getMaxX() - bb.getMinX();
if (x2 > x) {
x = x2;
}
}
return x;
}
default double calculateYOffset(AxisAlignedBB bb, double y) {
if (bb.getMaxX() <= this.getMinX() || bb.getMinX() >= this.getMaxX()) {
return y;
}
if (bb.getMaxZ() <= this.getMinZ() || bb.getMinZ() >= this.getMaxZ()) {
return y;
}
if (y > 0 && bb.getMaxY() <= this.getMinY()) {
double y1 = this.getMinY() - bb.getMaxY();
if (y1 < y) {
y = y1;
}
}
if (y < 0 && bb.getMinY() >= this.getMaxY()) {
double y2 = this.getMaxY() - bb.getMinY();
if (y2 > y) {
y = y2;
}
}
return y;
}
default double calculateZOffset(AxisAlignedBB bb, double z) {
if (bb.getMaxX() <= this.getMinX() || bb.getMinX() >= this.getMaxX()) {
return z;
}
if (bb.getMaxY() <= this.getMinY() || bb.getMinY() >= this.getMaxY()) {
return z;
}
if (z > 0 && bb.getMaxZ() <= this.getMinZ()) {
double z1 = this.getMinZ() - bb.getMaxZ();
if (z1 < z) {
z = z1;
}
}
if (z < 0 && bb.getMinZ() >= this.getMaxZ()) {
double z2 = this.getMaxZ() - bb.getMinZ();
if (z2 > z) {
z = z2;
}
}
return z;
}
default boolean intersectsWith(AxisAlignedBB bb) {
if (bb.getMaxY() > this.getMinY() && bb.getMinY() < this.getMaxY()) {
if (bb.getMaxX() > this.getMinX() && bb.getMinX() < this.getMaxX()) {
return bb.getMaxZ() > this.getMinZ() && bb.getMinZ() < this.getMaxZ();
}
}
return false;
}
default boolean isVectorInside(Vector3 vector) {
return vector.x >= this.getMinX() && vector.x <= this.getMaxX() && vector.y >= this.getMinY() && vector.y <= this.getMaxY() && vector.z >= this.getMinZ() && vector.z <= this.getMaxZ();
}
default double getAverageEdgeLength() {
return (this.getMaxX() - this.getMinX() + this.getMaxY() - this.getMinY() + this.getMaxZ() - this.getMinZ()) / 3;
}
default boolean isVectorInYZ(Vector3 vector) {
return vector.y >= this.getMinY() && vector.y <= this.getMaxY() && vector.z >= this.getMinZ() && vector.z <= this.getMaxZ();
}
default boolean isVectorInXZ(Vector3 vector) {
return vector.x >= this.getMinX() && vector.x <= this.getMaxX() && vector.z >= this.getMinZ() && vector.z <= this.getMaxZ();
}
default boolean isVectorInXY(Vector3 vector) {
return vector.x >= this.getMinX() && vector.x <= this.getMaxX() && vector.y >= this.getMinY() && vector.y <= this.getMaxY();
}
default MovingObjectPosition calculateIntercept(Vector3 pos1, Vector3 pos2) {
Vector3 v1 = pos1.getIntermediateWithXValue(pos2, this.getMinX());
Vector3 v2 = pos1.getIntermediateWithXValue(pos2, this.getMaxX());
Vector3 v3 = pos1.getIntermediateWithYValue(pos2, this.getMinY());
Vector3 v4 = pos1.getIntermediateWithYValue(pos2, this.getMaxY());
Vector3 v5 = pos1.getIntermediateWithZValue(pos2, this.getMinZ());
Vector3 v6 = pos1.getIntermediateWithZValue(pos2, this.getMaxZ());
if (v1 != null && !this.isVectorInYZ(v1)) {
v1 = null;
}
if (v2 != null && !this.isVectorInYZ(v2)) {
v2 = null;
}
if (v3 != null && !this.isVectorInXZ(v3)) {
v3 = null;
}
if (v4 != null && !this.isVectorInXZ(v4)) {
v4 = null;
}
if (v5 != null && !this.isVectorInXY(v5)) {
v5 = null;
}
if (v6 != null && !this.isVectorInXY(v6)) {
v6 = null;
}
Vector3 vector = null;
//if (v1 != null && (vector == null || pos1.distanceSquared(v1) < pos1.distanceSquared(vector))) {
if (v1 != null) {
vector = v1;
}
if (v2 != null && (vector == null || pos1.distanceSquared(v2) < pos1.distanceSquared(vector))) {
vector = v2;
}
if (v3 != null && (vector == null || pos1.distanceSquared(v3) < pos1.distanceSquared(vector))) {
vector = v3;
}
if (v4 != null && (vector == null || pos1.distanceSquared(v4) < pos1.distanceSquared(vector))) {
vector = v4;
}
if (v5 != null && (vector == null || pos1.distanceSquared(v5) < pos1.distanceSquared(vector))) {
vector = v5;
}
if (v6 != null && (vector == null || pos1.distanceSquared(v6) < pos1.distanceSquared(vector))) {
vector = v6;
}
if (vector == null) {
return null;
}
int face = -1;
if (vector == v1) {
face = 4;
} else if (vector == v2) {
face = 5;
} else if (vector == v3) {
face = 0;
} else if (vector == v4) {
face = 1;
} else if (vector == v5) {
face = 2;
} else if (vector == v6) {
face = 3;
}
return MovingObjectPosition.fromBlock(0, 0, 0, face, vector);
}
default void setMinX(double minX) {
throw new UnsupportedOperationException("Not mutable");
}
default void setMinY(double minY) {
throw new UnsupportedOperationException("Not mutable");
}
default void setMinZ(double minZ) {
throw new UnsupportedOperationException("Not mutable");
}
default void setMaxX(double maxX) {
throw new UnsupportedOperationException("Not mutable");
}
default void setMaxY(double maxY) {
throw new UnsupportedOperationException("Not mutable");
}
default void setMaxZ(double maxZ) {
throw new UnsupportedOperationException("Not mutable");
}
double getMinX();
double getMinY();
double getMinZ();
double getMaxX();
double getMaxY();
double getMaxZ();
AxisAlignedBB clone();
}
| 9,751 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
NukkitMath.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/math/NukkitMath.java | package cn.nukkit.math;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class NukkitMath {
public static int floorDouble(double n) {
int i = (int) n;
return n >= i ? i : i - 1;
}
public static int ceilDouble(double n) {
int i = (int) (n + 1);
return n >= i ? i : i - 1;
}
public static int floorFloat(float n) {
int i = (int) n;
return n >= i ? i : i - 1;
}
public static int ceilFloat(float n) {
int i = (int) (n + 1);
return n >= i ? i : i - 1;
}
public static int randomRange(NukkitRandom random) {
return randomRange(random, 0);
}
public static int randomRange(NukkitRandom random, int start) {
return randomRange(random, 0, 0x7fffffff);
}
public static int randomRange(NukkitRandom random, int start, int end) {
return start + (random.nextInt() % (end + 1 - start));
}
public static double round(double d) {
return round(d, 0);
}
public static double round(double d, int precision) {
return ((double) Math.round(d * Math.pow(10, precision))) / Math.pow(10, precision);
}
public static double clamp(double check, double min, double max) {
return check > max ? max : (check < min ? min : check);
}
public static double getDirection(double d0, double d1) {
if (d0 < 0.0D) {
d0 = -d0;
}
if (d1 < 0.0D) {
d1 = -d1;
}
return d0 > d1 ? d0 : d1;
}
}
| 1,534 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
VectorMath.java | /FileExtraction/Java_unseen/Nukkit_Nukkit/src/main/java/cn/nukkit/math/VectorMath.java | package cn.nukkit.math;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class VectorMath {
public static Vector2 getDirection2D(double azimuth) {
return new Vector2(Math.cos(azimuth), Math.sin(azimuth));
}
}
| 245 | Java | .java | Nukkit/Nukkit | 821 | 272 | 171 | 2015-05-23T09:51:41Z | 2024-03-21T12:28:05Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.