id
stringlengths
36
36
text
stringlengths
1
1.25M
faebfab9-eae4-4576-9ab3-9e1b712cc7e8
public ObjectDatabase(String envUrl) { // 目录不存在的话创建新目录 if (FileUtils.isExisted(envUrl)) { FileUtils.createPath(envUrl); } // 打开环境 EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(true); envConfig.setAllowCreate(true); environment = new Environment(new File(envUrl), envConfig); // 数据库配置 dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); dbConfig.setTransactional(true); // 设置一个key是否允许存储多个值 dbConfig.setSortedDuplicates(true); }
bdb8c0a9-50e5-4b3a-9075-91cdb087e6bc
public Database createOrOpenDB(String dbName) { return environment.openDatabase(null, dbName, dbConfig); }
98476e90-ca5e-4314-9f7e-884042842ece
public boolean insertDataUnique(Database db, String key, String value, int type) { try { DatabaseEntry keyEntry = new DatabaseEntry(key.getBytes("utf-8")); DatabaseEntry valEntry = new DatabaseEntry(value.getBytes("utf-8")); OperationStatus status = null; if (type == 0) { // Database.put(): 向数据库写入数据,如果不支持重复记录,则会覆盖更新key对应的已有记录 status = db.put(null, keyEntry, valEntry); } else if (type == 1) { // Database.putNoOverwrite():向数据库写入数据,但是如果key已经存在,不会覆盖已有数据(即使数据库支持重复key) status = db.putNoOverwrite(null, keyEntry, valEntry); } else if (type == 2) { // Database.putNoDupData():向数据库写入数据(该方法仅用于支持重复key的数据库), // 如果key和value对应的记录已经存在,那么操作结果是:OperationStatus.KEYEXIST status = db.putNoDupData(null, keyEntry, valEntry); } else { throw new RuntimeException("Param type=" + type + " is error."); } if (status == OperationStatus.SUCCESS) { return Boolean.TRUE; } else if (status == OperationStatus.KEYEXIST) { logger.info("putNoDupData KEYEXIST:" + key); return Boolean.TRUE; } else { logger.error("Insert '" + value + "' in '" + key + "' " + status); return Boolean.FALSE; } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
c43a6739-4be3-490d-be8a-37cc08769af4
public String selectData(Database db, String key, int type) { try { DatabaseEntry value = new DatabaseEntry(); OperationStatus status = null; if (type == 0) { // Database.get() :检索key对应的记录 status = db.get(null, new DatabaseEntry(key.getBytes("utf-8")), value, LockMode.DEFAULT); } else if (type == 1) { // Database.getSearchBoth() :根据key和value 检索数据库记录 status = db.getSearchBoth(null, new DatabaseEntry(key.getBytes("utf-8")), value, LockMode.DEFAULT); } else { throw new RuntimeException("Param type=" + type + " is error."); } if (status == OperationStatus.SUCCESS) { return new String(value.getData(), "utf-8"); } else { throw new RuntimeException("Read data in '" + key + "' " + status); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
1379137e-2f53-488a-8a91-3f355197fdfe
public String updateData(Database db, String key, String value) { try { DatabaseEntry keyEntry = new DatabaseEntry(key.getBytes("utf-8")); DatabaseEntry valEntry = new DatabaseEntry(value.getBytes("utf-8")); OperationStatus status = db.put(null, keyEntry, valEntry); DatabaseEntry valueGet = new DatabaseEntry(); status = db.get(null, keyEntry, valueGet, LockMode.DEFAULT); if (status == OperationStatus.SUCCESS) { return new String(valueGet.getData(), "utf-8"); } else { throw new RuntimeException("Update '" + value + "' in '" + key + "' " + status); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
695eaa17-23af-4dbd-b2b4-b1d7436ebbd8
public boolean deleteData(Database db, String key) { try { OperationStatus status = db.delete(null, new DatabaseEntry(key.getBytes("utf-8"))); if (status == OperationStatus.SUCCESS) { return Boolean.TRUE; } else { logger.error("Read data in '" + key + "' " + status); return Boolean.FALSE; } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
6c152bb0-6ab0-4ab5-83ed-711a849ef79e
public void close() { environment.sync(); environment.cleanLog(); environment.close(); }
4451a047-a27a-4fd8-9571-a88edabc0285
public CuentaAtras10(String s, int i) { this.cont = i; this.id = s; }
e8284d60-a35b-4981-93a8-23edc97a41e8
public void run() { PruebaThreads.setT(PruebaThreads.getT() + 1); while (cont >= 0) { String s = PruebaThreads.getClase(); if (s == null) { System.out.println(this.id + " - " + cont + " Sin ultima lectura"); } else { System.out.println(this.id + " - " + cont + " Ultima escritura " + s); } PruebaThreads.setClase(id); if (cont == 0) { int r = PruebaThreads.getT(); PruebaThreads.setT(r - 1); System.out.println("Ultima escritura " + PruebaThreads.getClase() + " - " + (r - 1) + " Threads activos"); } else { Delaysegundo(); } cont--; } }
ae92d087-33e3-423f-a3c6-bee3db7b05e3
private void Delaysegundo() { try { Thread.sleep(1000); } catch (InterruptedException e) { } }
80f4c866-84c8-4040-abd0-8b8ec51bda8a
public static void main(String args[]) { (new Thread(new CuentaAtras11("ID1", 4))).start(); (new Thread(new CuentaAtras11("ID2", 7))).start(); (new Thread(new CuentaAtras11("ID3", 8))).start(); }
4b998c30-dbd6-4a4d-9cbd-72a4533dd40a
public synchronized static int getT() { return t; }
fccd7eb4-f68e-4505-9585-e5c213dd5b0b
public synchronized static void setT(int i) { PruebaThreads11.t = i; }
64ffa9b1-2899-414e-a239-7520635b5727
public synchronized static String getClase() { return clase; }
04ad47c2-aaf9-4245-85ac-46f3659c2717
public synchronized static void setClase(String i) { PruebaThreads11.clase = i; }
e377ccb1-99c3-4d28-a04a-3f4641ddd29a
public static void main(String args[]) { (new Thread(new CuentaAtras9("ID1", 4))).start(); (new Thread(new CuentaAtras9("ID2", 7))).start(); (new Thread(new CuentaAtras9("ID3", 8))).start(); }
c1e7281f-024c-4963-ba44-24a85986ba41
public static void main(String args[]) { (new Thread(new CuentaAtras10("ID1", 4))).start(); (new Thread(new CuentaAtras10("ID2", 7))).start(); (new Thread(new CuentaAtras10("ID3", 8))).start(); }
3cbc62ab-9a6c-476c-b10a-c855fff4e1c8
public static int getT() { return t; }
807c73ae-0119-4090-9296-1a5afee50d02
public static void setT(int i) { PruebaThreads.t = i; }
05358126-210d-42bd-9794-1184df0a09c6
public static String getClase() { return clase; }
c4244100-5eef-4aad-b430-82542d271751
public static void setClase(String i) { PruebaThreads.clase = i; }
04d281f2-8c11-4a45-804f-f6a87b46ed77
public static void main(String args[]) throws InterruptedException { CuentaAtras8 contador1 = new CuentaAtras8("ID1", 4); CuentaAtras8 contador2 = new CuentaAtras8("ID2", 7); CuentaAtras8 contador3 = new CuentaAtras8("ID3", 8); contador1.start(); contador2.start(); contador3.start(); }
0e6a96b9-5fae-46f5-b5a7-405cb03522aa
public CuentaAtras9(String s, int i) { this.cont = i; this.id = s; }
7a87a894-f32b-43ed-af7f-097ccaa63c6b
public void run() { while (cont > 0) { System.out.println(this.id + ": " + cont); cont--; Delaysegundo(); } }
f24087df-f913-4eca-bbca-5de1614f1f3f
private void Delaysegundo() { try { Thread.sleep(1000); } catch (InterruptedException e) { } }
24b64aee-9b80-4f2f-bafc-76ef96cc9771
public CuentaAtras8(String s, int i) { this.cont = i; this.id = s; }
9ec038cd-a99b-48ca-83b1-a429f6418908
public void run() { while (cont >= 0) { System.out.println(this.id + ": " + cont); cont--; Delaysegundo(); } }
f82ce3ed-f013-4027-8fdd-235216616a2f
private void Delaysegundo() { try { Thread.sleep(1000); } catch (InterruptedException e) { } }
6cec250a-3a4e-4eb7-8300-803d8b67774b
public CuentaAtras11(String s, int i) { this.cont = i; this.id = s; }
183ef0db-65a1-4a60-9f06-cb870574cc49
public void run() { PruebaThreads11.setT(PruebaThreads11.getT() + 1); while (cont >= 0) { String s = PruebaThreads11.getClase(); if (s == null) { System.out.println(this.id + " - " + cont + " Sin ultima lectura"); } else { System.out.println(this.id + " - " + cont + " Ultima escritura " + s); } PruebaThreads11.setClase(id); if (cont == 0) { int r = PruebaThreads11.getT(); PruebaThreads11.setT(r - 1); System.out.println("Ultima escritura " + PruebaThreads11.getClase() + " - " + (r - 1) + " Threads activos"); } else { Delaysegundo(); } cont--; } }
2c35bd64-76fb-44da-8f69-b39ec11dbef2
private void Delaysegundo() { try { Thread.sleep(1000); } catch (InterruptedException e) { } }
ca0ba069-6b98-43f8-966c-ead76761f0d0
public static void main( String[] args ) { System.out.println( "Hello World!" ); }
8bdd3704-9fc1-4a18-9c6f-c63aa48df3e0
public AppTest( String testName ) { super( testName ); }
eacd4890-144c-4868-aa23-6708c56a919d
public static Test suite() { return new TestSuite( AppTest.class ); }
ef5d715a-ad47-4c73-9f14-6788edacb6a2
public void testApp() { assertTrue( true ); }
8f0cdb02-261d-48ab-b637-cdc79ad9c52a
public void handlePacket(DatagramPacket packet) { try { Packet.constructAndHandle(packet); } catch(Exception e) { e.printStackTrace(); } }
f4e091b5-9a54-4fdf-8a24-6ff4421db328
private Server(String name, int port) throws SocketException { instance = this; logger = Logger.getLogger("MCPE_Server"); logger.setLevel(Level.ALL); logger.setUseParentHandlers(false); for(Handler h : logger.getHandlers()) logger.removeHandler(h); logger.addHandler(new Handler() { DateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); @Override public void publish(LogRecord record) { Level l = record.getLevel(); PrintStream out = l.intValue() > Level.INFO.intValue() ? System.err : System.out; out.println(df.format(new Date(record.getMillis())) + " [" + record.getLoggerName() + "]" + "[" + l.getLocalizedName() + "] " + record.getMessage()); } @Override public void flush() { System.out.flush(); System.err.flush(); } @Override public void close() throws SecurityException { System.out.close(); System.err.close(); } }); random = new Random(); serverId = 0x372cdc9e; serverName = name; serverType = "Demo"; try { pcapLogger = new PcapLogger(new FileOutputStream("packets.pcap")); packetLogger = new PrintStream("packets.log"); } catch(FileNotFoundException e) { e.printStackTrace(); } clients = new HashMap<Integer, EntityPlayer>(); players = new HashMap<String, EntityPlayer>(); whitelist = new ArrayList<String>(); banned = new ArrayList<String>(); bannedIps = new ArrayList<InetAddress>(); serverSocket = new DatagramSocket(port); handler = new PacketHandler(); log("Starting Minecraft PE server on " + serverSocket.getInetAddress()+ ":" + port); }
d8592aae-9304-41a8-99e0-8da255fb27f2
@Override public void publish(LogRecord record) { Level l = record.getLevel(); PrintStream out = l.intValue() > Level.INFO.intValue() ? System.err : System.out; out.println(df.format(new Date(record.getMillis())) + " [" + record.getLoggerName() + "]" + "[" + l.getLocalizedName() + "] " + record.getMessage()); }
4f02f11e-35db-43a4-8a87-4e7530836f38
@Override public void flush() { System.out.flush(); System.err.flush(); }
079a4172-f39f-4662-ac91-62ab9e159622
@Override public void close() throws SecurityException { System.out.close(); System.err.close(); }
7a6dfa3e-c4e8-407c-bc4e-6ed1c01fc808
@Override public void run() { running = true; while(running) { DatagramPacket p = new DatagramPacket(new byte[18 + mtu], 18 + mtu); try { serverSocket.receive(p); p.setData(p.getData(), 0, p.getLength()); pcapLogger.logPacket(p, p.getAddress(), p.getPort(), serverSocket.getLocalAddress(), serverSocket.getLocalPort()); Utils.dumpPacket(p, p.getAddress(), p.getPort(), serverSocket.getLocalAddress(), serverSocket.getLocalPort(), packetLogger); handler.handlePacket(p); } catch(IOException e) { e.printStackTrace(); } } }
a6c287fb-dc73-49ac-9d5d-87b3b5a68798
public void sendToClient(DatagramPacket packet) { try { pcapLogger.logPacket(packet, serverSocket.getLocalAddress(), serverSocket.getLocalPort(), packet.getAddress(), packet.getPort()); Utils.dumpPacket(packet, serverSocket.getLocalAddress(), serverSocket.getLocalPort(), packet.getAddress(), packet.getPort(), packetLogger); serverSocket.send(packet); } catch(IOException e) { e.printStackTrace(); } }
ee7a384c-f076-40ce-9583-7326e5e6957a
public void log(Level level, String message) { logger.log(level, message); }
5379f5d4-48e6-476f-8db6-0237dc872666
public void log(String message) { log(Level.INFO, message); }
4680aceb-88f4-404b-b313-8c7e8ca7106c
public void error(String message) { log(Level.SEVERE, message); }
9788a081-6aef-4a3b-bcff-6ed0af27f14b
public void warning(String message) { log(Level.WARNING, message); }
ebc71747-f24e-4e80-b6ea-d40a0e36f24e
public void debug(String message) { log(debugLevel, message); }
2b501af0-221f-41c2-b3a6-03554ade870a
public static void main(String[] args) { try { new Server("SuperCraftServer", 19132).start(); } catch(SocketException e) { e.printStackTrace(); } }
ccb60556-353c-4ddb-bf57-37fc33ab6a66
public static void writeString(String s, DataOutput out) throws IOException { out.writeShort(s.length()); out.writeBytes(s); }
a28d2de6-4209-4f9b-9647-e6bbb4866c26
public static String readString(DataInputStream in) throws IOException { short length = in.readShort(); byte[] bytes = new byte[length]; in.read(bytes); return new String(bytes); }
c51c2e88-d46a-4ade-be42-d64a9ef59392
public static String toHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for(byte b : bytes) { sb.append(String.format(sb.length() == 0 ? "%02X" : " %02X", b)); } return sb.toString(); }
bd288157-be65-49fa-a3d2-f70c8c3199b0
public static String hexdump(byte[] bytes) { StringBuilder sb = new StringBuilder(); for(int addr = 0; addr < bytes.length; addr++) { if((addr&0xF) == 0) { if(addr != 0) sb.append('\n'); sb.append(String.format("%08X: ", addr)); } sb.append(String.format("%02X", bytes[addr])); if((addr&0xF) != 15) sb.append(' '); } return sb.toString(); }
f704b3e4-d3f1-4285-8257-9baf924e2db6
public static void dumpPacket(DatagramPacket p, InetAddress src, int srcport, InetAddress dst, int dstport, PrintStream out) { out.println("Timestamp : " + new SimpleDateFormat().format(new Date())); out.println("Source : " + src + ":" + srcport); out.println("Destination: " + dst + ":" + dstport); out.println("Data:"); out.println(hexdump(p.getData())); }
80252f95-a5fd-4377-9887-2f5433188ddd
public PcapLogger(OutputStream out) { this.out = new DataOutputStream(out); startMillis = System.currentTimeMillis(); startNanos = System.nanoTime(); }
4db54803-d1e1-43fc-9071-c2773564c80f
public void init() { if(init)return; try { out.writeInt(0xa1b2c3d4);//Using microsecond resolution because most Java implementations return nanoTime() in steps of 1000 out.writeShort(2);//Version 2.4 out.writeShort(4); out.writeInt(0);//Writing in UTC timezone out.writeInt(0);//Everyone does so out.writeInt(0xFFFF);//Capturing UDP so MAX_PACKET_LENGTH is 65535 out.writeInt(101);//Will write packets as IP packets out.flush(); } catch(IOException e) { e.printStackTrace(); } init = true; }
7a968ea4-0083-4210-bf71-528e4b15fecd
public void logPacket(DatagramPacket packet, InetAddress src, int srcport, InetAddress dst, int dstport) { if(!init) init(); int ts_sec = (int)((System.currentTimeMillis())/1000); int ts_usec = (int)((System.nanoTime())/1000)%1000000; try { out.writeInt(ts_sec); out.writeInt(ts_usec); byte[] bytes = encapsulateIP(packet, src, srcport, dst, dstport); out.writeInt(bytes.length&0xFFFF); out.writeInt(bytes.length); out.flush(); if(bytes.length > 0) out.write(bytes, 0, bytes.length&0xFFFF); out.flush(); } catch(IOException e) { e.printStackTrace(); } }
1ccd57d5-5aad-4d6f-8fa2-704b9c834fd4
private byte[] encapsulateIP(DatagramPacket packet, InetAddress src, int srcport, InetAddress dst, int dstport) throws IOException { boolean ipv4 = src instanceof Inet4Address; int data_length = packet.getLength(); int length = data_length + (ipv4 ? 20 : 40) + 8; ByteArrayOutputStream bytes = new ByteArrayOutputStream(length); DataOutputStream tout = new DataOutputStream(bytes); //IP Header byte[] ip_header = new byte[0]; if(ipv4) { ip_header = new byte[]{ 0x45,0x00,(byte)((length<<8)&0xFF),(byte)(length&0xFF), 0x00, 0x00, 0x00, 0x00, (byte)0xFF, 0x11, 0x00, 0x00, 0,0,0,0,//src ip 0,0,0,0//dst ip }; System.arraycopy(src.getAddress(), 0, ip_header, 12, 4); System.arraycopy(dst.getAddress(), 0, ip_header, 16, 4); int checksum = 0; for(int i = 0; i < ip_header.length - 1; i += 2) { checksum += ip_header[i] << 8 | ip_header[i+1]; } checksum&=0xFFFF; checksum+=2; checksum = ~checksum; ip_header[10] = (byte) ((checksum>>8)&0xFF); ip_header[11] = (byte) (checksum&0xFF); tout.write(ip_header); }else { return new byte[0];//TODO: IPv6 } //UDP Header tout.writeShort(srcport); tout.writeShort(dstport); tout.writeShort(data_length); tout.writeShort(0); tout.write(packet.getData()); return bytes.toByteArray(); }
78fe57a4-41d7-4bdf-80d1-6d7cdedc13c7
public PacketPayload(InetAddress ip, int port, byte[] data) { super(ip, port, data); }
380ace69-f66e-415a-913b-7e2f5bab70f9
public PacketPayload(InetAddress ip, int port) { super(ip, port); }
48d15832-f0a8-437e-91b4-9f3594bb9f32
@Override public void handle() throws Exception { int pid = in.readByte(); int count = in.readShort()<<8; count |= ((int)in.readByte())&0xFF; //if(pid < 0x80 || pid > 0x8F)return; byte encapsulationId = in.readByte(); short length = (short) (in.readShort()/8); if(length == 0) { server.warning(String.format("Recieved PacketPayload with 0 length (Packet id 0x%02X, Encapsulation 0x%02X, count 0x%06X)", pid, encapsulationId, count)); return; } payload = new byte[length]; if(encapsulationId == 0x40 || encapsulationId == 0x60) { in.readByte(); in.readByte(); in.readByte(); if(encapsulationId == 0x60) { in.readInt(); } } in.read(payload); in.close(); server.debug("Recieved " + this); payloadIn = new DataInputStream(new ByteArrayInputStream(payload)); EntityPlayer player = server.clients.get(ip.hashCode() + port); if(player == null) { payloadIn.close(); server.warning("No player from " + ip + ":" + port + " exists. Packet dropped."); return; } player.count = count; PacketAck ack = new PacketAck(ip, port); ack.construct(count); ack.send(); player.handleDataPacket(payload, payloadIn); payloadIn.close(); }
5b041162-d133-4a6c-8c99-270f3aea19a6
@Override public void construct(Object... data) { payload = (byte[])data[1]; int count = (short)(int)data[0]; try { out.writeInt(count | 0x80000000); out.write(0x00); out.writeShort(payload.length*8); out.write(payload); } catch(IOException e) { e.printStackTrace(); } }
d213c5d5-c12f-4b7a-a2d5-0e0561215ac0
@Override public String toString() { return super.toString() + (payload != null && payload.length > 0 ? String.format(" (0x%02X/%s)", payload[0], Constants.MC_NAMES[((int)payload[0])&0xFF]) : ""); }
183390e4-14e8-454b-bbb9-ffec5da83115
public Packet(InetAddress ip, int port, byte[] data) { this.ip = ip; this.port = port; this.data = data; this.in = new DataInputStream(new ByteArrayInputStream(data)); }
43a07957-c372-4dd2-a648-9a7a84b1792c
public Packet(InetAddress ip, int port) { this.ip = ip; this.port = port; this.bout = new ByteArrayOutputStream(); this.out = new DataOutputStream(bout); }
aa059c69-fcf3-4bfb-bb67-73440c1c62a9
public void handle() throws Exception { server.error("Packet type " + this.getClass().getSimpleName() + " cannot be handled"); }
dc329f70-5f42-43ad-8c7f-895ac51e1345
public void send() { if(bout != null) this.data = bout.toByteArray(); if(!(this instanceof PacketAck))server.debug("Sending " + this); server.sendToClient(new DatagramPacket(data, data.length, ip, port)); try { out.close(); } catch(IOException e) { e.printStackTrace(); } }
49c36179-62e9-4cfc-8e84-f8c569182df7
public void construct(Object... data) { server.error("Packet type " + this.getClass().getSimpleName() + " cannot be constructed"); }
7116d5b1-0f80-4284-8cc6-21da99c541c4
@Override public String toString() { return this.getClass().getSimpleName() + (data.length > 0 ? String.format(" 0x%02X", data[0]) : ""); }
5855c550-c778-452c-ab03-6aad5ad9e5b7
public static Packet construct(DatagramPacket packet) { byte[] data = packet.getData(); if(data.length == 0) { server.warning("Empty packet from " + packet.getAddress() + ":" + packet.getPort()); return null; } Class<? extends Packet> clazz = classes[((int)data[0])&0xFF]; if(clazz == null) { server.warning(String.format("Invalid packet id 0x%02X from %s:%d", ((int)data[0])&0xFF, packet.getAddress(), packet.getPort())); return null; } try { Constructor<? extends Packet> constructor = clazz.getConstructor(InetAddress.class, int.class, byte[].class); Packet p = constructor.newInstance(packet.getAddress(), packet.getPort(), data); if(!(p instanceof PacketPayload || p instanceof PacketAck))server.debug("Recieved " + p); return p; } catch(Exception e) { e.printStackTrace(); return null; } }
4183e91c-26be-474c-86ea-24496e0c51a8
public static void constructAndHandle(DatagramPacket packet) throws Exception { Packet p = construct(packet); if(p != null) p.handle(); }
700c2b4e-72f5-431b-a885-c96e9d4153d7
public PacketAck(InetAddress ip, int port) { super(ip, port); }
a3e32a5e-cbe7-41bb-92d6-010c134ff2a7
public PacketAck(InetAddress ip, int port, byte[] data) { super(ip, port, data); }
897d3318-a56f-4f93-b47e-2b3bbc19bb01
@Override public void handle() throws Exception { }
88bb03c8-2a8c-4ef3-b8ac-30273e2ec067
@Override public void construct(Object... data) { try { out.write(0xC0); out.writeShort(1); out.write(((int)data[0])&0xFFFFFF | 0x01000000); } catch(IOException e) { e.printStackTrace(); } }
2d9fcaa9-208b-4ec6-9a6f-2fe9c20b9030
public PacketOpenConnectionReply(InetAddress ip, int port) { super(ip, port); }
d2847134-02ae-4dd3-8aec-40f0483a83d0
@Override public void construct(Object... data) { try { out.writeByte(((Boolean)data[0]) ? 8 : 6); out.write(Constants.RAKNET_MAGIC); if((Boolean)data[0]) { out.writeLong(server.serverId); out.writeShort((Short)data[1]); out.writeShort((Short)data[2]); out.write(0); }else { out.writeLong(server.serverId); out.write(0); out.writeShort((Short)data[1]); } } catch(IOException e) { e.printStackTrace(); } }
af315d96-a45f-466d-b5d7-838fef761e29
public PacketIncompatibleProtocolVersion(InetAddress ip, int port) { super(ip, port); }
e655cbf3-977e-4166-857e-729308d25c88
@Override public void construct(Object... data) { try { out.writeByte((Byte)Constants.RAKNET_VERSION); out.write(Constants.RAKNET_MAGIC); out.writeLong(server.serverId); } catch(IOException e) { e.printStackTrace(); } }
e868d67e-e416-450b-879c-762ca3acf511
public PacketOpenConnectionRequest(InetAddress ip, int port, byte[] data) { super(ip, port, data); }
787abdf4-f4e7-4917-9639-ecc55465783c
@Override public void handle() throws Exception { byte pid = in.readByte(); if(!(pid == 5 || pid == 7)) { server.error(String.format("%s got wrong packet id: %u02X", this.getClass().getSimpleName(), pid)); in.close(); return; } if(pid == 5) { in.readLong(); in.readLong(); byte version = in.readByte(); if(version != Constants.RAKNET_VERSION) { Packet ipv = new PacketIncompatibleProtocolVersion(ip, port); ipv.construct(); ipv.send(); in.close(); return; } short mtu = (short) (data.length - 18); Packet reply = new PacketOpenConnectionReply(ip, port); reply.construct(false, mtu); reply.send(); }else if(pid == 7) { in.readLong(); in.readLong(); in.readByte(); in.readInt(); in.readShort(); short mtu = in.readShort(); long clientID = in.readLong(); server.clients.put(ip.hashCode() + port, new EntityPlayer(clientID, ip, port, mtu)); server.debug("Adding client from " + ip + ":" + port); server.log(String.format("%016X logged in from %s:%d with mtu %d", clientID, ip, port, mtu)); Packet reply = new PacketOpenConnectionReply(ip, port); reply.construct(true, (short)port, mtu); reply.send(); } }
c25202a8-88af-4b8d-a79b-e11fe222f884
public PacketPing(InetAddress from, int port, byte[] data) { super(from, port, data); }
39dd2f7d-3f07-422c-bd2d-a2570a773ece
@Override public void handle() throws IOException { byte pid = in.readByte(); if(!(pid == 1 || pid == 2)) { server.error(String.format("%s got wrong packet id: %u02X", this.getClass().getSimpleName(), pid)); in.close(); return; } pingId = in.readLong(); magic1 = in.readLong(); magic2 = in.readLong(); boolean magic = magic1 == Constants.RAKNET_MAGIC_1 && magic2 == Constants.RAKNET_MAGIC_2; //server.debug("Recieved ping from " + ip + ":" + port + ", packet-id: " + pid + ", ping-id: " + pingId + (magic ? ", magic matched" : ", wrong magic: 0x" + String.format("%08X%08X", magic1, magic2))); PacketPong response = new PacketPong(ip, port); response.construct((byte) 0x1C, pingId); response.send(); in.close(); }
e3069ad3-94c1-4086-9ef7-14cb6929b21f
public PacketPong(InetAddress from, int port) { super(from, port); }
a54a889f-44e4-466d-bc7c-0ec150190c65
@Override public void construct(Object... data) { try { out.writeByte((Byte)data[0]); out.writeLong((Long)data[1]); out.writeLong(server.serverId); out.write(Constants.RAKNET_MAGIC); Utils.writeString("MCCPP;" + server.serverType + ";" + server.serverName + " [" + server.clients.size() + "/" + server.maxClients + "]", out); } catch(IOException e) { e.printStackTrace(); } }
c2c6b34d-191b-4044-8e2f-7398c224ba25
public EntityPlayer(long clientID, InetAddress ip, int port, int mtu) { this.clientID = clientID; this.ip = ip; this.port = port; this.mtu = mtu; }
be5aa308-ad36-42b9-8e21-3ff9343a48e2
public void handleDataPacket(byte[] payload, DataInputStream in) throws IOException { switch(in.readByte()) { case MC_PONG: break; case MC_PING: { long ptime = in.readLong(); long time = System.currentTimeMillis(); sendPacket(MC_PONG, ptime, time); break; } case MC_CLIENT_CONNECT: { if(loggedIn)break; long clientID = in.readLong(); long session = in.readLong(); sendPacket(MC_SERVER_HANDSHAKE, 0x043f57f3, (byte)0xcd, (short)this.port, new byte[]{(byte)0xf5,-1,-1,(byte)0xf5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, session, new byte[]{0x00,0x00,0x00,0x00,0x04,0x44,0x0b,(byte)0xa9}); break; } case MC_CLIENT_HANDSHAKE: break; case MC_LOGIN: { if(loggedIn)break; String username = Utils.readString(in); int protocol1 = in.readInt(); int protocol2 = in.readInt(); int clientId = in.readInt(); realmsData = new byte[in.readShort()]; in.read(realmsData); if(server.clients.size() >= server.maxClients) { close("Server is full!", false); break; } if(protocol1 != PROTOCOL_VERSION) { sendPacket(MC_LOGIN_STATUS, protocol1 < PROTOCOL_VERSION ? 1 : 2); close("Incorrect protocol#"+protocol1, false); break; } if(username.matches("[a-zA-Z0-9_]+") && username.length() > 0) this.username = username; else { close("Bad Username", false); break; } if(server.hasWhitelist && !server.whitelist.contains(username)) { close("Server is white-listed", false); break; } if(server.banned.contains(username) || server.bannedIps.contains(ip)) { close("You are banned!", false); break; } loggedIn = true; EntityPlayer p1 = server.players.get(username); if(p1 != null) p1.close("logged in from another location", true); server.players.put(username, this); server.log(username + " logged in from " + ip + ":" + port); sendPacket(MC_LOGIN_STATUS, 0); } } }
bf2b06dd-5c5c-4334-8147-f9e1da6bff33
public void close(String reason, boolean message) { }
7792c403-387a-4aab-acdb-db39612f1dd2
public void sendChat(String message, String author) { }
93d575d1-f5f6-4489-a715-034839d1b67c
public void sendChat(String message) { }
4531edf2-4fb8-43b6-9c93-2a024359fb98
private void sendPacket(byte id, Object... data) throws IOException { ByteArrayOutputStream bo = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bo); out.write(id); for(Object o : data) { if(o == null) throw new IOException("Object is null"); if(o instanceof String) Utils.writeString((String)o, out); else if(o instanceof Byte) out.writeLong((Byte)o); else if(o instanceof Short) out.writeShort((Short)o); else if(o instanceof Integer) out.writeInt((Integer)o); else if(o instanceof Long) out.writeLong((Long)o); else if(o instanceof Float) out.writeFloat((Float)o); else if(o instanceof Double) out.writeDouble((Double)o); else if(o instanceof Character) out.writeChar((Character)o); else if(o instanceof byte[]) out.write((byte[])o); else throw new IOException("Invalid type " + o.getClass().getName()); } PacketPayload p = new PacketPayload(ip, port); p.construct(count++, bo.toByteArray()); p.send(); }
037416e2-6fc9-4d48-b259-94b2cf2c110d
public class Brie extends BaseCheese { String brieName() { return "This is brie"; } }
a3a2506e-b62a-446c-8afd-c4d9ab7b520f
public interface Visitor { void visit(Cheese c) throws Exception; }
395a414f-3d44-4e08-b991-1f5ef5a65a23
private Method getPolymorphicMethod(Cheese cheese) throws Exception { Class cl = cheese.getClass(); // the bottom-most class // Check through superclasses for matching method while(!cl.equals(Object.class)) { try { return this.getClass().getDeclaredMethod("visit", new Class[] { cl }); } catch(NoSuchMethodException ex) { cl = cl.getSuperclass(); } } // Check through interfaces for matching method Class[] interfaces = cheese.getClass().getInterfaces(); for (int i=0; i<interfaces.length; i++) { try { return this.getClass().getDeclaredMethod("visit", new Class[] { interfaces[i] }); } catch(NoSuchMethodException ex) { } } return null; }
99351ec8-a338-4b27-9ea2-ccd5fbadc712
public void visit(Cheese c) throws Exception { Method downPolymorphic = getPolymorphicMethod(c); if (downPolymorphic == null) { defaultVisit(c); } else { downPolymorphic.invoke(this, new Object[] {c}); } }
335d14ea-81d0-4c8a-a736-58180cd2b987
void defaultVisit(Cheese c) { System.out.println("A cheese"); }
e5d53fae-884a-4b54-ab1e-2923ac4adf35
void visit(Wensleydale w) { System.out.println(w.wensleydaleName()); }
28f97512-dd5a-45e8-ac8d-3ed059b94e2c
void visit(Gouda g) { System.out.println(g.goudaName()); }
86862f29-5960-4b3a-8510-5b87ab098e01
void visit(Brie b) { System.out.println(b.brieName()); }
2d67015e-cf44-4929-855f-a44573524524
void visit(AnotherCheese a) { System.out.println(a.otherCheeseName()); }
44a68bda-4e1b-42dc-9047-d79bccd32b55
public class Gorgonzola extends BaseCheese { String gorgonzolaName() { return "This is gorgonzola"; } }