ScriptsLab
WikiDownloadsSourcesSupport
ScriptsLab
DocumentationDownloadsGitHubDiscord

© 2026 ScriptsLab

Back to src/main/java/com/scriptslab
J

ScriptsLabPlugin.java

Java · 417 lines · 14.5 KB

src/main/java/com/scriptslab/ScriptsLabPlugin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package com.scriptslab;

import com.scriptslab.api.command.CommandManager;
import com.scriptslab.api.event.EventBus;
import com.scriptslab.api.item.ItemManager;
import com.scriptslab.api.metrics.MetricsCollector;
import com.scriptslab.api.module.ModuleManager;
import com.scriptslab.api.scheduler.TaskScheduler;
import com.scriptslab.api.script.ScriptEngine;
import com.scriptslab.api.storage.StorageManager;
import com.scriptslab.core.command.CommandManagerImpl;
import com.scriptslab.core.config.ConfigurationManager;
import com.scriptslab.core.di.Container;
import com.scriptslab.core.event.EventBusImpl;
import com.scriptslab.core.item.ItemManagerImpl;
import com.scriptslab.core.metrics.MetricsCollectorImpl;
import com.scriptslab.core.module.ModuleManagerImpl;
import com.scriptslab.core.scheduler.TaskSchedulerImpl;
import com.scriptslab.core.script.GraalScriptEngine;
import com.scriptslab.core.script.ScriptAPIImpl;
import com.scriptslab.core.storage.StorageManagerImpl;
import org.bukkit.plugin.java.JavaPlugin;

import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;

/**
 * ScriptsLab - Production-grade scriptable plugin framework.
 * 
 * Your laboratory for Minecraft scripting - experiment, create, and deploy
 * with confidence using our powerful modular architecture.
 * 
 * Features:
 * - JavaScript scripting with GraalVM
 * - Modular plugin system
 * - Custom items with abilities
 * - Event-driven architecture
 * - Storage abstraction
 * - Command framework
 * - GUI system
 * 
 * @author ScriptsLab Team
 * @version 1.0.0
 */
public final class ScriptsLabPlugin extends JavaPlugin {
    
    private static ScriptsLabPlugin instance;
    private static boolean hotReloadAttempted = false;
    private Container container;
    
    // Core services
    private ConfigurationManager configManager;
    private ModuleManager moduleManager;
    private EventBus eventBus;
    private TaskScheduler taskScheduler;
    private ItemManager itemManager;
    private ScriptEngine scriptEngine;
    private StorageManager storageManager;
    private CommandManager commandManager;
    private MetricsCollector metricsCollector;
    
    @Override
    public void onEnable() {
        if (instance != null && hotReloadAttempted) {
            getLogger().warning("================================================== ");
            getLogger().warning("  HOT RELOAD DETECTED - ScriptsLab requires full server restart!");
            getLogger().warning("  Please restart the server to reload ScriptsLab");
            getLogger().warning("  Using /restart or stop + start (not /reload)");
            getLogger().warning("================================================== ");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }
        
        if (instance == null) {
            hotReloadAttempted = false;
        }
        
        instance = this;
        long startTime = System.currentTimeMillis();
        
        printBanner();
        
        try {
            // Phase 1: Initialize DI container
            initializeContainer();
            
            // Phase 2: Load configuration
            initializeConfiguration();
            
            // Phase 3: Initialize core services
            initializeServices();
            
            // Phase 4: Register commands
            registerCommands();
            
            // Phase 5: Load modules (async)
            loadModulesAsync();
            
            // Phase 6: Load scripts (async)
            loadScriptsAsync();
            
            long loadTime = System.currentTimeMillis() - startTime;
            getLogger().info("╔═══════════════════════════════════════╗");
            getLogger().info("║   ScriptsLab - Ready!                 ║");
            getLogger().info("║   Load time: " + loadTime + "ms" + " ".repeat(Math.max(0, 23 - String.valueOf(loadTime).length())) + "║");
            getLogger().info("╚═══════════════════════════════════════╝");
            
        } catch (Exception e) {
            getLogger().log(Level.SEVERE, "Critical error during plugin initialization!", e);
            getServer().getPluginManager().disablePlugin(this);
        }
    }
    
