ScriptsLab
WikiDownloadsSourcesSupport
ScriptsLab
DocumentationDownloadsGitHubDiscord

© 2026 ScriptsLab

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

YamlStorageProvider.java

Java · 233 lines · 6.9 KB

src/main/java/com/scriptslab/core/storage/YamlStorageProvider.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
package com.scriptslab.core.storage;

import com.scriptslab.api.storage.StorageProvider;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * YAML-based storage provider implementation.
 * Thread-safe with caching.
 */
public final class YamlStorageProvider implements StorageProvider {
    
    private final Path dataDirectory;
    private final Map<String, Object> cache;
    private final Map<String, YamlConfiguration> fileCache;
    private volatile boolean initialized;
    
    public YamlStorageProvider(Path dataDirectory) {
        this.dataDirectory = dataDirectory;
        this.cache = new ConcurrentHashMap<>();
        this.fileCache = new ConcurrentHashMap<>();
        this.initialized = false;
    }
    
    @Override
    public String getName() {
        return "yaml";
    }
    
    @Override
    public CompletableFuture<Void> initialize() {
        return CompletableFuture.runAsync(() -> {
            dataDirectory.toFile().mkdirs();
            initialized = true;
        });
    }
    
    @Override
    public CompletableFuture<Void> shutdown() {
        return CompletableFuture.runAsync(() -> {
            // Save all cached data
            for (Map.Entry<String, YamlConfiguration> entry : fileCache.entrySet()) {
                try {
                    File file = getFile(entry.getKey());
                    entry.getValue().save(file);
                } catch (Exception e) {
                    // Log error but continue
                }
            }
            
            cache.clear();
            fileCache.clear();
            initialized = false;
        });
    }
    
    @Override
    public CompletableFuture<Void> save(String key, Object value) {
        return CompletableFuture.runAsync(() -> {
            ensureInitialized();
            
            cache.put(key, value);
            
            // Determine file and path
            String[] parts = key.split("\\.", 2);
            String fileName = parts[0];
            String path = parts.length > 1 ? parts[1] : "value";
            
            YamlConfiguration yaml = getOrCreateYaml(fileName);
            yaml.set(path, value);
            
            // Save to disk
            try {
                yaml.save(getFile(fileName));
            } catch (Exception e) {
                throw new RuntimeException("Failed to save: " + key, e);
            }
        });
    }
    
    @Override
    public CompletableFuture<Void> saveBatch(Map<String, Object> data) {
        return CompletableFuture.runAsync(() -> {
            ensureInitialized();
            
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                save(entry.getKey(), entry.getValue()).join();
            }
        });
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public <T> CompletableFuture<Optional<T>> load(String key, Class<T> type) {
        return CompletableFuture.supplyAsync(() -> {
            ensureInitialized();
            
            // Check cache first
            if (cache.containsKey(key)) {
                return Optional.of((T) cache.get(key));
            }
            
            // Load from file
            String[] parts = key.split("\\.", 2);
            String fileName = parts[0];
            String path = parts.length > 1 ? parts[1] : "value";
            
            YamlConfiguration yaml = getOrCreateYaml(fileName);
            Object value = yaml.get(path);
            
            if (value != null) {
                cache.put(key, value);
                return Optional.of((T) value);
            }
            
            return Optional.empty();
        });
    }
    
    @Override
    public CompletableFuture<Map<String, Object>> loadBatch(Set<String> keys) {
        return CompletableFuture.supplyAsync(() -> {
            Map<String, Object> result = new HashMap<>();
            
            for (String key : keys) {
                load(key, Object.class).join().ifPresent(value -> result.put(key, value));
            }
            
            return result;
        });
    }
    
    @Override
    public CompletableFuture<Void> delete(String key) {
        return CompletableFuture.runAsync(() -> {
            ensureInitialized();
            
            cache.remove(key);
            
            String[] parts = key.split("\\.", 2);
            String fileName = parts[0];
            String path = parts.length > 1 ? parts[1] : "value";
            
            YamlConfiguration yaml = getOrCreateYaml(fileName);
            yaml.set(path, null);
            
            try {
                yaml.save(getFile(fileName));
            } catch (Exception e) {
                throw new RuntimeException("Failed to delete: " + key, e);
            }
        });
    }
    
    @Override
    public CompletableFuture<Boolean> exists(String key) {
        return CompletableFuture.supplyAsync(() -> {
            ensureInitialized();
            
            if (cache.containsKey(key)) {
                return true;
            }
            
            String[] parts = key.split("\\.", 2);
            String fileName = parts[0];
            String path = parts.length > 1 ? parts[1] : "value";
            
            YamlConfiguration yaml = getOrCreateYaml(fileName);
            return yaml.contains(path);
        });
    }
    
    @Override
    public CompletableFuture<Set<String>> getAllKeys() {
        return CompletableFuture.supplyAsync(() -> {
            ensureInitialized();
            return new HashSet<>(cache.keySet());
        });
    }
    
    @Override
    public CompletableFuture<Void> clear() {
        return CompletableFuture.runAsync(() -> {
            ensureInitialized();
            
            cache.clear();
            fileCache.clear();
            
            // Delete all files
            File[] files = dataDirectory.toFile().listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().endsWith(".yml")) {
                        file.delete();
                    }
                }
            }
        });
    }
    
    @Override
    public boolean isInitialized() {
        return initialized;
    }
    
    private void ensureInitialized() {
        if (!initialized) {
            throw new IllegalStateException("Storage provider not initialized");
        }
    }
    
    private File getFile(String fileName) {
        return dataDirectory.resolve(fileName + ".yml").toFile();
    }
    
    private YamlConfiguration getOrCreateYaml(String fileName) {
        return fileCache.computeIfAbsent(fileName, name -> {
            File file = getFile(name);
            
            if (file.exists()) {
                return YamlConfiguration.loadConfiguration(file);
            } else {
                return new YamlConfiguration();
            }
        });
    }
}