### Register Custom Commands with Java and Cloud Source: https://context7.com/whereareiam/socialismus/llms.txt This Java code demonstrates how to define and register custom commands using the Cloud command framework and the Socialismus `CommandService`. It shows how to annotate command methods with `@Command`, `@Permission`, and `@Argument`, and how to provide additional metadata like aliases and descriptions through `CommandDefinition`. This enables developers to easily extend the game's functionality with new commands. ```java import com.google.inject.Inject; import com.google.inject.Singleton; import me.whereareiam.commandant.annotation.Definition; import me.whereareiam.commandant.model.CommandDefinition; import me.whereareiam.keystone.Actor; import me.whereareiam.keystone.Player; import me.whereareiam.socialismus.service.CommandService; import net.kyori.adventure.text.Component; import org.incendo.cloud.annotations.Argument; import org.incendo.cloud.annotations.Command; import org.incendo.cloud.annotations.Permission; import java.util.Map; @Singleton public class CustomCommands { @Definition("broadcast") @Command("broadcast ") @Permission("socialismus.broadcast") public void broadcastCommand( Actor sender, @Argument("message") String message ) { // Broadcast to all online players Component broadcastMsg = Component.text("[Broadcast] " + message); // Implementation depends on your platform sender.sendMessage(Component.text("Broadcasting message...")); } @Definition("mute") @Command("mute [duration]") @Permission("socialismus.mute") public void muteCommand( Actor sender, @Argument("player") String targetPlayer, @Argument("duration") String duration ) { sender.sendMessage( Component.text("Muted " + targetPlayer + " for " + duration) ); } } public class CommandRegistrar { private final CommandService commandService; @Inject public CommandRegistrar(CommandService commandService) { this.commandService = commandService; } public void registerModuleCommands() { // Define command metadata Map definitions = Map.of( "broadcast", CommandDefinition.builder() .aliases(List.of("bc", "announce")) .description("Broadcast a message to all players") .arguments(Map.of("message", "The message to broadcast")) .build(), "mute", CommandDefinition.builder() .aliases(List.of("silence")) .description("Mute a player") .arguments(Map.of( "player", "The player to mute", "duration", "Mute duration (e.g., 1h, 30m)" )) .build() ); // Register commands commandService.registerCommands(definitions, CustomCommands.class); System.out.println("Registered " + commandService.getCommandCount() + " commands"); } } ``` -------------------------------- ### Use Sync Service for Cross-Server Communication (Java) Source: https://context7.com/whereareiam/socialismus/llms.txt This Java code illustrates how to synchronize data across multiple server instances using the `SyncService`. It shows how to subscribe to channels for receiving messages and publish messages to specific channels. Key dependencies include Guice for injection and Socialismus services for synchronization. ```java import com.google.inject.Inject; import me.whereareiam.socialismus.service.resource.sync.SyncService; import me.whereareiam.socialismus.service.resource.sync.SyncSubscriber; import java.nio.charset.StandardCharsets; public class CrossServerMessaging { private final SyncService syncService; @Inject public CrossServerMessaging(SyncService syncService) { this.syncService = syncService; // Subscribe to channels syncService.subscribe("announcements", this::handleAnnouncement); syncService.subscribe("player-join", this::handlePlayerJoin); } public void broadcastAnnouncement(String message) { // Publish to all servers byte[] payload = message.getBytes(StandardCharsets.UTF_8); syncService.publish("announcements", payload); } public void notifyPlayerJoin(String playerName, String serverName) { String data = playerName + ":" + serverName; syncService.publish("player-join", data.getBytes(StandardCharsets.UTF_8)); } private void handleAnnouncement(byte[] payload) { String announcement = new String(payload, StandardCharsets.UTF_8); System.out.println("Received announcement: " + announcement); // Broadcast to local server } private void handlePlayerJoin(byte[] payload) { String data = new String(payload, StandardCharsets.UTF_8); String[] parts = data.split(":"); String player = parts[0]; String server = parts[1]; System.out.println(player + " joined " + server); } } ``` -------------------------------- ### Java: Load and Reload Module Configuration Source: https://context7.com/whereareiam/socialismus/llms.txt This Java code defines a configuration class 'ModuleConfig' and a 'ModuleConfigProvider' that handles loading, saving, and hot-reloading of this configuration from a JSON file. It uses Guice for dependency injection and the 'Configura' library for configuration management. Errors during loading default to a new configuration object. ```java import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import me.whereareiam.configura.Config; import me.whereareiam.socialismus.config.ConfigProvider; import lombok.Data; import java.nio.file.Path; import java.util.List; @Data public class ModuleConfig { private boolean enabled = true; private String prefix = "[Module]"; private int maxMessages = 100; private List blockedWords = List.of("spam", "ad"); } @Singleton public class ModuleConfigProvider extends ConfigProvider { private final Path configPath; @Inject public ModuleConfigProvider(@Named("dataPath") Path dataPath) { this.configPath = dataPath.resolve("module-config.json"); } @Override protected ModuleConfig load() { try { return Config.load(configPath.toFile(), ModuleConfig.class); } catch (Exception e) { System.err.println("Failed to load config: " + e.getMessage()); return new ModuleConfig(); // Return defaults } } @Override protected void registerTemplate() { // Register default template if file doesn't exist if (!configPath.toFile().exists()) { try { Config.save(configPath.toFile(), new ModuleConfig()); } catch (Exception e) { System.err.println("Failed to save default config: " + e.getMessage()); } } } } public class ModuleMain { private final ModuleConfigProvider configProvider; @Inject public ModuleMain(ModuleConfigProvider configProvider) { this.configProvider = configProvider; } public void initialize() { ModuleConfig config = configProvider.get(); if (!config.isEnabled()) { System.out.println("Module is disabled in config"); return; } System.out.println("Module prefix: " + config.getPrefix()); } public void reloadConfiguration() { configProvider.reload(); System.out.println("Configuration reloaded"); } } ``` -------------------------------- ### Evaluate Player Requirements with Java Source: https://context7.com/whereareiam/socialismus/llms.txt This Java code demonstrates how to check if players meet specific requirements, such as permissions and world conditions, before allowing certain actions. It utilizes the `RequirementEvaluatorService` to process `RequirementGroup` objects, which can combine multiple conditions using different modes like ALL. This is crucial for access control within the game. ```java import com.google.inject.Inject; import me.whereareiam.socialismus.service.requirement.RequirementEvaluatorService; import me.whereareiam.socialismus.model.player.SocialismusPlayer; import me.whereareiam.socialismus.model.requirement.RequirementGroup; import me.whereareiam.socialismus.model.requirement.type.PermissionRequirement; import me.whereareiam.socialismus.model.requirement.type.WorldRequirement; import me.whereareiam.socialismus.type.requirement.RequirementMode; import me.whereareiam.socialismus.type.requirement.RequirementCondition; import java.util.List; public class AccessController { private final RequirementEvaluatorService evaluatorService; @Inject public AccessController(RequirementEvaluatorService evaluatorService) { this.evaluatorService = evaluatorService; } public boolean canAccessVipChat(SocialismusPlayer player) { // Create permission requirement PermissionRequirement permReq = PermissionRequirement.builder() .condition(RequirementCondition.HAS) .value("socialismus.chat.vip") .build(); // Create world requirement WorldRequirement worldReq = WorldRequirement.builder() .condition(RequirementCondition.EQUALS) .value("world") .build(); // Combine requirements (both must be satisfied) RequirementGroup group = RequirementGroup.builder() .mode(RequirementMode.ALL) .requirements(List.of(permReq, worldReq)) .build(); // Evaluate return evaluatorService.check(group, player); } public boolean canUseColorCodes(SocialismusPlayer player) { PermissionRequirement colorPerm = PermissionRequirement.builder() .condition(RequirementCondition.HAS) .value("socialismus.color") .build(); RequirementGroup group = RequirementGroup.builder() .mode(RequirementMode.ALL) .requirements(List.of(colorPerm)) .build(); return evaluatorService.check(group, player); } } ``` -------------------------------- ### Add Socialismus Dependency (Maven) Source: https://context7.com/whereareiam/socialismus/llms.txt This snippet demonstrates how to add the Socialismus API as a dependency to your project using Maven. It involves defining the Jitpack repository and declaring the dependency in your pom.xml file. Verify the version compatibility with your project. ```xml jitpack https://jitpack.io com.github.whereareiam Socialismus 2.0.0-RC1 ``` -------------------------------- ### Manage Modules Programmatically (Java) Source: https://context7.com/whereareiam/socialismus/llms.txt This Java code provides functionality to interact with Socialismus modules programmatically. It demonstrates how to list all loaded modules with their details, check a specific module's state and dependencies, and reload all modules. This requires access to the ModuleService provided by the Socialismus API. ```java import com.google.inject.Inject; import me.whereareiam.socialismus.module.ModuleService; import me.whereareiam.socialismus.model.module.InternalModule; import me.whereareiam.socialismus.type.module.ModuleState; public class ModuleManager { private final ModuleService moduleService; @Inject public ModuleManager(ModuleService moduleService) { this.moduleService = moduleService; } public void listAllModules() { List modules = moduleService.getModules(); for (InternalModule module : modules) { System.out.println("Module: " + module.getName()); System.out.println(" Version: " + module.getVersion()); System.out.println(" State: " + module.getState()); System.out.println(" Authors: " + String.join(", ", module.getAuthors())); } } public void checkModuleDependency(String moduleName) { Optional module = moduleService.getModule(moduleName); if (module.isEmpty()) { System.out.println("Module " + moduleName + " is not loaded"); return; } InternalModule mod = module.get(); if (mod.getState() == ModuleState.ENABLED) { System.out.println("Module is enabled and ready"); } else { System.out.println("Module exists but is not enabled: " + mod.getState()); } } public void reloadAllModules() { moduleService.reloadModules(); System.out.println("All modules have been reloaded"); } } ``` -------------------------------- ### Add Socialismus Dependency (Gradle) Source: https://context7.com/whereareiam/socialismus/llms.txt This snippet shows how to add the Socialismus API as a dependency to your project using Gradle. It includes configuring the necessary Maven repository (Jitpack) and declaring the dependency itself. Ensure you are using a compatible version. ```gradle repositories { maven("https://jitpack.io") } dependencies { implementation("com.github.whereareiam:Socialismus:2.0.0-RC1") } ``` -------------------------------- ### Use Cache Service with Java Source: https://context7.com/whereareiam/socialismus/llms.txt Stores and retrieves cached data with optional Time-To-Live (TTL). It supports caching arbitrary data, adding elements to sets, retrieving set members, and checking for the existence of cache entries. Dependencies include Guice for injection and Java's time and util packages. ```java import com.google.inject.Inject; import me.whereareiam.socialismus.service.resource.CacheService; import java.time.Duration; import java.util.Optional; import java.util.Set; public class PlayerDataCache { private final CacheService cacheService; @Inject public PlayerDataCache(CacheService cacheService) { this.cacheService = cacheService; } public void cachePlayerData(String playerUuid, PlayerData data) { // Store with 1 hour TTL cacheService.put("player:" + playerUuid, data, Duration.ofHours(1)); } public Optional getPlayerData(String playerUuid) { return cacheService.get("player:" + playerUuid, PlayerData.class); } public void addPlayerToGroup(String groupName, String playerUuid) { // Add to a set cacheService.add("group:" + groupName, playerUuid); } public Set getGroupMembers(String groupName) { return cacheService.get("group:" + groupName); } public void removePlayerFromCache(String playerUuid) { boolean removed = cacheService.delete("player:" + playerUuid); System.out.println("Cache entry removed: " + removed); } public boolean isPlayerCached(String playerUuid) { return cacheService.exists("player:" + playerUuid); } } ``` -------------------------------- ### Use Database Service with Java and ORMLite Source: https://context7.com/whereareiam/socialismus/llms.txt Persists entities using ORMLite Data Access Objects (DAOs). This allows for database migrations and CRUD operations on entities like PlayerStats. It requires Guice for dependency injection and ORMLite for database interaction. Exceptions can be thrown during database operations. ```java import com.google.inject.Inject; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import me.whereareiam.socialismus.service.resource.DatabaseService; @DatabaseTable(tableName = "player_stats") public class PlayerStats { @DatabaseField(id = true) private String uuid; @DatabaseField private int messageCount; @DatabaseField private long lastSeen; // Getters and setters } public class StatisticsManager { private final DatabaseService databaseService; private final Dao statsDao; @Inject public StatisticsManager(DatabaseService databaseService) { this.databaseService = databaseService; // Migrate the table schema databaseService.migrate(PlayerStats.class); // Get the DAO for operations this.statsDao = databaseService.dao(PlayerStats.class); } public void updatePlayerStats(String uuid) throws Exception { PlayerStats stats = statsDao.queryForId(uuid); if (stats == null) { stats = new PlayerStats(); stats.setUuid(uuid); stats.setMessageCount(1); } else { stats.setMessageCount(stats.getMessageCount() + 1); } stats.setLastSeen(System.currentTimeMillis()); statsDao.createOrUpdate(stats); } public int getMessageCount(String uuid) throws Exception { PlayerStats stats = statsDao.queryForId(uuid); return stats != null ? stats.getMessageCount() : 0; } } ``` -------------------------------- ### Listen to Chat Events (Java) Source: https://context7.com/whereareiam/socialismus/llms.txt This Java code demonstrates how to create an event listener to intercept and modify chat messages before they are broadcasted. It shows how to register the listener, access message content, cancel events, and modify messages. This requires the Socialismus API and Guice for dependency injection. ```java import com.google.inject.Inject; import com.google.inject.Singleton; import me.whereareiam.socialismus.event.EventListener; import me.whereareiam.socialismus.event.EventManager; import me.whereareiam.socialismus.event.chat.ChatBroadcastEvent; import me.whereareiam.socialismus.event.base.EventOrder; import me.whereareiam.socialismus.model.chat.message.FormattedChatMessage; @Singleton public class ChatFilter implements EventListener { @Inject public ChatFilter(EventManager eventManager) { // Register this listener with the event manager eventManager.register(this); } // Subscribe annotation with event order @Subscribe(order = EventOrder.HIGH) public void onChatBroadcast(ChatBroadcastEvent event) { FormattedChatMessage message = event.getChatMessage(); // Check if message contains blocked words if (message.getRawMessage().toLowerCase().contains("spam")) { event.setCancelled(true); message.getSender().sendMessage( Component.text("Your message was blocked!") ); return; } // Modify the message content message.setRawMessage( message.getRawMessage().replaceAll("(?i)discord", "****") ); } } ``` -------------------------------- ### Add Socialismus API Dependency with Maven Source: https://github.com/whereareiam/socialismus/wiki/Developer-API Sets up the JitPack repository and includes the Socialismus API as a dependency in your Maven project. Remember to replace 'version' with the desired release tag or 'dev-SNAPSHOT'. ```xml jitpack https://jitpack.io com.github.whereareiam Socialismus version ``` -------------------------------- ### Coordinate Chat Messages using Java Source: https://context7.com/whereareiam/socialismus/llms.txt Processes chat messages through the coordination service pipeline. This includes applying triggers and requirements, formatting the message, broadcasting to recipients, and storing it in history. It takes a player and raw message as input and returns a formatted message or indicates cancellation. ```java import com.google.inject.Inject; import me.whereareiam.socialismus.service.chat.ChatCoordinationService; import me.whereareiam.socialismus.model.chat.message.ChatMessage; import me.whereareiam.socialismus.model.chat.message.FormattedChatMessage; import me.whereareiam.socialismus.model.player.SocialismusPlayer; import me.whereareiam.socialismus.model.position.Position; public class CustomChatHandler { private final ChatCoordinationService chatCoordination; @Inject public CustomChatHandler(ChatCoordinationService chatCoordination) { this.chatCoordination = chatCoordination; } public void sendCustomMessage(SocialismusPlayer player, String message) { // Build a chat message ChatMessage chatMessage = ChatMessage.builder() .sender(player) .rawMessage(message) .position(Position.builder() .world(player.getWorld()) .x(player.getLocation().getX()) .y(player.getLocation().getY()) .z(player.getLocation().getZ()) .build()) .cancelled(false) .build(); // Coordinate processes the message through the entire pipeline: // - Applies chat triggers and requirements // - Formats the message // - Broadcasts to recipients // - Stores in history FormattedChatMessage result = chatCoordination.coordinate(chatMessage); if (result.isCancelled()) { System.out.println("Message was cancelled during processing"); } } } ``` -------------------------------- ### Add Socialismus API Dependency with Gradle (Kotlin) Source: https://github.com/whereareiam/socialismus/wiki/Developer-API Configures Gradle (Kotlin DSL) to use the JitPack repository and adds the Socialismus API dependency. Ensure 'version' is updated to a specific release or 'dev-SNAPSHOT'. ```kotlin repositories { maven("https://jitpack.io") } dependencies { implementation("com.github.whereareiam:Socialismus:version") } ``` -------------------------------- ### Add Socialismus API Dependency with Gradle (Groovy) Source: https://github.com/whereareiam/socialismus/wiki/Developer-API Configures Gradle to use the JitPack repository and adds the Socialismus API dependency to your project. Replace 'version' with a specific release tag or 'dev-SNAPSHOT'. ```gradle repositories { maven { url 'https://jitpack.io' } } dependencies { implementation 'com.github.whereareiam:Socialismus:version' } ``` -------------------------------- ### Create Worker Pipeline with Message Transformers (Java) Source: https://context7.com/whereareiam/socialismus/llms.txt This Java code demonstrates how to add custom transformation logic to the message processing pipeline. It utilizes `WorkerProcessor` to register workers for censoring URLs and replacing text emojis with their Unicode equivalents. Dependencies include Guice for dependency injection and specific Socialismus models and registries. ```java import com.google.inject.Inject; import com.google.inject.Singleton; import me.whereareiam.socialismus.model.Worker; import me.whereareiam.socialismus.model.chat.message.FormattedChatMessage; import me.whereareiam.socialismus.registry.WorkerProcessor; @Singleton public class MessageTransformers { @Inject public MessageTransformers( WorkerProcessor workerProcessor ) { // Register a worker that replaces URLs with censored text // Priority 10 - runs early in the pipeline workerProcessor.addWorker(new Worker<>( this::censorUrls, 10, true, // removable false // not cancelled )); // Register a worker that adds emoji support // Priority 20 - runs after URL censoring workerProcessor.addWorker(new Worker<>( this::replaceEmojis, 20, true, false )); } private FormattedChatMessage censorUrls(FormattedChatMessage message) { String content = message.getRawMessage(); // Replace URLs with [LINK] String censored = content.replaceAll( "https?://[^\\s]+", "[LINK]" ); message.setRawMessage(censored); return message; } private FormattedChatMessage replaceEmojis(FormattedChatMessage message) { String content = message.getRawMessage(); // Replace text emojis with unicode content = content.replace(":smile:", "😊"); content = content.replace(":heart:", "❤️"); content = content.replace(":fire:", "🔥"); message.setRawMessage(content); return message; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.