    @Override
    public void onDisable() {
        getLogger().info("Shutting down ScriptsLab...");
        
        try {
            // Shutdown in reverse order
            
            // 1. Unload scripts
            if (scriptEngine != null && scriptEngine.isInitialized()) {
                scriptEngine.shutdown().join();
            }
            
            // 2. Disable all modules
            if (moduleManager != null) {
                moduleManager.getEnabledModules().forEach(module -> {
                    try {
                        moduleManager.disableModule(module.getId()).join();
                    } catch (Exception e) {
                        getLogger().log(Level.WARNING, "Error disabling module: " + module.getId(), e);
                    }
                });
            }
            
            // 3. Shutdown storage
            if (storageManager != null) {
                storageManager.shutdown().join();
            }
            
            // 3b. Save script storage data
            if (scriptEngine != null && scriptEngine.getScriptAPI() instanceof com.scriptslab.core.script.ScriptAPIImpl apiImpl) {
                apiImpl.getStorage().saveAll();
            }
            
            // 4. Cancel all tasks
            if (taskScheduler != null) {
                taskScheduler.cancelAllTasks();
            }
            
            // 5. Clear container
            if (container != null) {
                container.clear();
            }
            
            getLogger().info("ScriptsLab shut down successfully");
            
        } catch (Exception e) {
            getLogger().log(Level.SEVERE, "Error during plugin shutdown", e);
        }
        
        instance = null;
    }
    
    /**
     * Prints the startup banner.
     */
    private void printBanner() {
        getLogger().info("╔═══════════════════════════════════════╗");
        getLogger().info("║                                       ║");
        getLogger().info("║         ScriptsLab v1.0.0             ║");
        getLogger().info("║   Your Minecraft Scripting Lab        ║");
        getLogger().info("║                                       ║");
        getLogger().info("╚═══════════════════════════════════════╝");
    }
    
    /**
     * Initializes the dependency injection container.
     */
    private void initializeContainer() {
        getLogger().info("→ Initializing DI container...");
        container = Container.getInstance();
        
        // Register plugin instance
        container.registerSingleton(JavaPlugin.class, this);
        container.registerSingleton(ScriptsLabPlugin.class, this);
        
        getLogger().info("✓ DI container initialized");
    }
    
    /**
     * Initializes configuration system.
     */
    private void initializeConfiguration() {
        getLogger().info("→ Loading configuration...");
        
        saveDefaultConfig();
        configManager = new ConfigurationManager(this);
        container.registerSingleton(ConfigurationManager.class, configManager);
        
        getLogger().info("✓ Configuration loaded");
    }
    
    /**
     * Initializes core services and registers them in the container.
     */
    private void initializeServices() {
        getLogger().info("→ Initializing core services...");
        
        // Metrics Collector
        metricsCollector = new MetricsCollectorImpl();
        container.registerSingleton(MetricsCollector.class, metricsCollector);
        getLogger().info("  ✓ Metrics Collector");
        
        // Event Bus
        eventBus = new EventBusImpl();
        container.registerSingleton(EventBus.class, eventBus);
        getLogger().info("  ✓ Event Bus");
        
        // Task Scheduler
        taskScheduler = new TaskSchedulerImpl(this);
        container.registerSingleton(TaskScheduler.class, taskScheduler);
        getLogger().info("  ✓ Task Scheduler");
        
        // Storage Manager
        storageManager = new StorageManagerImpl(this);
        storageManager.initialize().join();
        container.registerSingleton(StorageManager.class, storageManager);
        getLogger().info("  ✓ Storage Manager");
        
        // Item Manager
        itemManager = new ItemManagerImpl(this);
        container.registerSingleton(ItemManager.class, itemManager);
        getLogger().info("  ✓ Item Manager");
        
        // Command Manager
        commandManager = new CommandManagerImpl(this);
        container.registerSingleton(CommandManager.class, commandManager);
        getLogger().info("  ✓ Command Manager");
        
        // Module Manager
        Path modulesDir = getDataFolder().toPath().resolve("modules");
        moduleManager = new ModuleManagerImpl(modulesDir);
        container.registerSingleton(ModuleManager.class, moduleManager);
        getLogger().info("  ✓ Module Manager");
        
        // Script Engine
        Path scriptsDir = getDataFolder().toPath().resolve("scripts");
        ScriptAPIImpl scriptAPI = new ScriptAPIImpl(this);
        scriptEngine = new GraalScriptEngine(scriptsDir, scriptAPI);
        scriptEngine.initializeSync();
        container.registerSingleton(ScriptEngine.class, scriptEngine);
        getLogger().info("  ✓ Script Engine");
        
        // Start periodic cleanup task for item cooldowns
        taskScheduler.runTaskTimer(
                () -> ((ItemManagerImpl) itemManager).cleanupCooldowns(),
                60, 60, java.util.concurrent.TimeUnit.SECONDS
        );
        
        getLogger().info("✓ Core services initialized");
    }
    
