### Java Primitive Type Maps for Performance Source: https://context7.com/hytale-server/hytale-src/llms.txt Demonstrates the use of fastutil's primitive type maps (Int2ObjectMap, Long2LongMap, Byte2ObjectConcurrentHashMap) to store and retrieve data without autoboxing overhead. These collections are crucial for performance-sensitive areas like player data management and entity tracking in the Hytale server. The example also shows efficient iteration using primitive iterators. ```java import com.hypixel.fastutil.ints.*; import com.hypixel.fastutil.longs.*; // Int to Object map (no autoboxing) Int2ObjectMap playerNames = new Int2ObjectOpenHashMap<>(); playerNames.put(1001, "Alice"); playerNames.put(1002, "Bob"); String name = playerNames.get(1001); // Long to Long map for entity tracking Long2LongMap entityHealth = new Long2LongOpenHashMap(); entityHealth.put(999999L, 100L); entityHealth.put(888888L, 75L); long health = entityHealth.get(999999L); // Concurrent map for thread-safe access Byte2ObjectConcurrentHashMap blockCache = new Byte2ObjectConcurrentHashMap<>(); blockCache.put((byte) 1, new BlockData("stone")); blockCache.put((byte) 2, new BlockData("dirt")); // Iterate with primitive iterators (no boxing) Int2ObjectMap.FastEntrySet entries = playerNames.int2ObjectEntrySet(); for (Int2ObjectMap.Entry entry : entries) { int id = entry.getIntKey(); // primitive int, no autoboxing String playerName = entry.getValue(); System.out.println(id + ": " + playerName); } ``` -------------------------------- ### Initialize Hytale Server: Main Entry Point (Java) Source: https://context7.com/hytale-server/hytale-src/llms.txt The main entry point for the Hytale server. It sets system defaults, loads early plugins with transformation support, and determines whether to launch with a transforming classloader or proceed with late initialization. ```java package com.hypixel.hytale; public class Main { public static void main(String[] args) { // Set system defaults Locale.setDefault(Locale.ENGLISH); System.setProperty("java.awt.headless", "true"); System.setProperty("file.encoding", "UTF-8"); // Load early plugins with transformation support EarlyPluginLoader.loadEarlyPlugins(args); if (EarlyPluginLoader.hasTransformers()) { launchWithTransformingClassLoader(args); } else { LateMain.lateMain(args); } } } ``` -------------------------------- ### Reusable Compression Contexts with Zstd Source: https://context7.com/hytale-server/hytale-src/llms.txt Demonstrates the use of reusable Zstd compression and decompression contexts for improved performance when handling multiple data operations. It shows how to set compression levels, worker threads, and checksums, and how to manage decompression with multiple dictionary support. ```java import com.github.luben.zstd.ZstdCompressCtx; import com.github.luben.zstd.ZstdDecompressCtx; // Reusable compression context try (ZstdCompressCtx ctx = new ZstdCompressCtx()) { ctx.setLevel(9); ctx.setChecksum(true); ctx.setWorkers(4); // Compress multiple buffers with same context for (byte[] data : dataBatches) { byte[] compressed = new byte[(int) Zstd.compressBound(data.length)]; long size = ctx.compress(compressed, data); sendCompressed(compressed, size); } } // Reusable decompression context try (ZstdDecompressCtx ctx = new ZstdDecompressCtx()) { ctx.setRefMultipleDDicts(true); for (byte[] compressed : compressedBatches) { long originalSize = Zstd.getFrameContentSize(compressed); byte[] decompressed = new byte[(int) originalSize]; long size = ctx.decompress(decompressed, compressed); processDecompressed(decompressed, size); } } ``` -------------------------------- ### Stream Compression and Decompression with Zstandard in Java Source: https://context7.com/hytale-server/hytale-src/llms.txt Java code demonstrating stream-based compression and decompression using Zstandard. It shows how to write compressed data to an output stream and read decompressed data from an input stream, including options for checksums, parallel compression, and continuous stream processing. ```java import com.github.luben.zstd.ZstdOutputStream; import com.github.luben.zstd.ZstdInputStream; import java.io.*; // Assume getData(), processData() are defined elsewhere // byte[] data = getData(); // void processData(byte[] buffer, int bytesRead) { /* ... */ } // Compress data to stream try (FileOutputStream fos = new FileOutputStream("output.zst"); ZstdOutputStream zos = new ZstdOutputStream(fos, 5)) { // compression level 5 zos.setChecksum(true); zos.setWorkers(4); // parallel compression byte[] data = getData(); zos.write(data); zos.flush(); } catch (IOException e) { e.printStackTrace(); } // Decompress stream try (FileInputStream fis = new FileInputStream("output.zst"); ZstdInputStream zis = new ZstdInputStream(fis)) { zis.setContinuous(true); // support multiple frames byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = zis.read(buffer)) != -1) { processData(buffer, bytesRead); } } catch (IOException e) { e.printStackTrace(); } ``` -------------------------------- ### Netty ByteBuf Buffer Management Source: https://context7.com/hytale-server/hytale-src/llms.txt Illustrates Netty's ByteBuf buffer management, including adaptive allocation, pooling, and the creation of direct (off-heap) and heap buffers. It also demonstrates the use of CompositeByteBuf for efficient zero-copy operations. ```java import io.netty.buffer.*; // Create pooled allocator with adaptive sizing ByteBufAllocator allocator = new AdaptiveByteBufAllocator(); // Allocate direct buffer (off-heap) ByteBuf directBuffer = allocator.directBuffer(1024); try { directBuffer.writeInt(42); directBuffer.writeBytes("Hello".getBytes()); // Read data int value = directBuffer.readInt(); byte[] text = new byte[directBuffer.readableBytes()]; directBuffer.readBytes(text); } finally { directBuffer.release(); // Important: release buffer back to pool } // Allocate heap buffer ByteBuf heapBuffer = allocator.heapBuffer(512); try { heapBuffer.writeIntLE(100); // Little-endian heapBuffer.writeLongLE(System.currentTimeMillis()); } finally { heapBuffer.release(); } // Composite buffer for zero-copy operations CompositeByteBuf composite = allocator.compositeBuffer(); try { composite.addComponent(true, allocator.buffer().writeBytes("Header".getBytes())); composite.addComponent(true, allocator.buffer().writeBytes("Body".getBytes())); composite.addComponent(true, allocator.buffer().writeBytes("Footer".getBytes())); // Access as single buffer byte[] fullData = new byte[composite.readableBytes()]; composite.readBytes(fullData); } finally { composite.release(); } ``` -------------------------------- ### Initialize Hytale Server: Late Initialization (Java) Source: https://context7.com/hytale-server/hytale-src/llms.txt Handles the late-stage server initialization, including configuring logging, error tracking, and creating the main HytaleServer instance. It parses command-line options and sets up custom log level loading. ```java package com.hypixel.hytale; public class LateMain { public static void lateMain(String[] args) { try { // Parse command-line options if (Options.parse(args)) return; // Initialize Hytale logging system HytaleLogger.init(); HytaleFileHandler.INSTANCE.enable(); HytaleLogger.replaceStd(); // Configure dynamic log level loading HytaleLoggerBackend.LOG_LEVEL_LOADER = (name -> { HytaleServer server = HytaleServer.get(); if (server != null) { HytaleServerConfig config = server.getConfig(); if (config != null) { Level level = config.getLogLevels().get(name); if (level != null) return level; } } return Level.WARNING; }); // Create the main server instance new HytaleServer(); } catch (Throwable t) { if (!SkipSentryException.hasSkipSentry(t)) { Sentry.captureException(t); } throw new RuntimeException("Failed to create HytaleServer", t); } } } ``` -------------------------------- ### Compress and Decompress Byte Arrays with Zstandard in Java Source: https://context7.com/hytale-server/hytale-src/llms.txt Java code for compressing and decompressing byte arrays using the Zstandard library. It supports basic compression, compression with checksums, and dictionary-based compression for improved ratios. It also includes decompression functionality and determining original content size. ```java import com.github.luben.zstd.Zstd; // Assume input, dictionary, and processData are defined elsewhere // byte[] input = "Hello World".getBytes(); // byte[] dictionary = loadDictionary(); // byte[] decompressed = new byte[1024]; // Simple compression with default level byte[] compressed = new byte[(int) Zstd.compressBound(input.length)]; long compressedSize = Zstd.compress(compressed, input, 3); // level 3 // Compression with checksum byte[] output = new byte[(int) Zstd.compressBound(input.length)]; long size = Zstd.compress(output, input, 5, true); // level 5, with checksum // Decompression long originalSize = Zstd.getFrameContentSize(compressed); byte[] decompressed = new byte[(int) originalSize]; long decompressedSize = Zstd.decompress(decompressed, compressed); // Dictionary-based compression for better ratios byte[] dictCompressed = new byte[(int) Zstd.compressBound(input.length)]; Zstd.compressUsingDict(dictCompressed, 0, input, 0, dictionary, 3); // Dictionary-based decompression Zstd.decompressUsingDict(decompressed, 0, dictCompressed, 0, dictionary); ``` -------------------------------- ### Manage QUIC Connections with Protocol Utilities in Java Source: https://context7.com/hytale-server/hytale-src/llms.txt Java utilities for managing QUIC and TCP connections, including methods to close connections with specific transport or application-level error codes. It handles channel type checking and uses Netty's QuicChannel for QUIC operations. ```java import io.netty.channel.Channel; import io.netty.handler.codec.quic.QuicChannel; import io.netty.handler.codec.quic.QuicTransportError; import io.netty.buffer.Unpooled; public class ProtocolUtil { // Application-level error codes public static final int APPLICATION_NO_ERROR = 0; public static final int APPLICATION_RATE_LIMITED = 1; public static final int APPLICATION_AUTH_FAILED = 2; public static final int APPLICATION_INVALID_VERSION = 3; // Close connection with protocol violation public static void closeConnection(Channel channel) { closeConnection(channel, QuicTransportError.PROTOCOL_VIOLATION); } // Close with specific transport error public static void closeConnection(Channel channel, QuicTransportError error) { if (channel instanceof QuicChannel) { QuicChannel quic = (QuicChannel) channel; quic.close(false, (int) error.code(), Unpooled.EMPTY_BUFFER); } else if (channel.parent() instanceof QuicChannel) { QuicChannel quic = (QuicChannel) channel.parent(); quic.close(false, (int) error.code(), Unpooled.EMPTY_BUFFER); } else { channel.close(); } } // Close with application-level error public static void closeApplicationConnection(Channel channel, int errorCode) { if (channel instanceof QuicChannel) { QuicChannel quic = (QuicChannel) channel; quic.close(true, errorCode, Unpooled.EMPTY_BUFFER); } else if (channel.parent() instanceof QuicChannel) { QuicChannel quic = (QuicChannel) channel.parent(); quic.close(true, errorCode, Unpooled.EMPTY_BUFFER); } else { channel.close(); } } } // Usage example // boolean authFailed = true; // boolean rateLimited = false; // Channel channel = null; // Assume channel is initialized // if (authFailed) { // ProtocolUtil.closeApplicationConnection(channel, ProtocolUtil.APPLICATION_AUTH_FAILED); // } else if (rateLimited) { // ProtocolUtil.closeApplicationConnection(channel, ProtocolUtil.APPLICATION_RATE_LIMITED); // } ``` -------------------------------- ### Hytale Codec System: Basic Usage (Java) Source: https://context7.com/hytale-server/hytale-src/llms.txt Demonstrates the basic usage of the Hytale codec system for type-safe serialization and deserialization of data formats like BSON and JSON. It covers encoding and decoding primitive types, arrays, and special types such as UUID, Instant, and Duration. ```java import com.hypixel.hytale.codec.Codec; import org.bson.BsonValue; import org.bson.BsonDocument; import java.time.Duration; import java.time.Instant; import java.util.UUID; // Primitive type codecs String text = Codec.STRING.decode(bsonValue); int number = Codec.INTEGER.decode(bsonValue); boolean flag = Codec.BOOLEAN.decode(bsonValue); double decimal = Codec.DOUBLE.decode(bsonValue); // Array codecs int[] numbers = Codec.INT_ARRAY.decode(bsonValue); String[] texts = Codec.STRING_ARRAY.decode(bsonValue); double[] doubles = Codec.DOUBLE_ARRAY.decode(bsonValue); // Special type codecs UUID id = Codec.UUID_BINARY.decode(bsonValue); Instant timestamp = Codec.INSTANT.decode(bsonValue); Duration duration = Codec.DURATION.decode(bsonValue); // Encoding data BsonValue encoded = Codec.STRING.encode("Hello World"); BsonValue uuidEncoded = Codec.UUID_BINARY.encode(UUID.randomUUID()); BsonValue instantEncoded = Codec.INSTANT.encode(Instant.now()); ``` -------------------------------- ### BSON Data Reading and Writing with MongoDB Driver Source: https://context7.com/hytale-server/hytale-src/llms.txt Shows how to create, manipulate, and serialize/deserialize BSON (Binary JSON) documents using the MongoDB Java driver. This includes adding various data types like strings, integers, doubles, booleans, binary data, nested documents, and arrays. ```java import org.bson.*; import java.util.UUID; // Create BSON document BsonDocument document = new BsonDocument(); document.put("username", new BsonString("player123")); document.put("level", new BsonInt32(42)); document.put("health", new BsonDouble(87.5)); document.put("isOnline", new BsonBoolean(true)); document.put("playerId", new BsonBinary(UUID.randomUUID())); // Create nested document BsonDocument inventory = new BsonDocument(); inventory.put("diamonds", new BsonInt32(64)); inventory.put("gold", new BsonInt32(128)); document.put("inventory", inventory); // Create array BsonArray quests = new BsonArray(); quests.add(new BsonString("main_quest_1")); quests.add(new BsonString("side_quest_5")); document.put("activeQuests", quests); // Read BSON values with type checking String username = document.getString("username").getValue(); int level = document.getInt32("level").getValue(); BsonDocument inv = document.getDocument("inventory"); int diamonds = inv.getInt32("diamonds").getValue(); // Iterate array BsonArray questArray = document.getArray("activeQuests"); for (BsonValue quest : questArray) { if (quest.isString()) { String questId = quest.asString().getValue(); System.out.println("Quest: " + questId); } } // Serialize to bytes byte[] bsonBytes = document.toByteArray(); // Deserialize from bytes BsonDocument parsed = BsonDocument.parse(new String(bsonBytes)); ``` -------------------------------- ### Custom Builder Codec for PlayerData Serialization (Java) Source: https://context7.com/hytale-server/hytale-src/llms.txt Defines a BuilderCodec for the PlayerData class, enabling structured serialization and deserialization to BSON. It includes fields for username, level, and playerId with specific codecs. ```java import com.hypixel.hytale.codec.builder.BuilderCodec; import com.hypixel.hytale.codec.builder.BuilderField; import com.mongodb.bson.BsonDocument; import com.mongodb.bson.codecs.Codec; public class PlayerData { private String username; private int level; private UUID playerId; public static final BuilderCodec CODEC = BuilderCodec.builder(PlayerData::new) .withField("username", Codec.STRING, PlayerData::getUsername, PlayerData::setUsername) .withField("level", Codec.INTEGER, PlayerData::getLevel, PlayerData::setLevel) .withField("playerId", Codec.UUID_BINARY, PlayerData::getPlayerId, PlayerData::setPlayerId) .build(); // Deserialize from BSON public static PlayerData fromBson(BsonDocument document) { return CODEC.decode(document); } // Serialize to BSON public BsonDocument toBson() { return (BsonDocument) CODEC.encode(this); } // Placeholder getters and setters (assuming they exist) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public UUID getPlayerId() { return playerId; } public void setPlayerId(UUID playerId) { this.playerId = playerId; } } // Mock classes/interfaces for compilation class UUID {} class Codec {} class ProtocolUtil { public static void closeConnection(Object channel) {} } class PacketRegistry { static class PacketInfo { public int maxSize() { return 0; } }; public static PacketInfo getById(int id) { return null; } } class PacketStatsRecorder { public static Object CHANNEL_KEY; } class ProtocolException extends Exception {} class PacketIO { public static Object readFramedPacketWithInfo(Object in, int length, PacketInfo info, Object stats) throws ProtocolException, IndexOutOfBoundsException { return null; } } ``` -------------------------------- ### Packet Decoder for Network Communication (Java) Source: https://context7.com/hytale-server/hytale-src/llms.txt Implements a custom packet decoder using Netty's ByteToMessageDecoder to parse framed network packets. It validates packet length, size limits, and packet IDs before processing. ```java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; public class PacketDecoder extends ByteToMessageDecoder { private static final int LENGTH_PREFIX_SIZE = 4; private static final int PACKET_ID_SIZE = 4; private static final int MIN_FRAME_SIZE = 8; private static final int MAX_PAYLOAD_SIZE = 1677721600; // ~1.56 GB protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { // Need at least 8 bytes: 4 for length + 4 for packet ID if (in.readableBytes() < MIN_FRAME_SIZE) return; in.markReaderIndex(); // Read length prefix (little-endian) int payloadLength = in.readIntLE(); if (payloadLength < 0 || payloadLength > MAX_PAYLOAD_SIZE) { in.skipBytes(in.readableBytes()); ProtocolUtil.closeConnection(ctx.channel()); return; } // Read packet ID int packetId = in.readIntLE(); PacketRegistry.PacketInfo packetInfo = PacketRegistry.getById(packetId); if (packetInfo == null || payloadLength > packetInfo.maxSize()) { in.skipBytes(in.readableBytes()); ProtocolUtil.closeConnection(ctx.channel()); return; } // Wait for complete packet if (in.readableBytes() < payloadLength) { in.resetReaderIndex(); return; } // Read and parse packet try { PacketStatsRecorder stats = ctx.channel().attr(PacketStatsRecorder.CHANNEL_KEY).get(); out.add(PacketIO.readFramedPacketWithInfo(in, payloadLength, packetInfo, stats)); } catch (ProtocolException | IndexOutOfBoundsException e) { in.skipBytes(in.readableBytes()); ProtocolUtil.closeConnection(ctx.channel()); } } } // Mock classes/interfaces for compilation class ProtocolUtil { public static void closeConnection(Object channel) {} } class PacketRegistry { static class PacketInfo { public int maxSize() { return 0; } }; public static PacketInfo getById(int id) { return null; } } class PacketStatsRecorder { public static Object CHANNEL_KEY; } class ProtocolException extends Exception {} class PacketIO { public static Object readFramedPacketWithInfo(Object in, int length, PacketInfo info, Object stats) throws ProtocolException, IndexOutOfBoundsException { return null; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.