    /**
     * Registers plugin commands.
     */
    private void registerCommands() {
        getLogger().info("→ Registering commands...");
        
        commandManager.registerCommands();
        
        getLogger().info("✓ Commands registered");
    }
    
    /**
     * Loads all modules asynchronously.
     */
    private void loadModulesAsync() {
        getLogger().info("→ Loading modules...");
        
        moduleManager.loadAllModules()
                .thenAccept(count -> {
                    getLogger().info("✓ Loaded " + count + " modules");
                    
                    // Enable all loaded modules
                    moduleManager.getModules().forEach(module -> {
                        try {
                            moduleManager.enableModule(module.getId()).join();
                        } catch (Exception e) {
                            getLogger().log(Level.SEVERE, "Failed to enable module: " + module.getId(), e);
                        }
                    });
                })
                .exceptionally(ex -> {
                    getLogger().log(Level.SEVERE, "Failed to load modules", ex);
                    return null;
                });
    }
    
    /**
     * Loads all scripts asynchronously.
     */
    private void loadScriptsAsync() {
        getLogger().info("→ Loading scripts...");
        
        Path scriptsDir = getDataFolder().toPath().resolve("scripts");
        
        scriptEngine.loadScriptsFromDirectory(scriptsDir)
                .thenAccept(count -> getLogger().info("✓ Loaded " + count + " scripts"))
                .exceptionally(ex -> {
                    getLogger().log(Level.SEVERE, "Failed to load scripts", ex);
                    return null;
                });
    }
    
    /**
     * Reloads the entire plugin.
     * 
     * @return future that completes when reloaded
     */
    public CompletableFuture<Void> reload() {
        return CompletableFuture.runAsync(() -> {
            getLogger().info("Reloading ScriptsLab...");
            
            try {
                // Reload configuration
                reloadConfig();
                configManager.reload();
                
                // Reload scripts
                scriptEngine.reloadAllScripts().join();
                
                // Reload modules
                moduleManager.getModules().forEach(module -> {
                    try {
                        moduleManager.reloadModule(module.getId()).join();
                    } catch (Exception e) {
                        getLogger().log(Level.WARNING, "Failed to reload module: " + module.getId(), e);
                    }
                });
                
                getLogger().info("ScriptsLab reloaded successfully");
                
            } catch (Exception e) {
                getLogger().log(Level.SEVERE, "Error during plugin reload", e);
                throw new RuntimeException(e);
            }
        });
    }
    
    // === Getters ===
    
    public static ScriptsLabPlugin getInstance() {
        return instance;
    }
    
    public static void setHotReloadAttempted(boolean attempted) {
        hotReloadAttempted = attempted;
        if (instance != null) {
            instance.getLogger().warning("Hot reload flag set - next enable will require full restart");
        }
    }
    
    public Container getContainer() {
        return container;
    }
    
    public ConfigurationManager getConfigManager() {
        return configManager;
    }
    
    public ModuleManager getModuleManager() {
        return moduleManager;
    }
    
    public EventBus getEventBus() {
        return eventBus;
    }
    
    public TaskScheduler getTaskScheduler() {
        return taskScheduler;
    }
    
    public ItemManager getItemManager() {
        return itemManager;
    }
    
    public ScriptEngine getScriptEngine() {
        return scriptEngine;
    }
    
    public StorageManager getStorageManager() {
        return storageManager;
    }
    
    public CommandManager getCommandManager() {
        return commandManager;
    }
    
    public MetricsCollector getMetricsCollector() {
        return metricsCollector;
    }
    
    /**
     * Gets a service from the DI container.
     * 
     * @param type service type
     * @param <T> type parameter
     * @return service instance
     */
    public <T> T getService(Class<T> type) {
        return container.resolveOrThrow(type);
    }
}